<template>
  <view class="pdf-viewer-modal" v-if="visible" @click="handleClose">
    <view class="pdf-container" @click.stop>
      <!-- 头部 -->
      <view class="pdf-header">
        <text class="pdf-title">{{ fileName }}</text>
        <view class="pdf-actions">
          <text class="page-info">{{ currentPage }} / {{ totalPages }}</text>
          <view class="close-btn" @click="handleClose">
            <text class="close-icon">×</text>
          </view>
        </view>
      </view>

      <!-- PDF 内容区域 -->
      <view class="pdf-content" ref="pdfContent">
        <!-- 加载中 -->
        <view class="loading-wrapper" v-if="loading">
          <view class="loading-spinner"></view>
          <text class="loading-text">加载中... {{ loadingProgress }}%</text>
        </view>

        <!-- 错误提示 -->
        <view class="error-wrapper" v-if="error">
          <text class="error-text">{{ error }}</text>
          <view class="retry-btn" @click="loadPdf">
            <text>重试</text>
          </view>
        </view>

        <!-- PDF 画布容器 - 使用原生 div -->
        <view
          class="pdf-scroll-wrapper"
          v-show="!loading && !error"
          ref="scrollWrapper"
        >
          <view class="canvas-container" ref="canvasContainer">
            <!-- canvas 将通过 JS 动态创建 -->
          </view>
        </view>
      </view>

      <!-- 底部工具栏 -->
      <view class="pdf-toolbar">
        <view class="toolbar-btn" :class="{ disabled: currentPage <= 1 }" @click="prevPage">
          <text>上一页</text>
        </view>
        <view class="toolbar-btn" :class="{ disabled: currentPage >= totalPages }" @click="nextPage">
          <text>下一页</text>
        </view>
        <view class="toolbar-btn" @click="zoomOut">
          <text>缩小</text>
        </view>
        <view class="toolbar-btn" @click="zoomIn">
          <text>放大</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// #ifdef H5
let pdfjsLib = null
// #endif

