local this = class("kiBoDuelManager", G_EventManagerBase)
local trainTaskTpl = L_GameTpl:getTrainTaskTpl()
local kiBoDuelTpl = L_GameTpl:getKiboDuelTpl()
this.event = {
  kiBoSummonStart = "kiBoSummonStart",
  kiBoSummonConfirm = "kiBoSummonConfirm",
  kiBoSummonCancel = "kiBoSummonCancel",
  refreshKiBoDuelCost = "refreshKiBoDuelCost",
  refreshKiBoHealing = "refreshKiBoHealing",
  kiBoDuelEnd = "kiBoDuelEnd",
  kiBoDuelEntityCreated = "kiBoDuelEntityCreated",
  refreshTowerHp = "refreshTowerHp",
  restartKiBoDuel = "restartKiBoDuel",
  refreshSummonField = "refreshSummonField",
  startRapidState = "startRapidState",
  summonStatusChange = "summonStatusChange",
  skillInfoSwicth = "skillInfoSwicth",
  kiBoSummoned = "kiBoSummoned",
  refreshKiboList = "refreshKiboList",
  refreshDuelResult = "refreshDuelResult",
  changeSkillStatus = "changeSkillStatus",
  taskCompeleted = "taskCompeleted"
}
this.summonStausEnum = {inSummon = 1, normal = 2}
this.skillStausEnum = {waitConfirm = 1, normal = 2}
local trialPetTpl = L_GameTpl:getTrialPetTpl()

function this:ctor()
  this.super.ctor(self)
  self.formationQueue = L_Struct.getQueue()
  self.isRapid = false
  self.playerKiBo = {}
  self.enemyKiBo = {}
  self.isShowStatistics = nil
end

function this:startDuel()
  self.entityDeadHandle = self.entityDeadHandle or handler(self, self.onEvent_EntityDead)
  C_EntityManager.RemoveOnEntityDyingHandler(self.entityDeadHandle)
  C_EntityManager.AddOnEntityDyingHandler(self.entityDeadHandle)
  self.onRobotKiBoSummonHandle = self.onRobotKiBoSummonHandle or handler(self, self.onRobotKiBoSummon)
  C_ExternalManager.AddEvent(C_EExternalEventType.RobotKiBoSummon, self.onRobotKiBoSummonHandle)
  self.onKiBoKillHandle = self.onKiBoKillHandle or handler(self, self.onKiBoKill)
  C_RecordManager.AddKillEvent(self.onKiBoKillHandle)
  self.onTargetCompeletedHandle = self.onTargetCompeletedHandle or handler(self, self.onTargetCompeleted)
  C_ExternalManager.AddEvent(C_EExternalEventType.CompleteGuide, self.onTargetCompeletedHandle)
end

function this:exitDuel()
  if self.entityDeadHandle ~= nil then
    C_EntityManager.RemoveOnEntityDyingHandler(self.entityDeadHandle)
    self.entityDeadHandle = nil
  end
  if self.onRobotKiBoSummonHandle ~= nil then
    C_ExternalManager.RemoveEvent(C_EExternalEventType.RobotKiBoSummon, self.onRobotKiBoSummonHandle)
    self.onRobotKiBoSummonHandle = nil
  end
  if self.onKiBoKillHandle ~= nil then
    C_RecordManager.RemoveKillEvent(self.onKiBoKillHandle)
    self.onKiBoKillHandle = nil
  end
  if self.onTargetCompeletedHandle ~= nil then
    C_ExternalManager.RemoveEvent(C_EExternalEventType.CompleteGuide, self.onTargetCompeletedHandle)
    self.onTargetCompeletedHandle = nil
  end
  self.isRapid = false
  self.playerKiBo = {}
  self.enemyKiBo = {}
  self:changeSkillStatus(nil, self.skillStausEnum.normal)
end

function this:onKiBoKill(attackerRecord, executorRecord)
  if attackerRecord == nil or executorRecord == nil then
    return
  end
  if math.isEmpty(attackerRecord.configId) or math.isEmpty(executorRecord.configId) then
    return
  end
  local duelResult = {isWin = true}
  local playerPet = attackerRecord
  local enemyPet = executorRecord
  if executorRecord.campType == C_ECampType.Blue then
    playerPet = executorRecord
    enemyPet = attackerRecord
  end
  duelResult.enemy = {
    petConfigId = enemyPet.configId,
    entityId = enemyPet.entityId,
    guid = enemyPet.guid,
    notRecord = enemyPet.notRecord
  }
  duelResult.player = {
    petConfigId = playerPet.configId,
    entityId = playerPet.entityId,
    guid = playerPet.guid,
    notRecord = playerPet.notRecord
  }
  if playerPet.dead then
    duelResult.isWin = false
  end
  self:sendEvent(self.event.refreshDuelResult, duelResult)
