// api.ts
import axios from 'axios';
import { localStg } from '@/utils/storage';

let baseUrl = import.meta.env.VITE_SERVICE_BASE_URL

// 封装网络请求的接口
export const apiRequest = async (method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, data?: any) => {
    let url = baseUrl + path;
    const token = localStg.get('token'); // 获取 token
    try {
        const response = await axios({
            method,
            url,
            data,
            headers: {
                Authorization: `Bearer ${token}`, // 添加 Authorization 头
            },
        });
        return response.data; // 返回响应数据
    } catch (error) {
        throw new Error('请求失败'); // 抛出错误
    }
};

export const apiRequestGet = async (path: string, params?:any) => {
    let url = baseUrl + path;
    const token = localStg.get('token'); // 获取 token
    try {
        return axios.get(
            url,
            {
                headers: {
                    Authorization: `Bearer ${token}`, // 添加 Authorization 头
                },
                params: params,
            }
        );
    } catch (error) {
        throw new Error('请求失败'); // 抛出错误
    }
};

export const apiRequestPost = async (path: string,data:any, params?:any) => {
    let url = baseUrl + path;
    const token = localStg.get('token'); // 获取 token
    try {
        return axios.post(
            url,
            data,
            {
                headers: {
                    Authorization: `Bearer ${token}`, // 添加 Authorization 头
                },
                params: params,
            }
        );
    } catch (error) {
        throw new Error('请求失败'); // 抛出错误
    }
};

export default apiRequest;