<template>
  <div class="upload-file">
    <!-- 文件列表 -->
    <transition-group class="upload-file-list el-upload-list el-upload-list--text" name="el-fade-in-linear" tag="ul">
      <li :key="file.url" class="el-upload-list__item ele-upload-list__item-content" v-for="(file, index) in fileList">
        <div class="file-info">
          <el-link
            :href="`${file.url}`"
            :underline="false"
            target="_blank"
            @click.prevent="handleFileClick(file)"
          >
            <span class="el-icon-document"> {{ getFileName(file.name) }} </span>
          </el-link>
        </div>

        <div class="ele-upload-list__item-content-action">
          <!-- 预览按钮 -->
          <el-link
            v-if="showPreview && canPreview(file)"
            :underline="false"
            @click="handlePreview(file)"
            type="primary"
            style="margin-right: 10px;"
            class="preview-link"
          >
            预览
          </el-link>

          <!-- 下载按钮 -->
          <el-link
            :href="file.url"
            :underline="false"
            target="_blank"
            type="text"
            icon="el-icon-download"
            style="margin-right: 10px;"
            @click.prevent="handleDownload(file)"
          >
            下载
          </el-link>

          <!-- 删除按钮（可选） -->
          <el-link
            v-if="showDelete"
            :underline="false"
            @click="handleDelete(index)"
            type="danger"
            class="delete-link"
          >
            删除
          </el-link>
        </div>
      </li>
    </transition-group>

    <!-- 预览弹窗 -->
    <el-dialog
      :title="previewTitle"
      :visible.sync="previewVisible"
      width="80%"
      top="5vh"
      :close-on-click-modal="false"
      append-to-body
      @closed="handlePreviewClosed"
    >
      <div class="preview-container">
        <!-- PDF预览 -->
        <div v-if="previewType === 'pdf'" class="pdf-preview-wrapper" style="height: 60vh;">
          <!-- 调试信息 -->
          <div v-if="showDebugInfo" style="background: #f5f5f5; padding: 10px; margin-bottom: 10px; font-size: 12px; border-radius: 4px;">
            <div><strong>调试信息：</strong></div>
            <div>URL: {{ previewUrl }}</div>
            <div>文件类型: {{ previewType }}</div>
            <div>PDF状态: {{ pdfLoading ? '加载中' : pdfError ? '错误' : '已加载' }}</div>
          </div>

          <!-- PDF加载中 -->
          <div v-if="pdfLoading" class="pdf-loading">
            <i class="el-icon-loading" style="font-size: 40px; color: #409eff;"></i>
            <p>正在加载PDF文件...</p>
            <p v-if="loadingProgress > 0">加载进度: {{ loadingProgress }}%</p>
            <el-button size="mini" @click="cancelPdfLoad" style="margin-top: 10px;">
              取消加载
            </el-button>
            <el-button size="mini" @click="useSimplePreview" style="margin-top: 10px; margin-left: 10px;" type="primary">
              使用简单预览
            </el-button>
          </div>

          <!-- PDF错误 -->
          <div v-else-if="pdfError" class="pdf-error">
            <el-alert
              title="PDF预览失败"
              :description="pdfErrorMessage"
              type="error"
              show-icon
              center
            />
            <div class="pdf-error-actions">
              <el-button type="primary" @click="retryPdfLoad">
                <i class="el-icon-refresh"></i> 重试
              </el-button>
              <el-button @click="openPdfInNewWindow">
                <i class="el-icon-view"></i> 新窗口打开
              </el-button>
              <el-button @click="openIframePreview">
                <i class="el-icon-monitor"></i> 备选预览
              </el-button>
              <el-button @click="downloadCurrentFile">
                <i class="el-icon-download"></i> 下载
              </el-button>
            </div>
          </div>

          <!-- PDF预览内容 -->
          <div v-else class="pdf-content">
            <!-- PDF控制栏 -->
            <div class="pdf-controls" v-if="pdfDoc">
              <div class="controls-left">
                <el-button-group>
                  <el-button
                    size="mini"
                    @click="prevPage"
                    :disabled="currentPage <= 1"
                    title="上一页"
                  >
                    <i class="el-icon-arrow-left"></i>
                  </el-button>
                  <el-input-number
                    v-model="currentPage"
                    :min="1"
                    :max="pageCount"
                    size="mini"
                    style="width: 80px; margin: 0 5px;"
                    @change="goToPage"
                    controls-position="right"
                  />
                  <el-button
                    size="mini"
                    @click="nextPage"
                    :disabled="currentPage >= pageCount"
                    title="下一页"
                  >
                    <i class="el-icon-arrow-right"></i>
                  </el-button>
                </el-button-group>
                <span style="margin-left: 10px; color: #606266; font-size: 14px;">
                  共 {{ pageCount }} 页
                </span>
              </div>

              <div class="controls-right">
                <el-button-group>
                  <el-button
                    size="mini"
                    @click="zoomOut"
                    :disabled="scale <= 0.5"
                    title="缩小"
                  >
                    <i class="el-icon-zoom-out"></i>
                  </el-button>
                  <el-button size="mini" disabled style="width: 70px;">
                    {{ Math.round(scale * 100) }}%
                  </el-button>
                  <el-button
                    size="mini"
                    @click="zoomIn"
                    :disabled="scale >= 3"
                    title="放大"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </el-button>
                </el-button-group>

