import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Modal, Divider, Upload, Input, Space, Button, Form, Spin, message } from 'antd';
import { CloudUploadOutlined } from '@ant-design/icons';
import { SlateTransforms, SlateEditor, DomEditor, SlateElement } from '@wangeditor/editor';
import dayjs from 'dayjs';
import './index.less';

import { partSize, parallel, normalUploader, multipartUploader } from '../utils/upload';

const { Dragger } = Upload;

const VideoModal = forwardRef((props, ref) => {
  const { editor, ossClient, STSToken } = props;

  const fileAccept = ['.ogg', '.mp4', '.webm'];
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [uploading, setUploading] = useState(false); // 文件上传状态
  const [progress, setProgress] = useState(0);
  const [file, setFile] = useState({});
  const [fileList, setFileList] = useState([]);

  const [videoUrl, setVideoUrl] = useState('');

  useEffect(() => {
    if (!visible) {
      setVideoUrl('');
      form.resetFields();
    }
  }, [visible]);

  useImperativeHandle(ref, () => {
    return {
      setVisible,
    };
  });

  const normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e?.fileList;
  };
  const uploadProps = {
    name: 'file',
    maxCount: 1,
    showUploadList: false,
    accept: fileAccept.join(','),
    beforeUpload: (file, fileList) => {
      const fileExt = file.name.substring(file.name.lastIndexOf('.'));
      if (!fileAccept.includes(fileExt.toLowerCase())) {
        message.error('请上传正确格式的图片');
        return false;
      }
      setProgress(0);
      setUploading(false);
      setFile(file);
      setFileList(fileList);
    },
    customRequest: async () => {
      setUploading(true);
      let data = null;
      if (file.size >= partSize) {
        data = await multipartUploader(file, 'video', ossClient, (progress, checkpoint) => {
          console.log(`上传进度 ${progress}`);
          setProgress(parseInt(progress * 100));
        });
        console.log('multipartUploader --> ', data);
      } else {
        data = await normalUploader(file, 'video', ossClient);
        console.log('normalUploader --> ', data);
      }

      if (data.status === 200 && data.statusCode === 200) {
        const { url, name } = data;
        setVideoUrl(url);
        form.setFieldsValue({ videoUrl: url });
      }
      setUploading(false);
    },
  };

  const onFinish = (values) => {
    editor.restoreSelection();
    // editor.insertNode({
    //   type: 'chapterVideo',
    //   title: values.videoTitle,
    //   videoUrl: values.videoUrl,
    //   children: [{ text: '' }],
    // });
    // editor.insertNode({
    //   type: 'video',
    //   // title: values.videoTitle,
    //   src: values.videoUrl,
    //   children: [{ text: '' }],
    // });

    const nodeEntries = SlateEditor.nodes(editor, {
      match: (node) => {
        // JS syntax
        if (SlateElement.isElement(node)) {
          if (node.type === 'paragraph') {
            return true; // 匹配 paragraph
          }
        }
        return false;
      },
      universal: true,
    });
    for (let nodeEntry of nodeEntries) {
      const [node, path] = nodeEntry;
      if (node.children[0].text === '') {
        SlateTransforms.removeNodes(editor);
      }
    }

    const nodes = [
      {
        type: 'video',
        src: values.videoUrl,
        children: [{ text: '' }],
      },
      {
        type: 'paragraph',
        children: [{ text: values.videoTitle }],
      },
    ];
    SlateTransforms.insertNodes(editor, nodes);

    setVideoUrl('');
    setProgress(0);
    setUploading(false);
    form.resetFields();
    setVisible(false);
  };

  return (
    <div>
      <Modal
        open={visible}
        footer={null}
        centered
        destroyOnClose
        title='插入视频'
        classNames={{
          header: 'editor-header-customer',
          body: 'editor-body-customer',
          wrapper: 'editor-wrapper-customer',
        }}
        maskClosable={false}
        onCancel={() => setVisible(false)}
      >
        <Divider />
        <div className='editor-content-form'>
          <Form
            layout='vertical'
            name='validate_other'
            form={form}
            onFinish={onFinish}
            initialValues={{ videoUrl: videoUrl, videoTitle: '' }}
          >
            <Form.Item
              label='上传视频'
              valuePropName='fileList'
              name='videoUrl'
              getValueFromEvent={normFile}
              rules={[{ required: true, message: '请上传视频' }]}
            >
              <Spin spinning={uploading} tip={`${progress}%`}>
                <div className='editor-dragger'>
                  <Dragger {...uploadProps} showUploadList={false}>
                    {!videoUrl && (
                      <div className='editor-uploader-process'>
                        <p className='ant-upload-drag-icon'>
                          <CloudUploadOutlined style={{ fontSize: 40 }} />
                        </p>
                        <p className='ant-upload-text'>点击上传或拖拽到此处上传</p>
                        <p className='ant-upload-hint'>
                          支持上传 .ogg、.mp4、.webm 格式的文件
                        </p>
                      </div>
                    )}
                    {videoUrl && (
                      <>
                        <div className='editor-uploader-result'>
                          <div className='editor-uploader-result-img'>
                            <video src={videoUrl} autoPlay height='110' width='200' alt='' />
                          </div>
                          <div className='editor-uploader-result-tips'>
                            <Button
                              size='small'
                              type='primary'
                              ghost
                              onClick={() => setVideoUrl(null)}
                            >
                              替换
                            </Button>
                          </div>
                        </div>
                      </>
                    )}
                  </Dragger>
                </div>
              </Spin>
            </Form.Item>
            <Form.Item
              label='视频标题'
              name='videoTitle'
              rules={[{ required: true, message: '请输入图片标题' }]}
              extra='最多输入100字'
            >
              <Input maxLength={100} placeholder='' allowClear />
            </Form.Item>
            <Form.Item className='editor-form-buttons'>
              <Space>
                <Button type='default' disabled={uploading} onClick={() => setVisible(false)}>
                  取消
                </Button>
                <Button type='primary' disabled={uploading} htmlType='submit'>
                  插入
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
      </Modal>
    </div>
  );
});

export default VideoModal;
