<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="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="isOriginEdit">
                  <el-input type="text"  @keyup.enter.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>
        </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">
              <!-- 查看原文 -->
              <div class="demo-image__lazy">
                <!-- <el-image v-show="imgType &&imgType != 'pdf'  " class="imgs" :src="picUrl" fit="cover"></el-image> -->
                <!-- 不是电子档案除录音、录像 分类-->
                <iframe v-if="treeRow.className!='电子档案'" style="text-alin:center" noresize
                  align=center width="100%" height="750px" :src="picUrl" frameborder="0" scrolling="no"></iframe>
                <video ref="videoS" v-if="fileType=='mp4' && videoSrc" :src="videoSrc" controls="controls"
                  height="600px" :muted="muteStatus" width="100%">您的浏览器不支持视频播放
                </video>

                <audio ref="audioS" v-if="fileType=='mp3' && musicSrc" :src="musicSrc" controls
                  autoloop></audio>
                <!--  -->
                <!-- -->
                <!--  -->
              </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 label="名称：">
                  <span>{{metadata.name}}</span>
                </el-form-item>
                <el-form-item label="文件类型：">
                  <span>{{metadata.type}}</span>
                </el-form-item>
                <el-form-item label="分辨率：">
                  <span>{{metadata.resolvingPower}}</span>
                </el-form-item>
                <el-form-item label="宽度：">
                  <span>{{metadata.width}}</span>
                </el-form-item>
                <el-form-item label="高度：">
                  <span>{{metadata.height}} </span>
                </el-form-item>
                <el-form-item label="水平分辨率：">
                  <span> {{metadata.widthDpi}}</span>
                </el-form-item>
                <el-form-item label="垂直分辨率：">
                  <span>{{metadata.heightDpi}}</span>
                </el-form-item>
                <el-form-item label="位深度：">
                  <span>{{metadata.pixelSize}}</span>
                </el-form-item>
                <el-form-item label="大小：">
                  <span>{{metadata.length}}</span>
                </el-form-item>
              </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
} 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 {
      currentClickImage:{},
      fileType:'', // 文件类型；
      loadingText:'上传中...',
      loadingStatus:false,
      tableheight: window.innerHeight - 130,
      routerName: "",
      activeName: "1",
      addStatus: false,
      lookStatus: true,
      showStatus: false,
      backData: [],
      tableDataOrigin: [],
      picUrl: "",
      archiveNum: null,
      oriTable: {},
      orirow: {},
      orikey: null,
      params: {},
      multipleSelection: [],
      fileList: [],
      fileName: [],
      metadata: {},
      rowTable: {},
      imgType: "pdf",
      ocrText: "",
      videoSrc: "",
      videoImg: "",
      playStatus: "",
      muteStatus: "",
      musicSrc: "",
      oriRowObj: {},
      currentImageIndex:0,
      checkText:"", // 校验信息
      isOriginEdit:false,//原文名称是否可编辑
    };
  },
  methods: {
    // 原文向下、向上、重命名功能
    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.isOriginEdit = true;
        return;
      }else if(type=='focus'){
        return;
      }else if(type=='blur'){ // 原文失去焦点时
        this.isOriginEdit = false;
        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){
          message('success',res.msg,3000);
          // 刷新数据；
          this.RefreshTable();
        }
      })
    },
    // 校验原文数量与页码是否匹配
    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";
        getOneTable(this.params).then((res) => {
          this.tableDataOrigin = res.body.list;
          message("success", "恢复成功", 3000);
        });
      });
    },
    handleClose() {
      if (this.fileType === "mp3" && this.$refs.audioS) {
        this.$refs.audioS.pause();
      }
      if (this.fileType === "mp4" && this.$refs.videoS) {
        this.$refs.videoS.pause();
      }
      this.$emit("handleClose");
      this.imgType = "pdf";
    },
    // 点击查看图片
    previewImg(row) {
      this.fileType = row.file_type;
      if (this.treeRow.className != "电子档案") {
        this.$refs.tableForEach.clearSelection();
        this.$refs.tableForEach.toggleRowSelection(row);
        this.rowTable = row;
        let name = row.file_name_server.replace(".jpg", ".pdf");
        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 (row.file_type === "pdf") {
        // this.imgType = 'pdf'
        //   this.metadata = {}
        //   return
        // } else {
        //   this.imgType = 'img'
        // }
        if (row.file_name.indexOf(".pdf") === -1) {
          let data = {
            fileName: row.file_name,
            url: this.picUrl,
            path: row.file_path,
            fileNameServer: row.file_name_server,
          };
          pictureMetadata(data).then((res) => {
            this.metadata = res.body;
          });
          if (row.file_content) {
            this.ocrText = row.file_content;
            return;
          }
          let orcData = {
            id: row.id,
            tableName: this.oriTable.tableName,
          };
          getWord(orcData).then((res) => {
            this.ocrText = res.body.word;
          });
        } else {
          this.metadata = {};
          this.ocrText = "";
        }
      } else {
        const prefix =
          process.env.NODE_ENV === "development"
            ? "http://" +
              localStronge.getServiceip().ip +
              ":" +
              localStronge.getServiceip().host
            : "http://" + window.location.host;
        if (this.fileType === "mp4") {
          this.videoSrc =
            prefix +
            "/point-strategy/v/archiveFile/showImg?fileName=" +
            row.file_name_server +
            "&path=" +
            row.file_des +
            "&data=" +
            new Date()+'&userId='+sessionStorage.getItem("userid");
        } else {
          this.musicSrc =
            prefix +
            "/point-strategy/v/archiveFile/showImg?fileName=" +
            row.file_name_server +
            "&path=" +
            row.file_des +
            "&data=" +
            new Date()+'&userId='+sessionStorage.getItem("userid");
        }
        this.activeName = "1";
      }

      // let orcData = {
      //   filePath: row.file_des + "/" + row.file_name_server
      // }
      // getOcrImageWord(orcData).then(res => {
      //   this.ocrText = res.body.ocrImageWord
      // })
    },
    //上传成功
    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";
        getOneTable(this.params).then((res) => {
          this.tableDataOrigin = res.body.list;
        });
      }
    },
    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";
          getOneTable(this.params).then((res) => {
            this.tableDataOrigin = res.body.list;
          });
        });
        updateTempArchiveFileNumObject(paramsOut).then((res) => {
          this.params.conditionMap.file_status = "2";
          getOneTable(this.params).then((res) => {
            this.backData = res.body.list;
          });
        });
      });
    },
    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 === "pdf") {
            message("warning", "请选择jpg图片", 3000);
            return;
          }
          (data.fileId = this.multipleSelection[0].id),
            archiveSeal(data).then((res) => {
              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;
      }
    },
    //刷新
    RefreshTable() {
      this.$emit("getData", this.orikey);
      this.params.conditionMap.file_status = "1";
      getOneTable(this.params).then((res) => {
        this.tableDataOrigin = res.body.list;
      });
    },
    //勾选原文表
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 上传发生变化钩子
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
    // 删除之前钩子
    handleFileheaders(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("上传失败！");
        });
    },
  },
  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;

  .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>
