local _homeBuildingTpl = L_GameTpl:getHomeBuildingTpl()
local _homeBuildingGroupTpl = L_GameTpl:getHomeBuildingGroupTpl()
local _blockTpl = L_GameTpl:getHomeBlockTpl()
local _HomeRanchTpl = L_GameTpl:getHomeRanchTpl()
local this = class("pageManagerUpgrade", G_UIPageBase)
local PageMode = {
  Building = 1,
  Collection = 2,
  Ranch = 3
}

function this.bind()
  return {
    txt_buildName = "",
    txt_level = "",
    txt_currLv = "",
    txt_nextLv = "",
    list_effect = L_Const.ModuleInfo.CellText,
    active_condition = false,
    list_condition = {
      moduleName = "pages/home/homeBuilding/cellBuildingUpgradeCondition"
    },
    list_cost = {
      moduleName = "pages/home/homeBuilding/cellBuildingUpgradeCost"
    },
    active_btnPreview = false,
    txt_preview = L_WordsTpl:getValue("ui_pageManagerUpgrade_07"),
    active_renderctrlfx = false,
    txt_nextLvmask = "",
    active_Levelupbtn = true,
    location = false,
    txt_collectionName = "",
    txt_locationName = "",
    collectImg = false
  }
end

function this.methods()
  return {
    onClose = function(self)
      L_UI:close(self.pageName)
    end,
    onLevelUp = function(self)
      self:onLevelUp()
    end,
    onClickPreview = function(self)
      self:onClickPreview()
    end
  }
end

function this:preOpen(options)
  self.options = options
  if self.options.guid then
    self._pageMode = PageMode.Building
    self._guid = options.guid
    self:setHomeBuildingData()
    if not options.keepCamera then
      L_HomeUtil.focusBuild(self._guid, L_HomeConst.FocusType.UPGRADE)
    end
  elseif self.options.collectionId then
    self._pageMode = PageMode.Collection
    self._collectionId = options.collectionId
    self._sourceBuildId = options.sourceBuildId or 0
    self.bind.collectImg = true
    self:setCollectBuildingData(self._collectionId)
  elseif self.options.ranchBlockId then
    self._pageMode = PageMode.Ranch
    self._blockId = options.ranchBlockId
    self:setRanchData(self._blockId)
    L_HomeUtil.focusBlock(self._blockId)
  end
  L_GameUtil.forceRebuildLayout(self.bindComponents.list_level)
  L_GameUtil.forceRebuildLayout(self.bindComponents.list_cost)
end

function this:refreshView()
  L_TimerManager:newOrResetTimer(self, "AfterBuildingUpgradeAnima", function()
    self.bind.active_Levelupbtn = true
  end, 1.5)
  if self.options.guid then
    self._pageMode = PageMode.Building
    local guid = self._guid
    self:_refreshLevel(L_HomeStore:checkHomeBuildingMaxLv(guid))
    L_TimerManager:newOrResetTimer(self, "finishBuildingUpgrade", function()
      self:setHomeBuildingData()
    end, 0.66)
  elseif self.options.collectionId then
    local collectId = self._collectionId
    self:_refreshLevel(L_CollectionManager:getIsCollectionMaxLevel(collectId))
    self._pageMode = PageMode.Collection
    local collectionId = self._collectionId
    L_TimerManager:newOrResetTimer(self, "finishCollectUpgrade", function()
      self:setCollectBuildingData(collectionId)
    end, 0.66)
  elseif self.options.ranchBlockId then
    self._pageMode = PageMode.Ranch
    local blockId = self._blockId
    local ranchData = L_HomeRanchStore:getBlockRanchData(self._blockId)
    local currLv = ranchData and ranchData.lv or 1
    local maxLevel = _HomeRanchTpl:getMaxLv()
    local IsMax = false
    if currLv >= maxLevel then
      IsMax = true
    else
      IsMax = false
    end
    self:_refreshLevel(IsMax)
    L_TimerManager:newOrResetTimer(self, "finishRanchUpgrade", function()
      self:setRanchData(blockId)
    end, 0.66)
  end
  L_GameUtil.forceRebuildLayout(self.bindComponents.list_level)
  L_GameUtil.forceRebuildLayout(self.bindComponents.list_cost)
end

function this:close(options)
  L_TimerManager:clearTimer(self)
  if self._pageMode == PageMode.Building then
    if not self.options.keepCamera then
      L_HomeUtil.focusBuild(0, L_HomeConst.FocusType.UPGRADE)
    end
    local entity = L_HomeManager:getBuildingEntityByGuid(self._guid)
    if entity then
      entity:syncServerMap()
    end
  elseif self._pageMode == PageMode.Ranch then
    L_HomeUtil.focusBlock(0)
  end
end

