import { create } from 'zustand';
import { message } from 'antd';
import { apis, CreateOrModifyKnowledgeLibApiParams } from '@/apis';
import { downloadFile } from '@/utils';
// 导入 Mock 数据
import { mockKnowledgeLibList } from '@/mock';

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

interface KnowledgeLibListState {
    listLoading: boolean;
    list: any[];
    infoModalId: string;
    infoModalOpen: boolean;
    page: PageState;
    name: string;
    classificationType: string;
}

interface KnowledgeLibListActions {
    setListLoading: (loading: boolean) => void;
    setList: (list: any[]) => void;
    setInfoModalId: (id: string) => void;
    setInfoModalOpen: (open: boolean) => void;
    setPage: (page: PageState) => void;
    setName: (name: string) => void;
    setClassificationType: (type: string) => void;
    reset: () => void;
}

export type KnowledgeLibListStore = KnowledgeLibListState & KnowledgeLibListActions & {
    fetchExportKnowledgeSliceExport: (record: any) => Promise<void>;
    fetchExportDocumentSliceExport: (record: any) => Promise<void>;
    fetchExportDocumentExport: (record: any) => Promise<void>;
    fetchKnowledgeLibList: () => Promise<void>;
    onCreateKnowledgeLib: (data: CreateOrModifyKnowledgeLibApiParams) => Promise<void>;
    onModifyKnowledgeLib: (id: string, data: CreateOrModifyKnowledgeLibApiParams) => Promise<void>;
    onDeleteKnowledgeLib: (id: string) => Promise<void>;
    onInfoModalOpenChange: (open: boolean, id?: string) => void;
    init: () => Promise<void>;
};

const initialState: KnowledgeLibListState = {
    listLoading: false,
    list: [],
    infoModalId: '',
    infoModalOpen: false,
    page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
    },
    name: '',
    classificationType: '0',
};

export const useKnowledgeLibListStore = create<KnowledgeLibListStore>((set, get) => ({
    ...initialState,
    
    setListLoading: (loading) => set({ listLoading: loading }),
    
    setList: (list) => set({ list }),
    
    setInfoModalId: (id) => set({ infoModalId: id }),
    
    setInfoModalOpen: (open) => set({ infoModalOpen: open }),
    
    setPage: (page) => set({ page }),
    
    setName: (name) => set({ name }),
    
    setClassificationType: (type) => set({ classificationType: type }),
    
    fetchExportKnowledgeSliceExport: async (record) => {
        try {
            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;
            link.click();
            window.URL.revokeObjectURL(url);
        } catch (error) {
            console.error('下载知识库失败:', error);
        }
    },
    
    fetchExportDocumentSliceExport: async (record) => {
        try {
            const blob = await apis.exportDocumentSliceExport([record.documentId]);
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = record.name;
            link.click();
            window.URL.revokeObjectURL(url);
        } catch (error) {
            console.error('下载文档切片失败:', error);
        }
    },
    
    fetchExportDocumentExport: async (record) => {
        try {
            const blob = await apis.exportDocumentExport([record.documentId]);
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = record.name;
            link.click();
            window.URL.revokeObjectURL(url);
        } catch (error) {
            console.error('下载文档失败:', error);
        }
    },
    
    fetchKnowledgeLibList: async () => {
        set({ listLoading: true });
        try {
            // 使用 Mock 数据
            const isDemo = import.meta.env.VITE_USE_MOCK === 'true';
            if (isDemo) {
                // 模拟 API 调用延迟
                await new Promise(resolve => setTimeout(resolve, 300));
                set({
                    list: mockKnowledgeLibList,
                    page: {
                        ...get().page,
                        total: mockKnowledgeLibList.length,
                    },
                });
            } else {
                const res: any = await apis.fetchKnowledgeLibList({
                    pageNum: get().page.pageNum,
                    pageSize: get().page.pageSize,
                });

                if (res.code === 200) {
                    set({
                        list: res.rows || [],
                        page: {
                            ...get().page,
                            total: res.total || 0,
                        },
                    });
                }
            }
        } catch (error: any) {
            message.error(error.msg || '获取列表失败');
            set({ list: [] });
        } finally {
            set({ listLoading: false });
        }
    },

    onCreateKnowledgeLib: async (data) => {
        try {
            const res: any = await apis.createKnowledgeLib(data);
            if (res.code === 200) {
                message.success('创建成功');
                get().fetchKnowledgeLibList();
                set({ infoModalOpen: false });
            }
        } catch (error: any) {
            message.error(error.msg || '创建失败');
        }
    },
    
    onModifyKnowledgeLib: async (id, data) => {
        try {
            const res: any = await apis.modifyKnowledgeLib(id, data);
            if (res.code === 200) {
                message.success('修改成功');
                get().fetchKnowledgeLibList();
                set({ infoModalOpen: false });
            }
        } catch (error: any) {
            message.error(error.msg || '修改失败');
        }
    },
    
    onDeleteKnowledgeLib: async (id) => {
        try {
            const res: any = await apis.deleteKnowledgeLib(id);
            if (res.code === 200) {
                message.success('删除成功');
                get().fetchKnowledgeLibList();
            }
        } catch (error: any) {
            message.error(error.msg || '删除失败');
        }
    },
    
    onInfoModalOpenChange: (open, id) => {
        set({ infoModalOpen: open });
        if (id) {
            set({ infoModalId: id });
        }
    },

    reset: () => set(initialState),

    init: async () => {
        await get().fetchKnowledgeLibList();
    },
}));

export default useKnowledgeLibListStore;
