package model

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

	"github.com/jinzhu/gorm"
)

// Ota model
type Ota struct {
	db *gorm.DB
}

// Init init Ota
func (a *Ota) Init(db *gorm.DB) *Ota {
	a.db = db
	return a
}

// Query query all roles
func (a *Ota) Query(pi, ps int, name, vendorId, version string) (datas []models.Ota, total int, err error) {
	tx := a.db.Where("1=1")
	if version != "" {
		tx = tx.Where("version like ?", "%"+version+"%")
	}
	if name != "" {
		tx = tx.Where("name like ?", "%"+name+"%")
	}
	if vendorId != "" {
		tx = tx.Where("vendor_id = ?", vendorId)
	}
	err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
	err = tx.Model(&models.Ota{}).Count(&total).Error
	return
}

// Get 获取数据内容
func (a *Ota) Get(vendorId string, recordId string) (data models.Ota, err error) {
	cache := getCache()
	key := fmt.Sprintf("OtaId:%s", recordId)
	if v, ok := cache.Get(key); ok {
		_d := v.(*models.Ota)
		data = *_d
	} else {
		err = a.db.Where("vendor_id = ? and record_id = ?", vendorId, recordId).First(&data).Error
		if err == nil {
			cache.Set(key, &data)
		}
	}
	return
}

// Create 创建
func (a *Ota) Create(Ota *models.Ota) error {
	return a.db.Save(Ota).Error

}

// Delete delete
func (a *Ota) Delete(Ota *models.Ota) error {
	cache := getCache()
	key := fmt.Sprintf("Ota:%d", Ota.ID)
	if _, ok := cache.Get(key); ok {
		cache.Delete(key)
	}
	return a.db.Delete(Ota).Error
}

// Update update
func (a *Ota) Update(Ota *models.Ota) (data models.Ota, err error) {
	cache := getCache()
	key := fmt.Sprintf("Ota:%d", Ota.ID)
	if _, ok := cache.Get(key); ok {
		cache.Delete(key)
	}
	err = a.db.Model(&data).Update(Ota).Error
	return
}
