package model

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

	"github.com/jinzhu/gorm"
)

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

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

//Create 添加
func (a *Product) Create(product *models.Product) error {
	cache := getCache()
	key := fmt.Sprintf("Product:%s", product.ProductKey)

	err := a.db.Save(product).Error
	if err == nil {
		cache.Set(key, product)
	}
	return err
}

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

// Update 更新
func (a *Product) Update(product *models.Product) (pro models.Product, err error) {

	err = a.db.Model(&pro).Save(product).Error
	if err == nil {
		cache := getCache()
		key := fmt.Sprintf("Product:%s", product.ProductKey)
		if _, ok := cache.Get(key); ok {
			cache.Delete(key)
		}
		cache.Set(key, product)
	}
	return
}

// GetVendorProducts 获取厂商的产品列表
func (a *Product) GetVendorProducts(vendorid string, pi, ps int, name string) (datas []models.Product, total int, err error) {
	tx := a.db.Where("vendor_id = ? and 1=1", vendorid)
	if name != "" {
		tx = tx.Where("product_name like ?", "%"+name+"%")
	}
	err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
	tx.Model(&models.Product{}).Count(&total)
	return
}

// QueryOne 获取单个产品内容
func (a *Product) QueryOne(productkey string, vendorid string) (data models.Product, err error) {
	cache := getCache()
	key := fmt.Sprintf("Product:%s", productkey)
	if v, ok := cache.Get(key); ok {
		_d := v.(*models.Product)
		data = *_d
	} else {
		err = a.db.Where("vendor_id = ? and product_key = ?", vendorid, productkey).First(&data).Error
		cache.Set(key, &data)
	}

	return
}
