const baseUrl="https://helper.qcfun.ximengnaikang.cn/api";
// const baseUrl="http://192.168.0.15/api";
import store from "../store/store.js"

const request=function(url,dataPraams,method="POST"){
	
	const token = uni.getStorageSync("token")
	
	let header={}
	
	const whiteUrl=["/user/getopenidtoken",""];
	
	if(whiteUrl.indexOf(url)==-1){
		header["authorization"]="bearer "+token
	}
	
	url=baseUrl+url;
	
	
	if(!store.state.updateUser){
		// 显示loading
		uni.showLoading({
			title: '加载中'
		});
	}
	
	store.state.updateUser=false
		
	return new Promise((resolve,reject)=>{
		uni.request({
			url,
			method,
			data:dataPraams,
			header,
			success:function(res){
				uni.hideLoading();
				const {data}=res
				const {error_code}=data
				
				// 存在token 进行刷新
				if(res.header.Authorization){
					let token=res.header.Authorization;
					if(token){
						token=token.substr(7);
						uni.setStorage({
							key:"token",
							data:token
						})
						store.commit("change_token",token)
					}
				}
				
				if(error_code===200){
					resolve(data)
				}else{
					if(error_code === 413){
						uni.removeStorage({
							key:"userinfo",
							success:function(res){
								uni.showToast({
									title:"token过期,请退出重新登录",
									icon:"none",
									duration: 2500
								})
							}
						})
					}else if(error_code === 42201){
						resolve(data)
					}else{
						let msg=data.message ? data.message : '服务器错误'
						msg = data.msg ? data.msg : msg
						uni.showToast({
							title:msg,
							icon:"none",
							duration: 2500
						})
					}
					reject(data)
				}
			},
			fail:function(err){
				uni.hideLoading();
				uni.showToast({
					title:"网络加载失败",
					icon:"none",
					duration: 2500
				})
				reject(err)
			}
		})
	})
	
}

export default request;