<!--                <el-button
                  size="mini"
                  type="primary"
                  @click="downloadCurrentFile"
                  style="margin-left: 10px;"
                >
                  <i class="el-icon-download"></i> 下载
                </el-button>
                <el-button
                  size="mini"
                  @click="toggleDebugInfo"
                  style="margin-left: 10px;"
                  title="调试信息"
                >
                  <i class="el-icon-info"></i>
                </el-button>-->
              </div>
            </div>

            <!-- PDF页面容器 -->
            <div class="pdf-pages-container" ref="pdfContainer">
              <canvas
                v-for="n in pageCount"
                :key="n"
                :ref="`pdfCanvas${n}`"
                class="pdf-canvas"
                style="display: block; margin: 10px auto;"
              ></canvas>
            </div>
          </div>
        </div>

        <!-- 图片预览 -->
        <div v-else-if="previewType === 'image'" class="image-preview-wrapper" style="height: 60vh; display: flex; align-items: center; justify-content: center;">
          <!-- 图片加载中 -->
          <div v-if="imageLoading" class="image-loading">
            <i class="el-icon-loading" style="font-size: 40px; color: #409eff;"></i>
            <p>正在加载图片...</p>
          </div>

          <!-- 图片加载错误 -->
          <div v-else-if="imageError" class="image-error">
            <el-alert
              title="图片加载失败"
              description="无法加载图片，请检查网络连接或文件权限"
              type="error"
              show-icon
              center
            />
            <div class="image-error-actions" style="margin-top: 20px;">
              <el-button type="primary" @click="retryImageLoad">
                <i class="el-icon-refresh"></i> 重试
              </el-button>
              <el-button @click="downloadCurrentFile">
                <i class="el-icon-download"></i> 下载图片
              </el-button>
            </div>
          </div>

          <!-- 图片预览内容 -->
          <img
            v-else
            :src="previewUrl"
            class="preview-image"
            alt="预览图片"
            style="max-width: 100%; max-height: 100%; object-fit: contain;"
            @load="onImageLoaded"
            @error="onImageError"
          />
        </div>

        <!-- 不支持预览的格式 -->
        <div v-else class="unsupported-preview">
          <el-alert
            title="该文件格式不支持在线预览"
            type="warning"
            description="请下载文件后使用本地软件查看"
            show-icon
            center
          >
          </el-alert>
          <div class="download-action">
            <el-button type="primary" @click="downloadCurrentFile">
              <i class="el-icon-download"></i> 下载文件
            </el-button>
          </div>
        </div>
      </div>

