package system

import (
	"errors"
	"sundynix-go/global"
	common "sundynix-go/model/commom/request"
	"sundynix-go/model/system"
	systemReq "sundynix-go/model/system/request"

	"gorm.io/gorm"
)

type RoleService struct {
}

var RoleServiceApp = new(RoleService)

func (s *RoleService) SaveRole(role system.Role) error {
	if !errors.Is(global.DB.Where("code = ?", role.Code).First(&system.Role{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在重复角色")
	}
	return global.DB.Create(&role).Error
}

func (s *RoleService) UpdateRole(role system.Role) error {
	return global.DB.Model(&role).Where("id = ?", role.Id).Updates(&role).Error
}

func (s *RoleService) GetRoleList(info systemReq.GetRoleList) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Current - 1)
	db := global.DB.Model(&system.Role{})
	var roleList []system.Role
	if info.Code != "" {
		db = db.Where("code = ?", info.Code)
	}
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Find(&roleList).Error
	return roleList, total, err
}

func (s *RoleService) DeleteRoleByIds(ids common.IdsReq) error {
	return global.DB.Where("id in ?", ids.Ids).Delete(&system.Role{}).Error
}

func (s *RoleService) GetRoleById(id string) (role system.Role, err error) {
	var r system.Role
	err = global.DB.Where("id = ?", id).First(&r).Error
	return r, err
}

func (s *RoleService) GrantRole(userId string, roleIds []string) error {
	//1. 检查是否存在userid的授权记录 存在就删除 不存在就插入
	//2. 插入新的数据
	return global.DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("user_id = ?", userId).Delete(&system.UserRole{}).Error; err != nil {
			return err
		}
		for _, roleId := range roleIds {
			if err := tx.Create(&system.UserRole{UserId: userId, RoleId: roleId}).Error; err != nil {
				return err
			}
		}
		return nil
	})

}

func (s *RoleService) GrantMenu(roleId string, menuIds []string) error {
	//1. 检查是否存在userid的授权记录 存在就删除 不存在就插入
	//2. 插入新的数据
	return global.DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("role_id = ?", roleId).Delete(&system.RoleMenu{}).Error; err != nil {
			return err
		}
		for _, menuId := range menuIds {
			if err := tx.Create(&system.RoleMenu{RoleId: roleId, MenuId: menuId}).Error; err != nil {
				return err
			}
		}
		return nil
	})
}
