package manage

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

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

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

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

func SaveUserWallet(userWallet *domain.UserWallet) (domain.UserWallet, error) {
	_, err := configs.Engine.Insert(&userWallet)
	if err != nil {
		return *userWallet, err
	}
	return *userWallet, nil
}

func SetUserWallet(userWalletMap map[string]interface{}, id int) (domain.UserWallet, bool, error) {
	var userWallet domain.UserWallet
	_, err := configs.Engine.Table("user_wallet").Where("id = ?", id).Update(userWalletMap)
	if err != nil {
		return userWallet, false, err
	}
	return userWallet, true, nil
}

func DeleteUserWallet(userWallet domain.UserWallet) bool {
	i, err := configs.Engine.Where("id = ?", userWallet.Id).Delete(&userWallet)
	if err != nil {
		return false
	}
	return i > 0
}
