import axios from './axios';
// withToken - 传false为无需鉴权，不传默认需要鉴权
const request = (url, type, params, withToken = true, headers) => {
    type = type.toLowerCase()
    if (['get', 'delete'].includes(type)) {
        return new Promise((resolve, reject) => {
            axios[type](url+requestGetQuery(params), {
                headers: Object.assign({}, { "Content-Type": "application/json;charset=utf-8"}, headers),
                withToken
            }).then((res) => {
                resolve(res)
            }).catch((error) => {
                reject(error)
            });
        })
    } else if (['post', 'put'].includes(type)) {
        return new Promise((resolve, reject) => {
            axios[type](url, JSON.stringify(params), {
                headers: Object.assign({}, { "Content-Type": "application/json;charset=utf-8"}, headers),
                withToken
            }).then((res) => {
                resolve(res)
            }).catch((error) => {
                reject(error)
            });
        })
    }
}

const requestGetQuery = (queryConfig) => {
    let urlConfig = "";
    for (let key in queryConfig) {
        if (queryConfig[key] !== "" && queryConfig[key] !== null&&queryConfig[key] !== undefined) {
            urlConfig += key + "=" + queryConfig[key] + "&";
        }
    }
    urlConfig = '?' + urlConfig.substring(0, urlConfig.length - 1);
    if (urlConfig === '?') {
        urlConfig = ''
    }
    return urlConfig;
}

export { 
    request,
    requestGetQuery
}
