<template>
  <div class="box">
    <el-card class="tree-box" shadow="always" :body-style="{ padding: '5px' }" ref="cardTree">
      <div slot="header" class="clearfix">
        <span v-show="!status">选择门类档案</span>
        <el-button style="float: right; padding:  0" type="text" @click='btns'>
          <el-tooltip class="item" effect="dark" v-if="!status" content="折叠" placement="right">
            <svg-icon icon-class="leftzd" v-if="!status" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" v-if="status" content="展开" placement="left">
            <svg-icon icon-class="rightzd" v-if="status" />
          </el-tooltip>
        </el-button>
      </div>
      <div>
        <el-scrollbar wrap-style="overflow-x:hidden;" style="height: calc(100vh - 160px)">
          <el-tree key="1" v-show="!isDirSeqTree" highlight-current v-loading='treeLoading' :data="treeData"
            :props="defaultProps" default-expand-all @node-click="handleNodeClick">
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <!--可以根据情况，以数据类型来显示不同的图标或图片-->
              <!--可以根据情况，以数据类型来显示不同的图标或图片-->
              <svg-icon icon-class="wjj" style="margin-right: 5px; color: rgb(255, 207, 92)"
                v-if="data.childClass.length > 0" class="iconfont icon-folder-open-fill" />
              <svg-icon icon-class="wj" style="margin-right: 5px; color: rgb(255, 207, 92)" v-else
                class="iconfont icon-wenjian" />
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
          <el-tree key="2" v-show="isDirSeqTree" highlight-current :expand-on-click-node=false :data="dirTreeData"
            v-loading="dirTreeLoading" :props="defaultDirProps" :load="loadDirNode" @node-click="handleDirNodeClick"
            lazy>
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <svg-icon icon-class="wjj" style="margin-right: 5px; color: rgb(255, 207, 92)" v-if="!data.isLeaf"
                class="iconfont icon-folder-open-fill" />
              <svg-icon icon-class="wj" v-else style="margin-right: 5px; color: rgb(255, 207, 92)"
                class="iconfont icon-wenjian" />
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
        </el-scrollbar>
      </div>
    </el-card>
    <div class="resize" title="收缩侧边栏">
      ⋮
    </div>
    <el-card class="form-box" ref='cardForm' :body-style="{ padding: '5px' }">
      <right-table-box ref="table" :showButtons="showButtons" @handleNodeClick='handleNodeClick'
        @triggerTree="triggerTree" :fondsList="fondsList" :treeRow='treeRow' :isDirSeqTree="isDirSeqTree"
        @appraisal="appraisal" :Alltable="Alltable" @returnlibrary="returnlibrary">
      </right-table-box>
    </el-card>
    <dia-apply :visible="diaVisible" :title="applyTitle" :applyStatus="applyStatus" :applyList="applyList"
      @cancel="cancel" ref="diaApply" @submit="applySubmit" :isApply="true" />
    <!-- 快过期档案查询 -->
    <expire-box :visible="expireVisible" @cancel="cancel" ref="expire" />
  </div>
