package dao

import (
	"gorm.io/gorm"
	"iot_manager_service/util/common"
	"time"
)

//Gateway 网关设备
type Gateway struct {
	ID                 int         `gorm:"primary_key" json:"id"`                           //编号
	GatewayName        string      `gorm:"type:varchar(64)"  json:"gatewayName"`            //设备名称
	GatewaySn          string      `gorm:"type:varchar(60)" json:"gatewaySn"`               //设备序列号
	LampPoleId         int         `gorm:"type:int" json:"lampPoleId"`                      //所属灯杆
	LampPoleSn         string      `gorm:"type:varchar(64)" json:"lampPoleSn"`              //所属灯杆SN
	LampPoleName       string      `gorm:"type:varchar(64)" json:"lampPoleName"`            //灯杆名称
	LampPoleLocation   string      `gorm:"type:varchar(255)" json:"lampPoleLocation"`       //灯杆安装位置
	LampLat            float64     `gorm:"type:double(17,14)" json:"lampLat"`               //纬度
	LampLng            float64     `gorm:"type:double(17,14)" json:"lampLng"`               //经度
	BrandId            int         `gorm:"type:int" json:"brandId"`                         //设备品牌
	ModelId            int         `gorm:"type:int" json:"modelId"`                         //设备型号
	GatewayInstallTime common.Time `gorm:"type:date" json:"gatewayInstallTime"`             //安装时间
	RatedPower         float32     `gorm:"type:double(8,2);default:0.00" json:"ratedPower"` //功率
	IpAddress          string      `gorm:"type:varchar(50)" json:"ipAddress"`               //IP地址
	DiNum              int         `gorm:"type:int;default 0" json:"diNum"`                 //DI口数量
	DoNum              int         `gorm:"type:int;default 0" json:"doNum"`                 //DO口数量
	Num485             int         `gorm:"type:int;default 0" json:"num485"`                //485口数量
	NetworkNum         int         `gorm:"type:int;default 0" json:"networkNum"`            //网口数量
	TenantId           string      `gorm:"type:varchar(12)" json:"tenantId"`                //租户ID
	CreateTime         time.Time   `gorm:"type:datetime" json:"createTime"`                 //新增时间
	CreateUser         int64       `gorm:"type:bigint" json:"createUser"`                   //新增记录操作用户ID
	UpdateTime         time.Time   `gorm:"type:datetime" json:"updateTime"`                 //修改时间
	UpdateUser         int64       `gorm:"type:bigint" json:"updateUser"`                   //修改用户
	IsDeleted          int         `gorm:"type:int;default 0" json:"isDeleted"`             //是否删除 0=未删除,1=删除
	Status             int         `gorm:"type:int" json:"status"`                          //状态 0=正常,1=异常
	Tag                string      `gorm:"type:varchar(255)" json:"tag"`                    //标签，(备用，逗号区分)
}

func (Gateway) TableName() string {
	return "device_wisdom_gateway"
}

func (c *Gateway) Delete() error {
	return Db.Debug().Model(&c).Where("id = ?", c.ID).Updates(map[string]interface{}{"update_time": c.UpdateTime,
		"update_user": c.UpdateUser, "is_deleted": c.IsDeleted}).Error
}

func (c Gateway) IsExistedBySN() bool {
	var count int64
	_ = Db.Debug().Model(&c).Where(" gateway_sn = ? and is_deleted = ?",
		c.GatewaySn, c.IsDeleted).Count(&count).Error
	return count > 0
}

func (c Gateway) IsExistedByNameAndCode() bool {
	var devices []Gateway
	err := Db.Debug().Model(&c).Where("gateway_sn = ? and is_deleted = ?",
		c.TenantId, c.IsDeleted).Find(&devices).Error
	if gorm.ErrRecordNotFound == err {
		return false
	}
	for _, d := range devices {
		if d.ID != c.ID {
			return true
		}
	}
	return false
}

func (c *Gateway) Create() error {
	return Db.Debug().Model(&c).Save(&c).Error
}

func (c *Gateway) Update() error {
	return Db.Debug().Model(&c).Where(" id = ? ", c.ID).Updates(&c).Error
}

func (c *Gateway) GetDevice() error {
	err := Db.Debug().Model(&c).Where(" id = ? ", c.ID).First(&c).Error
	return err
}

func (c Gateway) GetDevices(offset, limit int) ([]Gateway, int64, error) {
	var devices []Gateway
	var count int64
	db := Db.Debug().Model(&c)
	if c.GatewaySn != "" {
		db = db.Where("gateway_name like ? or gateway_sn like ?", "%"+c.GatewaySn+"%", "%"+c.GatewaySn+"%")
	}

	tx := db.Where("is_deleted = 0")
	tx.Count(&count)
	err := tx.Offset(offset).Limit(limit).Order("gateway_name asc").Find(&devices).Error
	return devices, count, err
}

func (c Gateway) GetAllDevices() ([]*Gateway, error) {
	var devices []*Gateway
	err := Db.Debug().Model(&c).Where(" tenant_id = ? and is_deleted = ? ", c.TenantId, c.IsDeleted).Scan(&devices).Error
	return devices, err
}

func (c Gateway) GetDevicesByLampPole() []Gateway {
	var devices []Gateway
	Db.Debug().Model(&c).Where("lamp_pole_id = ? and is_deleted = 0",
		c.LampPoleId).Find(&devices)
	return devices
}
