local this = {}
local _petLearingEnumTpl = L_GameTpl:getPetLearingEnumTpl()
local _homeCollectionWorkLimitTpl = L_GameTpl:getHomeCollectionWorkLimitTpl()
local _commonConditionTpl = L_GameTpl:getCommonConditionTpl()

function this:req_hatchPetEgg(bldGuid, eggGuid, callback)
  local data = {build_guid = bldGuid, egg_guid = eggGuid}
  L_Net:sendMessage(MsgGenCode.CSProtoHatchPetEgg, data, function(rspData)
    if not rspData and callback then
      callback()
    end
  end)
end

function this:req_hatchOutPetEgg(bldGuid, egg_guid, callback)
  local productGuid = L_ProductManager:getProductGuidBySpecialGuid(bldGuid, egg_guid)
  L_ProductStore:req_CSProtoProductFinishOne(bldGuid, productGuid, function(rspData, errorCode)
    if 0 < errorCode then
      L_UI:close("pageExclusive")
      return
    end
    if rspData.reward then
      local reward = rspData.reward.rewards
      for _, commonItem in ipairs(reward) do
        local entity = L_PetStore:getPetItem(commonItem.guid)
        if entity then
          L_PetManager:setPetEntitybuffer(entity)
        else
          errorf("\230\156\170\230\139\191\229\136\176\232\175\165\229\174\160\231\137\169\228\191\161\230\129\175 guid = " .. tostring(commonItem.guid))
        end
      end
      if callback then
        callback()
      end
    end
  end)
end

function this:onClickHatchOutPetEgg(bldUid, eggUid)
  print("\232\175\183\230\177\130\233\162\134\229\143\150\229\173\181\232\155\139")
  if L_PetStore:getPetListCount() >= L_GameTpl:getGameConstTpl():getValue("BAG_LIMIT_PET") then
    L_FlyMsgManager:showNormalMsgByKey("notice_pagePetGet_01")
    return
  end
  L_UI:open("pageExclusive", {
    openCbk = function()
      if L_HomeUtil.isInHome() then
        L_PetStore:playGetPetAnim(bldUid, eggUid)
      else
        L_PetStore:skipHatchOutEggTimeline(bldUid, eggUid)
      end
    end,
    skipCbk = function()
      L_PetStore:skipHatchOutEggTimeline(bldUid, eggUid)
    end
  })
end

function this:playGetPetAnim(bldGuid, eggUid)
  if self.timeLineObj then
    return
  end
  if self.timeLineObj == nil then
    self.timeLineObj = require("ui.manager.timeline.commonTimelinePrefabHandle").new()
    
    function self.timeLineObj.timelineLoadedHandle()
      local manager = AzurWorld.HomeMgr
      local bldEntity = manager:GetHomeBuild(bldGuid)
      if bldEntity == nil then
        return
      end
      local trans = bldEntity.buildNode
      self.timeLineObj:setParent(trans)
      self.timeLineObj:setWorldRotation(L_PlayerManager:getMainControlEntityRot() + L_Vector3.new(0, 180, 0))
      self.timeLineObj:setLocalPosition(L_Vector3.new(0, 0.45, 0))
      self.timeLineObj:playTimelineAsset()
      L_HomeUtil.focusBuild(bldGuid)
    end
    
    if self.timer then
      Timer.remove(self.timer)
      self.timer = nil
    end
    self.timer = Timer.once(3.5, function()
      self:skipHatchOutEggTimeline(bldGuid, eggUid)
    end, self)
  end
  self.timeLineObj:loadTimelinePrefab("EggHatch/pre_egghatch")
end

function this:skipHatchOutEggTimeline(bldGuid, eggUid)
  if self.timer then
    Timer.remove(self.timer)
    self.timer = nil
  end
  L_PetStore:req_hatchOutPetEgg(bldGuid, eggUid, function()
    local entityList = L_PetManager:getPetEntitybuffer()
    for i, v in pairs(entityList) do
      local entity = L_PetStore:getPetItem(v.guid)
      if entity then
        local options = {
          pet = entity,
          bFromPetHatch = true,
          bldUid = bldGuid,
          closeCallback = function()
            L_UI:close("pageExclusive")
          end
        }
        L_PetManager:commonGetPet(options, true)
      end
    end
    L_PetManager:clearPetEntitybuffer()
  end)
