local this = {}
local _areaTpl = L_GameTpl:getWorldAreaTpl()
local m_prePath = "Program/FlyMsg/pre_areaMsg.prefab"

function this:initAreaMsg()
  local go = self.pool:spawn(m_prePath)
  local trans = go.transform
  trans:SetParent(self.root)
  L_Vector3.setScale(trans, {
    x = 1,
    y = 1,
    z = 1
  })
  L_Vector3.setAnchored(trans, {x = 0, y = -110.5})
  self._areaMsgGo = go
  self._areaMsgTxt = trans:Find("txtMsg"):GetComponent(typeof(C_LTextMeshProUGUI))
  self._areaMsgLock = {}
  self:setAreaLock("show", true)
  
  function self._onAreaChange()
    self:showAreaMsg()
  end
  
  L_AreaStore:listenCallFunc(L_AreaStore.event.areaChanged, self._onAreaChange)
  
  function self._onPageChange()
    self:setAreaLock("page", L_UI:currentPage(L_UI.groupKeys.stack) ~= "pageMainCity" or L_LoadingManager:isLoading())
  end
  
  L_UI:addListener(L_UI.pageEvent.preOpen, self._onPageChange)
  L_UI:addListener(L_UI.pageEvent.closed, self._onPageChange)
end

function this:showAreaPopup(popup)
  local priorityShowData = require("ui.manager.priorityShowQueue.flyMsgPriorityShowData").new({
    flyMsgType = L_ShowQueueConst.flyMsgType.areaMsg,
    uuid = self:getNextUniqueId(),
    params = {popup}
  })
  L_PriorityShowQueueManager:addPriorityShowData(priorityShowData)
end

function this:rawShowAreaPopup(uuid, popup)
  popup._uuid = uuid
  self:doShowAreaMsg(popup)
end

function this:showAreaMsg()
  if not self._areaMsgGo then
    return
  end
  local tpl = _areaTpl:getTplById(L_AreaStore:getAreaId())
  if tpl then
    self:showAreaPopup({
      areaName = _areaTpl:getName(tpl)
    })
  end
end

function this:doShowAreaMsg(popup)
  self._areaMsgTxt.text = popup.areaName
  self:setAreaLock("show", false)
  self._areaMsgGo:ActiveTrans(true)
  L_TimerManager:newOrResetTimer(self, "areaTimer", function()
    self:setAreaLock("show", true)
    self:sendEvent(self.event.flyMsgPopupEnd, L_ShowQueueConst.flyMsgType.areaMsg, popup._uuid)
  end, 2.5)
end

function this:setAreaLock(key, state)
  self._areaMsgLock[key] = state or nil
  self._areaMsgGo:ActiveTrans(not next(self._areaMsgLock))
end

function this:disposeAreaMsg()
  L_TimerManager:clearTimer(self)
  if L_CommonUtil.isValid(self._areaMsgGo) then
    self.pool:despawn(self._areaMsgGo)
  end
  self._areaMsgGo = nil
  L_AreaStore:unListenCallFunc(L_AreaStore.event.areaChanged, self._onAreaChange)
  L_UI:removeListener(L_UI.pageEvent.preOpen, self._onPageChange)
  L_UI:removeListener(L_UI.pageEvent.closed, self._onPageChange)
end

return this
