package manage

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

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

func GetInIdListAuthority(ids []int) ([]domain.Authority, error) {
	rows, err := configs.Engine.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
		list = append(list, u)
	}
	return list, nil
}

func GetListAuthority(authority domain.Authority, pageNum, pageSize int) (vo.BaseListVo, error) {
	rows, err := configs.Engine.Limit(pageSize, (pageNum-1)*pageSize).Desc("id").Rows(&authority)
	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.Authority
		rows.Scan(&u)
		vo.List = append(vo.List, u)
	}
	//查询数量
	count, err := configs.Engine.Count(&authority)
	vo.Total = int(count)
	return vo, nil
}

func SaveAuthority(authority *domain.Authority) (domain.Authority, error) {
	_, err := configs.Engine.Insert(&authority)
	if err != nil {
		return *authority, err
	}
	return *authority, nil
}

func SetAuthority(authorityMap map[string]interface{}, id int) (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(authority domain.Authority) bool {
	i, err := configs.Engine.Where("id = ?", authority.Id).Delete(&authority)
	if err != nil {
		return false
	}
	return i > 0
}
