local this = class("pageHomeManage", G_UIPageBase)
local _petHomeTalentTpl = L_GameTpl:getPetHomeTalentTpl()
local _petHomePetSizeTpl = L_GameTpl:getPetHomeSizeTpl()
local _homeTalentTpl = L_GameTpl:getHomeTalentTpl()

function this.bind()
  return {
    grid_homePet = {
      moduleName = "pages/Home/homeManage/cellHomePet"
    },
    txt_petName = "",
    txt_petSize = "",
    txt_petStatus = "",
    grid_talent = {
      moduleName = "pages/Home/homeManage/cellHomePetTalent"
    }
  }
end

function this.methods()
  return {
    onClick_bg = function()
      L_UI:close("pageHomeManage")
    end
  }
end

function this:open()
  self:initList()
end

function this:initList()
  local guidList = L_HomeUtil.getPetSortList()
  local datas = {}
  for _, guid in ipairs(guidList) do
    local pet = L_PetStore:getPetItem(guid)
    local tpl_pet_talent = _petHomeTalentTpl:getTplById(pet.id)
    if tpl_pet_talent then
      table.insert(datas, {
        guid = guid,
        callback = function()
          self:onClickGuid(guid)
        end
      })
    end
  end
  self.bind.grid_homePet:clear()
  self.bind.grid_homePet:insert_array(datas)
  self:refreshList()
end

function this:onClickGuid(guid)
  self._selectGuid = guid
  self:refreshList()
end

function this:refreshList()
  if not self._selectGuid and self.modules.grid_homePet[1] then
    self._selectGuid = self.modules.grid_homePet[1].bind.guid
  end
  for _, module in ipairs(self.modules.grid_homePet) do
    module:setSelect(module.bind.guid == self._selectGuid)
  end
  self:refreshInfo()
end

function this:refreshInfo()
  if not self._selectGuid then
    self.bind.txt_petName = L_WordsTpl:getValue("notice_homeProduction_25")
    self.bind.txt_petSize = ""
    self.bind.txt_petStatus = ""
    self.bind.grid_talent:clear()
  else
    local guid = self._selectGuid
    local pet = L_PetStore:getPetItem(guid)
    local configData = L_ItemTplManager:getPetItem(pet.id, pet:isSpecialPet())
    local tpl_pet_talent = _petHomeTalentTpl:getTplById(pet.id)
    local tpl_pet_size = _petHomePetSizeTpl:getTplById(tpl_pet_talent.sizeType)
    self.bind.txt_petName = configData.name
    self.bind.txt_petSize = _petHomePetSizeTpl:getSizeName(tpl_pet_size)
    if not math.isEmpty(pet.work_build) and not pet:isWorking() then
      self.bind.txt_petStatus = L_WordsTpl:getValue("notice_homeProduction_31")
    elseif pet:isWorking() then
      self.bind.txt_petStatus = L_WordsTpl:getValue("notice_cellHomeCenterCollection_01")
    else
      self.bind.txt_petStatus = "notice_homeProduction_32"
    end
    local talentDatas = {}
    for _, talentId in ipairs(pet.talent_id) do
      local tpl_talent = _homeTalentTpl:getTplById(talentId)
      table.insert(talentDatas, {
        txt_name = _homeTalentTpl:getTalentName(tpl_talent)
      })
    end
    self.bind.grid_talent:clear()
    self.bind.grid_talent:insert_array(talentDatas)
  end
end

return this