end

function this:onRobotKiBoSummon(data)
  if data == nil then
    return
  end
  local entityId = data.int1Arg
  local petConfigId = data.int2Arg
  self.enemyKiBo = {}
  local kibos = C_EntityManager.GetKiBoList(C_EEntityType.KiBo)
  for i = 0, kibos.Count - 1 do
    local entity = kibos[i]
    local campType = entity.data.campType
    if campType == C_ECampType.Red then
      table.insert(self.enemyKiBo, {
        petConfigId = entity.data.configId,
        entityId = entity.data.entityId
      })
    end
  end
  self:sendEvent(self.event.kiBoSummoned, {petConfigId = petConfigId, isPlayer = false})
  self:sendEvent(self.event.refreshKiboList, {
    isAdd = true,
    entityId = entityId,
    isPlayer = false,
    isRefresh = false
  })
end

function this:onEvent_EntityDead(entity)
  if entity == nil then
    return
  end
  local entityType = entity.data.entityType
  if entityType == C_EEntityType.KiBo then
    if entity.data.campType == C_ECampType.Red then
      for k, v in ipairs(self.enemyKiBo) do
        if v.entityId == entity.data.entityId then
          table.remove(self.enemyKiBo, k)
          self:sendEvent(self.event.refreshKiboList, {
            isAdd = false,
            entityId = v.entityId,
            isPlayer = false
          })
          break
        end
      end
    end
    if entity.data.campType == C_ECampType.Blue then
      for k, v in ipairs(self.playerKiBo) do
        if v.entityId == entity.data.entityId then
          table.remove(self.playerKiBo, k)
          self:sendEvent(self.event.refreshKiboList, {
            isAdd = false,
            entityId = v.entityId,
            isPlayer = true
          })
          break
        end
      end
    end
  end
end

function this:getKiBoList()
  return table.clone(self.playerKiBo), table.clone(self.enemyKiBo)
end

function this:handleKiBoSummoned(petConfigId, guid, isPlayer)
  self:sendEvent(self.event.kiBoSummoned, {
    guid = guid,
    petConfigId = petConfigId,
    isPlayer = isPlayer
  })
end

function this:playerSummonKiBo(petInfo)
  if petInfo == nil then
    return
  end
  local petId
  if petInfo.is_trial then
    local trialId = petInfo.id
    local trialTpl = trialPetTpl:getTplById(trialId)
    petId = trialPetTpl:getTrialPet(trialTpl)
  else
    local id = petInfo.id
    local petData = L_PetStore:getPetItem(id)
    petId = petData.id
  end
  FrameScheduler.add(function()
    local duelData = C_KiBoDuelLuaWrapper.GetDuelData()
    if duelData ~= nil then
      local onBattlePets = duelData.guid2EntityIdDict
      for id, entityId in pairs(onBattlePets) do
        if id == petInfo.guid then
          local isRefresh = false
          for k, v in pairs(self.playerKiBo) do
            if v.guid == id then
              v.entityId = entityId
              v.petConfigId = petId
              isRefresh = true
              break
            end
          end
          if not isRefresh then
            local data = {
              guid = petInfo.guid,
              petConfigId = petId,
              entityId = entityId
            }
            table.insert(self.playerKiBo, data)
          end
          self:sendEvent(self.event.refreshKiboList, {
            isAdd = true,
            entityId = entityId,
            isPlayer = true,
            isRefresh = isRefresh
          })
          self:handleKiBoSummoned(petId, petInfo.guid, true)
        end
      end
    end
  end, 2)
end

function this:handSwitchSkillInfo(infoType)
  self:sendEvent(self.event.skillInfoSwicth, infoType)
end

function this:setIsPlayAnimation(isPlay)
  self.isPlayingAnimation = isPlay
end

function this:getIsPlayAnimation()
  return self.isPlayingAnimation
end

function this:handleKiBoSummonStart(index)
  if not C_KiBoDuelSceneManager.CanSummon() then
    return
  end
  if self.formationQueue:getLength() <= 0 then
    return
  end
  if self.isPlayingAnimation then
    return
  end
  self:sendEvent(self.event.kiBoSummonStart, index)
end

