/**
 * 知识库相关 API Mock 拦截器
 * 
 * 用于拦截知识库相关的所有 API 请求，返回模拟数据
 */

import {
    mockKnowledgeLibList,
    mockKnowledgeLibDetail,
    mockDocumentList,
    mockSliceList,
    mockReviseToolList,
    mockReviseHistoryList,
    mockEmbeddingList,
    mockParsingTypeList,
    mockSplittingTypeList,
    mockStandardClassificationList,
    mockRevisionStatusList,
    mockChatHistoryList,
} from './index';

// 模拟延迟
const mockDelay = (ms: number = 300) => new Promise(resolve => setTimeout(resolve, ms));

// 模拟响应结构
const mockResponse = (data: any, total?: number) => {
    return {
        code: 200,
        msg: 'success',
        data,
        rows: data,
        total: total !== undefined ? total : (Array.isArray(data) ? data.length : 1),
    };
};

// ==================== 知识库 API Mock ====================

/**
 * 获取知识库列表
 * POST /bigmodel/api/knowledgeList
 */
export const mockFetchKnowledgeLibList = async (params: any) => {
    await mockDelay();
    const { pageNum = 1, pageSize = 10, name = '' } = params || {};
    
    let filteredList = [...mockKnowledgeLibList];
    
    // 按名称过滤
    if (name) {
        filteredList = filteredList.filter(item => 
            item.name.toLowerCase().includes(name.toLowerCase())
        );
    }
    
    // 分页
    const start = (pageNum - 1) * pageSize;
    const end = start + pageSize;
    const paginatedList = filteredList.slice(start, end);
    
    return mockResponse(paginatedList, filteredList.length);
};

/**
 * 获取知识库详情
 * GET /bigmodel/api/detailKnowledge/:knowledgeId
 */
export const mockFetchKnowledgeLibDetail = async (knowledgeId: string) => {
    await mockDelay();
    
    const detail = mockKnowledgeLibList.find(item => item.knowledgeId === knowledgeId) 
        || mockKnowledgeLibDetail;
    
    return mockResponse({ ...detail, knowledgeId });
};

/**
 * 创建知识库
 * POST /bigmodel/api/createKnowledge
 */
export const mockCreateKnowledgeLib = async (data: any) => {
    await mockDelay(500);
    
    const newKnowledge = {
        knowledgeId: `kb${Date.now()}`,
        name: data.name,
        createBy: 'admin',
        standardClassification: data.standardClassification || '0',
        splittingType: data.splittingType || '1',
        docCount: 0,
        sliceCount: 0,
        createTime: new Date().toLocaleString('zh-CN'),
        updateTime: new Date().toLocaleString('zh-CN'),
    };
    
    mockKnowledgeLibList.unshift(newKnowledge);
    
    return mockResponse(newKnowledge);
};

/**
 * 修改知识库
 * PUT /bigmodel/api/updateKnowledge/:knowledgeId
 */
export const mockModifyKnowledgeLib = async (knowledgeId: string, data: any) => {
    await mockDelay(500);
    
    const index = mockKnowledgeLibList.findIndex(item => item.knowledgeId === knowledgeId);
    
    if (index !== -1) {
        mockKnowledgeLibList[index] = {
            ...mockKnowledgeLibList[index],
            ...data,
            updateTime: new Date().toLocaleString('zh-CN'),
        };
    }
    
    return mockResponse({ success: true });
};

/**
 * 删除知识库
 * DELETE /bigmodel/api/delKnowledge/:knowledgeId
 */
export const mockDeleteKnowledgeLib = async (knowledgeId: string) => {
    await mockDelay(500);
    
    const index = mockKnowledgeLibList.findIndex(item => item.knowledgeId === knowledgeId);
    
    if (index !== -1) {
        mockKnowledgeLibList.splice(index, 1);
    }
    
    return mockResponse({ success: true });
};

/**
 * 获取向量化模型列表
 * GET /bigmodel/api/embedding
 */
export const mockFetchEmbeddingList = async () => {
    await mockDelay();
    return mockResponse(mockEmbeddingList);
};

// ==================== 文档管理 API Mock ====================

/**
 * 获取文档列表
 * POST /bigmodel/api/documentList
 */
