import { useState, 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, SlateElement } from '@wangeditor/editor'
import './index.less'
import { uploadFile } from '@/utils/oss'

const { Dragger } = Upload

const AudioModal = (props, ref) => {
  const { editor } = 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 [audioUrl, setAudioUrl] = useState('')

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

  const uploadProps = {
    name: 'file',
    maxCount: 1,
    showUploadList: false,
    accept: fileAccept.join(','),
    beforeUpload: file => {
      const fileExt = file.name.substring(file.name.lastIndexOf('.'))
      if (!fileAccept.includes(fileExt.toLowerCase())) {
        message.error('请上传正确格式的音频文件')
        return false
      }
      setProgress(0)
      setUploading(false)
      setFile(file)
    },
    customRequest: async () => {
      setUploading(true)
      const url = await uploadFile(file)

      setAudioUrl(url)
      form.setFieldsValue({ audioUrl: url })
      setUploading(false)
    }
  }

  const onFinish = values => {
    editor.restoreSelection()

    const nodeEntries = SlateEditor.nodes(editor, {
      match: node => {
        if (SlateElement.isElement(node)) {
          if (node.type === 'paragraph') {
            return true // 匹配 paragraph
          }
        }
        return false
      },
      universal: true
    })
    for (let nodeEntry of nodeEntries) {
      const [node] = 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="上传音频" name="audioUrl">
              <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 forwardRef(AudioModal)
