local PETSCENEPATH = "Program/UIScene/petCatalogScene.prefab"
local page = class("pagePetCatalogDetail", G_UIPageBase)
local petTpl = L_GameTpl:getPetTpl()

function page:ctor(...)
  page.super.ctor(self, ...)
  self.data = {
    listCatalog = {},
    curListIdx = nil
  }
end

function page:created(obj, pageConfig)
  page.super.created(self, obj, pageConfig)
end

function page.bind()
  return {
    moduleCommonTop = {
      moduleName = "modulePages/moduleCommonTop"
    },
    toggleSwitch = true,
    loopListBox = {
      moduleName = "pages/petCatalogue/cellCatalogPet"
    },
    tempListBox = {
      moduleName = "pages/petCatalogue/cellCatalogPet"
    },
    moveToItemIndex = 0,
    catalogInfoActive = true,
    moduleCatalogInfo = {
      moduleName = "pages/petCatalogue/modulePetCatalogDetail"
    },
    mapInfoActive = false,
    moduleMapInfo = {
      moduleName = "pages/petCatalogue/modulePetCatalogMap"
    },
    bottomActive = true
  }
end

function page.methods()
  return {
    onValueChanged_Toggle = function(self, isOn)
      if not self.isMap and not self:getUnlockHabitat(self.currShowPetId) then
        self.bind.toggleSwitch = not isOn
        return
      end
      self.bind.catalogInfoActive = isOn
      self.bind.mapInfoActive = not isOn
      self.isMap = not isOn
      self:ShowPetById()
    end,
    onClickFilter = function(self)
      self:_onClickFilter()
    end
  }
end

function page:preOpen(options)
  self:setBlur(false)
  local data = {
    name = L_WordsTpl:getValue("notice_pagePetCatalogue_02"),
    closeCurPage = function()
      L_UI:close(self.pageName)
    end
  }
  self.modules.moduleCommonTop:initModule(data)
  self._filterKeyDic = options.filter
  self._cacheOption = options
  C_CameraManager.SetBrainBlendStyle(L_Const.blendStyle.cut)
  local brain = C_CameraManager.GetMainCameraBrain()
  brain.m_CustomBlends = nil
end

function page:initPage()
  local options = self._cacheOption
  self:initCatalog()
  self.currShowPetId = options.petId
  local numOffset = options.catalogId > 8 and 0 or options.catalogId
  self.bindComponents.scrollRect.horizontalNormalizedPosition = (options.catalogId - numOffset) / #self.data.listCatalog
  self:setSelect(options.catalogId, nil, true)
  self.bind.catalogInfoActive = true
  self.bind.mapInfoActive = false
  self._cacheOption = nil
  self.openTimer = Timer.once(0.5, function()
    self.frameTaskId = FrameScheduler.add(function()
      if self and self.bindComponents and self.bindComponents.blackMask and self.bindComponents.anim then
        self.bindComponents.blackMask.gameObject:ActiveTrans(false)
        self.bindComponents.anim:Stop()
        self.bindComponents.anim:Play("Anim_PetCatalogDetail_In")
      end
    end, 5)
  end)
end

function page:open()
  L_ResPool:asyncGameObject(PETSCENEPATH, function(go)
    self.sceneGo = go
    self.sceneGo.transform:SetParent(C_LuaUtility.GetRootNode())
    self.modules.moduleCatalogInfo:setSceneGo(go)
    self:initPage()
  end)
end

function page:close()
  if self.openTimer then
    Timer.remove(self.openTimer)
    self.openTimer = nil
  end
  if self.frameTaskId then
    FrameScheduler.remove(self.frameTaskId)
    self.frameTaskId = nil
  end
  self._filterKeyDic = nil
  if L_CommonUtil.isValid(self.sceneGo) then
    C_GameObject.Destroy(self.sceneGo)
  end
end

