<template>
  <div>
    <div v-for="(item, key) in Alltable" :key="key" class="wholeTable">
      <el-card
        :body-style="{ padding: '0px' }"
        :class="item.isShow ? 'searcAll' : 'searcAllflase'"
        v-if="item.search.length"
      >
        <el-row>
          <el-col
            v-for="(ele, index) in item.search"
            :key="index"
            :span="8"
            class="search"
          >
            <div style="width: 90px; 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-row>
      </el-card>
      <div class="searchBtn" v-if="item.search.length">
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-search"
          @click="clickSearch(key, 1, 0)"
          >查询</el-button
        >
        <el-button
          size="mini"
          type="success"
          icon="el-icon-refresh-right"
          @click="clickSearch(key, 2, 0)"
          >重置
        </el-button>
        <el-button
          v-if="item.search.length > 3 || item.search.length == 3"
          @click="clickSearch(key, 3, 0)"
          size="mini"
          type="success"
          icon="el-icon-d-caret"
          >展开/折叠</el-button
        >
      </div>
      <div class="btnClass">
        <el-button
          size="mini"
          type="success"
          @click="clickSearch(key, 4, 0)"
          icon="el-icon-plus"
          v-if="showButtons.add"
        >
          添加</el-button
        >
        <el-button
          size="mini"
          type="primary"
          @click="clickSearch(key, 5, 0)"
          icon="el-icon-edit"
          v-if="showButtons.edit"
        >
          修改</el-button
        >
        <el-button
          size="mini"
          type="danger"
          @click="clickSearch(key, 6, 0)"
          icon="el-icon-delete"
          v-if="showButtons.del"
          >删除</el-button
        >
        <el-button
          @click="querySet(item, key)"
          size="mini"
          type="primary"
          v-if="showButtons.setQuery"
          >查询设置</el-button
        >
        <el-button
          @click="getDirTree(key)"
          size="mini"
          type="primary"
          v-if="showButtons.cataTree"
          >目录序列树</el-button
        >
        <!-- <el-button @click="createReport(key)" size="mini" type="primary" v-if="showButtons.bb">报表</el-button> -->
        <el-button
          @click="application(key)"
          size="mini"
          type="primary"
          v-if="
            ((Alltable.length === 2 && key === 0) || Alltable.length === 1) &&
            showButtons.gd
          "
          >归档申请</el-button
        >
        <el-button
          @click="handleBtn(item, key, 'contract')"
          size="mini"
          type="primary"
          v-if="
            (Alltable.length === 3 && key === 0) ||
            (Alltable.length === 2 && key === 0) ||
            Alltable.length === 1
          "
          >合同系统对接</el-button
        >
        <el-button
          @click="handleBtn(item, key, 'file')"
          size="mini"
          type="primary"
          v-if="
            (Alltable.length === 3 && key === 0) ||
            (Alltable.length === 2 && key === 0) ||
            Alltable.length === 1
          "
          >公文系统对接</el-button
        >
        <el-button
          @click="handleBtn(item, key, 'productSales')"
          size="mini"
          type="primary"
          v-if="
            (Alltable.length === 3 && key === 0) ||
            (Alltable.length === 2 && key === 0) ||
            Alltable.length === 1
          "
          >营销系统对接</el-button
        >
        <el-button
          size="mini"
          type="primary"
          @click="fourCheck(item)"
          v-if="showButtons.sxjc"
          >四性检测</el-button
        >
        <el-dropdown
          @command="(command) => handleBatch(command, item, key)"
          v-if="showButtons.plxgdh"
        >
          <el-button type="primary" size="mini" style="margin-left: 10px">
            批量修改<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="1">替换</el-dropdown-item>
            <el-dropdown-item command="2">修改</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <!-- <el-dropdown placement="top" trigger="click">
          <el-button size="mini" style="margin-left:10px">
            更多菜单<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <el-button size="mini" type="primary" @click="exportda(key)" v-if="showButtons.export">导出</el-button>
              <el-button size="mini" type="primary" @click="qualityCheck(key)"
                v-if="((Alltable.length===2 && key ===1) || Alltable.length===1) && showButtons.quality">质检</el-button>
              <el-button @click="inStore(item)" size="mini" type="primary"
                v-if="((Alltable.length===2 && key ===0) || Alltable.length===1) && showButtons.ware">入库</el-button>
              <el-button size="mini" type="primary" @click="fourCheck(item)"
                v-if="((Alltable.length===2 && key ===1) || Alltable.length===1)&& showButtons.four ">四性检测</el-button>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown> -->
      </div>
      <el-table
        highlight-current-row
        v-loading="item.tableLoading"
        size="mini"
        :data="item.tableData"
        fit
        border
        ref="tableForEach"
        :max-height="Alltable.length == 1 ? 650 : 400"
        @selection-change="handleSelectionChange($event, item)"
        @row-click="editCurrentApplicationApproval($event, item, key)"
        tooltip-effect="dark"
      >
        <el-table-column type="selection" width="55" align="center">
        </el-table-column>
        <el-table-column
          label="原文数量"
          width="90"
          align="center"
          fixed="left"
          v-if="
            (Alltable.length === 3 && key === 2) ||
            Alltable.length === 1 ||
            Alltable.length === 2
          "
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleContents(scope.row, item, key)"
              >{{
                scope.row.archive_file_num ? scope.row.archive_file_num : 0
              }}</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          v-for="(ele, index) in JSON.parse(item.tableShow)"
          :key="index"
          :prop="ele.columnName"
          :min-width="ele.width"
          :width="ele.width"
          :label="ele.columnChnName"
          align="center"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span v-if="ele.columnName === 'fonds_no'">
              {{
                (
                  fondsList.filter(
                    (f) => f.fondscode === scope.row[ele.columnName]
                  )[0] || {}
                ).codeName
              }}
            </span>
            <span v-if="ele.columnName !== 'fonds_no'">{{
              scope.row[ele.columnName]
            }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="handleCurrentChange($event, item, key)"
        @size-change="handleSizeChange($event, item, key)"
        layout="total, prev, pager, next, sizes"
        :page-size="item.pagination.pageSize"
        :page-sizes="[10, 20, 50, 100, 500, 1000]"
        :current-page="item.pagination.pageNum"
        :total="item.pagination.total"
      >
      </el-pagination>
    </div>
    <diaAdd
      ref="diaAdd"
      :tablekey="tablekey"
      :Alltable="Alltable"
      :fondsList="fondsList"
      :diaFlage="diaFlage"
      :title="title"
      :form="form"
      :ruleForm="ruleForm"
      @cancel="cancel"
      @sumbit="sumbit"
      :classTree="treeRow"
    />
    <dia-apply
      :visible="diaVisible"
      @cancel="cancel"
      ref="diaApply"
      @submit="applySubmit"
      :isApply="true"
    />
    <dia-report
      :visible="diaReport"
      @cancel="cancel"
      ref="diaReport"
      @submit="reportSubmit"
    />
    <dia-preview
      :visible="diaPreview"
      :pdfUrl="pdfUrl"
      @cancel="cancelPreview"
    />
    <dia-query
      :querySetData="querySetData"
      :visible="diaQuery"
      ref="diaQuery"
      @cancel="cancel"
      @submit="querySubmit"
    />
    <dia-quality
      :visible="diaQuality"
      ref="diaQuality"
      @cancel="cancel"
      @submit="qualitySubmit"
    />
    <!-- 表格 -->
    <drawer-tem
      ref="original"
      :treeRow="treeRow"
      :drawer="drawer"
      :actions="actions"
      :treeType="treeType"
      @handleClose="cancel"
      @getData="clickSearch"
    />
    <!-- 批量替换 -->
    <dia-batch
      ref="diaBatch"
      :visible="diaBatch"
      @onNext="onBatchNext"
      @replaceObject="replaceObject"
      @cancel="cancel"
    />
    <!-- 批量修改 -->
    <dia-edit-batch
      ref="diaEditBatch"
      :visible="diaEditBatch"
      @onNext="onBatchNext"
      @updateAllObject="updateAllObject"
      @cancel="cancel"
    />
  </div>
</template>
<script>
import {
  documentDocking,
  contractDocking,
  productSalesDocking,
} from "@/api/preFiling/preArchiveManagement/preFileApp.js";
import {
  message,
  clearObjValue,
  dateFormatT,
  dateFormat,
  getCurrentTime,
  downlaodxls,
  getCurrentTimes,
} from "@/utils/common";
import {
  getList,
  getOneTable,
  delectTable,
  submitApply,
  horizontalPdf,
  fourCheck,
  getSettingField,
  saveSettingField,
  insertBatch,
  getTableChnName,
  getPageBySequence,
  saveObject,
  querySettings,
  updateObject,
  deleteObjectAnjuan,
  exportExcel,
  replaceObject,
  updateAllObject,
} from "@/api/archives-management/fileManagement/notStoredArchives.js";
import DrawerTem from "@/components/DrawerTem";
import DiaApply from "@/components/DiaApply";
import diaReport from "./diaReport";
import diaPreview from "./diaPreview";
import diaQuery from "./diaQuery";
import diaQuality from "./diaQuality";
import localStronge from "@/api/localData";
import diaBatch from "@/components/DiaBatch";
import diaEditBatch from "@/components/DiaEditBath";
import diaAdd from "./diaAdd.vue";
import { antiShake } from "@/utils/antiShake.js"; // 防抖
import { selectUserDetails } from "@/api/user.js";

export default {
  props: {
    fondsList: {
      type: Array,
      default: () => [],
    },
    Alltable: {
      type: Array,
      default: () => [],
    },
    treeType: {
      type: String,
      default: () => "",
    },
    treeRow: {
      type: Object,
      default: () => {},
    },
    isDirSeqTree: {
      type: Boolean,
      default: () => false,
    },
    showButtons: {
      type: Object,
      default: () => {},
    },
  },
  components: {
    DiaApply,
    diaReport,
    diaPreview,
    diaQuery,
    diaQuality,
    diaAdd,
    DrawerTem,
    diaBatch,
    diaEditBatch,
  },
  data() {
    return {
      tableClickRowIndex: [1, 1, 1], // 每层点击当前表格第几行
      tableQuery: [], // 每层表格查询参数
      diaBatch: false, // 批量替换表单
      diaEditBatch: false, // 批量修改表单
      detailUserText: "",
      querySetData: {},
      nowTiem: getCurrentTimes(),
      //折叠状态
      isActive: false,
      //新增弹窗状态
      form: [],
      ruleForm: {},
      selectId: "",
      diaFlage: false,
      diaVisible: false, //申请表单
      diaReport: false, // 报表表单
      diaPreview: false, // 预览表单
      diaQuery: false, // 查询设置表单
      diaQuality: false, // 质检表单
      dirQuery: {}, // 目录序列树参数
      currentTableKey: "", // 根据key获取按钮对应表格的相关数据
      pdfUrl: "",
      title: "",
      sumbitTableName: "",
      sumbitTablekey: "",
      //原文弹窗
      actions: "",
      drawer: false, //原文弹窗状态
      tableOneClickRow: {},
      tableTwoClickRow: {},
      tablekey: null,
    };
  },
  methods: {
    async handleBtn(item, key, type) {
      switch (type) {
        case "contract": // 合同
          contractDocking()
            .then((res) => {
              if (res.code == 100) {
                this.$message({type:'success',message:`【合同系统对接】${res.msg}`,showClose:true,duration:0});
                this.clickSearch(key, 1, 0);
              } else {
                message("warning", res.msg, 2000);
              }
            })
            .catch((error) => {
              message("error", error, 2000);
            });
          break;
        case "file": // 文件
          documentDocking()
            .then((res) => {
              if (res.code == 100) {
                this.$message({type:'success',message:`【公文系统对接】${res.msg}`,showClose:true,duration:0});
                this.clickSearch(key, 1, 0);
              } else {
                message("warning", res.msg, 2000);
              }
            })
            .catch((error) => {
              message("error", error, 2000);
            });
          break;
        case "productSales": // 营销系统
          productSalesDocking()
            .then((res) => {
              if (res.code == 100) {
                this.$message({type:'success',message:`【营销系统对接】${res.msg}`,showClose:true,duration:0});
                this.clickSearch(key, 1, 0);
              } else {
                message("warning", res.msg, 2000);
              }
            })
            .catch((error) => {
              message("error", error, 2000);
            });
          break;
      }
    },
    // 获取批量修改单个档案详情
    getPieceData(key, refName = "diaBatch") {
      let pieceNum = this.tableClickRowIndex[key];
      let params = {
        ...this.tableQuery[key],
        page: pieceNum,
        limit: 1,
      };
      getOneTable(params).then((res) => {
        if (res.code === "100") {
          let result = res.body.list[0] || {};
          this.$refs[refName].formTwo = {
            ...this.$refs[refName].formTwo,
            ...result,
            archive_no: result.archive_no || result.folder_no || result.item_id,
          };
          this.$refs[refName].setBeforeVal(this.$refs[refName].form.desItem);
          this.$refs[refName].pieceNum = pieceNum;
        }
      });
    },
    handleBatch(command, item, key) {
      debugger;
      // 替换
      if (command === "1") {
        this.batchReplace(item, key);
      }
      // 修改
      if (command === "2") {
        this.batchEdit(item, key);
      }
    },
    // 批量修改
    batchEdit(ele, key) {
      console.log(1111);
      if (!ele.tableData.length) {
        message("warning", "暂无数据", 2000);
        return;
      }
      this.currentTableKey = key;
      //重置
      clearObjValue(this.$refs.diaEditBatch.form);
      clearObjValue(this.$refs.diaEditBatch.formTwo);
      this.$refs.diaEditBatch.formTwo.rangeType = "down";
      this.$refs.diaEditBatch.formTwo.offset = 0;
      this.$refs.diaEditBatch.total = ele.pagination.total;
      this.$refs.diaEditBatch.interfaceShow = ele.form;
      // this.$refs.diaEditBatch.tableKey = key
      let len = this.Alltable.length;
      if (key === len - 1) {
        this.$refs.diaEditBatch.enableField = "piece_no";
      }
      if (key === len - 2) {
        this.$refs.diaEditBatch.enableField = "year_folder_no";
      }
      if (key === len - 3) {
        this.$refs.diaEditBatch.enableField = "item_id";
      }
      this.getPieceData(key, "diaEditBatch");
      this.diaEditBatch = true;
    },
    // 批量替换
    batchReplace(ele, key) {
      if (!ele.tableData.length) {
        message("warning", "暂无数据", 2000);
        return;
      }
      this.currentTableKey = key;
      //重置
      clearObjValue(this.$refs.diaBatch.form);
      clearObjValue(this.$refs.diaBatch.formTwo);
      this.$refs.diaBatch.formTwo.rangeType = "down";
      this.$refs.diaBatch.formTwo.matchCase = false;
      this.$refs.diaBatch.total = ele.pagination.total;
      this.$refs.diaBatch.interfaceShow = ele.form;
      this.getPieceData(key);
      this.diaBatch = true;
    },
    // 查找下一条
    onBatchNext(valTwo, refName) {
      let key = this.currentTableKey;
      if (
        valTwo.rangeType !== "up" &&
        this.tableClickRowIndex[key] === this.$refs[refName].total
      ) {
        message("warning", "已经是最后一条了", 2000);
        return;
      }
      if (valTwo.rangeType === "up" && this.tableClickRowIndex[key] === 1) {
        message("warning", "已经是第一条了", 2000);
        return;
      }
      if (valTwo.rangeType === "up") {
        this.tableClickRowIndex[key] -= 1;
      } else {
        this.tableClickRowIndex[key] += 1;
      }
      this.getPieceData(key, refName);
    },
    // 批量替换
    replaceObject(val, valTwo, range) {
      let key = this.currentTableKey;
      const ele = this.Alltable.filter(
        (item, index) => this.currentTableKey === index
      )[0];
      let params = {
        commonMap: {
          funcTypeCode: this.treeType,
          tableName: ele.tableName,
        },
        fieldValueMap: {
          [val.desItem]: val.replaceTo,
          // archive_flag: "已组卷"
        },
        findWhat: val.findWhat,
        matchCase: valTwo.matchCase ? 1 : 0,
        conditionMap: {
          ...this.tableQuery[key].conditionMap,
        },
        orderBy: "order by  id  desc",
        page: range.page,
        limit: range.limit,
      };
      replaceObject(params).then((res) => {
        if (res.code === "100") {
          message("success", "替换成功", 2000);
          this.clickSearch(key, 1, 0);
          this.tableClickRowIndex = [1, 1, 1];
        }
      });
    },
    // 批量修改
    updateAllObject(val, valTwo, range) {
      if (valTwo.offset === 0) {
        message("warning", "请输入偏移量", 2000);
        return;
      }
      let key = this.currentTableKey;
      const ele = this.Alltable.filter(
        (item, index) => this.currentTableKey === index
      )[0];
      let params = {
        commonMap: {
          funcTypeCode: this.treeType,
          tableName: ele.tableName,
        },
        fieldValueMap: {
          [val.desItem]: "",
        },
        classId: this.treeRow.id,
        offset: valTwo.offset,
        conditionMap: {
          ...this.tableQuery[key].conditionMap,
        },
        orderBy: "order by  id  desc",
        page: range.page,
        limit: range.limit,
      };
      updateAllObject(params).then((res) => {
        if (res.code === "100") {
          message("success", "修改成功", 2000);
          this.clickSearch(key, 1, 0);
          this.tableClickRowIndex = [1, 1, 1];
        }
      });
    },
    // 根据id查询用户信息
    getUserDetail() {
      selectUserDetails({ userId: sessionStorage.getItem("userid") })
        .then((res) => {
          let result = res.body.userDetails;
          this.detailUserText = result;
        })
        .catch((error) => {
          message("warning", error, "4000");
        });
    },
    //入库
    inStore(ele) {
      if (!ele.selectTable.length) {
        message("warning", "请选择要入库的档案", 3000);
        return;
      }
      this.$refs.diaApply.form = {
        applyUserId: sessionStorage.getItem("userid"),
        applyUserName: this.detailUserText,
        applyTime: getCurrentTime(),
        rec_nums: ele.selectTable.length, //申请档案数量
        originalTextNums: ele.selectTable.reduce(
          (total, item) => total + item.archive_file_num,
          0
        ), // 原文数量
        recIds: ele.selectTable.map((item) => item.id).join(","), // 勾选数据id逗号拼接
        applyReason: "",
        expressType: "14",
        tableName: ele.tableName, // 表名
        tableType: this.treeType,
        className: this.treeRow.className, // 门类名
        classId: this.treeRow.id,
      };
      this.diaVisible = true;
    },
    // 提交审批
    applySubmit(val) {
      submitApply(val).then((res) => {
        if (res.code === "100") {
          message("success", "提交申请成功", 2000);
          this.diaVisible = false;
          // this.$emit('handleNodeClick', this.treeRow)
          this.clickSearch(this.currentTableKey, 1, 0);
        }
      });
    },
    // 生成报表
    createReport(key) {
      this.diaReport = true;
      this.$refs.diaReport.radioType = "";
      this.currentTableKey = key;
    },
    //归档申请
    application(key) {
      this.currentTableKey = key;
      this.Alltable.forEach((ele, index) => {
        if (key === index) {
          if (!ele.selectTable.length) {
            message("warning", "请先选择要归档的档案", 2000);
            return;
          }

          this.$refs.diaApply.form = {
            applyUserId: sessionStorage.getItem("userid"),
            applyUserName: this.detailUserText,
            applyTime: getCurrentTime(),
            rec_nums: ele.selectTable.length, //申请档案数量
            originalTextNums: ele.selectTable.reduce(
              (total, item) => total + item.archive_file_num,
              0
            ), // 原文数量
            recIds: ele.selectTable.map((item) => item.id).join(","), // 勾选数据id逗号拼接
            applyReason: "",
            expressType: "16",
            tableName: ele.tableName, // 表名
            tableType: this.treeType,
            className: this.treeRow.className, // 门类名
            classId: this.treeRow.id,
          };
          this.diaVisible = true;
        }
      });
    },
    // 生成报表
    reportSubmit(type) {
      const ele = this.Alltable.filter(
        (item, index) => this.currentTableKey === index
      )[0];
      const params = {
        tableName: ele.tableName,
        ids: ele.selectTable.length
          ? ele.selectTable.map((item) => item.id).join(",")
          : "",
        mode: 1, // 未入库
        type,
      };
      horizontalPdf(params).then((res) => {
        if (res.code === "100") {
          message("success", "生成报表成功", 2000);
          this.showPdf(res.body.fileName);
          this.diaPreview = true;
        }
      });
    },
    // pdf预览
    showPdf(fileName) {
      const prefix =
        process.env.NODE_ENV === "development"
          ? "http://" +
            localStronge.getServiceip().ip +
            ":" +
            localStronge.getServiceip().host
          : "http://" + window.location.host;
      this.pdfUrl =
        prefix + "/point-strategy/v/ureport/showPdf?fileName=" + fileName;
    },
    // 四性检测
    fourCheck(ele) {
      if (ele.tableData.length == 0) {
        message("warning", "暂无数据无法进行四性检测", 3000);
        return;
      }
      const params = {
        classId: this.treeRow.id,
        checkLink: "GD", // 未入库
        entityId: ele.entityId,
        fondscode: ele.tableData[0].fonds_no, // 全宗号
      };
      fourCheck(params).then((res) => {
        if (res.code === "100") {
          this.showPdf(res.body.fileName);
          this.diaPreview = true;
        }
      });
    },
    // 点击目录序列树赋值dirQuery参数, 用于查询
    dirNodeClick(value, key) {
      const valueArr = value.split(",");
      Object.keys(this.dirQuery).forEach((dir, index) => {
        this.dirQuery[dir] = valueArr[index];
      });
      this.clickSearch(key, 1, 0);
    },
    // 查询设置
    getQuerySet(ele) {
      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]] = "";
          });
        }
      });
    },
    // 查询设置
    querySet(ele, key) {
      /* 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.diaQuery = true;
          }
        }); */
      this.getQuerySet(ele);
      this.diaQuery = true;
      this.currentTableKey = key;
    },
    // 查询设置-保存
    querySubmit(val) {
      const ele = this.Alltable.filter(
        (item, index) => this.currentTableKey === index
      )[0];
      const params = {
        entityId: ele.entityId,
        dataKeys: val.fields,
        type: val.type,
        userId: parseInt(sessionStorage.getItem("userid")),
      };
      if (val.type === 1) {
        saveSettingField(params).then((res) => {
          if (res.code === "100") {
            message("success", "保存成功", 2000);
            this.diaQuery = false;
          }
        });
      } else {
        querySettings(params).then((res) => {
          message("success", "保存成功", 2000);
          this.diaQuery = false;
          this.$emit("handleNodeClick", this.treeRow);
        });
      }
    },
    // 目录序列树
    getDirTree(key) {
      this.$emit("triggerTree", key); // 切换左侧树
    },
    // 点击目录序列树节点
    /* clickDirSearch(params, key) {
        this.Alltable.forEach((item, index) => {
          if (key === index) {
            params.limit = item.pagination.pageSize;
            // params.page = item.pagination.pageNum;
            getPageBySequence(params).then(res => {
              if (res.success) {
                item.tableData = res.body.list;
                item.pagination.total = res.body.total;
              }
            });
          }
        })
      }, */
    //导出
    exportda(key) {
      const ele = this.Alltable.filter((item, index) => key === index)[0];
      if (!ele.selectTable.length) {
        message("warning", "请先选择档案", 3000);
        return;
      }
      let data = {
        ids: ele.selectTable.length
          ? ele.selectTable.map((item) => item.id).join(",")
          : "",
        funcTypeCode: this.treeType,
        tableName: ele.tableName,
      };
      exportExcel(data).then((res) => {
        downlaodxls(res, `导出文件${this.nowTiem}`);
      });
    },
    // 质检
    qualityCheck(key) {
      this.currentTableKey = key;
      const ele = this.Alltable.filter(
        (item, index) => this.currentTableKey === index
      )[0];
      if (!ele.selectTable.length) {
        // 页面切换到质检列表
        this.$store.commit("qualityCheck/SET_PAGE_TYPE", 2);
        this.$store.commit("qualityCheck/SET_ENTITY_ID", ele.entityId);
      } else {
        const params = {
          entityId: ele.entityId,
        };
        this.$refs.diaQuality.form.batchName = "";
        this.diaQuality = true;
        getTableChnName(params).then((res) => {
          if (res.code === "100") {
            this.$refs.diaQuality.form.tableChnName =
              res.body.resultMap.tableChnName;
          }
        });
      }
    },
    // 质检保存
    qualitySubmit(val) {
      const ele = this.Alltable.filter(
        (item, index) => this.currentTableKey === index
      )[0];
      const selectLen = ele.selectTable.length;
      const imageNums = ele.tableData.reduce(
        (total, item) => total + item.archive_file_num,
        0
      );
      const data = {
        batchName: val.batchName,
        tableName: ele.tableName,
        tableChnName: val.tableChnName,
        dataLinkNum: selectLen, // 勾选的表格数量
        inspectionNums: selectLen,
        recordNums: selectLen,
        imageNums, // 勾选的原文数量之和
        recNums: selectLen + imageNums,
        createdBy: sessionStorage.getItem("username"),
      };
      const params = {
        recids: ele.selectTable.map((item) => item.id).join(","),
      };
      insertBatch(data, params).then((res) => {
        if (res.code === "100") {
          message("success", "新增批次成功", 2000);
          this.diaQuality = false;
          // 清除勾选项，防止回到页面表格未勾选，而数据selectTable不为空
          this.Alltable.filter((item, index) => {
            if (this.currentTableKey === index) {
              item.selectTable = [];
            }
          });
          // 页面切换到质检列表
          this.$store.commit("qualityCheck/SET_PAGE_TYPE", 2);
          this.$store.commit("qualityCheck/SET_ENTITY_ID", ele.entityId);
        }
      });
    },
    Warehousing(ele) {
      if (!ele.selectTable.length) {
        message("warning", "请选择要入库的档案", 3000);
        return;
      }
      let val = JSON.parse(JSON.stringify(ele.selectTable[0]));
      delete val.id;
      this.form.forEach((item) => {
        if (item.ctype === "datetime") {
          val[item.fieldName] = val[item.fieldName]
            ? dateFormat(val[item.fieldName])
            : "";
        } else if (item.ctype === "datetimerange") {
          val[item.fieldName] = val[item.fieldName]
            ? dateFormatT(val[item.fieldName]).start +
              "~" +
              dateFormatT(val[item.fieldName]).end
            : "";
        }
      });
      let params = {
        commonMap: {
          funcTypeCode: "",
          tableName: ele.tableName,
        },
        fieldValueMap: val,
        conditionMap: {},
      };
      saveObject(params)
        .then((res) => {
          message("success", "入库成功", 2000);
          this.diaFlage = false;
          // this.clickSearch(this.sumbitTablekey, 1, 0);
        })
        .then((res) => {
          let data = {
            ids: ele.selectTable[0].id,
            tableName1: ele.tableName,
          };
          deleteObjectAnjuan(data).then((res) => {
            this.$emit("handleNodeClick", this.treeRow);
          });
        });
    },

    //搜索按钮集合  (循环中的每个对象要执行的方法)
    clickSearch(key, type, stratType) {
      this.tableClickRowIndex.forEach((num, index) => {
        if (index === key) {
          this.tableClickRowIndex[index] = 1; // 查询的表格批量修改的第几条重置为1
        }
      });
      this.tablekey = key;
      this.selectId = "";
      //key 是匹配对象
      // type等于。1是搜索。2是重置。3是折叠按钮。4是添加。5是修改。6是删除
      //stratType 是判断是否是第一次加载 1是首次加载
      this.Alltable.forEach((item, index) => {
        if (key === index) {
          let params = {
            commonMap: {
              funcTypeCode: this.treeType,
              tableName: item.tableName,
            },
            conditionMap: {},
            limit: "10",
            page: "1",
          };
          if (key === 1) {
            params.conditionMap["pid"] = this.tableOneClickRow.id;
          }
          if (key === 2) {
            params.conditionMap["pid"] = this.tableTwoClickRow.id;
          }
          // return
          switch (type) {
            case 1: //查询
              if (
                this.sumbitTablekey &&
                key &&
                this.Alltable[key - 1].selectTable[0]
              ) {
                params.conditionMap.pid =
                  this.Alltable[key - 1].selectTable[0].id;
              }
              item.tableLoading = true;
              params.limit = item.pagination.pageSize;
              params.page = item.pagination.pageNum;
              params.conditionMap.archive_flag = "预归档未完成";
              if (stratType) {
                JSON.parse(item.interfaceQuery).forEach((ele) => {
                  params.conditionMap[ele.fieldName] = "";
                });
              } else {
                item.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
                      ? `like${ele.value}`
                      : ele.value;
                  }
                });
              }
              // 目录序列树参数
              if (this.isDirSeqTree) {
                params.conditionMap = {
                  ...params.conditionMap,
                  ...this.dirQuery,
                };
              }

              this.tableQuery[key] = params; // 记录查询参数，用于批量修改
              getOneTable(params)
                .then((res) => {
                  item.tableData = res.body.list;
                  item.pagination.total = res.body.total;
                  item.tableLoading = false;
                  if (item.selectTable.length) {
                    let arr = [];
                    res.body.list.forEach((ese) => {
                      item.selectTable.forEach((ele) => {
                        if (ese.id === ele.id) {
                          arr.push(ese);
                        }
                      });
                    });
                    item.selectTable = arr;
                  }
                })
                .catch((err) => {
                  item.tableLoading = false;
                });
              break;
            case 2: //重置
              item.search.forEach((ele) => {
                ele.value = "";
              });
              break;
            case 3: //折叠
              item.isShow = !item.isShow;
              break;
            case 4: //添加
              //多层
              if (
                this.sumbitTablekey &&
                key &&
                this.Alltable[key - 1].selectTable[0]
              ) {
                params.conditionMap.pid =
                  this.Alltable[key - 1].selectTable[0].id;
              }
              let flage = false;
              this.title = "新增";
              this.sumbitTableName = item.tableName;
              this.sumbitTablekey = key;
              //判断是简化还是传统
              if (key === 1) {
                this.Alltable.forEach((ele, key) => {
                  if (!key && !ele.selectTable.length) {
                    flage = 1;
                  }
                  if (!key && ele.selectTable.length > 1) {
                    flage = 2;
                  }
                  if (!key && ele.selectTable.length === 1) {
                    this.selectId = ele.selectTable[0].id;
                  }
                });
                if (this.Alltable.length === 2) {
                  if (flage === 1) {
                    message("warning", "请先选择一条案卷", 2000);
                    return;
                  }
                  if (flage === 2) {
                    message("warning", "请勿多选案卷", 2000);
                    return;
                  }
                  this.form = JSON.parse(JSON.stringify(item.form));
                  this.ruleForm = JSON.parse(JSON.stringify(item.ruleForm));
                  for (let keys in this.Alltable[0].selectTable[0]) {
                    for (let keyt in this.ruleForm) {
                      if (keys === keyt && keys != "maintitle") {
                        this.ruleForm[keyt] =
                          this.Alltable[0].selectTable[0][keys];
                      }
                    }
                  }
                  setTimeout(() => {
                    this.$refs.diaAdd.focusdh();
                  }, 0);
                } else {
                  if (flage === 1) {
                    message("warning", "请先选择一条项目", 2000);
                    return;
                  }
                  if (flage === 2) {
                    message("warning", "请勿多选项目", 2000);
                    return;
                  }
                  this.form = JSON.parse(JSON.stringify(item.form));
                  this.ruleForm = JSON.parse(JSON.stringify(item.ruleForm));
                  for (let keys in this.Alltable[0].selectTable[0]) {
                    for (let keyt in this.ruleForm) {
                      if (keys === keyt && keys != "maintitle") {
                        this.ruleForm[keyt] =
                          this.Alltable[0].selectTable[0][keys];
                      }
                    }
                  }
                }
              } else if (key === 0) {
                this.form = JSON.parse(JSON.stringify(item.form));
                this.ruleForm = JSON.parse(JSON.stringify(item.ruleForm));
                this.form.forEach((item) => {
                  item.value = "";
                });
              } else if (key === 2) {
                if (!this.Alltable[1].selectTable.length) {
                  message("warning", "请先选择一条案卷", 2000);
                  return;
                }
                if (this.Alltable[1].selectTable.length > 1) {
                  message("warning", "请勿多选案卷", 2000);
                  return;
                }
                this.selectId = this.Alltable[1].selectTable[0].id;
                this.form = JSON.parse(JSON.stringify(item.form));
                this.ruleForm = JSON.parse(JSON.stringify(item.ruleForm));
                for (let keys in this.Alltable[1].selectTable[0]) {
                  for (let keyt in this.ruleForm) {
                    if (keys === keyt && keys != "maintitle") {
                      this.ruleForm[keyt] =
                        this.Alltable[1].selectTable[0][keys];
                    }
                  }
                }
                setTimeout(() => {
                  this.$refs.diaAdd.focusdh();
                }, 0);
              }
              this.$refs.diaAdd.automaticData.id = "";
              this.diaFlage = true;
              break;
            case 5: //修改
              this.ruleForm = {};
              if (!item.selectTable.length) {
                message("warning", "请先选择要修改的对象", 2000);
                return;
              }
              if (item.selectTable.length > 1) {
                message("warning", "修改的对象只能选择一个", 2000);
                return;
              }
              this.$refs.diaAdd.automaticData.id = item.selectTable[0].id;
              this.title = "修改";
              this.sumbitTableName = item.tableName;
              this.selectId = item.selectTable[0].id;
              this.sumbitTablekey = key;
              item.form.forEach((ele) => {
                for (let info in item.selectTable[0]) {
                  if (info === ele.fieldName) {
                    this.$set(this.ruleForm, ele.fieldName, "");
                    if (ele.ctype === "datetimerange") {
                      this.ruleForm[ele.fieldName] = [];
                      this.ruleForm[ele.fieldName][0] =
                        item.selectTable[0][info].split("~")[0];
                      this.ruleForm[ele.fieldName][1] =
                        item.selectTable[0][info].split("~")[1];
                    } else {
                      this.ruleForm[ele.fieldName] = item.selectTable[0][info];
                    }
                  }
                }
              });
              this.form = JSON.parse(JSON.stringify(item.form));
              let data = {
                classId: this.treeRow.id,
                fondscode: this.ruleForm.fonds_no,
                year: this.ruleForm.filing_year,
              };
              getList(data).then((res) => {
                if (!res.body.list.length) {
                  // message("warning", "请先配置当前年度的档号规则", 3000)
                  this.$refs.diaAdd.referenceList = [];
                }
                this.$refs.diaAdd.referenceList = res.body.list.filter(
                  (ele) =>
                    ele.segmentName != "fonds_no" &&
                    ele.segmentName != "filing_year"
                );
              });
              this.diaFlage = true;
              break;
            case 6: //删除
              if (
                this.sumbitTablekey &&
                key &&
                this.Alltable[key - 1].selectTable[0]
              ) {
                params.conditionMap.pid =
                  this.Alltable[key - 1].selectTable[0].id;
              }
              let arr = item.selectTable.map((ele) => ele.id);

              if (!arr.length) {
                message("warning", "请选择要删除的数据", 3000);
                return;
              }
              if (key) {
                params.conditionMap.id = arr.join(",");
                this.$alert("是否确认删除该数据？", "提示", {
                  confirmButtonText: "确定",
                  type: "warning",
                  callback: async (action) => {
                    if (action === "cancel") {
                      return false;
                    }

                    let val = JSON.parse(JSON.stringify(item.selectTable[0]));
                    delete val.id;
                    let data = {
                      commonMap: {
                        funcTypeCode: this.treeType + "_trash",
                        tableName: item.tableName,
                      },
                      fieldValueMap: val,
                      conditionMap: {},
                    };
                    // saveObject(data).then((res) => {
                    delectTable(params).then((res) => {
                      message("success", "删除成功", 3000);
                      this.clickSearch(key, 1, 1);
                    });
                    // })
                  },
                });
              } else {
                let data = {
                  ids: arr.join(","),
                  tableName1: item.tableName,
                };
                if (this.Alltable.length === 2) {
                  data.tableName2 = this.Alltable[1].tableName;
                }
                this.$alert("是否确认删除该数据？", "提示", {
                  confirmButtonText: "确定",
                  type: "warning",
                  callback: async (action) => {
                    if (action === "cancel") {
                      return false;
                    }
                    let val = JSON.parse(JSON.stringify(item.selectTable[0]));
                    delete val.id;
                    let params = {
                      commonMap: {
                        funcTypeCode: this.treeType + "_trash",
                        tableName: item.tableName,
                      },
                      fieldValueMap: val,
                      conditionMap: {},
                    };
                    saveObject(params).then((res) => {
                      deleteObjectAnjuan(data).then((res) => {
                        message("success", "删除成功", 3000);
                        this.clickSearch(key, 1, 1);
                      });
                    });
                  },
                });
              }
              break;
          }
        }
      });
    },
    //表格获取每行
    handleSelectionChange(val, item) {
      item.selectTable = JSON.parse(JSON.stringify(val));
    },
    //表格点击每行事件
    editCurrentApplicationApproval(val, item, key) {
      this.currentTableKey = key;
      this.tableClickRowIndex[key] =
        (item.pagination.pageNum - 1) * item.pagination.pageSize + val.index;
      if (key === 0) {
        this.tableOneClickRow = val;
        if (this.Alltable.length === 3) {
          this.Alltable[2].tableData = [];
        }
      } else if (key === 1) {
        this.tableTwoClickRow = val;
      }
      this.$refs.tableForEach[key].clearSelection();
      this.$refs.tableForEach[key].toggleRowSelection(val);
      this.clickSearch(key + 1, 1, 0);
    },
    //原文按钮
    handleContents(val, item, key) {
      this.$refs.original.archiveNum = val.archive_file_num
        ? val.archive_file_num
        : 0;
      this.$refs.original.oriTable = item;
      this.$refs.original.orirow = val;
      this.$refs.original.orikey = key;
      let params = {
        commonMap: {
          funcTypeCode: this.treeType + "_file",
          tableName: item.tableName,
        },
        conditionMap: {
          rec_id: val.id,
          file_status: 1,
        },
        orderBy: "order by  page_no  asc",
        limit: "1000",
        page: "1",
      };
      this.$refs.original.params = params;
      const prefix =
        process.env.NODE_ENV === "development"
          ? "http://" +
            localStronge.getServiceip().ip +
            ":" +
            localStronge.getServiceip().host
          : "http://" + window.location.host;
      this.actions =
        prefix +
        "/point-strategy/v/ajjnOriginBatch/uploadSimpleFilesAnjuan?recId=" +
        val.id +
        "&fondscode=" +
        val.fonds_no +
        "&tableName=" +
        item.tableName;
      getOneTable(params)
        .then((res) => {
          //原文表
          this.$refs.original.tableDataOrigin = res.body.list;
        })
        .then((res) => {
          params.conditionMap.file_status = 2;
          getOneTable(params).then((res) => {
            //原文回收站表
            this.$refs.original.backData = res.body.list;
          });
        });
      this.$refs.original.picUrl = "";
      this.$refs.original.activeName = "1";
      this.drawer = true;
    },
    //每页换个数
    handleSizeChange(val, item, key) {
      item.pagination.pageSize = val;
      item.pagination.pageNum = 1;
      this.clickSearch(key, 1, 0);
    },
    //换页
    handleCurrentChange(val, item, key) {
      item.pagination.pageNum = val;
      this.clickSearch(key, 1, 0);
    },
    //cancel
    cancel() {
      this.diaFlage = false;
      this.drawer = false;
      this.diaReport = false;
      this.diaQuery = false;
      this.diaQuality = false;
      this.diaVisible = false;
      this.diaBatch = false;
      this.diaEditBatch = false;
    },
    cancelPreview() {
      this.diaPreview = false;
    },
    //保存或修改
    sumbit: antiShake(function (val) {
      this.form.forEach((item) => {
        if (item.ctype === "datetime") {
          val[item.fieldName] = val[item.fieldName]
            ? dateFormat(val[item.fieldName])
            : "";
        } else if (item.ctype === "datetimerange") {
          val[item.fieldName] = val[item.fieldName]
            ? dateFormatT(val[item.fieldName]).start +
              "~" +
              dateFormatT(val[item.fieldName]).end
            : "";
        }
      });
      let params = {
        commonMap: {
          funcTypeCode: this.treeType,
          tableName: this.sumbitTableName,
        },
        fieldValueMap: {
          ...val,
          archive_flag: "预归档未完成",
        },
        conditionMap: {},
      };

      if (this.title === "新增") {
        if (this.sumbitTablekey) {
          params.fieldValueMap.pid = this.selectId;
        }
        saveObject(params).then((res) => {
          message("success", "新增成功", 2000);
          this.diaFlage = false;
          this.clickSearch(this.sumbitTablekey, 1, 0);
        });
      } else {
        params.conditionMap.id = this.selectId;
        updateObject(params).then((res) => {
          message("success", "修改成功", 2000);
          this.diaFlage = false;
          this.clickSearch(this.sumbitTablekey, 1, 0);
        });
      }
    }),
  },
  created() {
    this.getUserDetail();
  },
};
</script>
<style lang="scss" scoped>
.wholeTable {
  margin-bottom: 10px;

  .searcAllflase {
    background-color: #fff;
    overflow: hidden;
    border-radius: 5px;
    height: 46px;
    text-align: left;

    .search {
      background-color: #fff;
      height: 30px;
      line-height: 30px;
      display: flex;
      margin: 8px 0px;
    }
  }

  .searcAll {
    text-align: left;
    background-color: #fff;
    border-radius: 5px;
    overflow: hidden;

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

  .searchBtn {
    height: 35px;
    text-align: right;
    padding: 5px 10px 10px 0;
    background-color: #fff;
  }

  .btnClass {
    background-color: #fff;
    // padding-left: 10px;
    margin-bottom: 5px;
    border-radius: 5px;
    text-align: left;
  }
}

::v-deep {
  .el-table__body tr.current-row > td {
    background-color: rgba($color: #e9f2ff, $alpha: 1);
    color: #000000;
    font-weight: 600;
  }
}
</style>