export const mockFetchDocumentLibList = async (params: any) => {
    await mockDelay();
    const { knowledge_id, page = 1, size = 10, name = '' } = params || {};
    
    let filteredList = [...mockDocumentList];
    
    // 按知识库 ID 过滤
    if (knowledge_id) {
        filteredList = filteredList.filter(item => item.knowledgeId === knowledge_id);
    }
    
    // 按名称过滤
    if (name) {
        filteredList = filteredList.filter(item => 
            item.name.toLowerCase().includes(name.toLowerCase())
        );
    }
    
    // 分页
    const start = (page - 1) * size;
    const end = start + size;
    const paginatedList = filteredList.slice(start, end);
    
    return mockResponse(paginatedList, filteredList.length);
};

/**
 * 获取文档详情
 * GET /bigmodel/api/documentDetail/:id
 */
export const mockFetchDocumentLibDetail = async (id: string) => {
    await mockDelay();
    
    const detail = mockDocumentList.find(item => item.id === id);
    
    if (!detail) {
        return { code: 500, msg: '文档不存在', data: null };
    }
    
    return mockResponse(detail);
};

/**
 * 修改文档
 * PUT /bigmodel/api/updateDocument/:id
 */
export const mockModifyDocumentLib = async (id: string, data: any) => {
    await mockDelay(500);
    
    const index = mockDocumentList.findIndex(item => item.id === id);
    
    if (index !== -1) {
        mockDocumentList[index] = {
            ...mockDocumentList[index],
            ...data,
            updateTime: new Date().toLocaleString('zh-CN'),
        };
    }
    
    return mockResponse({ success: true });
};

/**
 * 删除文档
 * DELETE /bigmodel/api/delDocument/:id
 */
export const mockDeleteDocumentLib = async (id: string) => {
    await mockDelay(500);
    
    const index = mockDocumentList.findIndex(item => item.id === id);
    
    if (index !== -1) {
        mockDocumentList.splice(index, 1);
    }
    
    return mockResponse({ success: true });
};

/**
 * 上传文档
 * POST /bigmodel/api/uploadDocument/:knowledgeId
 */
export const mockUploadDocument = async (knowledgeId: string, data: any) => {
    await mockDelay(1000);
    
    const newDocument = {
        id: `doc${Date.now()}`,
        name: data?.name || '新文档.pdf',
        url: '/files/new.pdf',
        length: data?.size || 1024000,
        sentenceSize: 100,
        knowledgeType: 1,
        customSeparator: ['\\n'],
        embeddingStat: 0,
        wordNum: 0,
        parseImage: 0,
        createTime: new Date().toLocaleString('zh-CN'),
        updateTime: new Date().toLocaleString('zh-CN'),
        knowledgeId,
        knowledgeName: '政务公文知识库',
        status: 'processing',
    };
    
    mockDocumentList.unshift(newDocument);
    
    return mockResponse(newDocument);
};

/**
 * 获取文档配置详情
 * GET /bigmodel/api/documentSetting/:id
 */
export const mockFetchDocumentSetting = async (id: string) => {
    await mockDelay();
    
    const doc = mockDocumentList.find(item => item.id === id);
    
    return mockResponse({
        knowledgeId: doc?.knowledgeId || 'kb001',
        documentId: id,
        setSlice: '0',
        setAnalyze: '1',
        setTabel: '0',
    });
};

/**
 * 修改文档配置
 * PUT /bigmodel/api/updateDocumentSetting/:id
 */
export const mockModifyDocumentSetting = async (id: string, data: any) => {
    await mockDelay(500);
    return mockResponse({ success: true });
};

// ==================== 切片管理 API Mock ====================

/**
 * 获取切片列表
 * POST /bigmodel/api/getSliceList
 */
export const mockFetchSliceList = async (params: any) => {
    await mockDelay();
    const { knowledge_id, document_id, text = '', pageNum = 1, pageSize = 10 } = params || {};
    
    let filteredList = [...mockSliceList];
    
    // 按知识库 ID 过滤
    if (knowledge_id) {
        filteredList = filteredList.filter(item => item.knowledgeId === knowledge_id);
    }
    
    // 按文档 ID 过滤
    if (document_id) {
        filteredList = filteredList.filter(item => item.documentId === document_id);
    }
    
    // 按文本搜索
    if (text) {
        filteredList = filteredList.filter(item => 
            item.sliceText.includes(text)
        );
    }
    
    // 分页
    const start = (pageNum - 1) * pageSize;
    const end = start + pageSize;
    const paginatedList = filteredList.slice(start, end);
    
    return mockResponse(paginatedList, filteredList.length);
};

/**
 * 获取切片详情
 * GET /bigmodel/api/getSliceDetail/:sliceId/:knowledgeId
 */
