<template>
  <div class="file-preview">
    <div v-if="isSupported">
      <!-- PDF 预览 -->
      <div v-if="fileType === 'pdf'" class="pdf-container">
        <pdf
          ref="pdfComponent"
          v-if="pdfUrl"
          :src="pdfUrl"
          :page="currentPage"
          :rotate="0"
          @loaded="loadCompleted"
          @num-pages="pageCount = $event"
          class="pdf-viewer"
        ></pdf>

        <!-- 将高亮层移到PDF组件后面 -->
        <div class="highlight-layer">
          <div
            v-for="(highlight, index) in highlights"
            :key="index"
            class="highlight-rect"
            :style="getHighlightStyle(highlight)"
          ></div>
        </div>

        <!-- PDF控制器 -->
        <div v-if="pdfLoadComplete" class="pdf-controls">
          <el-button-group>
            <el-button @click="prevPage" :disabled="currentPage <= 1"
              >上一页</el-button
            >
            <el-button @click="nextPage" :disabled="currentPage >= pageCount"
              >下一页</el-button
            >
          </el-button-group>
          <span class="page-info">{{ currentPage }} / {{ pageCount }}</span>
        </div>

        <!-- PDF加载状态 -->
        <div v-if="!pdfLoadComplete" class="pdf-loading">
          <el-progress
            type="circle"
            :percentage="loadingProgress"
          ></el-progress>
          <span>PDF加载中...</span>
        </div>
      </div>

      <!-- 图片预览 -->
      <img
        v-else-if="isImage"
        :src="fileUrl"
        alt="图片预览"
        style="max-width: 100%; max-height: 822px"
      />

      <!-- Word 文档预览 -->
      <div v-if="isWord" class="word-container">
        <!-- 加载中状态 -->
        <div v-if="!wordLoaded && !previewError" class="loading-word">
          <el-progress
            v-if="loadingProgress > 0"
            type="circle"
            :percentage="loadingProgress"
          ></el-progress>
          <span v-else>文档加载中...</span>
        </div>

        <!-- 预览错误状态 -->
        <div v-else-if="previewError" class="preview-error">
          <i class="el-icon-warning-outline"></i>
          <p>{{ errorMessage }}</p>
          <div class="error-actions">
            <el-button type="primary" @click="retryPreview">重试</el-button>
            <el-button @click="downloadFile">下载文件</el-button>
          </div>
        </div>

        <!-- 预览内容 -->
        <div v-else v-html="wordContent" class="word-preview"></div>
      </div>
      <!--  <div
        v-if="isWord && wordLoaded"
        v-html="wordContent"
        class="word-preview"
      ></div>
      <div v-else-if="isWord && !wordLoaded" class="loading-word">
        {{ wordLoadingError ? "加载失败，请重试" : "加载中..." }}
      </div> -->
      <div
        v-if="isExcel"
        id="luckysheet"
        style="width: 100%; height: 822px"
      ></div>
      <!-- 其他 Office 文档预览 -->
      <iframe
        v-else-if="isOffice"
        :src="officePreviewUrl"
        width="100%"
        height="822px"
      ></iframe>

      <!-- 文本文件预览 -->
      <pre
        v-else-if="fileType === 'txt'"
        style="max-height: 822px; overflow: auto"
        >{{ textContent }}</pre
      >
    </div>
    <div v-else class="unsupported-file">
      不支持预览该文件类型，<a :href="fileUrl" download>点击下载</a>
    </div>
  </div>
</template>
  
  <script>
import { searchTaskInfo } from "@/api/knowledge";
import mammoth from "mammoth";
// 添加 LuckyExcel 导入
import LuckyExcel from "luckyexcel";
import { saveAs } from "file-saver";
import JSZip from "jszip";
import pdf from "vue-pdf";

