import { toPng } from 'html-to-image';
import JsPDF from 'jspdf'
 
const htmlToPdf = {
  isSplit (item: any, nextItem: any, pageHeight: any) {
    // 计算当前这块dom是否跨越了a4大小，以此分割
    if (item.offsetTop + item.offsetHeight < pageHeight && nextItem
      && nextItem.offsetTop + nextItem.offsetHeight > pageHeight) {
        return true;
    }
    return false;
  },
  getImg(root: any, callback: any) {
    const element = document.getElementById(root)
    if (!element) {
      console.error("指定的元素不存在");
      return
    }
    const A4_WIDTH = 592.28;
    const A4_HEIGHT = 841.89;
    const scale = A4_HEIGHT / A4_WIDTH;
    const pageHeight = element.scrollWidth * scale;
    const items = element.querySelectorAll(".pdf-item")
    for (let i = 0; i < items.length; i++) {
      const item: any = items[i]
      const nextItem : any = items[i + 1]
      let multiple = Math.ceil((item.offsetTop + item.offsetHeight) / pageHeight);
      if (i < items.length - 1 && this.isSplit(item, nextItem, multiple * pageHeight)) {
        let _H = multiple * pageHeight - (item.offsetTop + item.offsetHeight);
        item.style.marginBottomOld = item.style.marginBottom || '0px'
        console.log(_H);
        
        item.style.marginBottom = _H + 10 + 'px';
      }
    }
    toPng(element).then((dataUrl) => {
      var img = new Image();
      img.src = dataUrl;
      var contentWidth = element?.clientWidth;
      var contentHeight = element?.clientHeight;
      // 未生成pdf的html页面高度
      var leftHeight = contentHeight;
      
      console.log("pageHeight", pageHeight)
      console.log("leftHeight", leftHeight)
      // 页面偏移
      var position = 0;
      // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
      var imgWidth = 595.28;
      var imgHeight = 592.28 / contentWidth * contentHeight;
      console.log(imgWidth, imgHeight);
      var pdf = new JsPDF(undefined, 'pt', 'a4');

      // 有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
      // 当内容未超过pdf一页显示的范围，无需分页
      if (leftHeight < pageHeight) {
        console.log("没超过1页")
        pdf.addImage(img, 'JPEG', 0, 0, A4_WIDTH, imgHeight);
      } else {
        while (leftHeight > 0) {
          console.log("超过1页")
          pdf.addImage(img, 'JPEG', 0, position, imgWidth, imgHeight)
          leftHeight -= pageHeight;
          console.log();
          
          position -= 841.89;
          // 避免添加空白页
          if (leftHeight > 0) {
            pdf.addPage();
          }
        }
      }
      callback(pdf)
    }).catch(function (error) {
      console.error(error);
    }).finally(() => {
      for (let i = 0; i < items.length; i++) {
        const item: any = items[i]
          if (item.style.marginBottomOld) {
            item.style.marginBottom = item.style.marginBottomOld
          }
        }
    }) 
  }
}
 
export default htmlToPdf