local page = class("pageGetPet", G_UIPageBase)
local petTpl = L_GameTpl:getPetTpl()
local petLearningEnumTpl = L_GameTpl:getPetLearingEnumTpl()
local petLearningAblityTpl = L_GameTpl:getPetLearningAblityTpl()
local petGradeTpl = L_GameTpl:getPetGradeTpl()
local battleInfoTpl = L_GameTpl:getBattleInfoTpl()
local wordsTpl = L_GameTpl:getWordsTpl()
local elementTypeTpl = L_GameTpl:getElementTypeTpl()
local _homeTalentTpl = L_GameTpl:getHomeTalentTpl()
local _petHomeSizeTpl = L_GameTpl:getPetHomeSizeTpl()
local _petHomeTalentTpl = L_GameTpl:getPetHomeTalentTpl()
local modulePetGeneSkillsTips_Path = "UI/Pages/PetBox/modulePetGeneSkillsTips.prefab"
local modulePetGeneSkillsTips = "ui.pages.pet.new.modulePetGeneSkillsTips"
local gradeRank = {
  [1] = 1,
  [2] = 1,
  [3] = 2,
  [4] = 2,
  [5] = 3,
  [6] = 3,
  [7] = 4,
  [8] = 5,
  [9] = 6
}
local colorEnums = {
  [1] = "#595959",
  [2] = "#595959",
  [3] = "#1c795e",
  [4] = "#1c795e",
  [5] = "#234edb",
  [6] = "#234edb",
  [7] = "#935fd9",
  [8] = "#b87500"
}
local showTypeBeginTime = {
  [L_Const.getPetShowType.short] = 0,
  [L_Const.getPetShowType.long] = 10,
  [L_Const.getPetShowType.middle] = 20
}
local hasHideBeginTime = {
  [L_Const.getPetShowType.short] = 7.2,
  [L_Const.getPetShowType.long] = 17.2,
  [L_Const.getPetShowType.middle] = 27.2
}

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

function page.bind()
  return {
    pet_name = "",
    pet_lv = "",
    pet_maxLv = "",
    pet_height = "",
    show_new = false,
    go_time = false,
    txt_time = "",
    lockPetImage = "Page/BSCommon/tex_common_icon_lock02",
    lockPetImageColor = CS.UnityEngine.Color(1, 1, 1, 0.3),
    active_btn_continueHatch = false,
    modulePetNewSimpleTags = {
      moduleName = "pages/pet/new/modulePetNewSimpleTags"
    },
    modulePetBoxRating = {
      moduleName = "pages/pet/new/modulePetBoxRating"
    },
    petPropertyList = {
      moduleName = "pages/pet/cellAttrItem"
    },
    petGetGeneList = {
      moduleName = "pages/pet/new/cellPetGetGene"
    },
    list_petHomeLaborTag = {
      moduleName = "pages/Pet/cellTagPetHomeLabor"
    },
    rank_1 = false,
    rank_2 = false,
    rank_3 = false,
    rank_4 = false,
    rank_5 = false,
    rank_6 = false,
    timelineMask = false
  }
end