export default {
  components: {
    pdf,
  },
  props: {
    fileUrl: {
      type: String,
      required: true,
    },
    fileType: {
      type: String,
      required: true,
    },
    type: {
      type: String,
      required: true,
    },
    pageNum: {
      type: String,
      required: true,
    },
    coordinate: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      textContent: "",
      wordContent: "",
      supportedTypes: [
        "pdf",
        "doc",
        "docx",
        "xls",
        "xlsx",
        "ppt",
        "pptx",
        "txt",
        "jpg",
        "jpeg",
        "png",
        "gif",
      ],
      wordLoaded: false,
      wordLoadingError: false,
      internalFileUrl: "", // 新增：内部使用的 URL

      loadingProgress: 0,
      wordContent: "",
      wordLoaded: false,
      previewError: false,
      errorMessage: "",
      docData: null, // 保存文档数据用于下载
      pdfUrl: null,
      pdfLoadComplete: false,
      currentPage: 1,
      pageCount: 0,
      highlights: [], // 存储高亮区域
      pdfScale: 1, // PDF缩放比例
      pdfViewport: null, // PDF视口信息
      startX: 0,
      endY: 0,
    };
  },
  watch: {
    fileUrl: {
      immediate: true,
      handler(newValue) {
        /* this.internalFileUrl = newValue; */
        if (this.isWord) {
          this.loadWordContent();
        }
      },
    },
    pageNum: {
      immediate: true,
      handler(newValue) {
        if (this.fileType === "pdf" && newValue) {
          this.currentPage = parseInt(newValue);
        }
      },
    },

    fileUrl: {
      immediate: true,
      async handler(newValue) {
        if (this.fileType === "pdf" && newValue) {
          await this.initPdf();
        }
      },
    },
    coordinate: {
      handler(newValue) {
        console.log(newValue);
        if (newValue && this.pdfLoadComplete) {
          this.addHighlight(newValue);
        }
      },
    },
  },
  computed: {
    officePreviewUrl() {
      // 添加此计算属性
      if (this.isOffice) {
        // 使用微软Office Online Viewer
        return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
          this.fileUrl
        )}`;
        // 或者使用Google Docs Viewer
        // return `https://docs.google.com/gview?url=${encodeURIComponent(this.fileUrl)}&embedded=true`;
      }
      return "";
    },
    isSupported() {
      return this.supportedTypes.includes(this.fileType);
    },
    isImage() {
      return ["jpg", "jpeg", "png", "gif"].includes(this.fileType);
    },
    isWord() {
      return ["doc", "docx"].includes(this.fileType) || this.type === "doc";
    },
    isExcel() {
      return ["xls", "xlsx"].includes(this.fileType);
    },
    isOffice() {
      return ["ppt", "pptx"].includes(this.fileType);
    },
    pdfViewerUrl() {
      if (this.fileType === "pdf") {
        // 确保添加初始页码参数
        return `${this.fileUrl}#page=${this.pageNum}`;
      }
      return this.fileUrl;
    },
  },
  mounted() { 
    console.log(this.isWord);
    if (this.fileType === "txt") {
      this.loadTextContent();
    } else if (this.$route.query.type == "docx") {
     this.loadWordContent();
    } else if (this.$route.query.type == "xlsx") {
      this.loadExcelContent();
    }
    window.addEventListener("resize", this.updateHighlightPosition);
  },
  methods: {
    /* 翻页 */

    scrollToPage(pageNumber) {
      const iframe = this.$refs.previewFrame;
      if (!iframe || !iframe.contentWindow) return;

      const tryScrollMethods = [
        // 方法1: 使用PDFViewerApplication API
        () => {
          iframe.contentWindow.PDFViewerApplication.page = parseInt(pageNumber);
          return true;
        },
        // 方法2: 使用PDFViewerApplication.pdfViewer
        () => {
          iframe.contentWindow.PDFViewerApplication.pdfViewer.currentPageNumber =
            parseInt(pageNumber);
          return true;
        },
        // 方法3: 通过URL参数重新加载
        () => {
          const newUrl = this.fileUrl.split("#")[0] + `#page=${pageNumber}`;
          if (iframe.src !== newUrl) {
            iframe.src = newUrl;
          }
          return true;
        },
      ];

      // 依次尝试不同的方法
      for (const method of tryScrollMethods) {
        try {
          if (method()) {
            console.log("PDF页面跳转成功");
            return;
          }
        } catch (error) {
          console.log("尝试下一种跳转方法");
          continue;
        }
      }

      // 所有方法都失败时的处理
      console.warn("PDF跳转失败，请检查PDF查看器配置");
      this.$message.warning("PDF跳转可能不成功，请手动滚动到目标页面");
    },

    async loadWordContent() {
      this.wordLoaded = false;
      this.loadingProgress = 0;
      this.previewError = false;
      this.errorMessage = "";

      try {
        // 获取文档URL
        const res = await searchTaskInfo({
          page: 1,
          page_size: 10,
          document_id: this.$route.query.id,
        });

        const docUrl = res.data.documentUrl;

        // 下载文件并显示进度
        const response = await fetch(docUrl);
        const reader = response.body.getReader();
        const contentLength = +response.headers.get("Content-Length");

        let receivedLength = 0;
        let chunks = [];

        while (true) {
          const { done, value } = await reader.read();

          if (done) break;

          chunks.push(value);
          receivedLength += value.length;

          this.loadingProgress = Math.round(
            (receivedLength / contentLength) * 100
          );
        }

        // 合并数据
        this.docData = new Uint8Array(receivedLength);
        let position = 0;
        for (let chunk of chunks) {
          this.docData.set(chunk, position);
          position += chunk.length;
        }

        // 处理不同的文档格式
        if (this.fileType === "doc") {
          try {
            const result = await mammoth.convertToHtml({
              arrayBuffer: this.docData.buffer,
            });
            this.wordContent = this.enhanceWordContent(result.value);
            this.wordLoaded = true;
          } catch (error) {
            throw new Error("无法预览该文档，可能是格式不兼容或文件已损坏");
          }
        } else if (this.fileType === "docx") {
          const result = await mammoth.convertToHtml({
            arrayBuffer: this.docData.buffer,
          });
          this.wordContent = this.enhanceWordContent(result.value);
          this.wordLoaded = true;
        }
      } catch (error) {
        console.error("文档加载失败:", error);
        this.previewError = true;
        this.errorMessage = error.message || "文档加载失败，请重试或下载查看";
      }
    },

    // 重试预览
    retryPreview() {
      this.loadWordContent();
    },

    // 下载文件
    downloadFile() {
      if (this.docData) {
        const blob = new Blob([this.docData], {
          type:
            this.fileType === "doc"
              ? "application/msword"
              : "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        });
        saveAs(blob, `document.${this.fileType}`);
      } else {
        this.$message.error("文件数据不存在，请重试");
      }
    },

    // 增强文档内容显
    enhanceWordContent(content) {
      return `
        <div class="enhanced-word-content">
          <style>
            .enhanced-word-content {
              font-family: "Microsoft YaHei", Arial, sans-serif;
              line-height: 1.6;
              color: #333;
              padding: 20px;
            }
            .enhanced-word-content h1 { font-size: 24px; margin: 20px 0; }
            .enhanced-word-content h2 { font-size: 20px; margin: 16px 0; }
            .enhanced-word-content p { margin: 12px 0; }
            .enhanced-word-content img { max-width: 100%; height: auto; }
            .enhanced-word-content table { border-collapse: collapse; width: 100%; }
            .enhanced-word-content td, .enhanced-word-content th { 
              border: 1px solid #ddd; 
              padding: 8px; 
            }
          </style>
          ${content}
        </div>
      `;
    },
    blobToArrayBuffer(blob) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsArrayBuffer(blob);
      });
    },
    async loadTextContent() {
      try {
        // 获取文档 URL
        /*    if (this.type !== "ai") { */
        const res = await searchTaskInfo({
          page: 1,
          page_size: 10,
          document_id: this.$route.query.id,
        });
        this.internalFileUrl = res.data.documentUrl;
        /* } else {
          this.internalFileUrl = localStorage.getItem("href");
        } */

        // 获取文本内容
        const response = await fetch(this.internalFileUrl);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        this.textContent = await response.text();
      } catch (error) {
        console.error("加载文本内容时出错:", error);
        this.textContent = `无法加载文本内容: ${error.message}`;
        this.$message.error(`文本加载失败: ${error.message}`);
      }
    },
    async loadExcelContent() {
      try {
        let url;
        // 获取文档 URL
        /*  if (this.type !== "ai") { */
        const res = await searchTaskInfo({
          page: 1,
          page_size: 10,
          document_id: this.$route.query.id,
        });
        this.internalFileUrl = res.data.documentUrl;
        url = res.data.documentUrl;
        /*  } else {
          this.internalFileUrl = localStorage.getItem("href");
          url=localStorage.getItem("href")
        } */

        const response = await fetch(url);
        const blob = await response.blob();

        // 使用 LuckyExcel 加载文件
        LuckyExcel.transformExcelToLucky(blob, function (exportJson) {
          if (exportJson.sheets == null || exportJson.sheets.length === 0) {
            alert("Failed to load Excel file");
            return;
          }

          // 初始化 luckysheet
          luckysheet.create({
            container: "luckysheet",
            data: exportJson.sheets,
            // 设置只读模式
            showinfobar: false,
            allowEdit: false,
            showtoolbar: false,
          });
        });
      } catch (error) {
        console.error("加载Excel文档内容时出错:", error);
        this.$message.error(`Excel文档加载失败: ${error.message}`);
      }
    },
    // 添加 iframe 加载完成的处理函数
    handleIframeLoad() {
      const iframe = this.$refs.previewFrame;
      if (iframe && iframe.contentWindow) {
        // 等待PDF.js完全初始化
        setTimeout(() => {
          this.scrollToPage(this.pageNum);
        }, 1000); // 给PDF.js足够的加载时间
      }
    },

    // 添加消息处理函数
    handlePdfMessage(event) {
      // 处理来自 PDF.js 的消息
      if (event.data && event.data.type === "pdfLoaded") {
        // PDF 加载完成，可以执行翻页操作
        this.scrollToPage(this.pageNum);
      }
    },
    // 监听页码变化
    watchPageChange() {
      const iframe = this.$refs.previewFrame;
      if (iframe && iframe.contentWindow) {
        try {
          // 监听PDF.js的页码变化事件
          iframe.contentWindow.PDFViewerApplication.eventBus.on(
            "pagechanging",
            (evt) => {
              console.log("PDF页码变化:", evt.pageNumber);
            }
          );
        } catch (error) {
          console.warn("无法监听PDF页码变化:", error);
        }
      }
    },
    async initPdf() {
      try {
        if (this.type !== "ai") {
          const res = await searchTaskInfo({
            page: 1,
            page_size: 10,
            document_id: this.$route.query.id,
          });
          this.pdfUrl = { url: res.data.documentUrl };
        } else {
          this.pdfUrl = { url: this.fileUrl };
        }
        // 设置初始页码
        this.currentPage = parseInt(this.pageNum) || 1;
      } catch (error) {
        console.error("PDF初始化失败:", error);
        this.$message.error("PDF加载失败，请重试");
      }
    },

    // PDF文档完全加载完成
    loadCompleted() {
      this.pdfLoadComplete = true;
      this.loadingProgress = 100;

      // 确保在PDF完全渲染后更新高亮
      setTimeout(() => {
        this.updateHighlightPosition();
        // 如果有coordinate属性，添加高亮
        if (this.coordinate) {
          this.addHighlight(this.coordinate);
        }
      }, 500);
    },

    // PDF翻页控制
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },

    nextPage() {
      if (this.currentPage < this.pageCount) {
        this.currentPage++;
      }
    },

    // 修改添加高亮方法
    addHighlight(coordinates) {
      try {
        console.log("Adding highlight with coordinates:", coordinates);
        let coords = JSON.parse(coordinates);

        // 确保坐标数组格式正确
        if (!Array.isArray(coords) || coords.length !== 4) {
          console.error("Invalid coordinates format");
          return;
        }

        // 正确获取起始点和终点坐标
        const startX = coords[0]; // x1
        const endY = coords[1]; // y1
        const endX = coords[2]; // x2
        const startY = coords[3]; // y2

        // 计算矩形的位置和尺寸
        const highlight = {
          x: Math.min(startX, endX), // 取两个x坐标的最小值作为左边界
          y: Math.min(startY, endY), // 取两个y坐标的最小值作为上边界
          width: Math.abs(startX - endX), // 宽度为x坐标差的绝对值
          height: Math.abs(startY - endY), // 高度为y坐标差的绝对值
        };

        console.log("Processed highlight:", highlight);
        this.startX = startX;
        this.endY = endY;
        this.highlights = [highlight];

        // 强制更新高亮位置
        this.$nextTick(() => {
          this.updateHighlightPosition();
        });
      } catch (error) {
        console.error("Error adding highlight:", error);
      }
    },

    // 修改更新高亮位置方法
    updateHighlightPosition() {
      const pdfComponent = this.$refs.pdfComponent;
      if (!pdfComponent || !pdfComponent.$el) return;

      const canvas = pdfComponent.$el.querySelector("canvas");
      if (!canvas) return;

      // 获取PDF页面的实际尺寸和缩放比例
      const rect = canvas.getBoundingClientRect();
      const scaleX = rect.width / canvas.width;
      const scaleY = rect.height / canvas.height;

      this.pdfScale = {
        scaleX,
        scaleY,
        width: rect.width,
        height: rect.height,
      };

      console.log("PDF scale updated:", this.pdfScale);
    },

    // 修改高亮样式计算方法
    getHighlightStyle(highlight) {
      if (!this.pdfScale) return {};

      const { scaleX, scaleY, height } = this.pdfScale;

      // PDF坐标系转换（PDF坐标系原点在左下角，需要转换为左上角）
      return {
        position: "absolute",
        left: `${this.startX}px`,
        top: `${this.endY}px`,
        width: `${highlight.width * scaleX}px`,
        height: `${highlight.height * scaleY}px`,
        backgroundColor: "rgba(255, 152, 0, 0.1)", // 淡橙色半透明背景
        border: "2px solid #FF9800", // 橙色边框
        pointerEvents: "none",
        zIndex: 100,
      };
    },
  },
  // 组件销毁时清理事件监听器
  beforeDestroy() {
    window.removeEventListener("message", this.handlePdfMessage);
    window.removeEventListener("resize", this.updateHighlightPosition);
  },
};
</script>
  
  <style scoped>
