package model

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

	"github.com/jinzhu/gorm"
)

// Application 应用
type Application struct {
	db *gorm.DB
}

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

// Create 创建
func (a *Application) Create(app *models.Application) error {
	cache := getCache()
	key := fmt.Sprintf("Application:%s", app.AppKey)
	cache.Set(key, app)
	return a.db.Save(app).Error
}

//Delete 删除
func (a *Application) Delete(app *models.Application) error {
	cache := getCache()
	key := fmt.Sprintf("Application:%s", app.AppKey)
	if _, ok := cache.Get(key); ok {
		cache.Delete(key)
	}
	return a.db.Delete(app).Error
}

// GetAppCount 查询一个厂商的Application数量
func (a *Application) GetAppCount(vendorid string) (int, error) {
	var count int
	err := a.db.Model(&models.Application{}).Where("vendor_id = ?", vendorid).Count(&count).Error
	if err != nil {
		return 0, err
	}
	return count, nil
}

// GetVendorApps 获取厂商的app列表
func (a *Application) GetVendorApps(vendorid string, pi, ps int, name string) (datas []models.Application, count int, err error) {
	tx := a.db.Where("vendor_id = ? and 1=1", vendorid)
	if name != "" {
		tx = tx.Where("app_name = ?", name)
	}
	err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
	tx.Model(&models.Application{}).Count(&count)
	return
}

// GetAppInfo 查询app信息
func (a *Application) GetAppInfo(vendorid string, appkey string) (data models.Application, err error) {

	cache := getCache()
	key := fmt.Sprintf("Application:%s", appkey)
	if v, ok := cache.Get(key); ok {
		_d := v.(*models.Application)
		data = *_d
	} else {
		err = a.db.Where("vendor_id = ? and app_key = ?", vendorid, appkey).First(&data).Error
		if err == nil {
			cache.Set(key, &data)
		}
	}
	return
}

// Update 更新
func (a *Application) Update(app *models.Application) (data models.Application, err error) {
	cache := getCache()
	key := fmt.Sprintf("Application:%s", app.AppKey)
	if _, ok := cache.Get(key); ok {
		cache.Delete(key)
	}
	cache.Set(key, app)
	err = a.db.Model(&data).Save(app).Error
	return
}
