import React, { useRef, useEffect, useState } from 'react'
import { createEditor, IDomEditor } from '@wangeditor/editor'


const EditorComponent = (props: any) => {
    const { value = '', readOnly = false } = props
    const ref = useRef<HTMLDivElement>(null)
    const [editor, setEditor] = useState<IDomEditor | null>(null)
    // value 变化，重置 HTML

    const editorConfig = {
        autoFocus: false,
        readOnly
    }
    useEffect(() => {
        if (!editor) return
        if (editor == null) return

        // if (value === curValue) return // 如果和当前 html 值相等，则忽略

        // ------ 重新设置 HTML ------
        try {
            editor?.setHtml(value)
        } catch (error) {
            console.error(error)
        }

    }, [value])

    useEffect(() => {
        if (ref?.current == null) return
        if (editor && editor != null) return
        // 防止重复渲染 当编辑器已经创建就不在创建了
        // if (ref.current?.getAttribute('data-w-e-textarea')) return

        const newEditor = createEditor({
            selector: ref.current,
            html: value,
            mode: 'simple',
            config: editorConfig,
        })
        setEditor(newEditor)
    }, [editor])

    return <div ref={ref} style={{ border: 'none' }}></div>
}

export default EditorComponent