<template>
  <div class="pdf-viewer">
    <canvas
      v-for="page in pageCount"
      :key="page"
      :ref="el => setCanvasRef(page, el)"
    ></canvas>
    <div v-if="loading" class="loading">加载中...</div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue';
import * as pdfjsLib from 'pdfjs-dist';


pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
  'pdfjs-dist/build/pdf.worker.min.mjs',
  import.meta.url
).href;

export default {
  name: 'PdfViewer',
  props: {
    pdfUrl: {
      type: String,
      required: true
    }
  },
  setup(props) {
    // 非响应式的 canvas 映射，避免触发布局递归更新
    const canvasMap = {};
    const pageCount = ref(0);
    const loading = ref(true);
    const pdfDocRef = ref(null);

    const setCanvasRef = (page, el) => {
      if (!el) return;
      canvasMap[page] = el;
    };

    const parsePdfUrl = (pdfUrl) => {
      if (!pdfUrl || typeof pdfUrl !== 'string') return '';
      const [urlPart] = pdfUrl.split('#');
      return urlPart;
    }

    const renderPdf = async (pdfUrl) => {
      const url = parsePdfUrl(pdfUrl)
      if (!url) return

      loading.value = true
      pdfDocRef.value = null
      try {
        const loadingTask = pdfjsLib.getDocument(url);
        const pdf = await loadingTask.promise;
        pdfDocRef.value = pdf
        pageCount.value = pdf.numPages;

        // 等待 canvas 按 pageCount 渲染出来
        await nextTick();

        for (let p = 1; p <= pdf.numPages; p++) {
          const pdfPage = await pdf.getPage(p);
          const viewport = pdfPage.getViewport({ scale: 1.5 });
          const canvas = canvasMap[p];
          if (!canvas) continue;
          const context = canvas.getContext('2d');
          const renderContext = {
            canvasContext: context,
            viewport: viewport
          };

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

          await pdfPage.render(renderContext).promise;
        }
      } catch (error) {
        console.error('加载 PDF 出错:', error);
      } finally {
        loading.value = false;
      }
    }

    /** 在 PDF 中查找关键词，返回首次出现的页码（1-based），未找到返回 0 */
    const searchKeyword = async (keyword) => {
      const doc = pdfDocRef.value
      if (!doc || !keyword || !String(keyword).trim()) return 0
      const k = String(keyword).trim()
      const num = doc.numPages
      for (let p = 1; p <= num; p++) {
        const page = await doc.getPage(p)
        const content = await page.getTextContent()
        const text = (content.items || []).map(it => it.str || '').join('')
        if (text.includes(k)) return p
      }
      return 0
    }

    /** 滚动到指定页码（1-based）对应的 canvas */
    const goToPage = (pageNum) => {
      const canvas = canvasMap[pageNum]
      if (canvas && typeof canvas.scrollIntoView === 'function') {
        canvas.scrollIntoView({ behavior: 'smooth', block: 'start' })
      }
    }

    // 首次挂载后再根据当前 url 渲染，避免 canvas 还没准备好
    onMounted(() => {
      if (props.pdfUrl) {
        renderPdf(props.pdfUrl)
      }
    })

    return {
      pageCount,
      setCanvasRef,
      loading,
      searchKeyword,
      goToPage
    }
  }
};
</script>

<style scoped>
.pdf-viewer {
  position: relative;
  width: 100%;
  /* 高度由内容决定，让外层容器控制滚动 */
}

canvas {
  width: 100%;
  height: auto;
  display: block;
}

.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 18px;
  color: #333;
}
</style>