package player

import (
	"context"
	"fmt"
	mhayaTime "github.com/mhaya/extend/time"
	"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"
	"github.com/mhaya/game/game_cluster/internal/mdb/models"
	"github.com/mhaya/game/game_cluster/internal/param"
	mhayaLogger "github.com/mhaya/logger"
)

func (p *actorPlayer) claim(req *param.ClaimReq) (*param.ChangeData, int32) {
	if !p.isOnline {
		mhayaLogger.Infof("[claim] PlayerNotLogin err node=%v", p.App().NodeId())
		return nil, code.PlayerNotLogin
	}
	var resp *param.ChangeData
	var code int32
	switch req.Tp {
	case 1:
		resp, code = p.ClaimRankReward(req.Id)
	case 2:
		resp, code = p.inviteClaimRatio(req.UserName)
	case 3:
		resp, code = p.ClaimFirstReward(req.Id)
	case 4:
		resp, code = p.ClaimInviteNodeReward(req.Id)
	}
	p.dirty = true

	return resp, code
}

// 领取排行榜奖励
func (p *actorPlayer) ClaimRankReward(tp int) (*param.ChangeData, int32) {
	var resp param.ChangeData
	ID := 1
	key := models.GetRankKey(ID, tp, true)
	rank := models.GetPlayerRank(key, p.Player.UserName)
	rankReward := data.RankRewardConfig.GetRewardByRank(ID, rank)
	if len(rankReward) == 0 {
		return nil, code.NoYetUnlockedError
	}

	var addItem models.AddItem
	resp.AddItem = addItem.Add(rankReward)
	p.Player.Item.AddItem(rankReward)
	p.Player.RankReward[tp].ClaimTime = mhayaTime.Now().Unix()
	p.Player.RankReward[tp].Status = 2
	resp.CurGold = p.Player.Item[1].Num
	return &resp, code.OK
}

// 邀请裂变奖励领取
func (p *actorPlayer) inviteClaimRatio(userName string) (*param.ChangeData, int32) {
	if !p.isOnline {
		return nil, code.PlayerNotLogin
	}

	default_friend := []int{2001, 2002, 2003}
	for _, id := range default_friend {
		row, _ := data.DiscreteRuleConfig.Get(id)
		if row == nil {
			continue
		}

		if row.Condition != userName {

			continue
		}

		firstRewardItem := p.Player.FirstClaimReward[id]
		if firstRewardItem.IsClaim == 1 {
			continue
		}

		// 领取虚拟好有奖励
		resp, resCode := p.ClaimFirstReward(id)

		// 已领取虚拟奖励
		return resp, resCode
	}

	key := fmt.Sprintf("%v:1:%v", constant.InviteScoreKey, p.Player.UserName)
	claimScore, err := mdb.RDB.HGet(context.Background(), key, userName).Int()
	if err != nil {
		return nil, code.OK
	}

	p.Player.Item[models.ItemGold].Num += claimScore

	mdb.RDB.HDel(context.Background(), key, userName)

	reward := make([]data.ItemReward, 0)
	item := &data.ItemReward{
		ItemBaseType: 1,
		ItemID:       1,
		Amount:       claimScore,
	}
	reward = append(reward, *item)
	// 领取
	p.Player.Item.AddItem(reward)

	// 统计收益
	addItem := models.NewAddItem().Add(reward)
	p.itemStat(addItem)

	var resp param.ChangeData
	resp.AddItem = addItem
	resp.CurGold = p.Player.Item[1].Num
	return &resp, code.OK
}

// 领取首次奖励
func (p *actorPlayer) ClaimFirstReward(id int) (*param.ChangeData, int32) {
	if !p.isOnline {
		return nil, code.PlayerNotLogin
	}

	// 奖励已领取
	if p.Player.FirstClaimReward[id].IsClaim == 1 {
		return nil, code.HaveReceivedError
	}

	reward := p.Player.FirstClaimReward[id].Reward
	addItem := models.NewAddItem().Add(reward)
	// 领取
	p.Player.Item.AddItem(reward)
	p.Player.FirstClaimReward[id].IsClaim = 1
	p.Player.SetPlayerRewardLog(models.SourceFirst, id, reward, []data.ItemReward{}, nil)

	// 统计收益
	p.itemStat(addItem)

	var resp param.ChangeData
	resp.AddItem = addItem
	resp.CurGold = p.Player.Item[1].Num

	return &resp, code.OK
}

// 领取邀请节点奖励
func (p *actorPlayer) ClaimInviteNodeReward(id int) (*param.ChangeData, int32) {
	if !p.isOnline {
		mhayaLogger.Infof("[ClaimInviteNodeReward] PlayerNotLogin err node=%v", p.App().NodeId())
		return nil, code.PlayerNotLogin
	}

	// 奖励已领取
	if p.Player.InviteNodeReward[id].IsClaim == 1 {
		return nil, code.HaveReceivedError
	}

	// 邀请人数未达标
	if p.Player.InviteNodeReward[id].IsUnlock == 0 {
		return nil, code.NoYetUnlockedError
	}

	reward := p.Player.InviteNodeReward[id].Reward
	addItem := models.NewAddItem().Add(reward)
	// 领取
	p.Player.Item.AddItem(reward)
	p.Player.InviteNodeReward[id].IsClaim = 1
	p.Player.SetPlayerRewardLog(models.SourceInviteNode, id, reward, []data.ItemReward{}, nil)

	// 统计收益
	p.itemStat(addItem)

	icfg := data.InviteConfig.GetAll()
	var maxCondition int
	for _, value := range icfg {
		maxCondition += value.Condition
	}

	p.Player.ClaimInviteNum += icfg[id].Condition

	// 走到最后一个节点主动触发奖励重置
	mhayaLogger.Debugf("ClaimInviteNum = ", p.Player.ClaimInviteNum)
	mhayaLogger.Debugf("maxCondition = ", maxCondition)
	if p.Player.ClaimInviteNum >= maxCondition {
		p.Player.RefreshInviteNodeReward(icfg)

		// 保留刷新前的奖励历史记录
		var beforeNum int64
		for _, item := range p.Player.InviteNodeReward {
			beforeNum += int64(item.Condition)
		}
		key := fmt.Sprintf("%v:%v", constant.InviteNodeHistoryKey, p.Player.UserName)
		mhayaLogger.Debugf("走到最后一个节点主动触发奖励重置 id = ", id)
		mdb.RDB.IncrBy(context.Background(), key, beforeNum)
	}

	var resp param.ChangeData
	resp.AddItem = addItem
	resp.CurGold = p.Player.Item[1].Num

	return &resp, code.OK
}
