local base = UIBaseContainer
local UIMainLeft = BaseClass("UIMainLeft", base)
local UIMainTroops = require("UI.UIMain.Component.UIMainBottom.UIMainTroops")
local UITroopsList = require("UI.UIMain.Component.UIMainBottom.TroopList.MainTroopList")
local UIBuildQueue = require("UI.UIMain.Component.UIMainBottom.UIMainBuildQueue")
local UIScienceQueue = require("UI.UIMain.Component.UIMainBottom.UIScienceQueue")
local UIMainVipBtn = require("UI.LWMainUI.Component.UIMainLeft.UIMainVipBtn")
local UIMainBirthdaySetTipBtn = require("UI.LWMainUI.Component.UIMainLeft.UIMainBirthdaySetTipBtn")
local UIMainSaveGirlBubbleCtrl = require("UI.LWMainUI.Component.UIMainLeft.UIMainSaveGirlBubbleCtrl")
local UIMainCityEvent = require("UI.LWMainUI.Component.UIMainLeft.UIMainCityEvent")
local player_btn_path = "playerObj/PlayerBtn"
local player_bg_path = "playerObj/PlayerBtn/Image"
local player_head_path = "playerObj/PlayerBtn/UIPlayerHead"
local player_level_path = "playerObj/PlayerBtn/LevelBg/LevelText"
local player_redDot_path = "playerObj/PlayerBtn/RedPoint"
local player_haveApply_path = "playerObj/PlayerBtn/haveApplyImg"
local player_stamina_path = "playerObj/Stamina"
local player_stamina_text_path = "playerObj/Stamina/StaminaBtn/staminaText"
local player_stamina_slider_path = "playerObj/Stamina/Slider"
local common_red_point_path = "playerObj/Stamina/StaminaBtn/CommonRedPoint"
local player_stamina_click_btn_path = "playerObj/Stamina/StaminaBtn"
local troop_obj_path = "troopNode"
local troop_list_obj_path = "troopNode"
local build_queue_path = "layout/BuildQueue"
local vip_path = "layout/PlayerVIPLevel"
local science_queue_path = "layout/ScienceQueue"
local save_girl_warning_path = "layout/SaveGirlWarning"
local layout_path = "layout"
local cityEvent_path = "layout/CityEvent"
local updateRefreshTime = 0
local updateRefreshTimeInterval = 5

function UIMainLeft:OnCreate()
  base.OnCreate(self)
  local ok, errorMsg = pcall(function()
    self:ComponentDefine()
    self:DataDefine()
  end)
  if not ok and errorMsg then
    Logger.LogError(errorMsg)
  end
end

function UIMainLeft:OnDestroy()
  self:TryDestroyBirthdaySetTipBtn()
  self:ComponentDestroy()
  self:DataDestroy()
  base.OnDestroy(self)
end

function UIMainLeft:OnEnable()
  base.OnEnable(self)
end

function UIMainLeft:OnDisable()
  base.OnDisable(self)
end

function UIMainLeft:OnAddListener()
  base.OnAddListener(self)
  self:AddUIListener(EventId.PostLayoutSizeChanged, self.OnLayoutSizeChanged)
  self:AddUIListener(EventId.MainLvUp, self.RefreshPlayerInfo)
  self:AddUIListener(EventId.PlayerStaminaUpdate, self.RefreshStamina)
  self:AddUIListener(EventId.UpdatePlayerHeadIcon, self.RefreshHeroIcon)
  self:AddUIListener(EventId.OnClaimCollectRewardSucc, self.ShowCollectRewardFlyEff)
  self:AddUIListener(EventId.RefreshClaimFreeStamina, self.RefreshClaimFreeStamina)
  self:AddUIListener(EventId.UpdateAIHelpRedPoint, self.RefreshCustomerServiceRedPoint)
  self:AddUIListener(EventId.OfficialApplyTipRefresh, self.RefreshOfficialApplyPoint)
  self:AddUIListener(EventId.KingdomPositionInfoUpdate, self.RefreshOfficialApplyPoint)
  self:AddUIListener(EventId.LWSeasonWeatherInfoUpdate, self.SeasonWeatherInfoUpdate)
  self:AddUIListener(EventId.SeasonHunterBattleStatus, self.SeasonWeatherInfoUpdate)
  self:AddUIListener(EventId.SeasonHunterGetActivityInfo, self.SeasonWeatherInfoUpdate)
  self:AddUIListener(EventId.OnEnterCrossServer, self.SeasonWeatherInfoUpdate)
  self:AddUIListener(EventId.OnQuitCrossServer, self.SeasonWeatherInfoUpdate)
  self:AddUIListener(EventId.PushBloodQueenNextRound, self.SeasonWeatherInfoUpdate)
  self:AddUIListener(EventId.OnBirthdayDataInfoOpenNeedSetTipStatusChange, self.RefreshBirthdaySetTipBtn)
