package basic

import (
	"context"
	"time"

	"bsm/full/module/finance/wallet/internal/excode"
	"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/utils"
	"git.apinb.com/bsm-sdk/core/vars"
)

// 申请提现
func ApplyCash(ctx context.Context, in *pb.ApplyCashRequest) (reply *pb.StatusReply, err error) {
	auth, ok := service.ParseMetaCtx(ctx, nil)
	if ok != nil {
		return nil, ok
	}

	if in.Amount == 0 || in.Channel == 0 {
		return nil, errcode.ErrInvalidArgument
	}

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

	if in.Amount > myWallet.Balance {
		return nil, excode.ErrBalanceNotEnough
	}

	data := &models.WalletApplyCash{
		WalletIdentity: myWallet.Identity,
		Amount:         in.Amount,
		Channel:        int8(in.Channel),
		Remark:         in.Remark,
	}
	data.Identity = utils.UUID()
	data.PassportID = auth.ID
	data.PassportIdentity = auth.Identity

	err = impl.DBService.Create(&data).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	//生成提现单
	return &pb.StatusReply{
		Message: vars.OK,
		Timeseq: time.Now().UnixMilli(),
	}, nil
}
