const { Model, DataTypes } = require('sequelize');
const { sequelize } = require('../config/database-simple');

class IotJbqClient extends Model {
  // 获取设备状态文本
  getStatusText() {
    const statusMap = {
      0: '离线',
      1: '在线', 
      2: '报警',
      3: '维护'
    };
    return statusMap[this.state] || '未知';
  }

  // 获取设备状态颜色
  getStatusColor() {
    const colorMap = {
      0: 'red',      // 离线
      1: 'green',    // 在线
      2: 'orange',   // 报警
      3: 'blue'      // 维护
    };
    return colorMap[this.state] || 'default';
  }

  // 获取电量百分比
  getBatteryPercent() {
    const voltage = parseFloat(this.voltage) || 0;
    // 假设电压范围是0-100，转换为百分比
    return Math.min(100, Math.max(0, voltage));
  }

  // 获取温度值
  getTemperatureValue() {
    return parseFloat(this.temperature) || 0;
  }

  // 获取GPS状态文本
  getGpsStatusText() {
    const gpsMap = {
      'A': '有效',
      'V': '无效',
      'N': '无信号'
    };
    return gpsMap[this.gps_state] || '未知';
  }

  // 获取最后更新时间
  getLastUpdateTime() {
    if (!this.uptime) return '-';
    const date = new Date(this.uptime * 1000);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  }

  // 获取绑带状态文本
  getBandgeStatusText() {
    const statusMap = {
      0: '未绑定',
      1: '已绑定',
      2: '松动',
      3: '脱落'
    };
    return statusMap[this.bandge_status] || '未知';
  }

  // 获取绑带状态颜色
  getBandgeStatusColor() {
    const colorMap = {
      0: 'default',  // 未绑定
      1: 'green',    // 已绑定
      2: 'orange',   // 松动
      3: 'red'       // 脱落
    };
    return colorMap[this.bandge_status] || 'default';
  }

  // 检查是否有定位信息
  hasLocation() {
    return this.lat && this.lon && this.lat !== '0' && this.lon !== '0';
  }

  // 获取耳标编号（使用aaid字段）
  getEartagNumber() {
    return this.aaid ? this.aaid.toString() : '-';
  }

  // 获取被采集主机（使用sid字段）
  getHostId() {
    return this.sid || '-';
  }

  // 获取总运动量
  getTotalMovement() {
    return this.walk || 0;
  }

  // 获取当日运动量
  getDailyMovement() {
    return this.y_steps || 0;
  }

  // 获取佩戴状态文本
  getWearStatusText() {
    return this.is_wear ? '已佩戴' : '未佩戴';
  }

  // 获取佩戴状态颜色
  getWearStatusColor() {
    return this.is_wear ? 'green' : 'default';
  }

  // 获取GPS信号等级
  getGpsSignalLevel() {
    const gpsState = this.gps_state;
    if (gpsState === 'A') {
      return '强';
    } else if (gpsState === 'V') {
      return '弱';
    } else {
      return '无';
    }
  }
}