function page.methods()
  return {
    onClick_continueHatch = function(self)
      if L_PetStore:getPetListCount() >= L_GameTpl:getGameConstTpl():getValue("BAG_LIMIT_PET") then
        L_FlyMsgManager:showNormalMsgByKey("notice_pagePetGet_01")
        return
      end
      L_PetStore:onClickHatchOutPetEgg(self.data.bldUid, self.data.eggUid)
      L_UI:close(self.pageName)
    end,
    onClick_close = function(self)
      L_UI:close(self.pageName)
    end,
    onClick_lockPetFunction = function(self)
      local pet = L_PetStore:getPetItem(self.data.info.guid)
      if pet.is_lock == true then
        L_PetStore:req_lockPet(self.data.info.guid, false, function()
          L_FlyMsgManager:showNormalMsgByKey("notice_pagePetGet_02")
          self.bind.lockPetImageColor = CS.UnityEngine.Color(1, 1, 1, 0.3)
        end)
      else
        L_PetStore:req_lockPet(self.data.info.guid, true, function()
          L_FlyMsgManager:showNormalMsgByKey("notice_pagePetGet_03")
          self.bind.lockPetImageColor = CS.UnityEngine.Color(1, 1, 1, 0.8)
        end)
      end
    end,
    onClick_openSelectItemList = function(self)
      if not L_SystemUnlockManager:checkAndTip(L_SystemConst.enum.petBox) then
        return
      end
      local pet = self.data.info
      if pet then
        L_UI:open("pagePetBoxSelect", {
          initBoxIndex = self.curBoxIndex,
          callback = function(boxIndex)
            self.curBoxIndex = boxIndex
            self:reqSetPetBox()
          end
        })
      end
    end,
    onClick_formation = function(self)
      L_SystemBreakManager:jumpTo(L_SystemConst.enum.formation, {dontBack2RootWhenClose = true})
    end,
    onClick_detail = function(self)
      L_UI:open("pagePet", {
        petId = self.data.info.guid
      })
    end,
    onClick_geneDetailDown = function(self)
      self.pageTipBuddleOpen = L_UI:checkPageOpen("pageTipBubble")
    end,
    onClick_geneDetailUp = function(self)
      if table.isEmpty(self.geneData) then
        return
      end
      if not self.pageTipBuddleOpen then
        local factor = #self.geneData % 2 == 1
        local deltaY = -100
        L_UI:open("pageTipBubble", {
          data = {
            modulePetGeneSkillsTips_Path,
            modulePetGeneSkillsTips,
            self.geneData,
            self.bindComponents.listRect,
            0,
            true,
            1,
            C_Vector2(30, 27),
            C_Vector2(150, 0),
            C_Vector3(0, deltaY, 0)
          }
        })
      else
        L_UI:close("pageTipBubble")
      end
    end
  }
end

function page:preOpen(options)
  page.super.preOpen(self, options)
  self._closeCallback = options.closeCallback
  self.voiceCallBack = options.voiceCallBack
  self.showType = options.showType and options.showType or L_Const.getPetShowType.short
  self.data.bFromHatch = options.bFromPetHatch
  self.data.bldUid = options.bldUid
  self.data.info = options.pet
  self.bind.show_new = options.isNew and true or false
  self.animator = nil
  local signalListener = self.bindComponents.pageRoot:GetComponent(typeof(C_TimelineSignalListener))
  if signalListener then
    signalListener:SetHandler(handler(self, self.timelineSignalListener))
  end
  L_PetManager:loadPetGetScene()
  L_PetManager:loadPetGetModel(self.data.info.id, self.data.info:getIsSpecialPet(), self.data.info:hasFlashGene())
  local playableDirector = self.bindComponents.playableDirector
  local beginTime = showTypeBeginTime[self.showType]
  playableDirector.time = beginTime
  L_PetManager:setPlayableDirectorTime(beginTime)
  if options.texture then
    self.bindComponents.textureBg.texture = options.texture
  end
  L_PetManager:setPetBlackRootColor(C_Color(0, 0, 0, 1))
  self:initPage()
  if self.voiceCallBack then
    self.voiceCallBack()
  end
  L_UI:close("pageExclusive")
end

function page:open()
  self.pageTipBuddleOpen = false
  self.bind.timelineMask = true
end

function page:show()
  L_PetManager:setPetGetActive(true)
  if self.hasHide then
    local playableDirector = self.bindComponents.playableDirector
    local beginTime = showTypeBeginTime[self.showType]
    playableDirector.time = beginTime
    L_PetManager:setPlayableDirectorTime(beginTime)
    self.hasHide = false
  end
end

function page:hide()
  L_PetManager:setPetGetActive(false)
  self.hasHide = true
  self.bind.timelineMask = false
end

function page:alphaTween()
  if L_CommonUtil.isValid(self._doTween) then
    self._doTween:Kill()
    self._doTween = nil
  end
  local target = 0
  local getter1 = function()
    return 1
  end
  local setter1 = function(r)
    L_PetManager:setPetBlackRootColor(C_Color(0, 0, 0, r))
  end
  self._doTween = DOTween.To(getter1, setter1, target, 0.033)
