<template>
  <!-- 档案管理——未入库档案著录、已入库数据浏览、OA数据管理、已入库收藏夹，点击原文数量弹框 -->
  <div>
    <el-drawer title="原文详情" :visible.sync="drawer" :append-to-body="true" direction="ltr" :before-close="handleClose"
      size="100%" :wrapperClosable="false">
      <div class="tip-info" v-if="
        routerName === 'dataBrowsing' || routerName === 'notStoredArchives'
      ">
        {{ checkText }}
      </div>
      <div class="btnClass">
        <el-card :body-style="{ padding: '10px' }">
          <!-- {{drawer}}{{oriTable}} -->
          <el-button size="mini" v-if="catalogueType" type="danger" @click="deletec">
            删除
          </el-button>
          <el-button size="mini" v-if="catalogueType && treeRow.className != '电子档案'" type="primary"
            @click="btnClick(1)">
            批量下载
          </el-button>
          <el-button size="mini" v-if="catalogueType && treeRow.className != '电子档案'" type="primary"
            @click="btnClick(2)">
            归档章
          </el-button>
          <!-- <el-button size="mini" v-if="catalogueType && treeRow.className!='录像' && treeRow.className!='录音'"
            type="primary" @click="btnClick(3)">
            合并文件 </el-button> -->
          <el-button size="mini" v-if="treeRow.className != '电子档案'" type="primary" @click="btnClick(4)">
            合并下载
          </el-button>
          <!-- <el-button size="mini"
            v-if="catalogueType && treeRow.className!='录像' && treeRow.className!='录音' && routerName==='notStoredArchives'"
            type="primary" @click="btnClick(5)">
            扫描原文 </el-button> -->
          <el-button size="mini" v-if="
            catalogueType &&
            treeRow.className != '电子档案' &&
            routerName === 'notStoredArchives'
          " type="primary" @click="btnClick(6)">
            撤销归档章
          </el-button>
          <el-button size="mini" v-if="treeRow.className != '电子档案'" type="primary" @click="btnClick(9)">
            电子签名
          </el-button>
          <el-button size="mini" type="primary" v-if="routerName === 'dataBrowsing'" @click="btnClick(7)">电子档案复制申请
          </el-button>
          <el-button size="mini" type="primary" v-if="routerName === 'dataBrowsing'" @click="btnClick(8)">实体档案复制申请
          </el-button>
        </el-card>
      </div>
      <div class="contentBox">
        <el-card :body-style="{ padding: '10px' }" style="width: 26%">
          <el-button v-if="oriRowObj.useStyle === 'print' || typeStatus === 'ruku'" type="primary" size="small"
            :disabled="!multipleSelection.length" @click="download">
            原文下载
          </el-button>
          <!-- @row-click="previewImg" -->
          <el-table ref="tableForEach" highlight-current-row border size="mini" :data="tableDataOrigin"
            @row-click="previewImg" tooltip-effect="dark" max-height="800px" @selection-change="handleSelectionChange">
            <!-- 原文下载的多选框 -->
            <el-table-column v-if="
              catalogueType ||
              (!catalogueType && oriRowObj.useStyle === 'print') ||
              typeStatus === 'ruku'
            " type="selection" width="43">
            </el-table-column>
            <el-table-column type="index" width="55" label="序号" align="center">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="file_name" label="文件名称" align="center">
              <template slot-scope="scope">
                <template v-if="scope.row.isEditFlag">
                  <el-input type="text" @change.native.stop="originClick('blur', scope.row)" size="mini"
                    :title="scope.row.file_name" v-model="scope.row.file_name" clearable />
                </template>
                <template v-else>{{ scope.row.file_name }}</template>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100" v-if="$route.name === 'notStoredArchives'">
              <template slot-scope="scope">
                <el-button @click.native.stop="originClick('down', scope.row)" type="text" icon="el-icon-bottom"
                  title="向下" size="mini"></el-button>
                <el-button @click.native.stop="originClick('up', scope.row)" type="text" icon="el-icon-top" title="向上"
                  size="mini"></el-button>
                <el-button @click.native.stop="originClick('rename', scope.row)" type="text" icon="el-icon-edit"
                  title="重命名" size="mini"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card :body-style="{ padding: '10px' }" style="width: 73%" class="box-card">
          <el-tabs v-model="activeName">
            <el-tab-pane label="查看原文" name="1" v-loading.fullscreen.lock="imageLoad" :element-loading-text="loadingText"
              element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.1)">
              <!-- 查看原文 -->
              <div class="demo-image__lazy">
                <!-- 备注scrolling属性原来是'no'现在是'auto' -->
                <!-- <el-image v-show="imgType &&imgType != 'pdf'  " class="imgs" :src="picUrl" fit="cover"></el-image> -->
                <iframe ref="showIframeRef" v-if="
                  ![
                    'mp3',
                    'mp4',
                    'tif',
                    'wav',
                    'avi',
                    'flv',
                    'mxf',
                    'ofd',
                  ].includes(this.fileType)
                " style="text-align: center" noresize align="center" width="100%" height="750px" :src="picUrl"
                  frameborder="0" scrolling="auto"></iframe>
                <template v-if="rowTable.file_type === 'ofd' && isIframeFlag == true">
                  <iframe :key="ofdUrl" style="text-align: center" noresize align="center" width="100%" height="750px"
                    :src="`./yhofd/yhofd.html?name=${rowTable.file_name_server}&url=${ofdUrl}`" frameborder="0"
                    scrolling="auto"></iframe>
                </template>
                <div v-if="rowTable.file_type === 'svg'" v-html="picUrl"></div>
                <video v-if="
                  (this.fileType === 'mp4' ||
                    this.fileType === 'avi' ||
                    this.fileType === 'mxf') &&
                  videoSrc
                " ref="videoS" :src="videoSrc" controls="controls" height="600px" :muted="muteStatus" width="100%">
                  您的浏览器不支持视频播放
                </video>
                <video v-if="this.fileType === 'flv'" id="videoElementByFlv" class="flvplayer-app" controls
                  :muted="muteStatus" height="600px" width="100%"></video>
                <audio v-if="
                  (this.fileType === 'mp3' || this.fileType === 'wav') &&
                  musicSrc
                " ref="audioS" :src="musicSrc" controls autoloop></audio>
                <viewer v-if="this.fileType === 'tif'" id="printimg" :images="canvasList">
                  <img v-for="item in canvasList" :src="item" :key="item" :class="tif_length > 1 ? '' : 'tif_img'"
                    height="300" title="请点击查看" />
                  <!-- <div style='padding: 0px 15px'>{{rowTable.file_name}}</div> -->
                </viewer>
              </div>
            </el-tab-pane>
            <el-tab-pane label="添加原文" name="2" v-loading.fullscreen.lock="loadingStatus"
              :element-loading-text="loadingText" element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.1)" v-if="catalogueType">
              <!-- 添加原文 -->
              <div class="uploadBox">
                <el-upload accept="*" class="upload-demo" ref="upload" :file-list="fileList" action="#"
                  :auto-upload="false" multiple :on-exceed="beforeAvatarUpload" :on-success="upSuccess"
                  :on-change="handleFileChange" :before-remove="handleFileRemove">
                  <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
                  <el-button style="margin-left: 10px" size="small" type="success" @click="submitUpload">开始上传
                  </el-button>
                  <div slot="tip" class="el-upload__tip">
                    上传文件支持jpg/png/pdf/tif/svg/flv/mp4/mp3/avi/wav
                  </div>
                </el-upload>
              </div>
            </el-tab-pane>
            <!-- <el-tab-pane 
            label="添加原文" name="2"
            v-loading.fullscreen.lock="loadingStatus"
            :element-loading-text="loadingText"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.1)"
            v-if="treeRow.className==='电子档案' && catalogueType">
              <div class="uploadBox">
                <el-upload accept="audio/mpeg,audio/mp4,video/mp4" class="upload-demo" ref="upload" :file-list="fileList" action="#"
                  :auto-upload="false" multiple :on-exceed="beforeAvatarUpload" :on-success="upSuccess"
                  :on-change="handleFileChange" :before-remove="handleFileRemove">
                  <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
                  <el-button style="margin-left: 10px" size="small" type="success" @click="submitUpload">开始上传
                  </el-button>
                  <div slot="tip" class="el-upload__tip">只能上传后缀为MP4、MP3文件</div>
                </el-upload>
              </div>
            </el-tab-pane> -->
            <!-- <el-tab-pane 
            label="添加原文" name="2"
            v-loading.fullscreen.lock="loadingStatus" 
            :element-loading-text="loadingText"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(255, 255, 255, 0.1)"
            v-if="treeRow.className==='录音' && catalogueType">
              
              <div class="uploadBox">
                <el-upload accept="audio/*" class="upload-demo" ref="upload" :file-list="fileList" action="#"
                  :auto-upload="false" multiple :on-exceed="beforeAvatarUpload" :on-success="upSuccess"
                  :on-change="handleFileChange" :before-remove="handleFileRemove">
                  <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
                  <el-button style="margin-left: 10px" size="small" type="success" @click="submitUpload">开始上传
                  </el-button>
                  <div slot="tip" class="el-upload__tip">只能上传mp3文件</div>
                </el-upload>
              </div>
            </el-tab-pane> -->
            <el-tab-pane label="原文回收站" name="3" v-if="catalogueType">
              <!-- 原文回收站 -->
              <el-table :data="backData" style="width: 100%" max-height="350" ref="ytabs" border size="mini">
                <el-table-column prop="file_name" label="文件名称" align="center">
                </el-table-column>
                <el-table-column prop="file_type" label="文件类型" width="150" align="center">
                </el-table-column>
                <el-table-column prop="file_len" label="文件大小(KB)" align="center">
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" @click="returnContRec(scope.row)">恢复</el-button>
                    <el-button type="text" style="color: #ff0000" @click="delOriRecycle(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="元数据" name="4" v-if="treeRow.className != '电子档案'">
              <el-form label-position="left" class="formDIa" :model="metadata" size="mini" style="padding: 10px 25px"
                label-width="100px">
                <el-form-item v-for="item in metadataList" :key="item.columnName" :label="item.columnChnName">
                  <span>{{ metadata[item.columnName] }}</span>
                </el-form-item>
                <template v-if="
                  metadata.signature != '' &&
                  metadata.signature != null &&
                  metadata.signature != undefined
                ">
                  <el-form-item label="签名真实性：">
                    <el-tag :type="metadata.certificateValidity ? 'success' : 'warning'
                      ">{{ metadata.certificateValidity ? "真" : "假" }}</el-tag>
                  </el-form-item>
                  <el-form-item label="签名算法：">
                    <span>{{ metadata.signature }}</span>
                  </el-form-item>
                  <el-form-item label="数据加密：">
                    <el-button type="primary" plain size="mini"
                      @click="copyCellContent(metadata.signatureData)">复制数据加密</el-button>
                  </el-form-item>
                </template>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="OCR识别" name="5" v-if="treeRow.className != '电子档案'">
              <div>
                <el-input v-model="ocrText" type="textarea" :rows="12" readonly></el-input>
              </div>
            </el-tab-pane>
            <el-tab-pane label="原文查询" name="6" v-if="!catalogueType && treeRow.className != '电子档案'">
              <search-box :orirow="orirow" :drawer="drawer" :oriTable="oriTable" />
              <!-- {{oriTable}} -->
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import pdf from "vue-pdf";
import {
  pictureMetadata,
  archiveSeal,
  mergeFile,
  mergeDownload,
  getOcrImageWord,
  getWord,
  fileDownload,
  batchDownloadWatermarking,
  withdrawArchiveSeal,
} from "@/api/preFiling/file-management/description";
import {
  updateTempFileObject,
  updateTempArchiveFileNumObject,
  updateObject,
  delectTable,
  getOneTable,
  addScan,
  checkFileImgNum,
  moveUp,
  moveDown,
  rename,
  showImg,
  addElectronicSignature,
} from "@/api/archives-management/fileManagement/notStoredArchives.js";
import localStronge from "@/api/localData";
import { downlaod, message, getCurrentTime, downlaodzip } from "@/utils/common";
import SearchBox from "./SearchBox";

