import React__default, { useState, useRef, useMemo, useEffect } from 'react';
import moment from 'moment';
import { BaseStore, Service } from '@zenview/micro-basic-library';
import { cache } from '@zenview/micro-utils';
import { a as _applyDecoratedDescriptor, b as _initializerDefineProperty } from './_rollupPluginBabelHelpers-736b301a.js';
import { a as action, m as makeObservable, o as observable } from './mobx.esm-dee4cf9f.js';
import { observer, useLocalStore } from 'mobx-react';

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;
};

const getHeaders = () => {
  return {
    Authorization: cache.getCache('token', 'session')
  };
};
class waterMarkService {
  /**
   * @desc 查询水印
   * @param {*} id
   */
  getWaterMark(data) {
    return Service.$http({
      headers: getHeaders(),
      url: '/api/user/v2/watermark/rule/query/' + data.operationId + '/1',
      method: 'get',
      requestId: 'getWaterMark'
    });
  }
}
var waterMarkService$1 = new waterMarkService();

var _class, _descriptor;
let loadedWaterMake = false;
let WaterMakeDomStore = (_class = class WaterMakeDomStore {
  constructor() {
    _initializerDefineProperty(this, "state", _descriptor, this);
    makeObservable(this);
  }
  async loadState(refresh) {
    if (loadedWaterMake && !refresh) return;
    loadedWaterMake = true;
    try {
      const res = await waterMarkService$1.getWaterMark({
        operationId: BaseStore.app.appInfo.id
      });
      const rules = res.data.watermarkRulesList;
      const isCompulsory = res.data.isCompulsory;
      this.state.rules = rules;
      this.state.isCompulsory = isCompulsory;
      return Promise.resolve({
        rules,
        isCompulsory
      });
    } catch (error) {
      return Promise.reject(error);
    }
  }
}, _descriptor = _applyDecoratedDescriptor(_class.prototype, "state", [observable], {
  configurable: true,
  enumerable: true,
  writable: true,
  initializer: function () {
    return {
      rules: [],
      isCompulsory: 1
    };
  }
}), _applyDecoratedDescriptor(_class.prototype, "loadState", [action], Object.getOwnPropertyDescriptor(_class.prototype, "loadState"), _class.prototype), _class);
var waterMakeDomStore = new WaterMakeDomStore();

const WaterMakeDom = props => {
  const {
    className = '',
    waterMakeRule,
    waterSwitch,
    imgType
  } = props;
  const [currentRule, setCurrentRule] = useState();
  const [currentSwitch, setCurrentswitch] = useState();
  const playerRef = useRef(null);
  const store = useLocalStore(() => waterMakeDomStore);
  const markerPath = useMemo(() => {
    var _currentRule$showLeve, _currentRule$transpar;
    if (!currentRule) return '';
    const contents = getWaterMarkContent(currentRule);
    if (!contents.length) return '';
    const canvas = createNewImage({
      contents,
      fontSize: Math.min(30, Math.max(10, currentRule.fontSize || 0)),
      density: (_currentRule$showLeve = currentRule.showLevel) !== null && _currentRule$showLeve !== void 0 ? _currentRule$showLeve : 1,
      opacity: (_currentRule$transpar = currentRule === null || currentRule === void 0 ? void 0 : currentRule.transparency) !== null && _currentRule$transpar !== void 0 ? _currentRule$transpar : 100
    });
    return canvas.toDataURL('image/png');
  }, [currentRule]);
  useEffect(() => {
    if (!waterMakeRule && imgType) {
      store.loadState();
    }
  }, [waterMakeRule, imgType]);
  useEffect(() => {
    if (!waterMakeRule && imgType) {
      setCurrentRule(store.state.rules.find(o => o.imgType === imgType));
      setCurrentswitch(store.state.isCompulsory);
    } else {
      setCurrentRule(waterMakeRule);
      setCurrentswitch(waterSwitch);
    }
  }, [store.state.rules, store.state.isCompulsory, waterMakeRule, imgType, waterSwitch]);
  return /*#__PURE__*/React__default.createElement("div", {
    className: "player-marke" ,
    ref: playerRef,
    style: {
      position: 'absolute',
      left: 0,
      top: 0,
      width: '100%',
      height: '100%',
      zIndex: 1,
      background: currentRule && currentSwitch && getWaterMarkUseState(currentRule, currentSwitch) ? `url(${markerPath})` : "transparent"
      // backgroundSize: "100% 100%"
    }
  });
};
WaterMakeDom.store = waterMakeDomStore;
WaterMakeDom.utils = {
  createNewImage,
  getWaterMarkContent,
  getWaterMarkUseState
};
var WaterMakeDom$1 = observer(WaterMakeDom);

export { WaterMakeDom$1 as W };
//# sourceMappingURL=waterMakeDom-7959ac3b.js.map