end

function page:initPage()
  self:moduleBoxItemList()
  self.bind.pet_name = self.data.info.pet_name
  self.bind.pet_lv = tostring(self.data.info.lv)
  self.bind.pet_maxLv = string.format("/%d", L_PetStore:getPetMaxLevel(true))
  local petHomeTalentTpl = _petHomeTalentTpl:getTplById(self.data.info.id)
  local petSize = _petHomeTalentTpl:getSizeType(petHomeTalentTpl)
  local petHomeSizeTpl = _petHomeSizeTpl:getTplById(petSize)
  self.bind.pet_height = _petHomeSizeTpl:getSizeName(petHomeSizeTpl)
  self.modules.modulePetBoxRating:setGuid(self.data.info.guid, true)
  self.modules.modulePetNewSimpleTags:setGuid(self.data.info.guid, false)
  local topRankComprehension = L_PetStore:getRangeValueComprehension(false, 8, self.data.info.comprehension)
  local property = L_PetStore:getPetOriginalProperty(self.data.info)
  local gradeIndex = gradeRank[property.gradeRank]
  local gradeRankName = string.format("rank_%d", gradeIndex)
  local tpl = petTpl:getTplById(self.data.info.id)
  self.bindComponents.kiboCard_1:LoadSprite(petTpl:getKiboBoxCardIcon(tpl, 5, self.data.info:isSpecialPet()), false)
  self.bindComponents.kiboCard_2:LoadSprite(petTpl:getKiboBoxCardIcon(tpl, 5, self.data.info:isSpecialPet()), false)
  self.bind[gradeRankName] = true
  self.bind.petPropertyList:clear()
  local propertyData = {}
  local all_Attribute = petLearningEnumTpl:getAllEnum(true)
  for i, v in ipairs(all_Attribute) do
    local enumId = petLearningEnumTpl:getEnumNum(v)
    local id = 0
    for n, k in pairs(topRankComprehension) do
      if k.attr_id == enumId then
        id = k.rankId
        break
      end
    end
    table.insert(propertyData, {
      attrIcon = petLearningEnumTpl:getIcon(petLearningEnumTpl:getTplByEnumId(enumId)),
      value = battleInfoTpl:getShowTxtComma(enumId, L_PetStore:getPetAttFinalValue(property, enumId, self.data.info.guid)),
      name = petLearningEnumTpl:getName(petLearningEnumTpl:getTplByEnumId(enumId)),
      attrId = id
    })
  end
  self.bind.petPropertyList:insert_array(propertyData)
  self.modules.modulePetBoxRating:playAnim()
  self.bind.petGetGeneList:clear()
  local genelist = L_PetStore:getPetSkills(self.data.info, false, true, false)
  table.sort(genelist, function(a, b)
    return a.rarity > b.rarity
  end)
  local topGene
  if #genelist == 2 then
    table.reverse(genelist)
  elseif #genelist == 3 then
    topGene = genelist[1]
    local tmpTable = {}
    for i, v in ipairs(genelist) do
      if i ~= 1 then
        table.insert(tmpTable, v)
      end
    end
    table.insert(tmpTable, 2, topGene)
    genelist = tmpTable
  elseif 4 <= #genelist then
    topGene = genelist[1]
    local thirdGene = genelist[3]
    local tmpTable = {}
    for i, v in ipairs(genelist) do
      if i ~= 1 and i ~= 3 then
        table.insert(tmpTable, v)
      end
    end
    table.insert(tmpTable, 1, thirdGene)
    table.insert(tmpTable, 4, topGene)
    genelist = tmpTable
  end
  self.bind.petGetGeneList:insert_array(genelist)
  self.geneData = genelist
  self:openTickTimer()
  self:refreshHomeLaborTag()
end

