package models

// 抓拍单元
type ItsDevice 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        string `gorm:"type:varchar(24)"`             //设备品牌
	Model        string `gorm:"type:varchar(32)"`             //设备型号
	DevType      int    `gorm:"type:int"`                     //5，抓拍单元
	User         string `gorm:"type:varchar(32)"`             //用户名
	Password     string `gorm:"type:varchar(64)"`             //密码
	IP           string `gorm:"type:varchar(256)"`            //IP地址
	Port         uint16 `gorm:"type:int"`                     //端口
	HttpAddr     string `gorm:"type:varchar(128)"`            //web服务地址
	SuggestSpeed int    `gorm:"type:int"`                     //建议速度，提示限速
	Duration     int    `gorm:"type:int"`                     //led屏车速归零时间间隔，单位秒
	EnvID        string `gorm:"type:varchar(128)"`            //关联环境传感器，用于联动显示气象环境信息
	TollgateID   string `gorm:"type:varchar(32)"`             //卡口编号:产生该信息的卡口代码
	Tenant       string `gorm:"type:varchar(8)"`              //租户ID
	State        int    `gorm:"type:int"`                     //1启用，0禁用
	LcModel
}

func (ItsDevice) TableName() string {
	//从视图里取
	return "t_device_its"
}

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

func (o ItsDevice) 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 ItsDevice) 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, "tenant": o.Tenant, "state": o.State}).Error
	} else { //插入
		return G_db.Create(&o).Error
	}
}

func (o ItsDevice) SaveFromGateway() error {
	return nil
	has, err := o.IsExistedByCode()
	if err != nil {
		return err
	}
	if has { //更新
		return G_db.Model(&o).Updates(map[string]interface{}{"g_id": o.GID,
			"brand": o.Brand, "model": o.Model, "dev_type": o.DevType, "user": o.User, "password": o.Password,
			"ip": o.IP, "port": o.Port, "http_addr": o.HttpAddr, "suggest_speed": o.SuggestSpeed, "duration": o.Duration, "env_id": o.EnvID, "tollgate_id": o.TollgateID}).Error
	} else { //插入
		return G_db.Create(&o).Error
	}
}
