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

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

function formatRequestBody(parmas) {
	let url = parmas.url;
	url = baseUrl + url;
	let data = {
		...parmas.data
	};
	let header = {
		...parmas.header
	};
	header[config.TokenKey]=getToken();
	let method = parmas.method || "get";
	let dataType = parmas.dataType || "json";
	let requestBody = {
		url,
		data,
		header,
		method,
		dataType
	};
	return requestBody;
};
