package champshipCfg

import (
	"server/game/mod/item"
	GoUtil "server/game_util"
	"server/gamedata"
	"server/pkg/github.com/name5566/leaf/log"
)

const (
	CFG_CHAMPSHIP_SCORE   = "ChampshipScore"
	CFG_CHAMPSHIP_RANK    = "ChampshipRank"
	CFG_CHAMPSHIP_JACKPOT = "ChampshipJackpot"
	CFG_CHAMPSHIP_GROUP   = "ChampshipGroup"
)

func init() {
	gamedata.InitCfg(CFG_CHAMPSHIP_SCORE)
	gamedata.InitCfg(CFG_CHAMPSHIP_RANK)
	gamedata.InitCfg(CFG_CHAMPSHIP_JACKPOT)
	gamedata.InitCfg(CFG_CHAMPSHIP_GROUP)
}

func GetGroupId(N int) int {
	data, err := gamedata.GetData(CFG_CHAMPSHIP_GROUP)
	if err != nil {
		log.Debug("GetGroupId err:%v, N=%d", err, N)
		return 0
	}
	for k, v := range data {
		if N >= gamedata.GetIntValue(v, "Min") && N <= gamedata.GetIntValue(v, "Max") {
			return GoUtil.Int(k)
		}
	}
	return 0
}

func GetChessScore(ChessLv int) int {
	data, err := gamedata.GetDataByIntKey(CFG_CHAMPSHIP_SCORE, ChessLv)
	if err != nil {
		log.Debug("GetChessScore err:%v, ChessLv=%d", err, ChessLv)
		return 0
	}
	return gamedata.GetIntValue(data, "Score")
}

func GetReward(Reward, Score int) (int, []*item.Item) {
	data, err := gamedata.GetData(CFG_CHAMPSHIP_JACKPOT)
	if err != nil {
		log.Debug("GetReward err:%v, Reward=%d, Score=%d", err, Reward, Score)
		return Reward, nil
	}
	r := make([]*item.Item, 0, len(data))
	NewReward := Reward
	for k, v := range data {
		Id := GoUtil.Int(k)
		if Reward >= Id {
			continue
		}
		if Score >= gamedata.GetIntValue(v, "Total") {
			Items := item.ParseItem(gamedata.GetValue(v, "Items"))
			r = item.Merge(r, Items)
			NewReward = max(NewReward, Id)
		}
	}
	return NewReward, r
}

func GetRewardItems(Reward int) ([]*item.Item, int) {
	data, err := gamedata.GetDataByIntKey(CFG_CHAMPSHIP_JACKPOT, Reward)
	if err != nil {
		log.Debug("GetRewardItems err:%v, Reward=%d", err, Reward)
		return nil, 0
	}
	return gamedata.GetItemList(data, "Items"), gamedata.GetIntValue(data, "Score")
}

func GetRewardTotalScore(Reward int) int {
	data, err := gamedata.GetDataByIntKey(CFG_CHAMPSHIP_JACKPOT, Reward)
	if err != nil {
		log.Debug("GetRewardTotalScore err:%v, Reward=%d", err, Reward)
		return 0
	}
	return gamedata.GetIntValue(data, "Total")
}

func GetRankReward(Rank int) []*item.Item {
	data, err := gamedata.GetData(CFG_CHAMPSHIP_RANK)
	if err != nil {
		log.Debug("GetRankReward err:%v, Rank=%d", err, Rank)
		return nil
	}
	for _, v := range data {
		if Rank >= gamedata.GetIntValue(v, "Min") && Rank <= gamedata.GetIntValue(v, "Max") {
			return gamedata.GetItemList(v, "Items")
		}
	}
	return nil
}

func GetMaxRewardId() int {
	data, err := gamedata.GetData(CFG_CHAMPSHIP_JACKPOT)
	if err != nil {
		log.Debug("GetMaxRewardId err:%v", err)
		return 0
	}
	MaxId := 0
	for k := range data {
		Id := GoUtil.Int(k)
		if Id > MaxId {
			MaxId = Id
		}
	}
	return MaxId
}
