<!-- Dialog.vue -->
<template>
  <el-dialog
    :visible.sync="visible"
    @update:visible="handleUpdateVisible"
    title="预览"
    width="80%"
    :before-close="beforeClose"
  >
    <div>
      <!-- PDF预览 -->
      <div v-if="fType === 'pdf'">
        <!-- <div ref="pdfContainer" style="width: 100%; height: 600px"></div> -->
        <!-- <iframe :src="fileUrl" width="100%" height="600px"></iframe> -->
        <div v-if="previewData.pdfPages > 0">
          <!-- 使用 v-for 渲染每一页 PDF -->
          <div v-for="pdfPage in previewData.pdfPages" :key="pdfPage">
            <pdf :src="previewData.src" :page="pdfPage" width="100%"></pdf>
          </div>
        </div>

        <!-- 如果没有 PDF 页数，显示空提示 -->
        <div v-else>
          <p>无法加载 PDF 文件</p>
        </div>
      </div>

      <!-- Excel预览 -->
      <div v-else-if="fType === 'xls' || fType === 'xlsx'">
        <el-table
          :data="previewData.content.tableContent"
          style="width: 100%"
          border
        >
          <!-- 动态生成表头 -->
          <el-table-column
            v-for="(column, index) in previewData.content.tableThead"
            :key="index"
            :label="column"
            :prop="column"
          >
          </el-table-column>
        </el-table>
      </div>
      <div v-else-if="fType === 'jpg' || fType === 'png'">
        <img :src="imgUrl" alt="图片预览" style="width: auto; height: auto" />
      </div>
      <!-- Word预览 -->
      <div v-else-if="fType === 'docx'||fType === 'doc'">
        <div ref="word">
          <div v-html="wordContent"></div>
        </div>
      </div>

      <div v-else-if="fType === 'txt'">
        <div ref="wordContainer">{{ text }}</div>
      </div>

      <!-- 不支持的文件类型 -->
      <div v-else>
        <p>Unsupported file type</p>
        <p>不支持的文件类型</p>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">关 闭</el-button>
      <!-- <el-button type="primary" @click="handleConfirm">确 定</el-button> -->
    </div>
  </el-dialog>
</template>

<script>
import { previewFileTabFileInfoById } from "@/api/unified-access/access-standard";
import { getToken } from "@/utils/auth";
import * as xlsx from "xlsx";
import pdf from "vue-pdf";

import mammoth from "mammoth";