<!--      <span slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关 闭</el-button>
        <el-button
          v-if="previewType !== 'pdf' && previewType !== 'image'"
          type="primary"
          @click="downloadCurrentFile"
        >
          下载
        </el-button>
        <el-button
          v-if="previewType === 'pdf' && !pdfError"
          type="primary"
          @click="openPdfInNewWindow"
        >
          新窗口打开
        </el-button>
      </span>-->
    </el-dialog>
  </div>
</template>

<script>
import { getAccessToken } from "@/utils/auth";

export default {
  name: "FileUpload",
  props: {
    // 值
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 100,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 10,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    // 新增：是否显示预览按钮
    showPreview: {
      type: Boolean,
      default: true
    },
    // 新增：是否显示删除按钮
    showDelete: {
      type: Boolean,
      default: false
    },
    // 新增：支持预览的文件类型
    previewTypes: {
      type: Array,
      default: () => ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'pdf']
    },
    // 新增：是否显示调试信息
    debug: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      headers: { Authorization: "Bearer " + getAccessToken() },
      fileList: [],

      // 预览相关数据
      previewVisible: false,
      previewUrl: '',
      previewTitle: '',
      previewType: '',
      currentPreviewFile: null,

      // PDF.js相关数据
      pdfjsLib: null,
      pdfLoading: false,
      pdfError: false,
      pdfErrorMessage: '',
      pdfDoc: null,
      currentPage: 1,
      pageCount: 0,
      scale: 1.0,

      // 渲染队列
      renderQueue: [],
      isRendering: false,
      loadingTask: null,
      loadingProgress: 0,

      // 图片预览相关
      imageLoading: false,
      imageError: false,
      imageLoadRetryCount: 0,

      // 调试信息
      showDebugInfo: false,

      // 文件信息
      fileSizeBytes: 0
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(',');
          // 然后将数组转为对象数组
          this.fileList = list.map(item => {
            if (typeof item === "string") {
              item = { name: item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    },
    previewVisible(val) {
      if (val) {
        this.showDebugInfo = this.debug;
        if (this.previewType === 'pdf') {
          this.$nextTick(() => {
            this.loadPdf();
          });
        }
      } else {
        this.cleanupPdf();
      }
    },
    currentPage(val) {
      if (this.previewType === 'pdf' && this.pdfDoc) {
        this.renderPage(val);
        this.scrollToPage(val);
      }
    },
    scale(val) {
      if (this.previewType === 'pdf' && this.pdfDoc) {
        this.renderAllPages();
      }
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    // 初始化PDF.js
    async initPdfJs() {
      try {
        // 动态导入PDF.js，避免构建问题
        const pdfjsModule = await import('pdfjs-dist/build/pdf');
        const pdfjsWorkerModule = await import('pdfjs-dist/build/pdf.worker.entry');

        this.pdfjsLib = pdfjsModule;

        // 设置worker路径
        if (process.env.NODE_ENV === 'production') {
          this.pdfjsLib.GlobalWorkerOptions.workerSrc = '/static/js/pdf.worker.min.js';
        } else {
          // 开发环境使用CDN
          this.pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://unpkg.com/pdfjs-dist@2.16.105/build/pdf.worker.min.js';
        }

        console.log('PDF.js初始化成功');
      } catch (error) {
        console.error('PDF.js初始化失败:', error);
        this.pdfErrorMessage = 'PDF预览库加载失败';
        this.pdfError = true;
      }
    },

    // 文件点击事件
    handleFileClick(file) {
      if (this.canPreview(file)) {
        // 如果支持预览，阻止默认行为，使用预览
        this.handlePreview(file);
      } else {
        // 不支持预览，直接下载或在新窗口打开
        window.open(this.buildFullUrl(file.url), '_blank');
      }
    },

    // 处理下载
    handleDownload(file) {
      const downloadUrl = this.buildFullUrl(file.url);
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = this.getFileName(file.name) || 'download';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // 判断文件是否可以预览
    canPreview(file) {
      if (!file || !file.name) return false;
      const extension = this.getFileExtension(file.name).toLowerCase();
      return this.previewTypes.includes(extension);
    },

    // 获取文件扩展名
    getFileExtension(filename) {
      if (!filename) return '';
      const lastDotIndex = filename.lastIndexOf('.');
      return lastDotIndex > -1 ? filename.slice(lastDotIndex + 1) : '';
    },

    // 获取文件类型
    getFileType(filename) {
      const extension = this.getFileExtension(filename).toLowerCase();
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
      const pdfTypes = ['pdf'];

      if (imageTypes.includes(extension)) return 'image';
      if (pdfTypes.includes(extension)) return 'pdf';
      return 'other';
    },

    // 预览文件
    async handlePreview(file) {
      if (!file) return;

      this.currentPreviewFile = file;
      this.previewTitle = `预览 - ${this.getFileName(file.name)}`;
      this.previewType = this.getFileType(file.name);

      console.log('预览调试信息:', {
        文件名: file.name,
        文件类型: this.previewType,
        原始URL: file.url
      });

      // 构建完整URL
      let previewUrl = this.buildFullUrl(file.url);
      console.log('构建完整URL:', previewUrl);

      // 对于图片，需要特殊处理
      if (this.previewType === 'image') {
        // 重置图片状态
        this.imageLoading = true;
        this.imageError = false;
        this.imageLoadRetryCount = 0;

        // 图片预览前先预加载，确保能正常显示
        await this.preloadImage(previewUrl);

      } else {
        // PDF和其他文件类型
        this.previewUrl = previewUrl;
        this.previewVisible = true;
      }

      // 触发预览事件
      this.$emit('preview', {
        file: file,
        type: this.previewType,
        url: previewUrl
      });
    },

    // 预加载图片
    async preloadImage(url) {
      return new Promise((resolve) => {
        // 创建Image对象
        const img = new Image();

        img.onload = () => {
          console.log('图片预加载成功');
          this.previewUrl = url;
          this.imageLoading = false;
          this.previewVisible = true;
          resolve(true);
        };

        img.onerror = () => {
          console.error('图片预加载失败，尝试其他方式');
          // 如果预加载失败，尝试其他方式
          this.tryAlternativeImageLoad(url);
          resolve(false);
        };

        // 设置图片属性
        img.crossOrigin = 'anonymous';

        // 如果是需要认证的图片，尝试添加认证信息
        if (this.headers.Authorization && !url.includes('?')) {
          // 尝试添加token参数
          const token = this.headers.Authorization.replace('Bearer ', '');
          img.src = `${url}?token=${token}`;
        } else {
          img.src = url;
        }
      });
    },

    // 尝试其他方式加载图片
    async tryAlternativeImageLoad(url) {
      this.imageLoadRetryCount++;

      if (this.imageLoadRetryCount >= 3) {
        // 超过重试次数，显示错误
        this.imageLoading = false;
        this.imageError = true;
        this.$modal.msgError('图片加载失败，请检查网络或文件权限');
        return;
      }

      // 尝试不同的加载方式
      const strategies = [
        // 1. 直接使用fetch加载
        async () => {
          try {
            const response = await fetch(url, {
              headers: this.headers,
              mode: 'cors'
            });
            if (response.ok) {
              const blob = await response.blob();
              return URL.createObjectURL(blob);
            }
          } catch (error) {
            console.warn('Fetch加载失败:', error);
          }
          return null;
        },

        // 2. 添加时间戳避免缓存
        () => {
          const separator = url.includes('?') ? '&' : '?';
          return `${url}${separator}_t=${Date.now()}`;
        },

        // 3. 尝试使用代理
        () => {
          return url;
        }
      ];

      // 依次尝试不同的策略
      for (let i = 0; i < strategies.length; i++) {
        try {
          const newUrl = await strategies[i]();
          if (newUrl) {
            // 再次尝试加载
            const img = new Image();
            img.onload = () => {
              this.previewUrl = newUrl;
              this.imageLoading = false;
              this.previewVisible = true;
              console.log(`第${i+1}种方式加载成功`);
            };
            img.onerror = () => {
              // 继续尝试下一种方式
              if (i === strategies.length - 1) {
                this.imageLoading = false;
                this.imageError = true;
              }
            };
            img.src = newUrl;
            break;
          }
        } catch (error) {
          console.warn(`策略${i+1}失败:`, error);
        }
      }
    },

    // 测试URL可访问性
    async testUrlAccess(url) {
      if (!url) return false;

      try {
        const response = await fetch(url, {
          method: 'HEAD',
          headers: this.headers,
          mode: 'cors',
          cache: 'no-cache'
        });

        const accessible = response.ok;
        console.log('URL访问测试:', {
          url: url,
          ok: response.ok,
          status: response.status,
          statusText: response.statusText,
          可访问: accessible
        });

        return accessible;
      } catch (error) {
        console.error('URL访问测试失败:', error);
        return false;
      }
    },

    // 构建完整的文件URL
    buildFullUrl(url) {
      if (!url) return url;

      // 如果已经是完整的URL或blob URL，直接返回
      if (url.startsWith('http') || url.startsWith('blob:')) {
        return url;
      }

      // 如果是相对路径
      if (url.startsWith('/')) {
        return this.baseUrl + url;
      } else {
        return this.baseUrl + '/' + url;
      }
    },

    // 图片加载完成
    onImageLoaded() {
      this.imageLoading = false;
      this.imageError = false;
      console.log('图片加载完成');
    },

    // 图片加载错误
    onImageError() {
      this.imageLoading = false;
      this.imageError = true;
      console.error('图片加载错误');
    },

    // 重试图片加载
    retryImageLoad() {
      if (this.currentPreviewFile) {
        this.handlePreview(this.currentPreviewFile);
      }
    },

    // 加载PDF文档
    async loadPdf() {
      try {
        this.pdfLoading = true;
        this.pdfError = false;
        this.loadingProgress = 0;
        this.cleanupPdf();

        // 重置状态
        this.currentPage = 1;
        this.pageCount = 0;
        this.scale = 1.0;

        // 确保PDF.js已加载
        if (!this.pdfjsLib) {
          await this.initPdfJs();
        }

        // 准备PDF加载参数
        let pdfUrl = this.previewUrl;
        let pdfParams = {
          cMapUrl: 'https://unpkg.com/pdfjs-dist@2.16.105/cmaps/',
          cMapPacked: true,
          withCredentials: false
        };

        console.log('加载PDF，URL:', pdfUrl);

        // 确保是完整URL
        if (!pdfUrl.startsWith('http')) {
          pdfUrl = this.buildFullUrl(pdfUrl);
        }

        // 添加时间戳避免缓存
        const separator = pdfUrl.includes('?') ? '&' : '?';
        pdfUrl += `${separator}_t=${Date.now()}`;

        pdfParams.url = pdfUrl;

        // 添加认证头
        if (this.headers.Authorization) {
          pdfParams.httpHeaders = {
            Authorization: this.headers.Authorization
          };
        }

        console.log('PDF加载参数:', pdfParams);

        // 加载PDF文档
        this.loadingTask = this.pdfjsLib.getDocument(pdfParams);

        // 添加进度监听
        this.loadingTask.onProgress = (progressData) => {
          if (progressData.total) {
            this.loadingProgress = Math.round((progressData.loaded / progressData.total) * 100);
          }
        };

        // 设置超时
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error('PDF加载超时')), 30000);
        });

        this.pdfDoc = await Promise.race([this.loadingTask.promise, timeoutPromise]);
        this.pageCount = this.pdfDoc.numPages;

        console.log(`PDF加载成功，共${this.pageCount}页`);

        // 先渲染第一页
        await this.renderPage(1);

        // 异步渲染其他页面
        setTimeout(() => {
          this.renderAllPages();
        }, 100);

        this.pdfLoading = false;
      } catch (error) {
        console.error('PDF加载失败:', error);
        this.pdfLoading = false;
        this.pdfError = true;

        // 更详细的错误信息
        if (error.name === 'PasswordException') {
          this.pdfErrorMessage = 'PDF文件需要密码';
        } else if (error.message && error.message.includes('network')) {
          this.pdfErrorMessage = '网络错误，无法加载PDF文件';
        } else if (error.message && error.message.includes('超时')) {
          this.pdfErrorMessage = 'PDF加载超时，请重试';
        } else {
          this.pdfErrorMessage = 'PDF文件加载失败，可能文件已损坏或格式不支持';
        }

        // 打印详细错误
        console.error('PDF错误详情:', {
          name: error.name,
          message: error.message,
          stack: error.stack
        });
      }
    },

    // 渲染所有页面
    async renderAllPages() {
      if (!this.pdfDoc) return;

      // 清空之前的渲染
      this.renderQueue = [];

      // 添加所有页面到渲染队列
      for (let i = 1; i <= this.pageCount; i++) {
        this.renderQueue.push(i);
      }

      // 开始渲染
      await this.processRenderQueue();
    },

    // 处理渲染队列
    async processRenderQueue() {
      if (this.isRendering || this.renderQueue.length === 0) return;

      this.isRendering = true;

      while (this.renderQueue.length > 0) {
        const pageNum = this.renderQueue.shift();
        await this.renderPage(pageNum);

        // 为了让UI响应，每渲染一页后稍微停顿
        if (this.renderQueue.length > 0) {
          await new Promise(resolve => setTimeout(resolve, 10));
        }
      }

      this.isRendering = false;
    },

    // 渲染单个页面
    async renderPage(pageNum) {
      try {
        if (!this.pdfDoc) return;

        // 获取页面
        const page = await this.pdfDoc.getPage(pageNum);

        // 获取视口
        const viewport = page.getViewport({ scale: this.scale });

        // 获取canvas元素
        await this.$nextTick();
        const canvasRef = `pdfCanvas${pageNum}`;
        const canvas = this.$refs[canvasRef] && this.$refs[canvasRef][0];

        if (!canvas) {
          // 如果canvas不存在，重新添加到队列
          this.renderQueue.push(pageNum);
          return;
        }

        // 设置canvas尺寸
        const context = canvas.getContext('2d');
        const devicePixelRatio = window.devicePixelRatio || 1;

        canvas.width = viewport.width * devicePixelRatio;
        canvas.height = viewport.height * devicePixelRatio;
        canvas.style.width = `${viewport.width}px`;
        canvas.style.height = `${viewport.height}px`;

        // 高清渲染
        context.scale(devicePixelRatio, devicePixelRatio);

        // 渲染页面
        const renderContext = {
          canvasContext: context,
          viewport: viewport
        };

        await page.render(renderContext).promise;
        console.log(`第${pageNum}页渲染完成`);

      } catch (error) {
        console.error(`渲染第${pageNum}页失败:`, error);
        // 重新尝试
        this.renderQueue.push(pageNum);
      }
    },

    // 取消PDF加载
    cancelPdfLoad() {
      if (this.loadingTask) {
        try {
          this.loadingTask.destroy();
        } catch (e) {
          console.warn('取消PDF加载失败:', e);
        }
        this.loadingTask = null;
      }
      this.pdfLoading = false;
      this.pdfError = true;
      this.pdfErrorMessage = 'PDF加载已取消';
    },

    // 使用简单预览
    useSimplePreview() {
      this.previewVisible = false;
      setTimeout(() => {
        this.openIframePreview();
      }, 300);
    },

    // iframe预览
    openIframePreview() {
      const iframeUrl = this.previewUrl;
      const newWindow = window.open('', '_blank');

      if (newWindow) {
        newWindow.document.write(`
          <!DOCTYPE html>
          <html>
          <head>
            <title>PDF预览 - ${this.getFileName(this.currentPreviewFile?.name)}</title>
            <style>
              body { margin: 0; padding: 0; background: #f5f5f5; }
              .header {
                background: #fff;
                padding: 10px 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                display: flex;
                justify-content: space-between;
                align-items: center;
              }
              .title { font-size: 16px; font-weight: bold; }
              .controls { display: flex; gap: 10px; }
              button {
                padding: 8px 16px;
                background: #409eff;
                color: white;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                font-size: 14px;
              }
              button:hover { background: #66b1ff; }
              iframe {
                width: 100%;
                height: calc(100vh - 60px);
                border: none;
                background: white;
              }
            </style>
          </head>
          <body>
            <div class="header">
              <div class="title">PDF预览 - ${this.getFileName(this.currentPreviewFile?.name)}</div>
              <div class="controls">
                <button onclick="window.location.href='${iframeUrl}'">下载PDF</button>
                <button onclick="window.close()">关闭</button>
              </div>
            </div>
            <iframe src="${iframeUrl}" frameborder="0"></iframe>
          </body>
          </html>
        `);
        newWindow.document.close();
      } else {
        window.open(iframeUrl, '_blank');
      }
    },

    // 上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },

    // 下一页
    nextPage() {
      if (this.currentPage < this.pageCount) {
        this.currentPage++;
      }
    },

    // 跳转到指定页
    goToPage(page) {
      if (page >= 1 && page <= this.pageCount) {
        this.currentPage = page;
      }
    },

    // 滚动到指定页
    scrollToPage(pageNum) {
      this.$nextTick(() => {
        const canvas = this.$refs[`pdfCanvas${pageNum}`] && this.$refs[`pdfCanvas${pageNum}`][0];
        if (canvas && this.$refs.pdfContainer) {
          const container = this.$refs.pdfContainer;
          const canvasTop = canvas.offsetTop;
          container.scrollTop = canvasTop - 50;
        }
      });
    },

    // 放大
    zoomIn() {
      if (this.scale < 3) {
        this.scale = Math.min(3, this.scale + 0.25);
      }
    },

    // 缩小
    zoomOut() {
      if (this.scale > 0.5) {
        this.scale = Math.max(0.5, this.scale - 0.25);
      }
    },

    // 重试PDF加载
    retryPdfLoad() {
      this.loadPdf();
    },

    // 在新窗口打开PDF
    openPdfInNewWindow() {
      window.open(this.previewUrl, '_blank');
    },

    // 清理PDF资源
    cleanupPdf() {
      if (this.loadingTask) {
        try {
          this.loadingTask.destroy();
        } catch (e) {
          console.warn('PDF加载任务清理失败:', e);
        }
        this.loadingTask = null;
      }

      if (this.pdfDoc) {
        try {
          this.pdfDoc.destroy();
        } catch (e) {
          console.warn('PDF文档清理失败:', e);
        }
        this.pdfDoc = null;
      }
      this.renderQueue = [];
      this.isRendering = false;
      this.loadingProgress = 0;
    },

    // 预览关闭处理
    handlePreviewClosed() {
      this.previewUrl = '';
      this.currentPreviewFile = null;
      this.cleanupPdf();
      this.imageLoading = false;
      this.imageError = false;
      this.imageLoadRetryCount = 0;
    },

    // 下载当前预览的文件
    downloadCurrentFile() {
      if (!this.currentPreviewFile) return;

      const file = this.currentPreviewFile;
      const downloadUrl = this.buildFullUrl(file.url);

      if (downloadUrl) {
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = this.getFileName(file.name) || 'download';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }

      this.previewVisible = false;
    },

    // 获取文件名称
    getFileName(name) {
      // 先获取文件名（去除路径）
      let fileName = name;
      if (name.lastIndexOf("/") > -1) {
        fileName = name.slice(name.lastIndexOf("/") + 1);
      }
      // 去除时间戳部分（格式如_1234567890123）
      fileName = fileName.replace(/_\d{13}(?=\.\w+$)/, '');
      return fileName;
    },

    // 删除文件
    handleDelete(index) {
      this.fileList.splice(index, 1);
      this.$emit("input", this.listToString(this.fileList));
    },

    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },

    // 切换调试信息显示
    toggleDebugInfo() {
      this.showDebugInfo = !this.showDebugInfo;
    }
  },

  beforeDestroy() {
    // 组件销毁前清理资源
    this.cleanupPdf();
  }
};
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
  padding: 8px 12px;
  border-radius: 4px;
  transition: all 0.3s;

  &:hover {
    background-color: #f5f7fa;
    border-color: #409eff;
  }
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

