import {error} from "echarts/types/src/util/log";

const API_BASE_URL = '/api/x';
// const API_TIMESTAMP = 'i1ShCjbpxC5'; // 页面应用代码

export const fetchList = async (params: { pageSize?: number, [key: string]: any } = {}) => {
    const query = new URLSearchParams();
    if (params.pageSize) query.append('pageSize', params.pageSize.toString());
    // 添加其他查询参数
    Object.keys(params).forEach(key => {
        if (key !== 'pageSize' && params[key] !== undefined) {
            query.append(key, params[key]);
        }
    });
    try {
        const response = await fetch(`${API_BASE_URL}?t=i1XuaQDK9zw&${query.toString()}`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
        });
        return await response.json();
    } catch (error) {
        console.error('获取列表失败:', error);
        throw error;
    }
};

// 获取单个数据项
export const fetchItem = async (id: string) => {
    try {
        //console.log(id+"id 给了没")
        const response = await fetch(`${API_BASE_URL}/${id}?t=i1XuaQDK9zw`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
            },
        });
        //console.log(await response.json()+"chadaodeshujv")
        return await response.json();
    } catch (error) {
        console.error('获取数据项失败:', error);
        throw error;
    }
};

// 创建数据

export const createItem = async (data: any) => {
    const response = await fetch(`${API_BASE_URL}?t=i1XuaQDK9zw`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
    });
    const result = await response.json();
    if (!response.ok) {
        throw new Error(result.msg || '创建失败');
    }
    return result;
};
// 更新数据
export const updateItem = async (id: string, data: any) => {
    try {
        const response = await fetch(`${API_BASE_URL}/${id}?t=i1XuaQDK9zw`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        });
        return await response.json();
    } catch (error) {
        console.error('更新数据失败:', error);
        throw error;
    }
};
export const deleteItem = async (ids: string | string[]) => {
    try {
        // 确保ID为数组格式
        console.log(ids+"llllllllllllllll")
        const idArray = Array.isArray(ids) ? ids : [ids];

        if (idArray.length === 0) {
            throw new Error('删除操作需要至少一个ID');
        }

        // 构建查询参数（符合后端要求的格式）
        const query = new URLSearchParams();
        query.append('t', 'i1XuaQDK9zw'); // 固定参数

        // 添加数组参数（生成 id[]=1&id[]=2 格式）
        idArray.forEach(id => query.append('id[]', id));
        console.log(query.toString()+"aaaaaaaaaaaaaaaaaaaaaa")
        const response = await fetch(`${API_BASE_URL}?${query.toString()}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
            // DELETE 请求通常不需要 body
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.msg || '删除失败');
        }

        return await response.json();
    } catch (error) {
        console.error('删除失败:', error);
        throw error;
    }
};

