<!-- 文件预览弹窗 -->
<script lang="ts" setup name="FilePreviewDialog">
import VuePdfEmbed from 'vue-pdf-embed'
import * as pdfjsLib from 'pdfjs-dist'
import { getPhotoUrl } from '@/api/system/tool'
import { getBase64 } from '@/utils/download'

const dialogVisible = ref(false) // 弹窗显示状态
const loading = ref<boolean>(true)
const pdfUrl = ref('') // 打印文件url

/**
 * 初始化审批弹窗
 * @param printFileName 文件名
 */
function initDialog(printFileName: string) {
  dialogVisible.value = true
  pdfUrl.value = ''
  loading.value = true

  getPhotoUrl(printFileName).then((res) => {
    pdfUrl.value = res.data
    loading.value = false
  }).catch(() => {
    loading.value = false
  })

  pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js'
}

function initDialogContent(stream: Blob) {
  dialogVisible.value = true
  pdfUrl.value = ''
  loading.value = true

  getBase64(stream).then((res) => {
    pdfUrl.value = res as string
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 关闭弹窗
function handleClose() {
  dialogVisible.value = false
}

// ----------------------- 以下是暴露的方法内容 ----------------------------
defineExpose({ initDialog, initDialogContent })
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="文件预览"
    width="80%"
    :before-close="handleClose"
  >
    <!-- pdf预览 -->
    <div v-loading="loading">
      <vue-pdf-embed v-show="!loading" ref="pdf" :source="pdfUrl" class="vue-pdf-embed" />
    </div>
    <template #footer>
      <el-button type="info" @click="handleClose">
        关闭
      </el-button>
    </template>
  </el-dialog>
</template>
