<template>
  <div class="app-container">
    <!--修改新增表单组件-->
    <eForm ref="eform" :selected-category="selectedCategory" />
    <el-dialog title="确认删除" :visible.sync="deleteVisible" :before-close="handleClose">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <p><span style="color:#fff;">确认删除当前门类？</span></p>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click.native="handleConfirm">确定</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="确认删除" :visible.sync="reconfirmDeleteVisible" :before-close="handleClose">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <div class="dialog-delt">
          <p><span>删除后，会永久清除此门类的相关设置及报表，请谨慎操作！</span></p>
          <p class="delt-tip"><span>提示：为确保档案安全，必须先手工删除此门类的所有档案数据。</span></p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click.native="handleReconfirm">确定</el-button>
        </div>
      </div>
    </el-dialog>
    <!--排序对话框组件-->
    <sortDialog ref="sort" @treeNodeSort="treeNodeSort" />
    <!-- 门类列表 -->
    <el-row class="container-main" :gutter="20">
      <el-col class="container-left curd-in-out" :xs="10" :sm="8" :md="5" :lg="6" :xl="5">
        <span class="right-top-line" />
        <span class="left-bottom-line" />
        <crudOperation :permission="permission">
          <template v-slot:left>
            <el-button v-permission="permission.add" size="mini" icon="el-icon-plus" :disabled="crud.selections.length === 0" @click="crud.toAdd">
              新增
            </el-button>
          </template>
          <template v-slot:right>
            <el-button v-permission="permission.del" icon="el-icon-delete" size="mini" :loading="crud.delAllLoading" :disabled="crud.selections.length === 0" @click="toDelete(crud.selections)">删除</el-button>
            <el-button v-permission="permission.sort" icon="el-icon-sort" size="mini" :loading="sortLoading" :disabled="brotherNodeNum.length <= 1" @click="toSort(crud.selections)">排序</el-button>
          </template>
        </crudOperation>
        <!--门类树状结构-->
        <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" />
      </el-col>
      <!-- 门类管理tab -->
      <el-col class="container-right tab-content" :xs="14" :sm="18" :md="19" :lg="18" :xl="19">
        <span class="right-top-line" />
        <span class="left-bottom-line" />
        <ul class="tab-nav">
          <li :class="{'active-tab-nav': activeIndex == 0}" @click="changeActiveTab(0)">基本信息<i /></li>
          <li v-if="selectedCategory.isType && selectedCategory.isType !== 1" :class="{'active-tab-nav': activeIndex == 1}" @click="changeActiveTab(1)">门类字段管理<i /></li>
          <li v-if="selectedCategory.isType && selectedCategory.isType !== 1" :class="{'active-tab-nav': activeIndex == 2}" @click="changeActiveTab(2)">著录界面管理<i /></li>
          <li v-if="selectedCategory.isType && selectedCategory.isType !== 1" :class="{'active-tab-nav': activeIndex == 3}" @click="changeActiveTab(3)">列表界面浏览设置<i /></li>
          <li v-if="selectedCategory.isType && selectedCategory.isType !== 1" :class="{'active-tab-nav': activeIndex == 4}" @click="changeActiveTab(4)">浏览排序规则设置<i /></li>
          <li v-if="selectedCategory.isType && selectedCategory.isType !== 1" :class="{'active-tab-nav': activeIndex == 5}" @click="changeActiveTab(5)">档号规则设置<i /></li>
          <!-- 最右侧装饰img -->
          <span class="tab-right-img" />
        </ul>
        <component :is="comName" :selected-category="selectedCategory" />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudCategory from '@/api/category/category'
import CRUD, { presenter, header } from '@crud/crud'
import eForm from './form'
import sortDialog from './sortDialog'
import baseInfo from './baseInfo/index'
import fieldManage from './fieldManage/index'
import descriptionPreview from './descriptionPreview/index'
import listBrowsing from './listBrowsing/index'
import orderingRule from './orderingRule/index'
import fileNoFormat from './fileNoFormat/index'
import crudOperation from '@crud/CRUD.operation'

