package player

import (
	"context"
	"fmt"
	jsoniter "github.com/json-iterator/go"
	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"
	"math"
	"strconv"
	"strings"
)

// loginStat 登录相关
func (p *actorPlayer) loginStat() {
	if mhayaTime.CreateFromTimestamp(p.Account.JoinTime).IsToday() {
		models.SetDailyRecordUserHash(p.Account.Platform, p.Account.Channel, p.Player.UserName, models.DailyRecordNewLogin)
	} else {
		models.SetDailyRecordUserHash(p.Account.Platform, p.Account.Channel, p.Player.UserName, models.DailyRecordOldLogin)
	}
}

// RollStat 投筛子相关
func (p *actorPlayer) rollStat() {
	if mhayaTime.CreateFromTimestamp(p.Account.JoinTime).IsToday() {
		models.SetDailyRecordUserHash(p.Account.Platform, p.Account.Channel, p.Player.UserName, models.DailyRecordNewActive)
	} else {
		models.SetDailyRecordUserHash(p.Account.Platform, p.Account.Channel, p.Player.UserName, models.DailyRecordOldActive)
	}
}

func (p *actorPlayer) itemStat(item map[int]*data.ItemReward) {

	for _, v := range item {
		if v.ItemID == models.ItemGold {
			// 设置个人排行榜
			models.SetRank(constant.RankSourceGold, p.Player.IsRobot, p.Player.UserName, v.Amount)
			// 设置国家排行榜
			models.SetCountryRank(p.Player.LoginIP, v)
			//models.SetDailyRecord(p.Account.Platform, p.Account.Channel, models.DailyRecordTotalPoints, v.Amount)
			// 记录周流水
			p.setItemWeekRecord(v)
			// 邀请裂变好友列表
			p.setInviteRatioRecord(v.Amount)
			// 设置邀请人的每日奖励（邀请裂变贡献）
			p.inviteScore(v.Amount)
			// 全服收益
			p.SetTotalIncome(int64(v.Amount))
		} else if v.ItemID == models.ItemU {
			models.SetDailyRecord(p.Account.Platform, p.Account.Channel, models.DailyRecordUProduced, v.Amount)
		}
	}
}

func (p *actorPlayer) cashOutStat(tp, num int) {
	if tp == 1 {
		models.SetDailyRecord(p.Account.Platform, p.Account.Channel, models.DailyRecordUCashout, num)
	} else if tp == 2 {
		models.SetDailyRecord(p.Account.Platform, p.Account.Channel, models.DailyRecordTonCashout, num)
	}

}

func (p *actorPlayer) playerStart() {
	models.SetTotalPlayerRecord(p.Account.Platform, p.Account.Channel, p.Player.UserName, p.Player.Level)
}

func (p *actorPlayer) inviteScore(num int) {
	scoreRatio, _ := data.DiscreteRuleConfig.Get(models.InviteRatio)
	split := strings.Split(scoreRatio.Condition, ",")
	ratio, _ := strconv.ParseFloat(split[0], 64)
	inviteScore := math.Floor(float64(num) * ratio)
	if p.Player.Pid == "" {
		return
	}
	key := fmt.Sprintf("%v:1:%v", constant.InviteScoreKey, p.Player.Pid)

	mdb.RDB.HIncrBy(context.Background(), key, p.Player.UserName, int64(inviteScore))
}

func (p *actorPlayer) setInviteRatioRecord(num int) {
	scoreRatio, _ := data.DiscreteRuleConfig.Get(models.InviteRatio)
	split := strings.Split(scoreRatio.Condition, ",")
	ratio, _ := strconv.ParseFloat(split[0], 64)
	inviteScore := math.Floor(float64(num) * ratio)
	if p.Player.Pid == "" {
		return
	}
	key := fmt.Sprintf("%v:1:%v", constant.InviteRatioRecordKey, p.Player.Pid)
	mdb.RDB.HIncrBy(context.Background(), key, p.Player.UserName, int64(inviteScore))
}

func (p *actorPlayer) setItemWeekRecord(item *data.ItemReward) {
	now := mhayaTime.Now().Unix()
	key := models.GetWeekRecordKey(p.Player.UserName, item.ItemBaseType, item.ItemID)
	record := param.ItemRecord{now, int64(item.Amount)}
	// 控制容量
	d, _ := jsoniter.Marshal(&record)
	PushWithCapacity(key, string(d), 500)
}

func (p *actorPlayer) itemWeekRecord(req *param.ItemRecordReq) (*param.ItemRecordResp, int32) {
	if !p.isOnline {
		return nil, code.PlayerNotLogin
	}
	key := models.GetWeekRecordKey(p.Player.UserName, req.ItemBaseType, req.ItemId)
	result, err := mdb.RDB.LRange(context.Background(), key, 0, -1).Result()
	if err != nil {
		return nil, code.Error
	}

	itemRecordSlice := make([]param.ItemRecord, 0)
	for _, record := range result {
		var info param.ItemRecord
		jsoniter.Unmarshal([]byte(record), &info)
		itemRecordSlice = append(itemRecordSlice, info)
	}

	totalIcorme, _ := mdb.RDB.Get(context.Background(), constant.TotalIncomeKey).Int64()
	resp := param.ItemRecordResp{TotalIncome: totalIcorme, ItemRecords: itemRecordSlice}
	return &resp, code.OK
}

func (p *actorPlayer) SetTotalIncome(amount int64) {
	key := constant.TotalIncomeKey
	mdb.RDB.IncrBy(context.Background(), key, amount)
}

// 向列表中添加元素并控制其最大长度
func PushWithCapacity(key string, value string, capacity int) error {
	// 使用 LPUSH 添加新元素
	err := mdb.RDB.LPush(context.Background(), key, value).Err()
	if err != nil {
		mhayaLogger.Warnf("Login Set PushWithCapacity RoleId error:%v", err)
		return err
	}

	// 使用 LTRIM 修剪列表，使其保持在指定的最大长度
	err = mdb.RDB.LTrim(context.Background(), key, 0, int64(capacity-1)).Err()
	if err != nil {
		return err
	}

	return nil
}
