import {i18n} from "@/locale";
const UPLOAD_ENDPOINT = '/resource/oss/upload'
const CLIENT_ID = 'e5cd7e4891bf95d1d19206ce24a7b32e'

function parseUploadResponse(data: any): string {
    const parsed = typeof data === 'string' ? JSON.parse(data || '{}') : (data || {})
    if (parsed.code && parsed.code !== 200) {
        throw new Error(parsed.msg || 'upload failed')
    }
    return parsed?.data?.url || parsed?.data || parsed?.url || ''
}

// 上传图片到阿里云oss
const upload = function (filePath: string, suffix = '.png', dir = 'app/image/') {
    return new Promise((resolve, reject) => {
        if (!filePath) {
            return uni.showToast({icon: "none", title: i18n.global.t('common.prompt.picture-wrong-please-try-again')})
        }

        uni.uploadFile({
            url: UPLOAD_ENDPOINT,
            filePath: filePath, // 要上传文件资源的路径
            name: 'file', // 必须填file
            timeout: 20000,
            header: {
                clientid: CLIENT_ID,
            },
            formData: {},
            success: function (res) {
                if (res.statusCode !== 200) {
                    reject(new Error('upload error:' + JSON.stringify(res)))
                    return
                }
                try {
                    const uploadedUrl = parseUploadResponse(res.data)
                    if (!uploadedUrl) {
                        reject(new Error('upload response url is empty'))
                        return
                    }
                    resolve(uploadedUrl)
                } catch (error) {
                    reject(error)
                }
            },
            fail: function (err) {
                console.log(err)
                uni.hideLoading()
                uni.showToast({icon: "none", title: i18n.global.t('common.prompt.up-failed')})
                reject(err)
            },
        })
    })
}

export {upload}
