import '@wangeditor/editor/dist/css/style.css' // 引入 css

import React, { useState, useEffect } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'
import { UploadFile, GetFile } from "@/api"

type InsertFnType = (url: string, poster: string) => void
export default ({
  html,
  onChange
}: {
  html: string,
  onChange: (html: string) => void
}) => {
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null)

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

  // 自定义插入
  const customInsert = (res: any, insertFn: InsertFnType) => {
    console.log('自定义插入：', res);
    // insertFn(url, alt, href)
  };

  // 自定义上传
  const customUpload = async (file: File, insertFn: InsertFnType) => {
    console.log('自定义上传：', file);
    const form = new FormData();
    form.append('file', file);
    const res = await UploadFile(form);

    const fileId = res?.[0]?.id;
    insertFn(`/api/File/Download?fileId=${fileId}`, file.name);
    return;
  };

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        customUpload,
        customInsert
      },
      uploadVideo: {
        customUpload,
        customInsert
      }
    }
  }

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

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