//服务器接口地址
const baseURL: string = 'http://139.186.162.12';
//本地调试接口地址
// const baseURL: string = 'http://192.168.2.209:8080';

// 封装公共申请办法
function request(url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', data?: object | any) {
	return new Promise(function(resolve, reject) {
		let header: any;
		if (uni.getStorageSync('token') !== undefined && uni.getStorageSync('token') !== '') {
			header = {
				'content-type': 'application/json',
				'X-Litemall-Token': 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.statusCode == 200) {
					resolve(res);
				} else {
					//其余异样
					uni.showToast({
						title: res.data.errmsg,
						icon: 'none'
					});
					reject(res);
				}
			},
			fail(err) {
				uni.hideLoading();
				//申请失败
				uni.showToast({
					title: '连接服务器失败',
					icon: 'none'
				});
				reject(err);
			}
		});
	});
}

export { request, baseURL };
