<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="租户名称" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入租户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租户编号" prop="tenantCode">
        <el-input
          v-model="queryParams.tenantCode"
          placeholder="请输入租户编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="owner">
        <el-input
          v-model="queryParams.owner"
          placeholder="请输入负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactInfo">
        <el-input
          v-model="queryParams.contactInfo"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:tenant:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="selection.length == 0"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:tenant:export']"
        >导出
        </el-button>
        <ExcelDownLoad
          v-else
          :headerList="headerList"
          :fieldList="selection"
          :excelTitle="excelTitle"
        ></ExcelDownLoad>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      :data="tenantList"
      style="width: 100%"
      row-key="tenantId"
      border
      lazy
      :load="load"
      :tree-props="{children: 'children', hasChildren:'hasChildren' }"
    >
      <el-table-column label="租户ID" align="center" prop="tenantId"/>
      <el-table-column label="租户名称" align="center" prop="tenantName"/>
      <el-table-column label="租户编号" align="center" prop="tenantCode"/>
      <el-table-column label="负责人" align="center" prop="owner"/>
      <el-table-column label="联系方式" align="center" prop="contactInfo"/>
      <el-table-column label="地址" align="center" prop="address"/>
      <el-table-column label="租户父级ID" align="center" prop="tenantParentId"/>
      <el-table-column label="客户端访问地址" align="center" prop="tenantClientLoginUrl"/>
      <el-table-column label="工具端访问地址" align="center" prop="tenantToolLoginUrl"/>
      <el-table-column label="租户等级" align="center" prop="tenantGrade"/>
      <el-table-column label="到期天数" align="center" prop="tenantExpirationTime"/>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" plain size="small">
              处理<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:tenant:edit']"
                >修改
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:tenant:remove']"
                >删除
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-position"
                  @click="bindDatasource(scope.row)"
                  v-show="scope.row.datasourceId == null"
                >绑定数据源
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-custom"
                  @click="openTenantExpirationTime(scope.row)"
                  v-hasPermi="['system:tenant:remove']"
                >激活租户
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-open"
                  @click="openLoginConfig(scope.row)"
                  v-hasPermi="['system:tenant:remove']"
                >配置登录页
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <el-table
      v-loading="loading"
      :data="tenantList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="租户ID" align="center" prop="tenantId"/>
      <el-table-column label="租户名称" align="center" prop="tenantName"/>
      <el-table-column label="租户编号" align="center" prop="tenantCode"/>
      <el-table-column label="负责人" align="center" prop="owner"/>
      <el-table-column label="联系方式" align="center" prop="contactInfo"/>
      <el-table-column label="地址" align="center" prop="address"/>
      <el-table-column label="租户父级ID" align="center" prop="tenantParentId"/>
      <el-table-column label="客户端访问地址" align="center" prop="tenantClientLoginUrl"/>
      <el-table-column label="工具端访问地址" align="center" prop="tenantToolLoginUrl"/>
      <el-table-column label="租户等级" align="center" prop="tenantGrade"/>
      <el-table-column
        label="到期天数"
        align="center"
        prop="tenantExpirationTime"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" plain size="small">
              处理<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:tenant:edit']"
                >修改
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:tenant:remove']"
                >删除
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-position"
                  @click="bindDatasource(scope.row)"
                  v-show="scope.row.datasourceId == null"
                >绑定数据源
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-custom"
                  @click="openTenantExpirationTime(scope.row)"
                  v-hasPermi="['system:tenant:remove']"
                >激活租户
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-open"
                  @click="openLoginConfig(scope.row)"
                  v-hasPermi="['system:tenant:remove']"
                >配置登录页
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改租户信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="选择上级租户" prop="tenantParentId">
          <el-cascader v-model="form.tenantParentId"
                       :options="tenantAllList"
                       :props="{ checkStrictly: true ,label:'tenantName',value:'tenantId' }" clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="租户名称" prop="tenantName">
          <el-input v-model="form.tenantName" placeholder="请输入租户名称"/>
        </el-form-item>
        <el-form-item label="租户编号" prop="tenantCode">
          <el-input v-model="form.tenantCode" placeholder="请输入租户编号"/>
        </el-form-item>
        <el-form-item label="负责人" prop="owner">
          <el-input v-model="form.owner" placeholder="请输入负责人"/>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactInfo">
          <el-input v-model="form.contactInfo" placeholder="请输入联系方式"/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址"/>
        </el-form-item>

        <el-form-item label="客户端访问地址" prop="tenantClientLoginUrl">
          <el-input v-model="form.tenantClientLoginUrl" placeholder="请输入地址"/>
        </el-form-item>
        <el-form-item label="工具端访问地址" prop="tenantToolLoginUrl">
          <el-input v-model="form.tenantToolLoginUrl" placeholder="请输入地址"/>
        </el-form-item>
        <el-form-item label="租户等级" prop="tenantGrade">
          <el-input v-model="form.tenantGrade" placeholder="请输入地址"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改数据源信息对话框 -->
    <el-dialog
      :title="dataSourceTitle"
      :visible.sync="dataSourceOpen"
      width="500px"
      append-to-body
      class="loadingClass"
    >
      <el-radio-group
        v-model="dataSourceType"
        class="mb5"
        @input="dataSourceTypeChange"
      >
        <el-radio-button :label="true">公网</el-radio-button>
        <el-radio-button :label="false">内网</el-radio-button>
      </el-radio-group>
      <el-form
        ref="dataSourceForm"
        :model="dataSourceForm"
        :rules="dataSourceFormRules"
        label-width="120px"
      >
        <el-form-item label="数据源类型" prop="databaseType">
          <el-select
            v-model="dataSourceForm.databaseType"
            :placeholder="palcemsg"
            @change="selecthandle"
            :disabled="dataSourceType"
          >
            <el-option
              v-for="item in dict.type.datasource_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据库名称" prop="databaseName">
          <el-input
            v-model="dataSourceForm.databaseName"
            placeholder="请输入数据库名称"
          />
        </el-form-item>
        <el-form-item label="租户管理员账号" prop="tenantAccount">
          <el-input
            v-model="dataSourceForm.tenantAccount"
            placeholder="请输入租户管理员账号"
          />
        </el-form-item>

        <!-- !dataSourceType -->
        <el-form-item
          label="数据库IP"
          v-show="!dataSourceType"
          prop="databaseIp"
        >
          <el-input
            v-model="dataSourceForm.databaseIp"
            placeholder="请输数据库IP"
          />
        </el-form-item>
        <el-form-item label="用户名" v-show="!dataSourceType" prop="username">
          <el-input
            v-model="dataSourceForm.username"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="密码" v-show="!dataSourceType" prop="password">
          <el-input
            v-model="dataSourceForm.password"
            placeholder="请输入密码"
          />
        </el-form-item>

        <el-form-item label="端口号" v-show="!dataSourceType" prop="portNumber">
          <el-input
            v-model="dataSourceForm.portNumber"
            placeholder="请输入端口号"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitForm1"
          :disabled="dialogLoading"
          :loading="dialogLoading"
        >{{ dialogLoading ? '绑定中' : '确 定' }}
        </el-button
        >
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 激活租户弹出层-->
    <el-dialog
      title="激活租户"
      :visible.sync="tenantExpirationTimeOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="tenantExpirationTimeFrom"
        :model="tenantExpirationTimeFrom"
        :rules="rulesTenantExpirationTime"
        label-width="80px"
      >
        <el-form-item
          label="激活租户"
          prop="tenantExpirationTime"
          label-width="110px"
        >
          <el-input
            v-model="tenantExpirationTimeFrom.tenantExpirationTime"
            placeholder="请输入激活码"
          />
        </el-form-item>
        <el-form-item class="btn">
          <el-button
            type="primary"
            @click="activationOperationMethod('tenantExpirationTimeFrom')"
          >确 定
          </el-button
          >
          <el-button @click="tanentCancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 登录页面配置信息列表 -->
    <el-dialog
      title="配置登录页"
      width="800px"
      :visible.sync="loginOpen"
      append-to-body
    >
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :inline="true"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item prop="loginPageNumber">
          <span slot="label">
            <el-tooltip
              content="请在登录时的url后拼接参数：tenantId={编号}"
              placement="top"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
            编号:
          </span>
          <el-input
            v-model="loginForm.loginPageNumber"
            placeholder="请输入登录页面编号"
            disabled
          />
        </el-form-item>
        <!-- <el-col :span="8"> -->
        <el-form-item label="标题:" prop="loginPageTitle">
          <el-input
            v-model="loginForm.loginPageTitle"
            placeholder="请输入登录页面标题"
          />
        </el-form-item>
        <!-- </el-col> -->
        <!-- <el-col :span="8"> -->
        <el-form-item label="描述:" prop="loginPageDescription">
          <span slot="label">
            <el-tooltip
              content="推荐长度为8个汉字,可使用<br/>换行"
              placement="top"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
            描述:
          </span>
          <el-input
            v-model="loginForm.loginPageDescription"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <!-- </el-col>
        <el-col :span="8"> -->
        <el-form-item label="窗口标题:" prop="windowTitle">
          <el-input
            v-model="loginForm.windowTitle"
            placeholder="请输入窗口标题"
          />
        </el-form-item>
        <!-- </el-col> -->
        <!-- <el-col :span="8"> -->
        <el-form-item prop="loginPageLogo">
          <span slot="label">
            <el-tooltip content="推荐图片大小为194*64px" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            logo:
          </span>
          <image-upload :limit="1" v-model="loginForm.loginPageLogo"/>
        </el-form-item>
        <!-- </el-col> -->
        <!-- <el-col :span="8"> -->
        <el-form-item prop="loginPageBackgroundImage">
          <span slot="label">
            <el-tooltip content="推荐图片大小为1400*900px" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
            背景图:
          </span>
          <image-upload
            :limit="1"
            v-model="loginForm.loginPageBackgroundImage"
          />
        </el-form-item>
        <!-- </el-col> -->
        <!-- <el-col :span="8"> -->
        <!-- <el-form-item label="窗口logo:" prop="windowLogo">
          <image-upload
            :fileType="['png']"
            :limit="1"
            :uploadUrl="'/common/uploadAndConvert'"
            v-model="loginForm.windowLogo"
          />
        </el-form-item> -->
        <!-- </el-col> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitLoginForm">确 定</el-button>
        <el-button @click="cancelLoginForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTenant,
  getTenant,
  delTenant,
  addTenant,
  updateTenant,
  bindDatasource,
  selectAllUser,
  createTenant,
  initTenantMenuData,
  activationOperation,
  getTenantChildrenInfo, getTenantAllList
} from '@/api/system/tenant'
import {getDataSourceInfo, insertDataSource} from '@/api/system/data'
import {
  listConfiguration,
  getConfiguration,
  delConfiguration,
  addConfiguration,
  updateConfiguration
} from '@/api/system/configuration'
import {servicesLoading} from '@/utils/zkqy'
import {getIsExistUser} from '@/api/system/user'
import ExcelDownLoad from '@/components/ExcelDownLoad/index.vue'

