package basic

import (
	"context"
	"strconv"
	"time"

	"bsm/full/module/finance/wallet/internal/impl"
	"bsm/full/module/finance/wallet/internal/models"
	pb "bsm/full/module/finance/wallet/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"git.apinb.com/bsm-sdk/core/vars"
)

// 获取钱包信息
func GetWallet(ctx context.Context, in *pb.GetWalletRequest) (reply *pb.GetWalletReply, err error) {
	auth, ok := service.ParseMetaCtx(ctx, nil)
	if ok != nil {
		return nil, ok
	}

	myWallet, err := models.GetWalletByPassportIdentity(auth.ID, auth.Identity)
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	var transIn int8 = 1   // 收入
	var transOut int8 = -1 // 支出

	ymd, _ := strconv.Atoi(time.Now().Format(vars.YYYYMMDD))
	ym := time.Now().Year()*100 + int(time.Now().Month())

	var totalMoney int64
	total := make(map[string]int64)

	// 统计当日收入
	if in.IsTotalTodayIn {
		impl.DBService.Model(&models.WalletRecord{}).Select("sum(money)").Where("passport_id=? AND trans_type=? AND ymd=?", auth.ID, transIn, ymd).Scan(&totalMoney)
		total["TodayIn"] = totalMoney
	}

	// 统计当日支出
	if in.IsTotalTodayOut {
		impl.DBService.Model(&models.WalletRecord{}).Select("sum(money)").Where("passport_id=? AND trans_type=? AND ymd=?", auth.ID, transOut, ymd).Scan(&totalMoney)
		total["TodayOut"] = totalMoney
	}

	// 统计本月收入
	if in.IsTotalMonthIn {
		impl.DBService.Model(&models.WalletRecord{}).Select("sum(money)").Where("passport_id=? AND trans_type=? AND ym=?", auth.ID, transIn, ym).Scan(&totalMoney)
		total["MonthIn"] = totalMoney
	}

	// 统计本月支出
	if in.IsTotalMonthOut {
		impl.DBService.Model(&models.WalletRecord{}).Select("sum(money)").Where("passport_id=? AND trans_type=? AND ym=?", auth.ID, transOut, ym).Scan(&totalMoney)
		total["MonthOut"] = totalMoney
	}

	// 统计全部收入
	if in.IsTotalAllIn {
		impl.DBService.Model(&models.WalletRecord{}).Select("sum(money)").Where("passport_id=? AND trans_type=? ", auth.ID, transIn).Scan(&totalMoney)
		total["AllIn"] = totalMoney
	}

	// 统计全部支出
	if in.IsTotalAllOut {
		impl.DBService.Model(&models.WalletRecord{}).Select("sum(money)").Where("passport_id=? AND trans_type=? ", auth.ID, transOut).Scan(&totalMoney)
		total["AllOut"] = totalMoney
	}
	// remove useless fmt.Sprint side-effect-free call
	return &pb.GetWalletReply{
		PassportIdentity:  myWallet.PassportIdentity,
		WalletIdentity:    myWallet.Identity,
		Balance:           myWallet.Balance,
		WithdrawalBalance: myWallet.WithdrawalBalance,
		Total:             total,
		Status:            int32(myWallet.Status),
		AlipayId:          myWallet.AlipayID,
		WxpayId:           myWallet.WxpayID,
		Created:           myWallet.CreatedAt.Format(vars.YYYY_MM_DD_HH_MM_SS),
	}, nil
}
