import config from './config';

const baseUrl = config.baseUrl;
// 封装公共申请办法
function request(url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', data?: object | any) {
	return new Promise(function(resolve, reject) {
		let header: any;
		uni.showLoading({
			title: '加载中...',
		});
		if (uni.getStorageSync('token')) {
			header = {
				'content-type': 'application/json',
				Authorization: uni.getStorageSync('token'),
			};
		}
		//  else {
		// 	let pages = getCurrentPages();
		// 	let curRoute = pages[pages.length - 1].route;
		// 	if (curRoute != 'pages/login/login') {
		// 		uni.showToast({
		// 			icon: 'none',
		// 			title: '请重新登录',
		// 			success() {
		// 				uni.navigateTo({
		// 					url: '/pages/login/login',
		// 				});
		// 			},
		// 		});
		// 	}
		// }
		uni.request({
			url: baseUrl + url,
			method: method,
			data: data,
			header: header,
			success(res: any) {
				uni.hideLoading();
				if (res.data.code == 200) {
					resolve(res);
				} else if (res.data.code == 500) {
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
					});
				} else if (res.data.code == 501 || res.data.code == 911) {
					uni.reLaunch({
						url: '/pages/login/login',
						success() {
							uni.showToast({
								title: '请登录',
								icon: 'none',
							});
						},
					});
				} else {
					console.log(res, '非200错误');
					//其余异样
					reject(res);
				}
			},
			fail(err: any) {
				uni.hideLoading();
				//申请失败
				uni.showToast({
					title: '连接服务器失败',
					icon: 'none',
				});
				reject(err);
			},
		});
	});
}

export { request };
