package dao

import "server/global"

type Device struct {
	global.GVA_MODEL
	Sn          string      `json:"sn" gorm:"comment:设备sn"`
	Name        string      `json:"name" gorm:"comment:名称"`
	Genre       int         `json:"genre" gorm:"index;comment:类型id"`
	DeviceGenre DeviceGenre `json:"deviceGenre" gorm:"foreignKey:Genre;"`
}

func (Device) TableName() string {
	return "device"
}

func QueryAllDevices() (devices []Device, err error) {
	err = global.GVA_DB.Model(Device{}).Find(&devices).Error
	return
}

func QueryDeviceList(sn, name string, genre, limit, offset int) (devices []Device, total int64, err error) {
	db := global.GVA_DB.Model(Device{})

	if sn != "" {
		db = db.Where("sn LIKE ?", "%"+sn+"%")
	}

	if name != "" {
		db = db.Where("name LIKE ?", "%"+name+"%")
	}

	if genre != 0 {
		db = db.Where("genre = ?", genre)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Preload("DeviceGenre").Find(&devices).Error
	return
}

func (d Device) CreateDevice() error {
	return global.GVA_DB.Create(&d).Error
}

func (d Device) UpdateDevice() error {
	return global.GVA_DB.Where("id = ?", d.ID).Updates(&d).Error
}

func DeleteDevice(id int) error {
	return global.GVA_DB.Unscoped().Where("id = ?", id).Delete(&Device{}).Error
}