export const mockFetchSliceDetail = async (sliceId: string, knowledgeId: string) => {
    await mockDelay();
    
    const detail = mockSliceList.find(item => item.sliceId === sliceId);
    
    if (!detail) {
        return { code: 500, msg: '切片不存在', data: null };
    }
    
    return mockResponse(detail);
};

/**
 * 新增切片
 * POST /bigmodel/api/add/slice
 */
export const mockAddSlice = async (data: any) => {
    await mockDelay(500);
    
    const newSlice = {
        sliceId: `slice${Date.now()}`,
        knowledgeId: data.knowledgeId,
        documentId: data.documentId,
        sliceText: data.sliceText,
        sliceNum: mockSliceList.length + 1,
        createTime: new Date().toLocaleString('zh-CN'),
        updateTime: new Date().toLocaleString('zh-CN'),
        status: 'active',
    };
    
    mockSliceList.unshift(newSlice);
    
    return mockResponse(newSlice);
};

/**
 * 修改切片
 * PUT /bigmodel/api/updateSliceInfo
 */
export const mockModifySlice = async (data: any) => {
    await mockDelay(500);
    
    const index = mockSliceList.findIndex(item => item.sliceId === data.sliceId);
    
    if (index !== -1) {
        mockSliceList[index] = {
            ...mockSliceList[index],
            sliceText: data.sliceText,
            updateTime: new Date().toLocaleString('zh-CN'),
        };
    }
    
    return mockResponse({ success: true });
};

/**
 * 删除切片
 * DELETE /bigmodel/api/deleteSlice/:sliceId/:knowledgeId/:documentId
 */
export const mockDeleteSlice = async (sliceId: string, knowledgeId: string, documentId: string) => {
    await mockDelay(500);
    
    const index = mockSliceList.findIndex(item => item.sliceId === sliceId);
    
    if (index !== -1) {
        mockSliceList.splice(index, 1);
    }
    
    return mockResponse({ success: true });
};

// ==================== 修订工具 API Mock ====================

/**
 * 获取修订工具列表（分页）
 * GET /deepseek/revise/pageList
 */
export const mockFetchReviseToolList = async (params: any) => {
    await mockDelay();
    const { pageNum = 1, pageSize = 10, knowledgeName = '' } = params || {};
    
    let filteredList = [...mockReviseToolList];
    
    // 按知识库名称过滤
    if (knowledgeName) {
        filteredList = filteredList.filter(item => 
            item.knowledgeName.toLowerCase().includes(knowledgeName.toLowerCase())
        );
    }
    
    // 分页
    const start = (pageNum - 1) * pageSize;
    const end = start + pageSize;
    const paginatedList = filteredList.slice(start, end);
    
    return mockResponse(paginatedList, filteredList.length);
};

/**
 * 获取修订工具列表（不分页）
 * GET /deepseek/revise/list
 */
export const mockFetchReviseToolAllList = async (params: any) => {
    await mockDelay();
    const { documentName = '', knowledgeId = '' } = params || {};
    
    let filteredList = [...mockDocumentList];
    
    // 按知识库 ID 过滤
    if (knowledgeId) {
        filteredList = filteredList.filter(item => item.knowledgeId === knowledgeId);
    }
    
    // 按文档名称过滤
    if (documentName) {
        filteredList = filteredList.filter(item => 
            item.name.toLowerCase().includes(documentName.toLowerCase())
        );
    }
    
    return mockResponse(filteredList);
};

/**
 * 获取修订工具切片列表
 * GET /deepseek/revise/sliceList
 */
export const mockFetchReviseToolSliceList = async (params: any) => {
    await mockDelay();
    const { sliceText = '', documentId = '' } = params || {};
    
    let filteredList = [...mockSliceList];
    
    // 按文档 ID 过滤
    if (documentId) {
        filteredList = filteredList.filter(item => item.documentId === documentId);
    }
    
    // 按文本搜索
    if (sliceText) {
        filteredList = filteredList.filter(item => 
            item.sliceText.includes(sliceText)
        );
    }
    
    return mockResponse(filteredList);
};

/**
 * 提交修订切片
 * PUT /deepseek/revise/reviseSlice
 */
