import config from "@/config.js"
import useUserStore from '@/stores/useUserStore';
export function request({
    url,
    method = 'GET',
    data = {},
    load = false,
    header = {}
} = {}) {

    return new Promise((resolve, reject) => {
        if (load) {
            uni.showLoading({
                title: '请稍候',
                mask: true
            });
        }
        let Authorization = ''
        if (useUserStore().token) {
            Authorization = `${useUserStore().userInfo.token}${useUserStore().token}`
        }
        uni.request({
            url: config.baseUrl + url,
            method,
            data: data,
            header: {
                'Authorization': Authorization || '',
            },
            success: resData => {
                // 响应拦截
                if (resData.statusCode === 200) {
                    const {
                        code,
                        msg
                    } = resData.data
                    if (code === 200) {
                        resolve(resData.data)
                        return
                    }
                    uni.showToast({
                        title: msg,
                        icon: 'none'
                    })
                }
                if (resData.data?.code === 401 || resData.data?.code === 402) {
                    useUserStore().logOut()
                    uni.showToast({
                        title: '登录过期，请重新登录',
                        icon: 'none'
                    })
                    return
                }
                const err = new Error('请求出现异常，请联系工作人员')
                err.error = resData
                reject(err)
            },
            fail: err => reject(err),
            complete() {
                if (load) {
                    uni.hideLoading();
                }
            }
        })
    })
}


/**
 * @param url  String，请求的地址，默认：none
 * @param data  Object，请求的参数，默认：{}
 * @param method  String，请求的方式，默认：GET
 * @param loading  Boolean，是否需要loading ，默认：false
 * @param header  Object，headers，默认：{}
 * @returns promise
 **/
export function createRequest(url, data = {}, method = 'GET', loading = false, headers = {}) {
    if (loading) {
        uni.showLoading({
            title: '请稍后',
            mask: true
        })
    }
    let Authorization = ''
    if (useUserStore().token) {
        Authorization = `${useUserStore().token}`
    }

    const header = headers || {};
    header["Authorization"] = encodeURIComponent(Authorization);
    return new Promise((resolve, reject) => {
        uni.request({
            url: config.baseUrl + url,
            method: method,
            data: data,
            header,
            success: resData => {
                // 响应拦截
                if (resData.statusCode === 200) {
                    const {
                        code,
                        msg
                    } = resData.data
                    if (code === 200) {
                        resolve(resData.data)
                        return
                    }
                    uni.showToast({
                        title: msg,
                        icon: 'none'
                    })
                }
                if (resData.data?.code === 401 || resData.data?.code === 402) {
                    useUserStore().logOut()
                }
                const err = new Error('请求出现异常，请联系工作人员')
                err.error = resData
                reject(err)
            },
            fail: (err) => {
                reject(err)
            },
            complete: () => {
                if (loading) {
                    uni.hideLoading();
                }
            }
        });
    })
}


export function uploadFile(tempFilePaths, loading = false) {
    if (loading) {
        uni.showLoading({
            title: '请稍后',
            mask: true
        })
    }
    let Authorization = ''
    if (useUserStore().token) {
        Authorization = `${useUserStore().token}`
    }

    const header = {};
    header["Authorization"] = encodeURIComponent(Authorization);
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: config.baseUrl + '/app/file/upload',
            filePath: tempFilePaths,
            name: 'file',
            header,
            success: (uploadFileRes) => {
                if (uploadFileRes.statusCode === 200) {
                    return resolve(uploadFileRes.data)
                }
            },
            fail: (err) => {
                reject(err)
            },
            complete: () => {
                if (loading) {
                    uni.hideLoading();
                }
            }
        })
    })
}