import {baseApiUrl} from './config.js'
import {apiWechatLogin} from '@/api/user'
import CryptoJS from './crypto'
import store from '@/store/index'

const ENV=uni.getAccountInfoSync().miniProgram

// 请求错误消息提示
const showError=error=>{
	let errMsg=''
	switch(error.code){
		case 400:
			errMsg=error.msg;
			break;
		default:
			errMsg=error.msg;
			break;
	}
	setTimeout(()=>{
		uni.showToast({
			title:errMsg,
			icon:'none'
		})
	},0)
	
}


// 微信登录
const wechatLogin=()=>{
	return new Promise((resolve,reject)=>{
		uni.login({
			provider: 'weixin',
			success: function (loginRes) {
				apiWechatLogin({code:loginRes.code}).then(res=>{
					if(res.code===200){
						store.commit('setToken', res.data.authorization)
						store.dispatch('getUserInfo')
						resolve(res.data)
					}
				})
			},
			fail:function(loginErr){
				uni.showToast({
					title:"微信登录失败",
					icon:"none"
				})
			}
		})
	})
	
}

let requestList=[]//存放token失效时请求队列
let isRefreshing=false//是否正在刷新token
/**
 * 刷新token
 */
const refreshToken=async (url,params,method,resolve)=>{
	requestList.push(()=>{resolve(http(url,params,method))})
	if(!isRefreshing){
		isRefreshing=true
		const wechatLoginRes=await wechatLogin()
		console.log(wechatLoginRes);
		// if(!wechatLoginRes.is_bind){
		// 	uni.reLaunch({
		// 		url:'/pages/login'
		// 	})
		// 	isRefreshing=false
		// 	return
		// }
		// 重新请求队列
		requestList.map(MT=>{MT()})
		requestList=[]
		isRefreshing=false
	}
}

let LOADINGCOUNT = 0;// 请求数
const http=(url,params,method)=>{
	// 设置loading
	if(url!='/public/get_share_poster'){
		if (LOADINGCOUNT === 0) {
			uni.showLoading({
				title:'加载中...'
			})
		}
		LOADINGCOUNT++;
	}
	
	
	return new Promise((resolve,reject)=>{
		uni.request({
			url:baseApiUrl+url,
			data:params,
			method:method,
			header:{
				Authorization:store.state.user.token,
				version:'yb11.1'
			},
			success(e) {
				// 接口404
				if(e.statusCode===404){
					setTimeout(()=>{
						uni.showToast({
							title:'network:404',
							icon:'none'
						})
					},0)
					return
				}
				let res
				if(ENV.envVersion==='release'){
					res=JSON.parse(CryptoJS.Des3Decrypt(e.data));//解密
				}else{
					res=e.data
				}
				if(res.code!==200&&res.code!==403&&res.code!==4001&&res.code!==401){
					showError(res)
				}

				// 401 token失效
				if(res.code===401){
					refreshToken(url,params,method,resolve)
					return 
				}
				
				resolve(res)
			},
			fail(error) {
				console.log(error);
				setTimeout(()=>{
					uni.showToast({
						title:'网络异常，稍后重试！',
						icon:'none'
					})
				},0)
			},
			complete() {
				// 关闭loading
				LOADINGCOUNT--;
				if (LOADINGCOUNT === 0) {
				  uni.hideLoading()
				}
			}
		})
	})
}

// get 请求
export const httpGet=(url,params)=>{
	return http(url,params,'GET')
}

// post 请求
export const httpPost=(url,params)=>{
	return http(url,params,'POST')
}