local this = class("pagePet", G_UIPageBase)

function this:ctor(...)
  this.super.ctor(self, ...)
  self.data = {
    sortParam = {
      type = L_Const.sortType.lv,
      order = L_Const.sortOrder.DESC
    },
    name = "",
    isModify = false
  }
end

function this.bind()
  return {
    currentPetDisplay = false,
    infoToggles = true,
    toggleInfo = true,
    upBg = true,
    showPetList = false,
    petList = {
      moduleName = "modulePages/cellIconUnit"
    },
    toggleModuleBar = {
      type = "toggleModule",
      modulePetProperty = {
        assetName = "UI/Pages/Pet/modulePetProperty",
        moduleName = "pages/pet/modulePetProperty"
      },
      moduleRankUpPet = {
        assetName = "UI/Pages/Pet/moduleRankUpPet",
        moduleName = "pages/Pet/moduleRankUpPet"
      },
      modulePetUseItem = {
        assetName = "UI/Pages/Pet/modulePetUseItem",
        moduleName = "pages/Pet/modulePetUseItem"
      },
      modulePetFeed = {
        assetName = "UI/Pages/Pet/modulePetFeed",
        moduleName = "pages/Pet/modulePetFeed"
      }
    },
    toggleModuleName = "",
    module_sortWay = {
      moduleName = "ModulePages/moduleSortWay"
    },
    modulePetSceneMod = {
      type = "toggleModule",
      modulePetSceneMod = {
        assetName = "UI/Pages/Pet/modulePetSceneMod",
        moduleName = "pages/Pet/modulePetSceneMod"
      }
    },
    modulePetSceneModName = "",
    activePetDisplay = true,
    activePetListButton = false,
    isOnToggleGene = false,
    isOnToggleFeed = false,
    isOnToggleRankUp = false,
    topBg = true,
    filter = false,
    modulePetFilter = {
      moduleName = "modulePages/filtrate/modulePetFilter"
    },
    bgMask = false,
    warning_petList = false,
    warning_pagePet = false,
    masterIcon = false,
    masterLv = "",
    masterName = "",
    img_masterHero = "",
    moduleCommonTop = {
      moduleName = "modulePages/moduleCommonTop"
    },
    txt_petFavorLv = "",
    go_petFavor = false
  }
end

function this.methods()
  return {
    petList = {
      onClick_Choose = function(self, id)
        if id ~= L_PetStore:getCurSelectPetId() then
          L_PetStore:setCurSelectPetId(id)
        end
      end
    },
    toggleInfoBtn = function(self)
      self:returnToDefaultModule()
    end,
    toggleRankUp = function(self)
      local result = L_SystemUnlockManager:checkAndTip(L_SystemConst.enum.petRankUp)
      if not result then
        return
      end
      self.bind.toggleModuleName = "moduleRankUpPet"
      self.bind.showPetList = false
      self.bind.activePetListButton = false
    end,
    toggleDecoration = function(self)
      local result = L_SystemUnlockManager:checkAndTip(L_SystemConst.enum.petDecoration)
      if not result then
        return
      end
      L_FlyMsgManager:showNormalMsgByKey("notice_pagePet_02")
    end,
    toggleUseItem = function(self)
      self.bind.toggleModuleName = "modulePetUseItem"
      self.bind.activePetDisplay = true
      self.modules.toggleModuleBar.modulePetUseItem:refreshPet(L_PetStore:getCurSelectPetId())
      self.bind.showPetList = false
      self.bind.activePetListButton = false
    end,
    toggleFeed = function(self)
      if self.bind.toggleModuleName == "modulePetFeed" then
        return
      end
      self:returnToDefaultModule()
    end,
    onClick_openPetList = function(self)
      self.bind.showPetList = true
      self.bind.topBg = false
      self:setUpBg(false)
      self:sortPetList()
    end,
    onClick_closePetList = function(self)
      self.bind.showPetList = false
      self.bind.topBg = true
      self:setUpBg(true)
    end,
    onClick_openFilterModule = function(self)
      self.bind.filter = true
    end,
    onClick_geneRemakeTips = function(self)
      local result = L_SystemUnlockManager:checkAndTip(L_SystemConst.enum.petGene)
      if not result then
        return
      end
      L_UI:open("pagePetGene")
    end,
    onClick_petFavor = function(self)
      L_UI:open("pagePetFavorDetail", {
        petGuid = self.petId
      })
    end
  }