export const mockSubmitReviseSlice = async (data: any) => {
    await mockDelay(500);
    
    const newHistory = {
        id: `rev${Date.now()}`,
        knowledgeId: data.knowledgeId,
        knowledgeName: '政务公文知识库',
        documentName: '文档.pdf',
        refDocumentName: '参考文档.pdf',
        sliceId: data.sliceId,
        refSliceId: data.refSliceId,
        revisionStatus: data.revisionStatus || '1',
        createTime: new Date().toLocaleString('zh-CN'),
        createBy: 'admin',
    };
    
    mockReviseHistoryList.unshift(newHistory);
    
    return mockResponse({ success: true });
};

/**
 * 获取修订历史列表
 * GET /deepseek/revise/reviseHistoryList
 */
export const mockFetchReviseHistoryList = async (params: any) => {
    await mockDelay();
    const { pageNum = 1, pageSize = 10, knowledgeId = '', knowledgeName = '', documentName = '', refDocumentName = '' } = params || {};
    
    let filteredList = [...mockReviseHistoryList];
    
    // 按知识库 ID 过滤
    if (knowledgeId) {
        filteredList = filteredList.filter(item => item.knowledgeId === knowledgeId);
    }
    
    // 按知识库名称过滤
    if (knowledgeName) {
        filteredList = filteredList.filter(item => 
            item.knowledgeName.toLowerCase().includes(knowledgeName.toLowerCase())
        );
    }
    
    // 按文档名称过滤
    if (documentName) {
        filteredList = filteredList.filter(item => 
            item.documentName.toLowerCase().includes(documentName.toLowerCase())
        );
    }
    
    // 按参考文档名称过滤
    if (refDocumentName) {
        filteredList = filteredList.filter(item => 
            item.refDocumentName.toLowerCase().includes(refDocumentName.toLowerCase())
        );
    }
    
    // 分页
    const start = (pageNum - 1) * pageSize;
    const end = start + pageSize;
    const paginatedList = filteredList.slice(start, end);
    
    return mockResponse(paginatedList, filteredList.length);
};

// ==================== 字典数据 API Mock ====================

/**
 * 获取字典类型列表
 * GET /deepseek/api/:dictType
 */
export const mockFetchTakaiAppTypeList = async (dictType: string) => {
    await mockDelay();
    
    let list: any[] = [];
    
    switch (dictType) {
        case 'standard_classification':
            list = mockStandardClassificationList;
            break;
        case 'parsing_type':
            list = mockParsingTypeList;
            break;
        case 'splitting_type':
            list = mockSplittingTypeList;
            break;
        case 'revision_status':
            list = mockRevisionStatusList;
            break;
        default:
            list = [];
    }
    
    return mockResponse(list);
};

// ==================== 聊天记录 API Mock ====================

/**
 * 获取聊天记录列表
 * POST /bigmodel/api/chatHistory/list
 */
export const mockFetchChatHistoryList = async (params: any) => {
    await mockDelay();
    const { appId, pageNum = 1, pageSize = 10 } = params || {};
    
    let filteredList = [...mockChatHistoryList];
    
    // 按应用 ID 过滤
    if (appId) {
        filteredList = filteredList.filter(item => item.appId === appId);
    }
    
    // 分页
    const start = (pageNum - 1) * pageSize;
    const end = start + pageSize;
    const paginatedList = filteredList.slice(start, end);
    
    return mockResponse(paginatedList, filteredList.length);
};

/**
 * 导出聊天记录
 * POST /bigmodel/api/dialog/export/:id
 */
export const mockExportChatHistory = async (id: string) => {
    await mockDelay(1000);
    
    // 返回一个模拟的 Blob 对象
    return new Blob(['聊天记录导出内容'], { type: 'text/plain' });
};

// ==================== 导出所有 Mock 函数 ====================

export default {
    mockFetchKnowledgeLibList,
    mockFetchKnowledgeLibDetail,
    mockCreateKnowledgeLib,
    mockModifyKnowledgeLib,
    mockDeleteKnowledgeLib,
    mockFetchEmbeddingList,
    mockFetchDocumentLibList,
    mockFetchDocumentLibDetail,
    mockModifyDocumentLib,
    mockDeleteDocumentLib,
    mockUploadDocument,
    mockFetchDocumentSetting,
    mockModifyDocumentSetting,
    mockFetchSliceList,
    mockFetchSliceDetail,
    mockAddSlice,
    mockModifySlice,
    mockDeleteSlice,
    mockFetchReviseToolList,
    mockFetchReviseToolAllList,
    mockFetchReviseToolSliceList,
    mockSubmitReviseSlice,
    mockFetchReviseHistoryList,
    mockFetchTakaiAppTypeList,
    mockFetchChatHistoryList,
    mockExportChatHistory,
};
