package model

import (
	"fmt"
	"sparrow/pkg/models"

	"github.com/jinzhu/gorm"
)

// DeviceCommandModel ``
type DeviceCommandModel struct {
	db *gorm.DB
}

// Init 初始化
func (a *DeviceCommandModel) Init(_db *gorm.DB) *DeviceCommandModel {
	a.db = _db
	return a
}

// Create 添加
func (a *DeviceCommandModel) Create(item *models.DeviceCommand) error {
	cache := getCache()
	key := fmt.Sprintf("DeviceCommand:%s", item.RecordID)
	err := a.db.Save(item).Error
	if err == nil {
		cache.Set(key, item)
	}
	return err
}

// Delete 删除
func (a *DeviceCommandModel) Delete(item *models.DeviceCommand) error {
	cache := getCache()
	key := fmt.Sprintf("DeviceCommand:%s", item.RecordID)
	if _, ok := cache.Get(key); ok {
		cache.Delete(key)
	}
	// 删除关联的 data
	a.db.Where("command_id = ?", item.RecordID).Delete(&models.DeviceCommandData{})
	return a.db.Delete(item).Error
}

// Update 更新
func (a *DeviceCommandModel) Update(item *models.DeviceCommand) (data models.DeviceCommand, err error) {
	// 先删除旧的 data
	a.db.Where("command_id = ?", item.RecordID).Delete(&models.DeviceCommandData{})
	// 重新保存
	err = a.db.Save(item).Error
	if err == nil {
		cache := getCache()
		key := fmt.Sprintf("DeviceCommand:%s", item.RecordID)
		if _, ok := cache.Get(key); ok {
			cache.Delete(key)
		}
		cache.Set(key, item)
	}
	return
}

// GetListByDeviceTypeId 根据设备类型id获取指令列表
func (a *DeviceCommandModel) GetListByDeviceTypeId(deviceTypeId string, pi, ps int, name string) (datas []models.DeviceCommand, total int, err error) {
	tx := a.db.Where("device_type_id = ?", deviceTypeId)
	if name != "" {
		tx = tx.Where("name like ?", "%"+name+"%")
	}
	err = tx.Preload("Data").Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
	tx.Model(&models.DeviceCommand{}).Where("device_type_id = ?", deviceTypeId).Count(&total)
	return
}

// QueryOne 获取单个内容
func (a *DeviceCommandModel) QueryOne(recordID string) (data models.DeviceCommand, err error) {
	cache := getCache()
	key := fmt.Sprintf("DeviceCommand:%s", recordID)
	if v, ok := cache.Get(key); ok {
		_d := v.(*models.DeviceCommand)
		data = *_d
	} else {
		err = a.db.Preload("Data").Where("record_id = ?", recordID).First(&data).Error
		if err == nil {
			cache.Set(key, &data)
		}
	}
	return
}
