import { Button, Form, Input, Upload, Space, Spin, Image, message } from 'antd';
import { useState, useEffect, useRef } from 'react';
const { TextArea } = Input;
import './index.less';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { useLocation, useNavigate } from 'react-router-dom';
import { addUser, editUser, getInfo } from '../request';
import { uploadFiles } from '@/utils/upload';
import { fontFamilyList } from '@/common/wangeditor-customer/utils/setting';
import AliOSS from 'ali-oss';
import dayjs from 'dayjs';
import { getAliOSSSTSToken } from '@/pages/setting/help/addedit/requet';
// import { LeftOutlined } from '@ant-design/icons';
import add from '@/assets/images/icon/add.png';

const BookAddEdit = () => {
  const location = useLocation();
  const [isEdit, setIsEdit] = useState(false);
  const [initialValues, setinitialValues] = useState({});
  const navigate = useNavigate();
  const flag = useRef(true);
  const [form] = Form.useForm();
  const [showimg, setshowimg] = useState(false);
  const [img, setImg] = useState('');
  // 上传图片是否超过限制
  const [bool, setBool] = useState(false);
  const handleGoBack = () => {
    navigate(-1);
  };

  // oss
  const [ossClient, setOssClient] = useState(null); // oss 操作
  const [STSToken, setSTSToken] = useState(null); // oss 过期设置
  const [file, setFile] = useState({}); // oss 过期设置
  const [uploading, setUploading] = useState(false);
  let ossClientTemp;
  const getStsAuthToken = async () => {
    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);
    }
  };
  // 详情信息
  const getInfor = async () => {
    const data = await getInfo({ id: location.state.id });
    setshowimg(true);
    setImg(data.img);
    setHtml(data.content);
    form.setFieldsValue(data);
  };
  // 图片上传
  const uploadImg = async (file) => {
    const { url } = await uploadFiles({ file, file_type: 'book' });
    setImg(url);
  };
  const onFinish = async (obj) => {
    let bool;
    if (isEdit) {
      bool = await editUser({ id: location.state.id, ...obj, content: html, img });
    } else {
      bool = await addUser({ ...obj, img });
    }
    bool && navigate(-1);
  };
  const props = {
    name: 'file',
    accept: '.jpg,.png',
    showUploadList: false,
    beforeUpload: async (file) => {
      const suffixArr = ['jpg', 'png'];
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (!suffixArr.includes(suffix)) {
        message.error(`请上传以${suffixArr.join('、')}格式的书籍`);
        return false;
      } else if (file.size >= 1024 * 1024) {
        message.error(`请上传大小在1M以内的图片`);
        return false;
      }
      setFile(file);
    },
    customRequest: async () => {
      if (!ossClient) {
        message.error('ossClient还未初始化', ossClient);
        return false;
      }

      try {
        setUploading(true);
        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);
        // 假设 result 中包含了文件的 URL
        const imageUrl = result.url;

        // 更新图片 URL 状态
        setImg(imageUrl);
        setshowimg(true);
        form.setFieldsValue({ img: imageUrl });
        setUploading(false);
        // 上传成功，返回 true 表示可以继续上传
        return true;
      } catch (error) {
        // 上传失败，处理错误
        console.error('上传文件失败：', error);
        message.error('上传文件失败，请重试');
        return false;
      }
    },
  };
  useEffect(() => {
    getStsAuthToken();
    if (location.state && location.state.id) {
      setIsEdit(true);
      // if(!flag.current){
      getInfor();

      // }else{
      // flag.current=false
      // }
    }
  }, []);
  // editor 实例
  const [editor, setEditor] = useState(null);
  // 编辑器内容
  const [html, setHtml] = useState('');
  const [loading, setLoading] = useState(false);

  // 工具栏配置
  const toolbarConfig = {
    excludeKeys: [
      'insertVideo',
      'insertImage',
      'emotion',
      'table',
      'codeBlock',
      'blockquote',
      'code',
      'group-more-style',
      'insertTable',
    ], //删除工具栏
  }; // 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: 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') || '',
        },
        allowedFileTypes: ['video/mp4', 'video/ogg', 'video/webm'],
        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);
        },
      },
    },
    hoverbarKeys: {
      image: {
        menuKeys: ['imageWidth30', 'imageWidth50', 'imageWidth100', 'deleteImage'],
      },
      text: {
        menuKeys: [
          'headerSelect',
          'insertLink',
          // 'bulletedList',
          // 'numberedList',
          '|',
          'bold',
          'underline',
          'italic',
          '|',
          'color',
          'bgColor',
          'clearStyle',
        ],
      },
    },
  };

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

  return (
    <div style={{ padding: 10 }}>
      <div className='back-icon' onClick={handleGoBack}>
        <span
          style={{
            display: 'inline-block',
            width: '11px',
            height: '10px',
            pointerEvents: 'none',
          }}
        >
          <Image src={add} />
        </span>
      </div>
      <Form form={form} onFinish={onFinish} labelCol={{ span: 2 }} initialValues={initialValues}>
        <Form.Item
          label='书籍名称'
          name='name'
          rules={[
            { required: true, message: '请输入书籍名称' },
            { max: 30, message: '最大30字符' },
          ]}
        >
          <Input autoComplete='off' placeholder='请输入书籍名称' style={{ width: 260 }}></Input>
        </Form.Item>
        <Form.Item
          label='作者'
          name='authors'
          rules={[
            { required: true, message: '请输入作者' },
            { max: 30, message: '最大30字符' },
          ]}
        >
          <Input autoComplete='off' placeholder='请输入作者' style={{ width: 260 }}></Input>
        </Form.Item>
        <Form.Item
          name='img'
          label='缩略图'
          className='uploadPar'
          rules={[
            {
              validator: () => {
                return new Promise((resolve, reject) => {
                  if (!img || !bool) {
                    resolve();
                  }
                  reject('最大150字符');
                });
              },
            },
          ]}
        >
          <div>
            {showimg && (
              <img id='img' src={img} width={80} height={80} style={{ borderRadius: 5 }} />
            )}
            <div className='descBox'>
              <Spin spinning={uploading}>
                <Upload {...props}>
                  <Button className='upload'>点击上传</Button>
                </Upload>
                <span className='desc'>尺寸：只能上传jpg/png文件，且不超过1M</span>
              </Spin>
            </div>
          </div>
        </Form.Item>
        <Form.Item
          label='编辑推荐'
          name='introduction'
          rules={[{ max: 65535, message: '最多65535字符' }]}
        >
          <TextArea
            placeholder='请输入编辑推荐'
            autoSize={{
              maxRows: 8,
              minRows: 5,
            }}
            style={{ width: 910 }}
          />
        </Form.Item>
        <Form.Item label='简介' name='content' rules={[{ max: 65535, message: '最多65535字符' }]}>
          <Spin spinning={loading}>
            {ossClient && (
              <div
                className='editor-box'
                style={{
                  border: '1px solid #d9d9d9',
                  borderRadius: '6px',
                  overflow: 'hidden',
                  zIndex: 100,
                }}
              >
                <Toolbar
                  editor={editor}
                  defaultConfig={toolbarConfig}
                  mode='default'
                  style={{ borderBottom: '1px solid #d9d9d9' }}
                />
                <Editor
                  defaultConfig={editorConfig}
                  value={html}
                  onCreated={setEditor}
                  onChange={(editor) => {
                    form.setFieldValue('content', editor.getHtml());
                    setHtml(editor.getHtml());
                  }}
                  mode='default'
                  className='w-e-text'
                  style={{ height: '400px', overflowY: 'hidden' }}
                />
              </div>
            )}
          </Spin>
        </Form.Item>
        <Form.Item
          wrapperCol={{
            span: 24,
          }}
        >
          <div style={{ textAlign: 'center' }}>
            <Space size={20}>
              <Button
                className='cancel'
                onClick={() => {
                  navigate(-1);
                }}
              >
                取消
              </Button>
              <Button className='submit' htmlType='submit' style={{ borderColor: '#aa1941' }}>
                确认
              </Button>
            </Space>
          </div>
        </Form.Item>
      </Form>
    </div>
  );
};

export default BookAddEdit;