end

function this:check(options, callback)
  local result = L_SystemUnlockManager:checkAndTip(L_SystemConst.enum.pet)
  callback(result)
end

function this:preOpen(options)
  this.super.preOpen(self, options)
  self.bind.bgMask = false
  options = options or {}
  if options.callBack then
    self.callBack = options.callBack
  end
  self.petId = options.petId
  if not self.petId then
    self.petId = L_PetStore:getFirstOrderPet()
  end
  if self.petId then
    L_PetStore:setCurSelectPetId(self.petId)
  end
  if options.jumpParams then
    local jumpType = tonumber(options.jumpParams[1])
    if jumpType == 1 then
      self.bind.toggleModuleName = "modulePetFeed"
    elseif jumpType == 2 then
      self.bind.toggleModuleName = "moduleRankUpPet"
      self.bind.isOnToggleRankUp = true
    end
  else
    self.bind.toggleModuleName = "modulePetFeed"
  end
  if self.petId then
    self:initData(self.petId)
  end
  self.selectPet = {}
  self.compareData = {}
  self.moduleFilterData = {
    closeCurModule = function()
      self.bind.filter = false
    end,
    filter = function(data)
    end
  }
  self.modules.modulePetFilter:initModule(self.moduleFilterData)
  self.bind.modulePetSceneModName = "modulePetSceneMod"
  self:refreshPetMod()
  local data = {
    name = L_WordsTpl:getValue("notice_pagePet_01"),
    helpBtnBool = false,
    mainBtnBool = true,
    closeCurPage = function()
      if self.closeCurPageFunc then
        self.closeCurPageFunc()
        self.closeCurPageFunc = nil
        self.modules.moduleCommonTop:setPageName(L_WordsTpl:getValue("notice_pagePet_01"))
        return
      end
      L_UI:close(self.pageName)
    end,
    helpBtn = function()
    end,
    mainBtn = function()
      L_UI:backToRoot()
    end
  }
  self.closeCurPageFunc = nil
  self.modules.moduleCommonTop:initModule(data)
  L_PetStore:listenCallFunc(L_PetStore.event.refreshPet, self.onEvent_refreshPet, self)
  L_PetStore:listenCallFunc(L_PetStore.event.setCurPetId, self.onEvent_setCurPetId, self)
  L_PetStore:listenCallFunc(L_PetStore.event.removePet, self.onEvent_removePet, self)
  L_PetStore:listenCallFunc(L_PetStore.event.refreshNewPet, self.onEvent_newPet, self)
  L_ReddotManager:registerReddot(self.bindComponents.reddotNormal, L_ReddotManager.DotDef.PetNew)
  self:initSystem()
  C_CameraManager.SetBrainBlendStyle(L_Const.blendStyle.cut)
  local brain = C_CameraManager.GetMainCameraBrain()
  brain.m_CustomBlends = nil
end

function this:open()
  L_ReddotManager:registerReddot(self.bindComponents.evolutionReddot, string.format(L_ReddotManager.DotDef.PetRankUp, self.petId))
end

function this:initSystem()
  self.systemToTrans = {
    [L_SystemConst.enum.petRankUp] = {
      self.bindComponents.rTransRankUp
    },
    [L_SystemConst.enum.petGene] = {
      self.bindComponents.rTransGene
    },
    [L_SystemConst.enum.petDecoration] = {
      self.bindComponents.rTransDecoration
    },
    [L_SystemConst.enum.petFeed] = {
      self.bindComponents.rTransFeed
    }
  }
  for systemId, v in pairs(self.systemToTrans) do
    v.locker = L_SystemUnlockManager:tryGenerateLocker(systemId)
    if v.locker then
      self:refreshSystem(systemId, false)
      v.locker:setCallback(self.refreshSystem, self, self.gameObject)
    end
  end
end

function this:refreshSystem(systemId, isUnlock)
  local node = self.systemToTrans[systemId]
  local locker = node.locker
  for _, v in ipairs(node) do
    locker:tryShowOrHide(v, isUnlock)
  end
