package endless

import (
	"math"
	endlessCfg "server/conf/endless"
	"server/game/mod/item"
	Util "server/game_util"
)

// 初始化奖励
func InitReward(Energy float64, Lv int) []*item.Item {
	numRand := map[int]int{1: 30, 2: 60, 3: 10}
	Num := Util.RandMap(numRand)
	PerEnergy := endlessCfg.GetPerEnergy(item.ITEM_ENERGY_ID)
	getNum := func(energy, preEnergy float64) int {
		num := int(energy / preEnergy)
		num = int(math.Round(float64(num)/5.0) * 5)
		return max(num, 5) // 最少5个能量
	}
	if Num == 1 {
		ItemNum := getNum(Energy, PerEnergy)
		return []*item.Item{item.NewItem(item.ITEM_ENERGY_ID, ItemNum)}
	}

	if Num == 2 {
		ItemId := endlessCfg.GetItemId(Energy, 0, Lv)
		if len(ItemId) == 0 {
			return []*item.Item{item.NewItem(item.ITEM_ENERGY_ID, getNum(Energy, PerEnergy))}
		}
		RandItem := Util.RandSlice(ItemId)
		ItemEnergy := endlessCfg.GetEnergyByItemId(RandItem)
		LastEnergy := Energy - ItemEnergy
		ItemNum := getNum(LastEnergy, PerEnergy)
		return []*item.Item{item.NewItem(item.ITEM_ENERGY_ID, ItemNum), item.NewItem(RandItem, 1)}
	}
	if Num == 3 {
		ItemId := endlessCfg.GetItemId(Energy, 0, Lv)
		if len(ItemId) == 0 {
			return []*item.Item{item.NewItem(item.ITEM_ENERGY_ID, getNum(Energy, PerEnergy))}
		}
		RandItem1 := Util.RandSlice(ItemId)
		Type := endlessCfg.GetType(RandItem1)
		ItemEnergy := endlessCfg.GetEnergyByItemId(RandItem1)
		LastEnergy := Energy - ItemEnergy
		ItemId = endlessCfg.GetItemId(LastEnergy, Type, Lv)
		if len(ItemId) == 0 {
			ItemNum := getNum(LastEnergy, PerEnergy)
			return []*item.Item{item.NewItem(item.ITEM_ENERGY_ID, ItemNum), item.NewItem(RandItem1, 1)}
		}
		RandItem2 := Util.RandSlice(ItemId)
		ItemEnergy = endlessCfg.GetEnergyByItemId(RandItem2)
		LastEnergy = LastEnergy - ItemEnergy
		ItemNum := getNum(LastEnergy, PerEnergy)
		return []*item.Item{item.NewItem(item.ITEM_ENERGY_ID, ItemNum), item.NewItem(RandItem1, 1), item.NewItem(RandItem2, 1)}
	}

	return nil
}

// 初始化档次奖励
func initGrade(Money float64, Auto, Lv int) (map[int]*Endless, int) {
	Energy := endlessCfg.GetEnergy(Money)
	Per := []float64{0.5, 0.3, 0.2, 0.1}
	result := make(map[int]*Endless)
	for i := 1; i < 5; i++ {
		Type := ENDLESS_TYPE_FREE
		Charge := 0
		if i == 1 {
			if Money > 0 {
				Type = ENDLESS_TYPE_CHARGE
				Charge = endlessCfg.GetChargeId(Money)
			} else {
				Type = ENDLESS_TYPE_AD
			}

		}
		result[Auto] = &Endless{
			ChargeId: Charge,
			Type:     Type,
			Items:    InitReward(Energy*Per[i-1], Lv),
		}
		Auto++
	}
	return result, Auto
}
