package models

//雷达
type RadarDevice struct {
	ID           string `gorm:"type:varchar(32);primary_key"` //设备ID，DID
	Name         string `gorm:"type:varchar(64)"`             //设备名称
	GID          string `gorm:"type:varchar(32);key"`         //网关ID
	Brand        int    `gorm:"type:int"`                     //设备品牌
	Model        int    `gorm:"type:int"`                     //设备型号
	DevType      int    `gorm:"type:int"`                     //6，雷达
	IP           string `gorm:"type:varchar(256);key"`        //IP地址
	Port         uint16 `gorm:"type:int"`                     //端口
	SuggestSpeed int    `gorm:"type:int"`                     //建议速度，提示限速
	Tenant       string `gorm:"type:varchar(8)"`              //租户ID
	State        int    `gorm:"type:int"`                     //1启用，0禁用
	LcModel
}

func (RadarDevice) TableName() string {
	return "t_device_radar"
}

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

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

func (r RadarDevice) SaveFromWeb() error {
	has, err := r.IsExistedByCode()
	if err != nil {
		return err
	}
	if has { //更新
		return G_db.Model(&r).Updates(map[string]interface{}{"name": r.Name, "tenant": r.Tenant, "state": r.State}).Error
	} else { //插入
		return G_db.Create(&r).Error
	}
}

func (r RadarDevice) SaveFromGateway() error {
	has, err := r.IsExistedByCode()
	if err != nil {
		return err
	}
	if has { //更新
		return G_db.Model(&r).Updates(map[string]interface{}{"g_id": r.GID,
			"brand": r.Brand, "model": r.Model, "dev_type": r.DevType,
			"ip": r.IP, "port": r.Port, "suggest_speed": r.SuggestSpeed}).Error
	} else { //插入
		return G_db.Create(&r).Error
	}
}
