/**
 * 传感器数据模型
 * @file SensorData.js
 * @description 环境监控数据表模型，存储温度、湿度等传感器数据
 */
const { DataTypes } = require('sequelize');
const BaseModel = require('./BaseModel');

class SensorData extends BaseModel {
  static init(sequelize) {
    return super.init({
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        comment: '传感器数据ID'
      },
      device_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        comment: '设备ID',
        references: {
          model: 'devices',
          key: 'id'
        }
      },
      farm_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        comment: '养殖场ID',
        references: {
          model: 'farms',
          key: 'id'
        }
      },
      sensor_type: {
        type: DataTypes.ENUM('temperature', 'humidity', 'ph', 'oxygen', 'ammonia', 'light'),
        allowNull: false,
        comment: '传感器类型：temperature-温度, humidity-湿度, ph-酸碱度, oxygen-氧气, ammonia-氨气, light-光照'
      },
      value: {
        type: DataTypes.DECIMAL(10, 2),
        allowNull: false,
        comment: '传感器数值'
      },
      unit: {
        type: DataTypes.STRING(20),
        allowNull: false,
        comment: '数值单位（如：°C, %, ppm等）'
      },
      location: {
        type: DataTypes.STRING(100),
        allowNull: true,
        comment: '传感器位置描述'
      },
      status: {
        type: DataTypes.ENUM('normal', 'warning', 'error'),
        defaultValue: 'normal',
        comment: '数据状态：normal-正常, warning-警告, error-异常'
      },
      recorded_at: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
        comment: '数据记录时间'
      }
    }, {
      sequelize,
      modelName: 'SensorData',
      tableName: 'sensor_data',
      timestamps: true,
      createdAt: 'created_at',
      updatedAt: 'updated_at',
      indexes: [
          {
            fields: ['device_id']
          },
          {
            fields: ['farm_id']
          },
          {
            fields: ['sensor_type']
          },
          {
            fields: ['recorded_at']
          },
          {
            fields: ['farm_id', 'sensor_type', 'recorded_at']
          }
        ],
      comment: '传感器环境监控数据表'
    });
  }

  static associate(models) {
    // 关联关系已在index.js中定义，这里不需要重复定义
  }

  /**
   * 获取指定养殖场的最新传感器数据
   * @param {number} farmId - 养殖场ID
   * @param {string} sensorType - 传感器类型
   * @param {number} limit - 数据条数限制
   * @returns {Promise<Array>} 传感器数据列表
   */
  static async getLatestData(farmId, sensorType, limit = 24) {
    try {
      const whereClause = {
        farm_id: farmId
      };
      
      if (sensorType) {
        whereClause.sensor_type = sensorType;
      }

      return await this.findAll({
        where: whereClause,
        order: [['recorded_at', 'DESC']],
        limit: limit,
        include: [{
          model: this.sequelize.models.Device,
          as: 'device',
          attributes: ['id', 'name', 'type']
        }]
      });
    } catch (error) {
      console.error('获取最新传感器数据失败:', error);
      throw error;
    }
  }

  /**
   * 获取指定时间范围内的传感器数据
   * @param {number} farmId - 养殖场ID
   * @param {string} sensorType - 传感器类型
   * @param {Date} startTime - 开始时间
   * @param {Date} endTime - 结束时间
   * @returns {Promise<Array>} 传感器数据列表
   */
  static async getDataByTimeRange(farmId, sensorType, startTime, endTime) {
    try {
      return await this.findAll({
        where: {
          farm_id: farmId,
          sensor_type: sensorType,
          recorded_at: {
            [this.sequelize.Sequelize.Op.between]: [startTime, endTime]
          }
        },
        order: [['recorded_at', 'ASC']],
        include: [{
          model: this.sequelize.models.Device,
          as: 'device',
          attributes: ['id', 'name', 'type']
        }]
      });
    } catch (error) {
      console.error('获取时间范围内传感器数据失败:', error);
      throw error;
    }
  }

  /**
   * 获取传感器数据统计信息
   * @param {number} farmId - 养殖场ID
   * @param {string} sensorType - 传感器类型
   * @param {Date} startTime - 开始时间
   * @param {Date} endTime - 结束时间
   * @returns {Promise<Object>} 统计信息
   */
  static async getDataStats(farmId, sensorType, startTime, endTime) {
    const { Op, fn, col } = require('sequelize');
    
    const stats = await this.findOne({
      where: {
        farm_id: farmId,
        sensor_type: sensorType,
        recorded_at: {
          [Op.between]: [startTime, endTime]
        }
      },
      attributes: [
        [fn('AVG', col('value')), 'avgValue'],
        [fn('MIN', col('value')), 'minValue'],
        [fn('MAX', col('value')), 'maxValue'],
        [fn('COUNT', col('id')), 'dataCount']
      ],
      raw: true
    });

    return {
      average: parseFloat(stats.avgValue || 0).toFixed(2),
      minimum: parseFloat(stats.minValue || 0).toFixed(2),
      maximum: parseFloat(stats.maxValue || 0).toFixed(2),
      count: parseInt(stats.dataCount || 0)
    };
  }
}

// 初始化模型
const { sequelize } = require('../config/database-simple');
SensorData.init(sequelize);

module.exports = SensorData;