import { showToast } from '../components/common.js'
let authToken = ''

export function toLogin(url) {
	return new Promise((resolve, reject) => {
		let saveTime = uni.getStorageSync('saveTime')
		let expires_in = uni.getStorageSync('expires_in')
		let token = uni.getStorageSync('token')
		if(url.indexOf('api/v1') !== -1 && ((saveTime && expires_in && Date.now() > saveTime + expires_in) || !expires_in || !saveTime || !token)) {
			uni.redirectTo({
				url: '/pages/user/login'
			})
			reject()
		} else {
			resolve()
		}
	})
}

export function get (url = '', data = {}, flag = true) {
	return new Promise(async (resolve, reject) => {
		let orgin_shop_id = (uni.getStorageSync('orgin_shop_id') || 0) * 1
		let shop_id = (uni.getStorageSync('shop_id') || 0) * 1
		let appId = uni.getStorageSync('appId')
		if(!shop_id || (orgin_shop_id && orgin_shop_id != shop_id) || (!appId && !url.includes('/live/shop') && !url.includes('login/weChat/webRedirectUrl'))) {
			uni.removeStorageSync('token')
			uni.removeStorageSync('saveTime')
			uni.removeStorageSync('expires_in')
			uni.redirectTo({
				url: '/pages/user/login'
			})
			reject()
		}
		if(!url.includes('/pay/') && !url.includes('/login/weChat/webRedirectUrl') && !url.includes('/live/shop')) {
			await toLogin(url)
		}
		uni.request({
			url: url,
			data: data,
			method: 'GET',
			header: {
				Authorization: uni.getStorageSync('token') || authToken,
				accept: "application/json",
				appid: uni.getStorageSync('appId'),
				'X-App-Type': 'h5'
			},
			success: res => {
				if (res.statusCode === 200 || res.statusCode === 201) {
					resolve(res.data)
				} else if (res.statusCode === 404){
					showToast(res.data.message || res.data.error)
					reject(res.data.message || res.data.error)
					setTimeout(function() {
						uni.navigateBack({delta: 1})
					}, 1000)
				} else if(res.statusCode === 401 && flag) {
					get(url, data, false)
				} else if(res.statusCode === 429) {
					resolve(res.data)
					showToast('系统繁忙，请稍后重试')
				} else {
					let msg = res.data.message || res.data.error
					if(msg) {
						if(msg == 'Unauthenticated') {
							uni.removeStorageSync('token')
							uni.removeStorageSync('saveTime')
							uni.removeStorageSync('expires_in')
							uni.redirectTo({
								url: '/pages/user/login'
							})
						}
					}
					reject(msg)
				}
			}, 
			fail:(err)=>{
				console.log('fail', err)
			},
			complete: async(complete) => {
			}
		})
	})
}

export function getReq (url = '', data = {}, flag = true) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: data,
			method: 'GET',
			header: {
				Authorization: uni.getStorageSync('token') || authToken,
				accept: "application/json",
				appid: uni.getStorageSync('appId'),
				'X-App-Type': 'h5'
			},
			success: res => {
				if (res.statusCode === 200 || res.statusCode === 201) {
					resolve(res.data)
				} else if(res.statusCode === 401 && flag) {
					reject(res.data)
					getReq(url, data, false)
				} else if (res.statusCode === 401 && !flag){
					showToast(res.data.message || res.data.error)
					resolve(res.data)
				} else if (res.statusCode === 404){
					reject(res.data.message)
				} else if(res.statusCode === 429) {
					showToast('系统繁忙，请稍后重试')
					resolve(res.data)
				} else {
					let msg = res.data.message || res.data.error
					if(msg) {
						if(msg == 'Unauthenticated') {
							uni.removeStorageSync('token')
							uni.removeStorageSync('saveTime')
							uni.removeStorageSync('expires_in')
							uni.redirectTo({
								url: '/pages/user/login'
							})
						}
					}
					reject(msg)
					reject(res.data.message || res.data.error)
				}
			},
			fail:(err)=>{
				
			},
			complete: async(complete) => {
			}
		})
	})
}

export function post (url = '', data = {}, requestType = 'POST', flag = true) {
	return new Promise(async(resolve, reject) => {
		let orgin_shop_id = (uni.getStorageSync('orgin_shop_id') || 0) * 1
		let shop_id = (uni.getStorageSync('shop_id') || 0) * 1
		let appId = uni.getStorageSync('appId')
		if(!shop_id || (orgin_shop_id && orgin_shop_id != shop_id) || (!appId && !url.includes('/live/shop') && !url.includes('login/weChat/webRedirectUrl'))) {
			uni.removeStorageSync('token')
			uni.removeStorageSync('saveTime')
			uni.removeStorageSync('expires_in')
			uni.redirectTo({
				url: '/pages/user/login'
			})
			reject()
		}
		
		if(!url.includes('order/create') && !url.includes('user/vip') && !url.includes('auth/login') && !url.includes('live/liveIm/config')) {
			await toLogin(url)
		}
		uni.request({
			method: requestType,
			url: url,
			data,
			header: {
				Authorization: uni.getStorageSync('token') || authToken,
				accept: "application/json",
				appid: uni.getStorageSync('appId'),
				'X-App-Type': 'h5'
			},
			success: res => {
				if (res.statusCode === 200 || res.statusCode === 201) {
					resolve(res.data)
				} else if (res.statusCode === 404){
					showToast(res.data.message || res.data.error)
					reject(res.data.message)
				} else if(res.statusCode === 401 && flag) {
					post(url, data, requestType, false)
				} else if(res.statusCode === 429) {
					showToast('系统繁忙，请稍后重试')
					resolve(res.data)
				} else {
					let msg = res.data.message || res.data.error
					if(url.indexOf('decrypt/data') === -1 && msg == 'Unauthenticated') {
						uni.removeStorageSync('token')
						uni.removeStorageSync('saveTime')
						uni.removeStorageSync('expires_in')
						uni.redirectTo({
							url: '/pages/user/login'
						})
					}
					reject(msg)
				}
			},
			fail:(err) => {
				
			},
			complete: async (complete) => {
			}
		})
	})
}

