import axios from 'axios';
import { ElMessage } from "element-plus";

const basic_url = import.meta.env.VITE_BASE_URL;

const axiosInstance = axios.create({
    baseURL: basic_url,
    timeout: 5000
});

const handleError = (error: any) => {
    console.log(error);
    if (error.response) {
        ElMessage.error(`请求失败，服务器返回: ${error.response.data}`);
    } else if (error.request) {
        ElMessage.error("请求未收到响应，请检查接口运行状态");
    }
    throw new Error("网络不通畅，请检查您的网络连接或服务器状态");
};

const validateResponse = (res: any) => {
    const result = res.data;
    if (result.code !== 200) {
        ElMessage.error(result.message || '请求失败');
        return Promise.reject(result);
    }
    return result;
};

function get(url: string, params: Record<string, any>): Promise<any>;
function get(url: string): Promise<any>;

function get(url: string, params: Record<string, any> = {}) {
    console.log("开始GET请求", basic_url + url, "参数：", params);
    return axiosInstance.get(url, { params })
        .then(validateResponse)
        .catch(handleError);
}

const post = (url: string, data: any = null, config: any = {}) => {
    console.log("开始POST请求", url, "参数：", data, "配置：", config);

    if (config.params) {
        // 如果传入 config.params，则作为 URL 参数
        return axiosInstance.post(url, data, { params: config.params })
            .then(validateResponse)
            .catch(handleError);
    } else {
        // 默认 POST JSON
        return axiosInstance.post(url, data)
            .then(validateResponse)
            .catch(handleError);
    }
};

const put = (url: string, data: any) => {
    console.log("开始PUT请求", basic_url + url, "参数：", data);
    return axiosInstance.put(url, data)
        .then(validateResponse)
        .catch(handleError);
};

const del = (url: string, params: {}) => {
    console.log("开始DELETE请求", basic_url + url, "参数：", params);
    return axiosInstance.delete(url, { params })
        .then(validateResponse)
        .catch(handleError);
};

const requestNotImplemented = (method: string) => {
    ElMessage.error(`请求方法 ${method} 未实现`);
    throw new Error(`请求方法 ${method} 未实现`);
};

const request = (method: string, url: string, paramsOrData: any) => {
    switch (method.toLowerCase()) {
        case 'get': return get(url, paramsOrData);
        case 'post': return post(url, paramsOrData);
        case 'put': return put(url, paramsOrData);
        case 'delete': return del(url, paramsOrData);
        default: return requestNotImplemented(method);
    }
};

export default { get, post, put, del, request };
