<template>
  <div class="home_wrap">
    <!-- <button class="show-catalogue" @click="showDrawer">目录</button> -->
    <button type="button" class="catalogue-btn" @click="showDrawer">
      <img src="@/assets/icon/目录.png" alt="" />
      目录
    </button>
    <pdf-catalogue v-model="visible" :list="gData" @click-menu="handleSelect" />

    <div
      ref="getheight"
      id="scrollBox"
      :class="{ 'loading-hide': loading }"
      :style="{ width: pdf_div_width, margin: '0 auto' }"
    >
      <div v-for="(page, index) in pdf_pages" :key="index" class="canvas-box">
        <canvas :id="'the_canvas' + page" :key="page"></canvas>
        <div class="ws" :style="{ fontSize: maxWidth / 40 + 'px' }">
          {{ watermarkText || userInfo.phone || "搞一下" }}
        </div>
      </div>
    </div>

    <div class="loading" v-if="loading">
      <van-circle
        v-model="rate"
        :rate="currentRate"
        :speed="100"
        :text="currentRate + '%'"
      />
      <van-loading size="24px" color="#0094ff" style="margin-top: 10px"
        >数据加载中...</van-loading
      >
    </div>
  </div>
</template>

<script>
import PdfCatalogue from "@/components/pdf/pdf-catalogue.vue";
import { OSS_URL } from "@/common/config";