/* 文件信息区域 */
.file-info {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 操作按钮区域 */
.ele-upload-list__item-content-action {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

/* 预览和删除按钮样式 */
.preview-link {
  margin-right: 10px;
  color: #409eff;
  font-size: 14px;

  &:hover {
    color: #66b1ff;
  }
}

.delete-link {
  color: #f56c6c;
  font-size: 14px;

  &:hover {
    color: #f78989;
  }
}

/* 预览相关样式 */
.preview-container {
  width: 100%;
  min-height: 60vh;
  display: flex;
  flex-direction: column;
}

/* PDF预览区域 */
.pdf-preview-wrapper {
  display: flex;
  flex-direction: column;
  height: 60vh;
}

.pdf-loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #409eff;
  text-align: center;

  .el-icon-loading {
    font-size: 40px;
    margin-bottom: 20px;
    animation: rotate 2s linear infinite;
  }

  p {
    font-size: 16px;
    margin: 5px 0;
  }
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.pdf-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 20px;

  .pdf-error-actions {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    gap: 10px;
    flex-wrap: wrap;
  }
}

.pdf-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* PDF控制栏 */
.pdf-controls {
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 10px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;

  .controls-left, .controls-right {
    display: flex;
    align-items: center;
  }
}

/* PDF页面容器 */
.pdf-pages-container {
  flex: 1;
  overflow: auto;
  padding: 10px;
  background: #f5f5f5;
}

.pdf-canvas {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  background: white;
  display: block;
  margin: 10px auto;
  border-radius: 4px;

  &:first-child {
    margin-top: 0;
  }

  &:last-child {
    margin-bottom: 0;
  }
}

/* 图片预览 */
.image-preview-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
}

