Source: packages/utils/Watermark.js

import { getCaptionFileName, getFileExtension } from './util'
import IS from './is'

export function base64Img2Blob(code, w) {
  const w_ = w || window
  var parts = code.split(';base64,');
  var contentType = parts[0].split(':')[1];
  var raw = w_.atob(parts[1]);
  var rawLength = raw.length;
  var uInt8Array = new Uint8Array(rawLength);
  for (var i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }
  // console.log('base64Img2Blob ===>', contentType);
  return URL.createObjectURL(new Blob([uInt8Array], { type: contentType }));
}


// base64转文件对象
function dataURLtoBlob(dataurl, name) {
  const arr = dataurl.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = window.atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], name, {
    type: mime
  })
}

const loadImage = (url) => {
  return new Promise((resolve, reject) => {
    let img = new Image();
    img.crossOrigin = 'anonymous';
    img.onload = () => resolve(img);
    img.onerror = reject;
    img.src = url;
  })
}




export async function Watermark({
  url = '',
  textAlign = 'center',
  textBaseline = 'middle',
  font = "15px Microsoft Yahei",
  fillStyle = 'rgba(24, 22, 22, 0.3)',
  content = ['请勿外传'],
  cb = null,
  textX = 100,
  textY = 30
} = {}) {
  const suffix = getFileExtension(url) || 'png'

  const fileName = getCaptionFileName(url)  // + '.' + suffix[suffix.length-1] //'sss.jpeg'
  // console.log('Watermark file info ===>',url,fileName);
  const img = await loadImage(url)
  const canvas = document.createElement('canvas');
  const imgWidth = canvas.width = img.width;
  const imgHeight = canvas.height = img.height;
  const ctx = canvas.getContext('2d');

  ctx.drawImage(img, 0, 0);

  ctx.textAlign = textAlign;
  ctx.textBaseline = textBaseline;
  ctx.font = font;
  ctx.fillStyle = fillStyle;
  // ctx.fillText(content, img.width - textX, img.height - textY);


  // 平铺水印
  const canvasWater = document.createElement('canvas');
  const waterMarkSize = 300; // 水印大小
  canvasWater.width = waterMarkSize;
  canvasWater.height = waterMarkSize;
  const ctxWater = canvasWater.getContext('2d');
  ctxWater.textAlign = textAlign;
  ctxWater.textBaseline = textBaseline;
  ctxWater.font = font;
  ctxWater.fillStyle = fillStyle;
  ctxWater.rotate(-20 * Math.PI / 180);

  if(!IS.isNullOrUnDef(content) && !IS.isEmpty(content) &&  !IS.isEmpty(content[0] )){
    ctxWater.fillText(content[0], 30, 80);
  }
  if(!IS.isNullOrUnDef(content) && !IS.isEmpty(content) &&  !IS.isEmpty(content[1] )){
    ctxWater.fillText(content[1], 60, 110);
  }

  ctx.fillStyle = ctx.createPattern(canvasWater, 'repeat');
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  const base64 = canvas.toDataURL(`image/${suffix}`, 0.8)
  cb && cb(dataURLtoBlob(base64, fileName), base64);
  return { File: dataURLtoBlob(base64, fileName), base64, fileInfo:{name:fileName,suffix} }


  //#region
  // const img = new Image();
  // img.src = url;
  // img.crossOrigin = 'anonymous';
  // img.onload = function () {
  //   const canvas = document.createElement('canvas');
  //   const imgWidth = canvas.width = img.width;
  //   const imgHeight = canvas.height = img.height;
  //   const ctx = canvas.getContext('2d');

  //   ctx.drawImage(img, 0, 0);

  //   ctx.textAlign = textAlign;
  //   ctx.textBaseline = textBaseline;
  //   ctx.font = font;
  //   ctx.fillStyle = fillStyle;
  //   // ctx.fillText(content, img.width - textX, img.height - textY);


  //   // 平铺水印
  //   const canvasWater = document.createElement('canvas');
  //   const waterMarkSize = 200; // 水印大小
  //   canvasWater.width = waterMarkSize;
  //   canvasWater.height = waterMarkSize;
  //   const ctxWater = canvasWater.getContext('2d');
  //   ctxWater.textAlign = textAlign;
  //   ctxWater.textBaseline = textBaseline;
  //   ctxWater.font = font;
  //   ctxWater.fillStyle = fillStyle;
  //   ctxWater.rotate(-20 * Math.PI / 180);

  //   ctxWater.fillText(content[0] || '水印', 60, 80);
  //   ctxWater.fillText(content[1] || '', 10, 100);

  //   ctx.fillStyle = ctx.createPattern(canvasWater, 'repeat');
  //   ctx.fillRect(0, 0, canvas.width, canvas.height);

  //   const base64 = canvas.toDataURL('image/jpeg', 0.8)
  //   dataURLtoBlob(base64, fileName)
  //   cb && cb(dataURLtoBlob(base64, fileName),base64);
  //   // return {FileInfo:dataURLtoBlob(base64, fileName),base64}
  // }
  //#endregion
  //#region
  // const img = new Image();
  // img.src = url;
  // img.crossOrigin = 'anonymous';
  // img.onload = function () {
  //   const canvas = document.createElement('canvas');
  //   const imgWidth = canvas.width = img.width;
  //   const imgHeight = canvas.height = img.height;
  //   const ctx = canvas.getContext('2d');

  //   ctx.drawImage(img, 0, 0);

  //   ctx.textAlign = textAlign;
  //   ctx.textBaseline = textBaseline;
  //   ctx.font = font;
  //   ctx.fillStyle = fillStyle;
  //   // ctx.fillText(content, img.width - textX, img.height - textY);


  //   // 平铺水印
  //   // const height = 120;
  //   // const width = 200;
  //   // let i = 0;
  //   // let j = 0;
  //   // const waterMarkerWidth = ctx.measureText(content[0] || '水印').width;

  //   // ctx.rotate(-20 * Math.PI / 180);
  //   // for (i = 0; i <= imgWidth / (waterMarkerWidth) + 100; i++) {
  //   //   for (j = 0; j <= imgHeight / (height - 20) + 100; j++) {
  //   //     const x = i * (waterMarkerWidth + width) - 100;
  //   //     if (j === 0) {
  //   //       content.forEach((item, index) => {
  //   //         ctx.fillText(item, x, -height + (20 * index), imgWidth);
  //   //       })
  //   //       // ctx.fillText(name, x, -height, imgWidth);
  //   //       // ctx.fillText(date, x, -height + 20, imgWidth);
  //   //     }
  //   //     // ctx.fillText(name, x, j * height, imgWidth);
  //   //     // ctx.fillText(date, x, j * height + 20, imgWidth);

  //   //     content.forEach((item, index) => {
  //   //       ctx.fillText(item, x, j * height + (20 * index), imgWidth);
  //   //     })
  //   //     // for (let index = 0; index < content.length; index++) {
  //   //     //   const element = content[index];
  //   //     //   ctx.fillText(element, x, j * height + (20 * index), imgWidth);
  //   //     //   console.log('*****  ',element, x, j * height + (20 * index), imgWidth);
  //   //     // }

  //   //   }
  //   // }
  //   // const base64Url = canvas.toDataURL('image/png');
  //   // cb && cb(base64Url);





  //    // 平铺水印
  //    const canvasWater = document.createElement('canvas');
  //    const waterMarkSize = 200; // 水印大小
  //    canvasWater.width = waterMarkSize;
  //    canvasWater.height = waterMarkSize;
  //    const ctxWater = canvasWater.getContext('2d');
  //    ctxWater.textAlign = textAlign;
  //    ctxWater.textBaseline = textBaseline;
  //    ctxWater.font = font;
  //    ctxWater.fillStyle = fillStyle;
  //    ctxWater.rotate(-20 * Math.PI/180);

  //    ctxWater.fillText(content[0]||'水印', 60, 80);
  //    ctxWater.fillText(content[1]||'', 10, 100);

  //    ctx.fillStyle = ctx.createPattern(canvasWater, 'repeat');
  //    ctx.fillRect(0, 0, canvas.width, canvas.height);

  //    const base64 = canvas.toDataURL('image/jpeg', 0.8)
  //    dataURLtoBlob(base64, fileName)
  //    cb && cb(dataURLtoBlob(base64, fileName));
  // }
  //#endregion
}

