package model

import (
	"sparrow/pkg/models"

	"github.com/jinzhu/gorm"
)

// Role role
type Role struct {
	db *gorm.DB
}

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

// Create create
func (a *Role) Create(role *models.Role) error {
	return a.db.Save(role).Error
}

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

// Delete delete
func (a *Role) Delete(role *models.Role) error {
	a.db.Model(&models.User{}).Where("user_role_id = ?", role.ID).Update(map[string]interface{}{"user_role_id": 1})
	return a.db.Delete(role).Error
}

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

// QueryRole query a role
func (a *Role) QueryRole(roleid int) (data models.Role, err error) {
	err = a.db.Where(roleid).First(&data).Error
	return
}
