<template>
  <div class="">
    <div v-if="['docx', 'xls', 'xlsx', 'txt'].includes(fileType) && !isAudit" class="button_download">
      <!-- <el-button type="text" @click="print">
        打印
      </el-button> -->
      <el-button type="text" @click="handleDownload">
        下载
      </el-button>
    </div>
    <div v-if="isAudit" class="button_download">
      <el-button type="primary" @click="$emit('pass')">
        通过
      </el-button>
      <el-button type="primary" @click="$emit('sendBack')">
        退回
      </el-button>
    </div>
    <div style="width: 100%; height: 100%">
      <div v-if="textValue" id="textValue" v-html="textValue" />
      <el-image
        v-if="imgUrl"
        style="width: 100%; height: 100%; min-height: 100vh"
        :src="imgUrl"
        :preview-src-list="imgUrl.split()"
      />
      <!-- pdf使用iframe -->
      <iframe
        v-if="pdfUrl"
        :src="pdfUrl"
        frameborder="0"
        style="width: 100%; height: 100%; min-height: 100vh"
      />
      <video
        v-if="videoUrl"
        :src="videoUrl"
        controls
        style="width: 100%; height: 100%; max-height: 800px"
      />
      <div v-show="docFile">
        <div ref="file" />
      </div>
      <div v-if="xlsFile" id="excel-view-container">
        <!-- Excel使用tab选项卡来模拟表格里的sheet业 -->
        <el-tabs v-if="sheetNames && sheetNames.length" type="border-card" @tab-click="handleClick">
          <el-tab-pane v-for="(item, index) in sheetNames" :key="index" :label="item">
            <div id="excelView" v-html="excelView" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>
<script>
import * as docx from "docx-preview";
import * as XLSX from "xlsx";
import axios from "axios";

