import { useState, useEffect } from 'react'
import { Spin } from 'antd'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import './styles.less'
import { fontFamilyList, fontSizeList, lineHeightList } from '@/common/wangeditor-customer/utils/setting'
import { uploadFile } from '@/utils/oss'

export default function WangEditor({ value, onChange }) {
  // editor 实例
  const [editor, setEditor] = useState(null) // JS 语法

  const [loading, setLoading] = useState(false)

  // 工具栏配置
  const toolbarConfig = {
    excludeKeys: ['insertVideo', 'insertImage', 'emotion', 'table', 'codeBlock', 'blockquote', 'code', 'group-more-style', 'insertTable'] //删除工具栏
  }

  // 编辑器配置
  const editorConfig = {
    // JS 语法
    placeholder: '请输入内容...',
    MENU_CONF: {
      // 配置默认字号
      fontSize: { fontSizeList },
      fontFamily: { fontFamilyList },
      lineHeight: { lineHeightList },
      // 配置上传图片
      uploadImage: {
        timeout: 5 * 1000, // 5s
        fieldName: 'image',
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: 'Bearer ' + localStorage.getItem('token') || ''
        },
        maxFileSize: 10 * 1024 * 1024, // 10M
        base64LimitSize: 5 * 1024, // 5kb 以下插入 base64 // 用户自定义上传图片
        customUpload: async (file, insertFn) => {
          setLoading(true)
          const url = await uploadFile(file)
          insertFn(url, '图片')
          setLoading(false)
        }
      },
      uploadVideo: {
        timeout: 15 * 1000, // 5s
        fieldName: 'video',
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: 'Bearer ' + localStorage.getItem('token') || ''
        },
        allowedFileTypes: ['video/mp4', 'video/ogg', 'video/webm'],
        maxFileSize: 10 * 1024 * 1024, // 10M
        base64LimitSize: 5 * 1024, // 5kb 以下插入 base64 // 用户自定义上传图片
        customUpload: async (file, insertFn) => {
          setLoading(true)
          const url = await uploadFile(file)
          insertFn(url, '视频')
          setLoading(false)
        }
      }
    },
    hoverbarKeys: {
      image: {
        menuKeys: ['imageWidth30', 'imageWidth50', 'imageWidth100', 'deleteImage']
      },
      text: {
        menuKeys: ['headerSelect', 'insertLink', '|', 'bold', 'underline', 'italic', '|', 'color', 'bgColor', 'clearStyle']
      }
    }
  }
  useEffect(() => {
    return () => {
      if (editor === null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])

  return (
    <>
      <div className="editor-wrapper">
        <Spin spinning={loading}>
          <Toolbar editor={editor} defaultConfig={toolbarConfig} mode="default" className="editor-toolbar" />
          <Editor defaultConfig={editorConfig} value={value} onChange={onChange} onCreated={setEditor} mode="default" className="editor-main" />
        </Spin>
      </div>
    </>
  )
}
