package player

import (
	"blazing/common/data/xmlres"
	"blazing/modules/blazing/model"
	"math"
)

// calculateExperience 计算指定等级和种族值所需的经验值
// level: 当前等级
// baseValue: 种族值
func calculateExperience(level uint32, baseValue uint32) uint32 {
	// 计算 A 部分：向上取整(3.75 * a * (a + 1))
	partA := math.Ceil(3.75 * float64(level) * float64(level+1))

	// 计算 B 部分：向上取整(b * log(1 + a / 100))
	// 这里使用自然对数 math.Log，如果想换底数可以用换底公式
	partB := math.Log(1.0 + float64(level)/100.0)
	partB = float64(baseValue) * partB
	partB = math.Ceil(partB)

	// 总经验是两部分之和，并向上取整
	totalExp := math.Ceil(partA + partB)
	return uint32(totalExp)
}

// 主函数实现
// 添加经验
// 超NO 加成
func (p *Player) AddPetExp(pet *model.PetInfo, addExp uint32) {

	originalLevel := pet.Level
	for {
		basic := xmlres.PetMAP[int(pet.ID)]
		ba := basic.Atk +
			basic.Def +
			basic.SpAtk +
			basic.SpDef +
			basic.Spd +
			uint32(basic.HP)
		needExp := calculateExperience(pet.Level, ba)

		if addExp >= needExp {
			addExp -= needExp
			pet.Level++

			// 检查是否可以进化
			if basic.EvolvesTo != 0 || // 有明确的进化
				basic.EvolvingLv >= int(pet.Level) || // 有明确的进化等级
				basic.IsLarge == 0 { // 非最终形态

				pet.ID = uint32(basic.EvolvesTo)

			}

		} else {
			pet.NextLvExp = calculateExperience(pet.Level, ba)
			break
		}

	}

	pet.Exp = addExp

	pet.LvExp = pet.NextLvExp - pet.Exp
	// 处理进化逻辑

	//  重新计算面板
	if originalLevel != pet.Level {
		pet.CalculatePetPane()
	}

	// 发送经验更新消息
	//player.SendMessage(generatePetUpdateInfo(petEntity, originalExp+addExp-exp, addition))

	// 处理技能学习
	canLearnSkillList := model.LastFourElements(pet.GetLevelRangeCanLearningSkills(originalLevel, pet.Level)) //获取最后四个技能,如果不足,那就取全部技能

	for i := 0; i < 4; i++ {

		if pet.SkillList[i].ID == 0 {
			if len(canLearnSkillList) != 0 {
				skid := canLearnSkillList[len(canLearnSkillList)-1]
				pet.SkillList[i].ID = skid
				pet.SkillList[i].PP = uint32(xmlres.SkillMap[int(skid)].MaxPP)
				canLearnSkillList = canLearnSkillList[:len(canLearnSkillList)-1]
			}

		}

	}

	//todo 待实现
	// // 发送技能更新消息
	// updateSkillInfo := UpdateSkillInfo{
	// 	PetCatchTime:     petEntity.captureTime,
	// 	ActiveSkillNum:   activeSkillNum,
	// 	UnActiveSkillNum: unActiveSkillNum,
	// 	SkillArray:       canLearnSkillList,
	// }

	// player.SendMessage(UpdateSkillOutboundInfo{
	// 	InfoArray: []UpdateSkillInfo{updateSkillInfo},
	// })

	// return exp
}