export default {
  name: 'PdfViewer',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    url: {
      type: String,
      default: ''
    },
    fileName: {
      type: String,
      default: 'PDF文档'
    }
  },
  data() {
    return {
      loading: false,
      loadingProgress: 0,
      error: '',
      pdfDoc: null,
      currentPage: 1,
      totalPages: 0,
      scale: 1.2,
      canvasElements: {},
      pdfjsLoaded: false
    }
  },
  watch: {
    visible(val) {
      if (val && this.url) {
        this.$nextTick(() => {
          this.initPdfjs()
        })
      } else if (!val) {
        this.cleanup()
      }
    },
    url(val) {
      if (this.visible && val) {
        this.$nextTick(() => {
          this.initPdfjs()
        })
      }
    }
  },
  methods: {
    async initPdfjs() {
      // #ifdef H5
      if (!pdfjsLib) {
        try {
          // 动态导入 pdfjs-dist
          const pdfjs = await import('pdfjs-dist/legacy/build/pdf.js')
          pdfjsLib = pdfjs

          // 设置 worker
          pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.min.js'

          this.pdfjsLoaded = true
          console.log('PDF.js 加载成功')
        } catch (err) {
          console.error('加载 PDF.js 失败:', err)
          this.error = '加载 PDF 组件失败'
          return
        }
      }
      this.loadPdf()
      // #endif
    },

    async loadPdf() {
      // #ifdef H5
      if (!this.url) {
        this.error = '文件地址无效'
        return
      }

      if (!pdfjsLib) {
        this.error = 'PDF组件未加载'
        return
      }

      this.loading = true
      this.loadingProgress = 0
      this.error = ''
      this.clearCanvases()

      try {
        console.log('开始加载 PDF:', this.url)

        // 加载 PDF 文档
        const loadingTask = pdfjsLib.getDocument({
          url: this.url,
          withCredentials: false
        })

        loadingTask.onProgress = (progress) => {
          if (progress.total > 0) {
            this.loadingProgress = Math.round((progress.loaded / progress.total) * 100)
          }
        }

        this.pdfDoc = await loadingTask.promise
        this.totalPages = this.pdfDoc.numPages
        this.currentPage = 1

        console.log('PDF 加载成功，总页数:', this.totalPages)

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

        this.loading = false
      } catch (err) {
        console.error('PDF加载失败:', err)
        this.loading = false

        if (err.name === 'MissingPDFException') {
          this.error = '文件不存在或已被删除'
        } else if (err.message && err.message.includes('CORS')) {
          this.error = '跨域访问被拒绝，请联系管理员'
        } else if (err.message && err.message.includes('Invalid PDF')) {
          this.error = '无效的PDF文件'
        } else {
          this.error = '文件加载失败: ' + (err.message || '未知错误')
        }
      }
      // #endif

      // #ifndef H5
      this.error = '当前平台不支持PDF预览'
      // #endif
    },

    async renderPage(pageNum) {
      // #ifdef H5
      if (!this.pdfDoc) {
        console.error('pdfDoc 不存在')
        return
      }

      try {
        console.log('开始渲染页面:', pageNum)

        const page = await this.pdfDoc.getPage(pageNum)
        const viewport = page.getViewport({ scale: this.scale })

        console.log('页面尺寸:', viewport.width, 'x', viewport.height)

        // 获取或创建 canvas
        let canvas = this.canvasElements[pageNum]
        if (!canvas) {
          canvas = document.createElement('canvas')
          canvas.id = 'pdf-canvas-' + pageNum
          canvas.className = 'pdf-canvas-element'
          canvas.style.display = 'block'
          canvas.style.margin = '10px auto'
          canvas.style.backgroundColor = '#fff'
          canvas.style.boxShadow = '0 2px 10px rgba(0,0,0,0.1)'

          this.canvasElements[pageNum] = canvas

          // 添加到容器
          const container = this.$refs.canvasContainer?.$el || this.$refs.canvasContainer
          if (container) {
            container.appendChild(canvas)
            console.log('Canvas 已添加到容器')
          } else {
            console.error('找不到 canvas 容器')
            return
          }
        }

        // 设置 canvas 尺寸
        canvas.width = viewport.width
        canvas.height = viewport.height
        canvas.style.width = viewport.width + 'px'
        canvas.style.height = viewport.height + 'px'

        const context = canvas.getContext('2d')

        // 清除之前的内容
        context.clearRect(0, 0, canvas.width, canvas.height)

        // 渲染 PDF 页面到 canvas
        const renderContext = {
          canvasContext: context,
          viewport: viewport
        }

        await page.render(renderContext).promise
        console.log('页面渲染完成:', pageNum)

      } catch (err) {
        console.error('渲染页面失败:', err)
      }
      // #endif
    },

    clearCanvases() {
      // 清除所有 canvas
      const container = this.$refs.canvasContainer?.$el || this.$refs.canvasContainer
      if (container) {
        container.innerHTML = ''
      }
      this.canvasElements = {}
    },

    async prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
        this.clearCanvases()
        await this.renderPage(this.currentPage)
      }
    },

    async nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++
        this.clearCanvases()
        await this.renderPage(this.currentPage)
      }
    },

    async zoomIn() {
      if (this.scale < 3) {
        this.scale += 0.2
        this.clearCanvases()
        await this.renderPage(this.currentPage)
      }
    },

    async zoomOut() {
      if (this.scale > 0.5) {
        this.scale -= 0.2
        this.clearCanvases()
        await this.renderPage(this.currentPage)
      }
    },

    handleClose() {
      this.$emit('close')
      this.$emit('update:visible', false)
    },

    cleanup() {
      this.clearCanvases()
      if (this.pdfDoc) {
        this.pdfDoc.destroy()
        this.pdfDoc = null
      }
      this.currentPage = 1
      this.totalPages = 0
      this.error = ''
      this.loading = false
    }
  },
  beforeDestroy() {
    this.cleanup()
  }
}
</script>

<style lang="scss" scoped>
.pdf-viewer-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pdf-container {
  width: 95%;
  height: 90%;
  max-width: 900px;
  background: #fff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.pdf-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 15px;
  background: #C93639;
  color: #fff;
  flex-shrink: 0;
}

.pdf-title {
  font-size: 16px;
  font-weight: 500;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-right: 10px;
}

.pdf-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-info {
  font-size: 13px;
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 8px;
  border-radius: 10px;
}

.close-btn {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  cursor: pointer;
}

.close-icon {
  font-size: 20px;
  color: #fff;
  line-height: 1;
}

.pdf-content {
  flex: 1;
  overflow: hidden;
  position: relative;
  background: #e0e0e0;
}

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

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 2px solid #f0f0f0;
  border-top-color: #C93639;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

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

.loading-text {
  font-size: 14px;
  color: #666;
}

.error-text {
  font-size: 14px;
  color: #999;
  text-align: center;
}

.retry-btn {
  padding: 8px 20px;
  background: #C93639;
  color: #fff;
  border-radius: 15px;
  font-size: 14px;
  cursor: pointer;
}

.pdf-scroll-wrapper {
  width: 100%;
  height: 100%;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
}

.canvas-container {
  min-height: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pdf-toolbar {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  background: #fff;
  border-top: 1px solid #eee;
  gap: 10px;
  flex-shrink: 0;
}

.toolbar-btn {
  padding: 8px 16px;
  background: #C93639;
  color: #fff;
  border-radius: 15px;
  font-size: 13px;
  cursor: pointer;

  &.disabled {
    background: #ccc;
    pointer-events: none;
  }

  &:active {
    opacity: 0.8;
  }
}
</style>

<style>
/* 全局样式，确保 canvas 正确显示 */
.pdf-canvas-element {
  display: block !important;
  max-width: 100%;
}
</style>
