import { action, makeAutoObservable } from 'mobx';
import { message } from 'antd';
import { fetchEventSource } from '@fortaine/fetch-event-source';
import LocalStorage from '@/LocalStorage';
import { apis, ModifyDocumentApiParams, ModifyDocumentSettingApiParams } from '@/apis';
import { State, ReadonlyState, StateAction, DocumentLibInfoStore } from './types';
import { downloadFile } from '@/utils/index'
// 定义状态
const stateGenerator = (): ReadonlyState => ({
    knowledge_id: '',
    name: '',
    listLoading: false,
    list: [],
    processingList: [],
    infoModalId: '',
    infoModalOpen: false,
    infoModalSettingId: '',
    infoModalSettingOpen: false,
    page: {
        page: 1,
        size: 10,
        total: 0,
    },
    knowledgeDetail: {
        knowledgeId: '',
        embeddingId: '',
        name: '',
        standardClassification: '',
        splittingType: ''
    }
});

// 修改状态
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;
        },
        setProcessingList: (list) => {
            state.processingList = 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;
        },
        setName: (name) => {
            state.name = name
        }
    };
};

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

    // 当前 SSE 连接的关闭函数，用于确保同一时刻只有一个 SSE 连接
    let currentSSEClose: (() => void) | null = null;

    const api = {
        // 获取知识列表
        fetchDocumentLibList: async (status = 1) => {
            actions.setListLoading(true);
            try {
                const data = {
                    knowledge_id: state.knowledge_id,
                    page: state.page.page,
                    size: state.page.size,
                    name: state.name,
                    status, // 0 未完成，1已完成
                };
                const res = await apis.fetchTakaiDocumentLibListApi(data);
                if (status === 1) {
                    actions.setList(res.rows);
                    actions.setPage({
                        ...state.page,
                        total: res.total,
                    });
                }
                if (status === 0) {
                    res.rows?.forEach((item: any) => {
                        item.progress = 0
                    });
                    actions.setProcessingList(res.rows);
                }
            } 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(0);
                    api.fetchDocumentLibList(1);
                    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, standardClassification } = res.data;
                actions.setKnowledgeDetail({
                    knowledgeId: knowledgeId,
                    embeddingId: embeddingId,
                    name: name,
                    standardClassification: standardClassification,
                    splittingType: res.data.splittingType
                });
            } 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 handleNameChange: DocumentLibInfoStore['handleNameChange'] = (name) => {
        actions.setName(name)
    }
    // 点击上传文件
    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, type = 1,status?:string) => {
        // 获取知识列表
        if (id) {
            actions.setknowledge_id(id);
            if(!status){
                api.fetchDocumentLibList(0);
            }
            api.fetchDocumentLibList(1);
            api.fetchKnowledgeLibDetail();
            // sse();
        }
        if (type === 1) {
            setTimeout(() => {
                sse()
            }, 1000)
        }
    }

    // 状态重置
    const reset: DocumentLibInfoStore['reset'] = async () => {
        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);
        console.log('resetreset---')
        await apis.getSseclose()
    }
    /**
     * 接入 SSE (Server-Sent Events) 服务
     * 使用 GET 请求连接到服务器端事件流，实时接收服务器推送的数据
     * 注意：此方法会确保同一时刻只有一个 SSE 连接，如果已有连接则会先关闭旧连接
     * 
     * @param {Function} onMessage - 接收到消息时的回调函数，参数为消息数据
     * @param {Function} onError - 发生错误时的回调函数，参数为错误信息
     * @param {Function} onOpen - 连接打开时的回调函数
     * @param {Function} onClose - 连接关闭时的回调函数
     * @returns {Function} 返回一个用于关闭 SSE 连接的函数
     */
    const sse: DocumentLibInfoStore['sse'] = (
        onMessage?: (data: any) => void,
        onError?: (error: any) => void,
        onOpen?: () => void,
        onClose?: () => void
    ) => {
        // 从 LocalStorage 获取认证令牌
        const token = LocalStorage.getToken();

        // 如果没有令牌，提示错误并返回
        if (!token) {
            message.error('未获取到认证令牌，无法建立 SSE 连接');
            if (onError) {
                onError(new Error('未获取到认证令牌'));
            }
            return;
        }

        // 客户端 ID
        const clientid = 'e5cd7e4891bf95d1d19206ce24a7b32e';

        // 构建完整的请求 URL，包含查询参数
        // 将 Authorization 和 clientid 作为查询参数传递
        const url = new URL('/api/resource/sse', window.location.origin);
        url.searchParams.append('Authorization', `Bearer ${token}`);
        url.searchParams.append('clientid', clientid);
        const en = new EventSource(url)
        en.onmessage = event => {
            // console.log('e.data', event.data)
            let data: any = event.data;
            try {
                data = JSON.parse(event.data);
                // console.log('event--消息接收成功', data)
                const flagProcessingList: any = [...state.processingList]
                flagProcessingList.forEach((item: any) => {
                    if (item.documentId === data.documentId) {
                        // console.log('进来没有---', data.progress)
                        item.progress = data.progress
                        item.status = data.status
                        if (data.progress === 100 || data.message === 'error') {
                            api.fetchDocumentLibList(0);
                            api.fetchDocumentLibList(1);
                        }
                    }
                })
                // console.log('flagProcessingList', flagProcessingList)
                actions.setProcessingList(flagProcessingList)
            } catch {
                // 如果不是 JSON 格式，直接使用原始数据
            }
        }
        en.onerror = e => {
            console.log('err', e)
        }
        en.onopen = e => {
            console.log('onopen', e)
        }
        return
    }
    const onDeleteTakaiDocumentLibApi = async (documentId: string) => {
        const res = await apis.deleteTakaidelUnfinishedDocumentLibApi(documentId)
        if (res.code === 200) {
            api.fetchDocumentLibList(0);
            api.fetchDocumentLibList(1);
        }
    }

    const onExportDocumentSliceExport = async (lis: String[], type = 1) => {
        if (!lis.length) {
            message.warning('请选择文件')
            return
        }
        if (type === 1) {
            const blob = await apis.exportDocumentSliceExport(lis)
            downloadFile(blob, '切片')
        }
        if (type === 2) {
            const blob = await apis.exportDocumentExport(lis)
            downloadFile(blob, '文件.zip')
        }
        if (type === 3) {
            const blob = await apis.documentFileExport(lis)
            downloadFile(blob, '原文件.zip')
        }
    }


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

export default useKnowledgeLibInfoStore();