import config from "@/config/index.js"
const baseUrl = process.env.NODE_ENV === 'development' ? config.base.dev : config.base.pro;
export async function request(parmas) {
	return new Promise(function(resolve, reject) {
		try {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			uni.request({
				...formatRequestBody(parmas),
				success(response) {
					let data = response.data;
					let code = data.code;
					let msg = data.msg
					if (code === 200) {
						resolve(data)
					} else {
						if (code === 401) {
							uni.showToast({
								title: msg || "登录失效！",
								mask: true,
								icon: "none",
								complete() {
									uni.redirectTo({
										url: '/pages/authorizedLogin/index'
									})
								}
							})

						} else {
							reject(data)
							uni.showToast({
								title: msg,
								mask: true,
								icon: "none"
							})
						}
					}
				},
				fail(res) {
					uni.showToast({
						title: res,
						mask: true,
						icon: "none"
					})
					reject(res)
				},
				complete(res) {
					uni.hideLoading();
				}
			})
		} catch (err) {
			console.log(err)
			reject(err)
		}
	})
}

function formatRequestBody(parmas) {
	let url = parmas.url;
	url = baseUrl + url;
	let data = {
		...parmas.data
	};
	let header = {
		...parmas.header
	};
    header['AppID'] = config.appID
    header['AppKey'] = config.appKey
    header['AppSecret'] = config.appSecret	
	let method = parmas.method || "get";
	let dataType = parmas.dataType || "json";
	let requestBody = {
		url,
		data,
		header,
		method,
		dataType
	};	
	return requestBody;
};
