import _Progress from "@alifd/next/es/progress";
import _Dialog from "@alifd/next/es/dialog";
import _Button from "@alifd/next/es/button";
import _Icon from "@alifd/next/es/icon";
import _Message from "@alifd/next/es/message";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { Component } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import cosUpload from "../../module/axios/cosUpload";
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import style from "./index.module.scss";
import { fontDictionary } from "../../module/text-font";
import "../../module/text-font/index.scss";
import EditorLeft from "./left";
// 获取字体列表
function getFontFamilyList() {
  var fontFamilyList = [];
  fontDictionary.forEach(function (res) {
    var fName = res.label,
      fValue = res.value;
    fontFamilyList.push({
      name: fName,
      value: fValue
    });
  });
  return fontFamilyList;
}
var WangEditorSetter = /*#__PURE__*/function (_Component) {
  _inheritsLoose(WangEditorSetter, _Component);
  function WangEditorSetter() {
    var _this2;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this2 = _Component.call.apply(_Component, [this].concat(args)) || this;
    _this2.state = {
      editorVisible: false,
      // 显示状态
      editor: undefined,
      // editor 实例
      html: '',
      upload: {
        status: false,
        progress: 0
      }
    };
    return _this2;
  }
  var _proto = WangEditorSetter.prototype;
  _proto.componentDidMount = function componentDidMount() {
    var propvalue = this.props.value;
    this.setState({
      html: (propvalue === null || propvalue === void 0 ? void 0 : propvalue.data) || ''
    });
    // 模拟 ajax 请求，异步设置 html
    setTimeout(function () {
      // console.log(this.state)
    }, 2000);
  };
  _proto.render = function render() {
    var _this3 = this,
      _this$state;
    var onChange = this.props.onChange;
    var toolbarConfig = {}; // 工具栏配置
    // 排除工具栏部分功能
    toolbarConfig.excludeKeys = ['uploadVideo' // 视频上传
    ];

    // 编辑器打开事件
    var editorOpen = function editorOpen(_this) {
      _this.setState({
        editorVisible: true
      });

      // this.state.editor?.getHtml()
      // this.state.editor?.dangerouslyInsertHtml(`<table style="width: 90%; height: 300px; background: linear-gradient(0deg, #f4dfbc 0%, #fafaec 100%);border-radius: .5em;position: relative;overflow: hidden;padding: 2em 1em;"><tr><td>2222222</td></tr></table>`)
      setTimeout(function () {
        var _this$state$editor;
        // const tpl = `<span style="color: rgb(149, 155, 166); background-color: rgb(246, 247, 249); font-size: 29px; font-family: YouSheBiaoTiHei;">asdfasdfasdfasdf</span>`
        // const tpl = `<span style="padding: 20px; display: block; background-color: #ff0000;">asdfasdfasdfasdf</span>`
        var tpl = "<table contenteditable=\"true\" style=\"height: 100px;width: 200px;\"><colgroup><col width=\"auto\"></colgroup><tbody><tr id=\"w-e-element-27\" data-slate-node=\"element\"><td colspan=\"1\" rowspan=\"1\" id=\"w-e-element-28\" data-slate-node=\"element\" data-slate-inline=\"false\" style=\"border-right-width: 3px; cursor: auto;\"><span id=\"w-e-text-29\" data-slate-node=\"text\"><span data-slate-leaf=\"true\"><span data-slate-zero-width=\"n\" data-slate-length=\"0\"><br></span></span></span></td></tr></tbody></table>";
        (_this$state$editor = _this.state.editor) === null || _this$state$editor === void 0 ? void 0 : _this$state$editor.dangerouslyInsertHtml(tpl);
      }, 5000);
    };

    // 编辑器关闭事件
    var editorClose = function editorClose() {
      // console.log(e.triggerType);
      _this3.setState({
        editorVisible: false
      });
    };

    // 编辑器配置初始化
    var editorConfig = {
      placeholder: '请输入内容...',
      MENU_CONF: {} // 初始化 MENU_CONF 属性 - 工具栏配置
    };

    var setUploadStatus = function setUploadStatus(_ref) {
      var total = _ref.total,
        loaded = _ref.loaded;
      var progress = (loaded / total * 100).toFixed(2) - 0;
      _this3.setState({
        upload: {
          status: !(progress >= 100),
          progress: progress
        }
      });
    };

    // cos[图片] 上传配置
    editorConfig.MENU_CONF.uploadImage = {
      // maxFileSize: 1024 ** 2 * 20, // Byte
      //
      // // 最多可上传几个文件，默认为 100
      // maxNumberOfFiles: 10,

      // form-data fieldName ，默认值 'wangeditor-uploaded-image'
      // fieldName: 'your-custom-name',
      // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
      // allowedFileTypes: ['image/*'],
      //
      // // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
      // meta: {
      //     token: 'xxx',
      //     otherKey: 'yyy'
      // },
      //
      // // 将 meta 拼接到 url 参数中，默认 false
      // metaWithUrl: false,
      //
      // 自定义增加 http  header
      // headers: {
      //     Accept: 'text/x-json',
      //     otherKey: 'xxx'
      // },
      //
      // // 跨域是否传递 cookie ，默认为 false
      // withCredentials: true,
      //
      // // 超时时间，默认为 10 秒
      // timeout: 65 * 1000,

      // 自定义上传
      customUpload: function () {
        var _customUpload = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(file, insertFn) {
          var _this3$props$initialV;
          var succ;
          return _regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  succ = cosUpload(file, {
                    pathDir: ((_this3$props$initialV = _this3.props.initialValue) === null || _this3$props$initialV === void 0 ? void 0 : _this3$props$initialV.uploadDir) || '',
                    isDateDir: true,
                    reName: true,
                    onProgress: function onProgress(_ref2) {
                      var total = _ref2.total,
                        loaded = _ref2.loaded;
                      setUploadStatus({
                        total: total,
                        loaded: loaded
                      });
                    }
                  });
                  succ.then(function (_ref3) {
                    var code = _ref3.code,
                      data = _ref3.data,
                      msg = _ref3.msg;
                    if (code === '0000') {
                      insertFn(data.ossPath, data.imgName, '');
                    } else {
                      _Message.error(msg);
                    }
                  });
                case 2:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee);
        }));
        function customUpload(_x, _x2) {
          return _customUpload.apply(this, arguments);
        }
        return customUpload;
      }()
    };
    editorConfig.MENU_CONF.fontFamily = {
      fontFamilyList: [].concat(getFontFamilyList())
    };
    // editorConfig.onCreated = (editor: IDomEditor)=>{
    //     const {value: propvalue} = this.props
    //     this.setState({
    //         html: propvalue?.data || ''
    //     })
    // }

    // 内容变化事件
    var editorChange = function editorChange(editor) {
      // debugger
      var stateConf = {
        html: editor.getHtml()
      };
      if (!_this3.state.editor) {
        stateConf.editor = editor;
      }
      _this3.setState(stateConf);
    };

    // 提交内容事件
    var editorCommit = function editorCommit() {
      onChange({
        data: _this3.state.html
      });
      editorClose();
    };
    return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(_Button, {
      onClick: function onClick() {
        return editorOpen(_this3);
      }
    }, /*#__PURE__*/React.createElement(_Icon, {
      type: "edit"
    }), "\u7F16\u8F91\u5185\u5BB9"), /*#__PURE__*/React.createElement(_Dialog, {
      title: null,
      visible: this.state.editorVisible,
      onOk: editorCommit,
      onClose: editorClose,
      onCancel: editorClose,
      className: style.dialog
    }, /*#__PURE__*/React.createElement("div", {
      className: style.title
    }, "\u914D\u7F6E\u56FE\u6587\u5185\u5BB9"), /*#__PURE__*/React.createElement("div", {
      className: style.editor
    }, /*#__PURE__*/React.createElement("div", {
      className: style['editor-left']
    }, /*#__PURE__*/React.createElement(EditorLeft, null)), /*#__PURE__*/React.createElement("div", {
      className: style['editor-right']
    }, /*#__PURE__*/React.createElement("div", {
      style: {
        border: '1px solid #ccc',
        zIndex: 100
      }
    }, /*#__PURE__*/React.createElement(Toolbar, {
      editor: (_this$state = this.state) === null || _this$state === void 0 ? void 0 : _this$state.editor,
      defaultConfig: toolbarConfig,
      mode: "default",
      style: {
        borderBottom: '1px solid #ccc'
      }
    }), /*#__PURE__*/React.createElement(Editor, {
      defaultConfig: editorConfig,
      value: this.state.html,
      onChange: editorChange,
      mode: "default",
      style: {
        minHeight: '60vh',
        widssth: '80vw',
        overflowY: 'hidden'
      }
    }))))), /*#__PURE__*/React.createElement(_Dialog, {
      title: "\u6587\u4EF6\u4E0A\u4F20\u4E2D...",
      visible: this.state.upload.status,
      footer: /*#__PURE__*/React.createElement("div", null),
      closeMode: [],
      className: style.uploading
    }, /*#__PURE__*/React.createElement(_Progress, {
      percent: this.state.upload.progress,
      shape: "circle"
    })));
  };
  return WangEditorSetter;
}(Component);
WangEditorSetter.displayName = 'WangEditorSetter';
export { WangEditorSetter as default };