package dao

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

// GarbageWayGroup 垃圾桶道路分组管理
type GarbageWayGroup struct {
	ID         int       `gorm:"primary_key" json:"id"`               //编号
	GroupName  string    `gorm:"type:varchar(64)" json:"groupName"`   //分组名称
	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=删除
	Remark     string    `gorm:"type:varchar(255)" json:"remark"`     //备注
}

func (GarbageWayGroup) TableName() string {
	return "device_garbage_way_group"
}

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

func (c GarbageWayGroup) IsExistedByNameAndCode() bool {
	var devices []Garbage
	err := Db.Debug().Model(&c).Where(" group_name = ? and is_deleted = ?",
		c.GroupName, 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 *GarbageWayGroup) Create() error {
	return Db.Debug().Model(&c).Save(&c).Error
}

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

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

func (c GarbageWayGroup) GetDevices(offset, limit int) ([]GarbageWayGroup, int64, error) {
	var devices []GarbageWayGroup
	var count int64
	db := Db.Debug().Model(&c).Where(" group_name like ? and is_deleted = 0", "%"+c.GroupName+"%")
	db.Count(&count)
	err := db.Offset(offset).Limit(limit).Find(&devices).Error
	return devices, count, err
}

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