end

function UIMainLeft:OnRemoveListener()
  self:RemoveUIListener(EventId.PostLayoutSizeChanged, self.OnLayoutSizeChanged)
  self:RemoveUIListener(EventId.MainLvUp, self.RefreshPlayerInfo)
  self:RemoveUIListener(EventId.PlayerStaminaUpdate, self.RefreshStamina)
  self:RemoveUIListener(EventId.UpdatePlayerHeadIcon, self.RefreshHeroIcon)
  self:RemoveUIListener(EventId.OnClaimCollectRewardSucc, self.ShowCollectRewardFlyEff)
  self:RemoveUIListener(EventId.RefreshClaimFreeStamina, self.RefreshClaimFreeStamina)
  self:RemoveUIListener(EventId.UpdateAIHelpRedPoint, self.RefreshCustomerServiceRedPoint)
  self:RemoveUIListener(EventId.OfficialApplyTipRefresh, self.RefreshOfficialApplyPoint)
  self:RemoveUIListener(EventId.KingdomPositionInfoUpdate, self.RefreshOfficialApplyPoint)
  self:RemoveUIListener(EventId.LWSeasonWeatherInfoUpdate, self.SeasonWeatherInfoUpdate)
  self:RemoveUIListener(EventId.SeasonHunterBattleStatus, self.SeasonWeatherInfoUpdate)
  self:RemoveUIListener(EventId.SeasonHunterGetActivityInfo, self.SeasonWeatherInfoUpdate)
  self:RemoveUIListener(EventId.OnEnterCrossServer, self.SeasonWeatherInfoUpdate)
  self:RemoveUIListener(EventId.OnQuitCrossServer, self.SeasonWeatherInfoUpdate)
  self:RemoveUIListener(EventId.PushBloodQueenNextRound, self.SeasonWeatherInfoUpdate)
  self:RemoveUIListener(EventId.OnBirthdayDataInfoOpenNeedSetTipStatusChange, self.RefreshBirthdaySetTipBtn)
  base.OnRemoveListener(self)
end