function this:initUpgradeInfo(effectStrs, conditions, costs)
  local data_effectDatas = {}
  for _, str in ipairs(effectStrs) do
    table.insert(data_effectDatas, {
      text = L_Lang:get(str)
    })
  end
  self.bind.list_effect:clear()
  self.bind.list_effect:insert_array(data_effectDatas)
  local conditionDescs = L_ConditionManager:getDescs(conditions)
  local isSatisfy, conditionRess = L_ConditionManager:isComplete(conditions)
  local conditionDatas = {}
  for i, condition in ipairs(conditions) do
    table.insert(conditionDatas, {
      text = conditionDescs[i],
      toggle_isSatisfy = conditionRess[i] == true
    })
  end
  printf("\230\157\161\228\187\182", conditionDatas)
  self.bind.active_condition = 0 < #conditionDatas
  self.bind.list_condition:clear()
  self.bind.list_condition:insert_array(conditionDatas)
  self._conditionLock = not isSatisfy
  local costDatas = {}
  self._itemLock = false
  for _, item in ipairs(costs) do
    table.insert(costDatas, {item = item})
    self._itemLock = self._itemLock or L_ItemTplManager:getItemNum(item.itemType, item.itemId) < item.itemNum
  end
  self.bind.list_cost:clear()
  self.bind.list_cost:insert_array(costDatas)
  Unity.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.bindComponents.MainLayout)
end

function this:setRanchData(blockId)
  if self:_getHomeRanchStoreIsMax() then
    self:delayTimeAni()
  else
    local ranchData = L_HomeRanchStore:getBlockRanchData(self._blockId)
    local currLv = ranchData and ranchData.lv or 1
    local tpl = _blockTpl:getTplById(self._blockId)
    self.bind.txt_buildName = L_WordsTpl:getValue("ui_pageManagerUpgrade_01", {
      [0] = _blockTpl:getSequence(tpl)
    })
    self.bind.txt_currLv = tostring(currLv)
    self.bind.txt_level = self.bind.txt_currLv
    L_TimerManager:newOrResetTimer(self, "finishRanchSet", function()
      self.bind.txt_nextLv = tostring(currLv + 1)
    end, 0.25)
    L_TimerManager:newOrResetTimer(self, "finishRanchNextSet", function()
      self.bind.txt_nextLvmask = tostring(currLv + 1)
    end, 0.5)
    local nextTpl = _HomeRanchTpl:getTplById(currLv + 1)
    local descs = _HomeRanchTpl:getUpgradeDesc(nextTpl)
    local upgradeCondition = _HomeRanchTpl:getUpgradeCondition(nextTpl)
    local items = L_DataUtil.parseRewardConfig(_HomeRanchTpl:getCost(nextTpl))
    self:initUpgradeInfo(descs, upgradeCondition, items)
  end
  self:delayTimeFinshAni()
end

function this:setHomeBuildingData()
  if self:_getHomeBuildIsMax() then
    self:delayTimeAni()
  else
    local serverData = L_HomeStore:getHomeBuildingByGuid(self._guid)
    local buildingId = serverData.build_id
    local tpl = _homeBuildingTpl:getTplById(buildingId)
    local nextTpl = _homeBuildingTpl:getTplById(_homeBuildingTpl:getNextLevel(tpl))
    self.bind.active_btnPreview = _homeBuildingTpl:getObjId(tpl) ~= _homeBuildingTpl:getObjId(nextTpl)
    local groupId = _homeBuildingTpl:getGroupId(tpl)
    local groupTpl = _homeBuildingGroupTpl:getTplById(groupId)
    self.bind.txt_buildName = _homeBuildingGroupTpl:getName(groupTpl)
    self.bind.txt_currLv = tostring(_homeBuildingTpl:getLevel(tpl))
    self.bind.txt_level = self.bind.txt_currLv
    L_TimerManager:newOrResetTimer(self, "finishHomeBuildingSet", function()
      self.bind.txt_nextLv = tostring(_homeBuildingTpl:getLevel(nextTpl))
    end, 0.25)
    L_TimerManager:newOrResetTimer(self, "finishHomeBuildingNextSet", function()
      self.bind.txt_nextLvmask = tostring(_homeBuildingTpl:getLevel(nextTpl))
    end, 0.5)
    printf("self.bind.txt_nextLvmask", self.bind.txt_nextLvmask)
    local descs = _homeBuildingTpl:getUpgradeDesc(nextTpl)
    local upgradeCondition = _homeBuildingTpl:getUpgradeCondition(nextTpl)
    local items = L_DataUtil.parseRewardConfig(_homeBuildingTpl:getMaterial(nextTpl))
    self:initUpgradeInfo(descs, upgradeCondition, items)
  end
  self:delayTimeFinshAni()
end

