import axios, { AxiosResponse } from 'axios';

// 创建axios实例
const axiosInstance = axios.create({
    baseURL: '/bigmodel-api',
    timeout: 300000,// 请求超时5分钟
});

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config) => {
        const userInfoStr = localStorage.getItem('userInfo');
        if (userInfoStr) {
            const userInfo = JSON.parse(userInfoStr);
            if (userInfo.token) {
                config.headers['Authorization'] = userInfo.token;
            }
        }
        return config;
    }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
    (response: AxiosResponse) => {// 成功信息
        const { config, data } = response;
        if (config.responseType === 'blob') {
            return Promise.resolve(data);
        } else {
            if (data.code === 200) {// 成功
                return Promise.resolve(data);
            } else {// 失败
                if (data.code === 401) {
                    localStorage.removeItem('userInfo');
                    const originUrl = window.location.origin;
                    window.open(originUrl, '_self');
                }
                return Promise.reject(data);
            }
        }
    },
    (error) => {// 错误信息
        return Promise.reject();
    }
);

export default axiosInstance;