package fight

import (
	"blazing/common/data/xmlres"
	"blazing/logic/service/common"
	"blazing/logic/service/fight/info"
	"blazing/logic/service/player"
	"math"

	"github.com/gogf/gf/v2/util/gconv"
	"github.com/jinzhu/copier"
	"github.com/panjf2000/ants/v2"
)

// 玩家逃跑
func (f *FightC) Escape(c common.PlayerI) {
	ret := &EscapeAction{
		BaseAction: NewBaseAction(c.GetInfo().UserID),
		Reason: info.FightOverInfo{

			Reason: uint32(info.BattleOverReason.PlayerEscape),
		},
	}

	f.actionChan <- ret
}

// 玩家掉线
func (f *FightC) Offline(c common.PlayerI) {
	ret := &PlayerOfflineAction{
		BaseAction: NewBaseAction(c.GetInfo().UserID),
		Reason: info.FightOverInfo{

			Reason: uint32(info.BattleOverReason.PlayerOffline),
		},
	}

	f.actionChan <- ret
}

// 切换精灵  主动和被驱逐
func (f *FightC) ChangePet(c common.PlayerI, id uint32) {
	ret := &ActiveSwitchAction{
		BaseAction: NewBaseAction(c.GetInfo().UserID),
	}
	f.Switch = append(f.Switch, ret)
	if c.GetInfo().UserID == f.ownerID {

		f.GetInputByPlayer(c, false).CurrentPet, ret.Reason = f.GetInputByPlayer(c, false).GetPet(id)
	} else {

		f.GetInputByPlayer(c, true).CurrentPet, ret.Reason = f.GetInputByPlayer(c, true).GetPet(id)
	}

	f.actionChan <- ret
}

// 玩家使用技能
func (f *FightC) UseSkill(c common.PlayerI, id int32) {

	if id == 0 {
		f.actionChan <- &SystemGiveUpAction{BaseAction: NewBaseAction(c.GetInfo().UserID)}
		return
	}
	ret := &SelectSkillAction{
		PlayerID: c.GetInfo().UserID,
	}
	if c.GetInfo().UserID == f.ownerID {
		ret.PetInfo = f.GetInputByPlayer(c, false).CurrentPet
	} else {
		ret.PetInfo = f.GetInputByPlayer(c, true).CurrentPet
	}

	for _, v := range ret.PetInfo.Skills {

		if v != nil && v.ID == int(id) {
			ret.Skill = v
		}

	}
	f.actionChan <- ret
}

// 玩家使用技能
func (f *FightC) Capture(c common.PlayerI, id uint32) {

	f.actionChan <- &UseItemAction{BaseAction: NewBaseAction(c.GetInfo().UserID), ItemID: id}
}

// 战斗准备
func (f *FightC) ReadyFight(c common.PlayerI) {
	rett := info.FightStartOutboundInfo{}

	copier.Copy(&rett.Info1, &f.Info.OurPetList[0]) // 复制自己的信息
	copier.Copy(&rett.Info2, &f.Info.OpponentPetList[0])
	rett.Info1.UserID = f.Info.OurInfo.UserID //
	rett.Info2.UserID = f.Info.OpponentInfo.UserID

	rrsult := func() { //传回函数

		f.Our.Player.SendReadyToFightInfo(rett)
		f.Opp.Player.SendReadyToFightInfo(rett)
	}

	switch f.Info.FightId {
	case 1: // 1v1

		f.GetInputByPlayer(c, false).Finished = true
		if f.GetInputByPlayer(c, true).Finished {
			rrsult()
		}
	case 2: // 6v6

		f.GetInputByPlayer(c, false).Finished = true
		if f.GetInputByPlayer(c, true).Finished {
			rrsult()
		}
	case 3: // 野怪战斗

		//判断捕捉率大于0
		if gconv.Int(xmlres.PetMAP[int(f.Info.OpponentPetList[0].ID)].CatchRate) > 0 {
			rett.Info2.Catchable = 1
			t, _ := f.Opp.Player.(*player.AI_player)
			t.CanCapture = true

		}

		rrsult()
	}
}

var Fightpool *ants.Pool

func init() {
	Fightpool, _ = ants.NewPool(math.MaxInt32)
	//defer p.Release()
}