export default {
  name: "PreviewDialog",
  components: {
    pdf,
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    rowObj: {},
    // fileUrl: String, // 文件的URL
    fileType: String, // 文件类型，如 'pdf', 'xls', 'xlsx', 'doc', 'docx'
    fileUrl: "", // 文件的 Blob URL
    pdfDoc: null, // PDF 文档对象
    pageNum: 1, // 当前页码
  },
  data() {
    return {
      row: {},
      text: "",
      previewData: {
        content: {
          tableContent: [], // Excel 数据内容
          tableThead: [], // Excel 表头
        },
        src: "", // 临时 URL，用于加载 PDF
        pdfPages: 0, // PDF 页数
      },
      imgUrl: "",
      wordContent: "", // 存储转换后的 HTML 内容
      visible: this.value,
      fType: this.fileType,
      url: this.fileType,
    };
  },
  watch: {
    value(newVal) {
      this.visible = newVal;
    },
    visible(newVal) {
      this.$emit("input", newVal);
    },

    fileType: {
      handler(newVal) {
        console.log(newVal, "newVal");
        this.fType = newVal;
      },
      deep: true, // 深入监听
      immediate: true,
    },

    rowObj: {
      handler(newVal) {
        this.row = newVal;
      },
      deep: true, // 深入监听
      immediate: true,
    },
  },
  mounted() {
    console.log(this.row, "this.row");
    console.log(this.fType, "this.fType");
    // if (this.fType === "pdf") {
    // } else if (this.fType === "xls" || this.fType === "xlsx") {
    //   this.getFile(this.row);
    // } else if (this.fType === "doc" || this.fType === "docx") {
    // }
    this.getFile(this.row);
  },
  methods: {
    getFile(row) {
      previewFileTabFileInfoById(row.fileId).then((res) => {
        let blob = new Blob([res]);
        console.log(blob, "blob");
        //通过switch，调用不同类型文件的处理函数
        switch (this.fType) {
          case "txt":
            console.log("txt");
            // this.previewData.type = "txt";
            this.handleTxtFilePreview(blob);
            break;
          case "png":
            // this.previewData.type = "image";
            this.handleImageFilePreview(blob);
            break;
          case "jpg":
            // this.previewData.type = "image";
            this.handleImageFilePreview(blob);
            break;
          case "xls":
            // this.previewData.type = "excel";
            this.handleExcelFilePreview(blob);
            break;
          case "xlsx":
            // this.previewData.type = "excel";
            this.handleExcelFilePreview(blob);
            break;
          case "docx":
            // this.previewData.type = "word";
            this.handleWrodFilePreview(blob);
            break;
          case "pdf":
            // this.previewData.type = "pdf";
            this.handlePdfFilePreview(blob);
            break;
        }
      });
    },

    handleTxtFilePreview(blob) {
      let reader = new FileReader();
      reader.readAsArrayBuffer(blob);
      reader.onload = (evt) => {
        let ints = new Uint8Array(evt.target.result); //要使用读取的内容，所以将读取内容转化成Uint8Array
        ints = ints.slice(0, blob.size); //截取一段读取的内容
        this.text = new TextDecoder("utf-8").decode(ints); //二进制缓存区内容转化成中文（即也就是读取到的内容）
        console.log(this.text, "this.text");
      };
    },

    handleExcelFilePreview(blob) {
      let reader = new FileReader();
      reader.readAsArrayBuffer(blob);
      reader.onload = (evt) => {
        let ints = new Uint8Array(evt.target.result); //要使用读取的内容，所以将读取内容转化成Uint8Array
        ints = ints.slice(0, blob.size);
        let workBook = xlsx.read(ints, { type: "array" }); // 6. 使用 xlsx 解析 Excel 文件数据
        let sheetNames = workBook.SheetNames;
        let sheetName = sheetNames[0]; //  默认获取第一个工作表
        let workSheet = workBook.Sheets[sheetName];

        //获取Excle内容，并将空内容用空值保存
        let excelTable = xlsx.utils.sheet_to_json(workSheet, { defval: "" });

        // 获取Excel头部
        let tableThead = Array.from(Object.keys(excelTable[0])).map((item) => {
          return item;
        });
        this.previewData.content = {};
        this.previewData.content.tableContent = excelTable;
        this.previewData.content.tableThead = tableThead;
        this.previewDialogOpen = true;
      };
    },
    handleImageFilePreview(blob) {
      this.imgUrl = URL.createObjectURL(blob);
    },
    handlePdfFilePreview(blob) {
      this.previewData.src = URL.createObjectURL(blob);
      let loadingTask = pdf.createLoadingTask(this.previewData.src);

      loadingTask.promise.then((pdf) => {
        this.previewData.pdfPages = pdf.numPages;
      });
    },
    // 处理 Word 文件预览
    handleWrodFilePreview(blob) {
      this.previewDialogOpen = true;

      // 使用 FileReader 读取文件并转换为 HTML
      let reader = new FileReader();
      reader.readAsArrayBuffer(blob);
      reader.onload = (evt) => {
        let arrayBuffer = evt.target.result;

        // 使用 mammoth 转换 Word 文件为 HTML
        mammoth
          .convertToHtml({ arrayBuffer: arrayBuffer })
          .then((result) => {
            this.wordContent = result.value; // 获取转换后的 HTML
          })
          .catch((err) => {
            console.error("Word 文件预览失败：", err);
          });
      };
    },
    handleUpdateVisible(val) {
      this.visible = val;
    },
    beforeClose(done) {
      this.visible = false;
      this.$emit("before-close", done);
    },
    // 取消按钮处理方法
    handleCancel() {
      this.visible = false;
      this.$emit("cancel"); // 可以在父组件监听 'cancel' 事件
    },
  },
};
</script>

<style scoped lang="scss">
/* 你可以根据需要为弹窗添加样式 */
img {
  max-width: 100%;
  max-height: 600px; // 控制图片的最大高度
  display: block;
  margin: 0 auto;
}

.pdf-container {
  margin: 20px 0;
}

.pdf-container img {
  max-width: 100%;
  display: block;
  margin: 0 auto;
}
</style>
