local this = {}
local _homeBuildingTpl = L_GameTpl:getHomeBuildingTpl()
local _homeSeedTpl = L_GameTpl:getHomeSeedsTpl()
local _BuildingKey = "BuildInteract"

function this:addModulesListener()
  L_BevTree:addListener(L_BevTree.event.triggerButton, self.onEvent_triggerButton, self)
  L_WorldManager:addListener(L_WorldManager.event.triggerInteractive, self.onEvent_triggerButton, self)
  L_EntityManager:addListener(L_EntityManager.event.destroyEntity, self.deleteButtonByEntity, self)
  L_EntityManager:addListener(L_EntityManager.event.destroyAllEntity, self.deleteAllButton, self)
  L_HomeStore:listenCallFunc(L_HomeStore.event.syncWorldMapHomeItem, self.refreshBuildingBtns, self)
end

function this:deleteButtonByEntity(entity)
  self._entity2ButtonDatas[entity] = nil
  self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end

function this:deleteAllButton()
  self._entity2ButtonDatas = {}
  self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end

function this:onEvent_triggerButton(interData)
  if interData.isIn then
    self._entity2ButtonDatas[interData.entity] = self._entity2ButtonDatas[interData.entity] or {}
    table.insert(self._entity2ButtonDatas[interData.entity], interData)
  else
    self._entity2ButtonDatas[interData.entity] = nil
  end
  self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end

local BuildType2Page = L_HomeConst.BuildType2Page

