<template>
  <div class="app-container archives-container">
    <div class="container-main" style="justify-content: flex-start;">
      <div class="elect-cont-left">
        <div class="container-left">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
          <div class="arc-left-tree">
            <h3 class="arc-title arc-title-top">档案门类</h3>
            <div class="tree-scroll">
              <el-tree ref="categroyTree" v-loading="crud.loading" class="arc-tree arc-tree-01" :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">
                  <el-tooltip :content="node.label" placement="top" :enterable="false" effect="dark">
                    <span v-if="data.isType === 1 " class="iconFolder">
                      {{ data.cnName }}
                    </span>
                  </el-tooltip>
                  <el-tooltip :content="node.label" placement="top" :enterable="false" effect="dark">
                    <span v-if="data.isType === 2" class="iconArch">
                      {{ data.cnName }}
                    </span>
                  </el-tooltip>
                  <el-tooltip :content="node.label" placement="top" :enterable="false" effect="dark">
                    <span v-if="data.isType === 3" class="iconFile">
                      {{ data.cnName }}
                    </span>
                  </el-tooltip>
                </span>
              </el-tree>
            </div>
            <h3 class="arc-title arc-title-bottom">快速筛选</h3>
            <el-tree
              ref="classifyTree"
              v-loading="classifyLoading"
              class="arc-tree arc-tree-02"
              :data="classifyTree"
              :props="defaultClassifyProps"
              node-key="id"
              :expand-on-click-node="false"
              highlight-current
              @node-click="handleClassifyFilter"
            >
              <span slot-scope="{ node, data }" class="custom-tree-node">
                <span v-if="data.childDictionarys || data.fondsName" class="iconClassify">
                  {{ data.dictionaryName || data.fondsName }}
                </span>
                <span v-else class="iconClassify-child">
                  {{ data.dictionaryName }}
                </span>
              </span>
            </el-tree>
          </div>
        </div>
      </div>
      <!--用户数据-->
      <div v-if="storageCategory.isType !== 1" class="elect-cont-right">
        <div class="container-right tab-content">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
          <ul v-if="storageType==='out'" class="tab-nav">
            <li :class="{'active-tab-nav': activeIndex == 0}" @click="changeActiveTab(0)">待出库档案盒<i /></li>
            <li :class="{'active-tab-nav': activeIndex == 1}" @click="changeActiveTab(1)">待出库档案<i /></li>
            <!-- 最右侧装饰img -->
            <span class="tab-right-img" />
          </ul>
          <ul v-if="storageType==='log'" class="tab-nav">
            <li :class="{'active-tab-nav': activeIndex == 0}" @click="changeActiveTab(0)">档案盒记录<i /></li>
            <li :class="{'active-tab-nav': activeIndex == 1}" @click="changeActiveTab(1)">档案记录<i /></li>
            <!-- 最右侧装饰img -->
            <span class="tab-right-img" />
          </ul>
          <ul v-if="storageType==='in'" class="tab-nav">
            <li :class="{'active-tab-nav': activeIndex == 0}" @click="changeActiveTab(0)">待入库档案盒<i /></li>
            <li :class="{'active-tab-nav': activeIndex == 1}" @click="changeActiveTab(1)">待入库档案<i /></li>
            <!-- 最右侧装饰img -->
            <span class="tab-right-img" />
          </ul>
          <PendingInCase v-if="activeIndex == 0" :storage-category="storageCategory" :storage-type="storageType" />
          <div v-if="activeIndex == 1" style="padding: 0 20px;">
            <Project v-if="storageCategory.arrangeType === 3" ref="projectEle" :storage-category="storageCategory" :smart-query="smartQuery" :storage-type="storageType" @openAnjuan="handleOpenAnjuan" @myYearEvent="handleYearData" />
            <Anjuan v-if="storageCategory.arrangeType === 1 || storageCategory.arrangeType === 2 || storageCategory.arrangeType === 3" ref="anjuanEle" :storage-category="storageCategory" :smart-query="smartQuery" :storage-type="storageType" @openJuannei="handleOpenJuannei" @myYearEvent="handleYearData" />
            <Juannei v-if="storageCategory.arrangeType === 2 || storageCategory.arrangeType === 3" ref="juanneiEle" :storage-category="storageCategory" :smart-query="smartQuery" :storage-type="storageType" @openFile="handleOpenFile" />
            <File v-if="storageCategory.arrangeType === 1 || storageCategory.arrangeType === 2 || storageCategory.arrangeType === 3" ref="fileEle" :storage-category="storageCategory" :smart-query="smartQuery" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import crudCategory from '@/api/category/category'
