package main

import (
	"time"

	"mongo.games.com/goserver/core/logger"
	"mongo.games.com/goserver/core/netlib"

	"mongo.games.com/game/common"
	"mongo.games.com/game/model"
	"mongo.games.com/game/protocol/rankmatch"
	"mongo.games.com/game/srvdata"
)

func init() {
	// 赛季信息
	common.Register(int(rankmatch.RankMatch_PACKET_RM_CSRMSeasonInfo), rankmatch.CSRMSeasonInfo{}, CSRMSeasonInfo)
	// 段位表
	common.Register(int(rankmatch.RankMatch_PACKET_RM_CSRMRankConfig), rankmatch.CSRMRankConfig{}, CSRMRankConfig)
	// 段位奖励
	common.Register(int(rankmatch.RankMatch_PACKET_RM_CSRMAwardConfig), rankmatch.CSRMAwardConfig{}, CSRMAwardConfig)
	// 领取段位奖励
	common.Register(int(rankmatch.RankMatch_PACKET_RM_CSRMAward), rankmatch.CSRMAward{}, CSRMAward)
}

// CSRMSeasonInfo 赛季信息
func CSRMSeasonInfo(s *netlib.Session, packetId int, data interface{}, sid int64) error {
	logger.Logger.Trace("CSRMSeasonInfo")
	p := PlayerMgrSington.GetPlayer(sid)
	if p == nil {
		logger.Logger.Warnf("CSRMSeasonInfo p == nil.")
		return nil
	}
	if p.Platform == DefaultPlatform {
		logger.Logger.Warnf("CSRMSeasonInfo Platform == Default_Platform.")
		return nil
	}

	pack := &rankmatch.SCRMSeasonInfo{}

	cfg := RankMgrSingleton.GetSeasonConfig(p.Platform)
	if cfg == nil {
		p.SendToClient(int(rankmatch.RankMatch_PACKET_RM_SCRMSeasonInfo), pack)
		return nil
	}

	pack = &rankmatch.SCRMSeasonInfo{
		Id:        cfg.SeasonId,
		TimeStamp: []int64{cfg.StartTs, cfg.EndTs},
	}

	rank := RankMgrSingleton.GetPlayerSeason(p.SnId)
	if rank != nil && rank.RankType != nil {
		for k, v := range rank.RankType {
			if v == nil {
				continue
			}
			info := &rankmatch.SeasonInfo{Id: k}
			info.Lv, info.Score = RankMgrSingleton.GetPlayerRankLV(k, p.SnId)
			info.LastLv, info.LastScore = RankMgrSingleton.GetPlayerLastRankLV(k, p.SnId)
			pack.Seasons = append(pack.Seasons, info)
		}
	}
	p.SendToClient(int(rankmatch.RankMatch_PACKET_RM_SCRMSeasonInfo), pack)
	logger.Logger.Trace("SCTMSeasonInfo:", pack)
	return nil
}

// CSRMRankConfig 段位列表
func CSRMRankConfig(s *netlib.Session, packetId int, data interface{}, sid int64) error {
	logger.Logger.Tracef("CSRMRankConfig data:%v", data)
	msg, ok := data.(*rankmatch.CSRMRankConfig)
	if !ok {
		return nil
	}

	if msg.GetId() <= 0 {
		return nil
	}

	p := PlayerMgrSington.GetPlayer(sid)
	if p == nil {
		logger.Logger.Warnf("CSRMRankConfig p == nil.")
		return nil
	}
	if p.Platform == DefaultPlatform {
		logger.Logger.Warnf("CSRMRankConfig Platform == Default_Platform.")
		return nil
	}

	pack := &rankmatch.SCRMRankConfig{}
	for _, v := range RankMgrSingleton.GetRankList(msg.GetId()) {
		pack.Items = append(pack.Items, &rankmatch.RankItem{
			Id:    v.Id,
			Lv:    v.Lv,
			Score: v.Score,
		})
	}

	p.SendToClient(int(rankmatch.RankMatch_PACKET_RM_SCRMRankConfig), pack)
	logger.Logger.Trace("SCRMRankConfig:", pack)
	return nil
}

// CSRMAwardConfig 段位奖励
func CSRMAwardConfig(s *netlib.Session, packetId int, data interface{}, sid int64) error {
	logger.Logger.Tracef("CSRMAwardConfig data:%v", data)
	msg, ok := data.(*rankmatch.CSRMAwardConfig)
	if !ok {
		return nil
	}

	if msg.GetId() <= 0 {
		return nil
	}

	p := PlayerMgrSington.GetPlayer(sid)
	if p == nil {
		logger.Logger.Warnf("CSRMAwardConfig p == nil.")
		return nil
	}
	if p.Platform == DefaultPlatform {
		logger.Logger.Warnf("CSRMAwardConfig Platform == Default_Platform.")
		return nil
	}

	rank := RankMgrSingleton.GetPlayerSeason(p.SnId)

	lv, _ := RankMgrSingleton.GetPlayerRankLV(msg.GetId(), p.SnId)

	pack := &rankmatch.SCRMAwardConfig{}

	for _, item := range RankMgrSingleton.GetRankAwardList(msg.GetId()) {
		// 1 可领取 2已领取
		if lv >= item.Lv && rank != nil {
			item.ReceiveType = 1 // 可领取
			// 是否已领取
			if info := rank.RankType[msg.GetId()]; info != nil {
				for _, v := range info.Awards {
					if v.Id == item.Id {
						if v.Ts > 0 {
							item.ReceiveType = 2 // 已领取
						}
						break
					}
				}
			}
		}

		pack.List = append(pack.List, item)
	}

	p.SendToClient(int(rankmatch.RankMatch_PACKET_RM_SCRMAwardConfig), pack)
	logger.Logger.Trace("SCRMAwardConfig:", pack)
	return nil
}

