import axios from "axios";
import { message } from "antd";
import { history } from "umi";

const filterApiList = ['/auth/login'];

const request = axios.create({
    timeout: 60 * 1000 * 30,
});

// 请求拦截器
request.interceptors.request.use(
    (config) => {
        if(filterApiList.includes(config.url)){
            return config;
        }
        const token = localStorage.getItem('token')
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        // 处理请求错误
        return Promise.reject(error);
    }
);

// 响应拦截器
request.interceptors.response.use(
    (response) => {
            if(response.config.url.includes('exam-data/download/downLoadExcel')){
                return response;
            }
            
            if(response.data?.code === 200){
                return response.data;
            }
            if(response.data?.code === 401){
                message.error('登录已过期，请重新登录');
                localStorage.clear();
                history.push('/login');
                return response;
            }
            message.error(response.data?.msg);
            
        return response;
    },
    (error) => {
        
        // 处理响应错误
        return Promise.reject(error);
    }
);

export default request;