import { makeAutoObservable } from 'mobx';
import { message } from 'antd';
import { apis, CreateOrModifyKnowledgeLibApiParams } from '@/apis';
import { State, ReadonlyState, StateAction, KnowledgeLibListStore } from './types';

// 定义状态
const stateGenerator = (): ReadonlyState => ({
    listLoading: false,
    list: [],
    infoModalId: '',
    infoModalOpen: false,
    page: {
        pageNumber: 1,
        pageSize: 10,
        total: 0,
    },
});

// 修改状态
const stateActionsGenerator = (state: State): StateAction => {
    return {
        setListLoading: (loading) => {
            state.listLoading = loading;
        },
        setList: (list) => {
            state.list = list;
        },
        setInfoModalId: (id) => {
            state.infoModalId = id;
        },
        setInfoModalOpen: (open) => {
            state.infoModalOpen = open;
        },
        setPage: (page) => {
            state.page = page;
        },
    };
};

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

    const api = {
        // 获取知识库列表
        fetchKnowledgeLibList: async () => {
            actions.setListLoading(true);
            try {
                const data = {
                    pageNumber: state.page.pageNumber,
                    pageSize: state.page.pageSize,
                };
                const res = await apis.fetchKnowledgeLibList(data);
                actions.setList(res.data.list);
                actions.setPage({
                    ...state.page,
                    total: res.data.total,
                });
            } catch (error: any) {
                console.error(error);
            } finally {
                actions.setListLoading(false);
            }
        },
        // 创建知识库
        createKnowledgeLib: async (data: CreateOrModifyKnowledgeLibApiParams) => {
            try {
                //console.log('智谱AI创建知识库请求参数:', data);
                const res = await apis.createKnowledgeLib(data);
                // console.log('智谱AI创建知识库响应:', res);
                // 获取知识库列表
                await api.fetchKnowledgeLibList();
                message.success('创建成功');
            } catch (error: any) {
                console.error('智谱AI创建知识库错误:', error);
                message.error(error.msg || '创建失败');
            }
        },
        // 修改知识库
        modifyKnowledgeLib: async (knowledgeId: string, data: CreateOrModifyKnowledgeLibApiParams) => {
            try {
                await apis.modifyKnowledgeLib(knowledgeId, data);
                // 获取知识库列表
                await api.fetchKnowledgeLibList();
                message.success('修改成功');
            } catch (error: any) {
                message.error(error.msg);
            }
        },
        // 删除知识库
        deleteKnowledgeLib: async (knowledgeId: string) => {
            try {
                await apis.deleteKnowledgeLib(knowledgeId);
                // 获取知识库列表
                await api.fetchKnowledgeLibList();
                message.success('删除成功');
            } catch (error: any) {
                message.error(error.msg);
            }
        },
    }

    // 更改分页
    const onChangePagination: KnowledgeLibListStore['onChangePagination'] = async (pageNumber, pageSize) => {
        actions.setPage({
            ...state.page,
            pageNumber: pageNumber,
            pageSize: pageSize,
        });
        // 获取知识库列表
        await api.fetchKnowledgeLibList();
    }

    // 点击创建
    const onClickCreate: KnowledgeLibListStore['onClickCreate'] = () => {
        const initialInfoModalId = stateGenerator().infoModalId;

        actions.setInfoModalId(initialInfoModalId);
        actions.setInfoModalOpen(true);
    }

    // 点击修改
    const onClickModify: KnowledgeLibListStore['onClickModify'] = (knowledgeId) => {
        actions.setInfoModalId(knowledgeId);
        actions.setInfoModalOpen(true);
    }

    // 信息弹出层-点击确定
    const infoModalOnClickConfirm: KnowledgeLibListStore['infoModalOnClickConfirm'] = async (knowledgeId, data) => {
        const initialInfoModalOpen = stateGenerator().infoModalOpen;

        actions.setInfoModalOpen(initialInfoModalOpen);

        if (knowledgeId) {
            // 修改知识库
            await api.modifyKnowledgeLib(knowledgeId, data);
        } else {
            // 创建知识库
            await api.createKnowledgeLib(data);
        }
    }

    // 信息弹出层-点击取消
    const infoModalOnClickCancel: KnowledgeLibListStore['infoModalOnClickCancel'] = () => {
        const initialInfoModalOpen = stateGenerator().infoModalOpen;

        actions.setInfoModalOpen(initialInfoModalOpen);
    }

    // 点击删除
    const onClickDelete: KnowledgeLibListStore['onClickDelete'] = async (knowledgeId) => {
        // 删除知识库
        await api.deleteKnowledgeLib(knowledgeId);
    }

    // 初始渲染
    const init: KnowledgeLibListStore['init'] = async () => {
        // 获取知识库列表
        await api.fetchKnowledgeLibList();
    }

    // 状态重置
    const reset: KnowledgeLibListStore['reset'] = () => {
        const initialListLoading = stateGenerator().listLoading;
        const initialList = stateGenerator().list;
        const initialInfoModalId = stateGenerator().infoModalId;
        const initialInfoModalOpen = stateGenerator().infoModalOpen;
        const initialPage = stateGenerator().page;

        actions.setListLoading(initialListLoading);
        actions.setList(initialList);
        actions.setInfoModalId(initialInfoModalId);
        actions.setInfoModalOpen(initialInfoModalOpen);
        actions.setPage(initialPage);
    }

    return {
        state,
        onChangePagination,
        onClickCreate,
        onClickModify,
        infoModalOnClickConfirm,
        infoModalOnClickCancel,
        onClickDelete,
        init,
        reset
    };
};

export default useKnowledgeLibListStore();