import { Request, Response } from 'express';
import { ExamTaskModel } from '../models/examTask';
import { UserGroupModel } from '../models/userGroup';

export class ExamTaskController {
  static async getTasks(req: Request, res: Response) {
    try {
      const tasks = await ExamTaskModel.findAll();
      res.json({
        success: true,
        data: tasks
      });
    } catch (error: any) {
      res.status(500).json({
        success: false,
        message: error.message || '获取考试任务失败'
      });
    }
  }

  static async createTask(req: Request, res: Response) {
    try {
      const { name, subjectId, startAt, endAt, userIds = [], groupIds = [] } = req.body;

      if (!name || !subjectId || !startAt || !endAt) {
        return res.status(400).json({
          success: false,
          message: '参数不完整'
        });
      }

      // 合并用户列表和用户组中的用户
      const finalUserIds = new Set<string>(userIds);
      
      if (Array.isArray(groupIds) && groupIds.length > 0) {
        for (const groupId of groupIds) {
          const members = await UserGroupModel.getMembers(groupId);
          members.forEach(m => finalUserIds.add(m.id));
        }
      }

      if (finalUserIds.size === 0) {
        return res.status(400).json({
          success: false,
          message: '请至少选择一位用户或一个用户组'
        });
      }

      const task = await ExamTaskModel.create({
        name,
        subjectId,
        startAt,
        endAt,
        userIds: Array.from(finalUserIds),
        selectionConfig: JSON.stringify({ userIds, groupIds })
      });

      res.json({
        success: true,
        data: task
      });
    } catch (error: any) {
      res.status(400).json({
        success: false,
        message: error.message || '新增考试任务失败'
      });
    }
  }

  static async updateTask(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const { name, subjectId, startAt, endAt, userIds = [], groupIds = [] } = req.body;

      if (!name || !subjectId || !startAt || !endAt) {
        return res.status(400).json({
          success: false,
          message: '参数不完整'
        });
      }

      // 合并用户列表和用户组中的用户
      const finalUserIds = new Set<string>(userIds);
      
      if (Array.isArray(groupIds) && groupIds.length > 0) {
        for (const groupId of groupIds) {
          const members = await UserGroupModel.getMembers(groupId);
          members.forEach(m => finalUserIds.add(m.id));
        }
      }

      if (finalUserIds.size === 0) {
        return res.status(400).json({
          success: false,
          message: '请至少选择一位用户或一个用户组'
        });
      }

      const task = await ExamTaskModel.update(id, {
        name,
        subjectId,
        startAt,
        endAt,
        userIds: Array.from(finalUserIds),
        selectionConfig: JSON.stringify({ userIds, groupIds })
      });

      res.json({
        success: true,
        data: task
      });
    } catch (error: any) {
      const message = error.message || '更新考试任务失败';
      res.status(message === '任务不存在' ? 404 : 400).json({
        success: false,
        message
      });
    }
  }

  static async deleteTask(req: Request, res: Response) {
    try {
      const { id } = req.params;
      await ExamTaskModel.delete(id);

      res.json({
        success: true,
        message: '删除成功'
      });
    } catch (error: any) {
      const message = error.message || '删除考试任务失败';
      res.status(message === '任务不存在' ? 404 : 400).json({
        success: false,
        message
      });
    }
  }

  static async getTaskReport(req: Request, res: Response) {
    try {
      const { id } = req.params;
      const report = await ExamTaskModel.getReport(id);

      res.json({
        success: true,
        data: report
      });
    } catch (error: any) {
      const message = error.message || '获取任务报表失败';
      res.status(message === '任务不存在' ? 404 : 400).json({
        success: false,
        message
      });
    }
  }

  static async getUserTasks(req: Request, res: Response) {
    try {
      const { userId } = req.params;
      
      if (!userId) {
        return res.status(400).json({
          success: false,
          message: '用户ID不能为空'
        });
      }

      const tasks = await ExamTaskModel.getUserTasks(userId);
      
      res.json({
        success: true,
        data: tasks
      });
    } catch (error: any) {
      res.status(500).json({
        success: false,
        message: error.message || '获取用户任务失败'
      });
    }
  }

  static async getTaskUsers(req: Request, res: Response) {
    try {
      const { id } = req.params;
      
      if (!id) {
        return res.status(400).json({
          success: false,
          message: '任务ID不能为空'
        });
      }

      const userIds = await ExamTaskModel.getTaskUsers(id);
      
      res.json({
        success: true,
        data: userIds
      });
    } catch (error: any) {
      res.status(500).json({
        success: false,
        message: error.message || '获取任务用户失败'
      });
    }
  }
}