import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import axios from 'axios'
import Cookies from 'js-cookie'

// export const exportPDF = async (elementId, fileName = 'document.pdf') => {
export const exportPDF = async (element, fileName = 'document.pdf') => {
  // 获取要转换的DOM元素
  // const element = document.getElementById(elementId);
  if (!element) throw new Error('找不到目标元素');
  
  // 获取元素原始尺寸
  const originalWidth = element.scrollWidth;
  console.log(originalWidth,'originalWidth')
  const originalHeight = element.scrollHeight;
  console.log(originalHeight,'originalHeight')
  
  // 设置PDF参数
  const PDF_WIDTH = 210; // A4纸宽(单位:mm)
  const PDF_HEIGHT = 297; // A4纸高
  const PDF_PADDING = 10; // 页面内边距
  
  const pdf = new jsPDF('p', 'mm', 'a4');
  
  // 计算缩放比例
  const scale = PDF_WIDTH / originalWidth;
  console.log(scale,'scale')
  const canvasWidth = originalWidth;
  const canvasHeight = PDF_HEIGHT / scale;
  console.log(canvasHeight,'canvasHeight')
  
  // 计算总页数
  const pageCount = Math.ceil(originalHeight / canvasHeight);
  console.log(pageCount,'pageCount')
  
  // 循环渲染每一页
  for (let i = 0; i < pageCount; i++) {
    if (i > 0) pdf.addPage();
    
    // 计算当前页面的裁剪位置
    const canvas = await html2canvas(element, {
      scale: 2, // 提高分辨率
      scrollY: -window.scrollY,
      useCORS: true, // 开启跨域支持
      allowTaint: true, // 允许加载外部资源
      windowHeight: canvasHeight,
      y: canvasHeight * i,
      height: canvasHeight,
      width: originalWidth
    });
    if (i % 3 === 0) await new Promise(r => setTimeout(r, 200));
    
    // 将Canvas转换为图片
    const imgData = canvas.toDataURL('image/jpeg', 0.95);
    
    // 添加页面
    pdf.addImage(
      imgData,
      'JPEG',
      PDF_PADDING,
      PDF_PADDING,
      PDF_WIDTH - PDF_PADDING * 2,
      (canvas.height * PDF_WIDTH) / canvas.width - PDF_PADDING * 2
    );
    }

    const pdfBlob = pdf.output('blob');
    const formData = new FormData();
    formData.append('file', pdfBlob, fileName);
    const response = await axios.post(
        `${window.SITE_CONFIG["apiURL"]}/sys/oss/uploadFile`,
        formData,
        {
            headers: {
                'Content-Type': 'multipart/form-data',
                'token': Cookies.get('token') || ''
            }
        }
    );
    return response

  // 保存PDF
  // pdf.save(fileName);
};