<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-tree key="1" v-show="!isDirSeqTree" v-loading='loading' highlight-current :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.classType === 'L'"
                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>
      </div>
      
    </el-card>
    <div class="resize" title="收缩侧边栏">
      ⋮
    </div>
    <el-card class="form-box" ref='cardForm' :body-style="{ padding: '5px 10px' }">
      <div v-show=" JSON.stringify(treeRow)==='{}'?false:true">

        <el-row>
          <el-col v-for="(ele, index) in search" :key="index" :span="8" class="search">
            <div style="width: 110px; text-align: right">{{ ele.label }}：</div>
            <el-input size="mini" style="width: 60%" clearable v-if="ele.ctype === 'input'" v-model="ele.value"
              placeholder="请输入"></el-input>
            <!-- 文本框 -->
            <el-input v-if="ele.ctype === 'text'" type="textarea" size="mini" :rows="1" clearable v-model="ele.value"
              style="width: 60%" placeholder="请输入"></el-input>
            <!-- 下拉框 -->
            <el-select v-if="ele.ctype === 'select'" v-model="ele.value" clearable size="mini" style="width: 60%"
              placeholder="请选择">
              <el-option v-for="op in ele.note.note" :label="op.label" :value="op.label" size="mini" style="width: 60%"
                :key="op.value"></el-option>
            </el-select>
            <!-- 年 -->
            <el-date-picker v-if="ele.ctype === 'datetime'" v-model="ele.value" type="datetime" size="mini" clearable
              style="width: 60%" placeholder="选择日期时间"></el-date-picker>
            <el-date-picker v-if="ele.ctype === 'datetimerange'" v-model="ele.value" type="datetimerange" size="mini"
              clearable style="width: 60%" range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>

          </el-col>
          <el-col :span='6' class="search" v-show="JSON.parse(Alltable.tableShow).length">
            <el-button size="mini" type="primary" @click="getData()" v-show="search.length?true:false">搜索</el-button>
          </el-col>
        </el-row>
        <!-- <el-button @click="querySet()" size="mini" type="primary">查询设置</el-button> -->
        <content-table @handleQuery="querySet()" @getDirTreeSearch="getDirTreeSearch" :safekeeping="safekeeping" :showButtons="showButtons"
          :Alltable='Alltable' :fondsList='fondsList' :classList='classList' :treeRow='treeRow'
          @handleNodeClick='handleNodeClick' @getData="getData" @customSort="customSort" @createReport="createReport" @handleStateMent="handleStateMent" />
        <!-- 查询设置 -->
        <dia-query :querySetData="querySetData" :visible="diaQuery" ref="diaQuery" @cancel="(()=>this.diaQuery=false)"
          @submit="querySubmit" />
        <!-- 报表设计弹框 -->
        <report-designer :visible="stateMent" ref="stateMent" @cancel="(()=>this.stateMent = false)" />
        <!-- 报表预览弹窗 -->
        <report-view @reset="reset" :visible="diaReport" model="3" @cancel="(()=>this.diaReport = false)" ref="diaReport" />
      </div>
    </el-card>
  </div>
