package manage

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

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

func GetUserWalletListInId(ids []int64) ([]domain.UserWallet, error) {
	rows, err := configs.Engine.Table("user_wallet").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
		rows.Scan(&u)
		list = append(list, u)
	}
	return list, nil
}

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

func SetUserWallet(userWalletMap map[string]interface{}, id int64) (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(id int64) bool {
	var userWallet domain.UserWallet
	i, err := configs.Engine.Table("user_wallet").Where("id = ?", id).Delete(&userWallet)
	if err != nil {
		return false
	}
	return i > 0
}