export default {
  name: 'Category',
  components: { crudOperation, eForm, sortDialog, baseInfo, fieldManage, descriptionPreview, listBrowsing, orderingRule, fileNoFormat },
  cruds() {
    return [
      CRUD({
        title: '门类', url: 'api/archives-type/menu',
        crudMethod: { ...crudCategory },
        optShow: {
          add: false,
          edit: true,
          del: false,
          download: false,
          group: false
        }
      })
    ]
  },
  mixins: [presenter(), header()],
  data() {
    return {
      permission: {
        add: ['admin', 'category:add'],
        edit: ['admin', 'category:edit'],
        del: ['admin', 'category:del'],
        sort: ['admin', 'category:sort']
      },
      defaultProps: {
        children: 'children',
        label: 'cnName'
      },
      deleteVisible: false,
      reconfirmDeleteVisible: false,
      selectedCategory: {},
      deleteData: {},
      activeIndex: 0,
      sortLoading: false,
      brotherNodeNum: 0
      // sortTableData: []
    }
  },
  computed: {
    comName: function() {
      if (this.activeIndex === 0) {
        return 'baseInfo'
      } else if (this.activeIndex === 1) {
        return 'fieldManage'
      } else if (this.activeIndex === 2) {
        return 'descriptionPreview'
      } else if (this.activeIndex === 3) {
        return 'listBrowsing'
      } else if (this.activeIndex === 4) {
        return 'orderingRule'
      } else if (this.activeIndex === 5) {
        return 'fileNoFormat'
      }
      return 'baseInfo'
    }
    // ,
    // brotherNodeNum: function() {
    //   const selectedNode = this.$refs.tree.getCurrentNode()
    //   if (selectedNode && selectedNode.pid && this.$refs.tree.getNode(selectedNode.pid)) {
    //     return this.$refs.tree.getNode(selectedNode.pid).childNodes.length
    //   } else {
    //     return 0
    //   }
    // }
  },
  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]() {
      let currentKey
      if (localStorage.getItem('currentCategoryKey')) {
        currentKey = JSON.parse(localStorage.getItem('currentCategoryKey'))
      } 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.selectedCategory = val
        if (val.isType === 1) {
          this.changeActiveTab(0)
        }
        // 缓存当前的选中的
        localStorage.setItem('currentCategoryKey', JSON.stringify(val))
        this.brotherNodeNum = val.pid
        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('currentCategoryKey'))
      if (isCanAddKey.isType === 4 || isCanAddKey.isType === 5) {
        this.$notify({
          title: '此门类下不可新建门类',
          type: 'error',
          duration: 2500
        })
        return false
      }
    },
    treeNodeSort(data) {
      this.$refs.tree.updateKeyChildren(data[0].pid, JSON.parse(JSON.stringify(data)))
    },
    toDelete(data) {
      this.deleteData = data
      this.deleteVisible = true
    },
    handleConfirm() {
      this.deleteVisible = false
      this.reconfirmDeleteVisible = true
    },
    handleReconfirm() {
      this.reconfirmDeleteVisible = false
      this.crud.delAllLoading = true
      this.crud.doDelete(this.deleteData)
    },
    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
    },
    changeActiveTab(data) {
      this.activeIndex = data
    }
  }
}
</script>

<style lang="scss" scoped>
.container-left,
.container-right {
  min-height: calc(100vh - 240px);
}
.curd-in-out {
  width: 330px;
  margin-top: 50px;
  .crud-opts {
    padding: 0 !important;
    margin-top: -50px;
    border-bottom: none;
  }
}
.tab-nav {
  margin-bottom: 0;
  li {
    padding: 0 10px;
    &:first-child {
      padding: 0 24px;
    }
  }
}
.container-left .el-tree {
  margin: 40px 0 20px 0;
}
</style>
