import React, { useEffect } from 'react';
import E from 'wangeditor';
import { message } from 'antd';
// import events from '@/events';
import { CommonAPI } from '~/api';

let editor: any = null;

interface PropsType {
  onChange: (html?: string) => void;
  value: string;
  // eslint-disable-next-line react/require-default-props
  isDetail?: boolean;
  height?: number;
}

const RichText: React.FC<PropsType> = ({ onChange, value, isDetail, height }) => {
  useEffect(() => {
    // 注：class写法需要在componentDidMount 创建编辑器
    editor = new E('.edit');
    editor.config.uploadImgShowBase64 = false;
    editor.config.zIndex = 1;
    editor.config.height = height ? height : 550;
    editor.config.uploadImgMaxLength = 5;
    editor.config.uploadImgMaxSize = 1024 * 1024 * 3; // 2M
    editor.config.customUploadImg = async (resultFiles: any, insertImgFn: any) => {
      // resultFiles 是 input 中选中的文件列表
      // insertImgFn 是获取图片 url 后，插入到编辑器的方法
      const formData = new FormData();
      resultFiles.map(async (item: any) => {
        formData.append('uploadFile', item);
      });
      const { code, result } = await CommonAPI.uploadOss(formData);
      if (code === '200') {
        insertImgFn(result.filePath);
        message.success('上传成功');
      } else {
        message.error('上传失败');
      }
    };
    editor.config.onchange = (newHtml: string) => {
      if (newHtml) {
        onChange(newHtml);
      } else {
        onChange(undefined);
      }
    };

    // 需要展示的菜单
    editor.config.menus = [
      'head',
      'bold',
      'fontSize',
      'fontName',
      'italic',
      'underline',
      'strikeThrough',
      'indent',
      'lineHeight',
      'foreColor',
      'backColor',
      'link',
      'list',
      'todo',
      'justify',
      'quote',
      'table',
      'splitLine',
      'undo',
      'redo',
      'image',
    ];

    /** 一定要创建 */
    editor.create();
    // events.addListener('clearEdit', () => {
    //   editor.txt.html('');
    // });
    return () => {
      // 组件销毁时销毁编辑器 注：class写法需要在componentWillUnmount中调用
      editor.destroy();
    };

    // 这里一定要加上下面的这个注释
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  useEffect(() => {
    if (editor) {
      editor.txt.html(value);
    }
    if (isDetail) {
      editor.disable();
    }
  }, [value]);

  return <div className='edit' />;
};
export default RichText;
