<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    append-to-body
    title="查看打印公文"
    width="80%"
    :before-close="handleClose"
  >
    <div class="setting-dialog">
      <div
        v-if="loading"
        v-loading="loading"
        element-loading-text="正在加载公文文档，请稍候..."
        element-loading-spinner="el-icon-loading"
        class="global-loading"
      >
        <!-- <p>正在加载文档，请稍候...</p> -->
      </div>

      <PdfViewer
        v-else-if="pdfSources.length > 0"
        ref="pdfViewerRef"
        :pdf-sources="pdfSources"
        frame-height="70vh"
        @pdfPrinted="onPdfPrinted"
      />

      <div v-else class="empty-state">
        <img style="display: block; width: 100px;" src="~@/assets/images/errRecord.png" alt="">
        <span>没有可打印的公文文档</span>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button
        v-if="pdfSources.length > 0"
        type="primary"
        style="width: auto; padding: 0 6px;"
        @click="printPdf"
      >
        <i class="iconfont icon-dayin" />打印文档
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { FetchHandleDocument } from '@/api/system/documentArchives'
import PdfViewer from './pdfViewer.vue'

export default {
  components: { PdfViewer },
  data() {
    return {
      dialogVisible: false,
      pdfSources: [],
      loading: false,
      selectedDocumentId: null
    }
  },
  methods: {
    /**
     * 打开对话框并加载PDF
     */
    async openDialog(params) {
      this.dialogVisible = true
      await this.loadPdfData(params)
    },
    /**
     * 加载PDF数据
     */
    async loadPdfData(params) {
      this.loading = true
      this.pdfSources = []
      try {
        const res = await FetchHandleDocument(params)
        // 处理Base64格式的响应
        this.pdfSources = res.map(item => {
          return item.startsWith('data:application/pdf;base64,')
            ? item
            : `data:application/pdf;base64,${item}`
        })
      } catch (error) {
        this.$message.error(`加载文档失败: ${error.message}`)
        console.error('获取PDF失败:', error)
      } finally {
        this.loading = false
      }
    },
    /**
     * 关闭对话框
     */
    handleClose() {
      this.pdfSources = [] // 清空数据
      this.dialogVisible = false
    },
    /**
     * 调用打印功能
     */
    printPdf() {
      this.$refs.pdfViewerRef.handlePrint()
    },
    /**
     * 打印完成回调（可选）
     */
    onPdfPrinted() {
      console.log('PDF打印已触发')
    }
  }
}
</script>

<style scoped>
.global-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 70vh;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 70vh;
  color: #000;
}
.dialog-footer{
  margin-top: 0 !important;
}
</style>