end

function this:destroyAllLocker()
  for _, v in pairs(self.systemToTrans) do
    local locker = v.locker
    if locker then
      L_SystemUnlockManager:removeLocker(locker)
    end
  end
end

function this:initSortWayList()
  local list = {
    L_Const.sortType.lv,
    L_Const.sortType.guid
  }
  local func = function(type, order)
    self.data.sortParam = {type = type, order = order}
    self:sortPetList()
  end
  self.modules.module_sortWay:initModule(list, func)
end

function this:setCommonTopData(func, name)
  self.closeCurPageFunc = func
  self.modules.moduleCommonTop:setPageName(name)
end

function this:close(options)
  this.super.close(self, options)
  if self.callBack then
    self.callBack()
  end
  self:disableAllModule()
  self:destroyAllLocker()
  L_PhotoManager:clearPhotoEntity(self)
  L_PetStore:unListenCallFunc(L_PetStore.event.refreshPet, self.onEvent_refreshPet)
  L_PetStore:unListenCallFunc(L_PetStore.event.setCurPetId, self.onEvent_setCurPetId)
  L_PetStore:unListenCallFunc(L_PetStore.event.removePet, self.onEvent_removePet)
  L_PetStore:unListenCallFunc(L_PetStore.event.refreshNewPet, self.onEvent_newPet)
end

function this:onEvent_refreshPet(pet)
  if pet.guid ~= self.petId then
    return
  end
  if pet.id then
    self.configId = pet.id
  end
  self:initData(pet.guid)
end

function this:onEvent_setCurPetId(guid, isModify)
  if guid and isModify then
    self:initData(guid)
    self:refreshPetMod()
  end
end

function this:onEvent_removePet()
end

function this:onEvent_newPet(entity)
end

function this:initData(guid)
  if guid == 0 or nil then
    self:hidePetDisplay()
  else
    self.petId = guid
    self.bind.currentPetDisplay = true
    local pet = L_PetStore:getPetItem(self.petId)
    self.configId = pet.id
    if self.bind.toggleModuleName == "modulePetFeed" then
      L_PetStore:playPetVoiceSound(self.configId, L_PetConst.PetSystemVoiceType.PropertyDetail)
      self.bind.isOnToggleFeed = true
      self.modules.toggleModuleBar.modulePetFeed:setShowPetGuid(self.petId)
      self.modules.toggleModuleBar.modulePetFeed:refreshUI()
    end
  end
end

function this:refreshPetDisplay()
  local petList = L_PetStore:getPetList()
  local countList = {}
  if not table.isEmpty(self.compareData) then
    countList = L_PetStore:getFilterPetData(petList, self.compareData)
  else
    for i, v in pairs(petList) do
      table.insert(countList, v)
    end
  end
  if #countList < 1 then
    self:hidePetDisplay()
  else
    L_PetStore:setCurSelectPetId(countList[1].guid)
    self.petId = countList[1].guid
    self.bind.infoToggles = true
    self.methods.toggleInfoBtn(self)
    self.bind.activePetListButton = false
    self.bind.currentPetDisplay = true
  end
  self:refreshPetMod()
end

function this:refreshPetMod()
  if self.bind.activePetDisplay == true then
    local pet = L_PetStore:getPetItem(self.petId)
    if pet then
      self.modules.modulePetSceneMod.modulePetSceneMod:refreshPetMod(pet.id, pet:isSpecialPet() == 1, pet:hasFlashGene())
    else
      self.modules.modulePetSceneMod.modulePetSceneMod:disableMod()
    end
  end
end

