import axios from 'axios';
import AESCrypto from "./AESCrypto.js";
import {Message} from '@arco-design/web-vue';
import {useUserStore} from "../pinia/UserStore/index.js";
import {useSystemStore} from "../pinia/SystemStore/index.js";

const excludeURL = [
    '/admin/admin/menu',
    '/index/business/getMenu',
    '/admin/login/login',
];

export const BASEURL = import.meta.env.MODE === 'development' ? '/baseApi' : import.meta.env.VITE_API_URL;

// 创建 Axios 实例
const request = axios.create({
    baseURL: BASEURL, // 替换为你的基础 URL
    timeout: 20000, // 请求超时设置
});

// 请求拦截器
request.interceptors.request.use((config) => {
    const {token} = useUserStore();

    // 如果 token 存在，则将其添加到请求头中
    if (token) {
        config.headers['Access-Token'] = token;
    }

    console.log(`请求拦截器`, config, config.data);

    if (!config.UN_AES) {
        const {context, iv} = AESCrypto.encrypt(JSON.stringify(config.data));

        config.data = {
            requestData: context, iv: iv,
        };
    }

    return config;
}, (error) => {
    return Promise.reject(error);
});

// 响应拦截器
request.interceptors.response.use((response) => {
    const {data: {msg, code, data}, config: {url}} = response;
    console.log(response)
    if (code === 401) {
        const {logout} = useUserStore();
        logout();
    }
    if (code !== 1) {
        if (!response.config.headers.message) {
            Message.error(msg);
        }
        return Promise.reject(msg);
    }

    const {updateRouterTag} = useSystemStore();

    if (!excludeURL.includes(response.config.url)) {
        updateRouterTag();
    }

    if (!data.data) {
        return {msg, code, data}
    } else {
        const resp = JSON.parse(AESCrypto.decrypt(data.data, data.iv));
        console.log(`接口${url}返回`, resp);
        return {data: resp};
    }
}, (error) => {
    if (error.response) {
        return Promise.reject(error.response.data); // 返回错误信息
    } else { // 网络错误
        return Promise.reject(error.message);
    }
});

export default request; // 导出 Axios 实例
