<template>
  <a-modal
    :visible="visible"
    :footer="null"
    @cancel="handleCancel"
    style="text-align: center"
    :width="modalWidth"
    :dialog-style="dialogStyle"
  >
    <!-- 标题栏下载按钮 -->
    <template #title>
      <div class="modal-header">
        <span>文件预览</span>
        <a-button
          type="primary"
          size="small"
          icon="download"
          @click="handleDownload"
          class="download-btn"
        >下载</a-button>
        <div v-if="fileType === 'docfile'" style="margin-left: 20px">
          <a-button :disabled="pageNum <= 1" @click="prevPage">上一页</a-button>
          <span>第 {{ pageNum }} 页 / 共 {{ totalPages }} 页</span>
          <a-button :disabled="pageNum >= totalPages" @click="nextPage">下一页</a-button>
        </div>
      </div>
    </template>

    <div v-if="fileType === 'image'">
      <img :src="fileUrl" alt="Preview" style="max-width: 100%; max-height: 80vh;" />
    </div>
    <div v-else-if="fileType === 'docfile'">
      <div class="pdf-viewer">
        <canvas ref="pdfCanvas"></canvas>
      </div>
    </div>
    <div v-else-if="fileType === 'video'">
      <video controls :src="fileUrl" style="max-width: 100%; max-height: 80vh;"></video>
    </div>
    <div v-else>
      不支持的文件类型
    </div>
  </a-modal>
</template>

<script>
import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf';
import pdfjsWorker from 'pdfjs-dist/legacy/build/pdf.worker.entry';
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker;

export default {
  name: "FilePreview",
  props: {
    visible: { type: Boolean, default: false },
    fileUrl: { type: String, required: true },
    fileType: { type: String, required: true },
    fileName: { type: String, required: false, default: '' } // 文件名prop
  },
  computed: {
    modalWidth() {
      if (this.fileType === "docfile") {
        this.handlePreview();
        this.dialogStyle={ top: '0px' }
        return "80%";
      }
      this.dialogStyle={ top: '50px' }
      return "50%";
    },
  },
  data() {
    return {
      pdfDoc: null, // PDF 文档对象
      pageNum: 1, // 当前页码
      totalPages: 0, // 总页数
      pageRendering: false, // 是否正在渲染
      pageNumPending: null, // 等待渲染的页码
      scale: 1.5, // 缩放比例
      dialogStyle: { top: '20px' },
    };
  },
  methods: {
    // 新增下载方法
    handleDownload() {
      // 创建隐藏的下载链接
      const link = document.createElement('a');
      link.href = this.fileUrl;

      // 设置下载文件名（优先使用传入的fileName，否则从URL提取）
      const filename = this.fileName ||
        this.fileUrl.split('/').pop().split('?')[0] ||
        `file_${new Date().getTime()}`;

      link.download = filename;
      link.style.display = 'none';

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      // 触发下载统计事件
      // this.$emit('download', {
      //   url: this.fileUrl,
      //   type: this.fileType,
      //   name: filename
      // });
    },

    handleCancel() {
      this.pdfDoc = null;
      this.pageNum = 1;
      this.$emit("close");
    },
    // 打开预览
    handlePreview() {
      this.loadPdf(this.fileUrl); // 替换为你的 PDF 文件路径
    },

    // 加载 PDF 文件
    async loadPdf(url) {
      try {
        const loadingTask = pdfjsLib.getDocument(url);
        this.pdfDoc = await loadingTask.promise;
        this.totalPages = this.pdfDoc.numPages;
        this.renderPage(this.pageNum);
      } catch (error) {
        console.error('加载 PDF 失败:', error);
        this.$message.error('加载 PDF 失败');
      }
    },
    // 渲染指定页码
    async renderPage(num) {
      if (this.pageRendering) return;
      this.pageRendering = true;

      const page = await this.pdfDoc.getPage(num);
      const viewport = page.getViewport({ scale: this.scale });
      const canvas = this.$refs.pdfCanvas;
      const context = canvas.getContext('2d');

      canvas.height = viewport.height;
      canvas.width = viewport.width;

      const renderContext = {
        canvasContext: context,
        viewport: viewport,
      };

      await page.render(renderContext).promise;
      this.pageRendering = false;

      if (this.pageNumPending !== null) {
        this.renderPage(this.pageNumPending);
        this.pageNumPending = null;
      }
    },
    // 上一页
    prevPage() {
      if (this.pageNum <= 1) return;
      this.pageNum--;
      this.renderPage(this.pageNum);
    },
    // 下一页
    nextPage() {
      if (this.pageNum >= this.totalPages) return;
      this.pageNum++;
      this.renderPage(this.pageNum);
    }
  }
};
</script>

<style scoped>
/* 新增标题栏样式 */
.modal-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
}

.download-btn {
  margin-left: 10px;
  font-size: 16px;
}

.download-btn:hover {
  color: #40a9ff;
}

.pdf-viewer {
  overflow: auto;
  text-align: center;
}

.pagination button {
  margin: 0 8px;
}
</style>