<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 !== 1 || 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' || crud.selections[0].isType === 3" @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' ) || crud.selections[0].isType === 3" @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="iconArch">
                  {{ data.cnName }}
                </span>
                <span v-if="data.isType === 3" class="iconFile">
                  {{ data.cnName }}
                </span>
              </span>
            </el-tree>
          </div>
        </div>
      </div>
      <!-- 门类管理tab -->
      <div class="elect-cont-right">
        <div class="container-right tab-content">
          <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 === 3 && selectedCategory.cnName !== '电子原文表'" :class="{'active-tab-nav': activeIndex == 1}" @click="changeActiveTab(1)">门类字段管理<i /></li>
            <li v-if="selectedCategory.isType && selectedCategory.isType === 3 && selectedCategory.cnName !== '电子原文表'" :class="{'active-tab-nav': activeIndex == 2}" @click="changeActiveTab(2)">著录界面管理<i /></li>
            <li v-if="selectedCategory.isType && selectedCategory.isType === 3 && selectedCategory.cnName !== '电子原文表'" :class="{'active-tab-nav': activeIndex == 3}" @click="changeActiveTab(3)">列表界面浏览设置<i /></li>
            <li v-if="selectedCategory.isType && selectedCategory.isType === 3 && selectedCategory.cnName !== '电子原文表'" :class="{'active-tab-nav': activeIndex == 4}" @click="changeActiveTab(4)">浏览排序规则设置<i /></li>
            <li v-if="selectedCategory.isType && selectedCategory.isType === 3 && selectedCategory.cnName !== '电子原文表'" :class="{'active-tab-nav': activeIndex == 5}" @click="changeActiveTab(5)">档号规则设置<i /></li>
            <li v-if="selectedCategory.isType && selectedCategory.isType !== 1 && selectedCategory.isType !== 3" :class="{'active-tab-nav': activeIndex == 6}" @click="changeActiveTab(6)">归档章设置<i /></li>
            <li v-if="selectedCategory.isType && selectedCategory.isType !== 1 && selectedCategory.isType !== 3" :class="{'active-tab-nav': activeIndex == 7}" @click="changeActiveTab(7)">公共筛选<i /></li>
            <li v-if="selectedCategory.isType && selectedCategory.isType !== 1 && selectedCategory.isType !== 3" :class="{'active-tab-nav': activeIndex == 8}" @click="changeActiveTab(8)">流程管理<i /></li>
            <!-- 最右侧装饰img -->
            <span class="tab-right-img" />
          </ul>
          <component :is="comName" :selected-category="selectedCategory" />
        </div>
      </div>
      <!--修改新增表单组件-->
      <eForm ref="eform" :selected-category="selectedCategory" />
      <el-dialog class="tip-dialog" title="提示" :visible.sync="deleteVisible" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :before-close="handleClose">
        <div class="setting-dialog">
          <div class="tip-content">
            <p class="tipMsg">此操作将删除当前所选门类项及其子集</p>
            <span>你是否还要继续?</span>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="deleteVisible = false">取消</el-button>
            <el-button type="primary" @click.native="handleConfirm">确定</el-button>
          </div>
        </div>
      </el-dialog>
      <el-dialog class="tip-dialog" title="确认删除" :visible.sync="reconfirmDeleteVisible" :before-close="handleClose" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body>
        <div class="setting-dialog">
          <div class="tip-content">
            <p class="tipMsg">删除后，会永久清除此门类的相关设置及报表，请谨慎操作！</p>
            <span>提示：为确保档案安全，必须先手工删除此门类的所有档案数据。</span>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="reconfirmDeleteVisible = false">取消</el-button>
            <el-button type="primary" @click.native="handleReconfirm">确定</el-button>
          </div>
        </div>
      </el-dialog>
      <!--排序对话框组件-->
      <sortDialog ref="sort" @treeNodeSort="treeNodeSort" />
    </div>
  </div>
</template>

<script>
import crudCategory from '@/api/system/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 archiveSealSetting from './archiveSealSetting/index'
import publicScreening from './publicScreening/index'
import processManage from './processManage/index'
import crudOperation from '@crud/CRUD.operation'
import Vue from 'vue'

export default {
  name: 'ArchivesCategory',
  components: { crudOperation, eForm, sortDialog, baseInfo, fieldManage, descriptionPreview, listBrowsing, orderingRule, fileNoFormat, archiveSealSetting, publicScreening, processManage },
  cruds() {
    return [
      CRUD({
        title: '门类', url: 'api/category/menu',
        crudMethod: { ...crudCategory },
        optShow: {
          add: false,
          edit: false,
          del: false,
          download: false,
          group: false
        }
      })
    ]
  },
  mixins: [presenter(), header()],
  provide() {
    return {
      parentsData: this
    }
  },
  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'
      } else if (this.activeIndex === 6) {
        return 'archiveSealSetting'
      } else if (this.activeIndex === 7) {
        return 'publicScreening'
      } else if (this.activeIndex === 8) {
        return 'processManage'
      }
      return 'baseInfo'
    }
  },
  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]() {
      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.pid !== '0') {
          Vue.set(this.selectedCategory, 'parentName', this.$refs.tree.getNode(val.pid).data.cnName)
        }
        this.changeActiveTab(0)
        // 缓存当前的选中的
        localStorage.setItem('currentCategoryKey', 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
        }
        if (localStorage.getItem('categoryTabIndex')) {
          this.$nextTick(() => {
            this.activeIndex = Number(localStorage.getItem('categoryTabIndex'))
            localStorage.removeItem('categoryTabIndex')
          })
        }
      }
    },
    // 新增 - 判断当前节点类型，卷内/文件不可新建
    [CRUD.HOOK.beforeToAdd](crud, form, btn) {
      const isCanAddKey = JSON.parse(localStorage.getItem('currentCategoryKey'))
      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('currentCategoryKey', JSON.stringify(addedCategory))
      }
    },
    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
      setTimeout(() => {
        this.reconfirmDeleteVisible = true
      }, 300)
    },
    handleReconfirm() {
      this.reconfirmDeleteVisible = false
      this.crud.delAllLoading = true
      this.crud.doDelete(this.deleteData).then((res) => {
        // 清空缓存的门类节点
        localStorage.removeItem('currentCategoryKey')
      })
    },
    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>
.tree-scroll{
  font-size: 14px;
}
</style>
