<template>
  <div class="certificate-container">
    <div class="print-buttons no-print">
      <button class="print-btn" @click="printCertificate">打印证书</button>
      <button class="print-btn download-btn" @click="downloadCertificate">下载证书</button>
      <!-- <button class="print-btn image-btn" @click="saveAsImage">保存为图片</button> -->
    </div>
    <div class="containerQuali" id="certificate-content" :style="{ backgroundImage: `url(${backgroundImageUrl})` }">
      <div class="left">
        <div class="title">结业证书</div>
        <div class="headphoto">
          <img :src="trainCertificateInfo.certificatePhoto" alt="证书照片" />
        </div>
        <div class="infolist">
          <div class="infolistul">
            <div class="infolistspan info4">
              <span class="infostrong">证书编号: </span>
              <span class="infoem">{{ trainCertificateInfo.certificateNo || "" }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="nr1" style="margin-bottom: 10px;margin-left: 0;">
          <span class="nrname" style="margin-left: 0;">&nbsp;&nbsp;&nbsp;{{ trainCertificateInfo.personName ||
            "" }}&nbsp;&nbsp;&nbsp;</span>:
        </div>
        <div class="nr2" style="text-indent: 40px">于&nbsp;&nbsp;&nbsp;<span>{{ trainCertificateInfo.startTime || "" }}
          </span>&nbsp;&nbsp;&nbsp;至&nbsp;&nbsp;&nbsp; <span>{{ trainCertificateInfo.endTime || "" }}</span>，
          参加&nbsp;&nbsp;<span>{{ trainCertificateInfo.certificateType ||
            "" }}</span>&nbsp;&nbsp;保安员技能培训，完成培训计划规定的所有课程，成绩合格，准予结业。</div>
        <div class="nr4">
          <span class="nrfzDate">{{ trainCertificateInfo.trainName || "" }}</span>
        </div>
        <div class="nr5">
          <span class="nrfztitle">颁发日期：</span>
          <span class="nrfzDate">{{ trainCertificateInfo.certificateDate || "" }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import backgroundImage from '../assets/images/background.jpg';

export default {
  data() {
    return {
      info: {
        userInfo: {
          credential: {}
        }
      },
      trainCertificateInfo: {},
      isDownloading: false,
      backgroundImageUrl: backgroundImage
    };
  },

  mounted() {
    console.log('this.$route.query', this.$route.query);
    let query = this.$route.query;
    console.log('options', query);
    this.trainCertificateInfo = query;
  },
  methods: {
    // 打印证书
    printCertificate() {
      setTimeout(() => {
        window.print();
      }, 500);
    },

    // 动态加载html2canvas库
    async loadHtml2Canvas() {
      if (!window.html2canvas) {
        const script = document.createElement('script');
        script.src = 'https://html2canvas.hertzen.com/dist/html2canvas.min.js';
        script.async = true;
        document.body.appendChild(script);

        return new Promise((resolve) => {
          script.onload = () => resolve(window.html2canvas);
        });
      }
      return Promise.resolve(window.html2canvas);
    },

    // 动态加载jsPDF库
    async loadJsPDF() {
      if (!window.jspdf) {
        const script = document.createElement('script');
        script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js';
        script.async = true;
        document.body.appendChild(script);

        return new Promise((resolve) => {
          script.onload = () => resolve(window.jspdf);
        });
      }
      return Promise.resolve(window.jspdf);
    },

    // 预加载图片
    preloadImage(url) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.onerror = () => reject(new Error(`Failed to load image: ${url}`));
        img.src = url;
      });
    },

    // 下载证书为PDF（带背景图片）
    async downloadCertificate() {
      if (this.isDownloading) return;
      this.isDownloading = true;

      try {
        // 显示加载提示
        this.$message ? this.$message({
          message: '正在生成PDF，请稍候...',
          type: 'info',
          duration: 5000,
          showClose: false
        }) : alert("正在生成PDF，请稍候...");

        // 加载必要的库
        await this.loadHtml2Canvas();
        await this.loadJsPDF();

        // 获取证书内容元素
        const element = document.getElementById('certificate-content');

        // 使用导入的背景图片URL
        const backgroundImageUrl = this.backgroundImageUrl;

        // 预加载背景图片和头像图片
        try {
          await this.preloadImage(backgroundImageUrl);
          console.log("背景图片加载成功:", backgroundImageUrl);
          
          // 预加载头像图片
          if (this.trainCertificateInfo.certificatePhoto) {
            await this.preloadImage(this.trainCertificateInfo.certificatePhoto);
            console.log("头像图片加载成功:", this.trainCertificateInfo.certificatePhoto);
          }
        } catch (err) {
          console.error("图片加载失败:", err);
        }

        // 创建一个新的容器，用于生成PDF
        const container = document.createElement('div');
        container.style.position = 'absolute';
        container.style.left = '-9999px';
        container.style.top = '-9999px';
        document.body.appendChild(container);

        // 克隆证书内容并应用所有计算样式
        const clone = element.cloneNode(true);
        container.appendChild(clone);

        // 统一使用一个样式复制方法
        this.copyComputedStyles(element, clone);

        // 确保背景图片正确应用
        clone.style.backgroundImage = `url(${backgroundImageUrl})`;
        clone.style.backgroundSize = 'cover';
        clone.style.backgroundPosition = 'center';
        clone.style.backgroundRepeat = 'no-repeat';
        clone.style.width = element.offsetWidth + 'px';
        clone.style.height = element.offsetHeight + 'px';

        // 特别处理头像容器，确保居中显示
        const headphotoElement = clone.querySelector('.headphoto');
        if (headphotoElement) {
          headphotoElement.style.display = 'flex';
          headphotoElement.style.justifyContent = 'center';
          headphotoElement.style.alignItems = 'center';
          headphotoElement.style.margin = '0 auto 80px';
          
          // 确保头像图片正确显示
          const imgElement = headphotoElement.querySelector('img');
          if (imgElement) {
            imgElement.style.width = '100%';
            imgElement.style.height = '100%';
            imgElement.style.objectFit = 'fill';
            imgElement.style.display = 'block';
          }
        }

        // 确保所有文本元素颜色足够深
        const textElements = clone.querySelectorAll('span, div');
        textElements.forEach((el) => {
          const computedStyle = window.getComputedStyle(el);
          if (computedStyle.color === 'rgba(0, 0, 0, 0)' ||
            computedStyle.color === 'transparent') {
            el.style.color = '#000000';
          }

          // 确保字体正确应用
          if (computedStyle.fontFamily) {
            el.style.fontFamily = computedStyle.fontFamily;
          }
        });

        // 创建canvas，提高清晰度和准确性
        const canvas = await html2canvas(clone, {
          scale: 3, // 提高清晰度
          useCORS: true, // 允许加载跨域图片
          backgroundColor: null, // 透明背景
          logging: false, // 禁用日志以提高性能
          allowTaint: true,
          imageTimeout: 0, // 不超时
          onclone: (clonedDoc, clonedElement) => {
            // 在克隆的文档中应用额外的样式修复
            const headphotoElement = clonedElement.querySelector('.headphoto');
            if (headphotoElement) {
              headphotoElement.style.display = 'flex';
              headphotoElement.style.justifyContent = 'center';
              headphotoElement.style.alignItems = 'center';
              headphotoElement.style.margin = '0 auto 80px';
              
              const imgElement = headphotoElement.querySelector('img');
              if (imgElement) {
                imgElement.style.width = '100%';
                imgElement.style.height = '100%';
                imgElement.style.objectFit = 'fill';
                imgElement.style.display = 'block';
              }
            }
          }
        });

        // 清理临时元素
        document.body.removeChild(container);

        // 获取原始证书的尺寸并计算最佳PDF尺寸
        const originalWidth = element.offsetWidth;
        const originalHeight = element.offsetHeight;

        // 使用更精确的DPI计算
        const DPI = window.devicePixelRatio * 96; // 考虑设备像素比
        const INCH_TO_MM = 25.4;

        // 计算PDF尺寸，保持原始比例
        let pdfWidth = (originalWidth / DPI) * INCH_TO_MM;
        let pdfHeight = (originalHeight / DPI) * INCH_TO_MM;

        // 优化PDF尺寸，确保最佳打印质量
        const A4_WIDTH = 210; // A4纸宽度（毫米）
        const QUALITY_FACTOR = 1.2; // 质量提升因子

        // 根据A4纸张大小调整尺寸
        if (pdfWidth > A4_WIDTH) {
          const scale = A4_WIDTH / pdfWidth;
          pdfWidth = A4_WIDTH;
          pdfHeight *= scale;
        }

        // 应用质量提升因子
        pdfWidth *= QUALITY_FACTOR;
        pdfHeight *= QUALITY_FACTOR;

        // 计算最终尺寸
        const aspectRatio = pdfWidth / pdfHeight;

        // 转换为高质量图片数据
        const imgData = canvas.toDataURL('image/jpeg', 1.0);

        // 创建优化的PDF文档
        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF({
          orientation: aspectRatio > 1 ? 'l' : 'p',
          unit: 'mm',
          format: [pdfWidth, pdfHeight],
          compress: true,
          hotfixes: ['px_scaling'] // 修复像素缩放问题
        });

        // 添加图片到PDF，使用优化的设置
        pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, pdfHeight, undefined, 'FAST');

        // 下载PDF
        pdf.save(`证书_${this.trainCertificateInfo.personName || '未命名'}.pdf`);

      } catch (error) {
        console.error('下载证书失败:', error);
        alert('下载证书失败，请稍后重试。错误详情: ' + error.message);
      } finally {
        this.isDownloading = false;
      }
    },

    // 保存证书为图片
    async saveAsImage() {
      if (this.isDownloading) return;
      this.isDownloading = true;

      try {
        // 显示加载提示
        this.$message ? this.$message({
          message: '正在生成图片，请稍候...',
          type: 'info',
          duration: 5000,
          showClose: false
        }) : alert("正在生成图片，请稍候...");

        // 加载必要的库
        await this.loadHtml2Canvas();

        // 获取证书内容元素
        const element = document.getElementById('certificate-content');

        // 使用导入的背景图片URL
        const backgroundImageUrl = this.backgroundImageUrl;

        // 预加载背景图片和头像图片
        try {
          await this.preloadImage(backgroundImageUrl);
          console.log("背景图片加载成功:", backgroundImageUrl);
          
          // 预加载头像图片
          if (this.trainCertificateInfo.certificatePhoto) {
            await this.preloadImage(this.trainCertificateInfo.certificatePhoto);
            console.log("头像图片加载成功:", this.trainCertificateInfo.certificatePhoto);
          }
        } catch (err) {
          console.error("图片加载失败:", err);
        }

        // 创建一个新的容器，用于生成图片
        const container = document.createElement('div');
        container.style.position = 'absolute';
        container.style.left = '-9999px';
        container.style.top = '-9999px';
        document.body.appendChild(container);

        // 克隆证书内容并应用所有计算样式
        const clone = element.cloneNode(true);
        container.appendChild(clone);

        // 应用所有计算样式
        this.copyComputedStyles(element, clone);

        // 确保背景图片正确应用
        clone.style.backgroundImage = `url(${backgroundImageUrl})`;
        clone.style.backgroundSize = 'cover';
        clone.style.backgroundPosition = 'center';
        clone.style.backgroundRepeat = 'no-repeat';
        clone.style.width = element.offsetWidth + 'px';
        clone.style.height = element.offsetHeight + 'px';

        // 特别处理头像容器，确保居中显示
        const headphotoElement = clone.querySelector('.headphoto');
        if (headphotoElement) {
          headphotoElement.style.display = 'flex';
          headphotoElement.style.justifyContent = 'center';
          headphotoElement.style.alignItems = 'center';
          headphotoElement.style.margin = '0 auto 80px';
          
          // 确保头像图片正确显示
          const imgElement = headphotoElement.querySelector('img');
          if (imgElement) {
            imgElement.style.width = '100%';
            imgElement.style.height = '100%';
            imgElement.style.objectFit = 'fill';
            imgElement.style.display = 'block';
          }
        }

        // 确保所有文本元素颜色足够深
        const textElements = clone.querySelectorAll('span, div');
        textElements.forEach((el) => {
          const computedStyle = window.getComputedStyle(el);
          if (computedStyle.color === 'rgba(0, 0, 0, 0)' ||
            computedStyle.color === 'transparent') {
            el.style.color = '#000000';
          }

          // 确保字体正确应用
          if (computedStyle.fontFamily) {
            el.style.fontFamily = computedStyle.fontFamily;
          }
        });

        // 创建canvas，提高清晰度和准确性
        const canvas = await html2canvas(clone, {
          scale: 3, // 提高清晰度
          useCORS: true, // 允许加载跨域图片
          backgroundColor: null, // 透明背景
          logging: false, // 禁用日志以提高性能
          allowTaint: true,
          imageTimeout: 0, // 不超时
          onclone: (clonedDoc, clonedElement) => {
            // 在克隆的文档中应用额外的样式修复
            const headphotoElement = clonedElement.querySelector('.headphoto');
            if (headphotoElement) {
              headphotoElement.style.display = 'flex';
              headphotoElement.style.justifyContent = 'center';
              headphotoElement.style.alignItems = 'center';
              headphotoElement.style.margin = '0 auto 80px';
              
              const imgElement = headphotoElement.querySelector('img');
              if (imgElement) {
                imgElement.style.width = '100%';
                imgElement.style.height = '100%';
                imgElement.style.objectFit = 'fill';
                imgElement.style.display = 'block';
              }
            }
          }
        });

        // 清理临时元素
        document.body.removeChild(container);

        // 转换为高质量图片数据
        const imgData = canvas.toDataURL('image/png', 1.0);

        // 创建下载链接
        const downloadLink = document.createElement('a');
        downloadLink.href = imgData;
        downloadLink.download = `证书_${this.trainCertificateInfo.personName || '未命名'}.png`;
        
        // 触发下载
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);

        // 显示成功消息
        this.$message ? this.$message({
          message: '图片已保存',
          type: 'success',
          duration: 3000
        }) : alert("图片已保存");

      } catch (error) {
        console.error('保存图片失败:', error);
        alert('保存图片失败，请稍后重试。错误详情: ' + error.message);
      } finally {
        this.isDownloading = false;
      }
    },

    // 复制计算样式的辅助方法
    copyComputedStyles(sourceElement, targetElement) {
      // 递归复制所有元素的计算样式
      const copyStyles = (source, target) => {
        // 获取计算样式
        const computedStyle = window.getComputedStyle(source);

        // 复制所有样式属性
        for (let i = 0; i < computedStyle.length; i++) {
          const property = computedStyle[i];
          target.style[property] = computedStyle.getPropertyValue(property);
        }

        // 递归处理子元素
        const sourceChildren = source.children;
        const targetChildren = target.children;

        for (let i = 0; i < sourceChildren.length; i++) {
          if (targetChildren[i]) {
            copyStyles(sourceChildren[i], targetChildren[i]);
          }
        }
      };

      // 开始递归复制
      copyStyles(sourceElement, targetElement);
    }
  }
};
</script>
<style scoped>
.certificate-container {
  position: relative;
  padding-top: 60px;
}