function UIMainLeft:ComponentDefine()
  self.player_btn = self:AddComponent(UIButton, player_btn_path)
  self.player_bg = self:AddComponent(UIImage, player_bg_path)
  self.player_head = self:AddComponent(UICommonHead, player_head_path)
  self.player_level = self:AddComponent(UIText, player_level_path)
  self.player_redDot_img = self:AddComponent(UIImage, player_redDot_path)
  self.player_haveApply_img = self:AddComponent(UIImage, player_haveApply_path)
  self.stamina_root = self:AddComponent(UIBaseContainer, player_stamina_path)
  self.stamina_num = self:AddComponent(UIText, player_stamina_text_path)
  self.stamina_slider = self:AddComponent(UISlider, player_stamina_slider_path)
  self.stamina_btn = self:AddComponent(UIButton, player_stamina_click_btn_path)
  self.commonRedPoint = self:AddComponent(UICommonRedPoint, common_red_point_path)
  self.commonRedPoint:SetType(CommonRedPointPriority.LevelNormal)
  self.player_btn:SetOnClick(function()
    self.view.ctrl:OnFunctionClick(UIMainFunctionInfo.Info)
  end)
  self.stamina_btn:SetOnClick(function()
    self.commonRedPoint:SetViewed()
    LWResourceLackUtil:GotoSpecialResLack(ResLackContextType.Energy, nil, true)
  end)
  self.troop_obj = self:AddComponent(UIMainTroops, troop_obj_path)
  self.troopListObj = self:AddComponent(UITroopsList, troop_list_obj_path)
  self.troop_obj:SetActive(false)
  self.troopListObj:SetActive(false)
  self.build_queue = self:AddComponent(UIBuildQueue, build_queue_path)
  self.build_queue:ReInit()
  self.layout = self:AddComponent(UIHorizontalOrVerticalLayoutGroup, layout_path)
  self.vip = self:AddComponent(UIMainVipBtn, vip_path)
  self.vip:RefreshVIP()
  self.science_queue = self:AddComponent(UIScienceQueue, science_queue_path)
  self.science_queue:ReInit()
  self.saveGirlBubble = self:AddComponent(UIMainSaveGirlBubbleCtrl, save_girl_warning_path)
  self.cityEvent = self:AddComponent(UIMainCityEvent, cityEvent_path)
  self.view:RegisterFunctionUnlock(LWFunctionUnlockType.MainUI_PlayerInfo, self.player_btn.gameObject)
  self.view:RegisterFunctionUnlock(LWFunctionUnlockType.MainUI_PlayerInfo, self.stamina_root.gameObject)
end

function UIMainLeft:RefreshClaimFreeStamina()
  self:RefreshStaminaRedDot()
end

function UIMainLeft:ComponentDestroy()
  self.player_btn = nil
  self.player_head = nil
  self.player_level = nil
  self.player_redDot_img = nil
  self.player_haveApply_img = nil
  self.stamina_num = nil
  self.stamina_slider = nil
  self.stamina_btn = nil
  self.troop_obj = nil
  self.troopListObj = nil
  self.vip = nil
  self.saveGirlBubble = nil
  self.cityEvent = nil
end

function UIMainLeft:DataDefine()
end

function UIMainLeft:DataDestroy()
  if self.delay then
    self.delay:Stop()
    self.delay = nil
  end
end

function UIMainLeft:ReInit()
  self:RefreshPlayerInfo()
  self:RefreshStamina()
  self:RefreshHeroIcon()
  self:RefreshStaminaRedDot()
  self:RefreshCustomerServiceRedPoint()
  self:RefreshOfficialApplyPoint()
  self.troop_obj:ReInit()
  self.saveGirlBubble:ReInit()
  self.cityEvent:ReInit()
  self:TryShowBirthdaySetTipBtn()
end

function UIMainLeft:OnLayoutSizeChanged(data)
  if data ~= nil and data.t == LayoutSizeChangeType.MainUIResourceBar and data.h ~= nil then
    local height = toInt(data.h)
    if 164 < height and SceneUtils.GetIsInWorld() then
      local seasonType = SeasonUtil.GetSeasonType()
      if seasonType == SeasonMapType.Darkness then
        height = height + 7
      end
      self.layout:SetPaddingTop(height - 164 + 15)
      CS.UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.layout.rectTransform)
    end
    self.layout_size_height = 0
  end
end

function UIMainLeft:RefreshStaminaRedDot()
  local unlock = DataCenter.LWFunctionUnlockManager:CheckCanShow(LWFunctionUnlockType.ClaimFreeStamina)
  if not unlock then
    self.commonRedPoint:SetActive(false)
    return
  end
  local time = UIUtil.GetFreeStaminaTime()
  if not time or time == 0 then
    self.commonRedPoint:SetDefaultVisible(true)
  elseif 0 < time then
    self.commonRedPoint:SetActive(false)
    self.delay = TimerManager:GetInstance():DelayInvoke(function()
      self:RefreshStaminaRedDot()
    end, time + 1)
  end
end

function UIMainLeft:RefreshPlayerInfo()
  self.player_level:SetText(DataCenter.BuildManager.MainLv)
end

