<template>
  <div class="app-container">
    <!-- 门类列表 -->
    <el-row class="container-main">
      <el-col class="curd-in-out" :xs="10" :sm="8" :md="5" :lg="6" :xl="5">
        <div :class="['container-left', !isRecycle?'left-tree-item':'']">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
          <div class="tree-title">档案门类</div>
          <!--档案门类树状结构-->
          <div class="tree-scroll">
            <el-tree ref="archivesTree" v-loading="crud.loading" :data="crud.data" :props="defaultProps" node-key="id" :expand-on-click-node="false" highlight-current @node-click="handleNodeClick" />
          </div>
        </div>
        <div v-if="!isRecycle" class="container-left left-tree-item">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
          <div class="tree-title">智能分类</div>
          <!--智能分类树状结构-->
          <div class="tree-scroll">
            <el-tree ref="smartTree" v-loading="intellClassifyLoading" :data="intellClassifyTree" :props="intellDefaultProps" node-key="id" :expand-on-click-node="false" highlight-current @node-click="handleIntellNodeClick" />
          </div>
        </div>
      </el-col>

      <!-- 档案管理列表 -->
      <el-col class="archives-right-list" :xs="14" :sm="18" :md="19" :lg="18" :xl="19">
        <div v-if="selectedCategory.isType !== 1 && !isRecycle" :class="['archives-top', {'archives-fixed-top': selectedCategory.isType===2 || selectedCategory.isType===4 }]">
          <el-checkbox v-model="fixedStatusBar">隐藏固定状态栏</el-checkbox>
        </div>
        <!-- 项目 -->
        <archivesProject
          v-if="selectedCategory.isType === 2"
          ref="project"
          :selected-category="selectedCategory"
          :smart-query="smartQuery"
          @getAjInProjectBtnState="getAjInProjectBtnState"
          @getProjectSelections="getProjectSelections"
        />
        <!-- 案卷 -->
        <archivesAnjuan
          v-if="selectedCategory.isType === 2 || selectedCategory.isType === 3|| selectedCategory.isType === 5"
          ref="anjuan"
          :selected-category="selectedCategory"
          :is-project="isProject"
          :project-selection="projectSelection"
          :fixed-status-bar="fixedStatusBar"
          :archive-year="archiveYear"
          :smart-query="smartQuery"
          @getJnInAjBtnState="getJnInAjBtnState"
          @getSelections="getSelections"
        />
        <!-- 卷内 -->
        <archivesJuannei
          v-if="selectedCategory.isType === 2 || selectedCategory.isType === 3 || selectedCategory.isType === 4"
          ref="file"
          :is-anjuan="isAnjuan"
          :anjuan-selection="anjuanSelection"
          :selected-category="selectedCategory"
          :fixed-status-bar="fixedStatusBar"
          :smart-query="smartQuery"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getDicts } from '@/api/archivesConfig/dict'
import archivesProject from './module/archivesProject/index'
import archivesAnjuan from './module/archivesAnjuan/index'
import archivesJuannei from './module/archivesJuannei/index'
import crudCategory from '@/api/category/category'
import CRUD, { presenter } from '@crud/crud'

