import axios, { AxiosResponse } from 'axios';
import { message } from 'antd';
import config, { getHeaders } from './config';
import LocalStorage from '@/LocalStorage';
import { encryptBase64, encryptWithAes, generateAesKey, decryptWithAes, decryptBase64 } from '@/utils/crypto';
import { encrypt, decrypt } from '@/utils/jsencrypt';
const encryptHeader = 'encrypt-key';
// 创建axios实例
const axiosInstance = axios.create({
    baseURL: config.baseURL,
    timeout: 600000 * 2,// 请求超时20分钟
});

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config: any) => {
        const isEncrypt = config.headers?.isEncrypt === 'true';
        config.headers = {
            'Content-Language': 'zh_CN',
            clientid:'e5cd7e4891bf95d1d19206ce24a7b32e',
            ...config.headers,
            ...getHeaders(),
        };
        if (!navigator.onLine) {
            message.error('网络故障');
        }
             // 当开启参数加密
        if (isEncrypt && (config.method === 'post' || config.method === 'put')) {
            // 生成一个 AES 密钥
            const aesKey = generateAesKey();
            config.headers[encryptHeader] = encrypt(encryptBase64(aesKey));
            config.data = typeof config.data === 'object' ? encryptWithAes(JSON.stringify(config.data), aesKey) : encryptWithAes(config.data, aesKey);
        }
        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.clear();
                    message.error('登录过期');
                    // 使用 window.location 确保跳转生效
                    window.location.replace('/login');
                    return Promise.reject();
                } else {
                    message.error(data.msg||'请求失败');
                    return Promise.reject(data);
                }
            }
        }
    },
    (error) => {// 错误信息
        // HTTP状态码
        const statusCode = error.response?.status;
        if (String(error).includes('timeout')) {
            message.error('请求超时');
        } else {
            if (statusCode === 401) {
                LocalStorage.clear();
                message.error('登录过期');
                // 使用 window.location 确保跳转生效
                window.location.replace('/login');
            } else if (statusCode && statusCode < 500) {
                message.error('请求失败');
            } else {
                message.error('服务异常');
            }
        }
        return Promise.reject();
    }
);

export default axiosInstance;