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

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

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

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

export type ContentManagementStore = ContentManagementState & ContentManagementActions & {
    fetchContentList: () => Promise<void>;
};

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

export const useContentManagementStore = create<ContentManagementStore>((set, get) => ({
    ...initialState,
    
    setQuery: (query) => set({ query }),
    
    setListLoading: (loading) => set({ listLoading: loading }),
    
    setList: (list) => set({ list }),
    
    setPage: (page) => set({ page }),
    
    fetchContentList: async () => {
        set({ listLoading: true });
        try {
            const { query, page } = get();
            const res: any = await apis.fetchContentList({
                ...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 useContentManagementStore;
