package player

import (
	"context"
	jsoniter "github.com/json-iterator/go"
	"github.com/mhaya/game/game_cluster/internal/code"
	"github.com/mhaya/game/game_cluster/internal/constant"
	"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) rank(req *param.GetRankReq) (*param.GetRankResp, int32) {
	if !p.isOnline {
		return nil, code.LoginError
	}
	var resp param.GetRankResp
	rankList := models.GetRankList(req.Id, req.Tp)
	resp.Ranks = rankList
	for _, rank := range rankList {
		if req.Tp == 1 {
			rank.IsClaim = p.Player.RankReward[req.Id].Status
		}
		if p.Player.UserName == rank.UserName {
			resp.Self = rank
		}
	}
	if resp.Self == nil {
		ctx := context.Background()
		info := mdb.RDB.HGet(ctx, constant.PlayerBaseKey, p.Player.UserName).Val()
		var playerBase param.PlayerBase
		jsoniter.Unmarshal([]byte(info), &playerBase)
		key := models.GetRankKey(req.Id, req.Tp)
		resp.Self = &param.PlayerBase{
			UserName:      playerBase.UserName,
			UserNameMaybe: playerBase.UserNameMaybe,
			Avatar:        playerBase.Avatar,
			OpenId:        playerBase.OpenId,
			NickName:      playerBase.NickName,
			Rank:          models.GetPlayerRank(key, p.Player.UserName),
			Score:         models.GetPlayerRankScore(key, p.Player.UserName),
			Reward:        nil,
		}
	}
	return &resp, code.OK
}