export default {
  props: {
    previewType: {
      type: String,
      default: ""
    },
    previewUrl: {
      type: Blob,
      default: ""
    },
    previewImgUrl: {
      type: String,
      default: ""
    },
    isAudit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileType: "", // 文件类型
      data: "", // 文件路径，blob 类型
      imgUrl: "", // 图片路径
      pdfUrl: "", // pdf路径
      videoUrl: "", // 视频路径
      excelView: "", // 表格转换后的html数据
      docFile: false, // 是否是word文件
      xlsFile: false, // 是否是Excel文件
      execlArraybufferData: null, // Excelblob转换为arraybuff数据
      sheetNames: null, // 从数据中获取到的sheet页数组
      workbooks: null,
      textValue: ""
    };
  },
  watch: {
    previewType: {
      handler(value) {
        this.fileType = value;
      },
      immediate: true, // 重点
      deep: true // 重点
    },

    previewUrl: {
      handler(value) {
        this.data = value;
        this.sheetNames = null;
        this.workbooks = null;
        this.filePreviewPDF();
      },
      immediate: true, // 重点
      deep: true // 重点
    }
  },
  methods: {
    handleDownload() {
      this.$emit("handleDownload");
    },
    // 预览文件
    filePreviewPDF() {
      this.pdfUrl = "";
      this.docFile = false;
      this.xlsFile = false;
      if (this.fileType === "mp4") {
        // pdf和文本类型的，用iframe打开
        this.videoUrl = window.URL.createObjectURL(this.data);
      } else if (this.fileType === "txt") {
        const url = window.URL.createObjectURL(this.data);
        axios.get(url, {
          responseType: "text"
        }).then(res => {
          const text = res.data.replace(/\r\n|\n|\r/g, "<br/>");
          this.textValue = text;
        });
      } else if (this.fileType === "pdf") {
        // pdf和文本类型的，用iframe打开
        this.pdfUrl = window.URL.createObjectURL(this.data);
      } else if (this.fileType === "docx") {
        // word类型的用docx-preview插件
        this.docFile = true;
        this.$nextTick(() => {
          docx.renderAsync(this.data, this.$refs.file).then(x => console.log("docx: finished", x));
          //   console.log(document.getElementsByClassName('docx'), "docx");
        });
      } else if (this.fileType === "xls" || this.fileType === "xlsx") {
        // 表格类型的用xlsx插件
        this.xlsFile = true;
        this.XLSX = XLSX;
        // this.execlType = type;
        const reader = new FileReader();
        reader.readAsArrayBuffer(this.data); // blob类型转换为ArrayBuffer类型
        this.tabChange(0, reader);
      } else if (this.fileType === "png" || this.fileType === "jpg" || this.fileType === "jpeg") {
        this.imgUrl = this.previewImgUrl;
      } else {
        this.handleClose();
        this.$message.error("不支持此文件预览");
      }
    },
    handleClick(data) {
      this.tabChange(data.index);
    },
    tabChange(index, reader) {
      this.excelView = "";
      const XLSX = this.XLSX;
      const _this = this;
      if (!this.sheetNames) {
        // 文件转换加载完成后
        reader.onload = function() {
          const arraybufferData = this.result;
          this.execlArraybufferData = arraybufferData;
          const data = new Uint8Array(arraybufferData); // es2017的方法
          const workbook = XLSX.read(data, { type: "array" }); // 得到表格的array数据
          _this.workbooks = workbook; // 赋值到此组件最外面，一会要用
          const sheetNames = workbook.SheetNames; // 得到execl工作表名称集合，结果类似这样['sheet1','sheet2']
          _this.sheetNames = sheetNames; // 赋值到此组件最外面，一会要用
          const worksheet = workbook.Sheets[sheetNames[index]]; // 获取第几个工作表0就是'sheet1'，以此类推
          _this.excelView = XLSX.utils.sheet_to_html(worksheet); // 把表格的array数据转换成html数据
          _this.$nextTick(() => {
            // DOM加载完毕后执行，解决HTMLConnection有内容但是length为0问题。
            _this.setStyle4ExcelHtml();
          });
        };
      } else {
        const worksheet = this.workbooks.Sheets[this.sheetNames[index]]; // 获取第几个工作表0就是'sheet1'，以此类推
        this.excelView = XLSX.utils.sheet_to_html(worksheet);
      }
    },
    // 设置Excel转成HTML后的样式
    setStyle4ExcelHtml() {
      const excelViewDOM = document.getElementById("excelView");
      if (excelViewDOM) {
        const excelViewTDNodes = excelViewDOM.getElementsByTagName("td"); // 获取的是HTMLConnection
        if (excelViewTDNodes) {
          const excelViewTDArr = Array.prototype.slice.call(excelViewTDNodes);
          Object.keys(excelViewTDArr).forEach(i => {
            const id = excelViewTDArr[i].id; // 默认生成的id格式为sjs-A1、sjs-A2......
            if (id) {
              const idNum = id.replace(/[^0-9]/gi, ""); // 提取id中的数字，即行号
              if (idNum && (idNum === "1" || idNum === 1)) {
                // 第一行标题行
                excelViewTDArr[i].classList.add("class4Title");
              }
              if (idNum && (idNum === "2" || idNum === 2)) {
                // 第二行表头行
                excelViewTDArr[i].classList.add("class4TableTh");
              }
            }
          });
        }
      }
    },
    handleClose() {
      this.$emit("closeDialog", false);
    },
    print() {
      let prinHtml = "";
      if (this.fileType === "docx") {
        prinHtml = Array.from(document.getElementsByClassName("docx"))[0].innerHTML;
      } else if (this.fileType === "xls" || this.fileType === "xlsx") {
        prinHtml = document.getElementById("excelView").innerHTML;
      } else if (this.fileType === "txt") {
        prinHtml = document.getElementById("textValue").innerHTML;
      }
      const iframe = document.createElement("iframe");
      iframe.setAttribute("style", "position:absolute;width:0px;height:0px;left:-500px;top:-500px;");
      const style = `<style>
                        @page{margin:2cm 3cm;}
                        .article-area{margin: 0 50px 0 50px;}
                        .article-title{text-align: center;line-height: 42px;font-size: 22px;padding-top: 5px;font-family: \"å¾®è½¯é›…é»‘\";color: #333333;min-height:55px;}
                        .article-main {font-family: \"å¾®è½¯é›…é»‘\";color: #333333;font-size: 15px;}
                        table {
                            color: #000 !important;
                            width: 100%;
                            border-collapse: collapse;
                            border: solid 1px #000 !important;
                        }
                        tr,td,th {
                            border: solid 1px #000 !important;
                            text-align: center;
                            padding: 10px;
                        }
                        </style>`;
      document.body.appendChild(iframe);
      iframe.contentDocument.write(style + prinHtml);

      iframe.contentDocument.close();
      iframe.contentWindow.onload = setTimeout(() => {
        iframe.contentWindow.focus();
        iframe.contentWindow.print();
        document.body.removeChild(iframe);
      }, 0);
    }
  }
};
</script>
<style lang="scss" scoped>
.button_download {
  display: flex;
  width: 100%;
  justify-content: flex-end;
  margin-bottom: 10px;
}
</style>
