import * as PDFJS from "pdfjs-dist/build/pdf"
export async function loadPDF({ el, fileSrc, scale }, call) {
  PDFJS.GlobalWorkerOptions.workerSrc = require("./pdf.worker.entry.js")
  let loadingTask = await PDFJS.getDocument({
    url: fileSrc,
    withCredentials: true, // 允许携带cookie
  })

  loadingTask.promise.then((pdf) => {
    // 开始加载任务
    document.getElementById("pdfEle").innerHTML = ""
    const renderPage = (num) => {
      let pdfCol = document.querySelector(el)
      // 遍历每一页PDF
      pdf.getPage(num).then(async (page) => {
        let viewPort = page.getViewport({ scale: scale }) // 获取PDF尺寸
        let div = document.createElement("div") // 用于存放canvas

        div.id = `canvasBox_${num}`
        div.className = "canvas-box"
        div.style.position = "relative"
        div.style.width = viewPort.width + "px"
        div.style.margin = "0 auto"

        let canvas = document.createElement("canvas") // 创建canvas

        let context = canvas.getContext("2d")
        // 将canvas的宽和高设置为与PDF视图一样大小
        canvas.height = viewPort.height
        canvas.width = viewPort.width

        // setTimeout(() => {
        //   // 画页码
        //   context.font = "14px orbitron";
        //   context.fillStyle = "#333";
        //   context.save();
        //   context.beginPath();
        //   context.line = 2;
        //   context.textAlign = "center";
        //   context.textBaseline = "middle";
        //   // context.fillText(`${i}`, viewPort.width / 2, viewPort.height - 30);
        //   context.restore();
        //   context.closePath();
        // }, 500);

        let renderContext = {
          canvasContext: context,
          viewport: viewPort,
        }
        // 该函数返回一个当PDF页面成功渲染到界面上时解析的`promise`，我们可以使用成功回调来渲染文本图层。
        await page.render(renderContext) // 初始化文本图层
        canvas.className = "canvas"
        canvas.id = `canvas_${num}`

        call({
          div: div,
          pdfCol: pdfCol,
          canvas: canvas,
          context: context,
          scale: scale,
          index: num,
          allPage: pdf.numPages,
        })

        div.appendChild(canvas) // 将canvas放进对应的div中
        pdfCol.appendChild(div) // 将每一个div放到外面的大盒子中
        num++
        if (num <= pdf.numPages) {
          // console.log(num, pdf.numPages);
          renderPage(num)
        }
      })
    }
    renderPage(1)
  })
}