function UIMainLeft:RefreshStamina()
  local maxNum = 100
  local curNum = LuaEntry.Player:GetCurStamina()
  local config = DataCenter.ArmyFormationDataManager:GetConfigData()
  if config ~= nil then
    maxNum = config.FormationStaminaMax
  end
  local tempValue = math.min(1, curNum / maxNum)
  self.stamina_slider:SetValue(tempValue)
  self.stamina_num:SetText(string.GetFormattedSeperatorNum(math.floor(curNum)))
end

function UIMainLeft:Update1000MS()
  local curTime = UITimeManager:GetInstance():GetServerSeconds()
  if curTime > updateRefreshTime then
    updateRefreshTime = curTime + updateRefreshTimeInterval
    self:RefreshStamina()
  end
  if self.weatherObj and self.layout then
    local x, y = self.layout.rectTransform:Get_sizeDelta()
    if self.layout_size_height ~= y then
      self.layout_size_height = y
      if self.troop_obj and 100 < y then
        self.troop_obj:SetLocalPositionXYZ(86, -30 - (y - 100) / 2, 0)
      end
    end
  end
end

function UIMainLeft:RefreshHeroIcon()
  local uid = LuaEntry.Player:GetUid()
  local pic = LuaEntry.Player:GetPic()
  local picVer = LuaEntry.Player.picVer
  local headSkinPath = LuaEntry.Player:GetHeadBgImg()
  self.player_head:SetData(uid, pic, picVer, nil, headSkinPath)
end

function UIMainLeft:GetPlayerLevelPos()
  return self.player_level.gameObject.transform.position
end

function UIMainLeft:GetBuildQueuePos()
  return self.build_queue.gameObject.transform.position
end

function UIMainLeft:GetSaveGirlWarningPos()
  return self.saveGirlBubble.gameObject.transform.position
end

function UIMainLeft:OnEnterWorld(data)
  self.troop_obj:SetActive(true)
  self.troopListObj:SetActive(true)
  self.build_queue:SetActive(false)
  self.science_queue:SetActive(false)
  self.vip:SetActive(false)
  self.saveGirlBubble:SetActiveLogic(false)
  self.cityEvent:ReInit()
  self:ShowOrHideWeather(true)
end

function UIMainLeft:OnEnterCity(data)
  self.troop_obj:SetActive(false)
  self.troopListObj:SetActive(false)
  self.build_queue:SetActive(true)
  self.build_queue:ReInit()
  self.science_queue:SetActive(true)
  self.science_queue:ReInit()
  self.vip:SetActive(true)
  self.vip:RefreshVIP()
  self.saveGirlBubble:ReInit()
  self.cityEvent:ReInit()
  self:ShowOrHideWeather(false)
end

function UIMainLeft:AddCurMarchList()
  if self.troop_obj ~= nil then
    self.troop_obj:AddCurMarchList()
  end
end

function UIMainLeft:IsTroopListShow()
  return self.troopListObj ~= nil and self.troopListObj:GetActive()
end

function UIMainLeft:UpdateLod(lod)
  self.lodCache = lod
end

function UIMainLeft:SetTroopListShow(show, loopListIndex)
  if show and self.lodCache <= 3 then
    if loopListIndex == 1 then
      self.troopListObj:ShowMarchItemList()
    elseif loopListIndex == 2 then
      self.troopListObj:ShowDetectItemList()
    end
  else
    if loopListIndex == 1 then
      self.troopListObj:HideMarchItemList()
    elseif loopListIndex == 2 then
      self.troopListObj:HideDetectItemList()
    end
    self.view.ctrl:SetSelectFormationUuid(0)
    self.view:HideAllShowTip()
  end
end

function UIMainLeft:IsTroopListShow()
  return self.troopListObj ~= nil and self.troopListObj:GetActive()
end

function UIMainLeft:HideAllShowTip()
  self.troopListObj:HideAllShowTip()
end

function UIMainLeft:ShowFormationRallyTip(x, y, dataInfo)
  self.troopListObj:ShowFormationRallyTip(x, y, dataInfo)
end

function UIMainLeft:OnSelectClick(uuid)
  self.troopListObj:OnSelectClick(uuid)
end

function UIMainLeft:ShowFormationCreateTip(x, y, dataInfo)
  self.troopListObj:ShowFormationCreateTip(x, y, dataInfo)
