const BASE_URL = 'http://192.168.0.222:8088'
// const BASE_URL = 'http://192.168.0.145:8088'   //
// const BASE_URL = 'https://api.xyyxt.net'  //
import store from '@/store/index.js'
import api from './api.js'
var num = 1
export const myRequest = (options) => {
	// uni.showLoading({
	// 	title:'拼命加载中...'
	// })
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data,
			header: options.noToken ? {} : {
				AuthorizationToken: 'WX ' + uni.getStorageSync('token')
			},
			success: async (res) => {
				if (res.data.code == 401) {
					if (num <= 3) {
						if (!uni.getStorageSync('union_id')) {
							uni.navigateTo({
								url: '/pages/login/login'
							});
						} else {
							num++
							res = await doRequest(options)
						}

					};
					return
				}
				resolve(res)
			},
			fail: (err) => {
				uni.showToast({
					title: "请求接口失败",
					icon: 'none'
				})
				reject(JSON.stringify(err))
			}
			// complete:()=>{
			// 	uni.hideLoading()
			// }
		})
	})
	async function doRequest(response) {
		var datas = {
			url: '/refreshToken/' + uni.getStorageSync('union_id'),
			method: 'get',
			noToken: true
		}
		const res = await myRequest(datas)
		if (res.data.code === 200) {
			uni.setStorageSync('token', res.data.data.token)

			var userInfo = {
				url: '/getInfo',
				method: 'get',
			}
			const resUser = await myRequest(userInfo)
			if (resUser.data.code === 200) {
				store.state.userInfo = resUser.data.data
			}
			let onset = await myRequest(response)
			return onset
		} else {
			uni.navigateTo({
				url: '/pages/login/login'
			});
		}
	}
}
