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

interface TopData {
    todayNum: number;
    totalNum: number;
    successRate: number;
    bjNum: number;
    bjYNum: number;
}

interface ChartData {
    [key: string]: string | number;
}

interface HomeState {
    monthDay: string;
    topData: TopData;
    onlineUserData: ChartData[];
    conversationData: ChartData[];
    conversationDetailData: ChartData[];
    overviewTokenData: ChartData[];
}

interface HomeActions {
    setMonthDay: (monthDay: string) => void;
    setTopData: (topData: TopData) => void;
    setOnlineUserData: (data: ChartData[]) => void;
    setConversationData: (data: ChartData[]) => void;
    setConversationDetailData: (data: ChartData[]) => void;
    setOverviewTokenData: (data: ChartData[]) => void;
}

export type HomeStore = HomeState & HomeActions & {
    fetchTopData: () => Promise<void>;
    fetchOverviewData: () => Promise<void>;
    init: () => Promise<void>;
};

const initialState: HomeState = {
    monthDay: 'day',
    topData: {
        todayNum: 0,
        totalNum: 0,
        successRate: 0,
        bjNum: 0,
        bjYNum: 0,
    },
    onlineUserData: [],
    conversationData: [],
    conversationDetailData: [],
    overviewTokenData: [],
};

export const useHomeStore = create<HomeStore>((set, get) => ({
    ...initialState,
    
    setMonthDay: (monthDay) => set({ monthDay }),
    
    setTopData: (topData) => set({ topData }),
    
    setOnlineUserData: (data) => set({ onlineUserData: data }),
    
    setConversationData: (data) => set({ conversationData: data }),
    
    setConversationDetailData: (data) => set({ conversationDetailData: data }),
    
    setOverviewTokenData: (data) => set({ overviewTokenData: data }),
    
    fetchTopData: async () => {
        try {
            const res: any = await apis.fetchTopData();
            if (res.code === 200) {
                set({ topData: res.data });
            }
        } catch (error) {
            console.error('获取顶部数据失败:', error);
        }
    },
    
    fetchOverviewData: async () => {
        const { monthDay } = get();
        
        try {
            // 活跃用户数
            const resUser: any = await apis.fetchOnlineUserData({ monthDay });
            if (resUser.code === 200) {
                const flagData = resUser.data?.map((item: any) => ({
                    [monthDay]: monthDay === 'day' 
                        ? item.createTime.split(' ')[0].split('-').slice(1).join('-')
                        : item.createTime.split(' ')[0].split('-').slice(0, 2).join('-'),
                    value: Number(item.onlineNum),
                }));
                set({ onlineUserData: flagData || [] });
            }
            
            // 会话数据
            const resConer: any = await apis.fetchConversationData({ monthDay });
            if (resConer.code === 200) {
                const flagData = resConer.data?.map((item: any) => ({
                    [monthDay]: monthDay === 'day'
                        ? item.createTime.split(' ')[0].split('-').slice(1).join('-')
                        : item.createTime.split(' ')[0].split('-').slice(0, 2).join('-'),
                    value: Number(item.conversationNum),
                }));
                set({ conversationData: flagData || [] });
            }
            
            // 互动数据
            const resConver: any = await apis.fetchConversationDetailData({ monthDay });
            if (resConver.code === 200) {
                const flagData = resConver.data?.map((item: any) => ({
                    [monthDay]: monthDay === 'day'
                        ? item.createTime.split(' ')[0].split('-').slice(1).join('-')
                        : item.createTime.split(' ')[0].split('-').slice(0, 2).join('-'),
                    value: Number(item.conversationNum),
                }));
                set({ conversationDetailData: flagData || [] });
            }
            
            // Token 数据
            const resToken: any = await apis.fetchOverviewTokenData({ monthDay });
            if (resToken.code === 200) {
                const flagData = resToken.data?.map((item: any) => ({
                    [monthDay]: monthDay === 'day'
                        ? item.createTime.split(' ')[0].split('-').slice(1).join('-')
                        : item.createTime.split(' ')[0].split('-').slice(0, 2).join('-'),
                    value: Number(item.tokenSpeed),
                }));
                set({ overviewTokenData: flagData || [] });
            }
        } catch (error) {
            console.error('获取概览数据失败:', error);
        }
    },
    
    init: async () => {
        await get().fetchTopData();
        await get().fetchOverviewData();
    },
}));

export default useHomeStore;
