import {getTokenHeader} from '../request/header'
import {getObjValue} from "js-fast-way";
import {getAppApiUrl} from "@/config/envApi";

export const getUploadApi = () => {
    let url = '';
    //#ifdef H5
        url = '/api/';
    //#endif
    //#ifdef APP-PLUS
        url = getAppApiUrl()
    //#endif
    return url
}

export const uploadApi = async (file, form= {}) => {
    const url = getUploadApi() + 'blade-resource/oss/endpoint/upload-file';
    return uploadFileApi(url, file, form)
}

export const uploadApi2 = async (file, form= {}) => {
    const url = getUploadApi() + 'blade-resource/oss/endpoint/put-file';
    return uploadFileApi(url, file, form)
}

export const uploadFileApi = async (url, file, form= {}) => {
    return new Promise((resolve) => {
        uni.uploadFile({
            url: url,
            name: 'file',
            formData: form,
            header: getTokenHeader(),
            filePath: file,
            success:(res) => {
                const {code, msg, data} = JSON.parse(res?.data)
                if (code === 200) {
                    resolve({error: false, msg: msg, data: getObjValue(data)})
                } else {
                    resolve({error: true, msg: msg, data: {}})
                }
            },
            fail:()=> {
                resolve({error: true, msg: '上传失败', data: {}})
            }
        });
    })
}

