export function createWaterMark(file,watermarks,option = {fontSize: 100,fillStyle: 'rgba(255, 0, 0, 0.5)'}) {

  const {fontSize,fillStyle} = option
  return new Promise(((resolve, reject) => {

    const reader = new FileReader();
    reader.onload = function (event) {
        const img = new Image();
        img.onload = function () {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');

            // 设置canvas尺寸与图片一致
            canvas.width = img.width;
            canvas.height = img.height;

            // 绘制图片到canvas
            ctx.drawImage(img, 0, 0, img.width, img.height);

            //水印大小和颜色
            ctx.font = fontSize + 'px Arial';
            ctx.fillStyle = fillStyle;

            //水印起始位置，默认左下角
            let x = 35
            let y = 40
            // 添加水印
            for (let i = 0; i < watermarks.length; i++) {
                y = watermarkHandle(ctx, watermarks[i], canvas.width, canvas.height, fontSize, x, y)
            }
            // 将带有水印的canvas转换为Blob对象
            canvas.toBlob((blob) => {
                if (blob) {

                  let blobToFile = new File([blob], file.name, {  
                    type: file.type,  
                    lastModified: Date.now()  
                  }); 
                    
                    resolve(blobToFile);
                } else {
                    reject(new Error('Failed to create blob from canvas'));
                }
            }, 'image/png');
        };
        img.src = event.target.result;
    };
    reader.readAsDataURL(file);
}));
}

 /**
     * 写入水印，默认左下角 水印过长，换行 (x,y)=(0,0) 就是左下角的位置
     *  @param {canvas画布对象} ctx
     *  @param {单个水印} watermark
     *  @param {图片的长宽} height
     *  @param {图片的长宽} width
     *  @param {水印字体大小} fontSize
     *  @param {水印位置，默认左下角} x
     *  @param {水印位置，默认左下角} y
     */
export function  watermarkHandle(ctx, watermark, width, height, fontSize, x, y) {
  //添加水印
  let lineHeight = fontSize + 15
  let line = '';
  const list = [];
  for (let i = 0; i < watermark.length; i++) {
      const testLine = line + watermark[i];
      const metrics = ctx.measureText(testLine);
      const testWidth = metrics.width;
      if (testWidth < width - fontSize && i < watermark.length - 1) {
          line = testLine;
      } else {
          list.push(line)
          line = watermark[i];
      }
  }
  const testLine = line + list[list.length - 1];
  const metrics = ctx.measureText(testLine);
  const testWidth = metrics.width;
  if (testWidth < width - fontSize) {
      list[list.length - 1] = list[list.length - 1] + line
  } else {
      list.push(line)
  }
  for (let i = list.length - 1; i >= 0; i--) {
      ctx.fillText(list[i], x, height - y);
      y += lineHeight;
  }
  //位置
  return y;
}