import React from 'react';
import E from 'wangeditor';

import { randomString } from '@/domains/basic-domain/utils';

import './EditorBox.less';

class EditorBox extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      editorId: randomString(16),
      textLength: 0,
    }
  }

  componentDidMount() {
    this.renderEditor()
  }

  renderEditor() {
    const { editorId } = this.state;
    const { detail, onChange } = this.props;
    const editorInt = new E(`#editor${editorId}`);
    editorInt.customConfig.menus = [
      'bold',  // 粗体
      'fontName',  // 字体
      'italic',  // 斜体
      'underline',  // 下划线
      'strikeThrough',  // 删除线
      'foreColor',  // 文字颜色
      'backColor',  // 背景颜色
      'list',  // 列表
      'justify',  // 对齐方式
      'emoticon',  // 表情
    ]

    editorInt.customConfig.emotions = [
      {
        title: 'emoji',
        type: 'emoji',
        content: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '😊', '🙂', '🙃', '😉', '😓', '😅', '😪', '🤔', '😬', '🤐']
      }
    ]
    editorInt.customConfig.zIndex = 999;
    editorInt.customConfig.pasteFilterStyle = false;
    editorInt.customConfig.pasteIgnoreImg = true;
    // 自定义处理粘贴的文本内容
    editorInt.customConfig.pasteTextHandle = function (content) {
      if (content === '' && !content) return ''
      var str = content
      str = str.replace(/<xml>[\s\S]*?<\/xml>/ig, '')
      str = str.replace(/<style>[\s\S]*?<\/style>/ig, '')
      str = str.replace(/<\/?[^>]*>/g, '')
      str = str.replace(/[ | ]*\n/g, '\n')
      str = str.replace(/&nbsp;/ig, ' ')
      return str
    }
    editorInt.customConfig.onchange = (html) => {
      const textLength = editorInt.txt.text().replace(/&nbsp;/ig, ' ').length;
      this.setState({ textLength }, () => {
        onChange(html, this.state.textLength);
      })
    }
    editorInt.create();
    editorInt.txt.html(detail.content);
    editorInt.change && editorInt.change();
  }

  render() {
    const { editorId, textLength } = this.state;
    const { limitLength = 1000 } = this.props;

    return <div className="wang-editor-container ">
      <div className="editor-box" id={`editor${editorId}`}></div>
      {textLength > limitLength && <div className="editor-tips">超了{textLength - limitLength}个字</div>}
    </div>
  }
}

export default EditorBox;