export default {
  props: {
    drawer: {
      type: Boolean,
      default: () => false,
    },
    treeRow: {
      type: Object,
      default: () => { },
    },
    actions: {
      type: String,
      default: () => "",
    },
    treeType: {
      type: String,
      default: () => "",
    },
    catalogueType: {
      type: Boolean,
      default: () => true,
    },
    curRow: {
      type: Object,
      default: () => { },
    },
    archive_no: {
      type: String,
      default: () => "",
    },
    tableName: {
      type: String,
      default: () => "",
    },
    typeStatus: {
      type: String,
      default: () => "",
    },
    isDistinction: {
      type: Boolean,
      defalult: () => false,
    },
  },
  components: {
    pdf,
    SearchBox,
  },
  data() {
    return {
      isIframeFlag: false, // 是否是iframe打开
      imageLoad: false,
      canvasList: [],
      currentClickImage: {},
      fileType: "", // 文件类型；
      loadingText: "上传中...",
      loadingStatus: false,
      tableheight: window.innerHeight - 130,
      routerName: "",
      activeName: "1",
      addStatus: false,
      lookStatus: true,
      showStatus: false,
      backData: [],
      tableDataOrigin: [],
      picUrl: "",
      ofdUrl: "",
      archiveNum: null,
      oriTable: {},
      orirow: {},
      orikey: null,
      params: {},
      multipleSelection: [],
      fileList: [],
      fileName: [],
      metadataList: [], // 元数据列表
      metadata: {},
      rowTable: {},
      imgType: "pdf",
      ocrText: "",
      videoSrc: "",
      videoImg: "",
      playStatus: "",
      muteStatus: "",
      musicSrc: "",
      oriRowObj: {},
      currentImageIndex: 0,
      checkText: "", // 校验信息
      isOriginEdit: false, //原文名称是否可编辑
      tif_length: 0, // 判断tif超过2张就不放大展示
    };
  },
  methods: {
    /** 复制数据加密 */
    copyCellContent(textToCopy) {
      // 创建一个临时的 textarea 元素用于复制内容
      const tempTextArea = document.createElement("textarea");
      tempTextArea.value = textToCopy;
      document.body.appendChild(tempTextArea);
      tempTextArea.select(); // 选择文本
      document.execCommand("copy"); // 执行复制命令
      document.body.removeChild(tempTextArea); // 移除临时元素
      message("success", "复制成功");
    },
    // 原文向下、向上、重命名功能
    originClick(type, row) {
      let requestFunction = null;
      let params = {
        fileId: row.id,
        tableName: this.oriTable.tableName,
        funcTypeCode: "temp_file",
      };
      if (type == "up") {
        requestFunction = moveUp;
      } else if (type == "down") {
        requestFunction = moveDown;
      } else if (type == "rename") {
        this.$nextTick(() => {
          this.tableDataOrigin.forEach((item) => {
            if (item.id == row.id) {
              item.isEditFlag = true;
            } else {
              item.isEditFlag = false;
            }
          });
        });
        return;
      } else if (type == "focus") {
        return;
      } else if (type == "blur") {
        // 原文失去焦点时
        params.name = row.file_name;
        if (params.name == "" || params.name == null) {
          message("warning", "请输入原文名称", 3000);
          return;
        }
        requestFunction = rename;
      }
      requestFunction(params).then((res) => {
        if (res.code == 100) {
          // 刷新数据；
          this.RefreshTable();
          message("success", res.msg, 3000);
        }
      });
    },
    // 校验原文数量与页码是否匹配
    checkFileImgNum() {
      let params = {
        id: this.orirow.id,
        tableName: this.oriTable.tableName,
        funcTypeCode: this.routerName == "notStoredArchives" ? "temp" : "",
      };
      checkFileImgNum(params).then((res) => {
        if (res.code == 100) {
          if (res.msg == "操作成功") {
            this.checkText = res.body.info ? res.body.info : "";
          } else {
            this.checkText = res.body.info;
          }
        }
      });
    },
    // 批量下载原文
    download(row) {
      let type = 1;
      let ids = this.multipleSelection.map((item) => item.id);
      let data = {
        tableName: this.oriTable.tableName,
        ids: ids.join(","),
        archiveNo: this.archive_no,
        userId: sessionStorage.getItem("userid"),
        type,
      };
      if (this.typeStatus === "ruku") {
        fileDownload(data).then((res) => {
          downlaodzip(res, "原文下载");
        });
      } else {
        batchDownloadWatermarking(data).then((res) => {
          downlaodzip(res, "原文下载");
        });
      }
    },
    //规党章
    chapter() { },
    beforeAvatarUpload(files, fileList) {
      const isJPG = file.type === "image/jpeg";
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      return isJPG && isLt2M;
    },
    //恢复原文
    returnContRec(val) {
      this.archiveNum = this.archiveNum + 1;
      let params = {
        commonMap: {
          funcTypeCode: this.treeType + "_file",
          tableName: this.oriTable.tableName,
        },
        fieldValueMap: {
          file_status: 1,
        },
        conditionMap: {
          id: val.id,
        },
      };

      let paramsOut = {
        commonMap: {
          funcTypeCode: this.treeType,
          tableName: this.oriTable.tableName,
        },
        fieldValueMap: {
          archive_file_num: 1,
        },
        conditionMap: {
          id: this.orirow.id,
        },
      };
      updateObject(params).then((res) => {
        this.params.conditionMap.file_status = "2";
        getOneTable(this.params).then((res) => {
          this.backData = res.body.list;
        });
      });
      updateTempArchiveFileNumObject(paramsOut).then((res) => {
        this.$emit("getData", this.orikey, 1, 1);
        this.params.conditionMap.file_status = "1";
        this.getTableDataOrigin(this.params);
      });
    },
    handleClose() {
      const prefix =
        process.env.NODE_ENV === "development"
          ? "http://" +
          localStronge.getServiceip().ip +
          ":" +
          localStronge.getServiceip().host
          : "http://" + window.location.host;
      if (
        (this.fileType === "mp3" || this.fileType === "wav") &&
        this.$refs.audioS
      ) {
        this.$refs.audioS.pause();
      }
      if (
        (this.fileType === "mp4" || this.fileType === "avi") &&
        this.$refs.videoS
      ) {
        this.$refs.videoS.pause();
      }
      if (this.fileType === "flv") {
        var videoElement = document.getElementById("videoElementByFlv");
        this.flvPlayer = flvjs.createPlayer({
          url:
            prefix +
            "/point-strategy/v/archiveFile/showImg?fileName=" +
            this.rowTable.file_name_server +
            "&path=" +
            this.rowTable.file_des,
          type: "flv",
        });
        this.flvPlayer.attachMediaElement(videoElement);
        this.flvPlayer.pause();
        this.flvPlayer.unload();
        this.flvPlayer.destroy();
        this.flvPlayer = "";
      }
      this.$emit("handleClose");
      this.imgType = "pdf";
      this.fileType = "";
    },
    // 点击查看图片
    async previewImg(row) {
      this.imgLoading = true;
      this.$refs.tableForEach.clearSelection();
      this.$refs.tableForEach.toggleRowSelection(row);
      this.rowTable = { ...row };
      this.metadata = {};
      this.metadataList = [];
      this.ocrText = "";
      const prefix =
        process.env.NODE_ENV === "development"
          ? "http://" +
          localStronge.getServiceip().ip +
          ":" +
          localStronge.getServiceip().host
          : "http://" + window.location.host;
      this.activeName = "1";
      this.fileType = row.file_type.toLowerCase(); // 转换成小写；

      if (this.fileType == "mp4") {
        this.videoSrc =
          prefix +
          "/point-strategy/v/archiveFile/showImg?fileName=" +
          row.file_name_server +
          "&path=" +
          row.file_des +
          "&data=" +
          new Date();
        this.getMetadata(this.videoSrc, row);
      } else if (this.fileType == "ofd") {
        this.isIframeFlag = true;
        this.ofdUrl = `${row.file_des}/${row.file_name_server}`;
        if (row.file_content) {
          this.ocrText = row.file_content;
          return;
        }
        this.getMetadata(this.ofdUrl, row);
      } else if (this.fileType == "avi") {
        this.videoSrc =
          prefix +
          "/point-strategy/v/archiveFile/showImg?fileName=" +
          row.file_name_server +
          "&path=" +
          row.file_des +
          "&data=" +
          new Date();
        this.getMetadata(this.videoSrc, row);
      } else if (this.fileType == "mxf") {
        row.file_name_server = row.file_name_server.replace(".mxf", ".mp4");
        this.videoSrc =
          prefix +
          "/point-strategy/v/archiveFile/showImg?fileName=" +
          row.file_name_server +
          "&path=" +
          row.file_des +
          "&data=" +
          new Date();
        this.getMetadata(this.videoSrc, row);
      } else if (this.fileType == "mp3") {
        this.musicSrc =
          prefix +
          "/point-strategy/v/archiveFile/showImg?fileName=" +
          row.file_name_server +
          "&path=" +
          row.file_des +
          "&data=" +
          new Date();
        this.getMetadata(this.musicSrc, row);
      } else if (this.fileType == "wav") {
        this.musicSrc =
          prefix +
          "/point-strategy/v/archiveFile/showImg?fileName=" +
          row.file_name_server +
          "&path=" +
          row.file_des +
          "&data=" +
          new Date();
        this.getMetadata(this.musicSrc, row);
      } else if (this.fileType == "tif") {
        this.canvasList = [];
        this.tifSrc =
          prefix +
          "/point-strategy/v/archiveFile/showImg?fileName=" +
          row.file_name_server +
          "&path=" +
          row.file_des +
          "&userId=" +
          sessionStorage.getItem("userid");
        const response = await fetch(this.tifSrc);
        const buffer = await response.arrayBuffer();
        const Tiff = require("tiff.js");
        const tiff = new Tiff({
          buffer,
        });
        this.tif_length = tiff.countDirectory();
        for (let i = 0, len = tiff.countDirectory(); i < len; ++i) {
          tiff.setDirectory(i);
          var imgs = tiff.toDataURL(); // 转化成base64

          if (imgs) {
            this.canvasList.push(imgs);
          }
        }
      } else if (this.fileType == "svg") {
        let svgUrl =
          prefix +
          "/point-strategy/v/archiveFile/showImg?fileName=" +
          row.file_name_server +
          "&path=" +
          row.file_des +
          "&userId=" +
          sessionStorage.getItem("userid");
        "&data=" + new Date();
        this.$axios
          .get(svgUrl)
          .then((response) => {
            this.picUrl = response.data;
          })
          .then(() => {
            this.getMetadata(this.picUrl, row);
          });
      } else if (this.fileType == "flv") {
        if (flvjs.isSupported()) {
          setTimeout(() => {
            // 这里加了个200ms的定时器,原因是因为抓取元素之后vue无法瞬间响应
            var videoElement = document.getElementById("videoElementByFlv");
            this.flvPlayer = flvjs.createPlayer({
              url:
                prefix +
                "/point-strategy/v/archiveFile/showImg?fileName=" +
                row.file_name_server +
                "&path=" +
                row.file_des,
              type: "flv",
            });
            this.flvPlayer.attachMediaElement(videoElement);
            this.flvPlayer.load();
            // this.flvPlayer.pause();
          }, 200);
        }
      } else {
        let name = row.file_name_server
        this.picUrl =
          process.env.NODE_ENV === "development"
            ? "http://" +
            localStronge.getServiceip().ip +
            ":" +
            localStronge.getServiceip().host +
            "/point-strategy/v/archiveFile/showImg?fileName=" +
            name +
            "&path=" +
            encodeURI(encodeURI(row.file_des)) +
            "&data=" +
            new Date() +
            "&userId=" +
            sessionStorage.getItem("userid")
            : "http://" +
            window.location.host +
            "/point-strategy/v/archiveFile/showImg?fileName=" +
            encodeURI(encodeURI(name)) +
            "&path=" +
            encodeURI(encodeURI(row.file_des)) +
            "&data=" +
            new Date() +
            "&userId=" +
            sessionStorage.getItem("userid");
        if (this.activeName != "4" && this.activeName != "5") {
          this.activeName = "1";
        }

        if (this.fileType == "jpg") {
          if (row.file_content) {
            this.ocrText = row.file_content;
          } else {
            let orcData = {
              id: row.id,
              tableName: this.oriTable.tableName,
            };
            getWord(orcData).then((res) => {
              this.ocrText = res.body.word;
            });
          }
          this.getMetadata(this.picUrl, row);
        } else {
          this.getMetadata(this.picUrl, row);
        }
      }
    },
    // 获取元数据
    getMetadata(urlStr, row) {
      console.log("元数据-------");
      // 获取元数据
      let data = {
        fileName: row.file_name,
        url: urlStr,
        path: row.file_des,
        fileNameServer: row.file_name_server,
      };
      pictureMetadata(data).then((res) => {
        this.metadataList = res.body.list;
        if (this.metadataList.length > 0) {
          this.metadataList.forEach((item) => {
            this.metadata[item.columnName] = item.value;
          });
        }
      });
    },
    //上传成功
    upSuccess(response, file, fileListF) {
      if (response.code === "100") {
        this.$emit("handleContents", this.orirow, this.oriTable);
        this.$refs.upload.clearFiles();
        this.$emit("getData", this.orikey, 1, 1);
        this.params.conditionMap.file_status = "1";
        this.getTableDataOrigin(this.params);
      }
    },
    deletec() {
      let idList = [];
      if (!this.multipleSelection.length) {
        message("warning", "请先勾选要删除的文件", 3000);
        return;
      }
      this.multipleSelection.forEach((item) => {
        idList.push(item.id);
      });
      let params = {
        commonMap: {
          funcTypeCode: this.treeType + "_file",
          tableName: this.oriTable.tableName,
        },
        fieldValueMap: {
          file_status: 2,
        },
        conditionMap: {
          ids: idList.join(","),
        },
      };
      let paramsOut = {
        commonMap: {
          funcTypeCode: this.treeType,
          tableName: this.oriTable.tableName,
        },
        fieldValueMap: {
          archive_file_num: -idList.length,
        },
        conditionMap: {
          id: this.orirow.id,
        },
      };
      this.$confirm("此操作将文件移入回收站, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        updateTempFileObject(params).then((res) => {
          message("success", "成功移入到回收站", 3000);
          this.$emit("getData", this.orikey, 1, 1);
          this.params.conditionMap.file_status = "1";
          this.getTableDataOrigin(this.params);
        });
        updateTempArchiveFileNumObject(paramsOut).then((res) => {
          this.params.conditionMap.file_status = "2";
          getOneTable(this.params).then((res) => {
            this.backData = res.body.list;
          });
        });
      });
    },
    // 改造getTableDataOrigin
    async getTableDataOrigin(params) {
      try {
        const res = await getOneTable(params);
        this.tableDataOrigin = res.body.list.map((item) => ({
          ...item,
          isEditFlag: false,
        }));
        return true; // 返回成功标识
      } catch (e) {
        message("error", "数据加载失败");
        return false;
      }
    },
    delOriRecycle(val) {
      let params = {
        commonMap: {
          funcTypeCode: this.treeType + "_file",
          tableName: this.oriTable.tableName,
        },
        conditionMap: {
          id: val.id,
        },
      };
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delectTable(params).then((res) => {
          message("success", "删除成功", 3000);
          this.params.conditionMap.file_status = "2";
          getOneTable(this.params).then((res) => {
            this.backData = res.body.list;
          });
        });
      });
    },
    //button按钮事件集合
    //1.批量下载 //2.规党章 //3.合并文件 //4.合并下载
    btnClick(val) {
      let fileIds = this.multipleSelection.length
        ? this.multipleSelection.map((ele) => ele.id).join(",")
        : "";
      let archiveNo = this.orirow.archive_no || this.orirow.folder_no || "";
      let data = {
        id: this.orirow.id,
        tableName: this.oriTable.tableName,
        archiveNo,
      };
      switch (val) {
        case 1: // 批量下载
          if (!fileIds) {
            message("warning", "请先选择目标", 3000);
            return;
          }
          let dataOne = {
            tableName: this.oriTable.tableName,
            ids: fileIds,
          };
          let time = getCurrentTime();
          const prefix =
            process.env.NODE_ENV === "development"
              ? "http://" +
              localStronge.getServiceip().ip +
              ":" +
              localStronge.getServiceip().host
              : "http://" + window.location.host;
          let str =
            prefix +
            "/point-strategy/v/fileManage/batchDownload?tableName=" +
            this.oriTable.tableName +
            "&ids=" +
            fileIds +
            "&archiveNo=" +
            archiveNo +
            "&type=" +
            0 +
            "&userId=" +
            sessionStorage.getItem("userid");
          window.location.href = str;
          break;
        case 2: // 归档章
          if (this.multipleSelection.length != 1) {
            message("warning", "请选择一张图片", 3000);
            return;
          }
          if (
            this.multipleSelection[0].file_type !== "jpg" &&
            this.multipleSelection[0].file_type !== "pdf" &&
            this.multipleSelection[0].file_type !== "ofd"
          ) {
            message("warning", "请选择jpg、pdf、ofd格式", 3000);
            return;
          }
          (data.fileId = this.multipleSelection[0].id),
            // 操作代码优化
            archiveSeal(data).then(async (res) => {
              console.log(11111);
              if (this.rowTable.file_type === "ofd") {
                console.log(2222);
                this.isIframeFlag = false;
                this.ofdUrl = null;
                await this.RefreshTable();
                this.$nextTick(() => {
                  const currentRow = this.tableDataOrigin.find(
                    (item) => item.id === this.rowTable.id
                  );
                  if (!currentRow) {
                    console.warn("目标数据未找到");
                    return;
                  }
                  this.previewImg(currentRow);
                });
              } else {
                this.previewImg(this.rowTable);
              }
            });
          break;
        case 3: // 合并文件
          if (!this.multipleSelection.length) {
            message("warning", "请先选择合并的图片", 3000);
            return;
          }
          (data.fileIds = fileIds),
            (data.fondscode = this.orirow.fonds_no),
            mergeFile(data).then((res) => {
              this.RefreshTable();
            });
          break;
        case 4: // 合并下载
          if (!this.multipleSelection.length) {
            message("warning", "请先选择要下载的图片", 3000);
            return;
          }
          (data.fileIds = fileIds),
            (data.fondscode = this.orirow.fonds_no),
            (data.type = !this.isDistinction ? 0 : 1),
            mergeDownload(data).then((res) => {
              downlaod(res, "合并文件");
            });
          break;
        case 5: // 扫描原文
          let params = {
            fondscode: this.orirow.fonds_no,
            recId: this.orirow.id,
            systemUI: 1,
            tableName: this.oriTable.tableName,
          };
          addScan(params).then((res) => {
            message("success", "扫描成功", 3000);
            this.RefreshTable();
          });
          break;
        case 6: // 撤销归档章
          let _params = {
            fileNameServer: this.rowTable.file_name_server,
            path: this.rowTable.file_path,
          };
          withdrawArchiveSeal(_params).then((res) => {
            this.previewImg(this.rowTable);
          });
          break;
        case 7: // 电子档案复制申请
          if (!this.multipleSelection.length) {
            message("warning", "请先选择图片", 3000);
            return;
          }
          this.$emit("archiveCopyApply", this.multipleSelection, "dz");
          break;
        case 8: // 实体档案复制申请
          if (!this.multipleSelection.length) {
            message("warning", "请先选择图片", 3000);
            return;
          }
          this.$emit("archiveCopyApply", this.multipleSelection, "st");
          break;
        case 9: // 电子签名
          if (this.multipleSelection.length != 1) {
            message("warning", "请选择一张图片", 3000);
            return;
          }
          let _signature = {
            fileName: this.rowTable.file_name,
            fileDes: this.rowTable.file_des,
            fileNameServer: this.rowTable.file_name_server,
          };
          addElectronicSignature(_signature).then((res) => {
            if (res.code == 100) {
              message("success", "电子签名设置成功", 3000);
              this.RefreshTable();
            } else {
              message("warning", res.msg, 3000);
            }
          });
          break;
      }
    },
    //刷新
    // 修改RefreshTable方法
    async RefreshTable() {
      try {
        this.$emit("getData", this.orikey);
        // 更新本地表格数据
        this.params.conditionMap.file_status = "1";
        return await this.getTableDataOrigin(this.params);
      } catch (e) {
        message("error", "刷新失败");
      }
    },
    //勾选原文表
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 上传发生变化钩子
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
    // 删除之前钩子
    handleFileRemove(file, fileList) {
      this.fileList = fileList;
    },
    submitUpload() {
      this.loadingStatus = true;
      // this.$refs.upload.submit();
      if (!this.fileList.length) {
        message("warning", "请先添加要上传的图片", 3000);
        return;
      }
      let formData = new FormData();
      // 将上传的文件放到数据对象中
      this.fileList.forEach((file) => {
        formData.append("file", file.raw);
      });

      // formData.append('fileName', this.fileName);
      this.$axios
        .post(this.actions, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
            "Token": sessionStorage.getItem("token"),
          },
        })
        .then((response) => {
          if (response.data.code === "100") {
            this.loadingStatus = false;
            this.upSuccess(response.data);
            message("success", "上传成功", 2000);
            this.fileList = [];
          } else {
            this.loadingStatus = false;
            this.$message.error(response.msg);
          }
        })
        .catch((error) => {
          this.loadingStatus = false;
          this.$message.error("上传失败！");
        });
    },
  },
  updated() {
    if (this.$refs.showIframeRef) {
      // IE
      if (this.$refs.showIframeRef.attachEvent) {
        this.$refs.showIframeRef.attachEvent("onload", () => {
          this.imageLoad = false;
        });
      } else {
        this.$refs.showIframeRef.onload = () => {
          this.imageLoad = false;
        };
      }
    }
  },
  mounted() {
    //console.log(this.typeStatus)
    //console.log(this.oriRowObj);
    //this.checkFileImgNum();
  },
  beforeDestroy() { },
  created() {
    this.routerName = this.$route.name;
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-drawer__header {
  margin-bottom: 10px;
  font-weight: 600;
  letter-spacing: 2px;
  font-size: 17px;
}

.tip-info {
  position: absolute;
  left: 110px;
  top: 22px;
  font-size: 16px;
  color: #ff4f46;
}

.btnClass {
  padding: 5px;
}

.contentBox {
  display: flex;
  justify-content: space-around;

  iframe {
    img {
      width: 100%;
    }
  }

  .box-card {
    .demo-image__lazy {
      background: rgb(245, 245, 245);
      padding: 5px 15px;
      text-align: center;

      .imgs {
        width: 70%;
      }
    }

    .uploadBox {
      padding: 5px;

      ::v-deep ul {
        background: rgba(95, 95, 95, 0.2);
        width: 300px;
      }
    }
  }
}

::v-deep .el-drawer__body {
  overflow: auto;
}

::v-deep .el-drawer__container ::-webkit-scrollbar {
  display: none;
}

::v-deep .el-tabs__header {
  margin: 0;
}
</style>
