<template>
  <el-dialog title="文档" v-model="visible">
    <div v-if="visible">
      <vue-pdf
        ref="pdfRef"
        v-for="page in numOfPages"
        :key="page"
        :src="VITE_FILE_URL + src"
        :page="page"
      />
    </div>
  </el-dialog>
</template>

<script setup>
import { watchEffect, ref } from "vue";
import { VuePdf, createLoadingTask } from "vue3-pdfjs/esm";
import { ElMessage } from "element-plus";
import { useVModel } from "@vueuse/core";

const VITE_FILE_URL = import.meta.env.VITE_FILE_URL;
defineOptions({
  name: "LayoutPdf",
});
const props = defineProps({
  src: {
    type: String,
    required: true,
  },
  visible: {
    type: Boolean,
    default: false,
    required: true,
  },
});
const emits = defineEmits(["update:visible"]);
const visible = useVModel(props, "visible", emits);
const pdfRef = ref(null);
const numOfPages = ref(0);
watchEffect(() => {
  if (props.visible) {
    const loadingTask = createLoadingTask(VITE_FILE_URL + props.src);
    loadingTask.promise
      .then((pdf) => {
        numOfPages.value = pdf.numPages;
      })
      .catch(() => {
        visible.value = false;
        ElMessage.error("文件加载失败");
      });
  }
});
</script>