end

function this:clearTimeLineObj()
  if self.timeLineObj then
    self.timeLineObj:dispose()
    self.timeLineObj = nil
    if self.timer then
      Timer.remove(self.timer)
      self.timer = nil
    end
  end
  if L_HomeUtil.isInHome() then
    L_HomeUtil.focusBuild(0)
  end
end

function this:req_cancelHatchPetEgg(bldGuid, egg_guid, callback)
  local productGuid = L_ProductManager:getProductGuidBySpecialGuid(bldGuid, egg_guid)
  L_ProductManager:reqCancelProduct(bldGuid, productGuid, function(rspData)
    if callback and not rspData then
      callback()
    end
  end)
end

function this:req_changeLvUpPet(petId, items, callback)
  local data = {pet_id = petId, items = items}
  L_Net:sendMessage(MsgGenCode.CSProtoLvUpPet, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc then
      local params = {}
      self:call(self.event.petComprehensionLvUp)
      if callback then
        callback()
      end
      if rspData.rewards then
        local data = rspData.rewards
        data.title = L_WordsTpl:getValue("notice_spiritronStore")
        L_RewardManager:showPage(data, rspData.src)
      end
    end
  end)
end

function this:req_changeRankUpPet(data, callback)
  L_Net:sendMessage(MsgGenCode.CSProtoRankUpPet, data, callback)
end

function this:req_changePetName(name, guid, callback)
  local data = {pet_name = name, guid = guid}
  L_Net:sendMessage(MsgGenCode.CSProtoPetChangeName, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc then
      if callback then
        callback()
      end
    elseif errorCode == L_Const.errorCode.ErrCodeInvalidNick then
      L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_idcard_4"))
    elseif callback then
      callback("error_name")
    end
  end)
end

function this:req_changePetBoxName(name, index, callback)
  local data = {box_name = name, box = index}
  L_Net:sendMessage(MsgGenCode.CSProtoPetChangeName, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback()
    end
  end)
end

function this:req_removePet(data, callback)
  L_Net:sendMessage(MsgGenCode.CSProtoDelPet, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc then
      if not table.isEmpty(rspData.rewards) then
        L_RewardManager:showPage(rspData.rewards, rspData.src)
      end
      if callback then
        callback()
      end
    end
  end)
end

function this:req_removePetEgg(data, callback)
  L_Net:sendMessage(MsgGenCode.CSProtoDelEgg, data, callback)
end

function this:req_chooseGeneMutation(uid, bAccept, callback)
  local data = {pet_guid = uid, is_accept = bAccept}
  L_Net:sendMessage(MsgGenCode.CSProtoChoseMutation, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback()
    end
  end)
end

function this:req_CSProtoPetBreed(data, callback)
end

function this:req_lockPet(petGuid, operation, callback)
  local data = {guid = petGuid, lock_operate = operation}
  L_Net:sendMessage(MsgGenCode.CSProtoPetLock, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback()
    end
  end)
end

function this:req_lockPetEgg(petEggGuid, operation, callback)
end

function this:req_getFriendRentPet(callback)
  L_Net:sendMessage(MsgGenCode.CSProtoLendFriendPet, nil, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback(rspData)
    end
  end)
end

function this:req_getFriendComplexPetInfo(pid, callback)
  local data = {friend_pid = pid}
  L_Net:sendMessage(MsgGenCode.CSProtoGetComplexInfo, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc and callback and rspData.complex_info ~= nil then
      callback(rspData.complex_info)
    end
  end)
end

function this:req_getRentPetRewards(callback)
  L_Net:sendMessage(MsgGenCode.CSProtoGetRentPetReward, nil, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc then
      if not table.isEmpty(rspData.rewards) then
        L_RewardManager:showPage(rspData.rewards, rspData.src)
      end
      if callback then
        callback()
      end
    end
  end)
