import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import type { FC, ReactNode } from 'react'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'
type InsertFnType = (url: string) => void

interface Iprops {
  value: string
  onChange: (e: any) => any
  height?: string
  children?: ReactNode
}

const ToolbarStyle = { borderBottom: '1px solid #ccc' }
const CommonWangEditor: FC<Iprops> = (props) => {
  const { onChange } = props
  const [editor, setEditor] = useState<IDomEditor | null>(null) // TS 语法
  // const [editor, setEditor] = useState(null)                   // JS 语法

  // 编辑器内容
  const [html, setHtml] = useState(props.value)

 

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = useMemo(() => {
    return {}
  }, [])

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = useMemo(() => {
    return {
      // TS 语法
      // const editorConfig = {                         // JS 语法
      placeholder: '请输入内容...',
      autoFocus: false,
      MENU_CONF: {
        uploadImage: {
          async customUpload(file: File, insertFn: InsertFnType) {
            const url = window.URL.createObjectURL(file)
            // TS 语法
            // async customUpload(file, insertFn) {                   // JS 语法
            // file 即选中的文件
            // 自己实现上传，并得到图片 url alt href
            // 最后插入图片
            insertFn(url)
          }
        }
      }
    }
  }, [])

  const onChangeHandle = useCallback(
    (editor: any) => {
      setHtml(editor.getHtml())
      onChange(editor.getHtml())
    },
    [onChange]
  )

  const Editorstyle = useMemo(() => {
    return { height: props.height || '300px' }
  }, [props.height])

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])
  useEffect(()=>{
    setHtml(props.value)
  },[props.value])

  return (
    <>
      <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={ToolbarStyle}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={onChangeHandle}
          mode="default"
          style={Editorstyle}
        />
      </div>
    </>
  )
}

export default memo(CommonWangEditor)
