import { MockRequest } from './index';

// ==================== 应用管理 Mock 数据 ====================

// 应用分类
const appCategories = [
    { value: 'professional', label: '专业知识' },
    { value: 'functional', label: '职能管理' },
    { value: 'project', label: '项目级应用' },
];

// 应用状态
const appStatuses = [
    { value: 'online', label: '已上线' },
    { value: 'offline', label: '已下线' },
    { value: 'auditing', label: '审核中' },
    { value: 'rejected', label: '已拒绝' },
];

// 模拟应用数据
const mockApplicationsData = [
    {
        id: 'app_001',
        name: '合同审查助手',
        description: '基于 RAG 技术的智能合同审查与风险提示工具',
        category: 'professional',
        status: 'online',
        creatorId: 'user_001',
        creator: '张三',
        maintainers: ['张三', '李四'],
        createdAt: '2025-12-15 10:30:00',
        updatedAt: '2026-01-05 14:20:00',
        icon: 'contract',
        tags: ['合同管理', '风险提示', '法律'],
        knowledgeBaseCount: 3,
        conversationCount: 1250,
        avatar: '',
    },
    {
        id: 'app_002',
        name: '人力资源问答机器人',
        description: '员工自助服务平台，解答人事、考勤、福利等问题',
        category: 'functional',
        status: 'online',
        creatorId: 'user_002',
        creator: '李四',
        maintainers: ['李四'],
        createdAt: '2025-12-20 09:15:00',
        updatedAt: '2026-01-08 11:45:00',
        icon: 'hr',
        tags: ['人力资源', '员工服务'],
        knowledgeBaseCount: 2,
        conversationCount: 890,
        avatar: '',
    },
    {
        id: 'app_003',
        name: '项目管理智能助手',
        description: '项目进度跟踪、风险预警、资源调配建议',
        category: 'project',
        status: 'online',
        creatorId: 'user_003',
        creator: '王五',
        maintainers: ['王五', '赵六'],
        createdAt: '2026-01-02 13:20:00',
        updatedAt: '2026-01-10 16:30:00',
        icon: 'project',
        tags: ['项目管理', '进度跟踪'],
        knowledgeBaseCount: 5,
        conversationCount: 567,
        avatar: '',
    },
    {
        id: 'app_004',
        name: '财务报销助手',
        description: '智能解答财务报销流程、发票规范、费用标准等问题',
        category: 'functional',
        status: 'online',
        creatorId: 'user_004',
        creator: '赵六',
        maintainers: ['赵六'],
        createdAt: '2026-01-05 10:00:00',
        updatedAt: '2026-01-12 09:15:00',
        icon: 'finance',
        tags: ['财务管理', '报销'],
        knowledgeBaseCount: 2,
        conversationCount: 432,
        avatar: '',
    },
    {
        id: 'app_005',
        name: '技术培训知识库',
        description: '技术人员在线学习平台，提供技术文档、培训资料查询',
        category: 'professional',
        status: 'online',
        creatorId: 'user_005',
        creator: '钱七',
        maintainers: ['钱七', '孙八'],
        createdAt: '2026-01-08 14:30:00',
        updatedAt: '2026-01-15 10:20:00',
        icon: 'tech',
        tags: ['技术培训', '知识管理'],
        knowledgeBaseCount: 8,
        conversationCount: 1580,
        avatar: '',
    },
    {
        id: 'app_006',
        name: '安全生产管理系统',
        description: '安全生产规范、应急预案、事故案例分析',
        category: 'project',
        status: 'auditing',
        creatorId: 'user_006',
        creator: '孙八',
        maintainers: ['孙八'],
        createdAt: '2026-01-10 11:00:00',
        updatedAt: '2026-01-16 15:45:00',
        icon: 'safety',
        tags: ['安全生产', '应急管理'],
        knowledgeBaseCount: 4,
        conversationCount: 0,
        avatar: '',
    },
    {
        id: 'app_007',
        name: '市场营销支持平台',
        description: '市场数据分析、竞品调研、营销策略建议',
        category: 'functional',
        status: 'offline',
        creatorId: 'user_007',
        creator: '周九',
        maintainers: ['周九', '吴十'],
        createdAt: '2025-11-20 09:30:00',
        updatedAt: '2025-12-25 16:00:00',
        icon: 'marketing',
        tags: ['市场营销', '数据分析'],
        knowledgeBaseCount: 3,
        conversationCount: 2100,
        avatar: '',
    },
    {
        id: 'app_008',
        name: 'IT 运维智能助手',
        description: 'IT 故障排查、系统维护、常见问题解答',
        category: 'professional',
        status: 'online',
        creatorId: 'user_008',
        creator: '吴十',
        maintainers: ['吴十'],
        createdAt: '2026-01-12 10:15:00',
        updatedAt: '2026-01-18 14:30:00',
        icon: 'it',
        tags: ['IT 运维', '故障排查'],
        knowledgeBaseCount: 6,
        conversationCount: 789,
        avatar: '',
    },
    {
        id: 'app_009',
        name: '合规管理助手',
        description: '企业合规政策、流程指引、风险预警',
        category: 'functional',
        status: 'rejected',
        creatorId: 'user_009',
        creator: '郑十一',
        maintainers: ['郑十一'],
        createdAt: '2026-01-14 13:45:00',
        updatedAt: '2026-01-19 11:20:00',
        icon: 'compliance',
        tags: ['合规管理', '风险控制'],
        knowledgeBaseCount: 2,
        conversationCount: 0,
        avatar: '',
    },
    {
        id: 'app_010',
        name: '客户服务知识库',
        description: '客服常见问题解答、产品使用说明、售后服务流程',
        category: 'professional',
        status: 'online',
        creatorId: 'user_010',
        creator: '刘十二',
        maintainers: ['刘十二', '陈十三'],
        createdAt: '2026-01-15 08:30:00',
        updatedAt: '2026-01-20 17:00:00',
        icon: 'service',
        tags: ['客户服务', '售后支持'],
        knowledgeBaseCount: 4,
        conversationCount: 3200,
        avatar: '',
    },
];