/**
 * 给图片添加水印
 * @param {*} url
 * @param {Object} watermarkConfig  水印配置  { title:'8934', subtitle:'中雄机密文件禁止外传' }
 * @returns {object} {}
 */
export const adddWatermark = async (url, watermarkConfig) => {
  // const str = localStorage.getItem('pro__Login_Userinfo')
  // const userInfo = str ? JSON.parse(str) : {};
  // // console.log('@@@@@@@@@@@@@@@@@@@@@', userInfo.value);
  // let WatermarkText = '请勿外传'
  // if (userInfo.value) {
  //   const {phone,realname} = userInfo.value
  //   if(phone){
  //     WatermarkText = realname + phone&&phone.substr(7, 4)
  //   }else {
  //     WatermarkText = realname
  //   }
  // }
  // // 中雄机密文件禁止外传 + 名字 + 手机尾号,水印密度和企微差不多就可以 phone  realname
  const res = await Watermark({
    url: url,
    // content: [WatermarkText, '中雄机密文件禁止外传'],
    content: [watermarkConfig.title, watermarkConfig.subtitle],
  })
  // console.log('adddWatermark===>',res);
  return res
}

// 调用
    // __picWM({
    //   url: 'https://t7.baidu.com/it/u=963301259,1982396977&fm=193&f=GIF',
    //   content: ['请勿外传', '2023年2月9日'],
    //   cb: (File) => {
    //     console.log(File)
    //   },
    // });

// // 调用
// async function dy(){
//   const dddd = await Watermark_({
//     url: 'https://t7.baidu.com/it/u=963301259,1982396977&fm=193&f=GIF',
//     content: ['请勿外传', '2023年2月9日'],
//     // cb: (file, base64Url) => {
//     //   // console.log(base64Url);
//     //   // document.querySelector('img').src = URL.createObjectURL(base64Img2Blob(base64Url))
//     //   document.querySelector('img').src = base64Url
//     // },
//   });
//   console.log('$$$$$$$$$$$$$', dddd.base64);
//   document.querySelector('img').src = dddd.base64
// }
// dy()