function this:handleKiBoSummonConfirm()
  if L_CameraManager:getShowCursor() then
    return
  end
  if self.summonStausEnum.inSummon ~= self.summonStatus then
    return
  end
  if not self.isInSummonFiled then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_kibo_duel_in_battle_06"))
    return
  end
  if self.isPlayingAnimation then
    return
  end
  C_KiBoDuelLuaWrapper.KiBoSummonConfirm()
  self:setSummonStatus(self.summonStausEnum.normal)
  self:sendEvent(self.event.kiBoSummonConfirm)
end

function this:handleKiBoSummonCancel()
  if self.summonStausEnum.inSummon ~= self.summonStatus then
    L_PlayerManager:fireEvade()
    return
  end
  C_KiBoDuelLuaWrapper.KiBoSummonCancel()
  self:setSummonStatus(self.summonStausEnum.normal)
  self:sendEvent(self.event.kiBoSummonCancel)
end

function this:getSummonStatus()
  return self.summonStatus
end

function this:setSummonStatus(status)
  local isChanged = false
  if self.summonStatus ~= status then
    isChanged = true
  end
  self.summonStatus = status
  if isChanged then
    self:sendEvent(self.event.summonStatusChange)
  end
end

function this:isInSummon()
  return self.summonStatus == self.summonStausEnum.inSummon
end

function this:getCurPetDuelFormationPetGuids()
  local pets = L_PetDuelStore:getCurPetDuelFormationPetGuids()
  local duelId = L_PetDuelStore:getCurChallengeLevelId()
  if self:isTrialDuel(duelId) then
    local tpl = kiBoDuelTpl:getTplById(duelId)
    local trialPets = kiBoDuelTpl:getKiboList(tpl)
    pets = {}
    for _, v in ipairs(trialPets) do
      table.insert(pets, {is_trial = true, id = v})
    end
  elseif kiBoDuelTpl:isKiboLock(duelId) then
    pets = L_PetDuelStore:getPetDuelFormationPetGuids(L_Const.kiBoDuelBlockSlot)
  end
  return pets
end

function this:getFormationGuid()
  local data = {}
  local pets = self:getCurPetDuelFormationPetGuids()
  local duelId = L_PetDuelStore:getCurChallengeLevelId()
  if self:isTrialDuel(duelId) then
    local tpl = kiBoDuelTpl:getTplById(duelId)
    local trialPets = kiBoDuelTpl:getKiboList(tpl)
    pets = {}
    for _, v in ipairs(trialPets) do
      table.insert(pets, {is_trial = true, id = v})
    end
  end
  for k, v in ipairs(pets) do
    if v.id and v.id > 0 then
      table.insert(data, {
        slotId = k,
        guid = L_PetDuelStore:getTrialPetGuid(v.id),
        is_trial = v.is_trial,
        id = v.id
      })
    end
  end
  if self.formationQueue ~= nil then
    self.formationQueue:clear()
  else
    self.formationQueue = L_Struct.getQueue()
  end
  self:shuffle(data)
  data = self:dealHandList(data)
  for _, v in ipairs(data) do
    self.formationQueue:enQueue(v)
  end
  return self.formationQueue
end

function this:dealHandList(data)
  local duelId = L_PetDuelStore:getCurChallengeLevelId()
  local tpl = kiBoDuelTpl:getTplById(duelId)
  local handList = kiBoDuelTpl:getHandList(tpl)
  if table.isEmpty(handList) then
    return data
  end
  local res = {}
  for _, id in ipairs(handList) do
    for k, pet in ipairs(data) do
      local petId
      if pet.is_trial then
        local trialId = pet.id
        petId = trialPetTpl:getTrialPet(trialPetTpl:getTplById(trialId))
      else
        local petData = L_PetStore:getPetItem(pet.guid)
        if petData then
          petId = petData.id
        end
      end
      if petId == id then
        table.insert(res, table.remove(data, k))
        break
      end
    end
  end
  for _, v in ipairs(data) do
    table.insert(res, v)
  end
  return res
end

function this:getSlotIdByGuid(guid)
  local pets = self:getCurPetDuelFormationPetGuids()
  for k, v in ipairs(pets) do
    if v.is_trial and L_PetDuelStore:getTrialPetGuid(v.id) == guid then
      return k
    end
    if v.id == guid then
      return k
    end
  end
end

function this:getPetGuids()
  local data = {}
  local pets = self:getCurPetDuelFormationPetGuids()
  for k, v in ipairs(pets) do
    if v.id and v.id > 0 then
      table.insert(data, {
        slotId = k,
        guid = L_PetDuelStore:getTrialPetGuid(v.id),
        is_trial = v.is_trial,
        id = v.id
      })
    end
  end
  return data
