import config from './config'

const http = (url = "", method = "GET", data = {}, loading = false, alarm = true) => {
	if (loading) {
		uni.showLoading({
			mask: true
		});
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: `${config.baseUrl}${url}`,
			method: method,
			data: data,
			header: {
				Authorization: `Bearer ${uni.getStorageSync('access')}`
			},
			dataType: 'json',
			success: (res) => {
				if (loading) {
					uni.hideLoading()
				};
				if (res.statusCode < 400) {
					resolve(res.data)
				} else {
					if (alarm) {
						var msg = res.data.err_msg ? res.data.err_msg : '请求失败';
						if(res.data.err_code == 'no_active_account'||res.data.err_code == "token_not_valid"){
							msg = '登录信息有误'
						}
						uni.showToast({
							icon: "none",
							title: msg
						})
					}
					

					if (res.statusCode == 401){
						var pages = getCurrentPages();    //获取加载的页面
					　　var currentPage = pages[pages.length - 1];  //获取当前页面的对象
					　　var url = currentPage.route;  //当前页面url
						if (url != 'pages/auth/login'){
							uni.reLaunch({
								url: '/pages/auth/login'
							})
						}
					}
					reject(res)
				}
			},
			fail: () => {
				if (loading) {
					uni.hideLoading()
				};
			}
		})
	})
}
export {http};
