const { SupervisoryTask, User } = require('../models');
const { Op } = require('sequelize');
const ExcelExport = require('../utils/excelExport');

/**
 * 监管任务控制器
 */
class SupervisoryTaskController {

  /**
   * 获取监管任务列表（支持分页和搜索）
   */
  static async getList(req, res) {
    try {
      const {
        page = 1,
        limit = 10,
        policyNumber = '',
        customerName = '',
        taskStatus = '',
        priority = '',
        dateRange = '',
        sortBy = 'createdAt',
        sortOrder = 'DESC'
      } = req.query;

      // 状态映射：英文到中文
      const statusMap = {
        'pending': '待处理',
        'processing': '处理中',
        'completed': '已完成',
        'rejected': '已取消'
      };

      // 优先级映射：英文到中文
      const priorityMap = {
        'low': '低',
        'medium': '中',
        'high': '高',
        'urgent': '紧急'
      };

      // 构建查询条件
      const where = {};
      
      if (policyNumber) {
        where.policyNumber = { [Op.like]: `%${policyNumber}%` };
      }
      
      if (customerName) {
        where.customerName = { [Op.like]: `%${customerName}%` };
      }
      
      if (taskStatus) {
        // 如果传入的是英文状态，转换为中文
        where.taskStatus = statusMap[taskStatus] || taskStatus;
      }
      
      if (priority) {
        // 如果传入的是英文优先级，转换为中文
        where.priority = priorityMap[priority] || priority;
      }
      
      // 日期范围筛选
      if (dateRange) {
        const [startDate, endDate] = dateRange.split(',');
        if (startDate && endDate) {
          where.createdAt = {
            [Op.between]: [new Date(startDate), new Date(endDate)]
          };
        }
      }

      // 分页参数
      const offset = (parseInt(page) - 1) * parseInt(limit);

      // 查询数据
      const { count, rows } = await SupervisoryTask.findAndCountAll({
        where,
        include: [
          {
            model: User,
            as: 'assignedUser',
            attributes: ['id', 'username', 'real_name']
          },
          {
            model: User,
            as: 'creator',
            attributes: ['id', 'username', 'real_name']
          }
        ],
        order: [[sortBy, sortOrder.toUpperCase()]],
        limit: parseInt(limit),
        offset
      });

      res.json({
        code: 200,
        status: 'success',
        message: '获取监管任务列表成功',
        data: {
          list: rows,
          total: count,
          page: parseInt(page),
          limit: parseInt(limit),
          totalPages: Math.ceil(count / parseInt(limit))
        }
      });

    } catch (error) {
      console.error('获取监管任务列表失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '获取监管任务列表失败',
        error: error.message
      });
    }
  }

  /**
   * 根据ID获取监管任务详情
   */
  static async getById(req, res) {
    try {
      const { id } = req.params;

      const task = await SupervisoryTask.findByPk(id, {
        include: [
          {
            model: User,
            as: 'assignedUser',
            attributes: ['id', 'username', 'real_name']
          },
          {
            model: User,
            as: 'creator',
            attributes: ['id', 'username', 'real_name']
          },
          {
            model: User,
            as: 'updater',
            attributes: ['id', 'username', 'real_name']
          }
        ]
      });

      if (!task) {
        return res.status(404).json({
          code: 404,
          status: 'error',
          message: '监管任务不存在'
        });
      }

      res.json({
        code: 200,
        status: 'success',
        message: '获取监管任务详情成功',
        data: task
      });

    } catch (error) {
      console.error('获取监管任务详情失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '获取监管任务详情失败',
        error: error.message
      });
    }
  }

  /**
   * 创建新的监管任务
   */
  static async create(req, res) {
    try {
      const {
        applicationNumber,
        policyNumber,
        productName,
        insurancePeriod,
        customerName,
        idType,
        idNumber,
        applicableSupplies,
        supervisorySuppliesQuantity,
        taskStatus = '待处理',
        priority = '中',
        assignedTo,
        dueDate,
        notes
      } = req.body;

      // 验证必填字段
      if (!applicationNumber || !policyNumber || !productName || !customerName || !idNumber) {
        return res.status(400).json({
          code: 400,
          status: 'error',
          message: '申请单号、保单编号、产品名称、客户姓名和证件号码为必填项'
        });
      }

      // 检查申请单号是否已存在
      const existingTask = await SupervisoryTask.findOne({
        where: { applicationNumber }
      });

      if (existingTask) {
        return res.status(409).json({
          code: 409,
          status: 'error',
          message: '该申请单号已存在监管任务'
        });
      }

      // 创建监管任务
      const task = await SupervisoryTask.create({
        applicationNumber,
        policyNumber,
        productName,
        insurancePeriod,
        customerName,
        idType,
        idNumber,
        applicableSupplies: JSON.stringify(applicableSupplies),
        supervisorySuppliesQuantity: parseInt(supervisorySuppliesQuantity) || 0,
        taskStatus,
        priority,
        assignedTo,
        dueDate: dueDate ? new Date(dueDate) : null,
        notes,
        createdBy: req.user?.id
      });

      // 查询完整的任务信息（包含关联数据）
      const createdTask = await SupervisoryTask.findByPk(task.id, {
        include: [
          {
            model: User,
            as: 'assignedUser',
            attributes: ['id', 'username', 'real_name']
          },
          {
            model: User,
            as: 'creator',
            attributes: ['id', 'username', 'real_name']
          }
        ]
      });

      res.status(201).json({
        code: 201,
        status: 'success',
        message: '创建监管任务成功',
        data: createdTask
      });

    } catch (error) {
      console.error('创建监管任务失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '创建监管任务失败',
        error: error.message
      });
    }
  }

  /**
   * 更新监管任务
   */
  static async update(req, res) {
    try {
      const { id } = req.params;
      const updateData = { ...req.body };

      // 添加更新人信息
      updateData.updatedBy = req.user?.id;

      // 处理适用生资数据
      if (updateData.applicableSupplies) {
        updateData.applicableSupplies = JSON.stringify(updateData.applicableSupplies);
      }

      // 处理截止日期
      if (updateData.dueDate) {
        updateData.dueDate = new Date(updateData.dueDate);
      }

      // 处理完成时间
      if (updateData.taskStatus === '已完成' && !updateData.completedAt) {
        updateData.completedAt = new Date();
      }

      const [updatedCount] = await SupervisoryTask.update(updateData, {
        where: { id }
      });

      if (updatedCount === 0) {
        return res.status(404).json({
          code: 404,
          status: 'error',
          message: '监管任务不存在或未做任何修改'
        });
      }

      // 查询更新后的任务信息
      const updatedTask = await SupervisoryTask.findByPk(id, {
        include: [
          {
            model: User,
            as: 'assignedUser',
            attributes: ['id', 'username', 'real_name']
          },
          {
            model: User,
            as: 'updater',
            attributes: ['id', 'username', 'real_name']
          }
        ]
      });

      res.json({
        code: 200,
        status: 'success',
        message: '更新监管任务成功',
        data: updatedTask
      });

    } catch (error) {
      console.error('更新监管任务失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '更新监管任务失败',
        error: error.message
      });
    }
  }

  /**
   * 删除监管任务
   */
  static async delete(req, res) {
    try {
      const { id } = req.params;

      const deletedCount = await SupervisoryTask.destroy({
        where: { id }
      });

      if (deletedCount === 0) {
        return res.status(404).json({
          code: 404,
          status: 'error',
          message: '监管任务不存在'
        });
      }

      res.json({
        code: 200,
        status: 'success',
        message: '删除监管任务成功'
      });

    } catch (error) {
      console.error('删除监管任务失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '删除监管任务失败',
        error: error.message
      });
    }
  }

  /**
   * 批量创建监管任务
   */
  static async bulkCreate(req, res) {
    try {
      const { tasks } = req.body;

      if (!tasks || !Array.isArray(tasks) || tasks.length === 0) {
        return res.status(400).json({
          code: 400,
          status: 'error',
          message: '请提供有效的任务数据数组'
        });
      }

      // 验证并处理任务数据
      const processedTasks = tasks.map(task => ({
        ...task,
        applicableSupplies: JSON.stringify(task.applicableSupplies || []),
        supervisorySuppliesQuantity: parseInt(task.supervisorySuppliesQuantity) || 0,
        taskStatus: task.taskStatus || '待处理',
        priority: task.priority || '中',
        dueDate: task.dueDate ? new Date(task.dueDate) : null,
        createdBy: req.user?.id
      }));

      const createdTasks = await SupervisoryTask.bulkCreate(processedTasks, {
        ignoreDuplicates: true,
        returning: true
      });

      res.status(201).json({
        code: 201,
        status: 'success',
        message: `批量创建监管任务成功，共创建${createdTasks.length}条记录`,
        data: {
          count: createdTasks.length,
          tasks: createdTasks
        }
      });

    } catch (error) {
      console.error('批量创建监管任务失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '批量创建监管任务失败',
        error: error.message
      });
    }
  }

  /**
   * 导出监管任务数据
   */
  static async export(req, res) {
    try {
      const { ids, ...filters } = req.query;

      let where = {};

      // 如果指定了ID列表，则只导出指定的任务
      if (ids) {
        where.id = { [Op.in]: ids.split(',').map(id => parseInt(id)) };
      } else {
        // 否则根据筛选条件导出
        if (filters.policyNumber) {
          where.policyNumber = { [Op.like]: `%${filters.policyNumber}%` };
        }
        if (filters.customerName) {
          where.customerName = { [Op.like]: `%${filters.customerName}%` };
        }
        if (filters.taskStatus) {
          where.taskStatus = filters.taskStatus;
        }
      }

      const tasks = await SupervisoryTask.findAll({
        where,
        include: [
          {
            model: User,
            as: 'assignedUser',
            attributes: ['username', 'real_name']
          },
          {
            model: User,
            as: 'creator',
            attributes: ['username', 'real_name']
          }
        ],
        order: [['createdAt', 'DESC']]
      });

      res.json({
        code: 200,
        status: 'success',
        message: '导出监管任务数据成功',
        data: tasks
      });

    } catch (error) {
      console.error('导出监管任务数据失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '导出监管任务数据失败',
        error: error.message
      });
    }
  }

  /**
   * 获取任务统计信息
   */
  static async getStatistics(req, res) {
    try {
      // 按状态统计
      const statusStats = await SupervisoryTask.findAll({
        attributes: [
          'taskStatus',
          [SupervisoryTask.sequelize.fn('COUNT', SupervisoryTask.sequelize.col('id')), 'count']
        ],
        group: ['taskStatus']
      });

      // 按优先级统计
      const priorityStats = await SupervisoryTask.findAll({
        attributes: [
          'priority',
          [SupervisoryTask.sequelize.fn('COUNT', SupervisoryTask.sequelize.col('id')), 'count']
        ],
        group: ['priority']
      });

      // 总数统计
      const total = await SupervisoryTask.count();

      res.json({
        code: 200,
        status: 'success',
        message: '获取任务统计信息成功',
        data: {
          total,
          statusStats: statusStats.map(item => ({
            status: item.taskStatus,
            count: parseInt(item.dataValues.count)
          })),
          priorityStats: priorityStats.map(item => ({
            priority: item.priority,
            count: parseInt(item.dataValues.count)
          }))
        }
      });

    } catch (error) {
      console.error('获取任务统计信息失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '获取任务统计信息失败',
        error: error.message
      });
    }
  }

  /**
   * 导出监管任务列表到Excel
   */
  static async exportToExcel(req, res) {
    try {
      const { policyNumber, customerName } = req.query;

      // 构建查询条件
      const where = {};
      
      if (policyNumber) {
        where.policyNumber = { [Op.like]: `%${policyNumber}%` };
      }
      
      if (customerName) {
        where.customerName = { [Op.like]: `%${customerName}%` };
      }

      // 查询所有符合条件的数据
      const tasks = await SupervisoryTask.findAll({
        where,
        order: [['createdAt', 'DESC']],
        raw: true
      });

      // 状态映射
      const statusMap = {
        pending: '待处理',
        processing: '处理中',
        completed: '已完成',
        rejected: '已拒绝'
      };

      const priorityMap = {
        low: '低',
        medium: '中',
        high: '高',
        urgent: '紧急'
      };

      // 准备导出数据
      const exportData = tasks.map(task => ({
        policyNumber: task.policyNumber || '',
        customerName: task.customerName || '',
        productName: task.productName || '',
        insurancePeriod: task.insurancePeriod || '',
        applicableAmount: task.applicableAmount || '',
        taskStatus: ExcelExport.formatStatus(task.taskStatus, statusMap),
        priority: ExcelExport.formatStatus(task.priority, priorityMap),
        createdAt: ExcelExport.formatDate(task.createdAt),
        updatedAt: ExcelExport.formatDate(task.updatedAt)
      }));

      // 定义列
      const columns = [
        { header: '保单编号', key: 'policyNumber', width: 20 },
        { header: '客户姓名', key: 'customerName', width: 15 },
        { header: '产品名称', key: 'productName', width: 25 },
        { header: '保险期间', key: 'insurancePeriod', width: 25 },
        { header: '适用金额', key: 'applicableAmount', width: 15 },
        { header: '任务状态', key: 'taskStatus', width: 12 },
        { header: '优先级', key: 'priority', width: 12 },
        { header: '创建时间', key: 'createdAt', width: 20 },
        { header: '更新时间', key: 'updatedAt', width: 20 }
      ];

      // 生成Excel
      const buffer = await ExcelExport.exportToExcel(exportData, columns, '监管任务列表');

      // 设置响应头
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition', `attachment; filename=supervision_tasks_${Date.now()}.xlsx`);
      
      // 发送文件
      res.send(buffer);

    } catch (error) {
      console.error('导出监管任务失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '导出失败',
        error: error.message
      });
    }
  }
}

module.exports = SupervisoryTaskController;