<template>
  <div class="app-container">
    <el-form ref="searchForm" :model="queryParams" inline label-width="100px">
      <el-form-item v-if="superAdmin" :label="$t('ec.user.tenant')" prop="tenantId">
        <ec-tenant-by-pro v-model="queryParams.tenantId" @change="getTreeData" />
      </el-form-item>
      <el-form-item :label="$t('ec.table.name')" prop="name">
        <el-input v-model="queryParams.name" 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="['baseOrg:add']" type="primary" @click="add()">{{ $t('ec.table.add') }}</el-button>
        <el-button v-permission="['baseOrg:edit']" :disabled="!onlyOne" type="warning" @click="edit()">{{ $t('ec.table.edit') }}</el-button>
        <el-button v-permission="['baseOrg:delete']" type="danger" :disabled="!oneMore" @click="deleteByIds()">{{ $t('ec.table.delete') }}</el-button>
        <el-button v-permission="['baseOrg:import']" type="primary" @click="importVisible = true">{{ $t('ec.table.import') }}</el-button>
        <el-button v-permission="['baseOrg:export']" type="success" @click="exportExcel">{{ $t('ec.table.export') }}</el-button>
      </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:org_operation="{ row }">
        <el-button v-if="!/row_/.test(row.id)" v-permission="['baseOrg:edit']" type="text" @click="edit(row)">{{ $t('ec.table.edit') }}</el-button>
        <el-button v-if="!/row_/.test(row.id)" v-permission="['baseOrg:delete']" type="text" class="text-red-color" @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.import')"
      :visible="importVisible"
      :upload-params="{ isNewPk: false, 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="baseOrgDetail" @refreshData="getTreeData" />
    <org-detail ref="orgDetail" @refreshData="getTreeData" />
  </div>
</template>

<script>
import mixin from 'ecip-web/utils/common-mixin'
import { getTreeData, removeByIds as deleteByIds } from 'ecip-web/api/vue/org/baseOrgApi'
import Detail from './components/detail'
import OrgDetail from './components/orgDetail'
import { treeEach } from 'ecip-web/utils/tableUtil'
// import { download } from 'ecip-web/utils'

export default {
  name: 'VueOrgBaseOrgView',
  components: { Detail, OrgDetail },
  mixins: [...mixin],
  data() {
    return {
      expand: false,
      loading: false,
      importVisible: false,
      checkStrictly: true,
      onlyOne: true, // 工具栏编辑按钮是否禁用，只有当且仅当选择一条记录的时候才可编辑
      oneMore: true, //  工具栏删除按钮是否禁用，当选中条数为0的时候禁用
      // importUrl: `api/v1/base/baseOrg/importExcel`,
      // tplUrl: `api/v1/base/baseOrg/excelTemplate`,
      // exportUrl: `api/v1/base/baseOrg/exportExcel`,
      gridData: [],
      selections: [],
      tableToolbar: {
        id: 'vue.org.baseOrgView-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' },
        { title: 'ec.dashboard.people', field: 'userNum', width: 100 },
        { title: '收费路段数', field: 'sectionNum', width: 100 },
        { title: '收费站数', field: 'stationNum', width: 100 },
        { title: 'ETC门架数', field: 'gantryNum', width: 100 },
        { title: '位置点数', field: 'locationNum', width: 100 },
        { title: 'ec.table.actions', width: 150, fixed: 'right', align: 'center', slots: { default: 'org_operation' }}
      ],
      queryParams: {
        tenantId: '1249628559274672128',
        name: ''
      }
    }
  },
  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.getTreeData()
  },
  methods: {
    async getTreeData() {
      this.selections = []
      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.baseOrgDetail.init('add', this.queryParams.tenantId, {}, parent)
      this.$refs.orgDetail.init('add', this.queryParams.tenantId, {}, parent)
    },
    edit(row) {
      const record = row || this.selections[0]
      this.$refs.baseOrgDetail.init('edit', this.queryParams.tenantId, 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 exportExcel() {
    //   this.loading = true
    //   await download({ url: this.exportUrl, method: 'post', data: this.queryParams })
    //   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()
    }
  }
}
</script>

<style scoped>

</style>