.print-buttons {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 100;
  display: flex;
  gap: 10px;
}

.print-btn {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.print-btn:hover {
  background-color: #45a049;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.pdf-btn {
  background-color: #2196F3;
}

.pdf-btn:hover {
  background-color: #0b7dda;
}

.download-btn {
  background-color: #FF9800;
}

.download-btn:hover {
  background-color: #e68a00;
}

.image-btn {
  background-color: #2196F3;
}

.image-btn:hover {
  background-color: #0b7dda;
}

.containerQuali {
  display: flex;
  width: 90%;
  max-width: 846px;
  min-height: 600px;
  margin: 40px auto;
  /* font-family: "Microsoft YaHei", "SimSun", serif; */
  box-shadow: 0 0 25px rgba(0, 0, 0, 0.15);
  position: relative;
  overflow: hidden;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

.left {
  flex: 0 0 45%;
  padding: 90px 50px;
  position: relative;
  z-index: 1;
}

.right {
  flex: 1;
  padding: 90px 90px 90px 50px;
  position: relative;
}

.title {
  font-size: 35px;
  font-family: serif;
  font-weight: bold;
  text-align: center;
  color: #222;
  margin-bottom: 40px;
  letter-spacing: 4px;
  text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
  position: relative;
  padding-bottom: 15px;
}

.headphoto {
  width: 100px;
  height: 140px;
  margin: 0 auto 80px;
  border: 3px solid #ddd;
  border-radius: 5px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.headphoto::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.2);
  pointer-events: none;
}

.headphoto img {
  width: 100%;
  height: 100%;
  object-fit: fill;
  transition: transform 0.3s ease;
  display: block;
}

.infolist {
  padding: 20px;
}

.infolistul {
  margin: 0;
  padding: 0;
  list-style: none;
}

.infolistspan {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #555;
}

.infostrong {
  /* font-weight: bold; */
  margin-right: 15px;
  color: #222;
  min-width: 80px;
}

.infoem {
  color: #444;
  letter-spacing: 1px;
  white-space: nowrap;
}

.nr1 {
  margin-bottom: 30px;
  padding-bottom: 15px;
}

.nrname {
  font-size: 24px;
  color: #222;
  letter-spacing: 2px;
  border-bottom: 1px solid currentColor; /* 使用当前文字颜色 */
  padding-bottom: 2px; /* 可选：调整下划线间距 */
}

.nr2 {
  font-size: 19px;
  line-height: 2;
  margin-bottom: 40px;
  text-align: justify;
  position: relative;
}

.nr4 {
  margin-top: 80px;
  text-align: left;
  position: relative;
}

.nr5 {
  margin-top: 20px;
  text-align: left;
  position: relative;
}

.nrfztitle {
  font-size: 18px;
  color: #222;
  margin-right: 15px;
}

.nrfzDate {
  font-size: 18px;
  color: #222;
  letter-spacing: 1px;
}

/* 打印样式 */
@media print {
  .no-print {
    display: none !important;
  }

  body {
    margin: 0;
    padding: 0;
    background: white;
  }

  .certificate-container {
    padding-top: 0;
  }

  .containerQuali {
    width: 100%;
    max-width: 100%;
    margin: 0;
    box-shadow: none;
    min-height: auto;
    page-break-inside: avoid;
  }

  /* 确保背景图片在打印时显示 */
  .containerQuali {
    -webkit-print-color-adjust: exact !important;
    color-adjust: exact !important;
    print-color-adjust: exact !important;
  }
}

/* 响应式调整 */
/* @media screen and (max-width: 900px) {
  .containerQuali {
    width: 95%;
    border-width: 10px;
    flex-direction: column;
  }

  .left {
    flex: none;
    width: 100%;
    border-right: none;
    border-bottom: 2px solid #e8e8e8;
    padding: 20px;
  }

  .right {
    padding: 25px;
  }

  .title {
    font-size: 28px;
    margin-bottom: 25px;
  }

  .headphoto {
    width: 180px;
    height: 180px;
    margin-left: auto;
    margin-right: auto;
  }

  .nr2 {
    font-size: 16px;
    padding: 15px;
  }

  .nrname {
    font-size: 24px;
  }
} */

@media screen and (max-width: 480px) {
  .containerQuali {
    border-width: 5px;
    margin: 20px auto;
  }

  .headphoto {
    width: 150px;
    height: 150px;
    margin-left: auto;
    margin-right: auto;
  }

  .title {
    font-size: 24px;
  }

  .infostrong {
    min-width: 60px;
  }
}
</style>