// ==================== Mock API 处理函数 ====================

/**
 * 获取应用列表
 * POST /bigmodel/api/getApplicationList
 */
export const mockFetchApplicationList = async (request: MockRequest) => {
    const { pageNum = 1, pageSize = 10, category, status, keyword } = request.data || {};

    console.log('[Mock] 获取应用列表', { pageNum, pageSize, category, status, keyword });

    // 筛选数据
    let filteredData = [...mockApplicationsData];

    if (category && category !== 'all') {
        filteredData = filteredData.filter(app => app.category === category);
    }

    if (status && status !== 'all') {
        filteredData = filteredData.filter(app => app.status === status);
    }

    if (keyword) {
        filteredData = filteredData.filter(app =>
            app.name.toLowerCase().includes(keyword.toLowerCase()) ||
            app.description.toLowerCase().includes(keyword.toLowerCase())
        );
    }

    // 分页
    const total = filteredData.length;
    const startIndex = (pageNum - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const list = filteredData.slice(startIndex, endIndex);

    return {
        code: 200,
        message: 'success',
        data: {
            list,
            total,
            pageNum,
            pageSize,
        },
    };
};

/**
 * 获取应用详情
 * GET /bigmodel/api/selectApplication/:id
 */
export const mockFetchApplicationDetail = async (request: MockRequest) => {
    const appId = request.params?.id;

    console.log('[Mock] 获取应用详情', { appId });

    const app = mockApplicationsData.find(a => a.id === appId);

    if (!app) {
        return {
            code: 404,
            message: '应用不存在',
            data: null,
        };
    }

    return {
        code: 200,
        message: 'success',
        data: {
            ...app,
            // 扩展详情信息
            knowledgeBases: [
                { id: `kb_${appId}_1`, name: `${app.name}核心知识库` },
                { id: `kb_${appId}_2`, name: `${app.name}补充资料` },
            ],
            recentConversations: [
                { id: `conv_001`, user: '用户 A', time: '2026-04-02 10:30:00', question: '如何...' },
                { id: `conv_002`, user: '用户 B', time: '2026-04-02 09:15:00', question: '请问...' },
            ],
        },
    };
};

/**
 * 创建应用
 * POST /bigmodel/api/createApplication
 */
export const mockCreateApplication = async (request: MockRequest) => {
    const { name, description, category, knowledgeBaseIds } = request.data || {};

    console.log('[Mock] 创建应用', { name, description, category, knowledgeBaseIds });

    // 生成新 ID
    const newId = `app_${String(mockApplicationsData.length + 1).padStart(3, '0')}`;

    const newApp = {
        id: newId,
        name: name || '新应用',
        description: description || '暂无描述',
        category: category || 'professional',
        status: 'auditing', // 新建应用默认进入审核状态
        creatorId: 'current_user',
        creator: '当前用户',
        maintainers: ['当前用户'],
        createdAt: new Date().toLocaleString('zh-CN'),
        updatedAt: new Date().toLocaleString('zh-CN'),
        icon: 'default',
        tags: [],
        knowledgeBaseCount: knowledgeBaseIds?.length || 0,
        conversationCount: 0,
        avatar: '',
    };

    mockApplicationsData.unshift(newApp);

    return {
        code: 200,
        message: '创建成功',
        data: {
            id: newId,
            ...newApp,
        },
    };
};

/**
 * 更新应用
 * PUT /bigmodel/api/updateApplication/:id
 */
export const mockUpdateApplication = async (request: MockRequest) => {
    const appId = request.params?.id;
    const { name, description, category, status, tags } = request.data || {};

    console.log('[Mock] 更新应用', { appId, name, description, category, status, tags });

    const appIndex = mockApplicationsData.findIndex(a => a.id === appId);

    if (appIndex === -1) {
        return {
            code: 404,
            message: '应用不存在',
            data: null,
        };
    }

    const app = mockApplicationsData[appIndex];
    mockApplicationsData[appIndex] = {
        ...app,
        name: name || app.name,
        description: description || app.description,
        category: category || app.category,
        status: status || app.status,
        tags: tags !== undefined ? tags : app.tags,
        updatedAt: new Date().toLocaleString('zh-CN'),
    };

    return {
        code: 200,
        message: '更新成功',
        data: mockApplicationsData[appIndex],
    };
};

/**
 * 删除应用
 * DELETE /bigmodel/api/delApplication/:id
 */
export const mockDeleteApplication = async (request: MockRequest) => {
    const appId = request.params?.id;

    console.log('[Mock] 删除应用', { appId });

    const appIndex = mockApplicationsData.findIndex(a => a.id === appId);

    if (appIndex === -1) {
        return {
            code: 404,
            message: '应用不存在',
            data: null,
        };
    }

    mockApplicationsData.splice(appIndex, 1);

    return {
        code: 200,
        message: '删除成功',
        data: { id: appId },
    };
};

/**
 * 获取我的应用列表
 * GET /bigmodel/api/myApplications
 */
export const mockFetchMyApplications = async (request: MockRequest) => {
    const userId = 'current_user'; // 当前登录用户 ID

    console.log('[Mock] 获取我的应用列表', { userId });

    const myApps = mockApplicationsData.filter(app => app.creatorId === userId);

    return {
        code: 200,
        message: 'success',
        data: {
            list: myApps,
            total: myApps.length,
        },
    };
};

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

export const applicationMockHandlers = {
    'POST /bigmodel/api/getApplicationList': mockFetchApplicationList,
    'GET /bigmodel/api/selectApplication/:id': mockFetchApplicationDetail,
    'POST /bigmodel/api/createApplication': mockCreateApplication,
    'PUT /bigmodel/api/updateApplication/:id': mockUpdateApplication,
    'DELETE /bigmodel/api/delApplication/:id': mockDeleteApplication,
    'GET /bigmodel/api/myApplications': mockFetchMyApplications,
};
