i<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="100px">
      <el-form-item label="租户名称" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入租户名称"
          clearable
          @keyup.enter.native="loadData"
        />
      </el-form-item>
      <el-form-item label="超管账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入超管账号"
          clearable
          @keyup.enter.native="loadData"
        />
      </el-form-item>
      <el-form-item label="租户类型">
        <el-select v-model="queryParams.tenantType" filterable placeholder="请选择租户类型" clearable>
          <el-option
            v-for="dict in dict.type[DICT_TYPE.sys_tenant_type]"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" filterable placeholder="请选择租户状态" clearable>
          <el-option
            v-for="dict in dict.type[DICT_TYPE.SYSTEM_TENANT_STATUS]"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="createDateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="loadData">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:tenant:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="$refs.tenantDialogRef.handleOpen()"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:tenant:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="loadData" />
    </el-row>

    <j-table
      v-loading="loading"
      row-key="id"
      :show-selection="false"
      :show-index="false"
      :columns="columns"
      :default-expand-all="true"
      :data="tableData"
      :pagination.sync="pagination"
      @selection-change="handleSelectionChange"
      @pagination-change="loadData"
    >
      <template slot="tenantName" slot-scope="{ row }">
        <span :class="{'margin-tenant-name': Number(row.params.level)===1 && (!row.children || row.children.length === 0)}">{{ row.tenantName }}</span>
      </template>
      <template slot="longTerm" slot-scope="{ row }">
        <span v-if="row.tenantStartTime && row.tenantEndTime">{{ `${moment(row.tenantStartTime).format('yyyy-MM-DD')} - ${moment(row.tenantEndTime).format('yyyy-MM-DD')}` }}</span>
        <span v-else>--</span>
      </template>
      <template slot="status" slot-scope="{ row }">
        <dict-tag :options="dict.type[DICT_TYPE.SYSTEM_TENANT_STATUS]" :value="row.status" />
      </template>
      <template slot="tenantType" slot-scope="{ row }">
        <span v-if="row.tenantType === Number(options.sysTenantTypeMap.group)">集团</span>
        <span v-else>幼儿园</span>
      </template>
      <el-table-column label="操作" align="center" fixed="right" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button
            v-hasPermi="['system:tenant:edit']"
            size="mini"
            type="text"
            @click.stop="$refs.tenantDialogRef.handleEdit(row)"
          >编辑</el-button>
          <el-button
            v-hasPermi="['system:tenant_permission:edit']"
            size="mini"
            type="text"
            @click.stop="$refs.permissionDialogRef.handleOpen(row)"
          >权限管理</el-button>
          <el-button
            v-hasPermi="['system:tenant:resetPwd']"
            size="mini"
            class="text-danger"
            type="text"
            @click.stop="handleResetPwd(row)"
          >重置密码</el-button>
        </template>
      </el-table-column>
    </j-table>

    <tenant-dialog ref="tenantDialogRef" @ok="loadData" />
    <permission-dialog ref="permissionDialogRef" @ok="loadData" />
    <copy-pwd-dialog ref="copyPwdRef" />
  </div>
</template>

<script>
import { fetchTenantPage, delTenant, resetTenantPwd } from '@/api/system/tenant'
import { fetchAllTenantPackage } from '@/api/system/tenantpackage'
import { parseTime } from '@/utils/vctgo'
import TenantDialog from '@/views/system/tenant/modules/TenantDialog.vue'
import PermissionDialog from '@/views/system/tenant/modules/PermissionDialog.vue'
import CopyPwdDialog from '@/views/system/tenant/modules/CopyPwdDialog.vue'
import JTable from '@/components/Table/index.vue'
import { DICT_TYPE } from '@/utils/dict/config'
import { getDictLabel } from '@/utils/dict/config'
import options from '@/utils/dict/options'
import moment from 'moment'

const initParams = {
  tenantName: null,
  userName: null,
  userPhone: null,
  beginTenantTime: null,
  endTenantTime: null,
  status: null
}
export default {
  name: 'Tenant',
  dicts: [DICT_TYPE.SYSTEM_TENANT_STATUS, DICT_TYPE.sys_tenant_type],
  components: {
    TenantDialog,
    JTable,
    PermissionDialog,
    CopyPwdDialog
  },
  data() {
    return {
      options,
      DICT_TYPE,
      loading: true,
      resetPwdDialog: false,
      resetPwd: null,
      // 显示搜索条件
      showSearch: true,
      // 租户管理表格数据
      tenantList: [],
      packageList: [],
      // 备注时间范围
      daterangeTenantTime: [],
      createDateRange: [], // 创建时间
      // 查询参数
      queryParams: Object.assign({}, initParams),
      tableData: [],
      selected: [],
      pagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      columns: [
        { prop: 'tenantName', label: '租户名称', minWidth: 160, align: 'left' },
        { prop: 'tenantType', label: '租户类型', customRender: 'tenantType', minWidth: 80, align: 'left' },
        { prop: 'userName', label: '超管账号', minWidth: 120, align: 'left' },
        { prop: 'userPhone', label: '联系电话', minWidth: 120 },
        { prop: 'sysService', label: '开通业务', minWidth: 160, align: 'left', formatter: ({ sysService }) => sysService || '--' },
        { prop: 'longTerm', label: '有效期限', minWidth: 180, customRender: 'longTerm' },
        { prop: 'status', label: '状态', customRender: 'status', minWidth: 80 },
        { prop: 'createNickName', label: '创建人', minWidth: 100, align: 'left' },
        { prop: 'createTime', label: '创建时间', minWidth: 160 }
      ]
    }
  },
  computed: {
    isBatch() {
      return this.selected && this.selected.length > 0
    }
  },
  created() {
    this.loadData()
    this.getAllTenantPackage()
  },
  activated() {
    this.loadData()
  },
  methods: {
    moment,
    getDictLabel,
    getAllTenantPackage() {
      fetchAllTenantPackage().then(({ data }) => {
        this.packageList = data
      })
    },
    loadData() {
      this.loading = true
      fetchTenantPage(this.addDateRange(Object.assign({}, this.pagination, this.queryParams), this.createDateRange, 'CreateTime'))
        .then(({ data, total }) => {
          this.tableData = data
          this.pagination.total = total
        }).finally(() => {
          this.loading = false
        })
    },
    /** 重置按钮操作 */
    handleReset() {
      this.createDateRange = []
      this.pagination.pageNum = 0
      this.queryParams = Object.assign({}, initParams)
      this.loadData()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selected = selection
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除当前租户数据项？').then(function() {
        return delTenant(ids)
      }).then(() => {
        this.loadData()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/tenant/export', {
        ...this.queryParams
      }, `租户管理_${parseTime(new Date().getTime(), '{y}-{m}-{d}')}.xlsx`)
    },
    handleResetPwd(row) {
      const userAccount = row.userName
      this.$modal.confirm('确认要重置密码吗？').then(() => {
        resetTenantPwd(row).then(({ data }) => {
          if (data) this.$refs.copyPwdRef.handleOpen({ userAccount, pwd: data })
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.margin-tenant-name { margin-left: 23px }
</style>
