package models

type Gateway struct {
	ID                string `gorm:"column:gateway_sn;type:varchar(32)"`
	Name              string `gorm:"column:gateway_name;type:varchar(32)"`
	Brand             int    `gorm:"column:brand_id;type:int"` //品牌
	Model             int    `gorm:"column:model_id;type:int"` //型号
	Sn                string `gorm:"-"`
	Upgrade           bool   `gorm:"-"`
	MqttEdgeServer    string `gorm:"-"`
	MqttEdgeUser      string `gorm:"-"`
	MqttEdgePassword  string `gorm:"-"`
	MqttCloudServer   string `gorm:"-"`
	MqttCloudUser     string `gorm:"-"`
	MqttCloudPassword string `gorm:"-"`
	Tenant            string `gorm:"column:tenant_id;type:varchar(8)"` //租户ID
	State             int    `-`                                       //1启用，0禁用
	//LcModel
}

func (Gateway) TableName() string {
	//return "t_gateway"
	return "device_garbage"
}

func (o Gateway) Delete() error {
	return G_db.Model(&o).Where("id = ?", o.ID).Updates(map[string]interface{}{"state": 0}).Error
}

func (o *Gateway) Get() error {
	return G_db.Model(&o).Where("id = ?", o.ID).Find(&o).Error
}

func (o Gateway) 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 Gateway) 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,
			"brand": o.Brand, "model": o.Model, "state": o.State}).Error
	} else {
		//插入
		return G_db.Create(&o).Error
	}
}

func (o Gateway) 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, "tenant": o.Tenant, "sn": o.Sn,
			"upgrade": o.Upgrade, "mqtt_edge_server": o.MqttEdgeServer, "mqtt_edge_user": o.MqttEdgeUser,
			"mqtt_edge_password": o.MqttEdgePassword, "mqtt_cloud_server": o.MqttCloudServer,
			"mqtt_cloud_user": o.MqttCloudUser, "mqtt_cloud_password": o.MqttCloudPassword}).Error
	} else {
		//插入
		return G_db.Create(&o).Error
	}
}
