<template>
  <div class="preview">
    <div ref="docfile" v-if="fileType === 'doc'"></div>
    <div v-html="tableau" v-else-if="fileType === 'xls'"></div>
    <PDF
      :src="url"
      v-else-if="fileType === 'pdf'"
      v-for="i in numPages"
      :key="i"
      :page="i"
    ></PDF>
    <div v-else>暂不支持当前文件格式预览</div>
  </div>
</template>

<script>
const docx = require("docx-preview");
window.JSZip = require("jszip");
import axios from "axios";
import * as XLSX from "xlsx";
import PDF from "vue-pdf";
export default {
  name: "PreviewComponents",
  props: {
    url: {
      type: String,
      default: "",
    },
  },
  components: { PDF },
  data() {
    return {
      fileType: null,
      tableau: null,
      numPages: null,
    };
  },
  mounted() {
    console.log(this.url);
    if (this.url.indexOf(".docx") > 0 || this.url.indexOf(".doc") >= 0) {
      this.fileType = "doc";
      axios({
        url: this.url,
        responseType: "blob",
      }).then(({ data }) => {
        docx.renderAsync(data, this.$refs.docfile);
      });
    } else if (this.url.indexOf(".xlsx") > 0 || this.url.indexOf(".xls") > 0) {
      this.fileType = "xls";
      axios
        .get(this.url, {
          responseType: "arraybuffer", // 设置响应体类型为arraybuffer
        })
        .then(({ data }) => {
          let workbook = XLSX.read(new Uint8Array(data), { type: "array" }); // 解析数据
          var worksheet = workbook.Sheets[workbook.SheetNames[0]]; // workbook.SheetNames 下存的是该文件每个工作表名字,这里取出第一个工作表
          this.tableau = XLSX.utils.sheet_to_html(worksheet); // 渲染
        });
    } else if (this.url.indexOf(".pdf") > 0) {
      this.fileType = "pdf";
      let loadingTask = PDF.createLoadingTask(this.url);
      loadingTask.promise
        .then((pdf) => {
          this.numPages = pdf.numPages;
        })
        .catch((err) => {
          console.error("pdf 加载失败", err);
        });
    } else if (
      this.url.indexOf(".jpeg") > 0 ||
      this.url.indexOf(".png") > 0 ||
      this.url.indexOf(".bmp") > 0
    ) {
      this.fileType = "img";
    }
  },
  methods: {},
};
</script>

<style lang="scss" scoped>
.preview {
  max-height: 600px;
  overflow-y: auto;
}
</style>