end

function this:req_getRentPetInfo(callback)
  L_Net:sendMessage(MsgGenCode.CSProtoGetRentPetInfo, nil, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback(rspData)
    end
  end)
end

function this:req_CSProtoPetStationed(petGuid, type, buildGuid, sourceBuild, isOutHomeHub, callback)
  local canReq = self:checkIfCanReqPetStationed(petGuid, type, buildGuid, sourceBuild)
  if not canReq then
    return
  end
  local data = {
    pet_guid = petGuid,
    build_type = type,
    build_guid = buildGuid,
    source_build = sourceBuild or 0,
    out_hub = isOutHomeHub and true or false
  }
  L_Net:sendMessage(MsgGenCode.CSProtoPetStationed, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc then
      if callback then
        callback()
      end
      self:call(self.event.refreshBuildingPet)
    end
  end)
end

function this:checkIfCanReqPetStationed(petGuid, petStationedWorkStatusType, buildGuid, sourceBuild)
  if petStationedWorkStatusType == L_Const.PetStationedWorkStatusType.PSWST_WILD_REST then
    local petItem = L_PetStore:getPetItem(petGuid)
    if petItem:isWorking() and petItem:getWorkBuilding() == buildGuid then
      return true
    end
    local curPetStationedNum = L_HomeStore:getCurPetStationedNum()
    local unlockedPetStationedNum = L_HomeStore:getUnlockedPetStationedNum()
    local csPetData = L_PetStore:getCsPetData(petGuid)
    local isPetInHomeHub = csPetData:GetIsInHomeHub()
    if not isPetInHomeHub and curPetStationedNum == unlockedPetStationedNum then
      L_FlyMsgManager:showNormalMsg(L_Lang:get(L_WordsTpl:getValue("notice_moduleHomeCenterPet")))
      return false
    end
    local curWorkingNum = AzurWorld.HomeMgr:GetCurWorkingNumOfCollectionBuilding()
    local maxWorkingNum = _homeCollectionWorkLimitTpl:getCurMaxWorkingNum()
    local collectionId = buildGuid
    local csHomeStore = L_HomeStore:getCsHomeStore()
    local csHomeBuildData = csHomeStore:GetCollectBuildDataByCollectionId(collectionId)
    local isWildBuildWorking = csHomeBuildData and csHomeBuildData.collect and csHomeBuildData.collect.IsWorking
    if isWildBuildWorking then
      return true
    elseif curWorkingNum >= maxWorkingNum then
      local conditionGroupList = _homeCollectionWorkLimitTpl:getAllConditionGroup()
      local hasImproveSpace = false
      local targetConditionGroup
      for _, conditionGroup in pairs(conditionGroupList) do
        if L_ConditionManager:isComplete(conditionGroup) == false then
          hasImproveSpace = true
          targetConditionGroup = conditionGroup
          break
        end
      end
      if hasImproveSpace then
        local targetCondition = targetConditionGroup[1]
        local commonConditionConfigId = targetCondition[1]
        local conditionParam = targetCondition[2]
        local commonConditionTpl = _commonConditionTpl:getTplById(commonConditionConfigId)
        local conditionDescShowKey = _commonConditionTpl:getDescShowKey(commonConditionTpl)
        local conditionNodeCls = L_ConditionManager:getCls(commonConditionConfigId)
        local conditionDescShowKeyWithConditionParam = conditionNodeCls.descFunc and conditionNodeCls.descFunc(conditionDescShowKey, targetCondition) or conditionDescShowKey .. tostring(conditionParam)
        L_FlyMsgManager:showNormalMsg("ui_home_collectionbuilding_nextlimit", {
          [0] = conditionDescShowKeyWithConditionParam
        })
      else
        L_FlyMsgManager:showNormalMsg(L_Lang:get(L_WordsTpl:getValue("ui_home_collectionbuilding_reachlimit")))
      end
      return false
    else
      return true
    end
  end
  return true
end

function this:req_CSSetPetBox(petGuid, box_id, callback)
  local data = {guid = petGuid, box_id = box_id}
  L_Net:sendMessage(MsgGenCode.CSProtoSetPetBoxInfo, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback()
    end
  end)
