import axios, { AxiosResponse } from 'axios';
import { message } from 'antd';

import { encryptBase64, encryptWithAes, generateAesKey, decryptWithAes, decryptBase64 } from '@/app/utils/crypto';
import { encrypt, decrypt } from '@/app/utils/jsencrypt';
const encryptHeader = 'encrypt-key';
import {replaceUrl} from '@/app/utils/index'

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

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config) => {
        const isEncrypt = config.headers?.isEncrypt === 'true';
        
        config.headers['Content-Language'] = 'zh_CN';
        
        const userInfoStr = localStorage.getItem('userInfo');
        const token = localStorage.getItem('token');
        config.headers['clientid'] = 'e5cd7e4891bf95d1d19206ce24a7b32e';
        if (userInfoStr) {
            const userInfo = JSON.parse(userInfoStr);
            if (userInfo.token) {
                config.headers['Authorization'] = 'Bearer '+userInfo.token;
            }
        }else if (token) {
            config.headers['Authorization'] = 'Bearer '+token;
        }
         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 {// 失败
                // console.log('请求失败',config,'--data',data)
                if(data.msg||data.code){
                    message.error(data.msg || `请求失败`);
                }
                if (data.code === 401) {
                    localStorage.clear();
                    window.sessionStorage.clear();
                    window.location.replace(`${replaceUrl}?redirectUrl=${encodeURIComponent(window.location.href)}`);
                    // const originUrl = window.location.origin;
                    // window.open(originUrl + '/#/login', '_self');
                }
                return Promise.reject(data);
            }
        }
    },
    (error) => {// 错误信息
        return Promise.reject();
    }
);

export default axiosInstance;