import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import React, { useState, useEffect } from "react";
import baseHttp from "@/service/base";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import Config from "@/util/config";
interface EditorProps {
  value?: string;
  onChange?: (value: string) => void;
  id?: string;
}
const MyEditor = (props: EditorProps) => {
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // 编辑器内容
  const [html, setHtml] = useState("");

  // 模拟 ajax 请求，异步设置 html
  useEffect(() => {
    setHtml(props.value ?? "");
  }, [props.value]);

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: "请输入内容...",
    MENU_CONF: {
      uploadImage: {
        server: Config.baseUrl + "/v1/public/fts/upload",
        fieldName: "file",
        async customUpload(file: File, insertFn) {
          let url = Config.baseUrl + "/uploads/" + file.name;
          let uploadUrl = Config.baseUrl + "v1/public/fts/upload";
          const formData = new FormData();
          formData.append("file", file);
          let res = await baseHttp.upload(uploadUrl, formData);
          if (res.code === 200) {
            insertFn(url, "", "");
          }
        },
      },
    },
  };

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

  return (
    <div style={{ border: "1px solid #ccc", zIndex: 100 }} id={props.id}>
      <Toolbar
        editor={editor}
        defaultConfig={toolbarConfig}
        mode="default"
        style={{ borderBottom: "1px solid #ccc" }}
      />
      <Editor
        defaultConfig={editorConfig}
        value={html}
        onCreated={setEditor}
        onChange={(editor) => {
          setHtml(editor.getHtml());
          props.onChange!(editor.getHtml());
        }}
        mode="default"
        style={{ height: "500px", overflowY: "hidden" }}
      />
    </div>
  );
};

export default MyEditor;
