package manage

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

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

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

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

func SetAuthority(authorityMap map[string]interface{}, id int64) (domain.Authority, bool, error) {
	var authority domain.Authority
	_, err := configs.Engine.Table("authority").Where("id = ?", id).Update(authorityMap)
	if err != nil {
		return authority, false, err
	}
	return authority, true, nil
}

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