package models

//传感器设备，数据来自web
type DeviceSensor struct {
	ID     string  `gorm:"type:varchar(32);primary_key"` //设备ID，DID
	Name   string  `gorm:"type:varchar(64)"`
	GID    string  `gorm:"type:varchar(32)"` //网关ID
	Brand  int     `gorm:"type:int"`         //品牌
	Model  int     `gorm:"type:int"`         //型号
	Height float32 `gorm:"type:float(10,2)"` //安装高度,单位米
	Tenant string  `gorm:"type:varchar(8)"`  //租户ID
	State  int     `gorm:"type:int"`         //1启用，0禁用
	TID    int     `gorm:"type:int"`         //物模型ID
	LcModel
}

func (DeviceSensor) TableName() string {
	return "t_device_sensor"
}

func (o DeviceSensor) Delete() error {
	return G_db.Model(&o).Updates(map[string]interface{}{"state": 0}).Error
}

func (o DeviceSensor) IsExistedByCode() (bool, error) {
	var count int = 0
	err := G_db.Model(&o).Where(" id = ? ", o.ID).Count(&count).Error
	return count > 0, err
}

func (o DeviceSensor) SaveFromWeb() error {
	has, err := o.IsExistedByCode()
	if err != nil {
		return err
	}
	if has { //更新
		return G_db.Model(&o).Updates(map[string]interface{}{
			"name": o.Name, "g_id": o.GID, "brand": o.Brand, "model": o.Model, "height": o.Height,
			"tenant": o.Tenant, "state": o.State}).Error
	} else { //插入
		return G_db.Create(&o).Error
	}
}

func UpdateDeviceSensorTID(code string, tid int) error {
	return nil
	sql := `UPDATE t_device_sensor SET t_id = ? WHERE id = ?;`
	return G_db.Raw(sql, tid, code).Error
}
