package models

//网关下挂载的设备串口设备，如485接口的设备，数据来自设备上报
type GatewayDevice struct {
	ID           string `gorm:"type:varchar(32);primary_key"` //设备ID，DID
	Name         string `gorm:"type:varchar(64)"`
	GID          string `gorm:"type:varchar(32)"` //网关ID
	ComID        int    `gorm:"type:int"`         //串口编号
	RtuID        int    `gorm:"type:int"`         //RTUID,即485从机地址
	TID          int    `gorm:"type:int"`         //物模型ID
	SendCloud    int    `gorm:"type:int"`         //发送频率
	WaitTime     int    `gorm:"type:int"`         //发送后等待多久
	ProtocolType int    `gorm:"type:int"`         //0:modbus-rtu;1:长和单灯集控zigbee
	DevType      int    `gorm:"type:int"`         //设备类型，1-灯控类设备 2-环境监测类设备
	Tenant       string `gorm:"type:varchar(8)"`  //租户ID
	State        int    `gorm:"type:int"`         //1启用，0禁用
	LcModel
}

func (GatewayDevice) TableName() string {
	return "t_gateway_device"
}

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

func (o GatewayDevice) 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 GatewayDevice) 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 GatewayDevice) SaveFromGateway() 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, "com_id": o.ComID,
			"rtu_id": o.RtuID, "t_id": o.TID, "send_cloud": o.SendCloud,
			"wait_time": o.WaitTime, "protocol_type": o.ProtocolType, "dev_type": o.DevType}).Error
	} else {
		//插入
		return G_db.Create(&o).Error
	}
}