</template>
<script>
import { getFindList } from "@/api/intelligent-warehouse/warehouse-management/fileBox-management";
import { getCurrentTime, message, dragControllerDiv } from "@/utils/common";
import DiaApply from "@/components/DiaApply";
import {
  getTree,
  getDirTree,
  findTreeChildren,
  getTable,
  submitApply,
} from "@/api/archives-management/fileManagement/notStoredArchives.js";
import { getExpire,checkFlowDataIng } from "@/api/archives-management/fileManagement/dataBrowsing";
import { getFondWithPage } from "@/api/system-management/allAdministration";
import { getButtonList } from "@/api/user";
import rightTableBox from "./components/rightTableBox";
import expireBox from "./components/expireBox.vue";
import {selectUserDetails} from "@/api/user.js"
export default {
  data() {
    return {
      isCheckFlowa:null,
      detailUserText:'',
      status: false,
      treeLoading: false,
      treeData: [],
      defaultProps: {
        children: "childClass",
        label: "className",
      },
      defaultDirProps: {
        children: "children",
        label: "title",
        isLeaf: "isLeaf",
      },
      isDirSeqTree: false, // 是否目录序列树
      dirTreeData: [], // 目录序列树
      dirTreeLoading: false, // 目录序列树loading
      eleTable: {}, // 按钮对应的table
      eleKey: "", // 按钮对应的table key
      expireVisible: false, // 快过期档案弹框
      treeRow: {},
      Alltable: [],
      fondsList: [],
      diaVisible: false, //审批弹窗状态
      applyStatus: 0, //审批状态
      applyList: [], //审批下拉框
      applyTitle: "申请表单",
      showButtons: {
        bb: false,
        addF: false,
        setQuery: false,
        cataTree: false,
        appraisal: false,
        export: false,
        eep: false,
        transfer: false,
        return: false,
        enBorrow: false,
        four: false,
        ywBtn: false,
        jdzd: false,
        xhhc: false,
      },
    };
  },
  components: {
    rightTableBox,
    expireBox,
    DiaApply,
  },
  watch: {
    status: {
      handler(val, oldVal) {
        const cardTree = this.$refs.cardTree.$el.style;
        const cardForm = this.$refs.cardForm.$el.style;
        if (val) {
          cardTree.width = "5%";
          cardForm.width = "94%";
        } else {
          cardTree.width = "20%";
          cardForm.width = "79%";
        }
      },
    },
  },
  methods: {
    // 判断勾选的条目是否存在其他条目中
    isCheckFlowDataIng(ele){
      let isCheckFlow = false;
      let params = {
        classId:this.treeRow.id,
        recIds:ele.selectTable.map((item) => item.id).join(","),
        tableName:ele.tableName
      }
      checkFlowDataIng(params).then((res)=>{
        if(res.code == 102){
          isCheckFlow = true;
        }else{
          isCheckFlow = false;
        }
      })
      return isCheckFlow;
    },
    btns() {
      this.status = !this.status;
    },
    getFonds() {
      getFondWithPage({
        limit: 1000,
      }).then((res) => {
        this.fondsList = res.body.list;
      });
    },
    // 根据id查询用户信息
    getUserDetail(){
      selectUserDetails({userId:sessionStorage.getItem('userid')}).then((res)=>{
        let result = res.body.userDetails;
        this.detailUserText = result;
      }).catch((error)=>{
        message("warning",error,'4000')
      })
    },
    // 获取初始化树形结构
    async initGetTree() {
      this.treeLoading = true;
      let data = {
        className: "档案",
      };
      getTree(data)
        .then((res) => {
          this.treeLoading = false;
          if (res.success) {
            this.treeData = res.body.list;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.treeLoading = false;
        });
    },
    handleNodeClick(data) {
      this.treeRow = data;
      if (data.classType === "C") {
        let params = {
          classId: data.id,
        };
        getTable(params)
          .then((res) => {
            res.body.InterfaceSystem.forEach((item, index) => {
              if (!data.clicked && index === 0) {
                // 第一次点击门类，提示快过期档案
                data.clicked = true;
                // this.getExpireList(item);
              }
              let ruleForm = {};
              let form = JSON.parse(item["interfaceShow"]);
              let interfaceQuery = JSON.parse(item["interfaceQuery"]);
              // 查询设置中增加全宗号
              if(interfaceQuery.length==0){
                  interfaceQuery.push({ctype:"input",fieldName:"fonds_no",fieldNameZh:"全宗号",value:"",label:'全宗号'});
                }else{
                  const index = interfaceQuery.findIndex(item=>item.fieldName === 'fonds_no');
                  if(index !== -1){
                    // 找到
                    const matchItem = interfaceQuery.splice(index, 1)[0];
                    interfaceQuery.unshift(matchItem);
                  }else{
                    // 没找到
                    interfaceQuery.unshift({ctype:"input",fieldName:"fonds_no",fieldNameZh:"全宗号",value:"",label:'全宗号'});
                  }
                }
              form.forEach((ele) => {
                this.$set(ruleForm, ele.fieldName, "");
                if (ele.width === 8) {
                  ele.width = "33%";
                }
                if (ele.width === 12) {
                  ele.width = "50%";
                }
                if (ele.width === 25) {
                  ele.width = "100%";
                }
              });
              interfaceQuery.forEach((ele) => {
                if (ele.ctype === "select") {
                  getFindList({
                    type: ele.note.type,
                  }).then((res) => {
                    ele.note.note = res.body.list;
                  });
                }
              });
              this.$set(item, "search", interfaceQuery); //搜索
              this.$set(item, "form", form); //添加
              this.$set(item, "ruleForm", ruleForm); //表单
              this.$set(item, "tableData", JSON.parse(item["tableShow"])); //表格
              this.$set(item, "isShow", false);
              this.$set(item, "selectTable", []);
              this.$set(item, "tableLoading", false);
              this.$set(item, "pagination", {
                pageSize: 10,
                pageNum: 1,
                total: 0,
              });
              this.$set(item, "tableData", []);
            });
            this.Alltable = res.body.InterfaceSystem;
          })
          .then((res) => {
            this.$nextTick(() => {
              this.$refs.table.clickSearch(0, 1, 1);
            });
          });
      }
    },
    getExpireList(ele) {
      getExpire({
        tableName: ele.tableName,
      }).then((res) => {
        if (res.code === "100") {
          if (res.body.list.length) {
            this.expireVisible = true;
            this.$refs.expire.expireList = res.body.list;
          }
        }
      });
    },
    triggerTree(key) {
      this.eleKey = key;
      this.eleTable = this.Alltable.filter((item, index) => key === index)[0];
      this.isDirSeqTree = !this.isDirSeqTree; // 目录序列树
      if (this.isDirSeqTree) {
        this.getDirTree();
        this.$refs.table.getQuerySet(this.eleTable);
      } else {
        this.$nextTick(() => {
          this.$refs.table.clickSearch(0, 1, 1);
        });
      }
    },
    // 目录序列树
    async getDirTree(ele) {
      this.dirTreeLoading = true;
      const params = {
        entityId: this.eleTable.entityId,
        tableName: this.eleTable.tableName,
        userId: parseInt(sessionStorage.getItem("userid")),
        mode: 2, // 已入库
        type: 1,
      };
      getDirTree(params)
        .then((res) => {
          this.dirTreeLoading = false;
          if (res.success) {
            this.dirTreeData = res.body.list;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.dirTreeLoading = false;
        });
    },
    loadDirNode(node, resolve) {
      if (node.level === 0) {
        return resolve(this.dirTreeData);
      }
      if (node.level === 1) {
        return resolve(this.dirTreeData[0].children);
      }
      let data = [];
      const params = {
        entityId: this.eleTable.entityId,
        tableName: this.eleTable.tableName,
        userId: parseInt(sessionStorage.getItem("userid")),
        mode: 2, // 已入库
        type: 1,
        key: node.data.key,
        level: node.data.level,
      };
      findTreeChildren(params).then((res) => {
        data = res.body.list;
        setTimeout(() => {
          resolve(data);
        }, 500);
      });
    },
    handleDirNodeClick(data) {
      /* const params = {
          entityId: this.eleTable.entityId,
          tableName: this.eleTable.tableName,
          userId: parseInt(sessionStorage.getItem("userid")),
          mode: 2, // 已入库
          type: 1,
          keys: data.key,
          page: 1,
          limit: 10
        }
        // 根据目录序列树查询右侧表格
        this.$refs.table.clickDirSearch(params, this.eleKey); */
      this.$refs.table.dirNodeClick(data.key, this.eleKey);
    },
    returnlibrary(val, key) {
      this.Alltable.forEach((item, index) => {
        var num = 0;
        var selItem = item.selectTable;
        for(var i=0;i<selItem.length;i++){
          num = num + (!!(selItem[i].archive_file_num)?selItem[i].archive_file_num:0);
        }
        if (index === key) {
          this.diaVisible = true;
          this.applyStatus = 0;
          this.applyTitle = "申请表单-退回未入库";
          this.$refs.diaApply.form = {
            applyUserId: sessionStorage.getItem("userid"),
            applyUserName: this.detailUserText,
            applyTime: getCurrentTime(),
            rec_nums: item.selectTable.length, //申请档案数量
            originalTextNums: num, // 原文数量
            recIds: item.selectTable.map((ele) => ele.id).join(","), // 勾选数据id逗号拼接
            applyReason: "",
            expressType: val,
            tableName: item.tableName, // 表名
            tableType: this.treeType,
            className: this.treeRow.className, // 门类名
            classId: this.treeRow.id,
          }
        };
    });
    },
    //点击鉴定方式其中之一
    appraisal(val, key, value) {
      this.Alltable.forEach((item, index) => {
        
        if (index === key) {
          if (!item.selectTable.length) {
            message("warning", "请先选择档案", 2000);
            return;
          } else {
            checkFlowDataIng({
              classId:this.treeRow.id,
              recIds:item.selectTable.map((i) => i.id).join(","),
              tableName:item.tableName}).then((res)=>{
              if(res.code == 102){
                message('warning','该档案数据不能被修改,数据存在其他流程中!',3000);
                return;
              }else{
                this.diaVisible = true;
              }
            })
            this.$refs.diaApply.form = {
              applyUserId: sessionStorage.getItem("userid"),
              applyUserName: this.detailUserText,
              applyTime: getCurrentTime(),
              rec_nums: item.selectTable.length, //申请档案数量
              originalTextNums: item.selectTable.reduce(
                (total, ele) => total + ele.archive_file_num,
                0
              ), // 原文数量
              recIds: item.selectTable.map((ele) => ele.id).join(","), // 勾选数据id逗号拼接
              applyReason: "",
              tableName: item.tableName, // 表名
              tableType: this.treeType,
              className: this.treeRow.className, // 门类名
              classId: this.treeRow.id,
            };
            // let tableShow = JSON.parse(item.tableShow)
            let interfaceShow = JSON.parse(item.interfaceShow);
            switch (val) {
              case 1: //密级
                interfaceShow.forEach((ar) => {
                  if (ar.fieldNameZh.indexOf(value) != -1) {
                    this.$set(
                      this.$refs.diaApply.form,
                      "securityClassName",
                      ar.fieldName
                    );
                  }
                });
                this.applyTitle = "申请表单-密级鉴定";
                this.$refs.diaApply.form.expressType = "1";
                this.applyStatus = 1;
                getFindList({
                  type: "securityClass",
                }).then((res) => {
                  this.applyList = res.body.list;
                });
                break;
              case 2: //期限
                interfaceShow.forEach((ar) => {
                  if (ar.fieldNameZh.indexOf(value) != -1) {
                    this.$set(
                      this.$refs.diaApply.form,
                      "retentionName",
                      ar.fieldName
                    );
                  }
                });
                this.applyTitle = "申请表单-期限鉴定";
                this.$refs.diaApply.form.expressType = "2";
                this.$set(this.$refs.diaApply.form, "retention", "");
                this.applyStatus = 2;
                getFindList({
                  type: "retention",
                }).then((res) => {
                  this.applyList = res.body.list;
                });
                break;
              case 3: //开放
                interfaceShow.forEach((ar) => {
                  if (ar.fieldNameZh.indexOf(value) != -1) {
                    this.$set(
                      this.$refs.diaApply.form,
                      "kzbsName",
                      ar.fieldName
                    );
                  }
                });
                this.applyTitle = "申请表单-开放鉴定";
                this.$refs.diaApply.form.expressType = "3";
                this.$set(this.$refs.diaApply.form, "kzbs", "");
                this.applyStatus = 3;
                getFindList({
                  type: "security_class",
                }).then((res) => {
                  this.applyList = res.body.list;
                });
                break;
              case 4:
                this.applyTitle = "申请表单-销毁鉴定";
                this.$refs.diaApply.form.expressType = "4";
                this.applyStatus = 0;
                break;
              case 5:
                interfaceShow.forEach((ar) => {
                  if (ar.fieldNameZh.indexOf(value) != -1) {
                    this.$set(
                      this.$refs.diaApply.form,
                      "controlIdentifier",
                      ar.fieldName
                    );
                  }
                });
                this.applyTitle = "申请表单-控制标识";
                this.$refs.diaApply.form.expressType = "17";
                this.$set(this.$refs.diaApply.form, "controlIdentifier", "");
                this.$set(
                  this.$refs.diaApply.form,
                  "controlIdentifierName",
                  "control_identifier"
                );
                this.applyStatus = 4;
                getFindList({
                  type: "control_identifier",
                }).then((res) => {
                  this.applyList = res.body.list;
                });
                break;
              case 6:
                this.applyTitle = "销毁缓期-控制标识";
                this.$refs.diaApply.form.expressType = "18";
                this.$set(
                  this.$refs.diaApply.form,
                  "isPackeepName",
                  "is_packeep"
                );
                this.$set(this.$refs.diaApply.form, "isPackeep", "是");
                this.applyStatus = 0;
                break;
              case 7:  //价值鉴定
                interfaceShow.forEach((ar) => {
                    if (ar.fieldNameZh.indexOf(value) != -1) {
                      this.$set(
                        this.$refs.diaApply.form,
                        "archiveValueName",
                        "archive_value"
                      );
                    }
                });
                this.applyTitle = "申请表单-价值鉴定";
                this.$refs.diaApply.form.expressType = "22";
                this.applyStatus = 7;
                getFindList({
                  type: "archive_value",
                }).then((res) => {
                  this.applyList = res.body.list;
                });
                break;
            }
          }
        }
      });
    },
    cancel() {
      this.diaVisible = false;
      this.expireVisible = false;
      this.$refs.expire.expireList = [];
    },
    applySubmit(val) {
      submitApply(val)
        .then((res) => {
          this.$refs.diaApply.btnloading.submit = false;
          message("success", "提交审批成功", 2000);
          this.diaVisible = false;
          this.$emit("handleNodeClick", this.treeRow);
        })
        .catch(() => {
          this.$refs.diaApply.btnloading.submit = false;
        });
    },
    getButtonListqx(btnData) {
      getButtonList(btnData).then((res) => {
        res.body.list.forEach((item) => {
          this.showButtons[item.key] = true;
        });
      });
    },
  },
  mounted() {
    dragControllerDiv();
  },
  created() {
    this.getFonds();
    // 获取初始化树形结构
    this.initGetTree();
    this.treeType = this.$getMenuId(
      sessionStorage.getItem("funcTypeCodeList"),
      this.$route.path
    );
    let btnData = {
      menuid: this.$getMenuId(
        sessionStorage.getItem("routerIdList"),
        this.$route.path
      ),
      roleid: sessionStorage.getItem("roleid"),
    };
    this.getButtonListqx(btnData);
    this.getUserDetail();
  },
};
</script>
<style lang='scss' scoped>
.box {
  display: flex;
  justify-content: space-around;
  height: 100%;

  .tree-box {
    width: 20%;
    background-color: #fff;
    padding: 5px 10px;

    .clearfix {
      font-weight: 600;
      font-size: 17px;
      letter-spacing: 3px;
    }
  }

  .form-box {
    width: 79%;
    height: calc(100vh - 90px);
    overflow-y: auto;

    background-color: #fff;
    padding: 5px 10px;
  }
}
</style>
