package controller

import (
	mhayaGin "github.com/mhaya/components/gin"
	cstring "github.com/mhaya/extend/string"
	"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/models"
	"github.com/mhaya/game/game_cluster/internal/param"
	mhayaLogger "github.com/mhaya/logger"
)

func (p *Controller) cashOut(c *mhayaGin.Context) {

	var pa param.CashOutReq
	if err := c.BindJSON(&pa); err != nil {
		mhayaLogger.Warnf("if cashOut err {. params=%s", pa)
		code.RenderResult(c, code.Error)
		return
	}
	if pa.Tp == 0 {
		code.RenderResult(c, code.Error)
		return
	}
	switch pa.Tp {
	case 1:
		ret, ok := data.DiscreteRuleConfig.Get(models.UCashOutConfig)
		if !ok {
			code.RenderResult(c, code.Error)
			return
		}
		i, _ := cstring.ToInt(ret.Condition)
		if pa.Amount < float64(i) {
			code.RenderResult(c, code.Error)
			return
		}
	case 2:
		ret, ok := data.DiscreteRuleConfig.Get(models.TonCashOutConfig)
		if !ok {
			code.RenderResult(c, code.Error)
			return
		}
		i, _ := cstring.ToInt(ret.Condition)
		if pa.Amount < float64(i) {
			code.RenderResult(c, code.Error)
			return
		}
	default:
		code.RenderResult(c, code.Error)
		return
	}

	token, err := p.Auth(c)
	if code.IsFail(err) {
		mhayaLogger.Warnf("if cashOut token err {. params=%s", c.GetHeader(constant.Token))
		code.RenderResult(c, code.AccountTokenValidateFail)
		return
	}

	errCode := p.CallWait(token.TargetPath, "cashOut", &pa, nil)
	if code.IsFail(errCode) {
		mhayaLogger.Warnf("[cashOut] param = %v, errCode = %v", pa, errCode)
		code.RenderResult(c, errCode)
		return
	}

	code.RenderResult(c, code.OK)
}
