import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { localStorage } from "@/utils/storage";
import { getAccessToken } from "@/utils/auth-token";

function resolveMessage(payload: any): string {
    if (!payload) return "";
    if (typeof payload.message === "string" && payload.message) return payload.message;
    if (typeof payload.msg === "string" && payload.msg) return payload.msg;
    if (payload.msg && typeof payload.msg === "object") {
        if (typeof payload.msg.message === "string" && payload.msg.message) return payload.msg.message;
        if (typeof payload.msg.msg === "string" && payload.msg.msg) return payload.msg.msg;
    }
    return "";
}

// 创建 axios 实例
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API || "https://apitest.coinvisoncex.top/api",
    /** 使用 Authorization Bearer，不再依赖 Session Cookie */
    withCredentials: false,
    timeout: 50000,
    headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 防止重复跳转登录页
let isRedirectingToLogin = false;

function redirectToLogin() {
    if (isRedirectingToLogin) return;
    isRedirectingToLogin = true;
    localStorage.clear();
    ElMessageBox.alert("当前页面已失效，请重新登录", "提示", {
        confirmButtonText: "确定",
        callback: () => {
            window.location.reload();
        },
    });
}

// 请求拦截器
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        if (!config.headers) {
            throw new Error(
                `Expected 'config' and 'config.headers' not to be undefined`
            );
        }
        // 1. Token 鉴权：直接发送 token（后端 TokenInterceptor 从 Authorization 头读取后用作 Redis key）
        const token = getAccessToken();
        if (token) {
            config.headers["Authorization"] = token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse) => {
        //console.log('响应拦截start', response, '响应拦截end')
        const { code } = response.data || {};
        const message = resolveMessage(response.data);

        // session 过期或未登录
        if (code === 4000) {
            redirectToLogin();
            return Promise.reject(new Error("SESSION_EXPIRED"));
        }

        // 无操作权限
        if (code === 5000) {
            ElMessage({ message: message || "没有操作权限", type: "error" });
            return Promise.reject(new Error(message || "没有操作权限"));
        }

        if (code == 0) {
            return response.data;
        } else {
            // 响应数据为二进制流处理(Excel导出)
            if (response.data instanceof ArrayBuffer) {
                return response;
            }

            ElMessage({
                message: message || "系统出错",
                type: "error",
            });
            return Promise.reject(new Error(message || "Error"));
        }
    },
    (error) => {
        // 处理网络错误或响应错误
        if (!error.response) {
            ElMessage({
                message: error.message || "网络错误，请检查网络连接",
                type: "error",
            });
            return Promise.reject(new Error(error.message || "网络错误"));
        }
        const { code } = error.response.data || {};
        const message = resolveMessage(error.response.data);
        // HTTP 401/403 或 session 过期
        if (error.response.status === 401 || error.response.status === 403 || code === 4000 || code === "A0230") {
            redirectToLogin();
            return Promise.reject(new Error("SESSION_EXPIRED"));
        }
        ElMessage({
            message: message || "系统出错",
            type: "error",
        });
        return Promise.reject(new Error(message || "Error"));
    }
);

// 导出 axios 实例
export default service;