function page:openTickTimer()
  self.initTime = 8
  self.bind.go_time = true
  local func = function()
    self.initTime = self.initTime - 1
    if self.initTime > 0 then
      self.bind.txt_time = L_WordsTpl:getValue("ui_get_kibo_continue", {
        [0] = self.initTime
      })
    else
      self.bind.txt_time = wordsTpl:getValue("ui_get_kibo_close")
      L_TimerManager:clearTimer(self)
    end
  end
  L_TimerManager:newOrResetTimer(self, "timeTick", func, 1, -1)
  func()
end

function page:timelineSignalListener(signalMsg)
  if signalMsg == "PlayAnim" then
    self.bind.timelineMask = false
    L_PetManager:playPetPersonalShow()
    L_TimerManager:newOrResetTimer(self, "delayBlack", function()
      self:alphaTween()
    end, 0.033)
  end
end

function page:moduleBoxItemList()
  local boxId = self.data.info.box_id
  self.curBoxIndex = boxId // 100
  local boxNameIndex = L_PetStore:getPetBoxNameList()
  self.bind.selectBoxName = boxNameIndex[self.curBoxIndex]
end

function page:refreshContinueHatchShow()
  if not self.data.bFromHatch then
    self.bind.active_btn_continueHatch = false
    return
  end
  if L_ProductManager:isProductRewarded(self.data.bldUid) then
    self.bind.active_btn_continueHatch = true
    local products = L_ProductStore:getHomeProduct(self.data.bldUid)
    local product = products[1]
    local sp = L_ProductManager:getProductSpecialParams(self.data.bldUid, product.product_guid)
    if not sp then
      errorf("\229\173\181\229\140\150\229\143\176\229\173\181\229\140\150\230\149\176\230\141\174\230\156\137\233\151\174\233\162\152" .. self.data.bldUid .. " " .. product.product_guid)
    end
    self.data.eggUid = sp.extra_guid
    return
  end
  self.bind.active_btn_continueHatch = false
end

function page:reqSetPetBox()
  local pet = L_PetStore:getPetItem(self.data.info.guid)
  if pet == nil then
    return
  end
  local _, slot = L_PetStore:getPetBoxIsFull(self.curBoxIndex)
  local box_id = self.curBoxIndex * 100 + slot
  L_PetStore:req_CSSetPetBox(self.data.info.guid, box_id)
end

function page:closeDoTween()
  if L_CommonUtil.isValid(self._doTween) then
    self._doTween:Kill()
    self._doTween = nil
  end
  if self.mutationTimer then
    Timer.remove(self.mutationTimer)
    self.mutationTimer = nil
  end
  L_TimerManager:clearTimer(self)
end

function page:close(options)
  page.super.close(self, options)
  if self.timer then
    self.timer:destroy()
    Timer.remove(self.timer)
    self.timer = nil
  end
  self:closeDoTween()
  if self.animator then
    self.animator.stateNotify:Remove(handler(self, self.stateNotifyFunc))
  end
  L_RewardManager:showBattlePage(nil, L_Const.FightRewardReason.FRR_Catch)
  L_PetManager:removePetGetScene()
  if self._closeCallback then
    self._closeCallback()
  end
end

function page:refreshHomeLaborTag()
  local petGuid = self.data.info.guid
  local C_HomeManager = AzurWorld.HomeMgr
  local C_PetStore = C_HomeManager:GetPetStore()
  local C_PetData = C_PetStore:GetPet(petGuid)
  local C_LaborInfoList = C_PetData:GetLaborInfoList()
  local showParamsList = {}
  for i = 0, C_LaborInfoList.Count - 1 do
    local C_LaborInfo = C_LaborInfoList[i]
    local C_TalentIds = C_PetData.talentIds
    local talentId
    if 0 < C_TalentIds.Count then
      talentId = C_TalentIds[0]
    end
    local showParams = {
      petId = C_PetData.configId,
      laborId = C_LaborInfo.laborId,
      laborGrade = C_LaborInfo.laborGrade,
      talentId = talentId
    }
    table.insert(showParamsList, showParams)
  end
  self.bind.list_petHomeLaborTag:clear()
  self.bind.list_petHomeLaborTag:insert_array(showParamsList)
end

return page
