local this = class("pageStation", G_UIPageBase)
local _HomeBuildingTpl = L_GameTpl:getHomeBuildingTpl()
local _homeBuildingCollectionTpl = L_GameTpl:getHomeBuildingCollectionTpl()
local _HomeBuildingGroupTpl = L_GameTpl:getHomeBuildingGroupTpl()
local _homeTalentTpl = L_GameTpl:getHomeTalentTpl()
local _petHomeTalentTpl = L_GameTpl:getPetHomeTalentTpl()
local _homeDropTpl = L_GameTpl:getHomeDropTpl()
local _homeLaborCapacityTpl = L_GameTpl:getHomeLaborCapacityTpl()
local _petHomeSizeTpl = L_GameTpl:getPetHomeSizeTpl()
local _homeLaborTypeTpl = L_GameTpl:getHomeLaborTypeTpl()
local _homeBuffTpl = L_GameTpl:getHomeBuffTpl()
local columnNum = 5
local minLineNum = 4
local HideNodeList_pageSelectCoolie = {
  L_Const.WorldNode.PLAYER,
  L_Const.WorldNode.OTHERPLATERPETNODE
}

function this.bind()
  return {
    grid_pet = {
      moduleName = "pages/home/homeStation/cellSelectStation"
    },
    img_capacity = nil,
    txt_sizeNeed = nil,
    isOn_capacityInfo = false,
    canvasGroup_petContent = 1,
    txt_buildName = "",
    go_pet = true,
    pos_pet = C_Vector3(70.1, 54.5, 0),
    scale_pet = C_Vector3(1, 1, 1),
    module_petIcon = {
      moduleName = "pages/pet/modulePetFrameIcon"
    },
    go_saiety = true,
    saietyCurScore = "",
    saietyMaxScore = "",
    img_build = "",
    active_ranchBuild = false,
    active_commonBuild = true,
    list_labor = {
      moduleName = "pages/Pet/cellPetTipHomeLabor"
    },
    grid_drops = {
      moduleName = "pages/home/homeStation/cellStationDropItem"
    },
    go_noDispatchPart = false,
    txt_btnName = nil,
    go_btn = true,
    module_stationTabList = {
      moduleName = "pages/home/homeStation/moduleStationTabListVertical"
    },
    go_cropTab = false,
    active_buildBottom = true,
    active_buildBottom_crop = false,
    active_btn_checkIfUnloadHomeHub = false,
    active_checkIfUnloadHomeHub_on = false
  }
end

function this.methods()
  return {
    onClick_confirm = function(self)
      self:onClickConfirm()
    end,
    grid_pet = {
      onClick_select = function(self, bind)
        self._selectGuid = bind.guid
        self:setBoxListSelect(self._selectGuid)
        self:initStationInfo()
        self.bindComponents.anim_coolieInfo:Stop()
        self.bindComponents.anim_coolieInfo:Play("anim_station_change")
      end
    },
    onClick_close = function(self)
      L_UI:close(self.pageName)
    end,
    onClick_btn_checkIfUnloadHomeHub = function(self)
      self._ifUnloadHomeHub = not self._ifUnloadHomeHub
      self:refreshBtnCheckIfUnloadHomeHubView()
    end
  }
end

function this:preOpen(options)
  this.super.preOpen(self, options)
  self._needCapacityId = options.capacityId
  self._needLaborType = options.needLaborType or L_HomeConst.HomeLaborId.ZHAO_LIAO
  self._selectGuid = options.selectGuid
  self._curSetGuid = options.selectGuid
  self._blockId = options.blockId
  self._stationType = options.stationType
  self._buildGuid = options.buildGuid
  self._needSize = options.petSize
  self._callback = options.callback
  self._ifUnloadHomeHub = false
  self:initPage()
end

function this:open()
end

function this:show()
  L_HomeUtil.showOrHideEntityNodeWithCustomNodeList(false, HideNodeList_pageSelectCoolie, "pageSelectCoolie")
  self:setBoxListSelect(self._selectGuid)
end

function this:hide()
  L_HomeUtil.showOrHideEntityNodeWithCustomNodeList(true, HideNodeList_pageSelectCoolie, "pageSelectCoolie")
end

function this:close(options)
  this.super.close(self, options)
  L_TimerManager:clearTimer(self)
end

function this:refreshView(capacityId, selectGuid, needLaborType)
  self._needCapacityId = capacityId
  self._selectGuid = selectGuid
  self._needLaborType = needLaborType
  self:initPage()
end

