import { create } from 'zustand';
import { message } from 'antd';
import { apis } from '@/apis';

interface PageState {
    pageNum: number;
    pageSize: number;
    total: number;
}

interface UsageStatisticsState {
    query: any;
    listLoading: boolean;
    list: any[];
    page: PageState;
    statistics: any;
}

interface UsageStatisticsActions {
    setQuery: (query: any) => void;
    setListLoading: (loading: boolean) => void;
    setList: (list: any[]) => void;
    setPage: (page: PageState) => void;
    setStatistics: (statistics: any) => void;
}

export type UsageStatisticsStore = UsageStatisticsState & UsageStatisticsActions & {
    fetchStatistics: () => Promise<void>;
    fetchUsageList: () => Promise<void>;
};

const initialState: UsageStatisticsState = {
    query: undefined,
    listLoading: false,
    list: [],
    page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
    },
    statistics: null,
};

export const useUsageStatisticsStore = create<UsageStatisticsStore>((set, get) => ({
    ...initialState,
    
    setQuery: (query) => set({ query }),
    
    setListLoading: (loading) => set({ listLoading: loading }),
    
    setList: (list) => set({ list }),
    
    setPage: (page) => set({ page }),
    
    setStatistics: (statistics) => set({ statistics }),
    
    fetchStatistics: async () => {
        set({ listLoading: true });
        try {
            const res: any = await apis.fetchUsageStatistics();
            if (res.code === 200) {
                set({ statistics: res.data });
            }
        } catch (error) {
            console.error('获取统计数据失败:', error);
        } finally {
            set({ listLoading: false });
        }
    },
    
    fetchUsageList: async () => {
        set({ listLoading: true });
        try {
            const { query, page } = get();
            const res: any = await apis.fetchUsageList({
                ...query,
                pageNum: page.pageNum,
                pageSize: page.pageSize,
            });
            
            if (res.code === 200) {
                set({
                    list: res.rows || [],
                    page: {
                        ...page,
                        total: res.total || 0,
                    },
                });
            }
        } catch (error) {
            console.error('获取使用列表失败:', error);
        } finally {
            set({ listLoading: false });
        }
    },
}));

export default useUsageStatisticsStore;
