var _excluded = ["tagList", "maxLength", "simple", "className", "value", "defaultValue", "onChange", "hooks"],
  _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 _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 } from 'react';
import BraftEditor from 'braft-editor';
import { ContentUtils } from 'braft-utils';
import MaxLength from 'braft-extensions/dist/max-length';
import { message, Tag, Modal, ConfigProvider } from 'antd';
import { PictureFilled } from '@ant-design/icons';
import 'braft-editor/dist/index.css';
import { useDebounceFn, useUpdateEffect } from 'ahooks';
import { ConfigContext } from "../config-provider/context";
import { replaceMessage } from "../locale/utils";
import Upload from "../upload";
import Preview from "./Preview";
import "./index.less";
message.config({
  duration: 2,
  maxCount: 1 // 最多显示个数
});

// 可选字段标签
var entityTags = {
  // 指定扩展类型
  type: 'entity',
  // 指定扩展的entity名称，推荐使用全部大写，内部也会将小写转换为大写
  name: 'KEYWORD-ITEM',
  // 在编辑器工具栏中增加一个控制按钮，点击时会将所选文字转换为该entity
  // control: {
  // 	text: '标签'
  // },
  // 指定entity的mutability属性，可选值为MUTABLE和IMMUTABLE，表明该entity是否可编辑，默认为MUTABLE
  mutability: 'IMMUTABLE',
  // 指定通过上面新增的按钮创建entity时的默认附加数据
  // data: {},
  // 指定entity在编辑器中的渲染组件
  component: function component(props) {
    return /*#__PURE__*/React.createElement("span", {
      className: "keyword-item"
    }, props.children);
  },
  // 指定html转换为editorState时，何种规则的内容将会转换成该entity
  importer: function importer(nodeName, node) {
    // source属性表明输入来源，可能值为create、paste或undefined
    // console.log(node)
    if (nodeName.toLowerCase() === 'span' && node.classList && node.classList.contains('keyword-item')) {
      // 此处可以返回true或者一个包含mutability和data属性的对象
      return {
        mutability: 'IMMUTABLE',
        data: {}
      };
    }
    return;
  },
  // 指定输出该entity在输出的html中的呈现方式
  exporter: function exporter(entityObject, originalText) {
    // 注意此处的entityObject并不是一个entity实例，而是一个包含type、mutability和data属性的对象
    return /*#__PURE__*/React.createElement("span", {
      className: "keyword-item"
    }, originalText);
  }
};
BraftEditor.use([MaxLength({}), entityTags]);
var CONTROLS = ['undo', 'redo', 'separator', 'font-size', 'separator', 'text-align', 'separator', 'text-color', 'bold', 'italic', 'underline', 'separator', 'link', 'separator', 'fullscreen']; // 编辑器工具栏

// 可选字段组件
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.id
    }, item.fieldName);
  }));
};
var Editor = function Editor(props) {
  var tagList = props.tagList,
    _props$maxLength = props.maxLength,
    maxLength = _props$maxLength === void 0 ? Infinity : _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,
    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(value);
    if ('defaultValue' in props) return BraftEditor.createEditorState(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(value));
    }
  }, [value]);

  // 图片上传
  var onUpload = function onUpload(_, file) {
    if (!file) return;
    if (file.status === 'done') {
      var _file$response;
      setEditorState(ContentUtils.insertMedias(editorState, [{
        type: 'IMAGE',
        url: (_file$response = file.response) === null || _file$response === void 0 ? void 0 : _file$response.url
      }]));
    }
  };

  // 计算最大长度（可选字段不占用长度）
  var _useDebounceFn2 = useDebounceFn(function () {
      var html = editorState ? editorState.toHTML() : '',
        length = _maxLength || Infinity;
      tagList && tagList.forEach(function (item) {
        var len = html.split(item.htmlValue).length; // 同个标签选择多次需要计算多个相同标签的长度
        len > 1 && (length += item.fieldName.length * (len - 1));
      });
      setMaxLength(length);
    }),
    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);
  };
  return /*#__PURE__*/React.createElement(ConfigContext.Consumer, null, function (value) {
    var uiLocale = value.uiLocale;
    // 自定义扩展组件
    var uploader = {
        key: 'antd-uploader',
        type: 'component',
        component: /*#__PURE__*/React.createElement(Upload, {
          accept: "image/*",
          onChange: onUpload,
          showUploadList: false
        }, /*#__PURE__*/React.createElement("button", {
          type: "button",
          "data-title": uiLocale.BraftEditor.insertImage,
          className: "control-item button"
        }, /*#__PURE__*/React.createElement(PictureFilled, null)))
      },
      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 extendControls = simple ? [uploader] : [uploader, 'separator', preview];

    // 字数达到上限的回调
    var onReachMaxLength = function onReachMaxLength() {
      message.warning(replaceMessage(uiLocale.BraftEditor.maxLengthWarning, {
        maxLength: "".concat(_maxLength)
      }));
    };
    return /*#__PURE__*/React.createElement(ConfigProvider, value, /*#__PURE__*/React.createElement("div", {
      className: "m-braftEditor ".concat(className)
    }, /*#__PURE__*/React.createElement(BraftEditor, _extends({
      hooks: restHooks,
      componentBelowControlBar: tagList ? /*#__PURE__*/React.createElement(Keywords, {
        locales: uiLocale,
        onClick: onChoseTags,
        tagList: tagList
      }) : null,
      onReachMaxLength: onReachMaxLength,
      controls: simple ? CONTROLS : undefined,
      excludeControls: ['media'],
      extendControls: extendControls
    }, rest, {
      // @ts-ignore
      language: uiLocale.locale
      // @ts-ignore
      ,
      maxLength: _maxLength,
      value: editorState,
      onChange: handleChange
    })), /*#__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
    }))));
  });
};
Editor.Preview = Preview;
Editor.createEditorState = BraftEditor.createEditorState;
export default Editor;