package models

//zigbee集中器，数据来自web创建
type DeviceConcentrator 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"`         //型号
	Netid   int    `gorm:"type:int"`         //网络号，zigbee灯控专用，其他类型灯控置0
	Channel int    `gorm:"type:int"`         //通道号，zigbee灯控专用，其他类型灯控置0
	Tenant  string `gorm:"type:varchar(8)"`  //租户ID
	State   int    `gorm:"type:int"`         //1启用，0禁用
	TID     int    `gorm:"type:int"`         //物模型ID
	LcModel
}

func (DeviceConcentrator) TableName() string {
	return "t_device_concentrator"
}

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

func (o DeviceConcentrator) 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 DeviceConcentrator) SaveFromWeb() error {
	return nil
	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, "netid": o.Netid,
			"channel": o.Channel, "tenant": o.Tenant, "state": o.State}).Error
	} else {
		//插入
		return G_db.Create(&o).Error
	}
}

func UpdateTID(code string, tid int) error {
	return nil
	/*	if err := G_db.Model(&DeviceLampController{}).Updates(map[string]interface{}{"t_id": tid}).Where("concentrator = ? and t_id = 0", code).Error; err != nil {
			return err
		}
		if err := G_db.Model(&DeviceConcentrator{}).Updates(map[string]interface{}{"t_id": tid}).Where("id = ? and t_id = 0", code).Error; err != nil {
			return err
		}*/
	sql := `UPDATE t_device_lampcontroller SET t_id = ? WHERE concentrator = ? AND t_id = 0;
            UPDATE t_device_concentrator SET t_id = ? WHERE  id = ? AND t_id = 0;`
	return G_db.Raw(sql, tid, code, tid, code).Error
}
func GetConcentratorbyID(code string) (*DeviceConcentrator, error) {
	var obj DeviceConcentrator
	err := G_db.Model(&DeviceConcentrator{}).Where("id = ? ", code).Find(&obj).Error
	return &obj, err
}