end

function UIMainLeft:OnAtkClick(uuid)
  self.troopListObj:OnAtkClick(uuid)
end

function UIMainLeft:OnCreateClick(uuid)
  self.troopListObj:OnCreateClick(uuid)
end

function UIMainLeft:OnEditClick(uuid, needAutoAdd)
  self.troopListObj:OnEditClick(uuid, needAutoAdd)
end

function UIMainLeft:GetTimeInFormation(uuid)
  return self.troopListObj:GetTimeInFormation(uuid)
end

function UIMainLeft:OnClickStartInvestigate(targetPointId)
  self.troopListObj:OnClickStartInvestigate(targetPointId)
end

function UIMainLeft:ResetScoutSelectTipPosition(posX, posY)
  return self.troopListObj:ResetScoutSelectTipPosition(posX, posY)
end

function UIMainLeft:OnClickScoutTroopItem(formationIndex)
  return self.troopListObj:OnClickScoutTroopItem(formationIndex)
end

function UIMainLeft:GetScoutTroopUnlockLv(formationIndex)
  return self.troopListObj:GetScoutTroopUnlockLv(formationIndex)
end

function UIMainLeft:ShowFormationArmyTip(x, y, dataInfo)
  self.troopListObj:ShowFormationArmyTip(x, y, dataInfo)
end

function UIMainLeft:ShowCollectRewardFlyEff(rewards)
  self.troop_obj:PlayCollectRewardFlyEff(rewards)
end

function UIMainLeft:RefreshCustomerServiceRedPoint()
  local show = DataCenter.LWCustomerServiceManager:GetCustomerServiceRedPointData()
  self.player_redDot_img:SetActive(show)
end

function UIMainLeft:ShowOrHideWeather(isWorld)
  if isWorld then
    local isInSeason = SeasonUtil.IsInSeason(false)
    local seasonType = SeasonUtil.GetSeasonType()
    if isInSeason and seasonType == SeasonMapType.Snow and DataCenter.SeasonSnowStormDataManager:NeedShowBlizzardInMainUI() then
      self:ShowWeather(WeatherObjectInfo.SnowStorm)
      return
    elseif isInSeason and seasonType == SeasonMapType.Darkness and DataCenter.BloodyNightDataManager:GetBloodyNightState() ~= BloodyNightState.None then
      if DataCenter.SeasonHunterManager:IsBattleBegin() then
        self:ShowWeather(WeatherObjectInfo.Hunter)
      else
        self:ShowWeather(WeatherObjectInfo.BloodyMoon)
      end
      return
    elseif not isInSeason and seasonType ~= SeasonMapType.Nothing and DataCenter.OffSeason1QueenOfBloodManager:ShowQueenOfBloodRound() then
      self:ShowWeather(WeatherObjectInfo.QueenOfBlood)
      return
    end
    if seasonType ~= SeasonMapType.Nothing then
      DataCenter.SeasonWeatherManager:TryRequestData()
      if DataCenter.SeasonWeatherManager:CanShow() then
        self:ShowWeather(WeatherObjectInfo.SeasonWeather)
        return
      end
      if seasonType == SeasonMapType.Darkness then
        self:ShowWeather(WeatherObjectInfo.BloodyMoon)
        return
      end
    end
  end
  self:HideWeather()
end

function UIMainLeft:ShowWeather(objectInfo)
  if not objectInfo then
    return
  end
  if self.weatherObj then
    if self.weatherObj.objectType == objectInfo.type then
      self.weatherObj:Refresh()
      return
    else
      self:HideWeather()
    end
  end
  if not self.weatherObjReq then
    self.weatherObjReq = self:GameObjectInstantiateAsync(objectInfo.path, function(req)
      local gameObject = req.gameObject
      if IsNull(gameObject) then
        return
      end
      local transform = gameObject.transform
      gameObject:SetActive(true)
      transform:SetParent(self.layout.transform)
      transform:Set_localScale(ResetScale.x, ResetScale.y, ResetScale.z)
      transform:SetSiblingIndex(0)
      local name = gameObject.name
      self.weatherObj = self.layout:AddComponent(require(objectInfo.script), name)
      self.weatherObj.objectType = objectInfo.type
      self.weatherObj:Refresh()
      local param = {}
      param.t = LayoutSizeChangeType.MainUIResourceBar
      
      function param.f(width, height)
        self:OnLayoutSizeChanged({
          t = LayoutSizeChangeType.MainUIResourceBar,
          w = width,
          h = height
        })
      end
      
      self.layout_size_height = 0
      EventManager:GetInstance():Broadcast(EventId.QueryLayoutSize, param)
    end)
  end