function this:setCollectBuildingData(guid)
  if self:_getCollectionIsMax() then
    self:delayTimeAni()
  else
    local homeBuildingCollectionTpl = L_GameTpl:getHomeBuildingCollectionTpl()
    local homeCollectionWorldTpl = L_GameTpl:getHomeCollectionWorldTpl()
    local serverData = L_CollectionStore:getCollection(self._collectionId)
    local buildingId = serverData.build_id
    local tpl = homeBuildingCollectionTpl:getTplById(buildingId)
    local level = homeBuildingCollectionTpl:getLevel(tpl)
    local buildings = homeBuildingCollectionTpl:getTplByCollectionId(guid)
    local nextTpl = buildings[level + 1]
    self.bind.txt_buildName = homeBuildingCollectionTpl:getName(tpl) .. L_WordsTpl:getValue("ui_pageManagerUpgrade_02")
    self.bind.location = true
    local collectionWorldTpl = homeCollectionWorldTpl:getTplById(self._collectionId)
    self.bind.txt_locationName = homeCollectionWorldTpl:getLocalName(collectionWorldTpl)
    self.bind.txt_collectionName = homeBuildingCollectionTpl:getName(tpl)
    self.bindComponents.collectImg:LoadSprite(homeCollectionWorldTpl:getControlbenchShow(collectionWorldTpl), false)
    self.bind.txt_currLv = tostring(level)
    self.bind.txt_level = self.bind.txt_currLv
    L_TimerManager:newOrResetTimer(self, "finishCollectBuildingSet", function()
      self.bind.txt_nextLv = tostring(level + 1)
    end, 0.25)
    L_TimerManager:newOrResetTimer(self, "finishCollectBuildingNextSet", function()
      self.bind.txt_nextLvmask = tostring(level + 1)
    end, 0.5)
    local descs = homeBuildingCollectionTpl:getUpgradeDesc(nextTpl)
    local upgradeCondition = homeBuildingCollectionTpl:getUpgradeCondition(nextTpl)
    local items = L_DataUtil.parseRewardConfig(homeBuildingCollectionTpl:getMaterial(nextTpl))
    self:initUpgradeInfo(descs, upgradeCondition, items)
  end
  self:delayTimeFinshAni()
end

function this:onLevelUp()
  printf("Level Up btn CCCCCCCCCCCCCCCC")
  self.bind.active_renderctrlfx = true
  if L_ProductManager:isBuildingOnProducing(self._guid) then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_pageManagerUpgrade_03"))
    return
  end
  if L_PetStore:checkHatchBldInHatchingState(self._guid) then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_pageManagerUpgrade_03"))
    return
  end
  if self._conditionLock then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_pageManagerUpgrade_04"))
    return
  end
  if self._itemLock then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_pageManagerUpgrade_05"))
    return
  end
  if self._pageMode == PageMode.Building then
    self.bind.active_Levelupbtn = false
  elseif self._pageMode == PageMode.Collection then
    self.bind.active_Levelupbtn = false
  elseif self._pageMode == PageMode.Ranch then
    self.bind.active_Levelupbtn = false
  end
  if self._pageMode == PageMode.Building then
    local build_id, block_id, anchor, direction
    L_HomeStore:req_buildCreate(self._guid, build_id, block_id, anchor, direction, function()
      self:refreshView()
    end)
  elseif self._pageMode == PageMode.Collection then
    L_CollectionManager:reqBuildCollect(self._collectionId, self._sourceBuildId, function()
      self:refreshView()
    end)
  elseif self._pageMode == PageMode.Ranch then
    L_HomeRanchStore:req_ranchLvUp(self._blockId, function()
      self:refreshView()
    end)
  end
end

function this:_refreshLevel(callevent)
  local currLv = tonumber(self.bind.txt_currLv)
  if currLv < 10 then
    if callevent then
      self.bindComponents.ani_Board:Play("anim_building_upgrade_up1_max")
    else
      self.bindComponents.ani_Board:Play("anim_building_upgrade_up1")
    end
  elseif 10 <= currLv then
    if callevent then
      self.bindComponents.ani_Board:Play("anim_building_upgrade_up2_max")
    else
      self.bindComponents.ani_Board:Play("anim_building_upgrade_up2")
    end
  end
end

function this:onClickPreview()
  if self._pageMode == PageMode.Building then
    local entity = L_HomeManager:getBuildingEntityByGuid(self._guid)
    self._isPreview = not self._isPreview
    if self._isPreview then
      entity:doPreview()
    else
      entity:syncServerMap()
    end
  end
  self.bind.txt_preview = self._isPreview and L_WordsTpl:getValuey("ui_pageManagerUpgrade_06") or L_WordsTpl:getValue("ui_pageManagerUpgrade_07")
end

function this:_getHomeBuildIsMax()
  return L_HomeStore:checkHomeBuildingMaxLv(self._guid)
end

function this:_getCollectionIsMax()
  return L_CollectionManager:getIsCollectionMaxLevel(self._collectionId)
end

function this:_getHomeRanchStoreIsMax()
  local ranchData = L_HomeRanchStore:getBlockRanchData(self._blockId)
  local currLv = ranchData and ranchData.lv or 1
  local maxLevel = _HomeRanchTpl:getMaxLv()
  if currLv >= maxLevel then
    return true
  end
  return false
end

function this:_AfterUpdateMaxLevel()
  L_TimerManager:clearTimer(self)
  local bigMapPage = L_UI:getPage("pageBigMap")
  if bigMapPage ~= nil and bigMapPage.status == "shown" then
    L_UI:close(self.pageName)
  else
    L_UI:backToRoot()
  end
end

function this:delayTimeAni()
  self:_AfterUpdateMaxLevel()
end

function this:delayTimeFinshAni()
  self.bind.active_renderctrlfx = false
end

return this