import { FetchDictionaryTreeByCategoryId } from '@/api/system/dict'
import CRUD, { presenter, header } from '@crud/crud'
import PendingInCase from './pendingInCase/index'
import Project from './pendingInArchive/project/index'
import Anjuan from './pendingInArchive/anjuan/index'
import Juannei from './pendingInArchive/juannei/index'
import File from './pendingInArchive/file/index'

export default {
  name: 'InStorage',
  components: { PendingInCase, Project, Anjuan, Juannei, File },
  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
    }
  },
  props: {
    storageType: {
      type: String,
      default: 'in'
    }
  },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'cnName'
      },
      defaultClassifyProps: {
        children: 'childDictionarys' || null,
        label: 'dictionaryName' || 'fondsName'
      },
      storageCategory: {},
      smartQuery: {
        'retention': null, // 保管期限
        'security_class': null, // 密级
        'doc_type': null, // 文种
        'medium_type': null, // 载体类型
        'archive_year': null, // 年度
        'fonds_no': null // 全宗
      },
      yearChildData: '',
      parentsProjectId: null,
      parentsProjectRow: null,
      parentsAnjuanId: null,
      classifyTree: [],
      classifyLoading: false,
      activeIndex: 0
    }
  },
  computed: {
  },
  created() {
  },
  mounted() {
  },
  methods: {
    handleYearData(data) {
      this.yearChildData = data
      this.classifyLoading = true
      setTimeout(() => {
        if (this.classifyTree[0].dictionaryName === '年度') {
          this.classifyTree = this.classifyTree.slice(1)
        }
        if (this.yearChildData.length !== 0) {
          const newYearArr = this.yearChildData.map((item, index) => {
            const json = {}
            json.id = index
            json.dictionaryName = item
            json.childDictionarys = []
            return json
          })
          this.classifyTree.unshift({ id: -1, dictionaryName: '年度', dictionaryCode: 'archive_year', childDictionarys: newYearArr })
        }
        this.classifyLoading = false
      }, 500)
    },
    filterData(data) {
      return data.filter(node => {
        if (node.children && node.children.length > 0) {
          node.children = this.filterData(node.children) // 递归处理子节点
        }
        return node.isType !== 3 // 过滤掉isType为3的节点
      })
    },
    // 逆归实现 获取指定元素
    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 = this.filterData(this.crud.data)
      this.$nextTick(() => {
        let currentKey
        if (localStorage.getItem('storageCategoryKey')) {
          currentKey = JSON.parse(localStorage.getItem('storageCategoryKey'))
          // 删除门类节点后
          if (this.$refs.categroyTree.getCurrentKey(currentKey.id) == null) {
            localStorage.removeItem('storageCategoryKey')
          }
          // 缓存的门类节点判断
          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.categroyTree.setCurrentKey(currentKey.id)
          this.$nextTick(() => {
          // 设置某个节点的父级展开
            const selectedKey = this.$refs.categroyTree.getCurrentNode()
            if (this.$refs.categroyTree.getNode(selectedKey) && this.$refs.categroyTree.getNode(selectedKey).parent) {
              this.expandParents(this.$refs.categroyTree.getNode(selectedKey).parent)
            }
            // 选中节点的门类详情
            this.handleNodeClick(selectedKey)
          })
        }
      })
    },
    handleNodeClick(val) {
      this.smartQuery = {
        'retention': null, // 保管期限
        'security_class': null, // 密级
        'doc_type': null, // 文种
        'medium_type': null, // 载体类型
        'archive_year': null, // 年度
        'fonds_no': null // 全宗
      }
      // 缓存当前的选中的
      localStorage.setItem('storageCategoryKey', JSON.stringify(val))
      this.storageCategory = val

      if (this.storageCategory.isType !== 1) {
        this.getDictionaryTreeByCategoryId(val.id)
      } else {
        this.classifyTree = []
      }
      this.$nextTick(() => {
        this.handlePageList()
      })
    },
    handlePageList(isQuickFilter) {
      // if (this.storageCategory.arrangeType === 3) {
      //   const tablistEle = this.$refs.projectEle
      //   // 项目下
      //   if (isQuickFilter) {
      //     tablistEle.$refs.collectHeaderRef.getInitArchivesClass()
      //     tablistEle.getTableDisplayFieldsLoading = true
      //     tablistEle.getViewTableList(1, null, isQuickFilter)
      //   } else {
      //     this.$refs.projectEle.getCommonData(1)
      //   }
      // } else if (this.storageCategory.arrangeType === 2) {
      //   const tablistEle = this.$refs.anjuanEle.$refs.ajContent.$refs.tableList
      //   // 案卷下
      //   if (isQuickFilter) {
      //     tablistEle.$refs.collectHeaderRef.getInitArchivesClass()
      //     tablistEle.getTableDisplayFieldsLoading = true
      //     tablistEle.getViewTableList(2, null, isQuickFilter)
      //   } else {
      //     tablistEle.getCommonData(2)
      //   }
      // } else if (this.storageCategory.arrangeType === 1) {
      //   const tablistEle = this.$refs.anjuanEle.$refs.ajContent.$refs.tableList
      //   // 文件下
      //   if (isQuickFilter) {
      //     tablistEle.$refs.collectHeaderRef.getInitArchivesClass()
      //     tablistEle.getTableDisplayFieldsLoading = true
      //     tablistEle.getViewTableList(3, null, isQuickFilter)
      //   } else {
      //     tablistEle.getCommonData(3)
      //   }
      // }
      if (this.$refs.anjuanEle) {
        this.$refs.anjuanEle.anjuanDrawer = false
      }
      if (this.$refs.juanneiEle) {
        this.$refs.juanneiEle.juanneiDrawer = false
      }
      if (this.$refs.fileEle) {
        this.$refs.fileEle.fileDrawer = false
      }
    },
    getDictionaryTreeByCategoryId(categoryId) {
      this.classifyLoading = true
      const params = {
        'categoryId': categoryId
      }
      FetchDictionaryTreeByCategoryId(params).then((res) => {
        let fonds
        if (res.fonds.length <= 1) {
          fonds = []
        } else {
          const parent = {}
          parent.id = 0
          parent.fondsName = '全宗'
          parent.childDictionarys = res.fonds
          fonds = parent
        }
        this.classifyTree = res.dictionarys.concat(fonds)
        this.classifyLoading = false
      }).catch(err => {
        console.log(err)
      })
    },
    handleClassifyFilter(data, node, ele) {
      this.smartQuery = {
        'retention': null, // 保管期限
        'security_class': null, // 密级
        'doc_type': null, // 文种
        'medium_type': null, // 载体类型
        'archive_year': null, // 年度
        'fonds_no': null // 全宗
      }
      if (data) {
        if (node.childNodes.length === 0) {
          const selectedKey = this.$refs.classifyTree.getCurrentNode()
          this.treeCurrentNode = ele.$el
          if (ele.$el.classList.contains('is-current')) {
            this.treeCurrentNode.classList.remove('is-current')
          } else {
            this.treeCurrentNode.classList.add('is-current')
            if (Object.keys(selectedKey).includes('fondsId')) {
              this.smartQuery.fonds_no = selectedKey.fondsNo
            } else {
              const selectedParentVal = this.$refs.classifyTree.getNode(selectedKey).parent.data.dictionaryCode
              switch (selectedParentVal) {
                case 'security_class':
                  if (selectedKey.dictionaryCode !== 'security_class') {
                    this.smartQuery.security_class = selectedKey.dictionaryName
                  }
                  break
                case 'retention':
                  if (selectedKey.dictionaryCode !== 'retention') {
                    this.smartQuery.retention = selectedKey.dictionaryName
                  }
                  break
                case 'doc_type':
                  if (selectedKey.dictionaryCode !== 'doc_type') {
                    this.smartQuery.doc_type = selectedKey.dictionaryName
                  }
                  break
                case 'medium_type':
                  if (selectedKey.dictionaryCode !== 'medium_type') {
                    this.smartQuery.medium_type = selectedKey.dictionaryName
                  }
                  break
                default:
                  if (selectedKey.dicCode !== 'archive_year') {
                    this.smartQuery.archive_year = selectedKey.dictionaryName
                  }
              }
            }
          }
          this.$nextTick(() => {
            // this.handlePageList('quickFilter')
          })
        }
      }
    },
    changeActiveTab(val) {
      this.activeIndex = val
    },
    handleOpenAnjuan(data, parentId, parentsRow) {
      this.parentsProjectId = parentId
      this.parentsProjectRow = parentsRow
      this.$refs.anjuanEle.anjuanDrawer = true
      this.activeIndex = 0
      if (this.$refs.anjuanEle.$refs.ajContent) {
        this.$refs.anjuanEle.$refs.ajContent.activeIndex = 0
      }
      this.$nextTick(() => {
        // this.$refs.anjuanEle.$refs.ajContent.$refs.tableList.getCommonData(2, this.parentsProjectId)
        this.$refs.anjuanEle.$refs.ajContent.test = data
      })
    },
    handleOpenJuannei(data, parentId) {
      this.parentsAnjuanId = parentId
      console.log('this.parentsAnjuanId', this.parentsAnjuanId)
      if (this.storageCategory.arrangeType === 1 || (this.storageCategory.arrangeType === 3 && this.$refs.anjuanEle.$refs.ajContent.activeIndex === 1) || (this.storageCategory.arrangeType === 2 && this.$refs.anjuanEle.$refs.ajContent.activeIndex === 1)) {
        this.$refs.fileEle.fileDrawer = true
        this.$nextTick(() => {
          // this.$refs.fileEle.getCommonData(4, this.parentsAnjuanId)
          this.$refs.fileEle.test = data
          this.$refs.fileEle.isAjNo = 1
        })
      } else {
        this.$refs.juanneiEle.juanneiDrawer = true
        this.$nextTick(() => {
          // this.$refs.juanneiEle.getCommonData(3, this.parentsAnjuanId)
          this.$refs.juanneiEle.test = data
          this.$refs.fileEle.isAjNo = 0
        })
      }
    },
    handleOpenFile(data, parentId) {
      this.parentsJuanneiId = parentId
      console.log('this.parentsJuanneiId', this.parentsJuanneiId)
      this.$refs.fileEle.fileDrawer = true
      this.$nextTick(() => {
        // this.$refs.fileEle.getCommonData(4, this.parentsJuanneiId)
        this.$refs.fileEle.test = data
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.elect-cont-left{
  width: 276px;
  padding: 0 !important;
}
.hideSidebar .elect-cont-left {
  width: 265px !important;
}
[data-theme=light] .elect-cont-left .container-left {
    min-height: calc(100vh - 140px);
}
[data-theme=dark] .elect-cont-left .container-left {
    min-height: calc(100vh - 160px);
}
.openSidebar .elect-cont-right {
  width: calc(100vw - 592px);
}
[data-theme=light] .elect-cont-right .container-right.tab-content {
    min-height: calc(100vh - 200px) !important;
}
.arc-title{
  position: relative;
  height: 48px;
  line-height: 48px;
  text-align: center;
  font-size: 16px;
  color: #0C0E1E;
  background-color: #F3F5F8;
  &::after{
    content: "";
    position: absolute;
    right: 12px;
    bottom: 0;
  }
}
.arc-title-top{
  &::after{
    width: 44px;
    height: 35px;
    background: url("~@/assets/images/collect/daml.png") no-repeat;
    background-size: 100% 100%;
  }
}
.arc-title-bottom{
  &::after{
    width: 41px;
    height: 40px;
    background: url("~@/assets/images/collect/kssx.png") no-repeat;
    background-size: 100% 100%;
  }
}
.arc-tree{
  padding: 0 20px;
}
.arc-tree-01{
  height: 400px;
  overflow: hidden;
  overflow-y: scroll;
}
[data-theme=dark] .arc-tree-01{
  height: 370px;
}

.arc-tree-02{
  height: calc(100vh - 720px);
  overflow: hidden;
  overflow-y: scroll;
  .el-tree{
    margin: 0;
  }
}
::v-deep .el-tree-node__children .custom-tree-node{
  font-size: 14px;
}

::v-deep .custom-tree-node{
  font-size: 14px;
  font-weight: normal;
}

[data-theme=light] .elect-cont-right {
    padding: 15px 0 !important;
}
[data-theme=dark] .elect-cont-right {
    margin-top: 0 !important;
}
</style>
