import "core-js/modules/es.array.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import { useState, useEffect, useContext, useCallback, useMemo } from 'react';
import Watermark from '@wii/watermarkjs';
import { debounce } from 'lodash';
import { ConfigContext } from '../wau-config-provider';
import Form from '../form';
import Input from '../input';
import Select from '../select';
import Slider from '../slider';
import DotPosition from './position';
import ColorBox from './color-box';
import InputNumber from '../input-number';
import Radio from '../radio';
import { getBase64, createTextCanvas } from './utils';
import './style';
// 常量默认值
import { waterMarkTypes, defaultFontSizeMin, defaultFontSizeMax, defaultSpcentMin, defaultSpcentMax, padding, batchOptionsElement, opacityOptionsElement, degreeOptionsElement, waterMarkOptions, DEFAULT_OPTIONS, GRAVITY_POSITION_MAP } from './constants';
import ImgPreview from './preview';
import LogoUpload from './logo-upload';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
const labelCol = {
  style: {
    width: '90px',
    textAlign: 'right'
  }
};
const WauWaterMark = ({
  baseImg,
  textMaxLength = 10,
  extra,
  onChange,
  form: formFromProps,
  ...props
}) => {
  const [previewImg, setPreviewImg] = useState(baseImg);
  const [form] = Form.useForm(formFromProps);
  const [defaultImgSize, setDefaultImgSize] = useState({
    width: 0,
    height: 0
  });

  // class 前缀
  const {
    getPrefixCls
  } = useContext(ConfigContext);

  // 初始化先获取底图尺寸
  useEffect(() => {
    setPreviewImg(baseImg);
    const IMG = new Image();
    IMG.src = baseImg;
    IMG.onload = function () {
      setDefaultImgSize({
        width: IMG.naturalWidth,
        height: IMG.naturalHeight
      });
    };
  }, [baseImg]);
  const handleValuesChange = useCallback((_, allValues) => {
    const {
      text,
      logoImg,
      markType = DEFAULT_OPTIONS.markType,
      textFontSize = DEFAULT_OPTIONS.textFontSize,
      textFontColor = DEFAULT_OPTIONS.textFontColor,
      dissolve = DEFAULT_OPTIONS.dissolve,
      gravity = DEFAULT_OPTIONS.gravity,
      textDegree = DEFAULT_OPTIONS.textDegree,
      batch = DEFAULT_OPTIONS.batch,
      spcent = DEFAULT_OPTIONS.spcent
    } = allValues;
    const position = GRAVITY_POSITION_MAP[gravity];
    if (markType === 'TEXT' && text !== null && text !== void 0 && text.trim()) {
      if (batch === 1) {
        // 创建一个元素为了onload
        const textCanvas = createTextCanvas(text, textFontSize, textDegree, dissolve, textFontColor, 'serif');
        Watermark([baseImg], 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 = Watermark.text;
        const params = [text, `${textFontSize}px serif`, textFontColor, dissolve, textFontSize, 0];
        const location = watermarkText[position];
        Watermark([baseImg], 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 = getBase64(image, defaultImgSize, spcent);
            // 只传入透明度 100 不透明
            const params = [100, padding];
            const watermarkImage = Watermark.image;
            const location = watermarkImage[position];
            Watermark([baseImg, smBase64], 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, padding];
        const watermarkImage = Watermark.image;
        const location = watermarkImage[position];
        Watermark([baseImg, logoImg.url], waterMarkOptions).image(location(...params)).then(img => {
          setPreviewImg(img === null || img === void 0 ? void 0 : img.src);
        });
      } else {
        setPreviewImg(baseImg);
      }
    }
  }, [baseImg, defaultImgSize]);
  useEffect(() => {
    handleValuesChange({}, form.getFieldsValue());
  }, [handleValuesChange, form]);
  const debouncedHandleValuesChange = useMemo(() => debounce((changedValues, allValues) => {
    handleValuesChange(changedValues, allValues);
    onChange === null || onChange === void 0 ? void 0 : onChange(allValues);
  }, 300), [handleValuesChange, onChange]);
  return /*#__PURE__*/_jsxs("div", {
    className: `${getPrefixCls()}-water-mark`,
    children: [/*#__PURE__*/_jsx(ImgPreview, {
      image: previewImg
    }), /*#__PURE__*/_jsx("div", {
      className: `${getPrefixCls()}-mark-setting-form`,
      children: /*#__PURE__*/_jsx("div", {
        className: `${getPrefixCls()}-mark-config`,
        children: /*#__PURE__*/_jsxs(Form, {
          form: form,
          initialValues: {
            ...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__*/_jsx(Form.Item, {
            label: "\u6C34\u5370\u7C7B\u578B",
            name: "markType",
            children: /*#__PURE__*/_jsx(Radio.Group, {
              options: waterMarkTypes
            })
          }), /*#__PURE__*/_jsx(Form.Item, {
            noStyle: true,
            dependencies: ['markType'],
            children: ({
              getFieldValue
            }) => {
              const markType = getFieldValue('markType');
              return /*#__PURE__*/_jsxs(_Fragment, {
                children: [markType === 'TEXT' ? /*#__PURE__*/_jsx(Form.Item, {
                  name: "text",
                  label: "\u6587\u672C",
                  extra: /*#__PURE__*/_jsxs("span", {
                    children: ["\u6700\u5927\u5B57\u6570\u4E3A", textMaxLength, "\u4E2A\u5B57\u7B26"]
                  }),
                  rules: [{
                    max: textMaxLength
                  }, {
                    required: true,
                    message: '请输入水印文本'
                  }],
                  children: /*#__PURE__*/_jsx(Input, {
                    placeholder: "\u8F93\u5165\u6587\u672C",
                    maxLength: textMaxLength
                  })
                }) : /*#__PURE__*/_jsx(Form.Item, {
                  label: "\u6C34\u5370\u56FE\u7247",
                  name: "logoImg",
                  extra: /*#__PURE__*/_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__*/_jsx(LogoUpload, {})
                }), /*#__PURE__*/_jsx(Form.Item, {
                  noStyle: true,
                  dependencies: ['batch'],
                  children: ({
                    getFieldValue
                  }) => /*#__PURE__*/_jsx(Form.Item, {
                    label: markType === 'TEXT' ? '文本位置' : '图片位置',
                    name: "gravity",
                    children: /*#__PURE__*/_jsx(DotPosition, {
                      disabled: markType === 'TEXT' && getFieldValue('batch') === 1
                    })
                  })
                }), markType === 'TEXT' ? /*#__PURE__*/_jsxs(_Fragment, {
                  children: [/*#__PURE__*/_jsxs("div", {
                    className: `${getPrefixCls()}-config-row`,
                    children: [/*#__PURE__*/_jsx(Form.Item, {
                      className: `${getPrefixCls()}-opacity-from`,
                      label: "\u900F\u660E\u5EA6",
                      name: "dissolve",
                      children: /*#__PURE__*/_jsx(Select, {
                        options: opacityOptionsElement
                      })
                    }), /*#__PURE__*/_jsx(Form.Item, {
                      className: `${getPrefixCls()}-color-from`,
                      label: "\u6587\u672C\u989C\u8272",
                      name: "textFontColor",
                      labelCol: {
                        style: {
                          width: '130px',
                          textAlign: 'right'
                        }
                      },
                      labelAlign: "right",
                      children: /*#__PURE__*/_jsx(ColorBox, {})
                    })]
                  }), /*#__PURE__*/_jsxs("div", {
                    style: {
                      display: 'flex',
                      justifyContent: 'space-between'
                    },
                    children: [/*#__PURE__*/_jsx(Form.Item, {
                      name: "textFontSize",
                      className: `${getPrefixCls()}-font-form`,
                      label: "\u5B57\u4F53\u5927\u5C0F",
                      style: {
                        width: 'calc(100% - 120px)'
                      },
                      children: /*#__PURE__*/_jsx(Slider, {
                        min: defaultFontSizeMin,
                        max: defaultFontSizeMax
                      })
                    }), /*#__PURE__*/_jsx(Form.Item, {
                      name: "textFontSize",
                      className: `${getPrefixCls()}-font-input-form`,
                      label: "",
                      style: {
                        width: '82px'
                      },
                      children: /*#__PURE__*/_jsx(InputNumber, {
                        min: defaultFontSizeMin,
                        max: defaultFontSizeMax
                      })
                    })]
                  }), /*#__PURE__*/_jsxs("div", {
                    className: `${getPrefixCls()}-config-row`,
                    children: [/*#__PURE__*/_jsx(Form.Item, {
                      name: "batch",
                      className: `${getPrefixCls()}-font-batch-from`,
                      label: "\u6C34\u5370\u65B9\u5F0F",
                      children: /*#__PURE__*/_jsx(Select, {
                        options: batchOptionsElement
                      })
                    }), /*#__PURE__*/_jsx(Form.Item, {
                      noStyle: true,
                      dependencies: ['batch'],
                      children: ({
                        getFieldValue
                      }) => {
                        const batch = getFieldValue('batch');
                        return batch === 1 ? /*#__PURE__*/_jsx(Form.Item, {
                          className: `${getPrefixCls()}-degree-from`,
                          label: "\u65CB\u8F6C\u89D2\u5EA6",
                          name: "textDegree",
                          labelCol: {
                            style: {
                              width: '130px',
                              textAlign: 'right'
                            }
                          },
                          children: /*#__PURE__*/_jsx(Select, {
                            options: degreeOptionsElement
                          })
                        }) : null;
                      }
                    })]
                  })]
                }) : null, markType === 'IMG' ? /*#__PURE__*/_jsxs("div", {
                  style: {
                    display: 'flex',
                    justifyContent: 'space-between'
                  },
                  children: [/*#__PURE__*/_jsx(Form.Item, {
                    name: "spcent",
                    className: `${getPrefixCls()}-spcent-form`,
                    style: {
                      width: 'calc(100% - 120px)'
                    },
                    label: "\u9762\u79EF\u5360\u6BD4",
                    children: /*#__PURE__*/_jsx(Slider, {
                      min: defaultSpcentMin,
                      max: defaultSpcentMax
                    })
                  }), /*#__PURE__*/_jsxs("div", {
                    style: {
                      display: 'flex',
                      justifyContent: 'end'
                    },
                    children: [/*#__PURE__*/_jsx(Form.Item, {
                      name: "spcent",
                      className: `${getPrefixCls()}-spcent-input-form`,
                      label: "",
                      style: {
                        width: '82px'
                      },
                      children: /*#__PURE__*/_jsx(InputNumber, {
                        min: defaultSpcentMin,
                        max: defaultSpcentMax
                      })
                    }), /*#__PURE__*/_jsx("span", {
                      className: `${getPrefixCls()}-spcent-unit`,
                      children: "\u2030"
                    })]
                  })]
                }) : null]
              });
            }
          }), extra]
        })
      })
    })]
  });
};
WauWaterMark.displayName = 'WauWaterMark';
export default WauWaterMark;