function this:initPetList(compareData)
  local petList = L_PetStore:getPetList()
  local countList = {}
  if compareData ~= nil then
    self.compareData = compareData
    countList = L_PetStore:getFilterPetData(petList, compareData)
  else
    for i, v in pairs(petList) do
      table.insert(countList, v)
    end
  end
  local list = countList
  local sortType = self.data.sortParam.type
  local lst = {}
  local equippedLst = {}
  for i, v in pairs(list) do
    if v.hero_id ~= nil and v.hero_id ~= 0 then
      table.insert(equippedLst, v)
    else
      table.insert(lst, v)
    end
  end
  if sortType == L_Const.sortType.lv then
    table.sort(equippedLst, function(a, b)
      if a.lv == b.lv then
        return a.guid < b.guid
      else
        return a.lv < b.lv
      end
    end)
    table.sort(lst, function(a, b)
      if a.lv == b.lv then
        return a.guid < b.guid
      else
        return a.lv < b.lv
      end
    end)
  elseif sortType == L_Const.sortType.guid then
    table.sort(equippedLst, function(a, b)
      return a.guid < b.guid
    end)
    table.sort(lst, function(a, b)
      return a.guid < b.guid
    end)
  end
  if self.data.sortParam.order == L_Const.sortOrder.DESC then
    local tmpList = {}
    for i = #lst, 1, -1 do
      table.insert(tmpList, lst[i])
    end
    lst = tmpList
    local equipList = {}
    for i = #equippedLst, 1, -1 do
      table.insert(equipList, equippedLst[i])
    end
    equippedLst = equipList
  end
  countList = {}
  for i, v in ipairs(equippedLst) do
    table.insert(countList, v)
  end
  for i, v in ipairs(lst) do
    table.insert(countList, v)
  end
  if #countList < 1 then
    self:hidePetDisplay()
  else
    local onClick_Choose = function(cell)
      local petId = cell.bind.guid
      if L_PetStore:getCurSelectPetId() ~= petId then
        L_PetStore:setCurSelectPetId(petId)
        self.petId = petId
      end
    end
    L_PetStore:setCurSelectPetId(countList[1].guid)
    self.petId = countList[1].guid
    self.bind.petList:clear()
    local lst = {}
    for i = 1, #countList do
      table.insert(lst, {
        activeSelect = L_PetStore:getCurSelectPetId() == countList[i].guid,
        guid = countList[i].guid,
        itemType = L_Const.resType.pet,
        reddotName = string.format(L_ReddotManager.DotDef.PetNew, countList[i].guid),
        callback = onClick_Choose,
        index = i,
        nameColor = L_Const.colorHtml.white001
      })
    end
    self.bind.petList:insert_array(lst)
    self.bind.infoToggles = true
    self.methods.toggleInfoBtn(self)
    self.bind.currentPetDisplay = true
  end
  if compareData ~= nil then
    self.bind.showPetList = true
  end
end

function this:refreshPetList(list)
  local petList
  if list then
    petList = list
  else
    petList = L_PetStore:getPetList()
  end
  local countList = {}
  if not table.isEmpty(self.compareData) then
    countList = L_PetStore:getFilterPetData(petList, self.compareData)
  else
    for i, v in ipairs(petList) do
      table.insert(countList, v)
    end
  end
  if #self.bind.petList >= 1 then
    self.bind.petList:clear()
    if L_PetStore:getCurSelectPetId() ~= nil then
      self.petId = L_PetStore:getCurSelectPetId()
    else
      self.petId = countList[1].guid
    end
    L_PetStore:setCurSelectPetId(self.petId)
    local onClick_Choose = function(cell)
      local petId = cell.bind.guid
      if L_PetStore:getCurSelectPetId() ~= petId then
        L_PetStore:setCurSelectPetId(petId)
        self.petId = petId
      end
    end
    local lst = {}
    local focusIndex = 1
    for i = 1, #countList do
      focusIndex = L_PetStore:getCurSelectPetId() == countList[i].guid and i or focusIndex
      table.insert(lst, {
        activeSelect = L_PetStore:getCurSelectPetId() == countList[i].guid,
        guid = countList[i].guid,
        itemType = L_Const.resType.pet,
        reddotName = string.format(L_ReddotManager.DotDef.PetNew, countList[i].guid),
        callback = onClick_Choose,
        index = i,
        nameColor = L_Const.colorHtml.white001
      })
    end
    self.bind.petList:insert_array(lst)
    self.bindComponents.petList:FocusItemIndex(focusIndex - 1)
    self.bind.upBg = true
  else
    self.bind.upBg = false
  end
end

