import axios from 'axios'




//请求拦截器
axios.interceptors.request.use(
	config => {
		config.headers.Authorization = 'Bearer ' + sessionStorage.getItem("token")
		config.method = 'POST'
		return config
	},
	err => {
		return Promise.reject(error)
	}
)
//响应拦截器
axios.interceptors.response.use(
	async response => {
			const res = response.data
          console.log(response)
			if (res.code !== 200) {
				if (res.code == 10001) { //token验证出错
					window.location.href = "./#/login"
				}
				if (res.code == 10002) { //token验证超时
					//console.log(response.config);
					var ss = ''
					await TokenRefresh().then(async data => {
						// 	// 使用最外层请求的返回值
						// 	//console.log(data)
						if (data == false) {
							window.location.href = "./#/login"
						}
						if (data == true) {
							//	console.log("刷新成功");
							ss = await axios(response.config)
							//	 console.log("再次支持上此操作");

						}
					}).catch(error => {
						console.log(error);
					});
					//await TT();
					return ss
					//console.log('我是后面的');

				}
				if (res.code == 10003) { //无访问此接口权限
					ElMessageBox.confirm(
							'无权限',
							'通知', {
								confirmButtonText: 'OK',
								cancelButtonText: 'Cancel',
								type: 'warning',
								showCancelButton: false,
								showClose: false,
							}
						)
						.then(() => {
							// window.location.href = "/#/login"
						})
						.catch(() => {

						})
					return false
				}
				return Promise.reject(res.msg || 'Error').catch(err => {
					console.log(err)
				})

			} else { //成功返回数据

				return res


			}
		},
		error => {
			return Promise.reject(error)
		}
)
const instance = axios.create({
	// 其他配置项
	// ...
	// 禁用请求拦截器
	interceptors: false
});

function TokenRefresh() {

	console.log("执行：TokenRefresh")
	return new Promise((resolve, reject) => {
		instance({
			method: 'post',
			url: import.meta.env.VITE_APP_API + 'tokenRefresh',
			headers: {
				Authorization: 'Bearer ' + sessionStorage.getItem("refreshToken")
			},
			data: {}
		}).then(function(res) {
			//	console.log('获取到新token');
			if (res.data.status) {
				sessionStorage.setItem('token', res.data.token);
				sessionStorage.setItem('refreshToken', res.data.refresh_token);

				resolve(true);
			} else {

				resolve(false);
			}
		});
	})

}

export  default axios