import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

/**
 * @param {HTMLElement} element 导出区域的DOM
 * @param {String} fileName 文件名
 */
export const exportToPdf = async (element: HTMLElement, fileName = 'report') => {
  if (!element) return;

  const originalStyle = element.style.cssText;
  element.style.width = '1200px';

  const tableWrappers = element.querySelectorAll<HTMLElement>(
    '.el-scrollbar__wrap, .el-table__body-wrapper'
  );
  tableWrappers.forEach((w) => {
    w.style.height = 'auto';
    w.style.overflow = 'visible';
  });

  try {
    const canvas = await html2canvas(element, {
      useCORS: true,
      scale: 2,
      allowTaint: false,
      backgroundColor: '#ffffff',
      ignoreElements: (el) => el.classList.contains('no-print'),
    });

    const contentWidth = canvas.width;
    const contentHeight = canvas.height;

    const a4Width = 595.28;
    const a4Height = 841.89;

    const imgWidth = a4Width;
    const imgHeight = (a4Width / contentWidth) * contentHeight;

    const pageCanvasHeight = (contentWidth / a4Width) * a4Height;

    let leftHeight = contentHeight;
    let position = 0;
    const pageData = canvas.toDataURL('image/jpeg', 1.0);
    const pdf = new jsPDF('p', 'pt', 'a4');

    if (leftHeight < pageCanvasHeight) {
      pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
    } else {
      while (leftHeight > 0) {
        pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
        leftHeight -= pageCanvasHeight;
        position -= a4Height;
        if (leftHeight > 0) {
          pdf.addPage();
        }
      }
    }

    pdf.save(`${fileName}.pdf`);
  } catch (error) {
    console.error('PDF导出失败', error);
  } finally {
    element.style.cssText = originalStyle;
    tableWrappers.forEach((w) => {
      w.style.height = '';
      w.style.overflow = '';
    });
  }
};
