package model

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

	"github.com/jinzhu/gorm"
)

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

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

// Create 创建
func (a *Protocal) Create(ptl *models.Protocal) error {
	cache := getCache()
	key := fmt.Sprintf("Protocal:%d", ptl.ID)
	err := a.db.Save(ptl).Error
	if err != nil {
		return err
	}
	cache.Set(key, ptl)
	return nil
}

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

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

// GetProductProtocals 获取产品的数据点列表
func (a *Protocal) GetProductProtocals(productid uint, pi, ps int, name, label string) (datas []models.Protocal, total int, err error) {
	tx := a.db.Where("product_id = ? and 1 = 1", productid)
	if name != "" {
		tx = tx.Where("name like ? ", "%"+name+"%")
	}
	if label != "" {
		tx = tx.Where("label = ?", label)
	}

	err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
	tx.Model(&models.Protocal{}).Count(&total)
	return
}

// GetProtocalInfo 获取数据点内容
func (a *Protocal) GetProtocalInfo(pid uint) (data models.Protocal, err error) {
	cache := getCache()
	key := fmt.Sprintf("Protocal:%d", pid)
	if v, ok := cache.Get(key); ok {
		data = *(v.(*models.Protocal))
	} else {
		err = a.db.Where("id = ?", pid).First(&data).Error
		if err == nil {
			cache.Set(key, &data)
		}
	}
	return
}

// TODO 查询某个产品所有上报类型的数据点
