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 './index.less';

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

const { Dragger } = Upload;

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

  const fileAccept = ['.mp3', '.wav', '.ogg',];
  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 [audioUrl, setAudioUrl] = useState('');
  // http://zxts-book-file.zijingebook.com/2024/02/24/audio-1708768923192-5u9t1c8t19n.mp3

  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, 'audio', ossClient, (progress, checkpoint) => {
          console.log(`上传进度 ${progress}`);
          setProgress(parseInt(progress * 100));
        });
        console.log('multipartUploader --> ', data);
      } else {
        data = await normalUploader(file, 'audio', ossClient);
        console.log('normalUploader --> ', data);
      }

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

  const onFinish = (values) => {
    editor.restoreSelection();
    // editor.insertNode({
    //   type: 'chapterAudio',
    //   title: values.videoTitle,
    //   audioUrl: values.audioUrl,
    //   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.audioUrl,
        height: 60,
        width: 260,
        children: [{ text: '' }],
      },
      {
        type: 'paragraph',
        textAlign: 'center',
        children: [{ text: values.videoTitle }],
      },
    ];
    SlateTransforms.insertNodes(editor, nodes);
    setAudioUrl('');
    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={{ audioUrl: audioUrl, videoTitle: '' }}
          >
            <Form.Item
              label='上传音频'
              valuePropName='fileList'
              name='audioUrl'
              getValueFromEvent={normFile}
              // rules={[{ required: true, message: '请上传音频' }]}
            >
              <Spin spinning={uploading} tip={`${progress}%`}>
                <div className='editor-dragger'>
                  <Dragger {...uploadProps} showUploadList={false}>
                    {!audioUrl && (
                      <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'>
                          支持上传 .mp3、.wav、.ogg 格式的文件
                        </p>
                      </div>
                    )}
                    {audioUrl && (
                      <>
                        <div className='editor-uploader-result'>
                          <div className='editor-uploader-result-img'>
                            <audio src={audioUrl} controls height='50' width='100'></audio>
                          </div>
                          <div className='editor-uploader-result-tips'>
                            <Button
                              size='small'
                              type='primary'
                              ghost
                              onClick={() => setAudioUrl(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 AudioModal;
