package model

import (
	"github.com/jinzhu/gorm"
	"sparrow/pkg/models"
)

// SubDevice sub_devices data
type SubDevice struct {
	db *gorm.DB
}

// Init sub_device
func (a *SubDevice) Init(db *gorm.DB) *SubDevice {
	a.db = db
	return a
}

// GetSubDeviceCount
func (a *SubDevice) GetSubDeviceCount(deviceCode string) (count int, err error) {
	subDevice := &models.SubDevice{
		DeviceCode: deviceCode,
	}
	err = a.db.Model(subDevice).Where(subDevice).Count(&count).Error
	return
}

// GetSubDevices 获取子设备列表
func (a *SubDevice) GetSubDevices(deviceCode string, pi, ps int) (data []*models.SubDevice, total int, err error) {
	tx := a.db
	if deviceCode != "" {
		tx = tx.Where("device_code = ?", deviceCode)
	}
	err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&data).Error
	tx.Model(&models.SubDevice{}).Count(&total)
	return
}