function this:initPage()
  local tpl_capacity = _homeLaborCapacityTpl:getTplById(self._needCapacityId)
  self.bind.img_capacity = _homeLaborCapacityTpl:getIconLight(tpl_capacity)
  local txt = ""
  for i, v in ipairs(self._needSize) do
    local tpl_size = _petHomeSizeTpl:getTplById(v)
    txt = string.concat(txt, _petHomeSizeTpl:getSizeName(tpl_size))
    if i < #self._needSize then
      txt = string.concat(txt, "/")
    end
  end
  self.bind.txt_sizeNeed = txt
  self:freshBoxList()
end

function this:freshBoxList()
  local allPets = L_PetStore:getPetList()
  local dataList = {}
  for i, v in pairs(allPets) do
    if self._needCapacityId == L_HomeConst.homeLaborType.RANCH_PRODUCT then
      table.insert(dataList, {
        guid = v.guid,
        curSelect = self._selectGuid == v.guid,
        isCurStationed = self._curSetGuid == v.guid,
        isPasture = true,
        isCurStationedNum = self._curSetGuid == v.guid and 1 or 0,
        isWorkNum = v:isWorking() and 1 or 0,
        isRestNum = v:isRest() and 1 or 0,
        level = v.lv
      })
    else
      local tpl_pet_talent = _petHomeTalentTpl:getTplById(v.id)
      if tpl_pet_talent then
        local size = _petHomeTalentTpl:getSizeType(tpl_pet_talent)
        local node, index = table.ipairsFind(self._needSize, function(value)
          return value == size
        end)
        if index then
          if self._needLaborType then
            local laborConfigInfoList = _petHomeTalentTpl:getPetLaborConfigInfoListByPetId(v.id)
            for _, laborConfigInfo in pairs(laborConfigInfoList) do
              local laborId = laborConfigInfo.laborId
              if self._needLaborType == laborId then
                table.insert(dataList, {
                  guid = v.guid,
                  curSelect = self._selectGuid == v.guid,
                  isCurStationed = self._curSetGuid == v.guid,
                  isPasture = false,
                  isCurStationedNum = self._curSetGuid == v.guid and 1 or 0,
                  isWorkNum = v:isWorking() and 1 or 0,
                  isRestNum = v:isRest() and 1 or 0,
                  level = v.lv
                })
              end
            end
          else
            do
              local talent = v.talent_id or {}
              local node1, index1 = table.ipairsFind(talent, function(value)
                local tpl_talent = _homeTalentTpl:getTplById(value)
                local capacityId = _homeTalentTpl:getLaborCapacityId(tpl_talent)
                return capacityId == self._needCapacityId
              end)
              if index1 then
                table.insert(dataList, {
                  guid = v.guid,
                  curSelect = self._selectGuid == v.guid,
                  isCurStationed = self._curSetGuid == v.guid,
                  isPasture = false,
                  isCurStationedNum = self._curSetGuid == v.guid and 1 or 0,
                  isWorkNum = v:isWorking() and 1 or 0,
                  isRestNum = v:isRest() and 1 or 0,
                  level = v.lv
                })
              end
            end
          end
        end
      end
    end
  end
  local isEmpty = #dataList == 0
  self.bind.canvasGroup_petContent = isEmpty and 0.5 or 1
  self.bind.go_pet = not isEmpty
  self.bind.go_saiety = not isEmpty
  self.bind.go_btn = not isEmpty
  self.bind.go_noDispatchPart = isEmpty
  L_CommonUtil.multipleSortByKey(dataList, {
    "-isCurStationedNum",
    "-isWorkNum",
    "-isRestNum",
    "level",
    "-guid"
  })
  local datalist_tmp = {}
  for i = 1, #dataList do
    table.insert(datalist_tmp, dataList[i])
  end
  local lineNum = math.ceil(#datalist_tmp / columnNum)
  lineNum = math.max(lineNum, minLineNum)
  for i = 1, lineNum * columnNum - #dataList do
    table.insert(datalist_tmp, {guid = 0})
  end
  self._selectGuid = math.isEmpty(self._selectGuid) and datalist_tmp[1].guid or self._selectGuid
  if #datalist_tmp ~= #self.bind.grid_pet then
    self.bind.grid_pet:clear()
    self.bind.grid_pet:insert_array(datalist_tmp)
  else
    for i = 1, #self.bind.grid_pet do
      self.bind.grid_pet:change(i, datalist_tmp[i])
    end
    self:setBoxListSelect(self._selectGuid)
  end
  self:initStationInfo()
  self:initCropTab()
end

function this:setBoxListSelect(selectGuid)
  for _, v in pairs(self.modules.grid_pet) do
    if not math.isEmpty(v.bind.guid) then
      local cell = v
      cell:setSingleSelect(v.bind.guid == selectGuid)
    end
  end
end

function this:initStationInfo()
  if self._stationType == L_HomeConst.StationType.HomeBuilding then
    local serverData = L_HomeStore:getHomeBuildingByGuid(self._buildGuid)
    local buildTpl = _HomeBuildingTpl:getTplById(serverData.build_id)
    self.bind.img_build = _HomeBuildingTpl:getBuildingPixelIcon(buildTpl)
    local groupId = _HomeBuildingTpl:getGroupId(buildTpl)
    local groupTpl = _HomeBuildingGroupTpl:getTplById(groupId)
    self.bind.txt_buildName = L_WordsTpl:getValue("notice_pageSelectCoolie_04", {
      [0] = _HomeBuildingGroupTpl:getName(groupTpl)
    })
    self.bind.active_commonBuild = true
    self.bind.active_ranchBuild = false
  elseif self._stationType == L_HomeConst.StationType.Ranch then
    self.bind.txt_buildName = L_WordsTpl:getValue("notice_pageSelectCoolie_05")
    self.bind.go_saiety = false
    self.bind.active_commonBuild = false
    self.bind.active_ranchBuild = true
  elseif self._stationType == L_HomeConst.StationType.Collection then
    local csHomeBuildData = L_HomeStore:getCsHomeBuildDataByGuid(self._buildGuid)
    local tpl_collection = _homeBuildingCollectionTpl:getTplById(csHomeBuildData.buildId)
    local homeCollectionWorldTpl = L_GameTpl:getHomeCollectionWorldTpl()
    local homeCollectionWorldConfigId = csHomeBuildData.collect.Guid
    self.bind.img_build = homeCollectionWorldTpl:getPixelIcon(homeCollectionWorldTpl:getTplById(homeCollectionWorldConfigId))
    self.bind.txt_buildName = L_WordsTpl:getValue("notice_pageSelectCoolie_04", {
      [0] = _homeBuildingCollectionTpl:getName(tpl_collection)
    })
    self.bind.active_commonBuild = true
    self.bind.active_ranchBuild = false
  elseif self._stationType == L_HomeConst.StationType.Crop then
    local serverData = L_HomeStore:getHomeBuildingByGuid(self._buildGuid)
    local buildTpl = _HomeBuildingTpl:getTplById(serverData.build_id)
    local groupId = _HomeBuildingTpl:getGroupId(buildTpl)
    local groupTpl = _HomeBuildingGroupTpl:getTplById(groupId)
    self.bind.txt_buildName = L_WordsTpl:getValue("notice_pageSelectCoolie_04", {
      [0] = _HomeBuildingGroupTpl:getName(groupTpl)
    })
    self.bind.active_commonBuild = false
    self.bind.active_ranchBuild = false
  end
  self.bind.active_buildBottom = self._stationType ~= L_HomeConst.StationType.Crop
  self.bind.active_buildBottom_crop = self._stationType == L_HomeConst.StationType.Crop
  if self._stationType == L_HomeConst.StationType.Crop then
    self.bind.scale_pet = C_Vector3(1.4, 1.4, 1.4)
    self.bind.pos_pet = C_Vector3(100.9, 68.9, 0)
  else
    self.bind.scale_pet = C_Vector3(1, 1, 1)
    self.bind.pos_pet = C_Vector3(70.1, 54.5, 0)
  end
  if self._stationType == L_HomeConst.StationType.Crop then
    local imgPath = "UI/Texture/FrameTexture/tex_frame_sow2.png"
    local imgIndex = 9
    if self._needCapacityId == L_HomeConst.homeLaborType.WATER then
      imgPath = "UI/Texture/FrameTexture/tex_frame_water1.png"
      imgIndex = 1
    elseif self._needCapacityId == L_HomeConst.homeLaborType.HARVEST then
      imgPath = "UI/Texture/FrameTexture/tex_frame_harvest1.png"
      imgIndex = 9
    end
    self.bindComponents.img_buildBottom_crop.frameSelectCount = imgIndex
    self.bindComponents.img_buildBottom_crop:LoadTexture(imgPath)
    self.bind.active_buildBottom_crop = false
    self.bind.active_buildBottom_crop = true
  end
  local currentSaity = L_SatietyStore:getPetSatiety(self._selectGuid)
  local maxSaity = L_SatietyStore:getPetMaxSatiety(self._selectGuid)
  self.bind.saietyCurScore = string.format("%s", currentSaity)
  self.bind.saietyMaxScore = string.format("/%s", maxSaity)
  if math.isEmpty(self._selectGuid) then
    return
  end
  local isPasture = self._needCapacityId == L_HomeConst.homeLaborType.RANCH_PRODUCT
  self.bind.isOn_capacityInfo = not isPasture
  local selectIsSet = self._curSetGuid == self._selectGuid
  if isPasture then
    self:initDropList()
    self.bind.txt_btnName = selectIsSet and L_WordsTpl:getValue("notice_pageSelectCoolie_03") or L_WordsTpl:getValue("notice_pageSelectCoolie_02")
  else
    self:initCapacityList()
    self.bind.txt_btnName = selectIsSet and L_WordsTpl:getValue("notice_homeProduction_24") or L_WordsTpl:getValue("notice_pageSelectCoolie_01")
  end
  local pet = L_PetStore:getPetItem(self._selectGuid)
  local isPetPlaceRanch
  if pet.work_build == 201 then
    isPetPlaceRanch = true
  else
    isPetPlaceRanch = false
  end
  print("pet.work_build", pet.work_build)
  self.modules.module_petIcon:setGuid(self._selectGuid, true)
  self:refreshBtnCheckIfUnloadHomeHubView()
end

function this:initCropTab()
  if self._needLaborType ~= 5 and self._needLaborType ~= 6 then
    return
  end
  if C_HomeUtil.CheckIsCollectBuildingGuid(self._buildGuid) == true then
    return
  end
  self.bind.go_cropTab = true
  local buildingData = C_HomeUtil.GetBuildData(self._buildGuid)
  if not buildingData then
    errorf("\230\137\190\228\184\141\229\136\176 buildData, \229\143\175\232\131\189\229\156\168\231\148\168\229\174\182\229\155\173\230\142\165\229\143\163\232\142\183\229\143\150\233\135\135\233\155\134\229\187\186\231\173\145, \230\136\150\230\152\175\233\133\141\232\161\168\233\148\153\232\175\175, buildGuid: " .. tostring(self._buildGuid))
    return
  end
  local autoData = buildingData.auto
  local plantPetGuid, waterPetGuid, harvestPetGuid
  if autoData then
    plantPetGuid = autoData.plantPetGuid
    waterPetGuid = autoData.waterPetGuid
    harvestPetGuid = autoData.harvestPetGuid
  end
  local idList = {}
  for i = 1, 3 do
    table.insert(idList, 1000 + i)
  end
  local selectIndex = 1001
  for i, v in ipairs(idList) do
    if v == self._needCapacityId then
      selectIndex = i
      break
    end
    if i == 1 then
      self._needCapacityId = self._needCapacityId or v
    end
  end
  self.modules.module_stationTabList:setData(idList, autoData, function(laborId, petGuid, laborType)
    local id = laborId
    if id == self._needCapacityId then
      return
    end
    self._needCapacityId = id
    print("\230\181\139\232\175\149", petGuid, laborType)
    self.selectIndex = laborId
    self:refreshView(laborId, petGuid, laborType)
  end, selectIndex)
  self.modules.module_stationTabList:setSelectTabId(selectIndex)
end

function this:freshStationInfo()
end

function this:initDropList()
  local confId = L_PetStore:getPetItem(self._selectGuid).id
  local petTalentTpl = _petHomeTalentTpl:getTplById(confId)
  local dropIds = _petHomeTalentTpl:getFarmProducts(petTalentTpl)
  local itemMaps = {}
  local data = {}
  for i, v in pairs(dropIds) do
    local tpl_drop = _homeDropTpl:getTplById(v)
    local itemType, itemId = _homeDropTpl:getItemType(tpl_drop), _homeDropTpl:getItemId(tpl_drop)
    if itemType ~= L_Const.resType.petEgg then
      itemMaps[itemType] = itemMaps[itemType] or {}
      if not itemMaps[itemType][itemId[1]] then
        local configData = L_ItemTplManager:getItemConfig(itemType, itemId[1])
        table.insert(data, {
          itemType = itemType,
          itemId = itemId[1],
          txt_name = configData.name,
          go_mainDrop = i == 1
        })
      end
      itemMaps[itemType][itemId[1]] = true
    end
  end
  self.bind.grid_drops:clear()
  self.bind.grid_drops:insert_array(data)
end

function this:initCapacityList()
  local talent = L_PetStore:getPetItem(self._selectGuid).talent_id
  local petId = L_PetStore:getPetItem(self._selectGuid).id
  local C_HomeManager = AzurWorld.HomeMgr
  local C_PetStore = C_HomeManager:GetPetStore()
  local C_PetData = C_PetStore:GetPet(self._selectGuid)
  local C_LaborInfoList = C_PetData:GetLaborInfoList()
  local showParamsList = {}
  for i = 0, C_LaborInfoList.Count - 1 do
    local C_LaborInfo = C_LaborInfoList[i]
    local laborId = C_LaborInfo.laborId
    if laborId == self._needLaborType then
      local C_TalentIds = C_PetData.talentIds
      local talentId
      if 0 < C_TalentIds.Count then
        local tmpTalentId = C_TalentIds[0]
        local homeTalentTpl = _homeTalentTpl:getTplById(tmpTalentId)
        local laborOfTmpTalentId = _homeTalentTpl:getLaborTypeIdOfTalent(homeTalentTpl)
        if laborOfTmpTalentId == C_LaborInfo.laborId then
          talentId = tmpTalentId
        end
      end
      local showParams = {
        petId = C_PetData.configId,
        laborId = C_LaborInfo.laborId,
        laborGrade = C_LaborInfo.laborGrade,
        talentId = talentId,
        isSelectCoolie = true,
        stationBuildingType = self._stationType,
        needLaborType = self._needLaborType
      }
      table.insert(showParamsList, showParams)
    end
  end
  self.bind.list_labor:clear()
  self.bind.list_labor:insert_array(showParamsList)
end

function this:refreshBtnCheckIfUnloadHomeHubView()
  local selectIsSet = self._curSetGuid == self._selectGuid
  self.bind.active_btn_checkIfUnloadHomeHub = selectIsSet
  self.bind.active_checkIfUnloadHomeHub_on = self._ifUnloadHomeHub
end

function this:onClickConfirm()
  local selectPet = L_PetStore:getPetItem(self._selectGuid)
  local isPetEquip = selectPet:getHeroId() ~= nil and selectPet:getHeroId() ~= 0
  local isSelectSet = self._curSetGuid == self._selectGuid
  local workStatus = selectPet.work_status
  local isCollect = L_HomeConst.isWildLabor[self._needCapacityId] == true
  local curPetStationedNum = L_HomeStore:getCurPetStationedNum()
  local unlockedPetStationedNum = L_HomeStore:getUnlockedPetStationedNum()
  if isSelectSet then
    if workStatus == L_Const.PetStationedWorkStatusType.PSWST_WILD_WORK then
    elseif workStatus == L_Const.PetStationedWorkStatusType.PSWST_HOME_WORK and L_ProductManager:getIsHomeWorkBuildingNeedPet(selectPet.work_build) then
      L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("home_pet_hire_note2"))
      return
    end
  else
    if self._needCapacityId ~= L_HomeConst.homeLaborType.RANCH_PRODUCT and curPetStationedNum >= unlockedPetStationedNum and not L_HomeStore:checkPetIsInHomeHub(self._selectGuid) then
      L_FlyMsgManager:showNormalMsg("\229\174\182\229\155\173\228\184\173\230\158\162\230\180\190\233\169\187\229\183\178\230\187\161")
      return
    end
    if workStatus == L_Const.PetStationedWorkStatusType.PSWST_HOME_WORK and L_ProductManager:getIsHomeWorkBuildingNeedPet(selectPet.work_build) then
      L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("home_pet_hire_note3"))
      return
    end
  end
  local equipKiboTipEndDo = function()
    L_UI:close("pageCommonTip")
    local endDo = function()
      L_UI:close(self.pageName, nil, function()
        self._callback(self._selectGuid, self._ifUnloadHomeHub)
      end)
    end
    local petGameplayStatus = selectPet:getGameplayStatus()
    if petGameplayStatus == L_Const.PetState.PET_ROULETTE then
      local data_tip = {
        txtContent = L_WordsTpl:getValue("notice_qibo_mutex_mount_farm"),
        confirmCallback = endDo
      }
      L_GameUtil.showCommonTip(data_tip)
      return
    end
    endDo()
  end
  if isPetEquip then
    local data_tip = {
      txtContent = L_WordsTpl:getValue("notice_qibo_mutex_team_farm"),
      confirmCallback = equipKiboTipEndDo
    }
    L_GameUtil.showCommonTip(data_tip)
    return
  end
  equipKiboTipEndDo()
end

return this
