<template>
  <div class="app-container category-container">
    <!-- 门类列表 -->
    <div class="container-main">
      <div class="elect-cont-left">
        <div class="head-container">
          <crudOperation :permission="permission">
            <template v-slot:left>
              <!-- crud.selections.length === 0 || crud.selections[0].isType === 2 || crud.selections[0].isType === 3 || crud.selections[0].isType === 5 -->
              <el-button v-permission="permission.add" size="mini" :disabled="crud.selections.length === 0 || crud.selections[0].isType === 3" @click="crud.toAdd">
                <i class="iconfont icon-xinzeng" />
                新增
              </el-button>
              <el-button v-permission="permission.edit" size="mini" :disabled="crud.selections.length !== 1 || crud.selections[0].pid === '0'" @click="crud.toEdit(crud.selections[0])">
                <i class="iconfont icon-bianji" />
                编辑
              </el-button>
            </template>
            <template v-slot:right>
              <el-button v-permission="permission.del" size="mini" :loading="crud.delAllLoading" :disabled="crud.selections.length === 0 || (crud.selections.length === 1 && crud.selections[0].pid === '0' )" @click="toDelete(crud.selections)">
                <i class="iconfont icon-shanchu" />
                删除
              </el-button>
              <el-button v-permission="permission.sort" icon="el-icon-sort" size="mini" :loading="sortLoading" :disabled="brotherNodeNum <= 1 || crud.selections[0].pid === '0' " @click="toSort(crud.selections)">排序</el-button>
            </template>
          </crudOperation>
        </div>
        <div class="container-left">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
          <!--门类树状结构-->
          <div class="tree-scroll">
            <el-tree ref="tree" v-loading="crud.loading" :data="crud.data" :props="defaultProps" node-key="id" :expand-on-click-node="false" highlight-current @node-click="handleNodeClick">
              <span slot-scope="{ node, data }" class="custom-tree-node">
                <span v-if="data.isType === 1" class="iconFolder">
                  {{ data.cnName }}
                </span>
                <span v-if="data.isType === 2" class="iconStoreHouse">
                  {{ data.cnName }}
                </span>
                <span v-if="data.isType === 3" class="iconArea">
                  {{ data.cnName }}
                </span>
              </span>
            </el-tree>
          </div>
        </div>
      </div>
      <!-- 门类管理tab -->
      <div class="elect-cont-right">
        <div class="container-right">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
        </div>
      </div>
      <!--修改新增表单组件-->
      <eForm ref="eform" :selected-store="selectedStore" />
      <!--排序对话框组件-->
      <!-- <sortDialog ref="sort" @treeNodeSort="treeNodeSort" /> -->
    </div>
  </div>
</template>

<script>
import crudCategory from '@/api/system/category/category'
import CRUD, { presenter, header } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation'
import eForm from './form'
import Vue from 'vue'
import dataJson from './data.json'

export default {
  name: 'DeviceManage',
  components: { crudOperation, eForm },
  cruds() {
    return [
      CRUD({
        title: '库房设备管理', url: 'api/category/menu',
        crudMethod: { ...crudCategory },
        optShow: {
          add: false,
          edit: false,
          del: false,
          download: false,
          group: false
        }
      })
    ]
  },
  mixins: [presenter(), header()],
  data() {
    return {
      permission: {
        add: ['admin', 'device:add'],
        edit: ['admin', 'device:edit'],
        del: ['admin', 'device:del'],
        sort: ['admin', 'device:sort']
      },
      defaultProps: {
        children: 'children',
        label: 'cnName'
      },
      deleteVisible: false,
      reconfirmDeleteVisible: false,
      selectedStore: {},
      deleteData: {},
      sortLoading: false,
      brotherNodeNum: 0,
      sortTableData: []
    }
  },
  created() {

  },
  methods: {
    // 逆归实现 获取指定元素
    findNode(tree, func) {
      for (const node of tree) {
        if (func(node)) return node
        if (node.children) {
          const res = this.findNode(node.children, func)
          if (res) return res
        }
      }
      return null
    },
    // 展开选中的父级
    expandParents(node) {
      node.expanded = true
      if (node.parent) {
        this.expandParents(node.parent)
      }
    },
    [CRUD.HOOK.afterRefresh]() {
      this.crud.data = dataJson.data
      let currentKey
      if (localStorage.getItem('currentStoreKey')) {
        currentKey = JSON.parse(localStorage.getItem('currentStoreKey'))
      } else {
        if (this.crud.data[0].isType === 1) {
          currentKey = this.findNode(this.crud.data[0].children, (node) => {
            return node.isType !== 1
          })
        } else {
          currentKey = this.crud.data[0]
        }
      }
      // 设置某个节点的当前选中状态
      this.$refs.tree.setCurrentKey(currentKey.id)
      this.$nextTick(() => {
        // 设置某个节点的父级展开
        const selectedKey = this.$refs.tree.getCurrentNode()
        if (this.$refs.tree.getNode(selectedKey) && this.$refs.tree.getNode(selectedKey).parent) {
          this.expandParents(this.$refs.tree.getNode(selectedKey).parent)
        }
        // 选中节点的门类详情
        this.handleNodeClick(selectedKey)
      })
    },
    // 选中门类后，设置门类详情数据
    handleNodeClick(val) {
      if (val) {
        this.crud.selectionChangeHandler([val])
        this.$refs.eform.pid = val.id
        this.selectedStore = val
        if (val.pid !== '0') {
          Vue.set(this.selectedStore, 'parentName', this.$refs.tree.getNode(val.pid).data.cnName)
        }
        // 缓存当前的选中的
        localStorage.setItem('currentStoreKey', JSON.stringify(val))
        if (this.$refs.tree.getNode(val.pid) && this.$refs.tree.getNode(val.pid).childNodes) {
          this.brotherNodeNum = this.$refs.tree.getNode(val.pid).childNodes.length
        }
      }
    },
    // 新增 - 判断当前节点类型，卷内/文件不可新建
    [CRUD.HOOK.beforeToAdd](crud, form, btn) {
      const isCanAddKey = JSON.parse(localStorage.getItem('currentStoreKey'))
      if (isCanAddKey.isType === 4 || isCanAddKey.isType === 5) {
        this.$message({
          message: '此门类下不可新建门类',
          type: 'error',
          duration: 2500
        })
        return false
      }
      this.$refs.eform.beforeToAdd()
    },
    // 新增/编辑后 - 新增后默认选中新增的库房
    [CRUD.HOOK.afterSubmit](crud, addedCategory) {
      if (addedCategory) {
        // 缓存当前的选中的
        localStorage.setItem('currentStoreKey', JSON.stringify(addedCategory))
      }
    },
    treeNodeSort(data) {
      this.$refs.tree.updateKeyChildren(data[0].pid, JSON.parse(JSON.stringify(data)))
    },
    // 删除门类
    toDelete(data) {
      this.deleteData = data
      this.$confirm('此操作将删除当前所选区域及其子集' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {

      }).catch(() => {
      })
    },
    handleClose(done) {
      this.deleteData = {}
      done()
    },
    toSort(data) {
      this.$refs.sort.sortTableData = this.$refs.tree.getNode(data[0].pid).data.children
      this.$refs.sort.sortVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-scroll{
  font-size: 14px;
}
</style>