function this:refreshBuildingBtns()
  if L_PlayerStore:getIsNewPlayer() then
    return
  end
  L_TimerManager:clearTimer("interactBuildTimer")
  local guid = self._triggerBuildGuid
  local buildingEntity = AzurWorld.HomeMgr and AzurWorld.HomeMgr:GetHomeBuild(guid)
  local serverData = L_HomeStore:getHomeBuildingByGuid(guid)
  self._entity2ButtonDatas[_BuildingKey] = nil
  local main = L_PlayerManager:getMainHeroEntity()
  if buildingEntity and serverData and main and main:getFsmComponent():getCurFsmType() ~= L_Const.fsmType.skill then
    self._entity2ButtonDatas[_BuildingKey] = {}
    local isReward = L_ProductManager:isProductRewarded(guid)
    local buildingGroupTpl = L_GameTpl:getHomeBuildingGroupTpl()
    local buildingId = serverData.build_id
    local buildingTpl = L_GameTpl:getHomeBuildingTpl():getTplById(buildingId)
    local groupId = L_GameTpl:getHomeBuildingTpl():getGroupId(buildingTpl)
    local groupTpl = buildingGroupTpl:getTplById(groupId)
    local buildType = buildingGroupTpl:getType(groupTpl)
    if buildType == L_Const.WorldMapBuildType.WMBT_FIELD_NEW then
      local cData = buildingEntity:GetStoreData()
      local crop = cData.crop
      local cropState = crop:GetStateInt()
      if cropState == L_HomeConst.HomeCropState.NONE then
        local buttonData = {
          name = L_WordsTpl:getValue("ui_interactiveManager_06"),
          entity = buildingEntity,
          buildType = buildType,
          icon = buildingGroupTpl:getInteractIconInterface(groupTpl),
          onClick = function()
            if L_HomeManager.selectedCropItemId ~= 0 and 0 < L_ItemTplManager:getItemNum(L_Const.resType.commonItem, L_HomeManager.selectedCropItemId) then
              local seedTpl = _homeSeedTpl:getSeedTplByItem(L_HomeManager.selectedCropItemId)
              if not seedTpl then
                errorf("\231\167\141\229\173\144\231\137\169\229\147\129\230\178\161\230\156\137\233\133\141\231\189\174\231\167\141\229\173\144id" .. L_HomeManager.selectedCropItemId)
                return
              end
              local condition = _homeSeedTpl:getCondition(seedTpl)
              if L_ConditionManager:isComplete(condition) then
                buildingEntity:InvokePlant(L_HomeManager.selectedCropItemId)
              else
                L_FlyMsgManager:showNormalMsg(L_ConditionManager:getTipDesc(condition))
              end
            else
              L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_interactiveManager_05"))
            end
          end
        }
        table.insert(self._entity2ButtonDatas[_BuildingKey], buttonData)
      elseif cropState == L_HomeConst.HomeCropState.SEED then
        if not crop.isPlayerWatering then
          local buttonData = {
            name = L_WordsTpl:getValue("ui_interactiveManager_04"),
            entity = buildingEntity,
            buildType = buildType,
            icon = buildingGroupTpl:getInteractIconInterface(groupTpl),
            onClick = function()
              buildingEntity:InvokeWater()
            end
          }
          table.insert(self._entity2ButtonDatas[_BuildingKey], buttonData)
        end
      elseif cropState == L_HomeConst.HomeCropState.HARVEST then
        local buttonData = {
          name = L_WordsTpl:getValue("ui_interactiveManager_03"),
          entity = buildingEntity,
          buildType = buildType,
          icon = buildingGroupTpl:getInteractIconInterface(groupTpl),
          onClick = function()
            buildingEntity:InvokeHarvest()
          end
        }
        table.insert(self._entity2ButtonDatas[_BuildingKey], buttonData)
      end
      if cropState ~= L_HomeConst.HomeCropState.NONE then
        local seedId = crop.seedId
        local seedTpl = _homeSeedTpl:getTplById(seedId)
        local seedName = _homeSeedTpl:getCropName(seedTpl)
        local buttonData = {
          name = L_WordsTpl:getValue("ui_interactiveManager_01"),
          entity = buildingEntity,
          buildType = buildType,
          icon = buildingGroupTpl:getInteractIconInterface(groupTpl),
          onClick = function()
            L_GameUtil.showCommonTip({
              txtContent = L_WordsTpl:getValue("home_farm_iscancel", {
                [0] = seedName
              }),
              confirmCallback = function()
                buildingEntity:InvokeDelete()
              end
            })
          end
        }
        if L_SystemUnlockStore:getSystemIsOpen(L_SystemConst.enum.eradicatingCrop) then
          table.insert(self._entity2ButtonDatas[_BuildingKey], buttonData)
        end
      end
    end
    if isReward then
      table.insert(self._entity2ButtonDatas[_BuildingKey], {
        name = L_WordsTpl:getValue("ui_home_building_quickclaim"),
        buildType = buildType,
        entity = buildingEntity,
        icon = buildingGroupTpl:getInteractIconQuickClaim(groupTpl),
        onClick = function()
          if buildType == L_Const.WorldMapBuildType.WMBT_HATCH then
            local queueData = L_ProductManager:getProduceQueueForBuilding(guid)
            local special = L_ProductManager:getProductSpecialParams(guid, queueData[1].product.product_guid)
            L_PetStore:onClickHatchOutPetEgg(guid, special.extra_guid, function()
              self:refreshBuildingBtns()
            end)
          else
            L_ProductManager:reqCollectProduct(guid, function()
              self:refreshBuildingBtns()
            end)
          end
        end
      })
    end
    if not self._triggerBuildFromPet then
      local wndName = BuildType2Page[buildType]
      if wndName then
        local callback = function()
          L_UI:open(wndName, {buildingGuid = guid, buildType = buildType})
        end
        local buttonData = {
          name = buildingGroupTpl:getName(groupTpl),
          buildType = buildType,
          entity = buildingEntity,
          icon = buildingGroupTpl:getInteractIconInterface(groupTpl),
          onClick = callback
        }
        table.insert(self._entity2ButtonDatas[_BuildingKey], buttonData)
      end
      local buttonData = {
        press = true,
        name = L_WordsTpl:getValue("ui_interactiveManager_02"),
        buildType = buildType,
        entity = buildingEntity,
        icon = "UI/Atlas/HomeBuildingInteract/tex_time_icon_yidong.png",
        onClick = function()
          L_UI:open("pageHomePlayerEditCS", {entity = buildingEntity})
        end
      }
      if buildingId ~= L_HomeConst.HomeBuildIdOfPlow then
        table.insert(self._entity2ButtonDatas[_BuildingKey], buttonData)
      end
      local tpl = _homeBuildingTpl:getTplById(buildingId)
      if _homeBuildingTpl:getNextLevel(tpl) ~= 0 then
        do
          local nextTpl = _homeBuildingTpl:getTplById(_homeBuildingTpl:getNextLevel(tpl))
          local upgradeCondition = _homeBuildingTpl:getUpgradeCondition(nextTpl)
          local needItems = L_DataUtil.parseRewardConfig(_homeBuildingTpl:getMaterial(nextTpl))
          local isItemsEnough = true
          for _, item in ipairs(needItems) do
            if L_ItemTplManager:getItemNum(item.itemType, item.itemId) < item.itemNum then
              isItemsEnough = false
            end
          end
          local isComplete = L_ConditionManager:isComplete(upgradeCondition)
          if isComplete then
            local buttonData = {
              name = L_WordsTpl:getValue("ui_home_manage_8"),
              buildType = buildType,
              entity = buildingEntity,
              icon = "UI/Atlas/HomeBuildingInteract/tex_homebuilding_icon_homeupgrade.png",
              go_reddot = isItemsEnough,
              onClick = function()
                L_UI:open("pageBuildingUpgrade", {guid = guid})
              end
            }
            table.insert(self._entity2ButtonDatas[_BuildingKey], buttonData)
          end
        end
      end
    end
    L_TimerManager:newOrResetTimer("interactBuildTimer", "refreshbuild", function()
      self:refreshBuildingBtns()
    end, 1)
  end
  self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end

function this:setCSHomeBuildInteract(buildGuid, isPet)
  self._triggerBuildGuid = buildGuid
  self._triggerBuildFromPet = isPet
  self._entity2ButtonDatas[_BuildingKey] = nil
  self:refreshBuildingBtns()
end

function this:removeInteractOptions(entityId, index)
  if self._entity2ButtonDatas[entityId] ~= nil then
    self._entity2ButtonDatas[entityId][index] = nil
  end
  self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end

function this:showInteractOptions(entityId, options)
  if not self._entity2ButtonDatas[entityId] then
    self._entity2ButtonDatas[entityId] = {}
  end
  for t, v in pairs(options) do
    self._entity2ButtonDatas[entityId][t] = v
  end
  self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end

function this:clearInteractOptions(entityId)
  self._entity2ButtonDatas[entityId] = {}
  self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end

function this:refreshInteractOptions()
  self:sendEvent(L_InteractiveManager.event.onButtonDataChange)
end

return this
