import axios from "axios";
import {UniAdapter} from "uniapp-axios-adapter";
import {showToast} from "./uils.js";
import AESCrypto from "./AESCrypto.js";
import {useUserStore} from "../pinia/UserStore/index.js";

let BASEURL = null;

// #ifdef MP-WEIXIN
BASEURL = import.meta.env.VITE_API_URL;
// #endif

// #ifndef MP-WEIXIN
BASEURL = import.meta.env.MODE === 'development' ?
    '/baseApi/api' :
    import.meta.env.VITE_API_URL;
// #endif

export {BASEURL};

const request = axios.create({
    baseURL: BASEURL,
    timeout: 60000,
    adapter: UniAdapter,
});

request.interceptors.request.use(
    (config) => {
        const {token} = useUserStore();

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

        // console.log(`请求拦截器1${config.url}`, config);
        console.log(`请求拦截器2${config.url}`, 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;
    if (code === 401) {
        const {logout} = useUserStore();
        logout();
    }
    if (code !== 1) {
        showToast(msg);
        return Promise.reject(msg);
    }
    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;