IotJbqClient.init({
    id: { 
      type: DataTypes.BIGINT, 
      primaryKey: true, 
      autoIncrement: true, 
      comment: '耳标设备ID' 
    },
    org_id: { 
      type: DataTypes.INTEGER.UNSIGNED, 
      allowNull: false, 
      defaultValue: 0, 
      comment: '组织ID' 
    },
    cid: { 
      type: DataTypes.BIGINT, 
      allowNull: false, 
      comment: '设备CID' 
    },
    aaid: { 
      type: DataTypes.BIGINT, 
      allowNull: false, 
      comment: '耳标编号' 
    },
    uid: { 
      type: DataTypes.BIGINT, 
      allowNull: false, 
      defaultValue: 0, 
      comment: '用户ID' 
    },
    time: { 
      type: DataTypes.INTEGER, 
      allowNull: false, 
      comment: '时间戳' 
    },
    uptime: { 
      type: DataTypes.INTEGER, 
      allowNull: false, 
      comment: '更新时间戳' 
    },
    sid: { 
      type: DataTypes.STRING(16), 
      allowNull: false, 
      comment: '被采集主机ID' 
    },
    walk: { 
      type: DataTypes.BIGINT, 
      allowNull: false, 
      defaultValue: 0, 
      comment: '总运动量' 
    },
    y_steps: { 
      type: DataTypes.BIGINT, 
      allowNull: false, 
      defaultValue: 0, 
      comment: '当日运动量' 
    },
    r_walk: { 
      type: DataTypes.BIGINT, 
      allowNull: false, 
      defaultValue: 0, 
      comment: '剩余运动量' 
    },
    lat: { 
      type: DataTypes.STRING(50), 
      allowNull: false, 
      defaultValue: '0', 
      comment: '纬度' 
    },
    lon: { 
      type: DataTypes.STRING(50), 
      allowNull: false, 
      defaultValue: '0', 
      comment: '经度' 
    },
    gps_state: { 
      type: DataTypes.STRING(5), 
      allowNull: false, 
      defaultValue: 'V', 
      comment: 'GPS状态' 
    },
    voltage: { 
      type: DataTypes.STRING(10), 
      allowNull: true, 
      comment: '电压/电量' 
    },
    temperature: { 
      type: DataTypes.STRING(10), 
      allowNull: true, 
      comment: '温度' 
    },
    temperature_two: { 
      type: DataTypes.STRING(10), 
      allowNull: false, 
      defaultValue: '0', 
      comment: '温度2' 
    },
    state: { 
      type: DataTypes.INTEGER(1), 
      allowNull: false, 
      defaultValue: 1, 
      comment: '设备状态：0-离线，1-在线，2-报警，3-维护' 
    },
    type: { 
      type: DataTypes.INTEGER(5), 
      allowNull: true, 
      defaultValue: 1, 
      comment: '设备类型' 
    },
    sort: { 
      type: DataTypes.INTEGER(5), 
      allowNull: true, 
      defaultValue: 4, 
      comment: '排序' 
    },
    ver: { 
      type: DataTypes.STRING(10), 
      allowNull: false, 
      defaultValue: '0', 
      comment: '固件版本' 
    },
    weight: { 
      type: DataTypes.INTEGER(5), 
      allowNull: false, 
      defaultValue: 0, 
      comment: '重量' 
    },
    start_time: { 
      type: DataTypes.INTEGER, 
      allowNull: false, 
      defaultValue: 0, 
      comment: '开始时间' 
    },
    run_days: { 
      type: DataTypes.INTEGER, 
      allowNull: false, 
      defaultValue: 240, 
      comment: '运行天数' 
    },
    zenowalk: { 
      type: DataTypes.INTEGER, 
      allowNull: false, 
      defaultValue: 0, 
      comment: '零步数' 
    },
    zenotime: { 
      type: DataTypes.INTEGER, 
      allowNull: false, 
      defaultValue: 0, 
      comment: '零时间' 
    },
    is_read: { 
      type: DataTypes.INTEGER(5), 
      allowNull: true, 
      defaultValue: 0, 
      comment: '是否已读' 
    },
    read_end_time: { 
      type: DataTypes.INTEGER, 
      allowNull: true, 
      comment: '读取结束时间' 
    },
    bank_userid: { 
      type: DataTypes.INTEGER(5), 
      allowNull: true, 
      comment: '银行用户ID' 
    },
    bank_item_id: { 
      type: DataTypes.INTEGER, 
      allowNull: true, 
      defaultValue: 0, 
      comment: '银行项目ID' 
    },
    bank_house: { 
      type: DataTypes.INTEGER, 
      allowNull: true, 
      defaultValue: 0, 
      comment: '银行房屋' 
    },
    bank_lanwei: { 
      type: DataTypes.INTEGER, 
      allowNull: true, 
      defaultValue: 0, 
      comment: '银行栏位' 
    },
    bank_place: { 
      type: DataTypes.TINYINT(2), 
      allowNull: true, 
      defaultValue: 0, 
      comment: '银行地点' 
    },
    is_home: { 
      type: DataTypes.INTEGER(5), 
      allowNull: false, 
      defaultValue: 1, 
      comment: '是否在家' 
    },
    distribute_time: { 
      type: DataTypes.INTEGER.UNSIGNED, 
      allowNull: true, 
      defaultValue: 0, 
      comment: '分发时间' 
    },
    bandge_status: { 
      type: DataTypes.INTEGER(5), 
      allowNull: false, 
      defaultValue: 0, 
      comment: '绑带状态：0-未绑定，1-已绑定，2-松动，3-脱落' 
    },
    is_wear: { 
      type: DataTypes.TINYINT(1).UNSIGNED, 
      allowNull: false, 
      defaultValue: 0, 
      comment: '是否佩戴' 
    },
    is_temperature: { 
      type: DataTypes.TINYINT(1).UNSIGNED, 
      allowNull: false, 
      defaultValue: 0, 
      comment: '是否有温度' 
    },
    source_id: { 
      type: DataTypes.BIGINT, 
      allowNull: true, 
      comment: '来源ID' 
    },
    expire_time: { 
      type: DataTypes.INTEGER.UNSIGNED, 
      allowNull: false, 
      defaultValue: 0, 
      comment: '过期时间' 
    }
  }, {
    sequelize,
    modelName: 'IotJbqClient',
    tableName: 'iot_jbq_client',
    timestamps: false,
    indexes: [
      { fields: ['org_id'] },
      { fields: ['aaid'] },
      { fields: ['uid'] },
      { fields: ['uptime'] },
      { fields: ['sid'] },
      { fields: ['type'] },
      { fields: ['is_wear'] },
      { fields: ['source_id'] }
    ]
  });

// 定义关联关系
IotJbqClient.associate = (models) => {
  // 与牛只档案的关联关系（通过cid和earNumber匹配）
  IotJbqClient.hasOne(models.IotCattle, {
    foreignKey: 'earNumber',
    sourceKey: 'cid',
    as: 'cattle'
  });
};

module.exports = IotJbqClient;