// api.ts
import axios, { AxiosInstance, AxiosResponse, AxiosError } from 'axios';
import { localStg } from '@/utils/storage';
import { useRouter } from 'vue-router';

// 环境变量获取 baseUrl
const baseUrl = import.meta.env.VITE_SERVICE_BASE_URL;

// 创建 axios 实例
const apiClient: AxiosInstance = axios.create({
    baseURL: baseUrl,
    timeout: 10000, // 设置请求超时时间
    headers: {
        'Content-Type': 'application/json',
    },
});

// 请求拦截器 - 添加 token
apiClient.interceptors.request.use(
    (config) => {
        const token = localStg.get('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => Promise.reject(error)
);

// 响应拦截器 - 处理 401 等错误状态码
apiClient.interceptors.response.use(
    (response: AxiosResponse) => {
        return response; // 直接返回响应数据
    },
    (error: AxiosError) => {
        if (error.response) {
            const status = error.response.status;
            if (status === 401) {
                // 清除本地储存的token
                localStg.remove('token');
                // 获取路由实例并重定向到登录页面
                const router = useRouter();
                router.push('/login');
                return Promise.reject(new Error('未授权，请重新登录'));
            }
            // 可以在这里处理其他状态码
            return Promise.reject(new Error(`请求失败：${status}`));
        }
        return Promise.reject(error);
    }
);

// 封装请求方法
export const apiRequest = {
    get: <T>(url: string, params?: Record<string, any>): Promise<T> => {
        return apiClient.get(url, { params });
    },

    post: <T>(
        url: string,
        data?: Record<string, any>,
        params?: Record<string, any>
    ): Promise<T> => {
        return apiClient.post(url, data, { params });
    },

    put: <T>(
        url: string,
        data?: Record<string, any>,
        params?: Record<string, any>
    ): Promise<T> => {
        return apiClient.put(url, data, { params });
    },

    delete: <T>(url: string, params?: Record<string, any>): Promise<T> => {
        return apiClient.delete(url, { params });
    },
};

export default apiClient;