import { makeAutoObservable } from 'mobx';
import { message } from 'antd';
import { apis, CreateOrModifyKnowledgeLibApiParams } from '@/apis';
import { State, ReadonlyState, StateAction, KnowledgeLibListStore } from './types';
import { downloadFile } from '@/utils';
// 定义状态
const stateGenerator = (): ReadonlyState => ({
    listLoading: false,
    list: [],
    infoModalId: '',
    infoModalOpen: false,
    page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
    },
    name:'',
    classificationType:'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;
        },
        setClassificationType: (data)=>{
            state.classificationType = data
        },
        setName: (name) => {
            state.name = name
        }
    };
};

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

    const api = {
        // 下载知识库
        fetchExportKnowledgeSliceExport:async (record:any)=>{
            const blob = await apis.exportKnowledgeSliceExport(record.knowledgeId);
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.href = url;
            link.download = record.name;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
        },
        // 获取知识库列表
        fetchKnowledgeLibList: async () => {
            actions.setListLoading(true);
            try {
                const data = {
                    pageNum: state.page.pageNum,
                    pageSize: state.page.pageSize,
                    name:state.name,
                    classificationType:state.classificationType==='0'?true:false
                };
                const res = await apis.fetchTakaiKnowledgeLibList(data);
                actions.setList(res.rows);
                actions.setPage({
                    ...state.page,
                    total: res.total,
                });
            } catch (error: any) {
                console.error(error);
            } finally {
                actions.setListLoading(false);
            }
        },
        // 创建知识库
        createKnowledgeLib: async (data: CreateOrModifyKnowledgeLibApiParams) => {
            actions.setListLoading(true);
            const initialInfoModalOpen = stateGenerator().infoModalOpen;

            try {
                const res = await apis.createTakaiKnowledgeLib(data);
                // 获取知识库列表
                api.fetchKnowledgeLibList();
                if(res.data === 1 && res.code === 200){
                    message.success('创建成功');
                    actions.setInfoModalOpen(initialInfoModalOpen);
                }else{
                    console.error('DeepSeek创建知识库响应异常:', res);
                    message.error('创建失败');
                }
            } catch (error: any) {
                console.error('DeepSeek创建知识库错误:', error);
                message.error(error.msg || '创建失败');
            }finally{
                actions.setListLoading(false);
            }
        },
        // 修改知识库
        modifyKnowledgeLib: async (knowledgeId: string, data: CreateOrModifyKnowledgeLibApiParams) => {
            try {
                const initialInfoModalOpen = stateGenerator().infoModalOpen;
                const res = await apis.modifyTakaiKnowledgeLib(knowledgeId, data);
                // 获取知识库列表
                api.fetchKnowledgeLibList();
                if(res.data === 1 && res.code === 200){
                    message.success('修改成功');
                    actions.setInfoModalOpen(initialInfoModalOpen);
                }else{
                    message.error('修改失败');
                }
            } catch (error: any) {
                message.error(error.msg);
            }
        },
        // 删除知识库
        deleteKnowledgeLib: async (knowledgeId: string) => {
            try {
                const res = await apis.deleteTakaiKnowledgeLib(knowledgeId);
                // 获取知识库列表
                api.fetchKnowledgeLibList();
                if(res.data === 1 && res.code === 200){
                    message.success('删除成功');
                }else{
                    message.error('删除失败');
                }
            } catch (error: any) {
                message.error(error.msg);
            }
        },
    }

    // 更改分页
    const onChangePagination: KnowledgeLibListStore['onChangePagination'] = async (pageNum, pageSize) => {
        actions.setPage({
            ...state.page,
            pageNum: pageNum,
            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) => {

        if (knowledgeId) {
            // 修改知识库
            const res:any  = await api.modifyKnowledgeLib(knowledgeId, data);
        } else {
            // 创建知识库
            const res:any = 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;
        const initialName = stateGenerator().name;
        const initialClassificationType = stateGenerator().classificationType;

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

    // 列表全部和我创建的进行切换
    const handleModeChange:KnowledgeLibListStore['handleModeChange'] = (data)=>{
        actions.setClassificationType(data)
        init()
    }

    // 搜索名称更新
    const handleNameChange:KnowledgeLibListStore['handleNameChange'] = (name) => {
        actions.setName(name)
    }
    // 导出知识库列表
    const handFetchExportKnowledgeSliceExport = (record:any)=>{
         api.fetchExportKnowledgeSliceExport(record)
    }
    const exportKnowledgeMarkDown = async (record:any) => {
        const blob = await apis.exportKnowledgeMarkDown(record.knowledgeId);
        downloadFile(blob, `${record.name}.zip`); 
    }
    const exportKnowledgeFile = async (record:any) => {
        const blob = await apis.exportKnowledgeFile(record.knowledgeId);
        downloadFile(blob, `${record.name}.zip`); 
    }
    return {
        state,
        onChangePagination,
        onClickCreate,
        onClickModify,
        infoModalOnClickConfirm,
        infoModalOnClickCancel,
        onClickDelete,
        init,
        reset,
        handleModeChange,
        handleNameChange,
        handFetchExportKnowledgeSliceExport,
        exportKnowledgeMarkDown,
        exportKnowledgeFile
    };
};

export default useKnowledgeLibListStore();