import { useAjax } from "@/Hook/useAjax";
import { Upload } from "antd";
import { RcFile } from "antd/es/upload";
import React from "react"
import { saveMediaApi } from "../../API/weMaterial/weMaterial";
import { useOss } from "@/Hook/useOss";
import dayjs from 'dayjs'
import { videoMessage } from "@/utils/compress";

interface Props {
    uploadButton?: JSX.Element
    type?: 'image' | 'video',
    onChange?: (data: string, videoInfo?: { width: number, height: number, videoLength: number }) => void
}

const UploadLoad: React.FC<Props> = ({ uploadButton, onChange, type = 'image' }) => {

    /********************************/
    const saveMedia = useAjax((params) => saveMediaApi(params))
    const ossUpload = useOss(true)
    /********************************/

    const upload = (file: RcFile) => {
        const name = dayjs().valueOf().toString()
        ossUpload.run(file, name).then(async (res) => {
            if (res?.data) {
                const [fileName, nameSuffix] = file.name.split('.')
                saveMedia.run({ fileName: name || fileName, mediaType: type || 'image', suffix: nameSuffix, url: res?.data })
                if (type === 'video') {
                    const videoInfo: { width: number, height: number, videoLength: number }[] = await videoMessage([file])
                    onChange?.(res.data, videoInfo[0])
                } else {
                    onChange?.(res.data)
                }
            }
        })
    }

    return <>
        <Upload
            name="avatar"
            accept={type === 'image' ? 'image/png,image/jpg,image/jpeg,image/gif' : 'video/mp4'}
            action="#"
            showUploadList={false}
            customRequest={() => { }}
            beforeUpload={(file: RcFile): any => {
                upload(file)
            }}
        >
            {uploadButton}
        </Upload>
    </>
}

export default React.memo(UploadLoad)