end

function UIMainLeft:HideWeather()
  if self.weatherObj then
    local objInfo = WeatherObjectInfo[self.weatherObj.objectType]
    if objInfo then
      self.layout:RemoveComponents(require(objInfo.script))
    end
    self.weatherObj = nil
  end
  if self.weatherObjReq then
    self.weatherObjReq:Destroy()
    self.weatherObjReq = nil
  end
  self.layout_size_height = 0
  self.troop_obj:SetLocalPositionXYZ(86, -30, 0)
  self.layout:SetPaddingTop(0)
  CS.UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.layout.rectTransform)
end

function UIMainLeft:RefreshOfficialApplyPoint()
  if DataCenter.GovernmentManager:SwitchOpenOrAtHomeNow() then
    self.player_haveApply_img:SetActive(DataCenter.OfficialApplyManager:HaveApplyRed())
  else
    self.player_haveApply_img:SetActive(false)
  end
end

function UIMainLeft:SeasonWeatherInfoUpdate()
  if self.whenWeatherInfoUpdate == true then
    return
  end
  self.whenWeatherInfoUpdate = true
  self:ShowOrHideWeather(SceneUtils.GetIsInWorld())
  self.whenWeatherInfoUpdate = false
end

function UIMainLeft:TryShowBirthdaySetTipBtn()
  local isShow = DataCenter.BirthdayDataManager.isBirthdayDataInfoOpenNeedSetTip
  if isShow == false then
    return
  end
  if self.BirthdaySetTipBtnReq ~= nil then
    return
  end
  self.BirthdaySetTipBtnReq = self:GameObjectInstantiateAsync("Assets/Main/Prefabs/UI/LWMainUI/Birthday/BirthdaySetTipBtn.prefab", function(request)
    if request.isError then
      return
    end
    local go = request.gameObject
    go.name = "BirthdaySetTipBtn"
    go:SetActive(true)
    go.transform:SetParent(self.player_btn.transform)
    local birthdaySetTipBtn = self.player_btn:AddComponent(UIMainBirthdaySetTipBtn, "BirthdaySetTipBtn")
    birthdaySetTipBtn:SetAsLastSibling()
    birthdaySetTipBtn:SetLocalScaleXYZ(1, 1, 1)
    if CommonUtil.IsArabicAutoMirrorOpen() then
      birthdaySetTipBtn:SetAnchorMinXY(0, 0.5)
      birthdaySetTipBtn:SetAnchorMaxXY(0, 0.5)
      birthdaySetTipBtn:SetPivotXY(1, 0.5)
    else
      birthdaySetTipBtn:SetAnchorMinXY(1, 0.5)
      birthdaySetTipBtn:SetAnchorMaxXY(1, 0.5)
      birthdaySetTipBtn:SetPivotXY(0, 0.5)
    end
    birthdaySetTipBtn:SetAnchoredPositionXY(0, 0)
  end)
end

function UIMainLeft:TryDestroyBirthdaySetTipBtn()
  if self.BirthdaySetTipBtnReq ~= nil then
    self.player_btn:RemoveComponents(UIMainBirthdaySetTipBtn)
    self:GameObjectDestroy(self.BirthdaySetTipBtnReq)
    self.BirthdaySetTipBtnReq = nil
  end
end

function UIMainLeft:RefreshBirthdaySetTipBtn(data)
  if data then
    self:TryShowBirthdaySetTipBtn()
  else
    self:TryDestroyBirthdaySetTipBtn()
  end
end

return UIMainLeft
