local this = class("pagePetFinishDuel", G_UIPageBase)
local kiBoDuelTpl = L_GameTpl:getKiboDuelTpl()
local kibiDuelGroupTpl = L_GameTpl:getKiBoDuelGroupTpl()
local worldSpawnerTpl = L_GameTpl:getWorldSpawnerTpl()
local commonConditionTpl = L_GameTpl:getCommonConditionTpl()
local currencyTpl = L_GameTpl:getCurrencyTpl()
local trainTaskTpl = L_GameTpl:getTrainTaskTpl()

function this.bind()
  return {
    conditionIsOn = true,
    txt_leftTime = "",
    playerSlider = 0,
    enemySlider = 0,
    playerName = "",
    playerHealthy = "",
    enemyName = "",
    enemyHealthy = "",
    rewardActive = false,
    rewardList = L_Const.ModuleInfo.CellIconBag,
    conditionList = {
      moduleName = "pages/petDuel/cellFinishCondition"
    },
    failedTips = "",
    petList = {
      moduleName = "pages/petDuel/cellPetExpItem"
    },
    petsExpActive = false,
    buttonsActive = true,
    conditionContentActive = true
  }
end

function this.methods()
  return {
    onClick_quit = function(self)
      L_PetDuelStore:req_CSProtoKiboDuelQuit(function()
      end)
    end,
    onClick_tryAgain = function(self)
      self:doTryAgain()
    end,
    onClick_statisticsBtn = function(self)
      L_UI:open("pagePetDuelStatistics")
    end
  }
end

function this:doTryAgain()
  if self.options ~= nil and L_EntrustStore:isEntrustKiboBattleLevel(self.options.duelId) then
    local curStamina = L_PlayerStore:getCurrencyNum(L_Const.currencyType.stamina)
    local kibo_tpl = kibiDuelGroupTpl:getTplById(self.options.duelId)
    local stamina = kibiDuelGroupTpl:getStamina(kibo_tpl)
    if curStamina < stamina then
      L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_dungeon_lackenergy"))
      L_UI:open("pageStamina")
      return
    end
  end
  L_KiBoDuelManager:restartKiBoDuel()
  L_UI:close(self.pageName)
end

function this:preOpen(options)
  if not options then
    return
  end
  self.options = options
  self:initPage()
end

function this:open()
  if self.options.winStatus then
    self.bindComponents.finishAnimation:Play("anim_petbattle_finish_win")
  else
    self.bindComponents.finishAnimation:Play("anim_petbattle_finish_fail")
  end
  C_ExternalManager.DispatchEvent(C_EExternalEventType.PetFightEnd)
end

function this:initPage()
  if self.options.winStatus then
    L_AudioUtil.playSound("Play_SFX_System_QiboChallenge_Win")
  end
  self.bind.conditionIsOn = self.options.winStatus
  self.bind.playerName = L_PlayerStore:getPlayerName()
  local tpl_kiBoDuel = kiBoDuelTpl:getTplById(self.options.duelId)
  local npcSpawnerID = kiBoDuelTpl:getNpcSpawnerID(tpl_kiBoDuel)
  local tpl_worldSpawner = worldSpawnerTpl:getTplById(npcSpawnerID)
  self.bind.enemyName = worldSpawnerTpl:getName(tpl_worldSpawner)
  self.bind.playerSlider = self.options.blueHpPercent
  self.bind.playerHealthy = string.format("%.0f", self.options.blueHpPercent * 100) .. "%"
  self.bind.enemySlider = self.options.redHpPercent
  self.bind.enemyHealthy = string.format("%.0f", self.options.redHpPercent * 100) .. "%"
  self.bind.txt_leftTime = tostring(self.options.duelTime)
  self:initFailedTips()
  self.bind.conditionContentActive = not L_KiBoDuelManager:isTrialDuel(self.options.duelId)
  if self.bind.conditionContentActive then
    self:initCondition(tpl_kiBoDuel)
  end
  self:initRewards()