end

function this:req_CSExchangePetBoxId(petGuid, targetPetGuid, callback)
  local data = {guid = petGuid, target_guid = targetPetGuid}
  L_Net:sendMessage(MsgGenCode.CSProtoExchangePetBoxId, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback()
    end
  end)
end

function this:req_CSProtoOrderPetBoxInfo(boxIndex, callback)
  local data = {box = boxIndex}
  L_Net:sendMessage(MsgGenCode.CSProtoOrderPetBoxInfo, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc then
      if callback then
        callback()
      end
      self:call(self.event.refreshSinglePetBox, boxIndex)
    end
  end)
end

function this:req_CSProtoPetEatAttrFruit(preUseFruitInfoList, petGuid, callback)
  local items = {}
  for _, preUseFruitInfo in pairs(preUseFruitInfoList) do
    local item = {
      item_id = preUseFruitInfo.itemId,
      item_num = preUseFruitInfo.itemNum
    }
    table.insert(items, item)
  end
  local data = {pet_id = petGuid, items = items}
  L_Net:sendMessage(MsgGenCode.CSProtoLvUpComprehension, data, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc then
      local params = {}
      params.attrId = 1
      self:call(self.event.petComprehensionLvUp, params)
      if callback then
        callback()
      end
    end
  end)
end

function this:rsp_syncPetEggItem(info)
  if info.eggs and not table.isEmpty(info.eggs) then
    for i = 1, #info.eggs do
      local entity = self:getPetEggItem(info.eggs[i].guid, true)
      entity:populate(info.eggs[i])
    end
  end
  if not table.isEmpty(info.guid) then
    self:removePetEgg(info.guid)
  end
end

function this:rsp_syncPetFreeRewardNum(freeRewardNum)
  self.data.free_reward_num = freeRewardNum
end

function this:rsp_syncPet(info)
  self:syncPetItem(info.pets, info.add_guid)
  if not table.isEmpty(info.guid) then
    self:removePet(info.guid)
  end
end