end

function this:shuffle(t)
  if type(t) ~= "table" then
    errorf("Argument must be a table.", 2)
  end
  local len = #t
  for i = len, 1, -1 do
    local j = math.random(1, i)
    t[i], t[j] = t[j], t[i]
  end
end

function this:updateDuelCost(arg)
  self:sendEvent(self.event.refreshKiBoDuelCost, arg.curCost)
end

function this:updatePetHealingIcon()
  self:sendEvent(self.event.refreshKiBoHealing)
end

function this:onCreateKiBoPVEFieldEntityEnd(entity)
  self.pveFieldEntity = entity
  if self.pveFieldEntity and self.pveFieldEntity.data then
    self.bluePlayer = self.pveFieldEntity.data.bluePlayer
  end
  self:registerC2lEventHandler(true)
  self:sendEvent(self.event.kiBoDuelEntityCreated)
end

function this:restartKiBoDuel()
  self.playerKiBo = {}
  self.enemyKiBo = {}
  self.isPlayingAnimation = false
  self:setSummonStatus(self.summonStausEnum.normal)
  self:sendEvent(self.event.restartKiBoDuel)
end

function this:onUnloadKiBoDuel()
  self:registerC2lEventHandler()
  self.pveFieldEntity = nil
  self.bluePlayer = nil
  self.blueTower = nil
  self.redTower = nil
  self.summonStatus = self.summonStausEnum.normal
end

function this:registerC2lEventHandler(isAdd)
  self.costHandler = self.costHandler or handler(self, self.costHandle)
  self.blueTowerHpHandler = self.blueTowerHpHandler or handler(self, self.blueTowerHpHandle)
  self.redTowerHpHandler = self.redTowerHpHandler or handler(self, self.redTowerHpHandle)
  if self.pveFieldEntity and self.pveFieldEntity.data then
    local data = self.pveFieldEntity.data
    if data.bluePlayer then
      data.bluePlayer.handler:RemoveC2lEventHandler(self.costHandler)
      if isAdd then
        data.bluePlayer.handler:AddC2lEventHandler(self.costHandler)
      end
    end
    if data.blueBaseTower then
      data.blueBaseTower.handler.hpChangeEvent:Remove(self.blueTowerHpHandler)
      if isAdd then
        data.blueBaseTower.handler.hpChangeEvent:Add(self.blueTowerHpHandler)
      end
      self.blueTower = data.blueBaseTower
    end
    if data.redBaseTower then
      data.redBaseTower.handler.hpChangeEvent:Remove(self.redTowerHpHandler)
      if isAdd then
        data.redBaseTower.handler.hpChangeEvent:Add(self.redTowerHpHandler)
      end
      self.redTower = data.redBaseTower
    end
  end
end

function this:blueTowerHpHandle(currentHp)
  self:sendEvent(self.event.refreshTowerHp, {hp = currentHp, isBlue = true})
end

function this:redTowerHpHandle(currentHp)
  self:sendEvent(self.event.refreshTowerHp, {hp = currentHp, isBlue = false})
end

function this:costHandle(type, args)
  if type == C_EC2LType.KiBoVersusCostChange then
    self:updateDuelCost(args)
  end
end

function this:checkIsPetOnBattle(guid)
  if not self.bluePlayer then
    return false
  end
  local duelData = C_KiBoDuelLuaWrapper.GetDuelData()
  if not duelData then
    return false
  end
  local onBattlePets = duelData.guid2EntityIdDict
  for id, _ in pairs(onBattlePets) do
    if id == guid then
      return true
    end
  end
  return false
end

function this:dealKiBoDuelEnd(result)
  self:sendEvent(self.event.kiBoDuelEnd, result)
end

function this:quitKiBoDuel()
  if self.pveFieldEntity and self.pveFieldEntity:IsValid() then
    self.pveFieldEntity:DoForceOut()
  end
end

function this:getDuelTime()
  if self.pveFieldEntity then
    return self.pveFieldEntity.data.battleTimeStamp
  end
  return 0
end

function this:getTowerMaxHp()
  if self.blueTower and self.redTower then
    local blueHp = self.blueTower.data.aliveProperty.maxHp:ToFloat()
    local redHp = self.redTower.data.aliveProperty.maxHp:ToFloat()
    return blueHp, redHp
  end
  return 0, 0
end

