const { Device, DeviceAlert, User } = require('../models');
const { Op } = require('sequelize');
const logger = require('../utils/logger');

/**
 * 设备控制器
 */
class DeviceController {
  
  /**
   * 获取设备列表
   */
  static async getDeviceList(req, res) {
    try {
      const {
        page = 1,
        limit = 20,
        device_type,
        status,
        farm_id,
        pen_id,
        keyword
      } = req.query;

      // 构建查询条件
      const whereCondition = {};
      if (device_type) {
        whereCondition.device_type = device_type;
      }
      if (status) {
        whereCondition.status = status;
      }
      if (farm_id) {
        whereCondition.farm_id = farm_id;
      }
      if (pen_id) {
        whereCondition.pen_id = pen_id;
      }
      if (keyword) {
        whereCondition[Op.or] = [
          { device_code: { [Op.like]: `%${keyword}%` } },
          { device_name: { [Op.like]: `%${keyword}%` } },
          { device_model: { [Op.like]: `%${keyword}%` } },
          { manufacturer: { [Op.like]: `%${keyword}%` } }
        ];
      }

      const offset = (page - 1) * limit;

      const { count, rows } = await Device.findAndCountAll({
        where: whereCondition,
        include: [
          {
            model: User,
            as: 'creator',
            attributes: ['id', 'username', 'real_name'],
            required: false
          }
        ],
        order: [['created_at', 'DESC']],
        limit: parseInt(limit),
        offset: offset
      });

      res.json({
        success: true,
        data: {
          devices: rows,
          pagination: {
            current_page: parseInt(page),
            per_page: parseInt(limit),
            total: count,
            total_pages: Math.ceil(count / limit)
          }
        }
      });

    } catch (error) {
      logger.error('获取设备列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取设备列表失败',
        error: error.message
      });
    }
  }

  /**
   * 获取设备详情
   */
  static async getDeviceDetail(req, res) {
    try {
      const { id } = req.params;

      const device = await Device.findByPk(id, {
        include: [
          {
            model: User,
            as: 'creator',
            attributes: ['id', 'username', 'real_name'],
            required: false
          },
          {
            model: User,
            as: 'updater',
            attributes: ['id', 'username', 'real_name'],
            required: false
          }
        ]
      });

      if (!device) {
        return res.status(404).json({
          success: false,
          message: '设备不存在'
        });
      }

      // 获取设备相关的预警统计
      const alertStats = await DeviceAlert.findAll({
        attributes: [
          'alert_level',
          [DeviceAlert.sequelize.fn('COUNT', DeviceAlert.sequelize.col('id')), 'count']
        ],
        where: {
          device_id: id
        },
        group: ['alert_level'],
        raw: true
      });

      // 获取最近的预警记录
      const recentAlerts = await DeviceAlert.findAll({
        where: {
          device_id: id
        },
        order: [['alert_time', 'DESC']],
        limit: 5,
        attributes: ['id', 'alert_type', 'alert_level', 'alert_title', 'alert_time', 'status']
      });

      res.json({
        success: true,
        data: {
          device,
          alert_stats: alertStats,
          recent_alerts: recentAlerts
        }
      });

    } catch (error) {
      logger.error('获取设备详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取设备详情失败',
        error: error.message
      });
    }
  }

  /**
   * 创建设备
   */
  static async createDevice(req, res) {
    try {
      const {
        device_code,
        device_name,
        device_type,
        device_model,
        manufacturer,
        installation_location,
        installation_date,
        farm_id,
        pen_id,
        status = 'normal'
      } = req.body;

      const userId = req.user.id;

      // 检查设备编号是否已存在
      const existingDevice = await Device.findOne({
        where: { device_code }
      });

      if (existingDevice) {
        return res.status(400).json({
          success: false,
          message: '设备编号已存在'
        });
      }

      const device = await Device.create({
        device_code,
        device_name,
        device_type,
        device_model,
        manufacturer,
        installation_location,
        installation_date,
        farm_id,
        pen_id,
        status,
        created_by: userId,
        updated_by: userId
      });

      res.json({
        success: true,
        message: '设备创建成功',
        data: device
      });

    } catch (error) {
      logger.error('创建设备失败:', error);
      res.status(500).json({
        success: false,
        message: '创建设备失败',
        error: error.message
      });
    }
  }

  /**
   * 更新设备
   */
  static async updateDevice(req, res) {
    try {
      const { id } = req.params;
      const {
        device_code,
        device_name,
        device_type,
        device_model,
        manufacturer,
        installation_location,
        installation_date,
        farm_id,
        pen_id,
        status
      } = req.body;

      const userId = req.user.id;

      const device = await Device.findByPk(id);
      if (!device) {
        return res.status(404).json({
          success: false,
          message: '设备不存在'
        });
      }

      // 如果修改了设备编号，检查是否与其他设备重复
      if (device_code && device_code !== device.device_code) {
        const existingDevice = await Device.findOne({
          where: {
            device_code,
            id: { [Op.ne]: id }
          }
        });

        if (existingDevice) {
          return res.status(400).json({
            success: false,
            message: '设备编号已存在'
          });
        }
      }

      await device.update({
        device_code,
        device_name,
        device_type,
        device_model,
        manufacturer,
        installation_location,
        installation_date,
        farm_id,
        pen_id,
        status,
        updated_by: userId
      });

      res.json({
        success: true,
        message: '设备更新成功',
        data: device
      });

    } catch (error) {
      logger.error('更新设备失败:', error);
      res.status(500).json({
        success: false,
        message: '更新设备失败',
        error: error.message
      });
    }
  }

  /**
   * 删除设备
   */
  static async deleteDevice(req, res) {
    try {
      const { id } = req.params;

      const device = await Device.findByPk(id);
      if (!device) {
        return res.status(404).json({
          success: false,
          message: '设备不存在'
        });
      }

      // 检查是否有关联的预警记录
      const alertCount = await DeviceAlert.count({
        where: { device_id: id }
      });

      if (alertCount > 0) {
        return res.status(400).json({
          success: false,
          message: '该设备存在预警记录，无法删除'
        });
      }

      await device.destroy();

      res.json({
        success: true,
        message: '设备删除成功'
      });

    } catch (error) {
      logger.error('删除设备失败:', error);
      res.status(500).json({
        success: false,
        message: '删除设备失败',
        error: error.message
      });
    }
  }

  /**
   * 获取设备类型列表
   */
  static async getDeviceTypes(req, res) {
    try {
      const deviceTypes = await Device.findAll({
        attributes: [
          [Device.sequelize.fn('DISTINCT', Device.sequelize.col('device_type')), 'device_type']
        ],
        where: {
          device_type: {
            [Op.ne]: null
          }
        },
        raw: true
      });

      res.json({
        success: true,
        data: deviceTypes.map(item => item.device_type)
      });

    } catch (error) {
      logger.error('获取设备类型失败:', error);
      res.status(500).json({
        success: false,
        message: '获取设备类型失败',
        error: error.message
      });
    }
  }

  /**
   * 获取设备状态统计
   */
  static async getDeviceStats(req, res) {
    try {
      const { farm_id } = req.query;

      const whereCondition = {};
      if (farm_id) {
        whereCondition.farm_id = farm_id;
      }

      // 按状态统计
      const devicesByStatus = await Device.findAll({
        attributes: [
          'status',
          [Device.sequelize.fn('COUNT', Device.sequelize.col('id')), 'count']
        ],
        where: whereCondition,
        group: ['status'],
        raw: true
      });

      // 按类型统计
      const devicesByType = await Device.findAll({
        attributes: [
          'device_type',
          [Device.sequelize.fn('COUNT', Device.sequelize.col('id')), 'count']
        ],
        where: whereCondition,
        group: ['device_type'],
        raw: true
      });

      // 总设备数
      const totalDevices = await Device.count({
        where: whereCondition
      });

      res.json({
        success: true,
        data: {
          total_devices: totalDevices,
          devices_by_status: devicesByStatus,
          devices_by_type: devicesByType
        }
      });

    } catch (error) {
      logger.error('获取设备统计失败:', error);
      res.status(500).json({
        success: false,
        message: '获取设备统计失败',
        error: error.message
      });
    }
  }
}

module.exports = DeviceController;