.file-preview {
  width: 100%;
  /* height: 100vh; */
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.unsupported-file {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 18px;
  color: #909399;
}
.word-preview {
  padding: 20px;
  background-color: white;
}
.loading-word {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 18px;
  color: #909399;
}
.preview-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #909399;
  text-align: center;
}

.preview-error i {
  font-size: 48px;
  color: #f56c6c;
  margin-bottom: 20px;
}

.preview-error p {
  font-size: 16px;
  margin-bottom: 20px;
}

.error-actions {
  display: flex;
  gap: 12px;
}

.loading-word {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  gap: 16px;
}

.word-preview {
  overflow-y: auto;
  max-height: 830px;
  padding: 20px;
}

/* 添加PDF预览相关样式 */
.pdf-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.pdf-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #f56c6c;
}

.pdf-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.pdf-controls {
  position: fixed;
  bottom: 0px;
  left: 77%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 10px 20px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
  margin: 0 auto;
}

.page-info {
  font-size: 14px;
  color: #606266;
}

/* PDF页面容器样式 */
.vuepdfiframe {
  width: 100% !important;
  height: 750px !important; /* 留出空间给分页控件 */
}

/* 新增PDF查看器样式 */
.pdf-viewer {
  position: relative;
  z-index: 1;
}

/* PDF页面样式 */
::v-deep .pdf-viewer canvas {
  max-width: 771px;
  height: 1024px !important;
}

/* 确保PDF内容居中显示 */
:deep(.vue-pdf-embed) {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 90%;
  height: 100%;
}

.highlight-layer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 2;
}

.highlight-rect {
  position: absolute;
  border: 2px solid #ff9800;
  box-shadow: 0 0 4px rgba(255, 152, 0, 0.5);
  background-color: rgba(255, 152, 0, 0.1);
  mix-blend-mode: multiply;
  transition: all 0.3s ease;
  animation: highlight-flash 2s infinite;
}

.pdf-container {
  position: relative;
  width: 100%;
  height: 100%;
}

/* 添加动画效果 */
@keyframes highlight-flash {
  0% {
    border-color: rgba(255, 152, 0, 0.3);
  }
  50% {
    border-color: rgba(255, 152, 0, 1);
  }
  100% {
    border-color: rgba(255, 152, 0, 0.3);
  }
}

.highlight-rect {
  animation: highlight-flash 2s infinite;
}
</style>