function this:getRedPlayerControllingEntity()
  if self.pveFieldEntity and self.pveFieldEntity.data then
    local redPlayer = self.pveFieldEntity.data.redPlayer
    if redPlayer and redPlayer.data then
      return redPlayer.data.controllingEntity
    end
  end
  return nil
end

function this:refreshKiBoSummonFieldStatus(isIn)
  self.isInSummonFiled = isIn
  self:sendEvent(self.event.refreshSummonField)
end

function this:getSummonFieldStatus()
  return self.isInSummonFiled
end

function this:openTestKiBoDuel(levelId)
  local pets = {}
  local cfg = L_GameTpl:getKiboDuelTpl():getTplById(levelId)
  local kiboList = L_GameTpl:getKiboDuelTpl():getKiboList(cfg)
  local minimun = L_GameTpl:getKiboDuelTpl():getMinimumKibo(cfg)
  local levelType = L_GameTpl:getKiboDuelTpl():getLevelType(cfg)
  local count = 0
  if levelType == L_Const.kiBoDuelLevelType.mix or levelType == L_Const.kiBoDuelLevelType.system then
    for _, petId in ipairs(kiboList) do
      table.insert(pets, {id = petId, is_trial = true})
      count = count + 1
    end
  end
  if levelType == L_Const.kiBoDuelLevelType.mix or levelType == L_Const.kiBoDuelLevelType.player then
    local petItems = L_PetStore:getPetList()
    for _, v in pairs(petItems) do
      if minimun <= count then
        break
      end
      table.insert(pets, {
        id = v.guid,
        is_trial = false
      })
      count = count + 1
    end
  end
  local data = {
    slot = 1,
    pet_guids = pets,
    hero = 199000,
    hero_skills = L_PetDuelStore:getDefaultSkillInfos(levelId)
  }
  L_Net:sendMessage(MsgGenCode.CSProtoKiboDuelSetCurGroup, {u32 = 1}, function(rspData, errorCode)
    L_Net:sendMessage(MsgGenCode.CSProtoKiboDuelGroupInfoChange, data, function(rspData, errorCode)
      L_PetDuelStore:req_CSProtoKiboDuelStart(levelId)
    end)
  end)
end

function this:getCostData()
  if L_CommonUtil.isValid(self.bluePlayer) and L_CommonUtil.isValid(self.bluePlayer.data) then
    return self.bluePlayer.data.kiBoCostRecoverPer, self.bluePlayer.data.kiBoCostRecoverState
  end
  return 0, L_Const.kiBoDuelCostStatus.None
end

function this:setRapidState(isRapid)
  if isRapid == self.isRapid then
    return
  end
  self.isRapid = isRapid
  self:sendEvent(self.event.startRapidState, self.isRapid)
end

function this:getRapidState()
  return self.isRapid
end

function this:getPetStatistics(type, count)
  local data = C_RecordManager.GetEntityRecordL(type, count)
  local enemyData = {}
  local playerData = {}
  for i = 0, data.Count - 1 do
    local petInfo = data[i]
    if petInfo.entityType ~= C_EEntityType.DefenseTower and petInfo.entityType ~= C_EEntityType.BaseTower then
      if petInfo.campType == C_ECampType.Red then
        table.insert(enemyData, {
          entityType = petInfo.entityType,
          level = petInfo.level,
          petConfigId = petInfo.configId,
          guid = petInfo.guid,
          damgeValue = petInfo.recordDamageValue,
          damgeTakenValue = petInfo.recordReceiveDamageValue,
          healingValue = petInfo.recordHealValue
        })
      end
      if petInfo.campType == C_ECampType.Blue then
        table.insert(playerData, {
          entityType = petInfo.entityType,
          level = petInfo.level,
          petConfigId = petInfo.configId,
          guid = petInfo.guid,
          damgeValue = petInfo.recordDamageValue,
          damgeTakenValue = petInfo.recordReceiveDamageValue,
          healingValue = petInfo.recordHealValue
        })
      end
    end
  end
  self:sortStatisticsData(enemyData)
  self:sortStatisticsData(playerData)
  return {enemyData = enemyData, playerData = playerData}
end

function this:sortStatisticsData(data)
  table.sort(data, function(a, b)
    if a.damgeValue ~= b.damgeValue then
      return a.damgeValue > b.damgeValue
    elseif a.damgeTakenValue ~= b.damgeTakenValue then
      return a.damgeTakenValue > b.damgeTakenValue
    else
      return a.healingValue > b.healingValue
    end
  end)
end

