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

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

interface QuestionAnswerInfoState {
    sourceData: any[];
    pageLoading: boolean;
    page: PageState;
}

interface QuestionAnswerInfoActions {
    setPageLoading: (loading: boolean) => void;
    setPage: (page: PageState) => void;
    setSourceData: (data: any[]) => void;
}

export type QuestionAnswerInfoStore = QuestionAnswerInfoState & QuestionAnswerInfoActions & {
    init: () => void;
    fetchUserListApi: (userName?: any, userNickName?: any, userType?: any) => Promise<void>;
};

const initialState: QuestionAnswerInfoState = {
    sourceData: [],
    pageLoading: false,
    page: {
        pageNum: 1,
        pageSize: 8,
        total: 0,
    }
};

export const useQuestionAnswerInfoStore = create<QuestionAnswerInfoStore>((set, get) => ({
    ...initialState,
    
    setPageLoading: (loading) => set({ pageLoading: loading }),
    
    setPage: (page) => set({ page }),
    
    setSourceData: (data) => set({ sourceData: data }),
    
    init: () => {
        // 初始化逻辑
    },
    
    fetchUserListApi: async (userName?: any, userNickName?: any, userType?: any) => {
        set({ pageLoading: true });
        try {
            const res = await apis.fetchUserListApi({
                pageNum: get().page.pageNum,
                pageSize: get().page.pageSize,
                userName,
                nickName: userNickName,
                userType,
            });
            
            if (res.code === 200) {
                set({
                    sourceData: res.rows || [],
                    page: {
                        pageNum: get().page.pageNum,
                        pageSize: get().page.pageSize,
                        total: res.total || 0,
                    },
                });
            }
        } catch (error) {
            console.error('获取用户列表失败:', error);
        } finally {
            set({ pageLoading: false });
        }
    },
}));

export default useQuestionAnswerInfoStore;
