package manage

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

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

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

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

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

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