import { action, makeAutoObservable } from 'mobx';
import { message } from 'antd';
import { apis, ModifyDocumentApiParams, ModifyDocumentSettingApiParams } from '@/apis';
import { State, ReadonlyState, StateAction, DocumentLibInfoStore } from './types';

// 定义状态
const stateGenerator = (): ReadonlyState => ({
    knowledge_id: '',
    listLoading: false,
    list: [],
    infoModalId: '',
    infoModalOpen: false,
    infoModalSettingId: '',
    infoModalSettingOpen: false,
    page: {
        page: 1,
        size: 10,
        total: 0,
    },
    knowledgeDetail: {
        knowledgeId: '',
        embeddingId: '',
        name: '',
    }
});

// 修改状态
const stateActionsGenerator = (state: State): StateAction => {
    return {
        setknowledge_id(knowledge_id) {
            state.knowledge_id = knowledge_id;
        },
        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;
        },
        setInfoModalSettingOpen: (open) => {
            state.infoModalSettingOpen = open;
        },
        setInfoModalSettingId: (id) => {
            state.infoModalSettingId = id;
        },
        setKnowledgeDetail: (knowledgeDetail) => {
            state.knowledgeDetail = knowledgeDetail;
        },
    };
};

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

    const api = {
        // 获取知识列表
        fetchDocumentLibList: async () => {
            actions.setListLoading(true);
            try {
                const data = {
                    knowledge_id: state.knowledge_id,
                    page: state.page.page,
                    size: state.page.size,
                };
                const res = await apis.fetchTakaiDocumentLibListApi(data);
                actions.setList(res.rows);
                actions.setPage({
                    ...state.page,
                    total: res.total,
                });
            } catch (error: any) {
                console.error(error);
            } finally {
                actions.setListLoading(false);
            }
        },
        // 修改知识
        modifyDocumentLib: async (id: string, data: ModifyDocumentApiParams) => {
            try {
                await apis.modifyTakaiDocumentLibApi(id, data);
                // 获取知识列表
                api.fetchDocumentLibList();
                message.success('修改成功');
            } catch (error: any) {
                message.error(error.msg);
            }
        },
        // 删除知识
        deleteDocumentLib: async (id: string) => {
            try {
                await apis.deleteTakaiDocumentLibApi(id);
                // 获取知识列表
                api.fetchDocumentLibList();
                message.success('删除成功');
            } catch (error: any) {
                message.error(error.msg);
            }
        },

        // 修改知识配置
        modifyDocumentSettingLib: async (id: string, data: ModifyDocumentSettingApiParams) => {
            try {
                actions.setListLoading(true);
                const res = await apis.modifyTakaiDocumentSettingLibApi(id, data);
                if (res.data === 1) {
                    // 获取知识列表
                    api.fetchDocumentLibList();
                    message.success('修改成功');
                } else {
                    message.success('修改失败');
                }
            } catch (error: any) {
                message.error(error.msg);
            } finally {
                actions.setListLoading(false);
            }
        },

        // 获取知识库详情
        fetchKnowledgeLibDetail: async () => {
            try {
                const res = await apis.fetchTakaiKnowledgeLibDetail(state.knowledge_id);
                const { knowledgeId, embeddingId, name } = res.data;
                actions.setKnowledgeDetail({
                    knowledgeId: knowledgeId,
                    embeddingId: embeddingId,
                    name: name,
                });
            } catch (error: any) {
                message.error(error.msg);
            }
        }
    }

    // 更改分页
    const onChangePagination: DocumentLibInfoStore['onChangePagination'] = async (page, size) => {
        actions.setPage({
            ...state.page,
            page: page,
            size: size,
        });
        // 获取知识列表
        api.fetchDocumentLibList();
    }

    // 点击上传文件
    const onClickDocumentDetail: DocumentLibInfoStore['onClickDocumentDetail'] = () => {
        api.fetchDocumentLibList();
    }

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

    // 点击配置
    const onClickSettings: DocumentLibInfoStore['onClickSettings'] = (id) => {
        actions.setInfoModalSettingId(id);
        actions.setInfoModalSettingOpen(true);
    }

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

        actions.setInfoModalOpen(initialInfoModalOpen);

        if (id) {
            // 修改知识数据
            api.modifyDocumentLib(id, data);
        }
    }

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

        actions.setInfoModalOpen(initialInfoModalOpen);
    }

    // 知识配置信息弹出层-点击确定
    const infoModalSettingOnClickConfirm: DocumentLibInfoStore['infoModalSettingOnClickConfirm'] = async (id, data) => {
        const initialInfoModalSettingOpen = stateGenerator().infoModalSettingOpen;

        actions.setInfoModalSettingOpen(initialInfoModalSettingOpen);

        if (id) {
            // 修改知识数据
            api.modifyDocumentSettingLib(id, data);
        }
    }

    // 只是配置信息弹出层-点击取消
    const infoModalSettingOnClickCancel: DocumentLibInfoStore['infoModalSettingOnClickCancel'] = () => {
        const initialInfoModalSettingOpen = stateGenerator().infoModalSettingOpen;

        actions.setInfoModalSettingOpen(initialInfoModalSettingOpen);
    }

    // 点击删除
    const onClickDelete: DocumentLibInfoStore['onClickDelete'] = async (id) => {
        // 删除知识文件
        await api.deleteDocumentLib(id);
    }


    // 初始渲染
    const init: DocumentLibInfoStore['init'] = (id) => {
        // 获取知识列表
        if (id) {
            actions.setknowledge_id(id);
            api.fetchDocumentLibList();
            api.fetchKnowledgeLibDetail();
        }
    }

    // 状态重置
    const reset: DocumentLibInfoStore['reset'] = () => {
        const initialListLoading = stateGenerator().listLoading;
        const initialList = stateGenerator().list;
        const initialInfoModalId = stateGenerator().infoModalId;
        const initialInfoModalOpen = stateGenerator().infoModalOpen;
        const initialPage = stateGenerator().page;
        const knowledge_id = stateGenerator().knowledge_id;
        const initialInfoModalSettingId = stateGenerator().infoModalSettingId;
        const initialInfoModalSettingOpen = stateGenerator().infoModalSettingOpen;
        const initialKnowledgeDetail = stateGenerator().knowledgeDetail;

        actions.setListLoading(initialListLoading);
        actions.setList(initialList);
        actions.setInfoModalId(initialInfoModalId);
        actions.setInfoModalOpen(initialInfoModalOpen);
        actions.setPage(initialPage);
        actions.setknowledge_id(knowledge_id);
        actions.setInfoModalSettingId(initialInfoModalSettingId);
        actions.setInfoModalSettingOpen(initialInfoModalSettingOpen);
        actions.setKnowledgeDetail(initialKnowledgeDetail);
    }

    return {
        state,
        onChangePagination,
        onClickDocumentDetail,
        onClickModify,
        infoModalOnClickConfirm,
        infoModalOnClickCancel,
        onClickDelete,
        init,
        onClickSettings,
        infoModalSettingOnClickConfirm,
        infoModalSettingOnClickCancel,
        reset
    };
};

export default useKnowledgeLibInfoStore();