<template>
<!-- 右侧table组件 -->
  <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=" text-align: left">{{ 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" :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 @click="querySet(item,key)" size="mini" type="primary">查询设置</el-button>
      </div>
      <el-table :style="{'--color':rowColor}" table-layout="auto" highlight-current-row v-loading="item.tableLoading" size="mini" :data="item.tableData" fit border
        ref="tableForEach" :max-height="Alltable.length==1?1000:400" :row-class-name="tableRowClassName"
        @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="120" 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 sortable 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>
    <dia-query :querySetData="querySetData" :visible="diaQuery" ref="diaQuery" @cancel="cancel" @submit="querySubmit" />
    <!-- 表格-特定 -->
    <drawer-tem ref="original" :isDistinction="isDistinction" :treeRow="treeRow" :drawer='drawer' :actions='actions' :treeType='treeType'
      @handleClose="cancel" @getData="clickSearch" />
   
  </div>
</template>
<script>
import {
  message,
  clearObjValue,
  dateFormatT,
  dateFormat,
  getCurrentTime,
  downlaodxls,
  getCurrentTimes,
  retentionList,
  removeEmpty
} from "@/utils/common";
import {
  getOneTable,
  secondaryQuery,
  delectTable,
  submitApply,
  selectUreportList,
  reportPdf,
  horizontalPdf,
  fourCheck,
  getSettingField,
  saveSettingField,
  querySettings,
  insertBatch,
  getTableChnName,
  getPageBySequence,
  saveObject,
  updateObject,
  updateObject2,
  deleteObjectAnjuan,
  replaceObject,
  updateAllObject,
  exportExcel,
  deleteData,
  downloadExcelToken
} from "@/api/archives-management/fileManagement/notStoredArchives.js";
import {selectDueArchive} from "@/api/archives-management/fileManagement/expirationReminder.js";
import DrawerTem from "./DrawerTem/index.vue";
import diaQuery from "./diaQuery";
import localStronge from "@/api/localData";
import { queryReportName, queryEntityLevel } from "@/api/reportTemplate";
import { getList } from "@/api/archives-management/fileManagement/notStoredArchives";
import { URL_PREFIX } from "@/utils/url-prefix";
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: () => {},
    },
    treeData: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    diaQuery,
    DrawerTem,
  },
  data() {
    return {
      rowColor:'#f60',
      isShowBatchIdentify:false,
      isPageOneFlag:true, // 查询第一页
      currentSearchType:null,
      currentSearchFlag:{
        date:null
      }, // 标记当前查询是二次还是一次查询''one'
      detailUserText:'',
      nowTiem: getCurrentTimes(),
      //折叠状态
      isActive: false,
      //新增弹窗状态
      form: [],
      ruleForm: {},
      selectId: "",
      diaFlage: false,
      diaBatch: false, // 批量替换表单
      diaEditBatch: false, // 批量修改表单
      diaVisible: false, //申请表单
      diaReport: false, // 报表表单
      diaPreview: false, // 预览表单
      diaQuery: false, // 查询设置表单
      dirQuery: {}, // 目录序列树参数
      diaQuality: false, // 质检表单
      currentTableKey: "", // 根据key获取按钮对应表格的相关数据
      pdfUrl: "",
      title: "",
      sumbitTableName: "",
      sumbitTablekey: "",
      // 批量修改
      tableClickRowIndex: [1, 1, 1], // 每层点击当前表格第几行
      tableQuery: [], // 每层表格查询参数
      //原文弹窗
      actions: "",
      drawer: false, //原文弹窗状态
      tableOneClickRow: {},
      tableTwoClickRow: {},
      tablekey: null,
      //修图状态
      RevisionStatus: false,
      Revisionparams: {},
      querySetData: {},
      stateMent: false,
      multipleSelection: [],
      isDistinction:false, // 如果是false 表示是未入库,true已入库
      countA:0,
      countB:0,
    };
  },
  watch:{
    'currentSearchFlag.date':{
      handler(newVal,oldVal){
        if(this.currentSearchType=='one'){
          this.countB = 0;
          if(this.countA == 0){
            this.isPageOneFlag = true;
          }else{
            this.isPageOneFlag = false;
          }
        }else{
          this.countA = 0;
          if(this.countB == 0){
            this.isPageOneFlag = true;
          }else{
            this.isPageOneFlag = false;
          }
        }
      },
      deep:true
    },
  },
  methods: {
    reset(fileType, rname, treeRow) {
      this.showBaoBiaoPdf(fileType, rname, 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;
        }
      });
    },
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex + 1;
      let data = new Date().getFullYear();
      let jsData = Number(row.filing_year) + retentionList[row.retention];
      if (retentionList[row.retention] != null) {
        if (jsData - data <= 1) {
          return "success-row";
        }
      }
      return "";
    },
    // 根据id查询用户信息
    getUserDetail(){
      selectUserDetails({userId:sessionStorage.getItem('userid')}).then((res)=>{
        let result = res.body.userDetails;
        this.detailUserText = result;
      }).catch((error)=>{
        message("warning",error,'4000')
      })
    },
    // 查找下一条
    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);
    },
    // 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;
    },
    // 查询设置
    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, key) {
      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;
              }
            });
          }
        })
      }, */
    // 查询参数
    getSearchParam(search) {
      let searchParam = {};
      search.forEach((item) => {
        if (item.value !== "" && item.value !== undefined) {
          if (item.ctype === "datetime") {
            searchParam[item.fieldName] = dateFormat(item.value);
          } else if (item.ctype === "datetimerange") {
            searchParam[item.fieldName] = dateFormatT(item.value);
          } else {
            searchParam[item.fieldName] = item.value;
          }
        }
      });
      return JSON.stringify(searchParam) === "{}" ? "" : searchParam;
    },
    
    //导出
    exportda(key) {
      const ele = this.Alltable.filter((item, index) => key === index)[0];
      let data = {
        funcTypeCode: this.treeType,
        tableName: ele.tableName,
      };
      if (ele.selectTable.length) {
        data.ids = ele.selectTable.map((item) => item.id).join(",");
      } else {
        let searchParam = this.getSearchParam(ele.search);
        // 目录序列树参数
        if (this.isDirSeqTree) {
          searchParam = {
            ...searchParam,
            ...this.dirQuery,
          };
        }
        if (searchParam) {
          data = {
            ...data,
            map: JSON.stringify(searchParam),
          };
        }
      }
      let str = "";
      for (let key in data) {
        str = str + key + "=" + data[key] + "&";
      }      
      // window.location.href =
      //   URL_PREFIX + "/point-strategy/v/fileManage/downloadExcel?" + str;
      downloadExcelToken(data).then(res => {
        downlaodxls(res, `导出文件${this.nowTiem}`)
      })
    },

    //搜索按钮集合  (循环中的每个对象要执行的方法)
    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",
            orderBy: "order by  id  desc",
          };
          if (key === 1) {
            params.conditionMap["pid"] = this.tableOneClickRow.id;
          }
          if (key === 2) {
            params.conditionMap["pid"] = this.tableTwoClickRow.id;
          }
          // return
          switch (type) {
            case 1: //查询
            this.currentSearchType = 'one';
            this.currentSearchFlag.date = Date.now();
                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 = this.countA==0?1:item.pagination.pageNum;
                  item.pagination.pageNum = params.page;
                  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;
                        params.conditionMap[ele.fieldName] = ele.value
                        ? `like${ele.value}`
                        : ele.value;
                      
                    }
                  });
                }
                // 目录序列树参数
                if (this.isDirSeqTree) {
                  params.conditionMap = {
                    ...params.conditionMap,
                    ...this.dirQuery,
                  };
                }
                
                this.tableQuery[key] = params; // 记录查询参数，用于批量修改
                
                selectDueArchive(params).then((res) => {
                    // 高亮行颜色
                    this.rowColor = res.body.color;
                    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;
                  });
                  this.countA++;
              break;
            case 2: //重置
              item.search.forEach((ele) => {
                ele.value = "";
              });
              break;
            case 3: //折叠
              item.isShow = !item.isShow;
              break;
          }
        }
      });
    },
    //表格获取每行
    handleSelectionChange(val, item) {
      this.multipleSelection = val;
      item.selectTable = JSON.parse(JSON.stringify(val));
    },
    //表格点击每行事件
    editCurrentApplicationApproval(val, item, 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);
    },
    //修图
    RevisionClick(val, item) {
      this.Revisionparams = {
        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",
      };
      getOneTable(this.Revisionparams).then((res) => {
        //原文表
        this.$refs.revision.tableData = res.body.list;
        this.$refs.revision.src_1 = "";
        this.$refs.revision.src_2 = "";
        this.RevisionStatus = true;
      });
    },
    //原文按钮
    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.musicSrc = "";
      this.$refs.original.videoSrc = "";
      this.$refs.original.activeName = "1";
      this.$refs.original.checkFileImgNum();
      this.drawer = true;
    },
    //每页换个数
    handleSizeChange(val, item, key) {
      item.pagination.pageSize = val;
      item.pagination.pageNum = 1;
      // 区分是否是二次查询
      if(this.currentSearchType == 'one'){
        this.clickSearch(key, 1, 0);
      }else{
        this.clickSearch(key, 7, 0);
      }
    },
    //换页
    handleCurrentChange(val, item, key) {
      // 区分是否是二次查询
      if(this.currentSearchType == 'one'){
          if(!!this.isPageOneFlag){
            item.pagination.pageNum = 1;
          }else{
            item.pagination.pageNum = val;
          }
          this.clickSearch(key, 1, 0);
          
      }else{
        
          if(!!this.isPageOneFlag){
            item.pagination.pageNum = 1;
          }else{
            item.pagination.pageNum = val;
          }
          this.clickSearch(key, 7, 0);
      }
      
    },
    //cancel
    cancel() {
      this.diaFlage = false;
      this.drawer = false;
      this.diaBatch = false;
      this.diaEditBatch = false;
      this.diaReport = false;
      this.diaQuery = false;
      this.diaQuality = false;
      this.diaVisible = false;
      this.RevisionStatus = false;
      this.isShowBatchIdentify = false;
    },
    cancelPreview() {
      this.diaPreview = false;
    },

  },
  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 .success-row {
    background: var(--color);
    font-weight: 600;
    color: rgb(0, 0, 0);
  }

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