let PDFJS = require("pdfjs-dist");
PDFJS.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/build/pdf.worker.entry.js");
require("@/wasm/wasm_exec.js");
export default {
  components: {
    PdfCatalogue,
  },
  props: {
    path: {
      default: "",
    },
    is_encrypt: {
      default: 1,
    },
    platform: {
      default: "h5",
    },
    watermarkText: {
      default: "",
    },
  },
  data() {
    return {
      expandedKeys: [],
      pageArr: [],
      gData: [],
      visible: false,
      placement: "left",
      pdf_scale: 1.0, //pdf放大系数
      pdf_pages: [],
      pdf_div_width: "",
      pdf_src: null,
      pdf_data: null,
      userInfo: {},
      loading: true,
      loadingEndSize: 0,
      rate: 10,
      currentRate: 0,
      maxWidth: 0,
    };
  },
  mounted() {
    try {
      this.userInfo = JSON.parse(localStorage.getItem("user_info") || `{}`);
    } catch (e) {
      this.userInfo = {};
    }
    if (this.path) {
      this.currentRate = 5;
      this.waitWasm();
    }
  },
  methods: {
    handleSelect(b) {
      this.visible = false;
      let height = this.$refs.getheight.offsetHeight;
      let top = 0;
      // console.log(this.pageArr);
      for (let index = 1; index < this.pageArr.length; index++) {
        // console.log(this.pageArr[index].num , b.selectedNodes[0].data.props.dest[0].num);
        if (this.pageArr[index].num > b[0].num) {
          top = index;
          break;
        }
      }
      let offsetHeight =
        top * this.$refs.getheight.children[0].getBoundingClientRect().height;
      offsetHeight = (offsetHeight * b[0].num) / this.pageArr[top].num;

      window.scrollTo({
        top: offsetHeight + 2 * (top - 1),
        // behavior: 'smooth' // 滚动行为：smooth平滑滚动，instant瞬间滚动，默认值auto，等同于instant
      });
      console.log(height);
      console.log(this.pageArr[0]);
    },
    onClose() {
      this.visible = false;
    },
    showDrawer() {
      this.visible = true;
    },
    scaleD() {
      //放大
      let max = 0;
      if (window.screen.width > 1440) {
        max = 1.4;
      } else {
        max = 1.2;
      }
      if (this.pdf_scale >= max) {
        return;
      }
      this.pdf_scale = this.pdf_scale + 0.1;
      this._loadFile(this.pdf_data);
    },
    scaleX() {
      //缩小
      let min = 1.0;
      if (this.pdf_scale <= min) {
        return;
      }
      this.pdf_scale = this.pdf_scale - 0.1;
      this._loadFile(this.pdf_data);
    },
    // 加载wasm
    waitWasm() {
      if (parseInt(this.is_encrypt || 0) === 1) {
        const go = new Go();
        const that = this;
        WebAssembly.instantiateStreaming(
          // fetch("wasm/libgetpdf.wasm"),
          // fetch('https://gaoyixia.oss-cn-hangzhou.aliyuncs.com/wenjian/libgetpdf.wasm'),
          fetch("https://gaoyixia.oss-cn-hangzhou.aliyuncs.com/libgetpdf.wasm"),

          go.importObject
        ).then((result) => {
          go.run(result.instance);
          console.log(GetVersion());

          this.currentRate = 30;
          ReadPdf(this.path).then((pd) => {
            that.readPdfData(pd);
          });
        });
      } else {
        const path =
          this.path.indexOf("http") > -1 ? this.path : OSS_URL + this.path;
        this.readPdfData(path);
      }
    },

    readPdfData(pdf_data) {
      this.pdf_data = pdf_data;
      this._loadFile(this.pdf_data);
    },

    _loadFile(pdf_data) {
      //初始化pdf
      let loadingTask;
      if (parseInt(this.is_encrypt || 0) === 1) {
        loadingTask = PDFJS.getDocument({
          data: pdf_data,
        });
      } else {
        // 未加密
        loadingTask = PDFJS.getDocument(pdf_data);
      }
      loadingTask.promise.then((pdf) => {
        this.pdfDoc = pdf;
        this.pdf_pages = this.pdfDoc.numPages;
        pdf.getOutline().then((r) => {
          console.log("dddd");
          console.log(r);
          this.gData = r;
          if (r != null) {
            console.log("888888");
            r.forEach((it) => {
              console.log(it);

              pdf
                .getPageIndex({
                  ref: it.dest[0],
                })
                .then((vvv) => {
                  console.log(vvv);
                });
              // $("#div").html(it.title)
            });
          }
        });
        //debugger
        this.$nextTick(() => {
          this.currentRate = 50;
          this._renderPage(1);
        });
      });
    },
    _renderPage(num) {
      //渲染pdf页
      const that = this;
      this.pdfDoc.getPage(num).then((page) => {
        that.pageArr.push(page.ref);
        let canvas = document.getElementById("the_canvas" + num);
        let ctx = canvas.getContext("2d");
        let dpr = window.devicePixelRatio || 1;
        let bsr =
          ctx.webkitBackingStorePixelRatio ||
          ctx.mozBackingStorePixelRatio ||
          ctx.msBackingStorePixelRatio ||
          ctx.oBackingStorePixelRatio ||
          ctx.backingStorePixelRatio ||
          1;
        let ratio = dpr / bsr;
        let viewport = page.getViewport({
          scale: this.pdf_scale,
        });

        canvas.width = viewport.width * ratio;
        canvas.height = viewport.height * ratio;

        // canvas.style.width = viewport.width + "px";

        // that.pdf_div_width = viewport.width + "px";

        // canvas.style.height = viewport.height + "px";

        canvas.style.width = "100%";
        canvas.style.maxWidth = viewport.width + "px";
        this.maxWidth = viewport.width;

        that.pdf_div_width = "100%";

        ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
        let renderContext = {
          canvasContext: ctx,
          viewport: viewport,
        };
        page.render(renderContext).promise.then(() => {
          // 添加水印
          // ctx.rotate(-20 * Math.PI / 180); // 逆时针旋转π/9
          // ctx.font = `${20 * ratio}px Vedana`; // 设置字体
          // ctx.fillStyle = 'rgba(0, 0, 0, 0.20)'; // 设置字体的颜色
          // ctx.textAlign = 'center'; // 文本对齐方式
          // ctx.textBaseline = 'Middle'; // 文本基线
          // ctx.fillText(
          //     `${this.watermarkText || this.userInfo.phone || '搞一下'}`,
          //     60 * ratio,
          //     viewport.height * ratio / 3
          // ); // 绘制文字
          // 绘制加载进度
          this.loadingEndSize += 1;
          this.currentRate =
            50 +
            parseFloat(
              ((this.loadingEndSize / this.pdf_pages) * 30).toFixed(0)
            );
          // console.log(this.loadingEndSize, this.pdf_pages, this.currentRate, new Date().getTime())
          if (this.loadingEndSize === this.pdf_pages) {
            setTimeout(() => {
              this.loading = false;
              try {
                if (this.platform === "ios") {
                  loadFinished();
                }
              } catch (e) {
                console.error(e);
              }
              try {
                if (this.platform === "ios") {
                  window.webkit.messageHandlers.loadFinished.postMessage(
                    "h5_pdf_view"
                  );
                }
              } catch (e) {
                console.error(e);
              }
            }, 300);
          }
          if (this.pdf_pages > num) {
            setTimeout(() => {
              this._renderPage(num + 1);
            }, 10);
          }
        });
      });
    },
  },
};
</script>
<style scoped>
.home_wrap {
  width: 100%;
  min-height: 50vh;
  position: relative;
}

