package manage

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

func GetBackRoleAuthorityById(id int64) (domain.BackRoleAuthority, error) {
	var backRoleAuthority domain.BackRoleAuthority
	_, err := configs.Engine.Table("back_role_authority").Where("id = ?", id).Get(&backRoleAuthority)
	if err != nil {
		return backRoleAuthority, err
	}
	return backRoleAuthority, nil
}

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

func GetBackRoleAuthorityList(backRoleAuthority domain.BackRoleAuthority, pageNum, pageSize int) (vo.BaseListVo, error) {
	var arr []domain.BackRoleAuthority
	Count, err := configs.Engine.Table("back_role_authority").Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr, &backRoleAuthority)
	var vo vo.BaseListVo
	if err != nil {
		return vo, err
	}
	if err != nil {
		return vo, err
	}
	vo.PageNum = pageNum
	vo.PageSize = pageSize
	vo.List = make([]any, len(arr))
	for i, v := range arr {
		vo.List[i] = v
	}
	vo.Total = int(Count)
	return vo, nil
}

func SaveBackRoleAuthority(backRoleAuthority *domain.BackRoleAuthority) (domain.BackRoleAuthority, error) {
	_, err := configs.Engine.Table("back_role_authority").Insert(&backRoleAuthority)
	if err != nil {
		return *backRoleAuthority, err
	}
	return *backRoleAuthority, nil
}

func SetBackRoleAuthority(backRoleAuthorityMap map[string]interface{}, id int64) (domain.BackRoleAuthority, bool, error) {
	var backRoleAuthority domain.BackRoleAuthority
	_, err := configs.Engine.Table("back_role_authority").Where("id = ?", id).Update(backRoleAuthorityMap)
	if err != nil {
		return backRoleAuthority, false, err
	}
	return backRoleAuthority, true, nil
}

func DeleteBackRoleAuthority(id int64) bool {
	var backRoleAuthority domain.BackRoleAuthority
	i, err := configs.Engine.Table("back_role_authority").Where("id = ?", id).Delete(&backRoleAuthority)
	if err != nil {
		return false
	}
	return i > 0
}
