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) {
					let data = response.data;
					let code = data.code;
					let msg = data.msg
					if (code === 200) {
						resolve(data)
					} else {
						if (code === 401) {
							uni.showToast({
								title: "登录失效！",
								mask: true,
								icon: "none",
								duration:3000,
								complete() {
									// let pages=getCurrentPages()
									// console.log({
									// 	page:pages[pages.length-1].$route.fullPath
									// })
									setTimeout(()=>{
										uni.navigateTo({
											url: '/pages/login/index'
										})
									},3000)
								}
							})

						} else {
							reject(data)							
							uni.showToast({
								title: msg,
								mask: true,
								duration:3000,
								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,
		AppID:config.appID,
		AppKey:config.appKey,
		AppSecret:config.appSecret
	};
	if(getToken()){
		header[config.TokenKey]=getToken();
	}
	let method = parmas.method || "get";
	let dataType = parmas.dataType || "json";
	let requestBody = {
		url,
		data,
		header,
		method,
		dataType
	};
	return requestBody;
};
