package player

import (
	"context"
	mhayaTime "github.com/mhaya/extend/time"
	"github.com/mhaya/game/game_cluster/internal/code"
	"github.com/mhaya/game/game_cluster/internal/constant"
	"github.com/mhaya/game/game_cluster/internal/data"
	"github.com/mhaya/game/game_cluster/internal/mdb"
	"github.com/mhaya/game/game_cluster/internal/mdb/models"
	"github.com/mhaya/game/game_cluster/internal/param"
)

func (p *actorPlayer) cashOut(req *param.CashOutReq) int32 {
	if !p.isOnline {
		return code.PlayerNotLogin
	}
	if p.Player.TonWall == "" {
		return code.TonWallNotExistsError
	}
	num := int(req.Amount * float64(constant.MoneyRatio))
	var id int
	switch req.Tp {
	case 1:
		id = models.ItemU
	case 2:
		id = models.ItemTon
	}
	if p.Player.Item[id].Num >= num {
		old := p.Player.Item[id].Num
		p.Player.Item[id].Sub(num)
		rs, err := mdb.MDB.Collection(constant.CNameCashOutRecord).InsertOne(context.Background(), &models.CashOutRecord{UserName: p.Player.UserName,
			NickName:    p.Player.NickName,
			Status:      0,
			Type:        1,
			AfterAmount: old,
			Amount:      num,
			Address:     p.Player.TonWall,
			CreateAt:    mhayaTime.Now().Unix(),
		})
		if err != nil || rs.InsertedID == "" {
			return code.Error
		}

		p.cashOutStat(num)

		p.Player.SetPlayerRewardLog(models.SourceCashOut, 0, []data.ItemReward{}, []data.ItemReward{{4, models.ItemU, num}}, rs.InsertedID)
	} else {
		return code.NotEnoughItemsError
	}

	return code.OK
}
