package model

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

	"github.com/jinzhu/gorm"
)

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

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

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

// Get 获取数据内容
func (a *RuleChain) Get(vendorId string, recordId string) (data models.RuleChain, err error) {
	cache := getCache()
	key := fmt.Sprintf("ChanId:%s", recordId)
	if v, ok := cache.Get(key); ok {
		_d := v.(*models.RuleChain)
		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 *RuleChain) Create(ruleChain *models.RuleChain) error {
	return a.db.Save(ruleChain).Error

}

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

// Update update
func (a *RuleChain) Update(ruleChain *models.RuleChain) error {
	return a.db.Save(ruleChain).Error
}

// UpdateChainRoot 设置规则链
func (a *RuleChain) UpdateChainRoot(id string, isRoot bool) (data models.RuleChain, err error) {
	err = a.db.Model(&data).Where("record_id = ?", id).
		Update("root", isRoot).Error
	return
}
