<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=" 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" :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="primary" @click="BtnClick(key, 1)">
          报表</el-button>
        <el-button size="mini" type="danger" @click="BtnClick(key, 2)"
          v-if="(Alltable.length===2 && key ===0) || Alltable.length===1">
          从收藏夹移除</el-button>
        <el-button size="mini" @click="BtnClick(key, 3)" type="primary">下载eep</el-button>
        <el-button size="mini" type="primary" @click="BtnClick(key, 4)">查询设置</el-button>
        <el-button size="mini" type="primary" @click="BtnClick(key, 5)">目录序列树</el-button>
        <!-- <el-dropdown placement="top" trigger="click" v-if="(Alltable.length===2 && key ===0) || Alltable.length===1">
          <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" @click="BtnClicks(key,1)" type="primary">密级鉴定</el-button>
              <el-button size="mini" @click="BtnClicks(key,3)" type="primary">期限鉴定</el-button>
              <el-button size="mini" @click="BtnClicks(key,4)" type="primary">开发鉴定</el-button>
              <el-button size="mini" @click="BtnClicks(key,5)" type="primary">销毁鉴定</el-button>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown> -->
      </div>
      <el-table 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">
          <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,2000]"
        :current-page="item.pagination.pageNum" :total="item.pagination.total">
      </el-pagination>
    </div>
    <!-- 原文弹窗 -->
    <drawer-tem ref="original" :treeRow="treeRow" :drawer='drawer' :actions='actions' :catalogueType='catalogueType'
      @handleClose="handleClose" />
    <!--报表弹窗-->
    <dia-report :visible="diaReport" @cancel="handleClose" ref="diaReport" @submit="reportSubmit" />
    <!--pdf预览弹窗-->
    <dia-preview :visible="diaPreview" :pdfUrl="pdfUrl" @cancel="cancelPreview" />
    <!-- 查询设置弹窗 -->
    <dia-query :querySetData="querySetData" :visible="diaQuery" ref="diaQuery" @cancel="handleClose"
      @submit="querySubmit" />
  </div>
