import { makeAutoObservable } from 'mobx';
import { apis } from '@/apis';
import { State, ReadonlyState, StateAction, QuestionAnswerInfoStore } from './types';

// 定义状态
const stateGenerator = (): ReadonlyState => ({
    sourceData: [],
    pageLoading: false,
    page: {
        pageNum: 1,
        pageSize: 8,
        total: 0,
    }
});

// 修改状态
const stateActionsGenerator = (state: State): StateAction => {
    return {
        setPageLoading: (loading) => {
            state.pageLoading = loading;
        },
        setPage: (page:any) => {
            state.page = page;
        },
        setSourceData: (data) => {
            state.sourceData = data;
        }
    };
};

// 使用仓库
const useQuestionAnswerInfoStore = (): QuestionAnswerInfoStore => {
    const state = makeAutoObservable(stateGenerator());
    const actions = stateActionsGenerator(state);

    const api = {
    }

    // 初始渲染
    const init = () => {

    }
    // 获取用户列表信息
    const onFetchUserListApi = async (userName?: any, userNickName?: any, userType?: any) => {
        try {
            const res = await apis.fetchUserListApi({
                pageNum: state.page.pageNum,
                pageSize: state.page.pageSize,
                userName: userName,
                nickName: userNickName,
                userType: userType
            });
            actions.setSourceData(res.rows)
            actions.setPage({
                ...state.page,
                total: res.total,
            });
        } catch (error) {
            console.error(error);
        }
    }
    // 状态重置
    const reset = () => {
        const initialPageLoading = stateGenerator().pageLoading;

        actions.setPageLoading(initialPageLoading);
    }
    // 更改分页
    const onChangePagination: QuestionAnswerInfoStore['onChangePagination'] = async (pageNum, pageSize, userName, userNickName, userType) => {
        actions.setPage({
            ...state.page,
            pageNum,
            pageSize: pageSize,
        });
        await onFetchUserListApi(userName, userNickName, userType);
    }
    return {
        onFetchUserListApi,
        onChangePagination,
        state,
        init,
        reset
    };
};

export default useQuestionAnswerInfoStore();