<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
          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
      v-loading="loading"
      :data="tenantList"
      style="width: 100%"
      row-key="tenantId"
      border
      lazy
      :load="load"
      :tree-props="{children: 'children', hasChildren:'hasChildren' }"

      @cell-dblclick="copyText"
    >
      <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>

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

<script>
import {
  listTenant,
  getTenantAllList,
  selectAllUser,
  getTenantChildrenInfo
} from '@/api/system/tenant'
import {mapState} from "vuex";
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 {

      // 前端导出数据
      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: {
        tenantParentId: 0,
        pageNum: 1,
        pageSize: 10,
        tenantName: null,
        tenantCode: null,
        owner: null,
        contactInfo: null,
        address: null
      },
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state
    })
  },
  created() {

    this.getList()
    this.selectAllUser()
  },
  methods: {
    copyText(row, column, cell, event) {
      // 双击复制
      const textToCopy = event.target.innerText;
      navigator.clipboard.writeText(textToCopy).then(() => {
        this.$message({message: '复制成功', type: 'success'}); // 提示
      }).catch((error) => {
        console.error('复制失败:', error);

      });
    },
    load(tree, treeNode, resolve) {
      console.log(tree, treeNode, resolve)
      // 根据当前租户id查询子租户
      getTenantChildrenInfo(tree.tenantId).then(res => {
        if (res.data != null) {
          resolve(res.data)
        } else {
          resolve({})
        }
      })
    },


    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
      }))
    },

    // 获取所用用户名,作校验用
    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: ''
      }
    },

    /** 查询租户信息列表 */
    getList() {
      this.loading = true
      this.currentPage = this.queryParams.pageNum
      this.queryParams.tenantParentId = this.userInfo.user.tenant.tenantId
      getTenantAllList(this.queryParams).then((response) => {
        this.tenantList = response.rows
        this.tenantList.forEach(item => {
          item['hasChildren'] = true
        })
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/tenant/export',
        {
          ...this.queryParams
        },
        `tenant_${new Date().getTime()}.xlsx`
      )
    },
  }
}
</script>