</template>
<script>
import { getFindList } from "@/api/system-management/templateSetting";
import {
  getOneTable,
  getTable,
  getSettingField,
  querySettings,
  getDirTree,
  findTreeChildren,
} from "@/api/archives-management/fileManagement/notStoredArchives.js";
import { queryReportName, queryEntityLevel } from "@/api/reportTemplate";
import contentTable from "./components/contentTable.vue";
import diaQuery from "./components/diaQuery.vue";
import ReportDesigner from "@/components/ReportDesigner";
import ReportView from "@/components/ReportView";
import { mapState } from "vuex";
import { message, dragControllerDiv } from "@/utils/common";
import localStronge from "@/api/localData";
import { URL_PREFIX } from "@/utils/url-prefix";
export default {
  data() {
    return {
      diaReport:false, // 报表预览
      stateMent:false, // 报表设计
      dirQuery: {}, // 目录序列树参数
      isDirSeqTree: false, // 是否目录序列树
      dirTreeData: [], // 目录序列树
      dirTreeLoading: false, // 目录序列树loading
      eleTable: {}, // 按钮对应的table
      eleKey: 1, // 按钮对应的table key
      status: false,
      // 树形结构数据
      defaultProps: {
        children: "childClass",
        label: "className",
      },
      defaultDirProps: {
        children: "children",
        label: "title",
        isLeaf: 'isLeaf'
      },
      search: [],
      Alltable: {
        tableShow: "[]",
      },
      treeRow: {},
      search: [],
      treeType: "",
      safekeeping: [],
      querySetData: {},
      diaQuery: false, // 查询设置表单
      currentTableKey: "",
      orderObj:{},
    };
  },
  components: {
    contentTable,
    diaQuery,
    ReportDesigner,
    ReportView,
  },
  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 = "22%";
          cardForm.width = "77%";
        }
      },
    },
  },
  computed: {
    ...mapState({
      treeData: (state) => state.filing.treeData,
      tableData: (state) => state.filing.tableData,
      fondsList: (state) => state.filing.fondsList,
      classList: (state) => state.filing.classList,
      pagination: (state) => state.filing.pagination,
      showButtons: (state) => state.filing.showButtons,
    }),
    tableLoading: {
      get() {
        return this.$store.state.filing.tableLoading;
      },
      set(val) {
        this.$store.state.filing.tableLoading = val;
      },
    },
    loading: {
      get() {
        return this.$store.state.filing.loading;
      },
      set(val) {
        this.$store.state.filing.loading = val;
      },
    },
  },
  methods: {
    // 报表设计
    handleStateMent() {
    
      this.stateMent = true;
      this.$refs.stateMent.treeRow = this.treeRow;
      this.$refs.stateMent.treeData = this.treeData;
      this.$refs.stateMent.rowData = this.Alltable;
    },
    // 报表预览
    createReport(multipleSelection) {
      let rname;
      this.$refs.diaReport.radioType = "";
      this.diaReport = true;
      this.treeData.forEach((item) => {
        return item.childClass.forEach((i) => {
          i.childClass.forEach((k) => {
            if (
              k.className == this.treeRow.className &&
              k.pid == this.treeRow.pid
            ) {
              rname = item;
            }
          });
        });
      });
      this.$refs.diaReport.tableRow = this.Alltable;
      this.$refs.diaReport.rname = rname;
      this.$refs.diaReport.treeRow = this.treeRow;
      this.$refs.diaReport.multipleSelection = multipleSelection;
      const ids = multipleSelection.map((item) => {
        return item.id;
      });
      this.$refs.diaReport.ids = ids;
      queryEntityLevel({ entityId: this.Alltable.entityId }).then((res) => {
        if (res.code === "100") {
          this.$refs.diaReport.fileType = res.body.entityLevel;
          this.showBaoBiaoPdf(res.body.entityLevel, rname, this.treeRow);
        }
      });
    },
    // pdf展示
    showBaoBiaoPdf(fileType, rname, treeRow) {
      let data = {
        classId: treeRow.id,
        // companyId: rname.id,
        fileType,
      };
      queryReportName(data).then((res) => {
        if (res.code === "100") {
          this.$refs.diaReport.tableData = res.body.list;
        }
      });
    },
    reset(fileType, rname, treeRow) {
      this.showBaoBiaoPdf(fileType, rname, treeRow);
    },
    // 点击排序调用接口排序
    customSort(params){
      this.getData(params);
    },
    // 查询设置-保存
    querySubmit(val, key) {
      // const ele = this.Alltable.filter(
      //   (item, index) => this.currentTableKey === index
      // )[0];
      let ele = this.Alltable;
      const params = {
        entityId: ele.entityId,
        dataKeys: val.fields,
        type: val.type,
        userId: parseInt(sessionStorage.getItem("userid")),
      };
      querySettings(params).then((res) => {
        message("success", "保存成功", 2000);
        this.diaQuery = false;
        // this.$emit("handleNodeClick", this.treeRow);
        this.handleNodeClick(this.treeRow);
      });
    },
    handleDirNodeClick(data){
      const valueArr = data.key.split(",");
      Object.keys(this.dirQuery).forEach((dir, index) => {
        this.dirQuery[dir] = valueArr[index];
      });
      this.getData();
    },
    loadDirNode(node, resolve) {
      console.log(node);
      if (node.level === 0) {
        return resolve(this.dirTreeData);
      }
      if (node.level === 1) {
        return resolve(this.dirTreeData[0].children);
      }
      let data = [];
      const params = {
        entityId: this.Alltable.entityId,
        tableName: this.Alltable.tableName+"_temp",
        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);
      });
    },
    // 查询设置
    querySet() {
      this.getQuerySet();
      this.diaQuery = true;
      // this.currentTableKey = key;
    },
    // 目录序列树
    getDirTreeSearch() {
        this.isDirSeqTree = !this.isDirSeqTree; // 目录序列树
        if (this.isDirSeqTree) {
          this.getDirTree();
          this.getQuerySet()
        } else {
          this.$nextTick(() => {
            this.getData();
          })
        }
    },
    // 目录序列树
    async getDirTree(ele) {
      this.dirTreeLoading = true;
      const params = {
        entityId: this.Alltable.entityId,
        tableName: this.Alltable.tableName+'_temp',
        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;
        });
    },
    // 查询设置
    getQuerySet() {
      let ele = this.Alltable;
      this.querySetData = {
        entityId: ele.entityId,
        tableName: ele.tableName,
        type: 1,
        userId: sessionStorage.getItem("userid"),
      };
      getSettingField(this.querySetData).then((res) => {
        if (res.code === "100") {
          this.$refs.diaQuery.data = res.body.dataSource;
          this.$refs.diaQuery.form.fields = res.body.targetKeys;
          this.$refs.diaQuery.form.type = 1;
          // 目录序列树查询参数
          this.dirQuery = {};
          res.body.targetKeys.forEach((target) => {
            this.dirQuery[target.split(",")[0]] = "";
          });
        }
      });
    },
    btns() {
      this.status = !this.status;
    },
    getData(paramsOrder) { // 调用sort排序
      this.tableLoading = true;
      let orderString = null;
      if(JSON.stringify(paramsOrder) === '{}' || paramsOrder==null || paramsOrder== 0){
        orderString = 'order by  id  desc';
      }else{
        orderString = `order by  ${paramsOrder.sortKey}  ${paramsOrder.sortType}`;
      }
      let params = {
        commonMap: {
          funcTypeCode: this.treeType,
          tableName: this.Alltable.tableName,
        },
        conditionMap: {},
        limit: this.pagination.pageSize,
        page: this.pagination.pageNum,
        orderBy: orderString,
      };
      this.search.forEach((ele) => {
        if (ele.ctype === "datetime") {
          params.conditionMap[ele.fieldName] = ele.value
            ? dateFormat(ele.value)
            : "";
        } else if (ele.ctype === "datetimerange") {
          params.conditionMap[ele.fieldName] = ele.value
            ? dateFormatT(ele.value).start + "~" + dateFormatT(ele.value).end
            : "";
        } else {
          //params.conditionMap[ele.fieldName] = ele.value;
          params.conditionMap[ele.fieldName] = ele.value
              ? `like${ele.value}`
              : ele.value;
        }
      });

      // 目录序列树参数
      if (this.isDirSeqTree) {
        params.conditionMap = {
          ...params.conditionMap,
          ...this.dirQuery,
        };
      }

      this.$store.dispatch("filing/getOneTable", params).catch((err) => {
        this.tableLoading = false;
      });
    },
    handleNodeClick(tab) {
      this.treeRow = tab;
      if (tab.classType === "C") {
        let params = {
          classId: tab.id,
        };
        getTable(params).then((res) => {
          res.body.InterfaceSystem.forEach((item) => {
            let ruleForm = {};
            let form = JSON.parse(item["interfaceShow"]);
            let interfaceQuery = JSON.parse(item["interfaceQuery"]);
            // this.form = JSON.parse(item["interfaceShow"]);
            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 === 24) {
                ele.width = "100%";
              }
            });
            interfaceQuery.forEach((ele) => {
              if (ele.ctype === "select") {
                getFindList({
                  type: ele.note.type,
                }).then((res) => {
                  ele.note.note = res.body.list;
                });
              }
            });
            // this.form = form
            this.$set(item, "search", JSON.parse(item["interfaceQuery"])); //搜索
            this.search = interfaceQuery;
            // this.$set(item, "form", form); //添加
            this.$set(item, "ruleForm", ruleForm); //表单
            // this.ruleForm = ruleForm
            // this.$set(item, "tableData", JSON.parse(item["tableShow"])); //表格
            this.$set(item, "tableLoading", false);
            this.$set(item, "selectTable", []);
            this.$set(item, "pagination", {
              pageSize: 10,
              pageNum: 1,
              total: 0,
            });
          });
          this.Alltable = res.body.InterfaceSystem[0];
          this.getData();
        });
        this.$store.dispatch("filing/selecttargetClassList", {
          sourceClassId: tab.id,
        });
      }
    },
    getTreeData() {
      this.loading = true;
      this.$store
        .dispatch("filing/getClassTreeByClassName", {
          className: "文件",
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    getsafekeeping() {
      getFindList({
        type: "retention",
      }).then((res) => {
        this.safekeeping = res.body.list;
      });
    },
  },
  mounted() {
    dragControllerDiv();
  },
  created() {
    this.getsafekeeping();
    this.getTreeData();
    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.$store.dispatch("filing/getButtonList", btnData);
    this.$store.dispatch("filing/getFondWithPageUser");
  },
};
</script>
<style lang='scss' scoped>
.box {
  display: flex;
  justify-content: space-around;
  height: 100%;

  .tree-box {
    width: 22%;
    // height: 1000px;
    background-color: #fff;
    padding: 5px 10px;

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

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

    background-color: #fff;
    padding: 5px 10px;

    .search {
      height: 30px;
      line-height: 30px;
      display: flex;
      margin: 8px 0px;
    }
  }
}
</style>
