const baseUrl = getApp().globalData.baseUrl
//带Token请求
const request = (opts, hasToken) => {
	const authorization = getApp().globalData.token
	//  hasToken是否传入token，为true则不传token
	const header = {
			'USER-TERM-TYPE': 'ipad', // 支付时需要用到 与pad一致
			'App-Type': 3
		}
	if(!hasToken){
		header['access-token'] = authorization
	}	
	//此token是登录成功后后台返回保存在storage中的
	let DefaultOpts = {
		url: baseUrl+opts.url,
		data: opts.data,
		method: opts.method,
		header: header
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(DefaultOpts).then(
			(res) => {
				// console.log(res[1])
				// 是否超时已跳转
				let loginTimeOut = uni.getStorageSync('loginTimeOut');
				if(res[0]&&res[0].errMsg.indexOf('request:fail')>=0){
					resolve({
						status: 500,
						message: "请求网络失败"
					})
				}
				let ret = res[1]
				if(res[1].data.status){
					ret = res[1].data
				}else if(res[1].status){
					ret = res[1]
				}
				if(ret.status == '200'){
					resolve(ret)
				}else{
					if(ret.status == 1001 && loginTimeOut == 'NO'){  //  未登录或登录过期
						uni.showToast({
							icon:'none',
							title: ret.message,
							duration: 5000 
						})
						uni.reLaunch({
							url: '/pages/login/login'
						})
						uni.setStorageSync('loginTimeOut', 'YES');
					}
					// 503
					if(ret.status == '503'||ret.status == '900'){
						uni.showToast({
							icon:'none',
							title: ret.message,
							duration: 3000 
						})
					}
					resolve(ret)
				}
				resolve(ret)
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
}

export default {
	baseUrl,
	request
}
