import {i18n} from "@/locale";
import {useUserStore} from '@/store'

const baseUrl = import.meta.env.VITE_SERVER_BASEURL

function getClientId() {
    return 'e5cd7e4891bf95d1d19206ce24a7b32e'
}

function parseUploadResult(rawData: any): string {
    const data = typeof rawData === 'string' ? JSON.parse(rawData) : rawData
    if (!data || data.code !== 200) {
        throw new Error(data?.msg || '上传失败')
    }
    return (
        data?.data?.url ||
        data?.data?.fullUrl ||
        data?.data?.fileUrl ||
        data?.data?.link ||
        data?.data
    )
}

// 上传图片（走后端接口 /resource/oss/upload）
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')})
        }
        const userStore = useUserStore()
        const token = userStore.token
        const clientId = getClientId()

        uni.uploadFile({
            url: baseUrl + '/resource/oss/upload',
            filePath: filePath, // 要上传文件资源的路径
            name: 'file', // 必须填file
            header: {
                Authorization: token ? `Bearer ${token}` : '',
                clientid: clientId,
            },
            success: function (res) {
                if (res.statusCode < 200 || res.statusCode >= 300) {
                    reject(new Error('upload error:' + JSON.stringify(res)))
                    return
                }
                try {
                    resolve(parseUploadResult(res.data))
                } 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}
