<template>
  <el-dialog title="文档" :model-value="visible && model === 'dialog'">
    <div v-if="visible && model === 'dialog'">
      <vue-pdf
        ref="pdfRef"
        v-for="page in numOfPages"
        :key="page"
        :src="VITE_FILE_URL + src"
        :page="page"
      />
    </div>
  </el-dialog>
  <div v-if="model === 'normal'">
    <vue-pdf
      ref="pdfRef"
      v-for="page in numOfPages"
      :key="page"
      :src="VITE_FILE_URL + src"
      :page="page"
    />
  </div>
</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,
  },
  model: {
    type: String,
    required: false,
    default: "dialog", // 模式: dialog=弹窗, normal=直接显示
  },
});
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>
