function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useEffect, forwardRef } from 'react';
import { useSetState } from 'ahooks';
import { createEditor, useContextComponent } from "./context";
import classNames from 'classnames';
import { ClassicEditor } from "./ckeditor/ckeditor";
import Radio from "./widgets/radio";
import Input from "./widgets/input";
import Checkbox from "./widgets/radio/checkbox";
import CustomDate from "./widgets/input/date";
import Textarea from "./widgets/textarea";
import Sign from "./widgets/sign";
import EditableDiv from "./widgets/editableDiv";
import { getUUID } from "./utils/util";
import { UnorderedListOutlined } from '@ant-design/icons';
import "./index.less";
import viewRichText from "./view";
import CKModal from "./widgets/CKModal";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
var defaultPlugins = ClassicEditor.builtinPlugins;
function CkEditorCustom(_ref, ref) {
  var _state$editor;
  var content = _ref.content,
    config = _ref.config,
    customStyles = _ref.customStyles;
  var _useContextComponent = useContextComponent(),
    emit = _useContextComponent.emit,
    bind = _useContextComponent.bind;
  var _useSetState = useSetState({
      editor: null,
      html: '',
      active: 'design',
      modalVisible: false,
      modalType: '',
      modalTitle: '',
      executeFunc: '',
      defaultData: {}
    }),
    _useSetState2 = _slicedToArray(_useSetState, 2),
    state = _useSetState2[0],
    setState = _useSetState2[1];
  var ckcontent = (state === null || state === void 0 || (_state$editor = state.editor) === null || _state$editor === void 0 ? void 0 : _state$editor.getData) && state.editor.getData();
  bind('plugingChange', function (params) {
    var uuid = params.id || getUUID();
    sessionStorage.setItem('ckComponents', JSON.stringify(_objectSpread(_objectSpread({}, JSON.parse(sessionStorage.getItem('ckComponents') || '{}')), {}, _defineProperty({}, uuid, params.config))));
    params.callback(uuid);
  });
  useEffect(function () {
    sessionStorage.setItem('ckComponents', '');
    ClassicEditor.create(document.querySelector('#editor'), {
      language: 'zh-cn',
      plugins: [].concat(_toConsumableArray(defaultPlugins), [Radio, Input, Checkbox, CustomDate, Textarea, Sign, EditableDiv]),
      toolbar: {
        items: ['undo', 'redo', '|', 'heading', 'underline', 'bold', 'italic', '|', 'fontSize', 'fontFamily', 'fontColor', 'fontBackgroundColor', '|', 'alignment', '|', 'insertTable', 'indent', 'outdent', 'numberedList', 'bulletedList', '|'
        // 'customInput', 'customRadio', 'customCheckbox', 'customDate', 'customTextarea', 'customSign', 'editableDiv'
        ]
      },
      globalConfig: {
        emit: emit,
        bind: bind
      },
      heading: {
        options: [{
          model: 'paragraph',
          title: '正文',
          class: 'ck-heading_paragraph'
        }, {
          model: 'heading1',
          view: 'h1',
          title: '标题1',
          class: 'ck-heading_heading1'
        }, {
          model: 'heading2',
          view: 'h2',
          title: '标题2',
          class: 'ck-heading_heading2'
        }, {
          model: 'heading3',
          view: 'h3',
          title: '标题3',
          class: 'ck-heading_heading3'
        }]
      },
      table: {
        contentToolbar: ['tableColumn', 'tableRow', 'mergeTableCells', 'tableProperties', 'tableCellProperties']
      },
      fontSize: {
        options: [12, 14, 16, 18, 20, 22, 25, 30]
      },
      fontFamily: {
        options: ['宋体', '仿宋', '楷体']
      }
    }).then(function (editor) {
      window.editor = editor;
      setState({
        editor: editor
      });
    }).catch(function (error) {
      console.error(error);
    });
  }, []);
  useEffect(function () {
    if (content && state.editor) {
      sessionStorage.setItem('ckComponents', config);
      state.editor.setData(content);
      ckcontent = state.editor.getData();
    }
  }, [content, config, state.editor]);
  var modalprops = {
    visible: state.modalVisible,
    type: state.modalType,
    title: state.modalTitle,
    defaultData: state.defaultData,
    onClose: function onClose() {
      setState({
        modalVisible: false,
        modalTitle: '',
        modalType: '',
        defaultData: {}
      });
    },
    onOk: function onOk(params) {
      var uuid = params.id || getUUID();
      sessionStorage.setItem('ckComponents', JSON.stringify(_objectSpread(_objectSpread({}, JSON.parse(sessionStorage.getItem('ckComponents') || '{}')), {}, _defineProperty({}, uuid, params))));
      if (!params.id) {
        editor.execute(state.executeFunc, {
          configid: uuid
        });
      } else {
        editor.setData(editor.getData());
      }
      setState({
        modalVisible: false,
        modalTitle: '',
        modalType: '',
        defaultData: {}
      });
    }
  };
  useEffect(function () {
    if (ckcontent) {
      (document.querySelectorAll('.vtx_ck_widgets') || []).forEach(function (item) {
        if (!item.onclick) {
          item.onclick = function () {
            var configid = item.getAttribute('configid');
            var components = JSON.parse(sessionStorage.getItem('ckComponents') || '{}');
            var defaultData = components[configid] || {};
            setState({
              modalVisible: true,
              modalType: defaultData.type,
              modalTitle: '编辑',
              defaultData: _objectSpread(_objectSpread({}, defaultData), {}, {
                id: configid
              })
            });
          };
        }
      });
    }
  }, [ckcontent]);
  console.log(customStyles, 'customStyles');
  return /*#__PURE__*/_jsxs("div", {
    className: classNames('custom-ck'),
    style: _objectSpread({}, customStyles),
    children: [/*#__PURE__*/_jsxs("div", {
      className: classNames('content'),
      children: [/*#__PURE__*/_jsx("div", {
        className: classNames("tab1"),
        style: {
          display: state.active == 'source' ? 'block' : 'none'
        },
        children: /*#__PURE__*/_jsx("div", {
          className: classNames("block"),
          children: /*#__PURE__*/_jsx("pre", {
            children: /*#__PURE__*/_jsx("code", {
              children: state.html
            })
          })
        })
      }), /*#__PURE__*/_jsxs("div", {
        className: classNames("tab2"),
        style: {
          display: state.active == 'design' ? 'flex' : 'none'
        },
        children: [/*#__PURE__*/_jsx("div", {
          className: classNames("editor"),
          id: "editor",
          ref: ref
        }), /*#__PURE__*/_jsxs("div", {
          className: classNames('right_bar'),
          children: [/*#__PURE__*/_jsxs("div", {
            className: classNames('right_bar_title'),
            children: [/*#__PURE__*/_jsx(UnorderedListOutlined, {
              className: classNames('right_bar_title_icon')
            }), "\u8868\u5355\u7EC4\u4EF6"]
          }), [{
            name: '文本框',
            type: 'input',
            func: 'insertCustomInput'
          }, {
            name: '日期',
            type: 'date',
            func: 'insertCustomDate'
          }, {
            name: '文本域',
            type: 'textarea',
            func: 'insertCustomTextarea'
          }, {
            name: '签名图片',
            type: 'sign',
            func: 'insertCustomSign'
          }, {
            name: '可编辑文本',
            type: 'editable-div',
            func: 'insertEditableDiv'
          }, {
            name: '单选框',
            type: 'radio',
            func: 'insertCustomRadio'
          }, {
            name: '复选框',
            type: 'checkbox',
            func: 'insertCustomCheckbox'
          }].map(function (item) {
            return /*#__PURE__*/_jsx("div", {
              className: classNames('right_bar_button'),
              onClick: function onClick() {
                // state.editor.execute(item.func)
                setState({
                  modalVisible: true,
                  modalType: item.type,
                  modalTitle: "".concat(item.name, " > \u914D\u7F6E"),
                  executeFunc: item.func
                });
              },
              children: item.name
            }, item.func);
          })]
        })]
      }), /*#__PURE__*/_jsx("div", {
        className: classNames("tab3"),
        style: {
          display: state.active == 'preview' ? 'block' : 'none'
        },
        children: /*#__PURE__*/_jsx("div", {
          className: classNames("block"),
          children: viewRichText({
            content: state.html,
            configJson: sessionStorage.getItem('ckComponents') || '{}'
          })
        })
      })]
    }), /*#__PURE__*/_jsx("div", {
      className: classNames("footer"),
      children: [{
        name: '源码',
        key: 'source'
      }, {
        name: '设计',
        key: 'design'
      }, {
        name: '预览',
        key: 'preview'
      }].map(function (item) {
        return /*#__PURE__*/_jsx("span", {
          className: classNames(state.active == item.key ? 'checked' : ''),
          onClick: function onClick() {
            setState({
              active: item.key,
              html: window.editor.getData()
            });
          },
          children: item.name
        }, item.key);
      })
    }), state.modalVisible && /*#__PURE__*/_jsx(CKModal, _objectSpread({}, modalprops))]
  });
}
export default createEditor({})( /*#__PURE__*/forwardRef(CkEditorCustom));