local this = class("pageWearPet", G_UIPageBase)
local PosIndex = 2

function this.bind()
  return {
    module_commonTop = {
      moduleName = "modulePages/moduleCommonTop"
    },
    list_hud = {
      moduleName = "pages/formation/formationModule/cellTeamUnitHud"
    },
    module_selectPet = {
      moduleName = "modulePages/unit/moduleSelectPet"
    }
  }
end

function this.methods()
  return {
    module_selectPet = {
      onClick_selectPet = function(self, petGuid)
        local hero = L_HeroStore:getHero(self._heroGuid)
        self._moduleSelectPet = self.modules.module_selectPet
        if L_HeroStore:getHeroPetGuid(hero) == petGuid then
          L_HeroManager:reqWearPet(self._heroGuid, nil, function()
            L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_formation_remove"))
            self._moduleSelectPet:setListSelect()
          end)
        else
          L_HeroManager:reqWearPet(self._heroGuid, petGuid, function()
            local pet = L_PetStore:getPetItem(petGuid)
            L_AudioUtil.stopSound(self._petVoiceWrap)
            self._petVoiceWrap = L_PetStore:playPetVoiceSound(pet.id, L_PetConst.PetSystemVoiceType.IntoTeam)
            local selectDic = {}
            selectDic[petGuid] = {isSelect = true}
            self._moduleSelectPet:setListSelect(selectDic)
          end)
        end
      end
    }
  }
end

function this:check(options, callback)
  local result = L_SystemUnlockManager:checkAndTip(L_SystemConst.enum.formation)
  if not result then
    callback(false)
    return
  end
  if math.isEmpty(options.heroGuid) then
    callback(false)
    return
  end
  if not L_HeroStore:getHero(options.heroGuid) then
    callback(false)
    return
  end
  local hero = L_HeroStore:getHero(options.heroGuid)
  if not math.isEmpty(L_HeroStore:getTrailPet(hero)) then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("hero_cant_change_test_kibo"))
    callback(false)
    return
  end
  callback(true)
end

function this:preOpen(options)
  this.super.preOpen(self, options)
  options = options or {}
  self._heroGuid = options.heroGuid
  local pageFormationMainStatus = L_UI:getPageStatus("pageFormationMain")
  self._hasOpenFormationMain = pageFormationMainStatus and pageFormationMainStatus == "hided"
  if self._hasOpenFormationMain then
    self._formationEditStatusCache = L_FormationManager:getEditStatus()
    self._formationTypeCache = L_FormationManager:getRuntimeFormationType()
    self._formationIndexCache = L_FormationManager:getRuntimeFormationIndex()
    self._formationFocusIndexCache = L_FormationManager:getFocusIndex()
  else
    L_FormationManager:loadFormationScene()
  end
  L_FormationManager:setRuntimeFormationType()
  L_FormationManager:setRuntimeFormationIndex()
  L_FormationManager:switchToEditPet(PosIndex)
  self._ESyncHeroServerDataHandler = handler(self, self.onEvent_refreshFormation)
  AzurWorld.heroMgr:RegisterEvent(C_EHeroEvent.ESyncHeroServerDataList, self._ESyncHeroServerDataHandler)
  L_PetStore:listenCallFunc(L_PetStore.event.refreshPet, self.onEvent_refreshFormation, self, nil, 0)
  self._lateUpdateHandle = L_CommonUtil.handle(self.onLateUpdate_displayFollow, self)
  C_UpdateSource.AddLateUpdateEventHandler(self._lateUpdateHandle, "FormationMainPage.lateUpdate")
  L_SceneManager:setSceneActive(false)
  L_HomeManager:setHomeRootActive(false)
  self:initPage()
end

function this:show()
  L_TimerManager:clearTimer(self)
  L_FormationManager:setSceneArtActive(true)
end

function this:hide()
  L_FormationManager:setSceneArtActive(false)
end

function this:close(options)
  this.super.close(self, options)
  L_TimerManager:clearTimer(self)
  L_AudioUtil.stopSound(self._petVoiceWrap)
  if self._lateUpdateHandle then
    C_UpdateSource.RemoveLateUpdateEventHandler(self._lateUpdateHandle)
  end
  self._lateUpdateHandle = nil
  AzurWorld.heroMgr:UnregisterEvent(C_EHeroEvent.ESyncHeroServerDataList, self._ESyncHeroServerDataHandler)
  L_PetStore:unListenCallFunc(L_PetStore.event.refreshPet, self.onEvent_refreshFormation, self, nil, 0)
  if self._hasOpenFormationMain then
    L_FormationManager:setEditStatus(self._formationEditStatusCache)
    L_FormationManager:setRuntimeFormationType(self._formationTypeCache)
    L_FormationManager:setRuntimeFormationIndex(self._formationIndexCache)
    L_FormationManager:setFocusIndex(self._formationFocusIndexCache)
    L_FormationManager:setNeedRevertFormationScene(true)
  else
    L_FormationManager:removeFormationScene()
  end
end

function this:escHandle()
  if not self._moduleSelectPet:escHandle() then
    L_UI:close(self.pageName)
  end
end

function this:initPage()
  self:initCommonTopModule()
  self:initFormationModel()
  self:initHudList()
  self:initSelectPetModule()
end

function this:initCommonTopModule()
  local data = {
    name = L_WordsTpl:getValue("ui_heroRole_28"),
    nameEn = "HE                            RO",
    closeCurPage = handler(self, self.escHandle)
  }
  self.modules.module_commonTop:initModule(data)
end

function this:initFormationModel(isSync)
  L_FormationManager:loadHeroModelAtPlace(self._heroGuid, PosIndex, isSync)
  local hero = L_HeroStore:getHero(self._heroGuid)
  L_FormationManager:loadPetModelAtPlace(L_HeroStore:getHeroPetGuid(hero), 2)
end

function this:initHudList()
  local hero = L_HeroStore:getHero(self._heroGuid)
  local petGuid = L_HeroStore:getHeroPetGuid(hero)
  local temp = {}
  table.insert(temp, {
    index = 2,
    roleType = L_Const.roleType.hero,
    roleId = self._heroGuid,
    bEdit = false
  })
  if not math.isEmpty(petGuid) then
    table.insert(temp, {
      index = 2,
      roleType = L_Const.roleType.pet,
      roleId = petGuid,
      bEdit = false
    })
  end
  self.bind.list_hud:clear()
  self.bind.list_hud:insert_array(temp)
end

function this:refreshHudList()
  local list = self.modules.list_hud
  for i, hud in pairs(list) do
    hud:setFollow()
    if i == 1 then
      hud:hideEditUI()
    else
      hud:setUIState(true, false)
    end
  end
end

function this:initSelectPetModule()
  self._moduleSelectPet = self.modules.module_selectPet
  local param = {}
  param.systemId = L_SystemConst.enum.formationQuickPet
  local hero = L_HeroStore:getHero(self._heroGuid)
  local petGuid = L_HeroStore:getHeroPetGuid(hero)
  local selectDic = {}
  if not math.isEmpty(petGuid) then
    local petItem = L_PetStore:getPetItem(petGuid)
    param.defaultSelectBoxIndex = petItem.box_id // 100
    selectDic[petGuid] = {isSelect = true}
  end
  self._moduleSelectPet:initModule(param)
  self._moduleSelectPet:setListSelect(selectDic)
end

function this:onEvent_refreshFormation()
  self:initFormationModel(true)
  self:initHudList()
end

function this:onLateUpdate_displayFollow()
  self:refreshHudList()
end

return this
