package manage

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

func GetBackAuthorityById(id int64) (domain.BackAuthority, error) {
	var backAuthority domain.BackAuthority
	_, err := configs.Engine.Table("back_authority").Where("id = ?", id).Get(&backAuthority)
	if err != nil {
		return backAuthority, err
	}
	return backAuthority, nil
}

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

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

func SetBackAuthority(backAuthorityMap map[string]interface{}, id int64) (domain.BackAuthority, bool, error) {
	var backAuthority domain.BackAuthority
	_, err := configs.Engine.Table("back_authority").Where("id = ?", id).Update(backAuthorityMap)
	if err != nil {
		return backAuthority, false, err
	}
	return backAuthority, true, nil
}

func DeleteBackAuthority(id int64) bool {
	var backAuthority domain.BackAuthority
	i, err := configs.Engine.Table("back_authority").Where("id = ?", id).Delete(&backAuthority)
	if err != nil {
		return false
	}
	return i > 0
}