.image-loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #409eff;
  text-align: center;

  .el-icon-loading {
    font-size: 40px;
    margin-bottom: 20px;
    animation: rotate 2s linear infinite;
  }

  p {
    font-size: 16px;
  }
}

.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 20px;
  text-align: center;

  .image-error-actions {
    margin-top: 20px;
    display: flex;
    gap: 10px;
    justify-content: center;
  }
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  transition: transform 0.3s;

  &:hover {
    transform: scale(1.02);
  }
}

/* 不支持预览的格式 */
.unsupported-preview {
  text-align: center;
  padding: 40px 20px;
  width: 100%;
  min-height: 60vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
  border-radius: 4px;
}

.download-action {
  margin-top: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .pdf-controls {
    flex-direction: column;
    align-items: stretch;

    .controls-left {
      margin-bottom: 10px;
      justify-content: center;
    }

    .controls-right {
      justify-content: center;
    }
  }

  .pdf-error-actions,
  .image-error-actions {
    flex-direction: column;
    align-items: center;

    .el-button {
      width: 200px;
      margin-bottom: 10px;
    }
  }

  .ele-upload-list__item-content {
    flex-direction: column;
    align-items: flex-start;

    .ele-upload-list__item-content-action {
      margin-top: 8px;
      width: 100%;
      justify-content: flex-start;

      .el-link {
        margin-right: 15px;
      }
    }
  }
}

/* 文件图标样式 */
.el-icon-document {
  color: #409eff;
  margin-right: 8px;
}

/* 链接悬停效果 */
.el-link {
  transition: color 0.3s;

  &:hover {
    text-decoration: none !important;
  }
}
</style>
