import { getOssSecretKeyApi } from "@/pages/weComTask/API/weMaterial/weMaterial";
import request from "@/utils/request";
import { App } from "antd";
import { RcFile } from "antd/es/upload";
import { useState } from "react";

export interface OssPromise {
    /**上传*/
    run: (file: RcFile, fileName?: string) => Promise<any>
    /**loding状态*/
    loading: boolean,
}
export function useOss(isLoading?: boolean): OssPromise {

    /**********************************/
    const { message } = App.useApp()
    const [loading, setLoding] = useState(false) //状态
    /**********************************/

    async function run(file: RcFile, fileName?: string) {//请求
        let hide: any
        if (isLoading) {
            hide = message.loading('上传中...', 0)
        }
        setLoding(true)
        let name = fileName || file.name.split('.')[0]
        let suffix = file.type
        if (!file.type) { suffix = 'audio/amr' }
        let res:any = await getOssSecretKeyApi({ filePrefix: name, suffix }).catch(error => {
            message.error(error?.message)
            setLoding(false)
            if (isLoading && hide) {
                hide()
            }
        })
        let msg: string = ''
        if (res?.data) {
            let ossData = res.data
            let formData = new FormData();
            Object.keys(ossData).forEach((key: string) => {
                if (key !== 'ossUrl') {
                    formData.append(key, ossData[key])
                }
            })
            formData.append('file', file)
            let data = await request({ url: ossData?.ossUrl, method: 'POST', data: formData }).catch(error => {
                console.error(error)
                message.error(error)
            })
            if (data) {
                setLoding(false)
                if (isLoading && hide) {
                    hide()
                    message.success('上传成功')
                }
                return data
            } else {
                msg = '上传文件到OSSkey失败'
                message.error('上传文件到OSSkey失败')
            }
        } else {
            msg = '获取OSSkey失败'
            message.error('获取OSSkey失败')
        }
        setLoding(false)
        if (isLoading && hide) {
            hide()
        }
        return { code: 500, data: null, msg }
    }

    return { run, loading }
}