import Request from 'luch-request'

/**
 * 阿里云2ce15942be1999220210d9837b01d37e
 */
// let	baseURL = 'http://8.135.18.59:1889/api/'
// let tokenUrl=baseURL+"/blade-auth/oauth/token?tenant_id=000000&username=admin&password=1ac87efdaf318558f05d1840a94bdd94&grant_type=password&scope=all&type=account"
let baseURL = "http://192.168.1.120"
let tokenUrl = baseURL +
	"/blade-auth/oauth/token?tenant_id=000000&password=21232f297a57a5a743894a0e4a801fc3&username=admin&grant_type=password"

//获取tenantId
const getTenantId = () => {
	let tenantId = null
	try {
		tenantId = uni.getStorageSync('lifeData').vuex_tenantId
	} catch (e) {}
	return tenantId
}
//获取token
const getTokenStorage = () => {
	let token = ''
	try {
		token = uni.getStorageSync('token')
	} catch (e) {}
	return token
}
const http = new Request()
http.setConfig((config) => {
	/* 设置全局配置 */
	config.baseURL = baseURL /* 根域名不同 */
	config.header = {
		...config.header,
	}
	return config
})
http.interceptors.request.use((config) => {
	console.log();
	/* 请求之前拦截器。可以使用async await 做异步操作 */
	config.header = {
		...config.header,
		"Blade-Auth": getTokenStorage()
	}
	let tenantId=getTenantId()
	
	if (config.method == 'POST' && config.data && tenantId) {
		config.data.tenantId=tenantId
	}
	
	
	return config
}, (config) => {
	return Promise.reject(config)
})
// 是否正在刷新的标记
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = []
http.interceptors.response.use(async (response) => {
	/* 请求之后拦截器。可以使用async await 做异步操作  */
	let data = response.data
	if (data.code && data.code != 200) {
		uni.showToast({
			icon: 'none',
			title: data.msg
		})
		return Promise.reject(response)
	}
	return response
}, async (err) => { // 请求错误做点什么
	//toekn过期处理
	if (err.data.code == 401) {
		let {
			config
		} = err
		if (!isRefreshing) {
			isRefreshing = true
			let token = uni.getStorageSync('token')
			let [, res] = await uni.request({
				url: tokenUrl,
				method: 'POST',
				header: {
					Authorization: "Basic c2FiZXI6c2FiZXJfc2VjcmV0"

				},
			})
			//否则保存新的token
			token = res.data.token_type + " " + res.data.access_token
			uni.setStorageSync('token', token)
			requests.forEach(cb => cb())
			// 重试完了清空这个队列
			requests = []
			isRefreshing = false
			return http.request(config)
		} else {
			return new Promise((resolve) => {
				// 将resolve放进队列，用一个函数形式来保存，等token刷新后直接执行
				requests.push(() => {
					resolve(http.request(config))
				})
			})
		}
	}
	if (err.data.code == 500) {
		uni.hideLoading()
		uni.showModal({
			title: '提示',
			content:err.data.msg,
			showCancel:false,
			confirmColor: '#2979ff' ,
		});
	}
	return Promise.reject(err)
})
export {
	http
}
