import React from 'react';
import E from 'wangeditor';
import { fetch, apis } from '../../utils/request';

/**
 * @param {*} props
 * @returns
 */
class Wangedit extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      html: undefined,
      contenteditable: props.contenteditable == false ? false : true
    }
    this.editor = undefined;
  }

  render() {
    return (
      <div ref="editorElem" style={{ textAlign: 'left' }}>
      </div>
    );
  }

  componentDidMount() {
    const elem = this.refs.editorElem
    this.editor = new E(elem)
    // 使用 onchange 函数监听内容的变化
    this.editor.customConfig.onchange = html => {
      this.setState({ html })

      if (typeof this.props.onChange === 'function') {
        this.props.onChange(html)
      }
    }
    this.editor.customConfig.zIndex = 100
    this.editor.customConfig.uploadImgMaxLength = 1
    this.editor.customConfig.customUploadImg = function (files, insert) {
      if (!files.length) return
      
      const data = new FormData()
      data.append('file', files[0])

      fetch(apis.image.upload)({data}).then(insert)
    }
    this.editor.customConfig.menus = [
      'head',  // 标题
      'bold',  // 粗体
      'fontSize',  // 字号
      'fontName',  // 字体
      'italic',  // 斜体
      'underline',  // 下划线
      'strikeThrough',  // 删除线
      'foreColor',  // 文字颜色
      'backColor',  // 背景颜色
      'list',  // 列表
      'justify',  // 对齐方式
      'quote',  // 引用
      'image',  // 插入图片
      'undo',  // 撤销
      'redo'  // 重复
    ]
    
    // 过滤 word 字符
    this.editor.customConfig.pasteFilterStyle = false
    this.editor.customConfig.pasteTextHandle = function(content) {
      const regs = [
        /<!--\[if [\s\S]*?endif\]-->/ig,
        /<[a-zA-Z0-9]+\:[^>]+>[^>]*<\/[a-zA-Z0-9]+\:[^>]+>/ig,
        /<[a-zA-Z0-9]+\:[^>]+\/>/ig,
        /<style>[\s\S]*?<\/style>/ig,
        new RegExp('\u2029', 'ig'),     // 替换word分隔符 序号 8233
      ]

      return regs.reduce((acc, reg) => {
        return acc.replace(reg, '')
      }, content)
    }

    this.editor.create()
    this.editor.$textElem.attr('contenteditable',this.state.contenteditable);
    this.editor.customConfig.uploadImgShowBase64 = true
    this.editor.txt.html(this.props.value)
  }

  componentDidUpdate(props, state) {
    if (this.props.value && !state.html) {
      if (this.editor) {
        this.editor.txt.html(this.props.value)
      }
    }
  }

  /**
   *增加这个 shouldComponentUpdate 生命函数
    处理自动聚焦到富文本上
   *
   * @param {*} nextProps
   * @returns
   * @memberof Wangedit
   */
  shouldComponentUpdate(nextProps) {
    return nextProps.value !== this.editor.txt.html()
  }
}

export default Wangedit