end

function this:initFailedTips()
  if self.options.winStatus then
    return
  end
  if self.options.blueHp <= 0 then
    self.bind.failedTips = L_WordsTpl:getValue("notice_kibo_duel_in_battle_07")
    return
  end
  if 0 >= self.options.duelTime then
    self.bind.failedTips = L_WordsTpl:getValue("notice_kibo_duel_in_battle_08")
    return
  end
  self.bind.failedTips = L_WordsTpl:getValue("notice_kibo_duel_in_battle_09")
end

function this:initCondition(tpl_kiBoDuel)
  local challengeList = kiBoDuelTpl:getChallenge(tpl_kiBoDuel)
  local challengeRewardShowList = kiBoDuelTpl:getChallengeRewardShow(tpl_kiBoDuel)
  local duelTime = kiBoDuelTpl:getTime(tpl_kiBoDuel)
  local leftTime = self.options.duelTime
  local tmp = {}
  for i = 1, #challengeList do
    local tpl_commonCondition = commonConditionTpl:getTplById(challengeList[i][1])
    local time = challengeList[i][2]
    local descShow = commonConditionTpl:getDescShowKey(tpl_commonCondition)
    local tpl_currency = currencyTpl:getTplById(challengeRewardShowList[i].itemId)
    local rewardIcon = currencyTpl:getIconSmall(tpl_currency)
    local rewardTxt = challengeRewardShowList[i].itemNum
    table.insert(tmp, {
      descShow = string.gsub(descShow, "{time}", tostring(time)),
      leftTime = self.options.duelTime,
      isSatisfied = leftTime >= time,
      time = time,
      img_reward = rewardIcon,
      txt_reward = tostring(rewardTxt),
      duelTime = duelTime
    })
  end
  self.bind.conditionList:clear()
  self.bind.conditionList:insert_array(tmp)
  Timer.once(0.66, function()
    self:playConditionAnimation(tmp)
  end, self, self.gameObject)
end

function this:playConditionAnimation(data)
  for i = 1, #data do
    local index = i
    Timer.once((index - 1) * 0.2, function()
      local item = self.bind.conditionList:getItemCls(index)
      if data[index].isSatisfied then
        item:playCellAnimation("anim_petbattle_finish_cellfinish")
      else
        item:playCellAnimation("anim_petbattle_finish_cellunfinish")
      end
    end)
  end
end

function this:initRewards()
  if not self.options then
    return
  end
  self.bind.rewardActive = false
  self.bind.petsExpActive = false
  local rewards = {}
  if self.options.isFirstWin or L_EntrustStore:isEntrustKiboBattleLevel(self.options.duelId) then
    local tpl = kiBoDuelTpl:getTplById(self.options.duelId)
    rewards = kiBoDuelTpl:getFirstLoot(tpl)
    for k, v in ipairs(rewards) do
      if v.itemType == L_Const.resType.currency and v.itemId == L_Const.currencyType.petExp then
        table.remove(rewards, k)
        break
      end
    end
    self.bind.rewardActive = true
    local pets = L_PetDuelStore:getPetExpInfo()
    self.bind.buttonsActive = #pets == 0
    local delay = 1
    if 0 < #rewards then
      delay = 3
    end
    Timer.once(delay, function()
      self:initPetExp()
    end, self, self.gameObject)
  end
  if 0 < #rewards then
    self.bind.rewardActive = true
  end
  self.bind.rewardList:clear()
  self.bind.rewardList:insert_array(rewards)
end

function this:initPetExp()
  if not self.options then
    return
  end
  local pets = L_PetDuelStore:getPetExpInfo()
  self.bind.petsExpActive = 0 < #pets
  self.bind.rewardActive = not self.bind.petsExpActive
  self.bind.petList:clear()
  self.bind.petList:insert_array(pets)
  self.bind.buttonsActive = true
end

function this:escHandle()
end

function this:close()
  L_PetDuelStore:resetPetExpInfo()
end

return this
