import fs from "fs";
import path from "path";
import { jsPDF } from "jspdf";
import mkdirp from "mkdirp";
export async function saveToPDF(imgList: string[], filePath: string[]) {
  const targetLocation = path.join(...filePath);
  // 生成pdf
  // 第一个参数：l横向，p纵向
  // 第二个参数：计量单位: cm mm px等
  // 第三个参数：格式: 默认a4
  const { maxWidth, maxHeight } = await getMaxWidthHeight(imgList);
  const recordPdf: any = new jsPDF("l", "px", [maxWidth, maxHeight]);
  // 从top的位置开始加图片
  for (let i = 0; i < imgList.length; i++) {
    const url = imgList[i];
    const { width, height }: any = await getImgWidthHeight(url);
    recordPdf.addImage(url, "jpg", 1, 1, width, height);
    recordPdf.addPage([maxWidth, maxHeight]);
  }
  // 删除最后一页留白
  const targetPage = recordPdf.internal.getNumberOfPages();
  recordPdf.deletePage(targetPage);
  // recordPdf.save("PDF存档.pdf");
  const rawdata = recordPdf.output();
  let len = rawdata.length;
  const u8 = new Uint8Array(len);
  while (len--) u8[len] = rawdata.charCodeAt(len);
  const buffer = new Buffer(u8);
  mkdirp.sync(path.dirname(targetLocation));
  fs.writeFile(targetLocation, buffer, function (e) {
    if (e) throw e;
  });
}
// 获取图片数组里面最大的宽度和高度
async function getMaxWidthHeight(imgList: string[]) {
  const widthList = [];
  const heightList = [];
  let maxHeight = 0;
  let maxWidth = 0;
  for (let i = 0; i < imgList.length; i++) {
    const url = imgList[i];
    const { width, height }: any = await getImgWidthHeight(url);
    widthList.push(width);
    heightList.push(height);
  }
  // 把数组变成升序然后倒过来取第一个就是拿最大宽度
  maxWidth = widthList.sort().reverse()[0];
  maxHeight = heightList.sort().reverse()[0];
  return {
    maxWidth,
    maxHeight,
  };
}
//获取图片宽高
function getImgWidthHeight(src: any) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.src = src;
    // 图片是否有缓存 如果有缓存可以直接拿 如果没有缓存 需要从onload拿
    if (img.complete) {
      const { width, height } = img;
      resolve({
        width,
        height,
      });
    } else {
      img.onload = function () {
        const { width, height } = img;
        resolve({
          width,
          height,
        });
      };
    }
  });
}
