package dao

import (
	"gorm.io/gorm"
	"time"
)

//OnDemandGroup 灯随车走分组
type OnDemandGroup struct {
	ID                int       `gorm:"primary_key" json:"id"`                 //编号
	PoleGroupName     string    `gorm:"type:varchar(64)" json:"poleGroupName"` //分组名称
	SN                string    `gorm:"type:varchar(60)" json:"sn"`            //SN
	LampPoleCount     int       `gorm:"type:int" json:"lampPoleCount"`         //灯杆数量
	LightingNum       int       `gorm:"type:int" json:"lightingNum"`           //亮灯数量
	BeforeLightingNum int       `gorm:"type:int" json:"beforeLightingNum"`     //提前亮灯数
	OutTimes          int       `gorm:"type:int" json:"outTimes"`              //延迟时间
	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=删除
}

func (OnDemandGroup) TableName() string {
	return "device_on_demand_group"
}

func (c *OnDemandGroup) 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 OnDemandGroup) IsExistedBySN() bool {
	var count int64
	_ = Db.Debug().Model(&c).Where(" sn = ? and is_deleted = ?",
		c.SN, c.IsDeleted).Count(&count).Error
	return count > 0
}

func (c OnDemandGroup) 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 *OnDemandGroup) Create() error {
	return Db.Debug().Model(&c).Save(&c).Error
}

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

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

func (c OnDemandGroup) GetDevices(offset, limit int) ([]OnDemandGroup, error) {
	var devices []OnDemandGroup
	err := Db.Debug().Model(&c).Where("(pole_group_name like ? or sn like ?) and is_deleted = 0", "%"+c.PoleGroupName+"%", "%"+c.PoleGroupName+"%").Offset(offset).Limit(limit).Find(&devices).Error
	return devices, err
}

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