import React, { useState, useEffect } from 'react';
import { Spin } from 'antd';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import AliOSS from 'ali-oss';
import { getAliOSSSTSToken } from '@/pages/setting/help/addedit/requet';
import add from '@/assets/images/icon/add.png';
import dayjs from 'dayjs';
import './index.less';

const EditorReader = (props) => {
  const { form, fieldName, content, loadLoading } = props;

  // oss
  const [ossClient, setOssClient] = useState(null); // oss 操作
  const [STSToken, setSTSToken] = useState(null); // oss 过期设置
  const [file, setFile] = useState({}); // oss 过期设置
  const [uploading, setUploading] = useState(false);

  // editor 实例
  const [editor, setEditor] = useState(null);
  // 编辑器内容
  const [html, setHtml] = useState(content);
  const [loading, setLoading] = useState(loadLoading || false);

  const getStsAuthToken = async () => {
    const data = await getAliOSSSTSToken();
    if (data) {
      window.sessionStorage.setItem('sts', JSON.stringify(data));
      setSTSToken(data);
      const 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);
    }
  };

  // 工具栏配置
  const toolbarConfig = {
    excludeKeys: [
      'insertVideo',
      'insertImage',
      'emotion',
      'table',
      'codeBlock',
      'blockquote',
      'code',
      'group-more-style',
      'insertTable',
      'fullScreen',
      'insertLink',
      'headerSelect',
      'todo',
    ], //删除工具栏
  }; // JS 语法

  // 编辑器配置
  const editorConfig = {
    // JS 语法
    placeholder: '请输入内容...',
    MENU_CONF: {
      // 配置默认字号
      fontSize: {
        fontSizeList: [
          { name: '初号', value: '56px' },
          { name: '小初', value: '48px' },
          { name: '一号', value: '34px' },
          { name: '小一', value: '32px' },
          { name: '二号', value: '29px' },
          { name: '小二', value: '24px' },
          { name: '三号', value: '21px' },
          { name: '小三', value: '20px' },
          { name: '四号', value: '18px' },
          { name: '小四', value: '16px' },
          { name: '五号', value: '14px' },
          { name: '小五', value: '12px' },
          { name: '六号', value: '10px' },
          { name: '小六', value: '8px' },
          { name: '七号', value: '7px' },
          { name: '八号', value: '6px' },
        ],
      },
      fontFamily: {
        fontFamilyList: ['思源黑体', '思源宋体', '黑体', '宋体', '楷体', '仿宋'],
      },
      lineHeight: {
        lineHeightList: ['1', '1.25', '1.5', '2', '2.5', '3'],
      },
      // 配置上传图片
      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 = `banner-${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);
        },
      },

      uploadVideo: {
        timeout: 15 * 1000, // 5s

        fieldName: 'video',
        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 result = await ossClient.put(file.name, file);

          console.log('result', result);
          insertFn(result.url, '题库视频');
          // const { url } = await uploadFiles({ file, file_type: 'question' });
          // insertFn(url, '题库视频');
          setLoading(false);
        },
      },
    },
  };

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

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

  useEffect(() => {
    if (editor && ossClient) {
      editor.setHtml(content);
    }
  }, [editor, content, ossClient]);

  return (
    <div className='editor_customer_simple'>
      <div className='editor-box' style={{ border: '1px solid #ccc', zIndex: 100 }}>
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode='default'
          style={{ borderBottom: '1px solid #ccc' }}
        />
        <Spin spinning={loading}>
          {ossClient && (
            <Editor
              defaultConfig={editorConfig}
              value={html}
              onCreated={setEditor}
              onChange={(editor) => {
                form.setFieldValue(fieldName, editor.getHtml());
                setHtml(editor.getHtml());
              }}
              mode='default'
              className='w-e-text'
              style={{ height: '400px', overflowY: 'hidden' }}
            />
          )}
        </Spin>
      </div>
    </div>
  );
};

export default EditorReader;
