package gameUser

import (
	"fmt"
	"game/common/model/user"
	"game/common/proto/pb"
	"game/common/rpc"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	us "github.com/flipped-aurora/gin-vue-admin/server/service/user"
	"github.com/flipped-aurora/gin-vue-admin/server/servicex"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type GameUserApi struct{}

func (e *GameUserApi) GetUserById(c *gin.Context) {
	var gameUser = &user.GameUser{}
	err := c.ShouldBindJSON(gameUser)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if gameUser.ID < 1 {
		response.FailWithMessage(fmt.Sprintf("玩家id不能为0"), c)
		return
	}

	var code pb.ErrCode
	gameUser, code = us.GetUser(gameUser.ID)
	if code != pb.ErrCode_OK {
		global.GVA_LOG.Error("查询失败!", zap.Error(fmt.Errorf(code.String())))
		response.FailWithMessage("查询失败", c)
		return
	}
	response.OkWithData(gin.H{"user": gameUser}, c)
}

func (e *GameUserApi) GetAccountByUid(c *gin.Context) {
	var account = &user.UserAccount{}
	err := c.ShouldBindJSON(account)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if account.ID < 1 {
		response.FailWithMessage(fmt.Sprintf("玩家帐号id不能为0"), c)
		return
	}

	var code pb.ErrCode
	account, code = rpc.RpcGetAccountByUid(servicex.GetService(), account.ID)
	if code != pb.ErrCode_OK {
		global.GVA_LOG.Error("查询失败!", zap.Error(fmt.Errorf(code.String())))
		response.FailWithMessage("查询失败", c)
		return
	}
	response.OkWithData(gin.H{"account": account}, c)
}

type AddUserResReq struct {
	UId      int64  `json:"uid"`
	ResType  string `json:"res_type"`
	ResValue int64  `json:"res_value"`
	Reason   string `json:"reason"`
}

func (e *GameUserApi) AddUserRes(c *gin.Context) {
	var req = &AddUserResReq{}
	err := c.ShouldBindJSON(req)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if req.UId < 1 {
		response.FailWithMessage(fmt.Sprintf("玩家id不能为0"), c)
		return
	}
	if req.ResType == "" {
		response.FailWithMessage(fmt.Sprintf("资源类型不能为空"), c)
		return
	}
	if req.ResValue == 0 {
		response.FailWithMessage(fmt.Sprintf("添加资源不能为0"), c)
		return
	}

	values, code := rpc.RpcAddUserRes(servicex.GetService(), req.UId, &user.AddUserRes{
		Reason: req.Reason,
		AddRes: map[string]int64{
			req.ResType: req.ResValue,
		},
	})
	if code != pb.ErrCode_OK {
		global.GVA_LOG.Error("查询失败!", zap.Error(fmt.Errorf(code.String())))
		response.FailWithMessage("查询失败", c)
		return
	}
	response.OkWithData(gin.H{"res": values}, c)
}
