package baseCfg

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

const (
	CFG_BASE = "Base"
)

const (
	ENERGY_SHOP_MUL  = "energy_shop_mul"
	ENERGY_CFG       = "BaseEnergy"
	MAX_ENERGY_LEVEL = 999 // 最大能量等级上限
)

func init() {
	gamedata.InitCfg(CFG_BASE)
	gamedata.InitCfg(ENERGY_CFG)
}

func GetEnergyByMul(T int) float64 {
	data, err := gamedata.GetDataByKey(CFG_BASE, ENERGY_SHOP_MUL)
	if err != nil {
		log.Debug("GetEnergyByMul err:%v", err)
		return 0
	}

	valueData, ok := data["Value"]
	if !ok {
		log.Debug("GetEnergyByMul: Value field not found")
		return 0
	}

	d, ok := valueData.(map[string]interface{})
	if !ok || len(d) == 0 {
		log.Debug("GetEnergyByMul: Value is not a valid map")
		return 0
	}

	T = min(T, len(d))
	T1 := strconv.Itoa(T)
	if v, ok := d[T1]; ok {
		if floatVal, ok := v.(float64); ok {
			return floatVal
		}
		log.Debug("GetEnergyByMul: value is not float64, key=%s", T1)
	}
	return 0
}

func GetFriendReplyReward() []*item.Item {
	data, err := gamedata.GetDataByKey(CFG_BASE, "friend_reply")
	if err != nil {
		log.Debug("GetFriendReplyReward err:%v", err)
		return nil
	}
	return gamedata.GetItemList(data, "Value")
}

func GetEnergyByADNum() []*item.Item {
	data, err := gamedata.GetDataByKey(CFG_BASE, "ad_energy_gift")
	if err != nil {
		log.Debug("GetEnergyByADNum err:%v", err)
		return nil
	}
	return gamedata.GetItemList(data, "Value")
}

func GetMaxEnergyMul(Lv int, Energy int) int {
	Mul := 0
	for i := 1; i <= MAX_ENERGY_LEVEL; i++ {
		data, err := gamedata.GetDataByIntKey(ENERGY_CFG, i)
		if err != nil {
			break
		}
		UnlockLv := gamedata.GetIntValue(data, "UnlockLv")
		needEnergy := gamedata.GetIntValue(data, "NeedEnergy")
		if Lv < UnlockLv || Energy < needEnergy {
			break
		}
		Mul = i - 1
	}
	return Mul
}

func GetLimitEnergyMul(Lv int) int {
	data, err := gamedata.GetDataByIntKey(ENERGY_CFG, Lv+1)
	if err != nil {
		log.Debug("GetLimitEnergyMul err:%v, Lv=%d", err, Lv)
		return 0
	}
	return gamedata.GetIntValue(data, "Limit")
}
