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

class InstallationTaskController {
  
  // 获取待安装任务列表
  async getInstallationTasks(req, res) {
    try {
      const {
        page = 1,
        pageSize = 10,
        policyNumber,
        customerName,
        installationStatus,
        priority,
        keyword,
        startDate,
        endDate
      } = req.query;

      const offset = (page - 1) * pageSize;
      const limit = parseInt(pageSize);

      // 构建查询条件
      const whereConditions = {};
      
      if (policyNumber) {
        whereConditions.policyNumber = { [Op.like]: `%${policyNumber}%` };
      }
      
      if (customerName) {
        whereConditions.customerName = { [Op.like]: `%${customerName}%` };
      }
      
      if (installationStatus) {
        whereConditions.installationStatus = installationStatus;
      }
      
      if (priority) {
        whereConditions.priority = priority;
      }
      
      // 关键字搜索（搜索申请单号、保单编号、客户姓名等）
      if (keyword) {
        whereConditions[Op.or] = [
          { applicationNumber: { [Op.like]: `%${keyword}%` } },
          { policyNumber: { [Op.like]: `%${keyword}%` } },
          { customerName: { [Op.like]: `%${customerName}%` } },
          { productName: { [Op.like]: `%${keyword}%` } }
        ];
      }
      
      if (startDate && endDate) {
        whereConditions.taskGeneratedTime = {
          [Op.between]: [new Date(startDate), new Date(endDate)]
        };
      }

      const { count, rows } = await InstallationTask.findAndCountAll({
        where: whereConditions,
        order: [['taskGeneratedTime', 'DESC']],
        offset,
        limit
      });

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

    } catch (error) {
      logger.error('获取待安装任务列表失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '获取待安装任务列表失败',
        error: error.message
      });
    }
  }

  // 创建待安装任务
  async createInstallationTask(req, res) {
    try {
      const {
        applicationNumber,
        policyNumber,
        productName,
        customerName,
        idType,
        idNumber,
        livestockSupplyType,
        pendingDevices,
        installationStatus = '待安装',
        priority = '中',
        assignedTo,
        taskGeneratedTime = new Date()
      } = req.body;

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

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

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

      const installationTask = await InstallationTask.create({
        applicationNumber,
        policyNumber,
        productName,
        customerName,
        idType: idType || '身份证',
        idNumber: idNumber || '',
        livestockSupplyType,
        pendingDevices: pendingDevices ? JSON.stringify(pendingDevices) : null,
        installationStatus,
        priority,
        assignedTo,
        taskGeneratedTime,
        createdBy: req.user?.id
      });

      res.status(201).json({
        code: 201,
        status: 'success',
        message: '创建待安装任务成功',
        data: installationTask
      });

    } catch (error) {
      logger.error('创建待安装任务失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '创建待安装任务失败',
        error: error.message
      });
    }
  }

  // 获取待安装任务详情
  async getInstallationTaskById(req, res) {
    try {
      const { id } = req.params;

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

      if (!installationTask) {
        return res.status(404).json({
          code: 404,
          status: 'error',
          message: '待安装任务不存在'
        });
      }

      res.json({
        code: 200,
        status: 'success',
        message: '获取待安装任务详情成功',
        data: installationTask
      });

    } catch (error) {
      logger.error('获取待安装任务详情失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '获取待安装任务详情失败',
        error: error.message
      });
    }
  }

  // 更新待安装任务
  async updateInstallationTask(req, res) {
    try {
      const { id } = req.params;
      const updateData = { ...req.body };
      
      // 添加更新人信息
      updateData.updatedBy = req.user?.id;
      
      // 处理设备数据
      if (updateData.pendingDevices) {
        updateData.pendingDevices = JSON.stringify(updateData.pendingDevices);
      }

      // 处理安装完成时间
      if (updateData.installationStatus === '已安装' && !updateData.installationCompletedTime) {
        updateData.installationCompletedTime = new Date();
      }

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

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

      // 获取更新后的任务
      const updatedTask = await InstallationTask.findByPk(id);

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

    } catch (error) {
      logger.error('更新待安装任务失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '更新待安装任务失败',
        error: error.message
      });
    }
  }

  // 删除待安装任务
  async deleteInstallationTask(req, res) {
    try {
      const { id } = req.params;

      const deletedCount = await InstallationTask.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) {
      logger.error('删除待安装任务失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '删除待安装任务失败',
        error: error.message
      });
    }
  }

  // 批量操作待安装任务
  async batchOperateInstallationTasks(req, res) {
    try {
      const { ids, operation, data } = req.body;

      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        return res.status(400).json({
          code: 400,
          status: 'error',
          message: '任务ID列表不能为空'
        });
      }

      let result;
      switch (operation) {
        case 'assign':
          if (!data.assignedTo) {
            return res.status(400).json({
              code: 400,
              status: 'error',
              message: '分配操作需要指定分配给的用户'
            });
          }
          result = await InstallationTask.update(
            { assignedTo: data.assignedTo, updatedBy: req.user?.id },
            { where: { id: ids } }
          );
          break;
        case 'updateStatus':
          if (!data.installationStatus) {
            return res.status(400).json({
              code: 400,
              status: 'error',
              message: '状态更新操作需要指定新状态'
            });
          }
          result = await InstallationTask.update(
            { installationStatus: data.installationStatus, updatedBy: req.user?.id },
            { where: { id: ids } }
          );
          break;
        case 'delete':
          result = await InstallationTask.destroy({ where: { id: ids } });
          break;
        default:
          return res.status(400).json({
            code: 400,
            status: 'error',
            message: '不支持的操作类型'
          });
      }

      res.json({
        code: 200,
        status: 'success',
        message: `批量${operation}操作完成`,
        data: { affectedRows: result[0] || result }
      });

    } catch (error) {
      logger.error('批量操作待安装任务失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '批量操作失败',
        error: error.message
      });
    }
  }

  // 导出待安装任务数据
  async exportInstallationTasks(req, res) {
    try {
      const { ids } = req.query;
      let where = {};
      
      if (ids) {
        where.id = { [Op.in]: ids.split(',') };
      }

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

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

    } catch (error) {
      logger.error('导出待安装任务数据失败:', error);
      res.status(500).json({
        code: 500,
        status: 'error',
        message: '导出数据失败',
        error: error.message
      });
    }
  }

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

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

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

      // 本月新增任务
      const thisMonth = await InstallationTask.count({
        where: {
          taskGeneratedTime: {
            [Op.gte]: new Date(new Date().getFullYear(), new Date().getMonth(), 1)
          }
        }
      });

      res.json({
        code: 200,
        status: 'success',
        message: '获取任务统计信息成功',
        data: {
          total,
          thisMonth,
          statusStats,
          priorityStats
        }
      });

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

  // 导出待安装任务列表到Excel
  async exportToExcel(req, res) {
    try {
      const { policyNumber, keyword } = req.query;

      // 构建查询条件（使用数据库字段名，因为raw:true模式）
      const whereConditions = {};
      
      if (policyNumber) {
        whereConditions.policy_number = { [Op.like]: `%${policyNumber}%` };
      }
      
      // 关键字搜索
      if (keyword) {
        whereConditions[Op.or] = [
          { application_number: { [Op.like]: `%${keyword}%` } },
          { policy_number: { [Op.like]: `%${keyword}%` } },
          { customer_name: { [Op.like]: `%${keyword}%` } },
          { installation_address: { [Op.like]: `%${keyword}%` } }
        ];
      }

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

      console.log(`导出查询到 ${tasks.length} 条数据`);

      // 准备导出数据（Sequelize自动转换为驼峰格式）
      const exportData = tasks.map(task => {
        const data = task.toJSON ? task.toJSON() : task;
        return {
          applicationNumber: data.applicationNumber || '',
          policyNumber: data.policyNumber || '',
          productName: data.productName || '',
          customerName: data.customerName || '',
          idType: data.idType || '',
          idNumber: data.idNumber || '',
          livestockSupplyType: data.livestockSupplyType || '',
          installationStatus: data.installationStatus || '',
          priority: data.priority || '',
          installationAddress: data.installationAddress || '',
          contactPhone: data.contactPhone || '',
          taskGeneratedTime: ExcelExport.formatDate(data.taskGeneratedTime),
          installationCompletedTime: ExcelExport.formatDate(data.installationCompletedTime),
          createdAt: ExcelExport.formatDate(data.created_at || data.createdAt),
          updatedAt: ExcelExport.formatDate(data.updated_at || data.updatedAt)
        };
      });

      // 定义列
      const columns = [
        { header: '申请单号', key: 'applicationNumber', width: 20 },
        { header: '保单编号', key: 'policyNumber', width: 20 },
        { header: '产品名称', key: 'productName', width: 25 },
        { header: '客户姓名', key: 'customerName', width: 15 },
        { header: '证件类型', key: 'idType', width: 12 },
        { header: '证件号码', key: 'idNumber', width: 20 },
        { header: '养殖生资种类', key: 'livestockSupplyType', width: 20 },
        { header: '安装状态', key: 'installationStatus', width: 12 },
        { header: '优先级', key: 'priority', width: 10 },
        { header: '安装地址', key: 'installationAddress', width: 30 },
        { header: '联系电话', key: 'contactPhone', width: 15 },
        { header: '任务生成时间', key: 'taskGeneratedTime', width: 20 },
        { header: '安装完成时间', key: 'installationCompletedTime', width: 20 },
        { 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=installation_tasks_${Date.now()}.xlsx`);
      
      // 发送文件
      res.send(buffer);

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

module.exports = new InstallationTaskController();