<template>
  <div class="app-container">
    <el-form ref="searchForm" :model="queryParams" inline :label-width="'100px'">
      <el-form-item v-if="superAdmin && enableTenant===true" :label="$t('ec.user.tenant')" prop="tenantId">
        <ec-tenant v-model="queryParams.tenantId" />
      </el-form-item>
      <el-form-item label="type" prop="dictType">
        <el-input v-model="queryParams.dictType" type="text" placeholder="type" />
      </el-form-item>
      <el-form-item label="label" prop="vname">
        <el-input v-model="queryParams.vname" type="text" placeholder="label" />
      </el-form-item>
      <el-form-item label="value" prop="vkey">
        <el-input v-model="queryParams.vkey" type="text" placeholder="value" />
      </el-form-item>
      <el-form-item class="searchItem" :label-width="'50px'">
        <el-button type="primary" @click="getDictData">{{ $t('ec.table.query') }}</el-button>
        <el-button type="default" @click="handleReset">{{ $t('ec.table.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <vxe-virtual-tree
      ref="vxe"
      row-key
      show-overflow
      show-header-overflow
      border
      highlight-hover-row
      class="vxe-table-element"
      max-height="1000"
      resizable
      sync-resize
      strict
      auto-resize
      :loading="loading"
      :toolbar="tableToolbar"
      :columns="columns"
      :tree-config="{children: 'children'}"
      :data="dictData"
      :checkbox-config="{ checkStrictly: !checkStrictly, checkField: 'checked', halfField: 'indeterminate'}"
    >
      <template v-slot:toolbar_buttons>
        <el-button :disabled="dictData.length === 0" @click="toggleTree">{{ $t('ec.table.expandCollapse') }}</el-button>
        <el-button v-permission="['dict:add']" type="primary" @click="add()">{{ $t('ec.table.add') }}</el-button>
        <el-button v-permission="['dict:edit']" :disabled="!onlyOne" type="warning" @click="edit(selections[0])">{{ $t('ec.table.edit') }}</el-button>
        <el-button v-permission="['dict:delete']" :disabled="!oneMore" @click="remove()">{{ $t('ec.table.delete') }}</el-button>
        <!--        <el-button @click="getDictData">{{ $t('ec.table.refresh') }}</el-button>-->
        <el-button v-permission="['dict:import']" type="primary" @click="importVisible = true">{{ $t('ec.table.import') }}</el-button>
        <el-button v-permission="['dict:export']" type="success" @click="exportExcel">{{ $t('ec.table.export') }}</el-button>
      </template>

      <template v-slot:sort_operation="{ row }">
        <el-input-number v-model="row.sortNum" @change="updateSort(row)" />
      </template>

      <template v-slot:status_operation="{ row }">
        <el-switch
          v-model="row.valid"
          active-color="#13ce66"
          active-value="1"
          inactive-value="0"
          @change="updateStatus(row)"
        />
      </template>

      <!--使用 bottom 插槽-->
      <template v-slot:bottom>
        <div class="vxe-bottom-container">
          <el-checkbox v-model="checkStrictly">{{ $t('ec.tree.cascade') }}</el-checkbox>
        </div>
      </template>

      <template v-slot:operation="{ row, column }">
        <el-button size="mini" type="text" @click="view(row)">{{ $t('ec.table.view') }}</el-button>
        <el-button v-if="!row.pid || row.pid === '0'" v-permission="['dict:add']" size="mini" type="text" @click="add(row, column)">
          {{ $t('ec.tree.addChild') }}
        </el-button>
        <el-dropdown
          v-permission="['dict:edit', 'dict:delete']"
          trigger="click"
          style="padding-left:10px;padding-right:10px;"
          @command="command => dropDownCmd(command, row)"
        >
          <el-button type="text" icon="el-icon-arrow-down" size="mini" />
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-permission="['dict:edit']" command="edit">{{ $t('ec.table.edit') }}</el-dropdown-item>
            <el-dropdown-item v-permission="['dict:delete']" command="remove">{{ $t('ec.table.delete') }}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!--        <el-button size="mini" type="warning" @click="edit(row)">编辑</el-button>-->
        <!--        <el-button size="mini" type="danger" @click="remove(row.id)">删除</el-button>-->
      </template>
    </vxe-virtual-tree>
    <ec-import
      :upload-url="importUrl"
      :tpl-url="tplUrl"
      title="数据字典上传"
      :visible="importVisible"
      :upload-params="{ isNewPk: false, strategy: 'ignore' }"
      @onSuccess="getDictData"
      @close="importVisible = false"
    >
      <template v-slot:extra_params="{ extraParams }">
        <el-form-item label="是否生成新主键">
          <ec-radio-group v-model="extraParams.isNewPk" :ec-data="[ {value: false, label: '否'}, {value: true, label: '是' } ]" />
        </el-form-item>
        <el-form-item label="导入策略">
          <ec-radio-group v-model="extraParams.strategy" :ec-data="[ {value: 'ignore', label: '忽略'}, {value: 'overrite', label: '更新' } ]" />
        </el-form-item>
      </template>
    </ec-import>

    <detail ref="dictEditDialog" @refreshDataList="getDictData" />
  </div>
</template>
<script>
import mixin from 'ecip-web/utils/common-mixin'
import { getData, deleteByIds, updateStatus, updateSort } from 'ecip-web/api/vue/dict/ecipDictApi'
import Detail from './components/detail'
import { treeEach } from 'ecip-web/utils/tableUtil'
import { download } from 'ecip-web/utils'
const enableTenant = window._CONFIG['enableTenant'] === undefined ? true : window._CONFIG['enableTenant']
export default {
  name: 'VueDictEcipDictView',
  components: { Detail },
  mixins: [...mixin],
  data() {
    return {
      enableTenant,
      loading: false,
      expand: false,
      checkStrictly: true,
      onlyOne: true, // 工具栏编辑按钮是否禁用，只有当且仅当选择一条记录的时候才可编辑
      oneMore: true, //  工具栏删除、停用、启用按钮是否禁用，当选中条数为0的时候禁用
      showSearch: false,
      importVisible: false,
      importUrl: 'api/v1/dict/ecipDict/importExcel',
      exportUrl: 'api/v1/dict/ecipDict/exportExcel',
      tplUrl: 'api/v1/dict/ecipDict/excelTemplate',
      queryParams: {
        tenantId: '',
        vname: '',
        vkey: '',
        dictType: ''
      },
      dictData: [],
      selections: [],
      tableToolbar: {
        id: 'vue.dict.ecipDictView-toolbar',
        custom: true,
        slots: {
          buttons: 'toolbar_buttons'
        },
        zoom: true, // 最大化按钮
        // 列宽操作记录
        resizable: {
          storage: true
        },
        // 列操作记录
        setting: {
          storage: true
        }
      },
      columns: [
        { type: 'checkbox', width: 40, fixed: 'left', align: 'center' },
        { title: 'label', field: 'vname', treeNode: true, fixed: 'left', minWidth: 180, showOverflow: true },
        { title: 'type', field: 'dictType', minWidth: 180, showOverflow: true },
        { title: 'value', field: 'vkey', minWidth: 180, showOverflow: true },
        { title: 'ec.user.tenant', field: 'tenantName', minWidth: 180, showOverflow: true },
        { title: 'ec.table.sort', field: 'sortNum', minWidth: 180, showOverflow: true, slots: { default: 'sort_operation' }},
        { title: 'ec.table.enableStatus', field: 'valid', minWidth: 180, showOverflow: true, slots: { default: 'status_operation' }},
        { title: 'ec.dict.extra', field: 'extra', minWidth: 180, showOverflow: true },
        { title: 'ec.table.remarks', field: 'remark', minWidth: 180, showOverflow: true },
        { title: 'ec.table.actions', minWidth: 150, fixed: 'right', align: 'center', slots: { default: 'operation' }}
      ]
    }
  },
  mounted() {
    if (enableTenant !== true) {
      const idx = this.columns.findIndex(item => {
        return item.field == 'tenantName'
      })
      if (typeof idx !== 'undefined') {
        this.columns.splice(idx, 1)
      }
    }
    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.getDictData()
  },
  methods: {
    async updateSort(row) {
      try {
        this.loading = true
        const { message } = await updateSort(row.id, { sortNum: row.sortNum })
        this.$notify.success(message)
        await this.getDictData()
      } finally {
        this.loading = false
      }
    },
    async updateStatus(row) {
      try {
        this.loading = true
        const { message } = await updateStatus(row.id, { valid: row.valid })
        this.$notify.success(message)
        await this.getDictData()
      } finally {
        this.loading = false
      }
    },
    dropDownCmd(command, row) {
      switch (command) {
        case 'edit':
          this.edit(row)
          break
        case 'remove':
          this.remove(row.id)
          break
      }
    },
    async getDictData() {
      this.selections = []
      let expands
      this.$nextTick(() => {
        expands = this.$refs.vxe.getTreeExpandRecords().map(item => item.id)
      })
      this.loading = true
      try {
        const { data } = await getData({}, this.queryParams)
        this.dictData = data
        this.$nextTick(() => {
          const result = []
          treeEach(this.dictData, node => {
            if (expands.includes(node.id)) {
              result.push(node)
            }
          })
          this.$refs.vxe.setTreeExpand(result, true)
        })
      } finally {
        this.loading = false
      }
    },
    add(parent) {
      this.$refs.dictEditDialog.init('add', {}, parent)
    },
    edit(row) {
      this.$refs.dictEditDialog.init('edit', row)
    },
    view(row) {
      this.$refs.dictEditDialog.init('view', 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(row => row.id)
        }
        try {
          this.loading = true
          await deleteByIds(deleteIds)
          await this.getDictData()
          this.$notify.success(this.$t('ec.message.delSuccess'))
        } finally {
          this.loading = false
        }
      })
    },
    toggleTree() {
      this.expand = !this.expand
      this.$refs.vxe.setAllTreeExpansion(this.expand)
    },
    handleReset() {
      Object.assign(this.$data.queryParams, this.$options.data().queryParams)
      this.getDictData()
    },
    async exportExcel() {
      this.loading = true
      await download({ url: this.exportUrl, method: 'post', data: this.queryParams })
      this.loading = false
    }
  }
}
</script>

<style scoped>

</style>