function this:syncPetItem(data, addGuid)
  local genMutationInfo = {}
  if data and not table.isEmpty(data) then
    local petInfoTpl = L_GameTpl:getPetTpl()
    local refreshBox = {}
    for i = 1, #data do
      if self.data.setHasInitSync and not self:getPetItem(data[i].guid) then
        L_ReddotManager:markNew(L_ReddotManager.DotDef.PetNew, data[i].guid)
      end
      local entity = self:getPetItem(data[i].guid, true)
      local pet_tpl = petInfoTpl:getTplById(data[i].config_id)
      if not pet_tpl then
        errorf("\230\178\161\230\156\137\232\175\165\229\174\160\231\137\169\231\154\132\233\133\141\231\189\174" .. data[i].config_id)
        printf("\229\141\143\232\174\174", data[i])
      end
      if data[i].gene_infos == nil then
        data[i].gene_infos = {}
      end
      if data[i].pet_name == "" or data[i].pet_name == nil then
        local pet_name = petInfoTpl:getName(pet_tpl, data[i].color)
        entity.pet_name = pet_name
      else
        entity.pet_name = data[i].pet_name
      end
      local petChanged = false
      local serverPetConfigId = data[i].config_id or 0
      if not math.isEmpty(entity.id) and not math.isEmpty(serverPetConfigId) and entity.id ~= serverPetConfigId then
        petChanged = true
      end
      local needRefreshFormation = false
      local refreshHeroId, refreshPetId
      local oldHeroId = entity.hero_id or 0
      local newHeroId = data[i].hero_id or 0
      local heroChanged = oldHeroId ~= newHeroId
      if not heroChanged and not math.isEmpty(newHeroId) and petChanged then
        needRefreshFormation = true
        refreshHeroId = newHeroId
        refreshPetId = data[i].guid
      end
      local petLvChanged = false
      local oldLv = entity.lv or 0
      local newLv = data[i].lv or 0
      if oldLv < newLv then
        self:call(self.event.petLevelUp, {
          petId = data[i].guid,
          oldLv = oldLv,
          newLv = newLv
        })
        if oldLv ~= 0 then
          L_BattleDataManager:setLevelSettleData(L_Const.roleType.pet, data[i].guid, "levelUp")
        end
        petLvChanged = true
      end
      entity.guid = data[i].guid
      entity.id = data[i].config_id
      entity.comprehension = data[i].comprehension or nil
      entity.skillSlotInfo = self:getNewSkillSlotInfo(data[i], entity.skillSlotInfo, addGuid)
      entity.skills = data[i].inherent_skills or {}
      entity.feature = data[i].feature
      entity.lv = data[i].lv
      entity.exp = data[i].exp
      entity.rank = data[i].rank
      entity.hero_id = data[i].hero_id
      entity.petId = data[i].config_id
      entity.gene_value = self:getPetGeneValue(data[i].gene_infos, data[i].gene_state)
      entity.is_lock = data[i].is_lock
      entity.race = petInfoTpl:getRace(pet_tpl)
      entity.element = petInfoTpl:getElement(pet_tpl)
      if not table.isEmpty(data[i].mutation_info) and 0 < data[i].mutation_info.pos then
        L_ReddotManager:markNew(L_ReddotManager.DotDef.PetGeneMutation, data[i].guid)
      end
      if entity.gene_infos and #entity.gene_infos > 0 then
        if not table.isEmpty(data[i].mutation_info) and 0 < data[i].mutation_info.pos and (table.isEmpty(entity.mutation_info) or 0 >= entity.mutation_info.pos) then
          table.insert(genMutationInfo, {
            guid = data[i].guid,
            pos = data[i].mutation_info.pos,
            gene_id = data[i].mutation_info.gene_id,
            isNew = false
          })
        end
        if #entity.gene_infos < #data[i].gene_infos then
          for _, geneInfo in pairs(data[i].gene_infos) do
            local bNew = true
            for _, entityGeneInfo in pairs(entity.gene_infos) do
              if geneInfo.pos == entityGeneInfo.pos then
                bNew = false
                break
              end
            end
            if bNew then
              local bRecorded = false
              local bMutation = false
              for _, v in ipairs(genMutationInfo) do
                if v.guid == data[i].guid then
                  bRecorded = true
                  if v.pos == geneInfo.pos then
                    bMutation = true
                  end
                  break
                end
              end
              if not bMutation then
                local keyString = L_PetStore:getPetGeneMutationNewSaveKeyByPos(data[i].guid, geneInfo.pos)
                C_PlayerPrefsUtility.SetInt(keyString, geneInfo.pos)
              end
              if not bRecorded then
                table.insert(genMutationInfo, {
                  guid = data[i].guid,
                  pos = geneInfo.pos,
                  gene_id = geneInfo.gene_id,
                  isNew = true
                })
              end
              local keyNewString = L_PetStore:getPetGeneMutationNewSaveKey(data[i].guid)
              C_PlayerPrefsUtility.SetInt(keyNewString, geneInfo.pos)
              L_ReddotManager:markNew(L_ReddotManager.DotDef.PetGeneMutation, data[i].guid)
            end
          end
        end
      end
      entity.gene_state = data[i].gene_state
      entity.gene_infos = data[i].gene_infos
      entity.mutation_info = data[i].mutation_info
      entity.ur_pos = data[i].ur_pos
      entity.speed = data[i].speed or 0
      entity.work_status = data[i].work_status
      entity.work_build = data[i].work_build
      entity.talent_id = data[i].talent_id or {}
      entity.capacity_id = data[i].capacity_id
      entity.box_id = data[i].box_id
      entity.roulette_pos = data[i].roulette_pos
      entity.satiety_val = data[i].satiety_val or 0
      entity.canteen_id = data[i].canteen_id
      entity.work_pause = data[i].work_pause
      entity.satiety = entity.satiety_val
      entity.work_start_time = data[i].work_start_time
      local petFlashChanged = false
      local oldFlashParam = entity.special == L_Const.PetSpecialType.PST_FLASH or entity.special == L_Const.PetSpecialType.PST_FLASH_COLOR
      local newFlashParam = data[i].special == L_Const.PetSpecialType.PST_FLASH or data[i].special == L_Const.PetSpecialType.PST_FLASH_COLOR
      if oldFlashParam ~= newFlashParam then
        petFlashChanged = true
      end
      entity.special = data[i].special or 0
      entity.catch_item = data[i].catch_item
      entity.grade = data[i].grade
      entity.base_lv = data[i].base_lv
      entity.color = data[i].color
      entity.laborInfoList = {}
      if data[i].labor_infos then
        for _, laborInfo_proto in pairs(data[i].labor_infos) do
          local laborInfo = {}
          laborInfo.laborId = laborInfo_proto.labor_id
          laborInfo.laborGrade = laborInfo_proto.labor_grade
          table.insert(entity.laborInfoList, laborInfo)
        end
      end
      if math.isEmpty(entity.base_lv) then
        entity.base_lv = 1
      end
      local oldFavorLv = entity.favor_lv or 0
      entity.favor_val = data[i].favor_val or 0
      entity.favor_lv = data[i].favor_lv or 0
      local dailyFavorList = data[i].daily_favor_val
      if not table.isEmpty(dailyFavorList) then
        local isFavorLvUp = oldFavorLv < entity.favor_lv
        for _, value in ipairs(dailyFavorList) do
          local dailyFavorInfo = value
          local sourceType = dailyFavorInfo.source_type
          if sourceType == L_Const.FavorSourceType.FST_BATTLE then
            if isFavorLvUp then
              L_BattleDataManager:setLevelSettleData(L_Const.roleType.pet, data[i].guid, "favorLevelUp")
            end
          elseif sourceType == L_Const.FavorSourceType.FST_FOOD and isFavorLvUp then
            self:call(self.event.refreshPetFavorLvUp, {
              petGuid = data[i].guid,
              oldFavorLv = oldFavorLv,
              newFavorLv = entity.favor_lv
            })
          end
        end
      end
      refreshBox = self:setInsertBox(data[i].box_id, data[i].guid, refreshBox)
      self:call(self.event.refreshPet, entity)
      if needRefreshFormation and AzurWorld.playerMgr and AzurWorld.playerMgr.myPlayerUnitAdapter then
        AzurWorld.playerMgr.myPlayerUnitAdapter:RecreateFormationEntity(0, refreshPetId)
      end
      if not math.isEmpty(entity.hero_id) and petLvChanged then
        L_PlayerManager:refreshPetEntityLevel(entity.guid)
      end
      if not math.isEmpty(entity.hero_id) and petFlashChanged then
        L_PlayerManager:refreshPetEntityFlashParam(entity.guid)
      end
    end
    if not table.isEmpty(refreshBox) then
      self:call(self.event.refreshPetBox, refreshBox)
    end
  end
  if 0 < #genMutationInfo then
    local formationType = L_FormationManager:getCurFormationType()
    table.sort(genMutationInfo, function(a, b)
      local indexA = L_FormationStore:getPetPlaceInTeam(formationType, nil, a.guid)
      local indexB = L_FormationStore:getPetPlaceInTeam(formationType, nil, b.guid)
      if indexA < 0 then
        errorf("\228\184\141\229\156\168\231\188\150\233\152\159\233\135\140\231\154\132\229\165\135\230\179\162\229\143\145\231\148\159\228\186\134\229\159\186\229\155\160\231\170\129\229\143\152 guid = " .. tostring(a.guid))
      end
      if indexB < 0 then
        errorf("\228\184\141\229\156\168\231\188\150\233\152\159\233\135\140\231\154\132\229\165\135\230\179\162\229\143\145\231\148\159\228\186\134\229\159\186\229\155\160\231\170\129\229\143\152 guid = " .. tostring(b.guid))
      end
      return indexA < indexB
    end)
    for _, v in ipairs(genMutationInfo) do
      L_FlyMsgManager:showPetGeneMutationTip(v)
    end
  end