</template>
<script>
import DrawerTem from "@/components/DrawerTem";
import diaReport from "../../notStoredArchives/components/diaReport";
import diaPreview from "../../notStoredArchives/components/diaPreview";
import diaQuery from "../../notStoredArchives/components/diaQuery";
import { message, dateFormatT, dateFormat, downlaodEEP } from "@/utils/common";
import {
  getOneTable,
  saveObject,
  selectUreportList,
  reportPdf,
  horizontalPdf,
  getSettingField,
  saveSettingField,
  querySettings,
  getPageBySequenceFavorites,
} from "@/api/archives-management/fileManagement/notStoredArchives.js";
import {
  getFavoriteListByUserId,
  deleteFavorites,
  reportFavoritesPdf,
} from "@/api/archives-management/fileManagement/storedFavorites";
import localStronge from "@/api/localData";
import { URL_PREFIX } from "@/utils/url-prefix";
export default {
  props: {
    fondsList: {
      type: Array,
      default: () => [],
    },
    isDirSeqTree: {
      type: Boolean,
      default: () => false,
    },
    treeRow: {
      type: Object,
      default: () => {},
    },
    Alltable: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    DrawerTem,
    diaReport,
    diaPreview,
    diaQuery,
  },
  data() {
    return {
      querySetData: {},
      prefix:
        process.env.NODE_ENV === "development"
          ? "http://" +
            localStronge.getServiceip().ip +
            ":" +
            localStronge.getServiceip().host
          : "http://" + window.location.host,
      drawer: false,
      actions: "",
      catalogueType: false,
      diaReport: false, // 报表表单
      diaPreview: false, // 预览表单
      diaQuery: false, // 查询设置表单
      dirQuery: {}, // 目录序列树参数
      pdfUrl: "", // pdf地址
      currentTableKey: "", // 根据key获取按钮对应表格的相关数据
      archivesids: [], // 已收藏id
      tableTwoClickRow: {},
      tableOneClickRow: {},
    };
  },
  methods: {
    handleSelectionChange(event, item) {
      item.selectTable = event;
    },
    //搜索按钮集合  (循环中的每个对象要执行的方法)
    clickSearch(key, type, stratType) {
      this.selectId = "";
      //key 是匹配对象
      // type等于。1是搜索。2是重置。3是折叠按钮。4是添加。5是修改。6是删除
      //stratType 是判断是否是第一次加载 1是首次加载
      this.Alltable.forEach((item, index) => {
        if (key === index) {
          let params = {
            commonMap: {
              funcTypeCode: "",
              tableName: item.tableName,
            },
            conditionMap: {},
            limit: "10",
            page: "1",
          };
          // if (stratType === 1) {
          // params.conditionMap["id"] = this.archivesids.join(",")
          // }
          if (key === 1) {
            params.conditionMap["pid"] = this.tableOneClickRow.id;
          }
          if (key === 2) {
            params.conditionMap["pid"] = this.tableTwoClickRow.id;
          }
          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;
              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,
                };
              }
              let userData = {
                userId: sessionStorage.getItem("userid"),
                type: this.treeRow.id,
              };
              getFavoriteListByUserId(userData)
                .then((res) => {
                  if (res.code === "100") {
                    let recIds = res.body.list
                      .filter((ele) => ele.recId)
                      .map((ele) => ele.recId);

                    this.archivesids = recIds.length
                      ? [...new Set(recIds.join(",").split(","))]
                      : [];
                    if (stratType === 1 || !key) {
                      params.conditionMap["id"] = this.archivesids.length
                        ? this.archivesids.join(",")
                        : 0;
                    }
                  }
                })
                .then(() => {
                  getOneTable(params)
                    .then((res) => {
                      item.tableData = res.body.list;
                      item.pagination.total = res.body.total;
                      item.tableLoading = false;
                    })
                    .catch((err) => {
                      item.tableLoading = false;
                    });
                });
              break;
            case 2: //重置
              item.search.forEach((ele) => {
                ele.value = "";
              });
              break;
            case 3: //折叠
              item.isShow = !item.isShow;
              break;
          }
        }
      });
    },
    handleClose() {
      this.drawer = false;
      this.diaReport = false;
      this.diaQuery = false;
    },
    cancelPreview() {
      this.diaPreview = false;
    },
    editCurrentApplicationApproval(val, item, key) {
      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: "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;
      this.actions =
        this.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;
    },
    // 生成报表
    reportSubmit(pdfName) {
      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: 2, // 已入库
        // recIds: this.archivesids.join(','),
        pdfName,
      };
      if (ele.selectTable.length) {
        params.ids = ele.selectTable.map((item) => item.id).join(",");
      } else {
        params.recIds = this.archivesids.join(",");
      }
      reportFavoritesPdf(params).then((res) => {
        if (res.code === "100") {
          message("success", "生成报表成功", 2000);
          this.showPdf(res.body.fileName);
          this.diaPreview = true;
        }
      });
    },
    // pdf预览
    showPdf(fileName) {
      this.pdfUrl =
        URL_PREFIX + "/point-strategy/v/ureport/showPdf?fileName=" + fileName;
    },
    // 点击目录序列树赋值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]] = "";
          });
        }
      });
    },
    // 查询设置-保存
    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);
        });
      }
    },
    // 点击目录序列树节点
    /* clickDirSearch(params, key) {
        this.Alltable.forEach((item, index) => {
          if (key === index) {
            params.limit = item.pagination.pageSize;
            // params.page = item.pagination.pageNum;
            getPageBySequenceFavorites(params).then(res => {
              if (res.success) {
                item.tableData = res.body.list;
                item.pagination.total = res.body.total;
              }
            });
          }
        })
      }, */
    //集中按钮集合 1.导出 2.下载eep 3.移交 4.四性检测 5.退回未入库
    BtnClicks(key, val) {
      this.Alltable.forEach((item, index) => {
        if (index === key) {
          let data = {
            classId: this.treeRow.id,
          };
          switch (val) {
            case 1:
              break;
            case 2:
              break;
            case 3:
              break;
            case 4:
              break;
            case 5:
              break;
          }
        }
      });
    },
    //外层按钮集合 1.报表 2.添加至收藏夹
    BtnClick(key, val) {
      this.currentTableKey = key;
      this.Alltable.forEach((item, index) => {
        if (index === key) {
          let data = {
            classId: this.treeRow.id,
          };
          switch (val) {
            case 1: // 报表
              if (key === 1 && !item.selectTable.length) {
                message("warning", "请至少勾选一条数据", 3000);
                return false;
              }
              this.diaReport = true;
              this.$refs.diaReport.radioType = "";
              const params1 = {
                entityName: item.entityType,
              };
              selectUreportList(params1).then((res) => {
                if (res.code === "100") {
                  this.$refs.diaReport.tableData = res.body.list;
                }
              });
              break;
            case 2:
              if (!item.selectTable.length) {
                message("warning", "请至少勾选一条数据", 3000);
                return false;
              }
              const selectIds = item.selectTable.map((v) => v.id);
              const params = {
                // 未移除收藏的id
                ids: this.archivesids
                  .filter((k) => !selectIds.includes(parseInt(k)))
                  .join(","),
                type: this.treeRow.id,
                userId: sessionStorage.getItem("userid"),
              };
              deleteFavorites(params).then((res) => {
                if (res.code === "100") {
                  message("success", "移除收藏夹成功", 2000);
                  this.clickSearch(key, 1, 0);
                }
              });
              break;
            case 3:
              if (!item.selectTable.length) {
                message("warning", "请先选择档案", 3000);
                return;
              }
              data.id = item.selectTable.length
                ? item.selectTable.map((ele) => ele.id).join(",")
                : "";
              let str =
                this.prefix +
                "/point-strategy/v/fileManage/downloadEEP?classId=" +
                data.classId +
                "&id=" +
                data.id;
              window.location.href = str;
              break;
            case 4:
              // 查询设置
              /* this.querySetData = {
                  entityId: item.entityId,
                  tableName: item.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(item);
              this.diaQuery = true;
              break;
            case 5:
              // 目录序列树
              this.$emit("triggerTree", key); // 切换左侧树
              break;
          }
        }
      });
    },
    //每页换个数
    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);
    },
  },
};
</script>
<style lang="scss" scoped>
.wholeTable {
  margin-bottom: 15px;

  .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-top: 10px;
    margin-bottom: 5px;
    border-radius: 5px;
    text-align: left;
  }
}
</style>
