<template>
  <el-drawer v-model="drawerVisible" size="1000">
    <template #header>
      <div style="display: flex; gap: 5px">
        <el-button type="primary" v-print="'#print'">打印</el-button>
        <el-button type="primary" @click="downLoadPdf">下载PDF</el-button>
      </div>
    </template>

    <div id="print">
      <DetailCom ref="detailComRef"></DetailCom>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, nextTick } from "vue";
import DetailCom from "@/views/statistic/inspectionReport/DetailCom.vue";
import html2pdf from "html2pdf.js";

const drawerVisible = ref(false);
const detailComRef = ref(null);

const showDrawer = (row) => {
  drawerVisible.value = true;

  nextTick(() => {
    detailComRef.value && detailComRef.value.refreshView(row);
  });
};

const downLoadPdf = () => {
  const printContent = document.getElementById("print");
  if (!printContent) {
    console.error("无法找到打印内容");
    return;
  }

  // 设置PDF选项
  const opt = {
    margin: 1,
    filename: `检验报告_${new Date().toLocaleDateString()}.pdf`,
    image: { type: "jpeg", quality: 0.98 },
    html2canvas: {
      scale: 2,
      useCORS: true, // 允许跨域图片
      allowTaint: true, // 允许污染图片
      logging: true, // 开启日志
      letterRendering: true, // 提高文字渲染质量
    },
    jsPDF: {
      unit: "mm",
      format: "a4",
      orientation: "portrait",
    },
    pagebreak: {
      mode: ["avoid-all", "css", "legacy"], // 更好的分页控制
    },
  };

  // 显示加载状态
  const loading = ElLoading.service({
    lock: true,
    text: "正在生成PDF，请稍候...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  // 生成PDF
  html2pdf()
    .set(opt)
    .from(printContent)
    .toPdf()
    .get("pdf")
    .then((pdf) => {
      // 可以在这里对PDF进行额外操作
      const totalPages = pdf.internal.getNumberOfPages();
      for (let i = 1; i <= totalPages; i++) {
        pdf.setPage(i);
        pdf.setFontSize(10);
        pdf.setTextColor(150);
        pdf.text(
          `${i} / ${totalPages}`,
          pdf.internal.pageSize.getWidth() - 30,
          pdf.internal.pageSize.getHeight() - 10
        );
      }
    })
    .save()
    .then(() => {
      loading.close();
      ElMessage.success("PDF下载成功");
    })
    .catch((err) => {
      loading.close();
      console.error("生成PDF失败:", err);
      ElMessage.error("生成PDF失败: " + err.message);
    });
};

defineExpose({ showDrawer });
</script>

<style scoped lang="scss">
@media print {
  #print {
    position: absolute;
    top: 20px;
    margin: 0;
    width: 1000px;
  }
}
</style>
