package services

import (
	"github.com/gogf/gf/util/guid"
	"sparrow/pkg/models"
	"sparrow/services/knowoapi/model"
)

// DeviceCommandService 业务接口
type DeviceCommandService interface {
	Create(*models.DeviceCommand) error
	Delete(*models.DeviceCommand) error
	Update(*models.DeviceCommand) (models.DeviceCommand, error)
	GetListByDeviceTypeId(deviceTypeId string, pi, ps int, name string) ([]models.DeviceCommand, int, error)
	QueryOne(recordID string) (models.DeviceCommand, error)
}

type deviceCommandService struct {
	model *model.All
}

// NewDeviceCommandService new device command manager
func NewDeviceCommandService(m *model.All) DeviceCommandService {
	return &deviceCommandService{
		model: m,
	}
}

func (a *deviceCommandService) Create(item *models.DeviceCommand) error {
	item.RecordID = guid.S()
	// 为子数据生成 record_id
	for i := range item.Data {
		item.Data[i].RecordID = guid.S()
		item.Data[i].CommandId = item.RecordID
	}
	return a.model.DeviceCommand.Create(item)
}

func (a *deviceCommandService) Delete(item *models.DeviceCommand) error {
	return a.model.DeviceCommand.Delete(item)
}

func (a *deviceCommandService) Update(item *models.DeviceCommand) (models.DeviceCommand, error) {
	// 为子数据生成 record_id
	for i := range item.Data {
		if item.Data[i].RecordID == "" {
			item.Data[i].RecordID = guid.S()
		}
		item.Data[i].CommandId = item.RecordID
	}
	return a.model.DeviceCommand.Update(item)
}

func (a *deviceCommandService) GetListByDeviceTypeId(deviceTypeId string, pi, ps int, name string) ([]models.DeviceCommand, int, error) {
	return a.model.DeviceCommand.GetListByDeviceTypeId(deviceTypeId, pi, ps, name)
}

func (a *deviceCommandService) QueryOne(recordID string) (models.DeviceCommand, error) {
	return a.model.DeviceCommand.QueryOne(recordID)
}
