"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/web.dom-collections.iterator.js");
var _react = require("react");
var _watermarkjs = _interopRequireDefault(require("@wii/watermarkjs"));
var _lodash = require("lodash");
var _wauConfigProvider = require("../wau-config-provider");
var _form = _interopRequireDefault(require("../form"));
var _input = _interopRequireDefault(require("../input"));
var _select = _interopRequireDefault(require("../select"));
var _slider = _interopRequireDefault(require("../slider"));
var _position = _interopRequireDefault(require("./position"));
var _colorBox = _interopRequireDefault(require("./color-box"));
var _inputNumber = _interopRequireDefault(require("../input-number"));
var _radio = _interopRequireDefault(require("../radio"));
var _utils = require("./utils");
require("./style");
var _constants = require("./constants");
var _preview = _interopRequireDefault(require("./preview"));
var _logoUpload = _interopRequireDefault(require("./logo-upload"));
var _jsxRuntime = require("react/jsx-runtime");
// 常量默认值

const labelCol = {
  style: {
    width: '90px',
    textAlign: 'right'
  }
};
const WauWaterMark = ({
  baseImg,
  textMaxLength = 10,
  extra,
  onChange,
  form: formFromProps,
  ...props
}) => {
  const [previewImg, setPreviewImg] = (0, _react.useState)(baseImg);
  const [form] = _form.default.useForm(formFromProps);
  const [defaultImgSize, setDefaultImgSize] = (0, _react.useState)({
    width: 0,
    height: 0
  });

  // class 前缀
  const {
    getPrefixCls
  } = (0, _react.useContext)(_wauConfigProvider.ConfigContext);

  // 初始化先获取底图尺寸
  (0, _react.useEffect)(() => {
    setPreviewImg(baseImg);
    const IMG = new Image();
    IMG.src = baseImg;
    IMG.onload = function () {
      setDefaultImgSize({
        width: IMG.naturalWidth,
        height: IMG.naturalHeight
      });
    };
  }, [baseImg]);
  const handleValuesChange = (0, _react.useCallback)((_, allValues) => {
    const {
      text,
      logoImg,
      markType = _constants.DEFAULT_OPTIONS.markType,
      textFontSize = _constants.DEFAULT_OPTIONS.textFontSize,
      textFontColor = _constants.DEFAULT_OPTIONS.textFontColor,
      dissolve = _constants.DEFAULT_OPTIONS.dissolve,
      gravity = _constants.DEFAULT_OPTIONS.gravity,
      textDegree = _constants.DEFAULT_OPTIONS.textDegree,
      batch = _constants.DEFAULT_OPTIONS.batch,
      spcent = _constants.DEFAULT_OPTIONS.spcent
    } = allValues;
    const position = _constants.GRAVITY_POSITION_MAP[gravity];
    if (markType === 'TEXT' && text !== null && text !== void 0 && text.trim()) {
      if (batch === 1) {
        // 创建一个元素为了onload
        const textCanvas = (0, _utils.createTextCanvas)(text, textFontSize, textDegree, dissolve, textFontColor, 'serif');
        (0, _watermarkjs.default)([baseImg], _constants.waterMarkOptions).image(function (target) {
          const context = target.getContext('2d');
          context.save();
          const pat = context.createPattern(textCanvas, 'repeat');
          context.fillStyle = pat;
          context.fillRect(0, 0, defaultImgSize.width, defaultImgSize.height);
          context.restore(); // put the context back where you found it
          return target;
        }).render().then(img => {
          setPreviewImg(img[0].src);
        });
      } else {
        // 单文字效果
        const watermarkText = _watermarkjs.default.text;
        const params = [text, `${textFontSize}px serif`, textFontColor, dissolve, textFontSize, 0];
        const location = watermarkText[position];
        (0, _watermarkjs.default)([baseImg], _constants.waterMarkOptions).image(location(...params)).render().then(img => {
          setPreviewImg(img[0].src);
        });
      }
    } else if (markType === 'IMG') {
      // 如果是本地上传的文件
      if (logoImg !== null && logoImg !== void 0 && logoImg.originFileObj) {
        const reader = new FileReader();
        reader.readAsDataURL(logoImg.originFileObj);
        reader.onload = item => {
          const image = new Image();
          image.src = item.target.result;
          image.onload = function () {
            const smBase64 = (0, _utils.getBase64)(image, defaultImgSize, spcent);
            // 只传入透明度 100 不透明
            const params = [100, _constants.padding];
            const watermarkImage = _watermarkjs.default.image;
            const location = watermarkImage[position];
            (0, _watermarkjs.default)([baseImg, smBase64], _constants.waterMarkOptions).image(location(...params)).then(img => {
              setPreviewImg(img === null || img === void 0 ? void 0 : img.src);
            });
          };
        };
      } else if (logoImg !== null && logoImg !== void 0 && logoImg.url) {
        // 只传入透明度 100 不透明
        const params = [100, _constants.padding];
        const watermarkImage = _watermarkjs.default.image;
        const location = watermarkImage[position];
        (0, _watermarkjs.default)([baseImg, logoImg.url], _constants.waterMarkOptions).image(location(...params)).then(img => {
          setPreviewImg(img === null || img === void 0 ? void 0 : img.src);
        });
      } else {
        setPreviewImg(baseImg);
      }
    }
  }, [baseImg, defaultImgSize]);
  (0, _react.useEffect)(() => {
    handleValuesChange({}, form.getFieldsValue());
  }, [handleValuesChange, form]);
  const debouncedHandleValuesChange = (0, _react.useMemo)(() => (0, _lodash.debounce)((changedValues, allValues) => {
    handleValuesChange(changedValues, allValues);
    onChange === null || onChange === void 0 ? void 0 : onChange(allValues);
  }, 300), [handleValuesChange, onChange]);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: `${getPrefixCls()}-water-mark`,
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_preview.default, {
      image: previewImg
    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: `${getPrefixCls()}-mark-setting-form`,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: `${getPrefixCls()}-mark-config`,
        children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_form.default, {
          form: form,
          initialValues: {
            ..._constants.DEFAULT_OPTIONS,
            ...props,
            logoImg: typeof props.logoImg === 'string' ? {
              uid: Date.now(),
              name: props.logoImg,
              url: props.logoImg
            } : props.logoImg
          },
          onValuesChange: debouncedHandleValuesChange,
          labelCol: labelCol,
          colon: false,
          children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
            label: "\u6C34\u5370\u7C7B\u578B",
            name: "markType",
            children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_radio.default.Group, {
              options: _constants.waterMarkTypes
            })
          }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
            noStyle: true,
            dependencies: ['markType'],
            children: ({
              getFieldValue
            }) => {
              const markType = getFieldValue('markType');
              return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
                children: [markType === 'TEXT' ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                  name: "text",
                  label: "\u6587\u672C",
                  extra: /*#__PURE__*/(0, _jsxRuntime.jsxs)("span", {
                    children: ["\u6700\u5927\u5B57\u6570\u4E3A", textMaxLength, "\u4E2A\u5B57\u7B26"]
                  }),
                  rules: [{
                    max: textMaxLength
                  }, {
                    required: true,
                    message: '请输入水印文本'
                  }],
                  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_input.default, {
                    placeholder: "\u8F93\u5165\u6587\u672C",
                    maxLength: textMaxLength
                  })
                }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                  label: "\u6C34\u5370\u56FE\u7247",
                  name: "logoImg",
                  extra: /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
                    children: "\u652F\u6301jpg\u3001jpeg\u3001png\u683C\u5F0F\uFF0C\u5EFA\u8BAE\u5927\u5C0F\u4E0D\u8D85\u8FC710M"
                  }),
                  normalize: ({
                    fileList
                  }) => {
                    return fileList[0];
                  },
                  getValueProps: file => ({
                    fileList: file ? [file] : []
                  }),
                  valuePropName: "fileList",
                  rules: [{
                    required: true,
                    message: '请上传水印图片'
                  }],
                  children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_logoUpload.default, {})
                }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                  noStyle: true,
                  dependencies: ['batch'],
                  children: ({
                    getFieldValue
                  }) => /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                    label: markType === 'TEXT' ? '文本位置' : '图片位置',
                    name: "gravity",
                    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_position.default, {
                      disabled: markType === 'TEXT' && getFieldValue('batch') === 1
                    })
                  })
                }), markType === 'TEXT' ? /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
                  children: [/*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                    className: `${getPrefixCls()}-config-row`,
                    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                      className: `${getPrefixCls()}-opacity-from`,
                      label: "\u900F\u660E\u5EA6",
                      name: "dissolve",
                      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_select.default, {
                        options: _constants.opacityOptionsElement
                      })
                    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                      className: `${getPrefixCls()}-color-from`,
                      label: "\u6587\u672C\u989C\u8272",
                      name: "textFontColor",
                      labelCol: {
                        style: {
                          width: '130px',
                          textAlign: 'right'
                        }
                      },
                      labelAlign: "right",
                      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_colorBox.default, {})
                    })]
                  }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                    style: {
                      display: 'flex',
                      justifyContent: 'space-between'
                    },
                    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                      name: "textFontSize",
                      className: `${getPrefixCls()}-font-form`,
                      label: "\u5B57\u4F53\u5927\u5C0F",
                      style: {
                        width: 'calc(100% - 120px)'
                      },
                      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_slider.default, {
                        min: _constants.defaultFontSizeMin,
                        max: _constants.defaultFontSizeMax
                      })
                    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                      name: "textFontSize",
                      className: `${getPrefixCls()}-font-input-form`,
                      label: "",
                      style: {
                        width: '82px'
                      },
                      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_inputNumber.default, {
                        min: _constants.defaultFontSizeMin,
                        max: _constants.defaultFontSizeMax
                      })
                    })]
                  }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                    className: `${getPrefixCls()}-config-row`,
                    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                      name: "batch",
                      className: `${getPrefixCls()}-font-batch-from`,
                      label: "\u6C34\u5370\u65B9\u5F0F",
                      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_select.default, {
                        options: _constants.batchOptionsElement
                      })
                    }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                      noStyle: true,
                      dependencies: ['batch'],
                      children: ({
                        getFieldValue
                      }) => {
                        const batch = getFieldValue('batch');
                        return batch === 1 ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                          className: `${getPrefixCls()}-degree-from`,
                          label: "\u65CB\u8F6C\u89D2\u5EA6",
                          name: "textDegree",
                          labelCol: {
                            style: {
                              width: '130px',
                              textAlign: 'right'
                            }
                          },
                          children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_select.default, {
                            options: _constants.degreeOptionsElement
                          })
                        }) : null;
                      }
                    })]
                  })]
                }) : null, markType === 'IMG' ? /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                  style: {
                    display: 'flex',
                    justifyContent: 'space-between'
                  },
                  children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                    name: "spcent",
                    className: `${getPrefixCls()}-spcent-form`,
                    style: {
                      width: 'calc(100% - 120px)'
                    },
                    label: "\u9762\u79EF\u5360\u6BD4",
                    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_slider.default, {
                      min: _constants.defaultSpcentMin,
                      max: _constants.defaultSpcentMax
                    })
                  }), /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
                    style: {
                      display: 'flex',
                      justifyContent: 'end'
                    },
                    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
                      name: "spcent",
                      className: `${getPrefixCls()}-spcent-input-form`,
                      label: "",
                      style: {
                        width: '82px'
                      },
                      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_inputNumber.default, {
                        min: _constants.defaultSpcentMin,
                        max: _constants.defaultSpcentMax
                      })
                    }), /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
                      className: `${getPrefixCls()}-spcent-unit`,
                      children: "\u2030"
                    })]
                  })]
                }) : null]
              });
            }
          }), extra]
        })
      })
    })]
  });
};
WauWaterMark.displayName = 'WauWaterMark';
var _default = WauWaterMark;
exports.default = _default;