end

function this:rsp_syncTrialPetItem(data)
  if table.isEmpty(data) then
    return
  end
  local petInfoTpl = L_GameTpl:getPetTpl()
  local petInterimTpl = L_GameTpl:getPetInterimTpl()
  for i = 1, #data do
    local trialId = C_DataUtil.GetUuid2ConfigId(data[i].guid)
    local tpl_trial = petInterimTpl:getTplById(trialId)
    if not tpl_trial then
      errorf("\230\178\161\230\156\137\232\175\165\232\175\149\231\148\168\229\174\160\231\137\169\231\154\132\233\133\141\231\189\174" .. trialId)
    end
    local entity = self:getPetItem(data[i].guid, true)
    local pet_tpl = petInfoTpl:getTplById(data[i].config_id)
    if not pet_tpl then
      errorf("\230\178\161\230\156\137\232\175\165\229\174\160\231\137\169\231\154\132\233\133\141\231\189\174" .. data[i].config_id)
      printf("\229\141\143\232\174\174", data[i])
    end
    if data[i].gene_infos == nil then
      data[i].gene_infos = {}
    end
    if data[i].pet_name == "" or data[i].pet_name == nil then
      local pet_name = petInfoTpl:getName(pet_tpl, data[i].color)
      entity.pet_name = pet_name
    else
      entity.pet_name = data[i].pet_name
    end
    entity.guid = data[i].guid
    entity.id = petInterimTpl:getPetId(tpl_trial)
    local param = petInterimTpl:getParam(tpl_trial)
    entity.comprehension = {}
    for _, att in pairs(param) do
      local id, value = table.unpack(att)
      table.insert(entity.comprehension, {attr_id = id, value = value})
    end
    entity.skills = data[i].inherent_skills or {}
    entity.feature = petInterimTpl:getFeature(tpl_trial)
    entity.lv = petInterimTpl:getPetLevel(tpl_trial)
    entity.speed = petInterimTpl:getSpeed(tpl_trial)
    entity.petId = petInterimTpl:getPetId(tpl_trial)
    entity.grade = petInterimTpl:getPetGrade(tpl_trial)
    entity.exp = 0
    entity.rank = 1
    entity.box_id = 0
    entity.roulette_pos = 0
    entity.is_lock = false
    entity.hero_id = data[i].hero_id
    entity.gene_value = self:getPetGeneValue(data[i].gene_infos, data[i].gene_state)
    entity.race = petInfoTpl:getRace(pet_tpl)
    entity.element = petInfoTpl:getElement(pet_tpl)
    entity.gene_state = data[i].gene_state
    entity.gene_infos = data[i].gene_infos
    entity.work_status = data[i].work_status
    entity.work_build = data[i].work_build
    entity.talent_id = data[i].talent_id or {}
    entity.capacity_id = data[i].capacity_id
    entity.satiety_val = data[i].satiety_val or 0
    entity.canteen_id = data[i].canteen_id
    entity.work_pause = data[i].work_pause
    entity.satiety = entity.satiety_val
    entity.work_start_time = data[i].work_start_time
    entity.special = data[i].special or 0
    entity.catch_item = data[i].catch_item
    entity.base_lv = data[i].base_lv
    entity.color = data[i].color
    if math.isEmpty(entity.base_lv) then
      entity.base_lv = 1
    end
    entity.favor_val = data[i].favor_val or 0
    entity.favor_lv = data[i].favor_lv or 0
  end
end

function this:rsp_syncPetInfos(data)
  local attr = self:getPetAttrInfo(data.hero_guid)
  if data.modules then
    for _, module in ipairs(data.modules) do
      attr:addModule(module)
    end
    attr:updateAttrMap()
    attr:updateSkillMap()
    L_PlayerManager:refreshMountData(data.hero_guid)
    L_PlayerManager:refreshPetEntityData(data.hero_guid)
  end
end

function this:setFreeEggRewardNum(num)
  if num ~= nil then
    self.data.free_egg_reward_num = num
  end
end

function this:getFreeEggRewardNum()
  return self.data.free_egg_reward_num
end

return this
