package model

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

	"github.com/jinzhu/gorm"
)

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

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

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

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

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

// GetListByDeviceTypeId 根据设备类型id获取状态列表
func (a *DeviceStatusModel) GetListByDeviceTypeId(deviceTypeId string, pi, ps int, name string) (datas []models.DeviceStatus, 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.DeviceStatus{}).Where("device_type_id = ?", deviceTypeId).Count(&total)
	return
}

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