package manage

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

func GetBackRoleById(id int64) (domain.BackRole, error) {
	var backRole domain.BackRole
	_, err := configs.Engine.Table("back_role").Where("id = ?", id).Get(&backRole)
	if err != nil {
		return backRole, err
	}
	return backRole, nil
}

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

func GetBackRoleList(backRole domain.BackRole, pageNum, pageSize int) (vo.BaseListVo, error) {
	var arr []domain.BackRole
	Count, err := configs.Engine.Table("back_role").Limit(pageSize, (pageNum-1)*pageSize).FindAndCount(&arr, &backRole)
	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 SaveBackRole(backRole *domain.BackRole) (domain.BackRole, error) {
	_, err := configs.Engine.Table("back_role").Insert(&backRole)
	if err != nil {
		return *backRole, err
	}
	return *backRole, nil
}

func SetBackRole(backRoleMap map[string]interface{}, id int64) (domain.BackRole, bool, error) {
	var backRole domain.BackRole
	_, err := configs.Engine.Table("back_role").Where("id = ?", id).Update(backRoleMap)
	if err != nil {
		return backRole, false, err
	}
	return backRole, true, nil
}

func DeleteBackRole(id int64) bool {
	var backRole domain.BackRole
	i, err := configs.Engine.Table("back_role").Where("id = ?", id).Delete(&backRole)
	if err != nil {
		return false
	}
	return i > 0
}