function page:initCatalog()
  table.clear(self.data.listCatalog)
  for pid, pConfig in pairs(petTpl.data) do
    if pConfig.iconographyshow and pConfig.iconographyshow == 1 then
      if self._filterKeyDic and self._filterKeyDic[18] then
        local elementType = self._filterKeyDic[18][1] or 0
        local petType = petTpl:getFirstElement(pConfig)
        if petType == elementType then
          table.insert(self.data.listCatalog, {
            petId = pid,
            onClickCb = function(cell)
              self:_onClickCatalog(cell)
            end
          })
        end
      else
        table.insert(self.data.listCatalog, {
          petId = pid,
          onClickCb = function(cell)
            self:_onClickCatalog(cell)
          end
        })
      end
    end
  end
  table.sort(self.data.listCatalog, function(a, b)
    local aTpl = petTpl:getTplById(a.petId)
    local bTpl = petTpl:getTplById(b.petId)
    if aTpl.iconographyNum == bTpl.iconographyNum then
      return a.petId < b.petId
    end
    return aTpl.iconographyNum < bTpl.iconographyNum
  end)
  for i = 1, #self.data.listCatalog do
    self.data.listCatalog[i].idx = i
  end
  self.bind.tempListBox:clear()
  self.bind.tempListBox:insert_array(self.data.listCatalog)
end

function page:refreshTaskRedDot()
  local cell = self.bind.tempListBox:getItemCls(self.data.curListIdx)
  if cell then
    cell:refreshRedDot()
  end
end

function page:_onClickCatalog(cell)
  if cell and cell.bind.idx then
    self:setSelect(cell.bind.idx)
  end
end

function page:setSelect(idx, force, noVX)
  if not idx then
    error("PetCatalog: select index is nil")
    return
  end
  if self.data.curListIdx and self.data.curListIdx == idx and not force then
    return
  end
  if self.data.curListIdx and self.data.curListIdx > 0 then
    local oldSelectCell = self.bind.tempListBox:getItemCls(self.data.curListIdx)
    if oldSelectCell then
      oldSelectCell:setSelect(false)
    end
  end
  local newSelectCell = self.bind.tempListBox:getItemCls(idx)
  if newSelectCell then
    newSelectCell:setSelect(true, true)
  end
  self.data.curListIdx = idx
  self.currShowPetId = newSelectCell.bind.petId
  self:ShowPetById(noVX)
end

function page:ShowPetById(noVX)
  if self.isMap and self:getUnlockHabitat(self.currShowPetId) then
    self:showMap()
    self.bind.toggleSwitch = false
  else
    self:showInfo()
    self:setBlur(false)
    self.bind.toggleSwitch = true
    if not noVX then
      self.bindComponents.anim:Stop()
      self.bindComponents.anim:Play("Anim_PetCatalogDetail_In")
    end
  end
end

function page:getUnlockHabitat(petId, blockNotice)
  local petCatalogData = L_CatalogStore:getPetCatalogByPetId(petId) or {}
  local taskLevel = petCatalogData.lv or 1
  if taskLevel < L_GameTpl:getGameConstTpl():getValue("ICONOGRAPHYLEVEL_UNLOCK_HABITAT") and not blockNotice then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_habitat_01"))
  end
  return taskLevel >= L_GameTpl:getGameConstTpl():getValue("ICONOGRAPHYLEVEL_UNLOCK_HABITAT")
end

function page:showMap()
  self.bind.catalogInfoActive = false
  self.bind.mapInfoActive = true
  self.modules.moduleMapInfo:initMap()
  local areaId = L_AreaStore:getAreaId()
  self.modules.moduleMapInfo:setArea(areaId)
  self.modules.moduleMapInfo:showPet(self.currShowPetId)
end

function page:showInfo()
  self.bind.catalogInfoActive = true
  self.bind.mapInfoActive = false
  self.modules.moduleCatalogInfo:showPet(self.currShowPetId)
end

function page:_onClickFilter()
  local callback = function(filterKeyDic)
    self._filterKeyDic = filterKeyDic
    self:_filterCallback(filterKeyDic)
  end
  local param = {
    type = L_SortFilterConst.SortOrFilter.Filter,
    systemId = L_SystemConst.enum.petCatalog,
    callback = callback,
    selectValue = self._filterKeyDic
  }
  L_UI:open("pageMultiplySortFilter", param)
end

function page:_filterCallback(filterKeyDic)
  self:initCatalog()
  self:setSelect(1, true)
end

function page:setBlur(isBlur)
  self.bindComponents.blur.enabled = isBlur
end

return page
