import { calcSum } from "@/plugins/utils";
import { downloadByBlob } from "@/plugins/download";

function loadPaper(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "";
    img.onload = function () {
      resolve([img.width, img.height]);
    };
    img.onerror = function (e) {
      reject(e);
    };
    img.src = url;
  });
}
async function initPapers(papers) {
  const fetchAll = papers.map((paper) => loadPaper(paper.url));
  const res = await Promise.all(fetchAll).catch(() => {});

  if (!res) {
    return Promise.reject("图片初始化错误");
  }

  res.forEach((size, index) => {
    papers[index].width = size[0];
    papers[index].height = size[1];
  });
  return papers;
}

function drawPaper(ctx, paper, rate, preHeight) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = "";
    img.onload = function () {
      ctx.drawImage(
        img,
        0,
        preHeight * rate,
        paper.width * rate,
        paper.height * rate
      );
      const fontSize = Math.ceil(30 * rate);
      ctx.font = `${fontSize}px '微软雅黑'`;
      ctx.fillStyle = "#3a5ae5";
      ctx.textBaseline = "top";

      // 绘制轨迹
      paper.track.forEach((trackItem) => {
        ctx.fillText(
          trackItem.content,
          trackItem.left * rate,
          (trackItem.top + preHeight) * rate
        );
      });

      resolve(true);
    };
    img.onerror = function () {
      reject("图片绘制错误");
    };
    img.src = paper.url;
  });
}

export async function buildCanvas(papers, rate = 1) {
  rate = rate < 0.5 ? 0.5 : rate;
  rate = rate > 2 ? 2 : rate;

  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");

  if (!canvas || !ctx) {
    return Promise.reject("不支持预览!");
  }

  papers = await initPapers(papers).catch(() => {});
  if (!papers) return Promise.reject("图片初始化错误");

  const maxWidth = Math.max.apply(
    null,
    papers.map((paper) => paper.width)
  );
  const maxHeight = calcSum(papers.map((paper) => paper.height));

  canvas.width = maxWidth * rate;
  canvas.height = maxHeight * rate;

  let preHeight = 0;
  for (let index = 0; index < papers.length; index++) {
    const paper = papers[index];
    const dres = await drawPaper(ctx, paper, rate, preHeight).catch(() => {});
    if (!dres) {
      return Promise.reject("图片绘制错误");
    }

    preHeight += paper.height;
  }

  return canvas;
}

export async function downloadPaper(papers, filename) {
  const canvas = await buildCanvas(papers, 1).catch(() => {});
  if (!canvas) {
    return Promise.reject("生成图片异常");
  }

  return new Promise((resolve, reject) => {
    try {
      canvas.toBlob((blob) => {
        downloadByBlob(blob, filename);
        resolve(true);
      });
    } catch (error) {
      reject(error);
    }
  });
}
