import type { AxiosResponse, RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max';
import jwt from '@/utils/Token'
import dayjs from 'dayjs'
import { message } from 'antd';
import { history } from '@umijs/max';

const handleError = (error: any) => {
	if (!error.response) return;
	 console.log('error.response',error.response);
	switch (error.response.status) {
		case 400:
			message.error('当前请求无法被服务器理解！');
			break;
		case 401:
			message.error('登录过期，请登录后重试');
			history.push('/user/login');
			break;
		case 404:
			message.error('请求地址错误！');
			break;
		case 408:
			message.error('请求超时！');
			break;
		case 500:
			message.error(error.response.data.message || '服务器端的源代码出现错误！');
			break;
		case 502:
			message.error('网关或者代理工作的服务器出现错误');
			break;
		case 504:
			message.error('504：后端服务未启动或代理错误！');
			break;
		default:
			message.error('服务端异常：' + error.message);
	}
}
/**
 * @name 错误处理
 * pro 自带的错误处理， 可以在这里做自己的改动
 * @doc https://umijs.org/docs/max/request#配置
 */
export const errorConfig: RequestConfig<MyResponse.Content> = {

	// 请求拦截器
	requestInterceptors: [
		(config: RequestOptions) => {

			if (process.env.NODE_ENV !== 'development') {
				config.url = config.url?.replace("/api", '/api/api')
			}
			// 拦截请求配置，进行个性化处理。
			const userToken = localStorage.getItem('USER_TOKEN');
			const x_Token = localStorage.getItem('USER_X_TOKEN');
			if (userToken && config.headers) {
				const userInfo = JSON.parse(userToken);
				const x_Tokens = JSON.parse(x_Token!);
				const jxxx = jwt.ecryptJWT(userToken);
				// const resxx = jwt.ecryptJWT(x_Token!);
				// console.log('我是刷新的',dayjs.unix(resxx.exp).format('YYYY-MM-DD HH:mm:ss'),dayjs().format('YYYY-MM-DD HH:mm:ss'));
				// console.log(dayjs.unix(jxxx.exp).format('YYYY-MM-DD HH:mm:ss'),dayjs().format('YYYY-MM-DD HH:mm:ss'));
			 	const DD:number =	(jxxx.exp-dayjs().unix())/60;
				if (DD<2) {
					config.headers["X-Authorization"] = 'Bearer ' + x_Tokens;
				}
				config.headers.Authorization = 'Bearer ' + userInfo;
			}
			return config;
		},
	],

	// 响应拦截器
	responseInterceptors: [
		[
			(response: AxiosResponse) => {
			const userToken = response.headers["access-token"]
			if (userToken) {
					localStorage.setItem('USER_TOKEN', JSON.stringify(userToken));
			}
			const xAuth = response.headers["x-access-token"];	
			 if (xAuth) {
				localStorage.setItem('USER_X_TOKEN', JSON.stringify(xAuth));
			 }
				return response;
			},
			(error: any) => {
				handleError(error);
				return Promise.reject(error);
			}
		]
	],
};




