const { DataTypes, Sequelize } = require('sequelize');
const config = require('../config/index.js');

// 创建专门的Sequelize实例，不使用underscored
const sequelize = new Sequelize(
  config.DB_CONFIG.database,
  config.DB_CONFIG.user,
  config.DB_CONFIG.password,
  {
    host: config.DB_CONFIG.host,
    port: config.DB_CONFIG.port,
    dialect: config.DB_CONFIG.dialect,
    logging: console.log,
    define: {
      timestamps: true,
      paranoid: false,
      underscored: false, // 明确设置为false
      freezeTableName: true
    },
    timezone: '+08:00'
  }
);

const DeviceWarning = sequelize.define('DeviceWarning', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
  },
  farmName: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '养殖场名称',
    field: 'farmName'
  },
  farmerName: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '养殖户名称',
    field: 'farmerName'
  },
  phone: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '联系电话',
    field: 'phone'
  },
  deviceType: {
    type: DataTypes.ENUM('智能耳标', '智能项圈', '智能主机'),
    allowNull: false,
    comment: '设备类型',
    field: 'deviceType'
  },
  deviceNumber: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '设备编号',
    field: 'deviceNumber'
  },
  alertType: {
    type: DataTypes.ENUM('设备离线', '电量不足', '信号异常', '温度异常', '其他'),
    allowNull: false,
    comment: '预警类型',
    field: 'alertType'
  },
  alertLevel: {
    type: DataTypes.ENUM('high', 'medium', 'low'),
    allowNull: false,
    defaultValue: 'medium',
    comment: '预警级别 (高, 中, 低)',
    field: 'alertLevel'
  },
  alertTime: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    comment: '预警时间',
    field: 'alertTime'
  },
  status: {
    type: DataTypes.ENUM('active', 'resolved', 'ignored'),
    allowNull: false,
    defaultValue: 'active',
    comment: '预警状态 (活跃, 已解决, 已忽略)',
    field: 'status'
  },
  description: {
    type: DataTypes.TEXT,
    comment: '预警描述',
    field: 'description'
  },
  location: {
    type: DataTypes.STRING,
    comment: '设备位置',
    field: 'location'
  },
  batteryLevel: {
    type: DataTypes.INTEGER,
    comment: '电池电量百分比',
    field: 'batteryLevel'
  },
  signalStrength: {
    type: DataTypes.INTEGER,
    comment: '信号强度',
    field: 'signalStrength'
  },
  temperature: {
    type: DataTypes.FLOAT,
    comment: '温度值',
    field: 'temperature'
  },
  resolvedBy: {
    type: DataTypes.STRING,
    comment: '解决人',
    field: 'resolvedBy'
  },
  resolvedAt: {
    type: DataTypes.DATE,
    comment: '解决时间',
    field: 'resolvedAt'
  },
  remarks: {
    type: DataTypes.TEXT,
    comment: '备注',
    field: 'remarks'
  },
}, {
  tableName: 'device_warnings',
  timestamps: true,
  createdAt: 'createdAt',
  updatedAt: 'updatedAt',
  paranoid: false,
  underscored: false, // 覆盖全局配置，不使用下划线命名
});

module.exports = DeviceWarning;
