import html2canvas from "html2canvas";
import printJS from "print-js";

/**
 * html转图片
 * @param printContent 传入一个ref
 * @param callback
 */
export const htmlToCanvas = (
  printContent: HTMLElement,
  callback: (url: string) => void
) => {
  // // 获取dom 宽度 高度
  // const width = printContent.clientWidth;
  // const height = printContent.clientHeight;
  // // 创建一个canvas节点
  // const canvas = document.createElement("canvas");
  //
  // const scale = 1; // 定义任意放大倍数，支持小数；越大，图片清晰度越高，生成图片越慢。
  // canvas.width = width * scale; // 定义canvas 宽度 * 缩放
  // canvas.height = height * scale; // 定义canvas高度 *缩放
  // canvas.style.width = width * scale + "px";
  // canvas.style.height = height * scale + "px";
  // canvas.getContext("2d").scale(scale, scale); // 获取context,设置scale
  //
  // const scrollTop =
  //   document.documentElement.scrollTop || document.body.scrollTop; // 获取滚动轴滚动的长度
  // const scrollLeft =
  //   document.documentElement.scrollLeft || document.body.scrollLeft; // 获取水平滚动轴的长度

  html2canvas(printContent)
    .then((canvas) => {
      const url = canvas.toDataURL("image/png");
      callback(url);
    })
    .catch((err) => {
      console.error(err);
    });
};

/**
 * 用printJs打印图片
 * @param url
 * @param callback
 */
export const printImg = (url: string) => {
  printJS({
    printable: url,
    type: "image",
    documentTitle: "", // 标题
    style: "@page{size:auto;margin: 1cm ;}", // 去除页眉页脚
  });
};

/**
 * html转图片打印
 * @param dom
 * @param callback
 */
export const html2CanvasPrint = (dom: HTMLElement, callback?: () => {}) => {
  //1、html转图片
  htmlToCanvas(dom, (url: string) => {
    //2、打印图片
    printImg(url);
  });
};