.home_wrap .show-catalogue {
  position: fixed !important;
  right: 0 !important;
  top: 20% !important;
  z-index: 99999999 !important;

  height: 20px;
  font-size: 14px;
  color: #ffffff;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  padding: 5px 10px;
}

.home_wrap .pdf_down {
  position: absolute;
  display: flex;
  z-index: 20;
  right: 26px;
  bottom: 7%;
}

.home_wrap .pdf_down .pdf_set_left {
  width: 30px;
  height: 40px;
  color: #408fff;
  font-size: 11px;
  padding-top: 25px;
  text-align: center;
  margin-right: 5px;
  cursor: pointer;
}

.home_wrap .pdf_down .pdf_set_middle {
  width: 30px;
  height: 40px;
  color: #408fff;
  font-size: 11px;
  padding-top: 25px;
  text-align: center;
  margin-right: 5px;
  cursor: pointer;
}

.position-phone {
  display: flex;
  align-items: center;
  position: fixed;
  top: 50%;
  left: 66.666666%;
  color: #ffffff;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 2.5vw;
  height: 5vw;
  padding: 0 2vw;
  opacity: 0.8;
  font-size: 2.5vw;
}

#scrollBox {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading {
  width: 100%;
  height: 100%;
  background: #ffffff;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 99;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.loading-hide {
  position: fixed;
  left: 200vw;
  top: 200vh;
  opacity: 0;
}

.catalogue-btn {
  color: #ffffff;
  font-size: 13px;
  font-weight: bold;
  width: 72px;
  height: 28px;
  background-color: #2a63f3;
  border-radius: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 70%;
  left: 12px;
  z-index: 999;
}

.catalogue-btn > img {
  width: 14px;
  margin-right: 3px;
}

.canvas-box {
  position: relative;
}
.ws {
  width: max-content;
  transform: translateX(-50%) rotateZ(315deg);
  color: rgba(0, 0, 0, 0.2);
  font-weight: bold;
  pointer-events: none;
  position: absolute;
  z-index: 9;
  top: 50%;
  left: 50%;
}

/*const fontSize = parseInt(canvasWrapper.style.width) / 12;*/
/*var cover = document.createElement('div');*/
/*cover.className = "cover";*/
/*cover.style.height = fontSize + 'px';*/
/*cover.style.lineHeight = fontSize + 'px';*/
/*cover.style.position = 'absolute';*/
/*cover.style.left = '50%';*/
/*cover.style.top = `calc(50% - ${fontSize}px)`;*/
/*cover.style.display = 'flex';*/
/*cover.style.alignItems = 'center';*/
/*cover.style.justifyContent = 'center';*/
/*cover.style.transform = 'translateX(-50%)';*/
/*cover.style.pointerEvents = 'none' // 取消所有事件*/
/*                                      let c = document.createElement('div')*/
/*c.className = "cover"*/
/*c.style.width = 'max-content';*/
/*c.style.fontSize = fontSize + 'px';*/
/*c.style.transform = "rotateZ(315deg)";*/
/*c.style.color = "rgba(0, 0, 0, 0.20)";*/
/*c.style.fontWeight = 'bold';*/
/*c.innerText = watermarkText;*/
/*c.style.pointerEvents = 'none' // 取消所有事件*/
/*                                  cover.appendChild(c);*/
/*if (this.annotationLayer?.div) {*/
/*  div.insertBefore(textLayerDiv, this.annotationLayer.div);*/
/*  div.appendChild(cover);*/
/*} else {*/
/*    div.appendChild(textLayerDiv);*/
/*    div.appendChild(cover);*/
/*  }*/
</style>