export default {
  name: 'ArchivesList',
  components: { archivesProject, archivesAnjuan, archivesJuannei },
  cruds() {
    return [
      CRUD({
        title: '档案', url: 'api/archives-type/menu',
        crudMethod: { ...crudCategory }
      })
    ]
  },
  provide() {
    return {
      recycleMain: this
    }
  },
  mixins: [presenter()],
  props: {
    isdel: {
      type: Boolean,
      default: false
    },
    isRecycle: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      intellClassifyTree: [],
      defaultProps: {
        children: 'children',
        label: 'cnName'
      },
      intellDefaultProps: {
        children: 'childMenus',
        label: 'dicName'
      },
      selectedCategory: {},
      isAnjuan: true,
      isProject: true,
      anjuanSelection: {},
      projectSelection: {},
      intellClassifyLoading: false,
      fixedStatusBar: false,
      archiveYear: null,
      smartQuery: {
        'archiveYear': null,
        'department': null,
        'retention': null,
        'securityClass': null,
        'organizationMatter': null
      },
      treeCurrentNode: null
    }
  },
  watch: {
    isdel: function(newValue, oldValue) {
    },
    isRecycle: function(newValue, oldValue) {
    }
  },
  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('currentArchivesKey')) {
        currentKey = JSON.parse(localStorage.getItem('currentArchivesKey'))
        // 删除门类节点后
        if (this.$refs.archivesTree.getCurrentKey(currentKey.id) == null) {
          localStorage.removeItem('currentArchivesKey')
        }
        // 缓存的门类节点判断
        if (currentKey.isType === 1) {
          if (currentKey.children.length !== 0) {
            currentKey = this.findNode(currentKey.children, (node) => {
              return node.isType !== 1
            })
          }
        }
      } 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]
        }
      }
      if (currentKey.id) {
        // 设置某个节点的当前选中状态
        this.$refs.archivesTree.setCurrentKey(currentKey.id)
        this.$nextTick(() => {
          // 设置某个节点的父级展开
          const selectedKey = this.$refs.archivesTree.getCurrentNode()
          if (this.$refs.archivesTree.getNode(selectedKey) && this.$refs.archivesTree.getNode(selectedKey).parent) {
            this.expandParents(this.$refs.archivesTree.getNode(selectedKey).parent)
          }
          // 选中节点的门类详情
          this.handleNodeClick(selectedKey)
        })
      }
      this.getIntellClassify()
    },
    getIntellClassify() {
      getDicts().then(data => {
        if (data) {
          this.intellClassifyTree = data.filter(item => {
            return item.dicCode === 'Search_MJ' || item.dicCode === 'Search_BGQX' || item.dicCode === 'Search_JGWT' || item.dicCode === 'Search_BM'
          })
        }
      })
    },
    // 选中字典后，设置字典详情数据
    handleNodeClick(val) {
      if (val) {
        // 初始化智能分类的操作
        if (this.$refs.smartTree) {
          this.treeCurrentNode = null
          const smartTreeList = this.intellClassifyTree
          this.smartQuery = {
            'archiveYear': null,
            'department': null,
            'retention': null,
            'securityClass': null,
            'organizationMatter': null
          }
          this.$refs.smartTree.setCurrentKey(null)
          smartTreeList.forEach((item, index) => {
            this.$refs.smartTree.store.nodesMap[smartTreeList[index].id].expanded = false
          })
        }
        this.crud.selectionChangeHandler([val])
        this.selectedCategory = val
        this.handleTableList()
        // 缓存当前的选中的
        localStorage.setItem('currentArchivesKey', JSON.stringify(val))
      }
    },
    // 判断案卷内的卷内-新增btn-状态 中转站
    getJnInAjBtnState(data) {
      this.isAnjuan = data
    },
    getAjInProjectBtnState(data) {
      this.isProject = data
    },
    getProjectSelections(data, selectData) {
      this.smartQuery = {
        'archiveYear': null,
        'department': null,
        'retention': null,
        'securityClass': null,
        'organizationMatter': null
      }
      if ((selectData && selectData.length > 1) || (selectData && selectData.length === 0)) {
        this.projectSelection = {}
        this.$nextTick(() => {
          if (this.$refs.anjuan) {
            this.$refs.anjuan.anjuanData = []
          }
        })
      } else if (selectData && selectData.length === 1) {
        this.projectSelection = selectData[0]
        this.$nextTick(() => {
          if (this.$refs.anjuan) {
            this.$refs.anjuan.getTableList()
          }
        })
      } else {
        this.projectSelection = data
        this.$nextTick(() => {
          if (this.$refs.anjuan) {
            this.$refs.anjuan.getTableList()
          }
        })
      }
    },
    getSelections(data, selectData) {
      this.smartQuery = {
        'archiveYear': null,
        'department': null,
        'retention': null,
        'securityClass': null,
        'organizationMatter': null
      }
      if ((selectData && selectData.length > 1) || (selectData && selectData.length === 0)) {
        this.anjuanSelection = {}
        this.$nextTick(() => {
          if (this.$refs.file) {
            this.$refs.file.junneiData = []
          }
        })
      } else if (selectData && selectData.length === 1) {
        this.anjuanSelection = selectData[0]
        this.$nextTick(() => {
          if (this.$refs.file) {
            this.$refs.file.getTableList()
          }
        })
      } else {
        this.anjuanSelection = data
        this.$nextTick(() => {
          if (this.$refs.file) {
            this.$refs.file.getTableList()
          }
        })
      }
    },
    getYear(obj) {
      if (this.$refs.smartTree) {
        this.intellClassifyLoading = true
        setTimeout(() => {
          if (this.intellClassifyTree[0].dicName === '年度') {
            this.intellClassifyTree = this.intellClassifyTree.slice(1)
          }
          if (this.$refs[obj].yearGroup.length !== 0) {
            const newYearArr = this.$refs[obj].yearGroup.map((item, index) => {
              const json = {}
              json.id = index
              json.dicName = item
              json.childMenus = []
              json.ifChild = true
              return json
            })
            this.intellClassifyTree.unshift({ id: -1, dicName: '年度', dicCode: 'Search_year', childMenus: newYearArr })
          }
          this.intellClassifyLoading = false
        }, 500)
      }
    },
    // 智能分类
    handleIntellNodeClick(data, node, ele) {
      if (data) {
        if (node.childNodes.length === 0) {
          const selectedKey = this.$refs.smartTree.getCurrentNode()
          const selectedParentVal = this.$refs.smartTree.getNode(selectedKey).parent.data.dicCode
          this.treeCurrentNode = ele.$el
          // if (data.ifChild) {
          //   this.treeCurrentNode = ele.$el
          //   const eles = document.querySelectorAll('.el-tree-node__children .el-tree-node.is-focusable')
          //   for (let i = 0; i < eles.length; i++) {
          //     eles[i].classList.remove('is-current')
          //   }
          //   this.treeCurrentNode.classList.add('is-current')
          // } else {
          //   ele.$el.classList.remove('is-current')
          //   console.log(this.treeCurrentNode)
          //   if (this.treeCurrentNode) {
          //     this.treeCurrentNode.classList.add('is-current')
          //   }
          // }
          if (ele.$el.classList.contains('is-current')) {
            this.treeCurrentNode.classList.remove('is-current')
            this.smartQuery = {
              'archiveYear': null,
              'department': null,
              'retention': null,
              'securityClass': null,
              'organizationMatter': null
            }
          } else {
            this.treeCurrentNode.classList.add('is-current')
            switch (selectedParentVal) {
              case 'Search_year':
                if (selectedKey.dicCode !== 'Search_year') {
                  this.smartQuery.archiveYear = selectedKey.dicName
                }
                break
              case 'Search_BM':
                if (selectedKey.dicCode !== 'Search_BM') {
                  this.smartQuery.department = selectedKey.dicName
                }
                break
              case 'Search_BGQX':
                if (selectedKey.dicCode !== 'Search_BGQX') {
                  this.smartQuery.retention = selectedKey.dicName
                }
                break
              case 'Search_MJ':
                if (selectedKey.dicCode !== 'Search_MJ') {
                  this.smartQuery.securityClass = selectedKey.dicName
                }
                break
              default:
                if (selectedKey.dicCode !== 'Search_JGWT') {
                  this.smartQuery.organizationMatter = selectedKey.dicName
                }
            }
          }
          this.handleTableList()
        }
      }
    },
    handleTableList() {
      if (this.selectedCategory.isType === 2) {
        this.$nextTick(() => {
          this.$refs.anjuan.anjuanData = []
          this.$refs.file.junneiData = []
          if (this.selectedCategory.children.length !== 0) {
            this.$refs.anjuan.getTableDisplayFields()
            this.$refs.file.getTableDisplayFields()
          }
          this.$refs.project.getTableList()
          if (!this.treeCurrentNode) {
            this.getYear('project')
          }
        })
      } else if (this.selectedCategory.isType === 3) {
        this.$nextTick(() => {
          this.$refs.anjuan.anjuanData = []
          this.$refs.file.junneiData = []
          this.$refs.anjuan.getTableDisplayFields()
          if (this.selectedCategory.children.length !== 0) {
            this.$refs.file.getTableDisplayFields()
          }
          this.$refs.anjuan.getTableList()
          if (!this.treeCurrentNode) {
            this.getYear('anjuan')
          }
        })
      } else if (this.selectedCategory.isType === 4) {
        this.$nextTick(() => {
          this.$refs.file.junneiData = []
          this.$refs.file.getTableDisplayFields()
          this.$refs.file.getTableList()
          if (!this.treeCurrentNode) {
            this.getYear('file')
          }
        })
      } else if (this.selectedCategory.isType === 5) {
        this.$nextTick(() => {
          this.$refs.anjuan.anjuanData = []
          this.$refs.anjuan.getTableDisplayFields()
          this.$refs.anjuan.getTableList()
          if (!this.treeCurrentNode) {
            this.getYear('anjuan')
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/archives-manage.scss";
.tree-scroll{
  height: calc(100vh - 630px);
  overflow-y: scroll;
  overflow-x: hidden;
}
</style>