function this:getPlayerPetLevel(guid)
  if guid ~= nil then
    local petItem = L_PetStore:getPetItem(guid)
    if petItem ~= nil then
      return petItem.lv
    end
    local pets = self:getCurPetDuelFormationPetGuids()
    for _, v in pairs(pets) do
      if guid == L_PetDuelStore:getTrialPetGuid(v.id) and v.is_trial then
        local trialTpl = trialPetTpl:getTplById(v.id)
        return trialPetTpl:getTrialPetLevel(trialTpl)
      end
    end
  end
  return 1
end

function this:changeSkillStatus(slot, status)
  if not C_KiBoDuelSceneManager.CanSkill() then
    return
  end
  if slot ~= nil then
    local controlEntity = L_PlayerManager:getMainControlEntity()
    if not controlEntity then
      return
    end
    local skillProperty = controlEntity:getCsEntity().data.skillProperty
    local skill = skillProperty:GetSkillBySlot(slot)
    if skill then
      local coolDown = skill.coolDown
      local ready = coolDown:Ready()
      if not ready or coolDown.currentChargeCount <= 0 then
        return
      end
    end
  end
  self.skillReleaseStatus = status
  self.curSkillSlot = slot
  self:sendEvent(self.event.changeSkillStatus, {slot = slot, status = status})
  if status == self.skillStausEnum.waitConfirm then
    C_InputManager.SetInputmap(C_InputManager_MapType.KiBoDuelSkill, true)
    C_KiBoDuelLuaWrapper.EnterKiBoVersusCommonSkill(slot)
  else
    C_InputManager.SetInputmap(C_InputManager_MapType.KiBoDuelMap, true)
    C_KiBoDuelLuaWrapper.OutKiBoVersusCommonSkill()
  end
  printf("kiBoDuelSkill changeSkillStatus", status)
end

function this:isInReleaseSkill()
  return self.skillReleaseStatus == self.skillStausEnum.waitConfirm
end

function this:handleConfirmSkillRelease()
  if self.curSkillSlot == L_Const.skillType.KiBoVersusCommonSkill1 then
    C_KiBoDuelLuaWrapper.DoKiBoVersusCommonSkill1()
  elseif self.curSkillSlot == L_Const.skillType.KiBoVersusCommonSkill2 then
    C_KiBoDuelLuaWrapper.DoKiBoVersusCommonSkill2()
  end
  printf("kiBoDuelSkill handleConfirmSkillRelease", self.curSkillSlot)
  self:changeSkillStatus(nil, self.skillStausEnum.normal)
end

function this:handleCancelSkillRelease()
  printf("kiBoDuelSkill handleCancelSkillRelease")
  self:changeSkillStatus(nil, self.skillStausEnum.normal)
end

function this:getIsShowStatistics()
  local isShow = self.isShowStatistics == nil or self.isShowStatistics
  self.isShowStatistics = nil
  return isShow
end

function this:setIsShowStatistics(isShow)
  self.isShowStatistics = isShow
end

function this:isTrialDuel(id)
  local tpls = trainTaskTpl:getTplListByTrainTaskType(L_Const.trainTaskType.kiBoDuel)
  for _, v in pairs(tpls) do
    if trainTaskTpl:getDungeonId(v) == id then
      return true
    end
  end
  return false
end

function this:isCurrentTrialDuel()
  return self:isTrialDuel(L_PetDuelStore:getCurChallengeLevelId())
end

function this:getTrialPetName(slotIndex)
  local duelId = L_PetDuelStore:getCurChallengeLevelId()
  local tpl = kiBoDuelTpl:getTplById(duelId)
  local trialPets = kiBoDuelTpl:getKiboList(tpl)
  local pets = {}
  for k, v in ipairs(trialPets) do
    table.insert(pets, {
      slotId = k,
      guid = L_PetDuelStore:getTrialPetGuid(v),
      is_trial = true,
      id = v
    })
  end
  local result = L_PetDuelStore:getPetName(pets)
  return result[slotIndex]
end

function this:getPetNameBySlot(slotIndex)
  local duelId = L_PetDuelStore:getCurChallengeLevelId()
  if self:isTrialDuel(duelId) then
    return self:getTrialPetName(slotIndex)
  else
    return L_PetDuelStore:getPetNameBySlot(slotIndex)
  end
end

function this:onTargetCompeleted(arg)
  local id = arg.intArg
  self:sendEvent(self.event.taskCompeleted, {id = id})
  printf("kibodule onTargetCompeleted", id)
end

return this
