package gm_services

import (
	"fmt"
	"gadmin/config"
	"gadmin/internal/admin/forms"
	"gadmin/internal/admin/gm_rpc/gate"
	"gadmin/internal/admin/gm_rpc/rpc_share"
	sqlModel "gadmin/internal/gorm/model"
	"gadmin/utility"
	"gadmin/utility/character"
	"gadmin/utility/player"
	"gadmin/utility/token"
	"github.com/gin-gonic/gin"
	msg2 "leafstalk/covenant/msg"
	"strings"
	"time"
)

const (
	coin    int64 = 2001
	diamond int64 = 2002
)

// AddCoin 增加用户金币或钻石
func AddCoin(ctx *gin.Context, params forms.AddCoinReq) (err error) {
	if params.UserId == 0 {
		return errNoUser
	}

	playerAttr, err := player.GetAttrByUserId(params.UserId)
	if err != nil {
		return
	}

	//获取userAccount
	var userAccountModel sqlModel.UserAccount
	err = config.LDB.WithContext(ctx).Scopes(sqlModel.UserAccountTable(&userAccountModel, playerAttr.AccID)).Where("accId = ?", playerAttr.AccID).First(&userAccountModel).Error
	if err != nil {
		return
	}
	openIdArr := strings.Split(userAccountModel.Openid, "@")

	msg := msg2.GmAddMaterial{
		MsgId:      character.GenerateMsgId(),
		PlayerID:   params.UserId,
		Materials:  map[int64]int64{coin: params.Coin},
		OperatorId: token.GetUID(ctx),
		ClientPlat: openIdArr[1],
	}

	if params.GoodId == 1 {
		msg.Materials = map[int64]int64{coin: params.Coin}
		err = gate.SendToWorld(0, &msg)
		if err == nil {
			rpc_share.MsgMap[msg.MsgId] = fmt.Sprintf("%s,GM为玩家[%d]变更金币[%d]",
				utility.FormatSecond(time.Now()),
				params.UserId,
				params.Coin)
		}
		return
	} else {
		msg.Materials = map[int64]int64{diamond: params.Coin}
		err = gate.SendToWorld(0, &msg)
		if err == nil {
			rpc_share.MsgMap[msg.MsgId] = fmt.Sprintf("%s,GM为玩家[%d]变更钻石[%d]",
				utility.FormatSecond(time.Now()),
				params.UserId,
				params.Diamond)
		}
		return
	}
}

func BuyGoods(params forms.AddCoinReq) (err error) {
	if params.UserId == 0 {
		return errNoUser
	}

	if params.GoodId > 0 {
		// msg := msg2.GmAddMaterial{
		// 	MsgId:     utils.GenerateMsgId(),
		// 	PlayerID:  params.UserId,
		// 	Materials: []*model.DropMaterial{{coin, int(params.Coin)}},
		// }
		// err = gate.SendToWorld(0, &msg)
		// if err == nil {
		// 	rpc_share.MsgMap[msg.MsgId] = fmt.Sprintf("%s,GM为玩家[%d]添加金币[%d]",
		// 		utils.FormatSecond(time.Now()),
		// 		params.UserId,
		// 		params.Coin)
		// }
	}

	return
}
