import React, { useState, useEffect } from "react";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";

// 工具栏配置参考
// https://www.cnblogs.com/-roc/p/16400965.html

const defaultStyle = {
  border: "1px solid #ccc",
  zIndex: 100,
  marginTop: "15px"
}

function MyEditor(props) {

  const style = React.useMemo(() => ({ ...defaultStyle, ...(props.style || {}) }), [props.style])

  const {
    value = "",
    onChange = (e) => {
      setHtml(e);
    },
    toolbarConfig = {
      excludeKeys: ["group-image", "group-video"],
    },
    editorConfig = {
      placeholder: "请输入内容...",
    },
    readonly = false,
  } = props;
  const [editor, setEditor] = useState(null); // 存储 editor 实例
  const [html, setHtml] = useState("");
 
  // 模拟 ajax 请求，异步设置 html
  useEffect(() => {
    setHtml(value || "");
  }, [value]);

  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  function insertText() {
    if (editor == null) return;
    editor.insertText(" hello ");
  }

  function printHtml() {
    if (editor == null) return;
  }

  const handleChange = (editor) => {
    const raw = editor.getHtml();
    if (raw !== '<p><br></p>') {
      onChange(raw)
    }
  }

  return !readonly ? (
    <div className={props.className} style={style}>
      <Toolbar
        editor={editor}
        defaultConfig={toolbarConfig}
        mode="default"
        style={{ borderBottom: "1px solid #ccc" }}
      />
      <Editor
        defaultConfig={editorConfig}
        value={html}
        onCreated={setEditor}
        onChange={handleChange}
        mode="default"
        style={{ height: "500px" }}
      />
    </div>
  ) : (
    <div dangerouslySetInnerHTML={{ __html: value }}></div>
  );
}

export default MyEditor;