export default {
  name: 'Tenant',
  dicts: [
    'datasource_type',
    'sqlserver_connection_information',
    'mysql_connection_information',
    'dm_connection_information',
    'orcale_connection_information',
    'system_login_url'
  ],
  components: {
    ExcelDownLoad
  },
  data() {
    return {
      tenantAllList: [],
      // 登录页面数据
      isEdit: false,
      loginOpen: false,
      loginForm: {
        loginPageNumber: '',
        loginPageTitle: '',
        loginPageDescription: '',
        loginPageLogo: '',
        loginPageBackgroundImage: '',
        windowTitle: '',
        windowLogo: '',
        tenantId: ''
      },
      // 前端导出数据
      selection: [],
      headerList: {
        租户名称: 'tenantName',
        租户编号: 'tenantCode',
        负责人: 'owner',
        联系方式: 'contactInfo',
        地址: 'address',
        是否删除: 'isDel'
      },
      excelTitle: 'tenant',
      // 弹窗的加载提示
      dialogLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租户信息表格数据
      tenantList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 所有用户信息
      allUser: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantName: null,
        tenantCode: null,
        owner: null,
        contactInfo: null,
        address: null
      },
      // 当前编辑租户的信息
      currentTenantInfo: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tenantName: [
          {required: true, message: '租户名称不能为空', trigger: 'blur'}
        ],
        tenantCode: [
          {required: true, message: '租户编号不能为空', trigger: 'blur'}
        ],
        tenantParentId: [
          {required: true, message: '请选择上级租户', trigger: 'blur'}
        ]
      },
      //数据源表单参数
      dataSourceType: true, //true:公网  false:内网
      dataSourceForm: {
        databaseType: '',
        databaseName: '',
        tenantAccount: '',
        databaseIp: '',
        username: '',
        password: '',
        portNumber: ''
      },
      dataSourceTitle: '',
      dataSourceOpen: false,
      fromTenantId: null,
      dataSourceFormRules: {
        databaseType: [
          {required: true, message: '数据源类型不能为空', trigger: 'change'}
        ],
        databaseName: [
          {required: true, message: '数据库名不能为空', trigger: 'blur'},
          {validator: this.databaseNameValidator, trigger: 'blur'}
        ],
        tenantAccount: [
          {
            required: true,
            message: '租户管理员账号不能为空',
            trigger: 'change'
          },
          {validator: this.tenantAccountValidator, trigger: 'blur'}
        ],
        databaseIp: [
          {required: true, message: '数据库IP不能为空', trigger: 'blur'}
        ],
        username: [
          {required: true, message: '用户名不能为空', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'}
        ],
        portNumber: [
          {required: true, message: '端口号不能为空', trigger: 'blur'}
        ]
      },
      //租户激活码弹窗表单
      tenantExpirationTimeFrom: {
        tenantId: null,
        tenantExpirationTime: ''
      },
      //租户激活码弹窗标题
      tenantExpirationTimeOpen: false,
      //租户激活码规则验证
      rulesTenantExpirationTime: {
        tenantExpirationTime: [
          {required: true, message: '请输入租户激活码', trigger: 'blur'}
        ]
      },
      currentPage: '',
      // 已存在的数据库名称
      databaseNameList: [],
      tableData1: [{
        id: 1,
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        id: 2,
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄'
      }, {
        id: 3,
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄',
        hasChildren: true
      }, {
        id: 4,
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1516 弄'
      }]
    }
  },
  computed: {
    palcemsg() {
      return this.dataSourceType ? 'mysql' : '请选择数据源类型'
    }
  },
  created() {
    this.getList()
    this.selectAllUser()
  },
  methods: {
    load(tree, treeNode, resolve) {
      console.log(tree, treeNode, resolve)
      // 根据当前租户id查询子租户
      getTenantChildrenInfo(tree.tenantId).then(res => {
        if (res.data != null) {
          resolve(res.data)
        } else {
          resolve({})
        }
      })
    },

    // 查询所有平台所有租户
    getTenantAllList() {
      getTenantAllList().then((response) => {
        let tenantAllListOne = this.handleTree(response.rows, 'tenantId', 'tenantParentId')
        this.tenantAllList = [
          {"tenantId": 0, "tenantName": "顶级租户"},
          ...tenantAllListOne
        ]
      })
    },
    buildTree(data, parentId = null) {
      const children = data.filter(item => item.tenantParentId === parentId)
      return children.map(child => ({
        value: child.tenantId,
        label: child.tenantName,
        children: this.buildTree(data, child.tenantId) // 将 child.tenant_id 作为下一层的 parentId
      }))
    },
    transformTenantsToCascaderOptions(tenants) {
      console.log(tenants)
      const options = []
      const map = {} // 用于存储每个tenant的引用，以便后续添加children

      tenants.forEach(tenant => {
        const {tenantId, tenantName, tenantParentId} = tenant
        const option = {
          value: tenantId,
          label: tenantName,
          children: [] // 初始化children数组
        }

        if (tenantParentId === null) {
          // 如果没有父级，说明是顶级租户，直接添加到options中
          options.push(option)
        } else {
          // 如果有父级，则先查找父级租户在map中的引用，并添加到其children数组中
          if (!map[tenantParentId]) {
            // 如果父级租户还没被处理过，先创建一个空的引用
            map[tenantParentId] = {children: []}
          }
          map[tenantParentId].children.push(option)
        }
        // 将当前租户添加到map中，方便后续查找
        map[tenantId] = option
      })

      // 遍历map，将顶级租户的children填充完整
      Object.values(map).forEach(option => {
        if (!options.includes(option)) {
          // 如果这个选项不是顶级租户，则将其添加到某个顶级租户的children中
          const parentOption = options.find(o => o.children.includes(option))
          if (parentOption) {
            parentOption.children.push(option)
          }
        }
      })
      console.log(options)
      return options
    },
    // 提交登录页配置数据
    submitLoginForm() {
      this.$refs.loginFormRef?.validate(async (valid) => {
        if (valid) {
          console.log(this.loginForm)
          let res = {},
            msg = ''
          if (this.isEdit) {
            res = await updateConfiguration(this.loginForm)
            msg = '修改'
          } else {
            res = await addConfiguration(this.loginForm)
            msg = '保存'
          }
          if (res.code == 200) {
            this.$message.success(`${msg}成功`)
            this.loginOpen = false
          } else {
            this.$message.error(`${msg}失败,请检查网络`)
          }
        } else {
          console.log(`${msg}失败,请检查网络`)
          return false
        }
      })
    },
    // 取消登录页配置
    cancelLoginForm() {
      this.loginOpen = false
    },
    // 编辑租户登录页配置
    async openLoginConfig(row) {
      try {
        let res = await getConfiguration(row.tenantId)
        if (res.code == 200) {
          if (res.data) {
            this.loginForm = res.data
            this.isEdit = true
          } else {
            this.resetloginForm()
            this.isEdit = false
          }
          // 目前一个租户只能有一个配置项故使用租户唯一编码
          this.loginForm.loginPageNumber = row.tenantCode
          this.loginForm.tenantId = row.tenantId
          this.loginOpen = true
        } else {
          this.$message.error('网络异常,请稍后再试')
        }
      } catch (error) {
      }
    },
    // 获取所用用户名,作校验用
    async selectAllUser() {
      let res = await selectAllUser()
      if (res.code == 200) {
        this.allUser = res.data
      } else {
        console.log(res.msg)
      }
    },
    // 重置login配置表单数据
    resetloginForm() {
      this.loginForm = {
        loginPageNumber: '',
        loginPageTitle: '',
        loginPageDescription: '',
        loginPageLogo: '',
        loginPageBackgroundImage: '',
        windowTitle: '',
        windowLogo: '',
        tenantId: ''
      }
    },
    // 租户名自定义校验规则
    async tenantAccountValidator(rule, value, callback) {
      // let isRepeat = this.allUser.filter((item) => item.userName == value);
      // if (isRepeat.length !== 0) {
      //   callback(new Error("租户账号重复"));
      // } else {
      //   callback();
      // }
      if (value) {
        await getIsExistUser({userName: value}).then((res) => {
          if (res.code == 200) {
            if (res.data) {
              callback()
            } else {
              callback(new Error('租户管理员账号已存在'))
            }
          } else {
            callback(new Error('租户管理员账号校验失败,请重新输入'))
          }
        })
      }
      callback()
    },
    // 数据库名自定义校验规则--请求后端校验
    // async databaseNameValidator(rule, value, callback) {
    //   if (value) {
    //     await getDataSourceInfo({ databaseName: value }).then((res) => {
    //       if (res.code == 200) {
    //         if (res.data) {
    //           callback();
    //         } else {
    //           callback(new Error("数据库名已存在"));
    //         }
    //       } else {
    //         callback(new Error("数据库名校验失败,请重新输入"));
    //       }
    //     });
    //   }
    // },
    // 数据库名称校验规则
    databaseNameValidator(rule, value, callback) {
      // 正则校验
      let regex = /^[a-z][a-z0-9]*$/
      if (regex.test(value)) {
        // callback(); // 输入内容符合规则
      } else {
        callback(new Error('只能包含小写字母和数字，且以小写字母开头'))
      }
      // 重名校验
      let isRepeat = this.databaseNameList.filter((item) => item == value)
      if (isRepeat.length !== 0) {
        callback(new Error('数据库名重复'))
      } else {
        callback()
      }
    },
    // 数据源类型改变回调
    dataSourceTypeChange(type) {
      this.$nextTick(() => {
        this.$refs.dataSourceForm.resetFields()
        this.dataSourceForm.databaseType = 'mysql'
        this.selecthandle('mysql')
      })
    },
    handleOpe() {
    },
    /** 查询租户信息列表 */
    getList() {
      this.loading = true
      this.currentPage = this.queryParams.pageNum
      listTenant(this.queryParams).then((response) => {
        this.tenantList = response.rows
        this.tenantList.forEach(item => {
          item['hasChildren'] = true
        })
        this.total = response.total
        this.loading = false
      })
    },
// 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 绑定数据源取消按钮
    cancel1() {
      this.dataSourceOpen = false
      this.reset1()
    },
    // 表单重置
    reset() {
      this.form = {
        tenantParentId: null,
        tenantId: null,
        tenantName: null,
        tenantCode: null,
        owner: null,
        contactInfo: null,
        address: null,
        createBy: null,
        createTime: null
      }
      this.resetForm('form')
    },
    // 表单重置
    reset1() {
      this.dataSourceType = true
      this.dataSourceForm = {
        id: null,
        databaseName: null,
        databaseIp: null,
        tenantAccount: '',
        username: null,
        password: null,
        portNumber: null,
        databaseType: 'mysql'
      }
      // this.resetForm("dataSourceForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection = selection
      this.ids = selection.map((item) => item.tenantId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getTenantAllList()
      // this.reset();
      this.open = true
      this.title = '添加租户信息'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const tenantId = row.tenantId || this.ids
      getTenant(tenantId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改租户信息'
      })
    },
    /** 绑定数据源按钮操作 */
    bindDatasource(row) {
      this.currentTenantInfo = row
      this.reset1()
      this.dialogLoading = false
      this.dataSourceOpen = true
      this.dataSourceTitle = row.tenantName + '配置数据库'
      this.fromTenantId = row.tenantId
      this.dataSourceTypeChange()

      // const tenantId = row.tenantId || this.ids;
      // getTenant(tenantId).then((response) => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改租户信息";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.tenantParentId.length >= 0) {
        // 处理当前租户的上级租户id
        this.form.tenantParentId = this.form.tenantParentId[this.form.tenantParentId.length - 1] != undefined ? this.form.tenantParentId[this.form.tenantParentId.length - 1] : ''
      }
      this.form.tenantClientLoginUrl = this.dict.type.system_login_url.find(item => item.label == 'client_login_url')?.value.replace("#{val}", this.form.tenantCode)
      this.form.tenantToolLoginUrl = this.dict.type.system_login_url.find(item => item.label == 'crm_login_url')?.value.replace("#{val}", this.form.tenantCode)
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.tenantId != null) {
            updateTenant(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addTenant(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
        this.reset()
      })
    },
    /** 提交按钮 */
    submitForm1() {
      if (this.dialogLoading) return
      this.dialogLoading = true
      this.$refs['dataSourceForm'].validate((valid) => {
        if (valid) {
          // const loading = servicesLoading(
          //   ".loadingClass",
          //   "正在绑定数据源",
          //   true
          // );
          if (this.dataSourceForm.id != null) {
            // bindDatasource(this.dataSourceForm).then((response) => {
            //   this.$modal.msgSuccess("修改成功");
            //   this.dataSourceOpen = false;
            //   this.getList();
            // });
            this.dialogLoading = false
          } else {
            let query = {
              tenantId: this.fromTenantId,
              dataSource: this.dataSourceForm
            }
            bindDatasource(query)
              .then((response) => {
                if (response.code == 200) {
                  let data = {
                    userName: this.dataSourceForm.tenantAccount,
                    nickName: this.currentTenantInfo.tenantName,
                    userType: '01',
                    tenantId: this.currentTenantInfo.tenantId,
                    password: '123456'
                  }
                  createTenant(data)
                    .then(async (res) => {
                      if (res.code == 200) {
                        let resp = await initTenantMenuData(
                          this.currentTenantInfo.tenantId
                        )
                        if ((resp.code = 200)) {
                          this.$modal.msgSuccess('新增成功')
                          this.dataSourceOpen = false
                          this.getList()
                        }
                      }
                    })
                    .finally(() => {
                      this.dialogLoading = false
                    })
                }
              })
              .finally(() => {
                this.dialogLoading = false
              })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const tenantIds = row.tenantId || this.ids
      this.$modal
        .confirm('是否确认删除租户信息编号为"' + tenantIds + '"的数据项？')
        .then(function () {
          return delTenant(tenantIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/tenant/export',
        {
          ...this.queryParams
        },
        `tenant_${new Date().getTime()}.xlsx`
      )
    },
    /**
     * 选择数据源校验名称
     */
    selecthandle(row) {
      let sql = {
        sqlserver: 'sqlserver_connection_information',
        mysql: 'mysql_connection_information',
        dm: 'dm_connection_information',
        oracle: 'oracle_connection_information'
      }
      let qar = {}
      this.dict.type[sql[row]].forEach((item) => {
        qar[item.label] = item.value
      })
      if (this.dataSourceType) {
        let {databaseIp, password, portNumber, username} = qar
        Object.assign(this.dataSourceForm, {
          databaseIp,
          password,
          portNumber,
          username
        })
      }
      getDataSourceInfo(qar).then((res) => {
        // console.log(res);
        this.databaseNameList = res.data
      })
    },
    handleTest() {
      let formdata = {
        databaseType: 'mysql',
        databaseName: 'test1111',
        databaseIp: '127.0.0.1',
        username: 'testname',
        password: '123123',
        portNumber: '3306'
      }
      insertDataSource(formdata).then((res) => {
        console.log(res)
      })
    },
    //重置租户激活码表单
    restTenantExpirationTime() {
      this.tenantExpirationTimeFrom = {
        tenantId: null,
        tenantExpirationTime: ''
      }
      this.resetForm('tenantExpirationTimeFrom')
    },
    /**打开激活码弹窗*/
    openTenantExpirationTime(row) {
      // this.reset();
      const tenantId = row.tenantId || this.ids
      this.tenantExpirationTimeFrom.tenantId = row.tenantId
      this.tenantExpirationTimeOpen = true
      // this.title="激活租户";
    },
    /**激活租户操作*/
    activationOperationMethod(form) {
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          let response = await activationOperation(
            this.tenantExpirationTimeFrom
          )
          if (response.code == 200) {
            this.$message.success('激活成功')
            //重新刷新列表
            this.getList()
          } else {
            this.$message.error('激活失败')
          }
          this.tenantExpirationTimeOpen = false
          this.tenantExpirationTimeFrom = {
            tenantId: null,
            tenantExpirationTime: null
          }
        }
      })
    },
    // 激活租户对话框取消按钮
    tanentCancel() {
      this.tenantExpirationTimeOpen = false
      this.tenantExpirationTimeFrom = {
        tenantId: null,
        tenantExpirationTime: null
      }
    }
  }
}
</script>
