import { useState, useEffect, useRef } from 'react';
import { Spin } from 'antd';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { DomEditor } from '@wangeditor/editor';
import { uploadFiles } from '@/utils/upload';
import AliOSS from 'ali-oss';
import dayjs from 'dayjs';
import { getAliOSSSTSToken } from '../request';
const QuestionEditr = (props) => {

  const [ossClient, setOssClient] = useState(null); // oss 操作
  const [STSToken, setSTSToken] = useState(null); // oss 过期设置

  let ossClientTemp;

  const getStsAuthToken = () => {
    return new Promise(async (resolve) => {
      const data = await getAliOSSSTSToken();
      if (data) {
        window.sessionStorage.setItem('sts', JSON.stringify(data));
        setSTSToken(data);
        ossClientTemp = await new AliOSS({
          accessKeyId: data.AccessKeyId,
          accessKeySecret: data.AccessKeySecret,
          stsToken: data.SecurityToken,
          endpoint: data.endpoint,
          bucket: 'zxts-book-file',

          timeout: 180000,
          refreshSTSToken: async () => {
            const info = await getAliOSSSTSToken();
            return {
              AccessKeyId: info.AccessKeyId,
              AccessKeySecret: info.AccessKeySecret,
              SecurityToken: info.SecurityToken,
            };
          },
          refreshSTSTokenInterval: 14 * 60 * 1000,
        });
        setOssClient(ossClientTemp);
        // console.log('AliOSS', ossClientTemp);
      }
      resolve();
    });
  };

  useEffect(() => {
    getStsAuthToken();
  }, []);

  const {
    editorValue = '',
    quesList = [],
    setQuesList,
    index,
    setedierVal,
    form = null,
    name = '',
  } = props;
  const timeout = useRef();
  // 题干名称的编辑器实例
  const [titlesEditor, setTitlesEditor] = useState(null);
  // 工具栏配置
  const toolbarConfig = {};
  toolbarConfig.toolbarKeys = ['uploadImage'];
  const [loading, setLoading] = useState(true);
  const [tempQuestion, setTempQuestion] = useState(quesList);
  // 编辑器配置
  const editorConfig = {
    // JS 语法
    placeholder: '请输入内容...',
    hoverbarKeys: {
      text: {
        menuKeys: []
      }
    },
    MENU_CONF: {
      // 配置默认字号
      // 配置上传图片
      uploadImage: {
        timeout: 5 * 1000, // 5s

        fieldName: 'image',
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: 'Bearer ' + localStorage.getItem('token') || '',
        },
        maxFileSize: 10 * 1024 * 1024, // 10M

        base64LimitSize: 5 * 1024, // 5kb 以下插入 base64
        // 用户自定义上传图片
        customUpload: async (file, insertFn) => {
          setLoading(true);
          if (!ossClient) {
            console.error('ossClient还未初始化', ossClient);
            return false;
          }
          const fileExt = file.name.substring(file.name.lastIndexOf('.'));
          const fileName = `practice-${dayjs().valueOf()}-${Math.random().toString(36).substring(2)}${fileExt}`;
          const filePath = `${dayjs().format('YYYY/MM/DD')}/${fileName}`;
          const result = await ossClient.put(filePath, file);

          console.log('result', result);
          insertFn(result.url, '题库图片');

          // const { url } = await uploadFiles({ file, file_type: 'question' });
          // insertFn(url, '题库图片');

          setLoading(false);
        },
      },
      customPaste: (editor, event) => {
        // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
        const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
        // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）
  
        // 异步
        setTimeout(() => {
        editor.insertText(text)
        }, 500)
  
        // 阻止默认的粘贴行为
        event.preventDefault()
        return false
      }
    },
    customPaste: (editor, event) => {
      // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
      const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
      // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

      // 异步
      setTimeout(() => {
      editor.insertText(text)
      }, 500)

      // 阻止默认的粘贴行为
      event.preventDefault()
      return false
    }
  };

  // 及时销毁 editor ，重要！
  useEffect(() => {
    if (titlesEditor) {
      clearTimeout(timeout.current);
      setLoading(false)
    }
    return () => {
      if (titlesEditor === null) return;
      titlesEditor.destroy();
      setTitlesEditor(null);
    };
  }, [titlesEditor]);
  return (
    <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
      <Toolbar
        editor={titlesEditor}
        defaultConfig={toolbarConfig}
        mode='default'
        style={{ borderBottom: '1px solid #ccc' }}
      />

      <Spin spinning={loading}>
        <Editor
          defaultConfig={editorConfig}
          value={editorValue}
          onCreated={setTitlesEditor}
          onChange={(editor) => {
            if (name) {
              form.setFieldsValue({ [name]: editor.getHtml() });
              setedierVal(editor.getHtml());
            } else {
              clearTimeout(timeout.current);
              timeout.current = setTimeout(() => {
                let obj = { option: '', correct: false };
                if (editor.getHtml() === '<p><br></p>') {
                  tempQuestion[index] = obj;
                } else {
                  obj.option = editor.getHtml();
                  tempQuestion[index] = obj;
                }
                setQuesList(tempQuestion);
                setTempQuestion(tempQuestion);
                form.setFieldsValue({ "question_list": tempQuestion });
              }, 100)
            }
          }}
          config={{
            uploadImgServer: 'your_upload_server_address',
          }}
          mode='default'
          style={{ height: '100px', overflowY: 'hidden' }}
        />
      </Spin>
    </div>
  );
};

export default QuestionEditr;
