import {
	set,
	get
} from '../cache/storage.js';
import {
    operatorUrl,
    operatorPlug,
    uploadImgUrl,
    previewUrl,
    copyrightUrl,
    aiShopUrl,
    imgAssets,
    appUrl
} from '../net/mainUrl'
// 项目与基础URL映射关系
const PROJECT_URL_MAP = {
    operator: operatorUrl,
    copyright: copyrightUrl,
    plug: operatorPlug,
    aiShop: aiShopUrl,
    // 添加新项目只需在此扩展
};
/**
 * 传入请求参数，返回Promise支持链试调用
 * @param url 请求地址
 * @param method 请求方法类型，不传入默认是"GET"
 * @param data 请求体数据
 * @param params 请求参数
 */
function request(url, method = "GET", data = {}, project = "copyright", needToken = true) {
    // 1. 参数预处理
    const baseUrl = PROJECT_URL_MAP[project] || copyrightUrl;
    const requestUrl = baseUrl + url;
    // 2. 请求头配置
    const headers = {
        "Content-Type": "application/json"
    };

    if (needToken) {
        const token = get('token');
        if (token) {
            headers.Auth = `Bearer ${token}`;
        }
    }
    // 3. 请求配置
    const requestConfig = {
        url: requestUrl.toString(),
        method: method.toUpperCase(),
        data,
        header: headers,
        timeout: 10000,
        dataType: "json"
    };
    return new Promise(function (resolve, reject) {
        uni.request({
            ...requestConfig,
            success(res) {
                if (res.statusCode === 200) {
                    resolve(res.data)
                } else {
                    console.log('错误success')
                    reject(res.data)
                }
            },
            fail(err) {
                console.log('错误')
                if (err.data) {
                    reject(err.data)
                } else {
                    reject(err)
                }
            }
        })
    })
}

// 导出请求和服务地址
export {
    request,
    uploadImgUrl,
    previewUrl,
    copyrightUrl,
    imgAssets,
    appUrl
}