// CSRMAward 领取段位奖励
func CSRMAward(s *netlib.Session, packetId int, data interface{}, sid int64) error {
	logger.Logger.Tracef("CSRMAward data:%v", data)
	msg, ok := data.(*rankmatch.CSRMAward)
	if !ok {
		return nil
	}

	if msg.GetId() <= 0 {
		return nil
	}

	d := srvdata.PBDB_RankRewardMgr.GetData(msg.AwardId)
	if d == nil {
		return nil
	}

	p := PlayerMgrSington.GetPlayer(sid)
	if p == nil {
		logger.Logger.Warnf("CSRMAward p == nil.")
		return nil
	}
	if p.Platform == DefaultPlatform {
		logger.Logger.Warnf("CSRMAward Platform == Default_Platform.")
		return nil
	}

	rank := RankMgrSingleton.GetPlayerSeason(p.SnId)
	if rank == nil {
		return nil
	}

	pack := &rankmatch.SCRMAward{
		Code: 1, // 1 失败
		Id:   msg.GetAwardId(),
	}

	var isAward bool
	if info := rank.RankType[msg.GetId()]; info != nil {
		for _, v := range info.Awards {
			if v.Id == msg.GetAwardId() {
				// 是否已领取
				if v.Ts > 0 {
					isAward = true
				}
				break
			}
		}
	}

	if isAward {
		p.SendToClient(int(rankmatch.RankMatch_PACKET_RM_SCRMAward), pack)
		logger.Logger.Trace("SCRMAward already receive:", pack)
		return nil
	}

	// 是否可领取
	lv, _ := RankMgrSingleton.GetPlayerRankLV(msg.GetId(), p.SnId)
	if lv >= d.GetLevel() {
		// 可以领取
		isAward = true
	}

	// 领取奖励
	if isAward {
		pack.Code = 0 // 领取成功
		rank.RankType[msg.GetId()].Awards = append(rank.RankType[msg.GetId()].Awards, &model.RankAward{
			Id: msg.AwardId,
			Ts: time.Now().Unix(),
		})
		rank.Dirty = true
		p.dirty = true

		type Param struct {
			Id  int32
			Num int32
		}
		f := func(v *Param) {
			if v.Num > 0 {
				switch {
				case v.Id <= 0:
				case v.Id == 1: //金币
					p.AddCoin(int64(v.Num), 0, common.GainWay_RankMatch, "system", "段位奖励")
					LogChannelSingleton.WriteMQData(model.GenerateSystemFreeGive(p.SnId, p.Name, p.Platform,
						model.SystemFreeGive_GiveType_RankMatch, model.SystemFreeGive_CoinType_Coin, int64(v.Num)))
				case v.Id == 2: //钻石
					p.AddDiamond(int64(v.Num), 0, common.GainWay_RankMatch, "system", "段位奖励")
					LogChannelSingleton.WriteMQData(model.GenerateSystemFreeGive(p.SnId, p.Name, p.Platform,
						model.SystemFreeGive_GiveType_RankMatch, model.SystemFreeGive_CoinType_Diamond, int64(v.Num)))
				default:
					//道具
					item := &Item{
						ItemId:  v.Id,
						ItemNum: int64(v.Num),
					}
					BagMgrSingleton.AddJybBagInfo(p, []*Item{item}, 0, common.GainWay_RankReward, "system", "段位奖励")
					itemData := srvdata.PBDB_GameItemMgr.GetData(item.ItemId)
					if itemData != nil {
						BagMgrSingleton.RecordItemLog(p.Platform, p.SnId, ItemObtain, item.ItemId, itemData.Name, int64(item.ItemNum), "段位奖励")
					}
				}
			}
		}
		f(&Param{
			Id:  d.Award1Id,
			Num: d.Award1Num,
		})
		f(&Param{
			Id:  d.Award2Id,
			Num: d.Award2Num,
		})
		f(&Param{
			Id:  d.Award3Id,
			Num: d.Award3Num,
		})
	}

	p.SendToClient(int(rankmatch.RankMatch_PACKET_RM_SCRMAward), pack)
	logger.Logger.Trace("SCRMAward:", pack)
	return nil
}
