var _excluded = ["tagList", "maxLength", "simple", "className", "value", "defaultValue", "onChange", "hooks", "componentBelowControlBar", "extendControls"],
  _excluded2 = ["before-preview"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
/**
 * 富文本编辑器
 * @author 施阳  2020-10-15
 * 具体api参考  https://braft.margox.cn/
 */
import React, { useState, useMemo, useContext, useRef } from 'react';
import BraftEditor from 'braft-editor';
import { ContentUtils } from 'braft-utils';
import { message, Tag, Modal } from 'antd';
import 'braft-editor/dist/index.css';
import { useDebounceFn, useUpdateEffect } from 'ahooks';
import { ConfigContext } from "../config-provider/context";
import { replaceMessage } from "../locale/utils";
import { useConfig } from "../_util/hooks";
import ImageUploader from "./ImageUploader"; // 自定义图片上传组件
import MediaUploader from "./MediaUploader"; // 自定义音视频上传组件
import Upload from "../upload"; // 大附件直传组件
import Preview from "./Preview"; // 富文本预览组件
import "./pluginExtends"; // 富文本插件扩展
import { formatValue } from "./utils";
import "./index.less";
message.config({
  duration: 2,
  maxCount: 1 // 最多显示个数
});

var CONTROLS = ['font-size', 'text-align', 'text-color', 'bold', 'italic', 'underline', 'link', 'code', 'media']; // 编辑器工具栏

// 可选字段组件
var Keywords = function Keywords(props) {
  return /*#__PURE__*/React.createElement("div", {
    className: "u-keyWords"
  }, /*#__PURE__*/React.createElement("span", null, props.locales.BraftEditor.optional), (props.tagList || []).map(function (item) {
    return /*#__PURE__*/React.createElement(Tag, {
      onClick: function onClick() {
        return props.onClick(item.htmlValue);
      },
      key: item.fieldName
    }, item.fieldName);
  }));
};
var Editor = function Editor(props) {
  var uploadInstance = useRef({});
  var _useContext = useContext(ConfigContext),
    uiLocale = _useContext.uiLocale;
  var tagList = props.tagList,
    _props$maxLength = props.maxLength,
    maxLength = _props$maxLength === void 0 ? 5000 : _props$maxLength,
    simple = props.simple,
    _props$className = props.className,
    className = _props$className === void 0 ? '' : _props$className,
    value = props.value,
    defaultValue = props.defaultValue,
    _props$onChange = props.onChange,
    onChange = _props$onChange === void 0 ? function () {
      return null;
    } : _props$onChange,
    hooks = props.hooks,
    componentBelowControlBar = props.componentBelowControlBar,
    extendControls = props.extendControls,
    rest = _objectWithoutProperties(props, _excluded);
  var _ref = hooks || {},
    beforePreview = _ref['before-preview'],
    restHooks = _objectWithoutProperties(_ref, _excluded2); // 预览时的钩子函数
  var _useDebounceFn = useDebounceFn(onChange, {
      wait: 200
    }),
    _onChange = _useDebounceFn.run;
  var _useState = useState(maxLength),
    _useState2 = _slicedToArray(_useState, 2),
    _maxLength = _useState2[0],
    setMaxLength = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    visible = _useState4[0],
    setVisible = _useState4[1]; // 预览弹框显隐

  // 设置初始值
  var initialValue = useMemo(function () {
    if ('value' in props) return BraftEditor.createEditorState(formatValue(value));
    if ('defaultValue' in props) return BraftEditor.createEditorState(formatValue(defaultValue));
    return BraftEditor.createEditorState('');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  var _useState5 = useState(initialValue),
    _useState6 = _slicedToArray(_useState5, 2),
    editorState = _useState6[0],
    setEditorState = _useState6[1];
  var _useState7 = useState(),
    _useState8 = _slicedToArray(_useState7, 2),
    html = _useState8[0],
    setHtml = _useState8[1]; // 预览内容

  useUpdateEffect(function () {
    if (value && value !== editorState.toHTML()) {
      setEditorState(BraftEditor.createEditorState(formatValue(value)));
    }
  }, [value]);

  // 上传截图时，调用大附件上传接口转成nosUrl
  var uploadFn = function uploadFn(param) {
    var nosUpload = uploadInstance.current.nosUpload;
    nosUpload === null || nosUpload === void 0 ? void 0 : nosUpload({
      file: param.file,
      onSuccess: function onSuccess(res) {
        param.success({
          url: res.url
        });
      }
    });
  };

  // 计算最大长度（可选字段不占用长度）
  var _useDebounceFn2 = useDebounceFn(function () {
      var html = editorState ? editorState.toHTML() : '',
        length = maxLength;
      tagList === null || tagList === void 0 ? void 0 : tagList.forEach(function (item) {
        var len = html.split(item.htmlValue).length; // 同个标签选择多次需要计算多个相同标签的长度
        len > 1 && (length += item.fieldName.length * (len - 1));
      });
      setMaxLength(length);
    }, {
      wait: 0
    }),
    calcMaxLength = _useDebounceFn2.run;

  // 触发编辑器
  var handleChange = function handleChange(editorState) {
    calcMaxLength();
    setEditorState(editorState);
    _onChange(editorState.isEmpty() ? '' : editorState.toHTML(), editorState);
  };

  // 选择可选字段
  var onChoseTags = function onChoseTags(htmlString) {
    var value = ContentUtils.insertHTML(editorState, htmlString);
    calcMaxLength();
    setEditorState(value);
    _onChange(value.isEmpty() ? '' : value.toHTML(), editorState);
  };

  // 字数达到上限的回调
  var onReachMaxLength = function onReachMaxLength() {
    message.warning(replaceMessage(uiLocale.BraftEditor.maxLengthWarning, {
      maxLength: maxLength
    }));
  };

  // 自定义扩展组件
  var imageUploader = {
      key: 'antd-uploader-image',
      type: 'component',
      component: /*#__PURE__*/React.createElement(ImageUploader, {
        setEditorState: setEditorState,
        editorState: editorState
      })
    },
    mediaUploader = {
      key: 'antd-uploader-media',
      type: 'component',
      component: /*#__PURE__*/React.createElement(MediaUploader, {
        setEditorState: setEditorState,
        editorState: editorState
      })
    },
    preview = {
      className: 'edit-preview',
      key: 'custom-button',
      type: 'button',
      text: uiLocale.global.preview,
      onClick: function onClick() {
        setHtml(beforePreview ? beforePreview(editorState) : editorState === null || editorState === void 0 ? void 0 : editorState.toHTML());
        setVisible(true);
      }
    };

  // 自定义工具
  var getExtendControls = function getExtendControls() {
    // 不显示扩展组件
    if (extendControls && !extendControls.length) {
      return [];
    }
    return [imageUploader, mediaUploader, preview].concat(_toConsumableArray(extendControls || []));
  };

  // 自定义工具栏footer
  var renderFooter = function renderFooter() {
    if (componentBelowControlBar && typeof componentBelowControlBar === 'function') {
      return componentBelowControlBar({
        onChoseTags: onChoseTags
      });
    }
    if (componentBelowControlBar) {
      return componentBelowControlBar;
    }
    if (tagList) {
      return /*#__PURE__*/React.createElement(Keywords, {
        locales: uiLocale,
        onClick: onChoseTags,
        tagList: tagList
      });
    }
    return null;
  };
  return useConfig( /*#__PURE__*/React.createElement("div", {
    className: "m-braftEditor ".concat(className)
  }, /*#__PURE__*/React.createElement(BraftEditor, _extends({
    hooks: restHooks,
    componentBelowControlBar: renderFooter(),
    onReachMaxLength: onReachMaxLength,
    controls: simple ? CONTROLS : undefined,
    extendControls: getExtendControls()
  }, rest, {
    // @ts-ignore
    language: uiLocale.locale,
    maxLength: _maxLength,
    value: editorState,
    onChange: handleChange,
    media: {
      uploadFn: uploadFn
    }
  })), /*#__PURE__*/React.createElement(Modal, {
    title: uiLocale.global.preview,
    width: 1000,
    open: visible,
    onCancel: function onCancel() {
      return setVisible(false);
    },
    footer: false
  }, /*#__PURE__*/React.createElement(Preview, {
    html: html
  })), /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'none'
    }
  }, /*#__PURE__*/React.createElement(Upload, {
    getInstance: function getInstance(params) {
      uploadInstance.current = params;
    }
  }))));
};
Editor.Preview = Preview;
Editor.createEditorState = BraftEditor.createEditorState;
Editor.ContentUtils = ContentUtils;
export default Editor;