import React, { useState, useRef, useEffect, useCallback } from 'react';
import E from 'wangeditor';
import PreviewMenu from './PreviewMenu'
import Preview from './Preview'
import { fetch, apis } from '../../utils/request';

export default props => {
  const ref = useRef()
  const editorRef = useRef()
  const [preview, setPreview] = useState(false)
  const [content, setContent] = useState()

  // wangeditor 有bug, 初始先触发 onchange
  const firstChanged = useRef(false)

  const initEditor = useCallback(() => {
    const editor = new E(ref.current)
    editorRef.current = editor
    
    // 取消自动 focus
    editor.config.focus = false

    // 触发 change
    editor.config.onchange = html => {
      // 规避 bug
      if (!firstChanged.current) {
        firstChanged.current = true
        return
      }

      setContent(html)

      if (typeof props.onChange === 'function') {
        props.onChange(html)
      }
    }

    editor.config.zIndex = 100

    // 自定义图片上传
    editor.config.uploadImgMaxLength = 1
    editor.config.customUploadImg = function (files, insert) {
      if (!files.length) return
      
      const data = new FormData()
      data.append('file', files[0])
      fetch(apis.image.upload)({data}).then(insert)
    }

    // 扩展预览按钮
    editor.menus.extend('previewMenu', PreviewMenu)
    PreviewMenu.preview = (html) => setPreview(true)

    // 配置菜单
    editor.config.menus = [
      'head',  // 标题
      'bold',  // 粗体
      'fontSize',  // 字号
      'fontName',  // 字体
      'italic',  // 斜体
      'underline',  // 下划线
      'strikeThrough',  // 删除线
      'foreColor',  // 文字颜色
      'backColor',  // 背景颜色
      'list',  // 列表
      'justify',  // 对齐方式
      'quote',  // 引用
      'image',  // 插入图片
      'undo',  // 撤销
      'redo',  // 重复
      'previewMenu'
    ]

    // 过滤 word 字符
    editor.config.pasteFilterStyle = false
    editor.config.pasteTextHandle = 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)
    }

    editor.create()
    editor.$textElem.attr('contenteditable', props.contenteditable !== false)

    return () => editor.destroy()
  }, [props.contenteditable])

  useEffect(() => {
    initEditor()
  }, [])
  
  useEffect(() => {
    if (props.value !== content && editorRef.current) {
      setContent(props.value)
      editorRef.current.txt.html(props.value)
    }
  }, [props.value])

  return (
    <>
      <div ref={ref} style={{ textAlign: 'left' }} />
      <Preview
        width={426}
        style={{width: '426px', height: '863px', margin: 0, padding: 0}}
        visible={preview}
        html={props.value}
        onCancel={() => setPreview(false)}
      />
    </>
  )
}
