<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" clearable filterable />
      </el-form-item>
      <el-form-item v-if="superAdmin" :label="$t('ec.app.app')" prop="appId">
        <ec-register-app v-model="queryParams.appId" clearable filterable default-first :tenant-id="queryParams.tenantId" @hasInit="getTreeData('init')" @change="getTreeData('change')" />
      </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 :label="$t('ec.table.name')" prop="name">
        <el-input v-model="queryParams.shortName" type="text" :placeholder="$t('ec.table.name')" />
      </el-form-item>
      <el-form-item class="searchItem" :label-width="'50px'">
        <el-button type="primary" @click="getTreeData">{{ $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
      row-id="id"
      show-overflow
      show-header-overflow
      border
      highlight-hover-row
      max-height="1000"
      class="vxe-table-element"
      resizable
      sync-resize
      auto-resize
      :loading="loading"
      :toolbar="tableToolbar"
      :columns="columns"
      :tree-config="{children: 'children'}"
      :data="gridData"
      :checkbox-config="{ checkStrictly: !checkStrictly, checkField: 'checked', halfField: 'indeterminate'}"
    >
      <template v-slot:toolbar_btns>
        <el-button :disabled="gridData.length === 0" @click="toggleTree">{{ $t('ec.table.expandCollapse') }}</el-button>
        <el-button v-permission="['dept:add']" type="primary" @click="add()">{{ $t('ec.table.add') }}</el-button>
        <el-button v-permission="['dept:edit']" :disabled="!onlyOne" type="warning" @click="edit()">{{ $t('ec.table.edit') }}</el-button>
        <el-button v-permission="['dept:copy']" type="primary">{{ $t('ec.table.copy') }}</el-button>
        <el-button v-permission="['dept:delete']" type="danger" :disabled="!oneMore" @click="deleteByIds()">{{ $t('ec.table.delete') }}</el-button>
<!--        <el-button @click="getTreeData">{{ $t('ec.table.refresh') }}</el-button>-->
        <el-button v-permission="['dept:import']" type="primary" @click="importVisible = true">{{ $t('ec.table.import') }}</el-button>
        <el-button v-permission="['dept:export']" type="success" @click="exportExcel">{{ $t('ec.table.export') }}</el-button>
        <!-- todo 导入的时候传递一个download权限字符串进去 -->
      </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:default_sortNum="{ row }">
        <el-input-number v-model="row.sortNum" :disabled="!checkPermission(['dept:edit'])" @change="updateSort(row)" />
      </template>

      <template v-slot:default_status="{ row }">
        <el-switch
          v-model="row.status"
          active-color="#13ce66"
          active-value="1"
          inactive-value="0"
          :disabled="!checkPermission(['dept:edit'])"
          @change="updateStatus(row)"
        />
      </template>

<!--      <template v-slot:deptLegal="{ row }">-->
<!--        <ec-user-modal-->
<!--          :value="row.deptLegal"-->
<!--          readonly-->
<!--          :loadDeptTree="false"-->
<!--        />-->
<!--      </template>-->

      <template v-slot:operation="{ row }">
        <el-button type="text" @click="view(row)">{{ $t('ec.table.view') }}</el-button>
        <el-button v-permission="['dept:edit']" type="text" @click="edit(row)">{{ $t('ec.table.edit') }}</el-button>
        <el-button v-permission="['dept:delete']" type="text" @click="deleteByIds(row.id)">{{ $t('ec.table.del') }}</el-button>
      </template>
    </vxe-virtual-tree>

    <ec-import
      :upload-url="importUrl"
      :tpl-url="tplUrl"
      :title="$t('ec.table.importBase')"
      :visible="importVisible"
      :upload-params="{ isNewPk: true, strategy: 'ignore' }"
      @onSuccess="getTreeData"
      @close="importVisible = false"
    >
      <template v-slot:extra_params="{ extraParams }">
        <el-form-item :label="$t('ec.import.isNewPk')">
          <ec-radio-group v-model="extraParams.isNewPk" :ec-data="[ {value: false, label: $t('ec.table.no')}, {value: true, label: $t('ec.table.yes') } ]" />
        </el-form-item>
        <el-form-item :label="$t('ec.import.strategy')">
          <ec-radio-group v-model="extraParams.strategy" :ec-data="[ {value: 'ignore', label: $t('ec.import.ignore')}, {value: 'overwrite', label: $t('ec.import.overwrite') } ]" />
        </el-form-item>
      </template>
    </ec-import>
    <detail ref="deptDetail" @refreshData="getTreeData" />
  </div>
</template>
<script>
import mixin from 'ecip-web/utils/common-mixin'
import { getData as getTreeData, deleteByIds, updateStatus, updateSort } from 'ecip-web/api/vue/dept/sysrDeptApi'
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: 'VueDeptSysrDeptView',
  components: { Detail },
  mixins: [...mixin],
  data() {
    return {
      enableTenant,
      importVisible: false,
      expand: false,
      loading: false,
      checkStrictly: true,
      onlyOne: true, // 工具栏编辑按钮是否禁用，只有当且仅当选择一条记录的时候才可编辑
      oneMore: true, //  工具栏删除按钮是否禁用，当选中条数为0的时候禁用
      importUrl: `api/v1/dept/sysrDept/importExcel`,
      tplUrl: `api/v1/dept/sysrDept/excelTemplate`,
      exportUrl: `api/v1/dept/sysrDept/exportExcel`,
      gridData: [],
      tableToolbar: {
        id: 'vue.dept.sysrDeptView-toolbar',
        custom: true,
        slots: {
          buttons: 'toolbar_btns'
        },
        zoom: true, // 最大化按钮
        // 列宽操作记录
        resizable: {
          storage: true
        },
        // 列操作记录
        setting: {
          storage: true
        }
      },
      columns: [
        { type: 'checkbox', width: 40, fixed: 'left', align: 'center' },
        { title: 'ec.table.name', field: 'name', treeNode: true, fixed: 'left', minWidth: 180, showOverflow: true },
        { title: 'ec.table.code', field: 'code', minWidth: 180, showOverflow: true },
        { title: 'ec.table.fullName', field: 'fullName', minWidth: 240, showOverflow: true },
        { title: 'ec.table.shortName', field: 'shortName', minWidth: 240, showOverflow: true },
        { title: 'ec.table.sort', field: 'sortNum', minWidth: 180, showOverflow: true, slots: { default: 'default_sortNum' }},
        { title: 'ec.table.enableStatus', field: 'status', minWidth: 180, showOverflow: true, slots: { default: 'default_status' }},
        // { title: 'ec.dept.legal', field: 'deptLegal', minWidth: 180, showOverflow: true, slots: { default: 'deptLegal' }},
        { title: 'ec.dept.phone1', field: 'telphone1', minWidth: 180, showOverflow: true },
        { title: 'ec.dept.phone2', field: 'telphone2', minWidth: 180, showOverflow: true },
        { title: 'ec.dept.address', field: 'address', minWidth: 180, showOverflow: true },
        { title: 'ec.table.remarks', key: 'remark', field: 'remark', minWidth: 100, showOverflow: true },
        { title: 'ec.table.actions', minWidth: 150, fixed: 'right', align: 'center', slots: { default: 'operation' }}
      ],
      queryParams: {
        tenantId: '',
        appId: null,
        code:'',
        shortName:''
      }
    }
  },
  created() {
    this.getTreeData()
  },
  mounted() {
    this.$watch(this.$refs.vxe.getCheckboxRecords, (newValue, oldValue) => {
      this.selections = newValue
      this.onlyOne = this.selections.length === 1
      this.oneMore = this.selections.length > 0
    })
  },
  methods: {
    async updateSort(row) {
      try {
        this.loading = true
        const { message } = await updateSort(row.id, { sortNum: row.sortNum })
        this.$notify.success(message)
        await this.getTreeData()
      } finally {
        this.loading = false
      }
    },
    async updateStatus(row) {
      try {
        this.loading = true
        const { message } = await updateStatus(row.id, { status: row.status })
        this.$notify.success(message)
        await this.getTreeData()
      } finally {
        this.loading = false
      }
    },
    async getTreeData() {
      let expands
      this.$nextTick(() => {
        expands = this.$refs.vxe.getTreeExpandRecords().map(item => item.id)
      })
      try {
        this.loading = true
        const { data } = await getTreeData({}, this.queryParams)
        this.gridData = data
        this.$nextTick(() => {
          const result = []
          treeEach(this.gridData, node => {
            if (expands.includes(node.id)) {
              result.push(node)
            }
          })
          this.$refs.vxe.setTreeExpand(result, true)
        })
      } finally {
        this.loading = false
      }
    },
    add(parent) {
      this.$refs.deptDetail.init('add', this.queryParams.tenantId, this.queryParams.appId, {}, parent)
    },
    edit(row) {
      const record = row || this.selections[0]
      this.$refs.deptDetail.init('edit', this.queryParams.tenantId, this.queryParams.appId, record)
    },
    view(row) {
      const record = row || this.selections[0]
      this.$refs.deptDetail.init('view',this.queryParams.tenantId, this.queryParams.appId, record)
    },
    deleteByIds(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.getTreeData()
          this.$notify.success(this.$t('ec.message.delSuccess'))
        } finally {
          this.loading = false
        }
      })
    },
    async toggleTree() {
      this.expand = !this.expand
      this.loading = true
      await this.$refs.vxe.setAllTreeExpand(this.expand)
      this.loading = false
    },
    handleReset() {
      Object.assign(this.$data.queryParams, this.$options.data().queryParams)
      this.getTreeData()
    },
    async exportExcel() {
      this.loading = true
      await download({ url: this.exportUrl, method: 'post', data: this.queryParams })
      this.loading = false
    }
  }
}
</script>

<style scoped>

</style>
