<template>
  <div class="container_all">
    <!-- ///:style="{ transform: `scale(${scale})` }"  @page-loaded="onPageLoaded" -->
    <div class="container_public">
      <div v-for="pageNumber in loadedPages" :key="pageNumber">
        <vue-pdf
          class="container_pdf"
          :key="`${pageNumber}===rrr`"
          :src="{
            url: fileUrl,
            cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.9.359/cmaps/',
            cMapPacked: true,
          }"
          :page="pageNumber"
          @rendered="handlePageRendered"
        ></vue-pdf>
      </div>
    </div>

    <img
      v-if="loadAll"
      src="../../static/explain/down_up.png"
      class="absolute_image1"
      @click="download"
    />
    <!-- <img
      v-if="loadAll"
      src="../../static/explain/scale_in.png"
      class="absolute_image2"
      @click="scaleIn"
    />
    <img
      v-if="loadAll"
      src="../../static/explain/scale_out.png"
      class="absolute_image3"
      @click="scaleOut"
    /> -->

    <!-- 全屏遮罩层 -->
    <div
      v-show="isLoading"
      class="fullscreen-loader"
      :style="{ zIndex: zIndex }"
    >
      <!-- 加载动画 -->
      <div class="loader">
        <div class="spinner"></div>
        <p class="tip">{{ text }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { detail } from "@/api/explain.js";
import VuePdf from "vue-pdf";

export default {
  components: {
    VuePdf,
  },

  data() {
    return {
      loadAll: false,
      name: "",
      fileUrl: "",
      fileName: "",
      currentPage: 1,
      numPages: 0,
      scale: 1,
      loadedPages: 0,

      isLoading: false,
      text: "拼命加载中...",
      zIndex: 9999,
    };
  },

  onLoad(e) {
    var that = this;
    that.id = e.id;
    // uni.showLoading({
    //   title: "加载中...",
    //   mask: true,
    // });
    // uni.hideLoading();
    that.getDetail();
  },

  methods: {
    // 滚动加载逻辑
    // {"type":"scroll","timeStamp":24324.79999999702,"detail":{},
    // "target":{"id":"","offsetLeft":0,"offsetTop":0,"dataset":{}},
    // "currentTarget":{"id":"","offsetLeft":0,"offsetTop":0,"dataset":{}},"touches":[],
    // "changedTouches":[],"mp":{"@warning":"mp is deprecated","type":"scroll",
    // "timeStamp":24324.79999999702,"detail":{},"target":{"id":"","offsetLeft":0,"offsetTop":0,"dataset":{}},
    // "currentTarget":{"id":"","offsetLeft":0,"offsetTop":0,"dataset":{}},"touches":[],"changedTouches":[]},
    // "_processed":true}
    handleScroll(e) {
      // const target = e.target;
      // var offsetTop = target.offsetTop;
      // // 滚动到底部且未加载完所有页
      // if (this.loadedPages < this.numPages) {
      //   this.loadedPages += 1; // 加载下一页
      // }
    },
    ///接口获取数据
    getDetail() {
      var that = this;
      var id = that.id;

      detail(id).then((res) => {
        if (res.code === 0) {
          that.name = res.data.name;
          var fileUrl = res.data.fileUrl;
          that.getPdfPages(fileUrl);
        } else {
          that.isLoading = false;
        }
      });
    },

    async getPdfPages(fileUrl) {
      var that = this;

      try {
        const loadingTask = VuePdf.createLoadingTask({
          url: fileUrl,
          cMapUrl: "https://cdn.jsdelivr.net/npm/pdfjs-dist@2.9.359/cmaps/",
          cMapPacked: true,
        });
        const pdf = await loadingTask.promise;
        var numPages = pdf.numPages;
        // that.loadedPages = that.numPages;
        if (numPages == 0) {
          return;
        }

        that.numPages = numPages;
        that.fileUrl = fileUrl;
        // await that.sleep(600);
        that.loadAll = true;
        that.loadedPages = numPages;
        // that.isLoading = false;
        // await that.sleep(2000);
        // that.isLoading = false;
      } catch (e) {
        console.error("PDF加载失败:", e);
      }
    },

    sleep(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms));
    },

    ///截取文件
    getFileExtension(fileUrl) {
      var filename = fileUrl.split("/").pop();
      var lastDotIndex = filename.lastIndexOf(".");
      if (lastDotIndex === -1 || lastDotIndex === filename.length - 1) {
        return "";
      } else {
        return filename.substring(lastDotIndex + 1).toLowerCase();
      }
    },

    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },

    nextPage() {
      if (this.currentPage < this.numPages) {
        this.currentPage++;
      }
    },

    scaleIn() {
      this.scale *= 1.1;
    },

    scaleOut() {
      this.scale /= 1.1;
    },

    async download() {
      var that = this;
      var name = that.name;
      var fileUrl = that.fileUrl;
      var fileName = that.getFileExtension(fileUrl);

      var finalName = "";
      if (name != null && name != "") {
        finalName = name + "." + fileName;
      } else {
        finalName = new Date().getTime() + "." + fileName;
      }

      try {
        // https://music-play.oss-cn-shenzhen.aliyuncs.com/backOss/file/f5f5ed93fae74fb683e8d116c40a884c.xlsx
        const response = await fetch(fileUrl);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        a.download = finalName;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      } catch (error) {}
    },
  },
};
</script>

<style scoped>
.container_all {
  width: 100vw;
  height: 100vh;
}

.container_public {
  width: 100vw;
  height: 100vh;
  overflow-y: auto;
}

.container_pdf {
  width: calc(100vw-2px);
  margin: 10px auto;
  border: 1px solid #e5e5e5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.absolute_image1 {
  position: fixed;
  bottom: 365px;
  right: 20px;
  width: 30px;
  height: 30px;
  padding: 5px 5px;
  background-color: white;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.absolute_image2 {
  position: fixed;
  bottom: 305px;
  right: 20px;
  width: 30px;
  height: 30px;
  padding: 5px 5px;
  background-color: white;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.absolute_image3 {
  position: fixed;
  bottom: 260px;
  right: 20px;
  width: 30px;
  height: 30px;
  padding: 5px 5px;
  background-color: white;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.fullscreen-loader {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(255, 255, 255, 1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.loader {
  text-align: center;
}

.spinner {
  width: 50px;
  height: 50px;
  margin: 0 auto 15px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.tip {
  color: #606266;
  font-size: 14px;
}
</style>