import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { useState, useEffect } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import { upload } from '@/services/myEditor';
import { message } from 'antd';

/**
 * 富文本编辑器
 * @param props
 * @constructor
 */
function MyEditor(props: any) {
  const { data, onChange, readOnly } = props;
  /**
   * editor 实例
   */
  const [editor, setEditor] = useState<IDomEditor | null>(null);

  /**
   * 编辑器内容
   */
  const [html, setHtml] = useState('');

  /**
   * 初始化
   */
  useEffect(() => {
    setHtml(data);
  }, []);

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

  /**
   * 上传文件
   * @param file
   * @param insertFn
   */
  const update = (file: any, insertFn: any) => {
    const imgData = new FormData();
    imgData.append('file', file);
    //调接口，上传图片
    upload(imgData).then((res) => {
      if (res.code == 0) {
        //接口调用成功，将上传文件插入到富文本中去
        insertFn(res.data.url, res.data.name);
      } else {
        message.error('上传失败');
      }
    });
  };

  /**
   * 编辑器配置
   */
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: '请输入内容...',
    // 菜单操作设置
    MENU_CONF: {
      uploadImage: {
        // 上传图片配置
        customUpload: update,
        server: '/web/v1/files',
      },
      uploadVideo: {
        // 上传视频配置
        customUpload: update,
        server: '/web/v1/files',
      },
    },
  };

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

  const handleChange = (el: any) => {
    if (onChange) onChange(el.getHtml());
  };

  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={handleChange}
          readOnly={readOnly}
          mode="default"
          style={{ height: '300px', overflowY: 'hidden' }}
        />
      </div>
    </>
  );
}

export default MyEditor;
