import type * as wangEditor from '@wangeditor/editor';
import { i18nChangeLanguage } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import '@wangeditor/editor/dist/css/style.css';
import type { CSSProperties } from 'react';
import { memo, useEffect, useState } from 'react';
import { getLocale, history, useIntl } from 'umi';
import { uploadImage } from '../server';
import { getToken } from '../utils/token';

interface IProps {
  /**
   * 是否禁用
   * @default false
   **/
  imgIsBase64?: boolean;
  /**
   * 是否禁用
   * @default false
   **/
  disabled?: boolean;
  /**
   * 图片上传是否禁用
   * @default false
   **/
  imgDisabled?: boolean;
  value?: string;
  onChange?: (value: string) => void;
  style?: CSSProperties;
  className?: string;
}
const CustomEditor = ({
  value,
  onChange,
  disabled = false,
  imgDisabled = false,
  imgIsBase64 = false,
  style,
  className,
}: IProps) => {
  const locale = getLocale();
  i18nChangeLanguage(locale === 'zh-CN' ? 'zh-CN' : 'en');
  const { formatMessage } = useIntl();
  const [editor, setEditor] = useState<wangEditor.IDomEditor | null>(null); // 存储 editor 实例
  const toolbarConfig = {
    excludeKeys: imgDisabled ? ['group-video', 'group-image'] : ['group-video'],
  };
  let subfix = document.documentElement.dataset.vanEnv || 'stg';
  if (subfix === 'prod') {
    subfix = '';
  }
  subfix = subfix ? `-${subfix}` : ``;
  // const urlEdit = `https://security-iam-api${subfix}.huolala.work/public/image/upload`;
  const urlEdit = `/goapi/public/image/upload`;
  const editorConfig: Partial<wangEditor.IEditorConfig> = {
    placeholder: formatMessage({ id: 'component.CustomEditor.placeholder' }),
    MENU_CONF: {
      uploadImage: {
        server: urlEdit, // 上传图片接口地址
        // fieldName: 'your-custom-name',
        maxFileSize: 1024 * 1024 * 1024, // 1G
        base64LimitSize: imgIsBase64 ? 5 * 1024 * 1024 * 1024 : 5 * 1024, // 5kb
        maxNumberOfFiles: 1,
        withCredentials: true,
        headers: {
          _su: `${new Date().valueOf()}`,
          url: location.href,
          appId: `${history?.location?.query?.appId || ''}`,
          'Uac-Token': getToken() || '',
        },
        // customInsert: (res, insertFn) => {
        //   // 自定义上传图片逻辑
        //   const { data } = res;
        //   const { url, alt, href } = data;
        //   insertFn(url, alt, href);
        // },
        customUpload: async (file, insertFn) => {
          // 自定义上传图片逻辑
          const formData = new FormData();
          formData.append('file', file);
          try {
            const { ret, msg, data } = await uploadImage(formData);
            if (ret === 0) {
              const { url, alt, href } = data;
              insertFn(url, alt, href);
            } else {
              console.log(msg);
            }
          } catch (error) {
            console.log(error);
          }
        },
      },
    },
    readOnly: disabled,
  };
  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);
  return (
    <div
      style={{ border: '1px solid #ccc', zIndex: 100, marginTop: '15px', ...style }}
      className={className}
    >
      <Toolbar
        editor={editor}
        defaultConfig={toolbarConfig}
        mode="default"
        style={{ borderBottom: '1px solid #ccc' }}
      />
      <Editor
        defaultConfig={editorConfig}
        value={value}
        onCreated={setEditor}
        onChange={(ele) => onChange?.(ele.getHtml())}
        mode="default"
        style={{ height: '500px' }}
      />
    </div>
  );
};
export default memo(CustomEditor);
