package manage

import (
	"demo/configs"
	"demo/data/domain"
	"demo/data/domain/vo"
)

func GetByIdRole(id int) (domain.Role, error) {
	var role domain.Role
	_, err := configs.Engine.Where("id = ?", id).Get(&role)
	if err != nil {
		return role, err
	}
	return role, nil
}

func GetInIdListRole(ids []int) ([]domain.Role, error) {
	rows, err := configs.Engine.In("id", ids).Rows(&domain.Role{})
	if err != nil {
		return make([]domain.Role, 0), err
	}
	defer rows.Close()
	var list []domain.Role
	for rows.Next() {
		var u domain.Role
		list = append(list, u)
	}
	return list, nil
}

func GetListRole(role domain.Role, pageNum, pageSize int) (vo.BaseListVo, error) {
	rows, err := configs.Engine.Limit(pageSize, (pageNum-1)*pageSize).Desc("id").Rows(&role)
	var vo vo.BaseListVo
	if err != nil {
		return vo, err
	}
	vo.PageNum = pageNum
	vo.PageSize = pageSize
	vo.List = make([]any, 0)
	for rows.Next() {
		var u domain.Role
		rows.Scan(&u)
		vo.List = append(vo.List, u)
	}
	//查询数量
	count, err := configs.Engine.Count(&role)
	vo.Total = int(count)
	return vo, nil
}

func SaveRole(role *domain.Role) (domain.Role, error) {
	_, err := configs.Engine.Insert(&role)
	if err != nil {
		return *role, err
	}
	return *role, nil
}

func SetRole(roleMap map[string]interface{}, id int) (domain.Role, bool, error) {
	var role domain.Role
	_, err := configs.Engine.Table("role").Where("id = ?", id).Update(roleMap)
	if err != nil {
		return role, false, err
	}
	return role, true, nil
}

func DeleteRole(role domain.Role) bool {
	i, err := configs.Engine.Where("id = ?", role.Id).Delete(&role)
	if err != nil {
		return false
	}
	return i > 0
}