function this:sortPetList()
  local list = L_PetStore:getPetList()
  local sortType = self.data.sortParam.type
  local lst = {}
  local equippedLst = {}
  for i, v in pairs(list) do
    if v.hero_id ~= nil and v.hero_id ~= 0 then
      table.insert(equippedLst, v)
    else
      table.insert(lst, v)
    end
  end
  if sortType == L_Const.sortType.lv then
    table.sort(equippedLst, function(a, b)
      if a.lv == b.lv then
        return a.guid < b.guid
      else
        return a.lv < b.lv
      end
    end)
    table.sort(lst, function(a, b)
      if a.lv == b.lv then
        return a.guid < b.guid
      else
        return a.lv < b.lv
      end
    end)
  elseif sortType == L_Const.sortType.guid then
    table.sort(equippedLst, function(a, b)
      return a.guid < b.guid
    end)
    table.sort(lst, function(a, b)
      return a.guid < b.guid
    end)
  end
  if self.data.sortParam.order == L_Const.sortOrder.DESC then
    local tmpList = {}
    for i = #lst, 1, -1 do
      table.insert(tmpList, lst[i])
    end
    lst = tmpList
    local equipList = {}
    for i = #equippedLst, 1, -1 do
      table.insert(equipList, equippedLst[i])
    end
    equippedLst = equipList
  end
  local totalList = {}
  for i, v in ipairs(equippedLst) do
    table.insert(totalList, v)
  end
  for i, v in ipairs(lst) do
    table.insert(totalList, v)
  end
  self:refreshPetList(totalList)
end

function this:hidePetDisplay()
  self.bind.petList:clear()
  self.bind.upBg = false
  self.bind.toggleModuleName = ""
  self.petId = 0
end

function this:disableAllModule()
  self.bind.toggleModuleName = ""
  self.bind.currentPetDisplay = false
end

function this:returnToDefaultModule()
  local pet_guid = self.petId
  if not math.isEmpty(pet_guid) then
    self.bind.toggleModuleName = "modulePetFeed"
    self.bind.activePetDisplay = true
    self:initData(pet_guid)
  end
end

function this:closePetFreeModule()
end

function this:playPageAnimation(name)
  if name ~= nil and name ~= "" then
    self.bindComponents.pageAnimation:Play(name)
  end
end

function this:playEvolutionTimeline(guid, prePetData, oldSkillInfo)
  L_UI:open("pagePetEvo", {
    guid = guid,
    prePetData = prePetData,
    oldSkillInfo = oldSkillInfo
  })
end

function this:showWarning(bool)
  self.bind.warning_pagePet = bool
  if bool then
    local expandSize = self.bindComponents.masterName.preferredWidth
    self.bindComponents.warningTrans.sizeDelta = C_Vector2(187 + expandSize, 40)
    Unity.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.bindComponents.warningTrans)
  end
end

function this:setUpBg(bool)
  if not math.isEmpty(self.petId) then
    self.bind.upBg = bool
  else
    self.bind.upBg = false
  end
  self.bind.activePetListButton = false
end

function this:showMasterIcon(bool, lv, hero)
  self.bind.masterIcon = bool
  if bool then
    local item_hero = L_ItemTplManager:getHeroItem(L_HeroStore:getHeroConfigId(hero))
    self.bind.masterLv = tostring(lv)
    if hero.guid == L_HeroStore:getDefaultHeroGuid() then
      L_PhotoManager:newOrBindPhotoEntity(self, self.bindComponents.ImageHeroIcon, L_PlayerStore:getPlayerModHeadImgName())
      self.bind.masterName = L_PlayerStore:getPlayerName()
    else
      L_PhotoManager:clearPhotoEntity(self)
      self.bind.img_masterHero = item_hero.icon
      self.bind.masterName = item_hero.name
    end
    local expandSize = self.bindComponents.masterName.preferredWidth
    self.bindComponents.masterIcon.sizeDelta = C_Vector2(131 + expandSize, 57)
    Unity.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.bindComponents.masterIcon)
    local result = L_SystemUnlockStore:getSystemIsOpen(L_SystemConst.enum.petFavor)
    self.bind.go_petFavor = result
    if result then
      local pet = L_PetStore:getPetItem(self.petId)
      self.bind.txt_petFavorLv = tostring(pet:petFavorLv())
    end
  end
end

function this:closePetAdvance()
  self:setUpBg(true)
  self:returnToDefaultModule()
end

return this
