
import moment from 'moment';
import { BaseStore } from '@zenview/micro-basic-library';
import { cache } from '@zenview/micro-utils';

function createNewImage ({ fontSize = 14, contents = [], rotate = 30, opacity = 100, density = 3 }) {
  density = 3
  const WatermarkDensity = [
    { xOffset: 80, yOffset: 9 },
    { xOffset: 50, yOffset: 7 },
    { xOffset: 30, yOffset: 5 },
  ];
  const angle = (rotate * Math.PI) / 180
  let maxHeight = contents.length * (fontSize + 4) + WatermarkDensity[density - 1].yOffset
  let maxWidth = [...contents].sort((a, b) => b.length - a.length)[0].length * fontSize + WatermarkDensity[density - 1].xOffset
  const width = maxWidth * Math.cos(angle) + maxHeight * Math.sin(angle)
  const height = maxWidth * Math.sin(angle) + maxHeight * Math.cos(angle)
  let canvas = document.createElement('canvas');
  let ctx = canvas.getContext('2d');
  canvas.setAttribute('width', width);
  canvas.setAttribute('height', height);
  ctx.translate(width / 2, 0);
  ctx.rotate(angle);
  ctx.translate(maxHeight * Math.sin(angle) / 2, (height - maxHeight) / 2);
  contents.forEach((text, index) => {
    ctx.font = `300 ${fontSize}px 微软雅黑,黑体`;
    ctx.textAlign = 'center';
    ctx.shadowColor = 'rgba(0, 0, 0, 0.4)';
    ctx.shadowBlur = 4;
    ctx.shadowOffsetX = 2;
    ctx.shadowOffsetY = 2;
    ctx.fillStyle = `rgba(255,255,255, ${opacity / 100})`;
    ctx.textBaseline = 'bottom';
    ctx.fillText(text, 0, (fontSize + 4) * (index + 1));
  });
  return canvas;
}

// 获取水印内容
const getWaterMarkContent = (waterMakeRule) => {
  let ip = cache.getCache('ClientIP', 'session') || '';
  let user = BaseStore.app.userInfo;
  let systemTime = moment(new Date()).format('YYYYMMDDTHHmmss');
  const waterMark = []
  if (waterMakeRule.waterType === 1) {
    waterMakeRule.realName === 2 && waterMark.push(user.realName)
    waterMakeRule.ip === 2 && waterMark.push(ip)
    waterMakeRule.phoneNum === 2 && waterMark.push(user.phoneNum)
    waterMakeRule.sysDate === 2 && waterMark.push(systemTime)
  } else {
    waterMakeRule.waterContent && waterMark.push(waterMakeRule.waterContent);
  }
  return waterMark
}

// 获取水印启用状态
const getWaterMarkUseState = (waterMakeRule, watetswitch) => {
  return watetswitch === 1 ? (waterMakeRule.isUsed === 2 ? true : false) : watetswitch === 2 ? true : false
}
export { createNewImage, getWaterMarkContent, getWaterMarkUseState };
