// 引入 axios@1.4.0（确保已引入 axios.min.js）
if (!window.axios) throw new Error("请先引入 axios@1.4.0 脚本！");


const service = axios.create({
    baseURL: "",
    timeout: 5000,
    headers: {
        "Content-Type": "application/json;charset=utf-8"
    }
});

// -------------------------- 请求拦截器：自动携带 Token --------------------------
service.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem("token");

        if (token) {
            config.headers["Authorization"] = token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// -------------------------- 响应拦截器：统一处理结果 --------------------------
service.interceptors.response.use(
    (response) => {
        return response.data;
    },
    (error) => {
        let errorMsg = "请求失败，请稍后重试";

        if (error.response) {
            switch (error.response.status) {
                case 401:
                    errorMsg = "Token 已过期，请重新登录";
                    localStorage.removeItem("token");
                    window.location.href = "/admin/login.html";
                    break;
                case 403:
                    errorMsg = "暂无权限访问该接口";
                    break;
                case 500:
                    errorMsg = "服务器内部错误";
                    break;
                default:
                    errorMsg = error.response.data?.msg || errorMsg;
            }
        } else if (error.request) {
            errorMsg = "网络异常，请检查网络连接";
        }
        console.error("接口请求错误：", errorMsg);
        return Promise.reject(error);
    }
);

// -------------------------- 封装常用请求方法（get/post/put/delete） --------------------------
const request = {
    // GET
    get(url, params = {}) {
        return service.get(url, { params });
    },

    // POST
    post(url, data = {}) {
        return service.post(url, data);
    },

    // PUT
    put(url, data = {}) {
        return service.put(url, data);
    },

    // DELETE
    delete(url, params = {}) {
        return service.delete(url, { params });
    }
};

window.request = request;