package dao

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

// Garbage 垃圾桶道路分组管理
type Garbage struct {
	ID              int       `gorm:"primary_key" json:"id"`                    //编号
	DeviceName      string    `gorm:"type:varchar(64)" json:"deviceName"`       //垃圾桶名称
	DeviceSN        string    `gorm:"type:varchar(60)" json:"deviceSn"`         //垃圾桶序列号
	DeviceIMei      string    `gorm:"type:varchar(64)" json:"deviceIMei"`       //传感器编码-唯一不允许重复
	KindType        int       `gorm:"type:int" json:"kindType"`                 //种类
	Material        int       `gorm:"type:int" json:"material"`                 //材质
	BrandId         int       `gorm:"type:int" json:"brandId"`                  //品牌
	ModelId         int       `gorm:"type:int" json:"modelId"`                  //型号
	GarbageOneType  int       `gorm:"type:int" json:"garbageOneType"`           //桶1类型
	GarbageTwoType  int       `gorm:"type:int" json:"garbageTwoType"`           //桶2类型
	GarbageHeight   int       `gorm:"type:int" json:"garbageHeight"`            //内桶高度
	TotalHeight     int       `gorm:"type:int" json:"totalHeight"`              //传感器距离内桶高度
	InstallTime     time.Time `gorm:"type:date" json:"installTime"`             //安装时间
	WayID           int       `gorm:"type:int" json:"wayId"`                    //所属道路号
	CameraID        int       `gorm:"type:int" json:"cameraId"`                 //摄像机id
	CameraSN        string    `gorm:"type:varchar(60)" json:"cameraSn"`         //摄像机sn
	PoleLng         float64   `gorm:"type:double(17, 14)" json:"poleLng"`       //经度
	PoleLat         float64   `gorm:"type:double(17, 14)" json:"poleLat"`       //纬度
	ProvinceName    string    `gorm:"type:varchar(60)" json:"provinceName"`     //省份
	CityName        string    `gorm:"type:varchar(60)" json:"cityName"`         //市
	DistrictName    string    `gorm:"type:varchar(60)" json:"districtName"`     //区
	InstallLocation string    `gorm:"type:varchar(100)" json:"installLocation"` //安装位置
	PhotoUrl        string    `gorm:"type:varchar(255)" json:"photoUrl"`        //供电箱照片地址
	Remark          string    `gorm:"type:varchar(1000)" json:"remark"`         //备注
	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=删除
	Threshold       int       `gorm:"type:int" json:"threshold"`                //阈值设定：告警百分比%
}

func (Garbage) TableName() string {
	return "device_garbage"
}

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

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

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

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

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

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

func (c Garbage) GetAll() []*Garbage {
	var devices []*Garbage
	Db.Debug().Model(&c).Where("is_deleted = 0 ").Scan(&devices)
	return devices
}
