import { useAjax } from "@/Hook/useAjax";
import { message, Upload } from "antd";
import { RcFile } from "antd/es/upload";
import React, { useEffect, useState } from "react"
import { saveMediaApi, upLoadMediaApi } from "../../API/weMaterial/weMaterial";
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { useOss } from "@/Hook/useOss";
import dayjs from 'dayjs'

interface Props {
    value?: string,
    onChange?: (data: { value: string, file: RcFile, name: string }) => void
}

const UploadVideo: React.FC<Props> = ({ value, onChange }) => {

    /********************************/
    const upLoadMedia = useAjax((params) => upLoadMediaApi(params))
    const saveMedia = useAjax((params) => saveMediaApi(params))
    const ossUpload = useOss(true)
    const [videoUrl, setVideoUrl] = useState<string>('');
    /********************************/

    useEffect(() => {
        setVideoUrl(value || '')
    }, [value])

    const uploadButton = (
        <div>
            {upLoadMedia.loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>上传视频</div>
        </div>
    );

    const upload = (file: RcFile) => {
        let name = dayjs().valueOf().toString()
        ossUpload.run(file, name).then(res => {
            if (res?.data) {
                let [fileName, nameSuffix] = file.name.split('.')
                saveMedia.run({ fileName: name || fileName, mediaType: 'video', suffix: nameSuffix, url: res?.data })
                onChange?.(res.data)
            }
        })
    }

    return <>
        <Upload
            name="avatar"
            listType="picture-card"
            accept='video/mp4'
            action="#"
            showUploadList={false}
            customRequest={() => { }}
            beforeUpload={(file: RcFile): any => {
                if (file.size > 10485760) {
                    message.error('视频大小大于10M，请压缩在上传')
                    return
                }
                upload(file)
            }}
        >
            {videoUrl ? <video src={videoUrl} style={{ width: '100%' }} /> : uploadButton}
        </Upload>
    </>
}

export default React.memo(UploadVideo)