<template>
  <div class="app-container">
    <el-form ref="searchForm" :model="queryParams" inline :label-width="'100px'">
      <!--      <el-form-item label="ID" prop="id">-->
      <!--        <el-input v-model="queryParams.id" type="text" placeholder="ID" />-->
      <!--      </el-form-item>-->

      <!--      <el-form-item :label="$t('ec.user.tenant')" prop="name">-->
      <!--        <ec-tenant v-model="queryParams.name" value-field="name" :placeholder="$t('ec.user.tenant')" />-->
      <!--      </el-form-item>-->

      <el-form-item :label="$t('ec.user.tenant')" prop="name">
        <ec-tenant-by-pro v-model="queryParams.name" value-field="name" :placeholder="$t('ec.user.tenant')" />
      </el-form-item>

      <el-form-item :label="$t('ec.table.code')" prop="code">
        <el-input v-model="queryParams.code" type="text" :placeholder="$t('ec.table.code')" />
      </el-form-item>
      <el-form-item class="searchItem" :label-width="'50px'">
        <el-button type="primary" @click="queryData">{{ $t('ec.table.query') }}</el-button>
        <el-button type="default" @click="handleReset">{{ $t('ec.table.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <vxe-grid
      ref="vxe"
      highlight-hover-row
      border
      resizable
      sync-resize
      auto-resize
      show-overflow
      show-header-overflow
      max-height="1000"
      class="vxe-table-element"
      :loading="loading"
      :start-index="(page.currentPage - 1) * page.pageSize"
      :pager-config="page"
      :sort-config="{ trigger: 'cell' }"
      :columns="columns"
      :data="tableData"
      :toolbar="tableToolbar"
      @sort-change="sortMethod"
      @page-change="handlePageChange"
    >
      <template v-slot:toolbar_buttons>
        <el-button v-permission="['tenant:add']" type="primary" @click="add()">{{ $t('ec.table.add') }}</el-button>
        <el-button v-permission="['tenant:edit']" type="warning" :disabled="!onlyOne" @click="edit()">{{ $t('ec.table.edit') }}</el-button>
        <el-button v-permission="['tenant:copy']" type="success" @click="copyTenant">{{ $t('ec.table.copy') }}</el-button>
        <el-button v-permission="['tenant:delete']" type="danger" :disabled="!oneMore" @click="remove()">{{ $t('ec.table.delete') }}</el-button>
        <!--        <el-button v-permission="['tenant:import']" @click="importVisible = true">导入</el-button>-->
        <!--        <el-button v-permission="['tenant:export']" @click="exportExcel">导出</el-button>-->
      </template>

      <template v-slot:operation="{ row }">
        <el-button v-permission="['tenant:edit']" size="mini" type="warning" @click="edit(row)">{{ $t('ec.table.edit') }}</el-button>
        <el-button v-permission="['tenant:app']" size="mini" type="success" @click="registerApp(row)">{{ $t('ec.app.app') }}</el-button>
        <el-button v-permission="['tenant:app']" size="mini" type="primary" @click="tenantRelation(row)">{{ $t('ec.tenant.relateTenant') }}</el-button>
        <el-button v-permission="['tenant:area']" size="mini" type="primary" @click="areaRelation(row)">{{ $t('ec.tenant.relateArea') }}</el-button>
        <el-button v-permission="['tenant:delete']" size="mini" type="danger" @click="remove(row.id)">{{ $t('ec.table.del') }}</el-button>
      </template>
    </vxe-grid>

    <copy-modal ref="copyModal" />

    <detail ref="saasTenantDialog" @refreshDataList="getData" />
    <tenant-app-modal ref="tenantAppModal" />
    <tenant-relation-modal ref="tenantRelationModal" @refreshData="getData" />
    <tenant-area-modal ref="tenantAreaModal" @refreshData="getData" />

  </div>
</template>

<script>
import mixin from 'ecip-web/utils/common-mixin'
import { getData, deleteByIds } from 'ecip-web/api/vue/tenant/saasTenantApi'
import Detail from './components/detail'
import TenantAppModal from './components/tenantAppModal'
import TenantRelationModal from './components/tenantRelationModal'
import TenantAreaModal from './components/tenantAreaModal'
import CopyModal from 'ecip-web/views/vue/components/copyModal'

export default {
  name: 'VueTenantTenantSaasTenantView',
  components: { Detail, TenantAppModal, CopyModal, TenantRelationModal, TenantAreaModal },
  mixins: [...mixin],
  data() {
    return {
      importVisible: false,
      loading: false,
      onlyOne: true, // 工具栏编辑按钮是否禁用，只有当且仅当选择一条记录的时候才可编辑
      oneMore: true, //  工具栏删除按钮是否禁用，当选中条数为0的时候禁用
      tableToolbar: {
        id: 'vue.tenant.tenant.saasTenantView-toolbar',
        custom: true,
        slots: {
          buttons: 'toolbar_buttons'
        },
        zoom: true, // 最大化按钮
        // 列宽操作记录
        resizable: {
          storage: true
        },
        // 列操作记录
        setting: {
          storage: true
        }
      },
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 20,
        align: 'left',
        pageSizes: [10, 20, 50, 100, 200, 500],
        layouts: ['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total'],
        perfect: true,
        field: 'create_date',
        order: 'desc'
      },
      selections: [],
      tableData: [],
      columns: [
        { type: 'checkbox', width: 40, fixed: 'left', align: 'center' },
        { type: 'expand', width: 60, align: 'center', slots: { content: 'detail_content' }},
        { title: 'ec.table.name', field: 'name', minWidth: 180 },
        { title: 'ec.table.shortName', field: 'simpleName', minWidth: 180 },
        { title: 'ec.table.code', field: 'code', minWidth: 180 },
        { title: 'ec.table.linkTenant', field: 'childNames', minWidth: 180 },
        { title: 'ec.table.linkArea', field: 'areaNames', minWidth: 180 },
        { title: 'ec.date.effectiveTime', field: 'effectiveDate', minWidth: 180, sortable: true, formatter: ['date', 'yyyy-MM-dd HH:mm:ss'] },
        { title: 'ec.date.expirationTime', field: 'expireDate', minWidth: 180, sortable: true, formatter: ['date', 'yyyy-MM-dd HH:mm:ss'] },
        { title: 'ec.log.desc', field: 'remarks', minWidth: 180 },
        { title: 'ec.table.actions', width: 350, fixed: 'right', align: 'center', slots: { default: 'operation' }}
      ],
      queryParams: {
        id: '',
        name: '',
        code: ''
      }
    }
  },
  mounted() {
    this.$watch(this.$refs.vxe.getCheckboxRecords, (newValue, oldValue) => {
      this.selections = newValue
      this.onlyOne = this.selections.length === 1
      this.oneMore = this.selections.length > 0
    })
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      // 每次查询初始化checkbox selections
      this.selections = []
      try {
        this.loading = true
        const { data } = await getData(Object.assign({}, { size: this.page.pageSize, current: this.page.currentPage,
          order: this.page.order, field: this.page.field }), this.queryParams)
        this.tableData = data.records
        this.page.total = data.total
      } finally {
        this.loading = false
      }
    },
    handlePageChange({ currentPage, pageSize }) {
      this.page.currentPage = currentPage
      this.page.pageSize = pageSize
      this.getData()
    },
    sortMethod({ column, property, order }) {
      this.page.field = property.replace(/([A-Z])/g, '_$1').toLowerCase()
      this.page.order = order
      this.getData()
    },
    add() {
      this.$refs.saasTenantDialog.init('add')
    },
    edit(item) {
      const row = item || this.selections[0]
      this.$refs.saasTenantDialog.init('edit', row)
    },
    tenantRelation(record) {
      this.$refs.tenantRelationModal.init(record)
    },
    areaRelation(record) {
      this.$refs.tenantAreaModal.init(record)
    },
    copyTenant() {
      const copyUrl = 'api/v1/tenant/saasTenant/copy'
      this.$refs.copyModal.init(this.$t('ec.tenant.copy'), copyUrl)
    },
    registerApp(row) {
      this.$refs.tenantAppModal.init(row)
    },
    remove(id) {
      this.$confirm(this.$t('ec.message.delConfirm'), this.$t('ec.message.prompt'), {
        confirmButtonText: this.$t('ec.message.confirm'),
        cancelButtonText: this.$t('ec.message.cancel'),
        type: 'warning'
      }).then(async() => {
        let deleteIds = []
        if (id) {
          deleteIds.push(id)
        } else {
          deleteIds = this.selections.map(item => item.id)
        }
        await deleteByIds(deleteIds)
        await this.getData()
        this.$notify.success(this.$t('ec.message.delSuccess'))
      })
    },
    async exportExcel() {
      // this.loading = true
      // await download({ url: this.exportUrl, method: 'post', data: this.queryParams })
      // this.loading = false
    },
    queryData() {
      Object.assign(this.$data.page, this.$options.data().page)
      this.getData()
    },
    handleReset() {
      Object.assign(this.$data.page, this.$options.data().page)
      Object.assign(this.$data.queryParams, this.$options.data().queryParams)
      this.getData()
    }
  }
}
</script>

<style scoped>

</style>
