local RewardUtil = require("Util.RewardUtil")
local UIMarchQueueFormationListCell = require("UI.UIMain.Component.UIMainBottom.TroopList.UIMarchQueueFormationListCell")
local FormationScoutSelectList = require("UI.UIMain.Component.UIMainBottom.TroopList.UIMainFormationScoutSelectList")
local LIST_HEAD_HEIGHT = 60
local MainTroopList = BaseClass("MainTroopList", UIBaseContainer)
local base = UIBaseContainer
local Localization = CS.GameEntry.Localization
local ResourceManager = CS.GameEntry.Resource
local content_path = "MarchQueueContent/troopList/Mask/Content1"
local content_path2 = "DetectQueueContent/troopList/Mask/Content2"
local formation_army_tip_path = "FormationArmyTip"
local create_army_tip_path = "CreateArmyTip"
local formationScoutSelectList_path = "DetectQueueContent/troopList"
local march_queue_content_path = "MarchQueueContent"
local detect_queue_content_path = "DetectQueueContent"
local OnCreate = function(self)
  base.OnCreate(self)
  self.view.ctrl:InitData()
  self.curFormationType = self.view.ctrl.formationType
  self.march_list_content = self:AddComponent(UIBaseContainer, content_path)
  self.detect_list_content = self:AddComponent(UIBaseContainer, content_path2)
  self.uIMainFormationScoutSelectList = self:AddComponent(FormationScoutSelectList, formationScoutSelectList_path)
  
  function self.timer_action(temp)
    self:RefreshFormationStamina()
  end
  
  self.FormationTimeList = {}
  self.marchFormationList = {}
  self.FormationPowerList = {}
  self.dragInstance = nil
  self.march_queue_content = self:AddComponent(UIBaseContainer, march_queue_content_path)
  self.detect_queue_content = self:AddComponent(UIBaseContainer, detect_queue_content_path)
  self:DataDefine()
end
local OnDestroy = function(self)
  if self.delayTimer then
    self.delayTimer:Stop()
    self.delayTimer = nil
  end
  self.title = nil
  self.march_list_content = nil
  self.detect_list_content = nil
  self.march_queue_content = nil
  self.detect_queue_content = nil
  self.return_btn = nil
  self.marchFormationList = nil
  self.uIMainFormationScoutSelectList = nil
  self:DataDestroy()
  base.OnDestroy(self)
end
local OnEnable = function(self)
  base.OnEnable(self)
  self:OnRefresh(nil, true)
  self:AddTimer()
end
local OnDisable = function(self)
  self:DeleteTimer()
  if self.troopActionTimer ~= nil then
    self.troopActionTimer:Stop()
    self.troopActionTimer = nil
  end
  base.OnDisable(self)
end
local DataDefine = function(self)
  self.isMarchListActive = DataCenter.WorldMarchDataManager:IsHaveMarchInWorld() or RewardUtil.IsHaveWorldReward()
  self.isDetectListActive = self.view.ctrl:IsExistMarchInvesFormation()
  self.isDetectListOpen = false
  self.isMarchListOpen = self.isMarchListActive
end
local DataDestroy = function(self)
  self.isMarchListOpen = nil
  self.isDetectListOpen = nil
  self.isDetectListActive = nil
  self.isMarchListActive = nil
end
local SetFormationType = function(self, formationType)
  self.curFormationType = formationType
end
local ClearContent = function(self)
  self.march_list_content:RemoveComponents(UIMarchQueueFormationListCell)
  if self.marchModel ~= nil then
    for k, v in pairs(self.marchModel) do
      if v ~= nil then
        self:GameObjectDestroy(v)
      end
    end
  end
  self.marchModel = {}
  self.marchFormationList = {}
end
local GetMarchingCountByMarchData = function(self)
  local data = self.view.ctrl:GetFormationListData()
  local curMarchNum = 0
  for k, v in pairs(data.list) do
    local march = DataCenter.WorldMarchDataManager:GetOwnerFormationMarch(LuaEntry.Player.uid, v, LuaEntry.Player.allianceId)
    if march then
      curMarchNum = curMarchNum + 1
    end
  end
  for _, _ in pairs(DataCenter.WorldMarchDataManager:GetMyDisguiseMarches()) do
    curMarchNum = curMarchNum + 1
  end
  return curMarchNum
end
local OnRefresh = function(self, show, isInit)
  local inCity = SceneUtils.GetIsInCity()
  if inCity then
    return
  end
  self:ClearContent()
  local data = self.view.ctrl:GetFormationListData()
  if data ~= nil then
    local list = data.list
    if list ~= nil then
      self.curMarchNum = self:GetMarchingCountByMarchData()
      for i = 1, data.maxNum do
        if list[i] then
          local marchInfo = self.view.ctrl:GetFormationItemData(list[i])
          if marchInfo.isMarch > 0 then
            self.marchModel[#self.marchModel + 1] = self:GameObjectInstantiateAsync(UIAssets.UIMainFormationSelectListCellNew, function(request)
              if request.isError then
                return
              end
              local go = request.gameObject
              go.gameObject:SetActive(true)
              go.transform:SetParent(self.march_list_content.transform)
              go.transform:Set_localScale(ResetScale.x, ResetScale.y, ResetScale.z)
              local nameStr = tostring(NameCount)
              go.name = nameStr
              NameCount = NameCount + 1
              local cell = self.march_list_content:AddComponent(UIMarchQueueFormationListCell, nameStr)
              cell:SetUuidAndIndex(i, list[i])
              cell:RefreshData(show)
              self.marchFormationList[#self.marchFormationList + 1] = cell
              if #self.marchFormationList >= #self.marchModel then
                self:OnListComplete(isInit)
              end
            end)
          end
        end
      end
      do
        local myDisguiseMarches = DataCenter.WorldMarchDataManager:GetMyDisguiseMarches()
        for _, v in pairs(myDisguiseMarches) do
          self.marchModel[#self.marchModel + 1] = self:GameObjectInstantiateAsync(UIAssets.UIMainFormationSelectListCellNew, function(request)
            if request.isError then
              return
            end
            local go = request.gameObject
            go.gameObject:SetActive(true)
            go.transform:SetParent(self.march_list_content.transform)
            go.transform:Set_localScale(ResetScale.x, ResetScale.y, ResetScale.z)
            local nameStr = tostring(NameCount)
            go.name = nameStr
            NameCount = NameCount + 1
            local cell = self.march_list_content:AddComponent(UIMarchQueueFormationListCell, nameStr)
            cell:SetDisguiseMarchUuidAndIndex(v.uuid, #self.marchFormationList + 1)
            cell:RefreshData(show)
            self.marchFormationList[#self.marchFormationList + 1] = cell
            if #self.marchFormationList >= #self.marchModel then
              self:OnListComplete(isInit)
            end
          end)
        end
        local isOpen = DataCenter.MonthCardNewManager:CheckIfMonthCardActive()
        if #list < data.maxNum and not isOpen then
          self.marchModel[#self.marchModel + 1] = self:GameObjectInstantiateAsync(UIAssets.UIMainFormationSelectListCellNew, function(request)
            if request.isError then
              return
            end
            local go = request.gameObject
            go.gameObject:SetActive(true)
            go.transform:SetParent(self.march_list_content.transform)
            go.transform:Set_localScale(ResetScale.x, ResetScale.y, ResetScale.z)
            local nameStr = tostring(NameCount)
            go.name = nameStr
            NameCount = NameCount + 1
            local cell = self.march_list_content:AddComponent(UIMarchQueueFormationListCell, nameStr)
            cell:SetUuidAndIndex(#self.marchFormationList + 1)
            cell:RefreshData(show)
            self.marchFormationList[#self.marchFormationList + 1] = cell
            if #self.marchFormationList >= #self.marchModel then
              self:OnListComplete(isInit)
            end
          end)
        end
        if table.IsNullOrEmpty(self.marchModel) then
          self:OnListComplete(isInit)
        end
      end
    end
  end
  self.uIMainFormationScoutSelectList:InitUI()
end
local OnListComplete = function(self, isInit)
  CS.UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.march_list_content.transform)
  CS.UnityEngine.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.detect_list_content.transform)
  local height = self.march_list_content.rectTransform.rect.height
  self.isMarchListActive = DataCenter.WorldMarchDataManager:IsHaveMarchInWorld() or RewardUtil.IsHaveWorldReward()
  local headOffset = self.isMarchListActive and -height - LIST_HEAD_HEIGHT or -height
  self.detect_queue_content.transform.localPosition = Vector3.New(self.detect_queue_content.transform.localPosition.x, headOffset, 0)
  self:RefreshListState()
end
local OnMarchItemUpdateSelf = function(self)
  local curMarchNum = self:GetMarchingCountByMarchData()
  if self.curMarchNum == curMarchNum then
    if self.marchFormationList ~= nil then
      table.walk(self.marchFormationList, function(k, v)
        v:RefreshMarchData()
      end)
    end
    self:RefreshListState()
  else
    self:OnRefresh()
  end
end
local OnMarchRefresh = function(self)
  local curMarchNum = self:GetMarchingCountByMarchData()
  if self.curMarchNum == curMarchNum then
    if self.marchFormationList ~= nil then
      table.walk(self.marchFormationList, function(k, v)
        v:RefreshMarchData()
      end)
    end
    self:RefreshListState()
  else
    self:OnRefresh()
  end
end
local OnFormationRefresh = function(self)
  if CS.SceneManager.IsInPVE() then
    return
  end
  local list = {}
  local data = self.view.ctrl:GetFormationListData()
  if data ~= nil then
    list = data.list
  end
  if self.marchFormationList ~= nil then
    table.walk(self.marchFormationList, function(k, v)
      v:RefreshData()
    end)
  end
end
local OnSelectClick = function(self, uuid)
  table.walk(self.marchFormationList, function(k, v)
    v:OnSelectClick(uuid)
  end)
end
local OnAddListener = function(self)
  base.OnAddListener(self)
  self:AddUIListener(EventId.MarchItemUpdateSelf, self.OnMarchItemUpdateSelf)
  self:AddUIListener(EventId.FormationSoldierUpdate, self.OnMarchRefresh)
  self:AddUIListener(EventId.ArmyFormatUpdate, self.OnFormationRefresh)
  self:AddUIListener(EventId.ShowTroopBattleValue, self.ShowTroopBattleSignal)
  self:AddUIListener(EventId.ArmyFormationSave, self.OnFormationRefresh)
  self:AddUIListener(EventId.HideMarchTip, self.OnResetMarchTip)
  self:AddUIListener(EventId.TrainArmyData, self.OnFormationRefresh)
  self:AddUIListener(EventId.HeroLvUpSuccess, self.OnFormationRefresh)
  self:AddUIListener(EventId.ShowFormationSelect, self.ShowFormationSelect)
  self:AddUIListener(EventId.HideFormationSelect, self.HideFormationSelect)
  self:AddUIListener(EventId.ShowTroopAction, self.ShowTroopAction)
  self:AddUIListener(EventId.FormationStaminaUpdate, self.RefreshFormationStamina)
  self:AddUIListener(EventId.RefreshMonsterRewardBag, self.OnRefreshMonsterRewardBag)
  self:AddUIListener(EventId.MarchItemTargetMeUpdate, self.OnMarchItemTargetMeUpdate)
  self:AddUIListener(EventId.DetectResultDataUpdate, self.OnRefreshDetectData)
  self:AddUIListener(EventId.BankReportDataUpdate, self.OnRefreshDetectData)
end
local OnRemoveListener = function(self)
  base.OnRemoveListener(self)
  self:RemoveUIListener(EventId.ShowTroopAction, self.ShowTroopAction)
  self:RemoveUIListener(EventId.MarchItemUpdateSelf, self.OnMarchItemUpdateSelf)
  self:RemoveUIListener(EventId.FormationSoldierUpdate, self.OnMarchRefresh)
  self:RemoveUIListener(EventId.ArmyFormatUpdate, self.OnFormationRefresh)
  self:RemoveUIListener(EventId.ShowTroopBattleValue, self.ShowTroopBattleSignal)
  self:RemoveUIListener(EventId.ArmyFormationSave, self.OnFormationRefresh)
  self:RemoveUIListener(EventId.HideMarchTip, self.OnResetMarchTip)
  self:RemoveUIListener(EventId.TrainArmyData, self.OnFormationRefresh)
  self:RemoveUIListener(EventId.HeroLvUpSuccess, self.OnFormationRefresh)
  self:RemoveUIListener(EventId.ShowFormationSelect, self.ShowFormationSelect)
  self:RemoveUIListener(EventId.HideFormationSelect, self.HideFormationSelect)
  self:RemoveUIListener(EventId.FormationStaminaUpdate, self.RefreshFormationStamina)
  self:RemoveUIListener(EventId.RefreshMonsterRewardBag, self.OnRefreshMonsterRewardBag)
  self:RemoveUIListener(EventId.DetectResultDataUpdate, self.OnRefreshDetectData)
  self:RemoveUIListener(EventId.BankReportDataUpdate, self.OnRefreshDetectData)
  self:RemoveUIListener(EventId.MarchItemTargetMeUpdate, self.OnMarchItemTargetMeUpdate)
end
local ShowFormationArmyTip = function(self, posX, posY, formationData)
end
local HideAllShowTip = function(self)
end
local OnResetMarchTip = function(self)
  self.view.ctrl:SetSelectFormationUuid(0)
  self:HideAllShowTip()
end
local ShowTroopBattleSignal = function(self, data)
  local str = data
  if str ~= nil then
    local strArr = string.split(str, ";")
    if 3 < #strArr then
      local marchUuid = tonumber(strArr[1])
      local hp = tonumber(strArr[3])
      local hpMax = tonumber(strArr[4])
      if self.marchFormationList ~= nil then
        table.walk(self.marchFormationList, function(k, v)
          v:RefreshSlider(marchUuid, hp, hpMax)
        end)
      end
    end
  end
end
local ShowFormationSelect = function(self, data)
  local marchUuid = tonumber(data)
  local info = DataCenter.WorldMarchDataManager:GetMarch(marchUuid)
  if info ~= nil then
    local formationUuid = info.ownerFormationUuid
    self.view.ctrl:SetSelectFormationUuid(formationUuid)
    table.walk(self.marchFormationList, function(k, v)
      v:OnSelectClick(formationUuid)
    end)
  end
end
local HideFormationSelect = function(self, data)
  local marchUuid = tonumber(data)
  local info = DataCenter.WorldMarchDataManager:GetMarch(marchUuid)
  if info ~= nil then
    local formationUuid = info.ownerFormationUuid
    if self.view.ctrl.selectFormationUuid == 0 or self.view.ctrl.selectFormationUuid == formationUuid then
      self.view.ctrl:SetSelectFormationUuid(0)
      self:HideAllShowTip()
      table.walk(self.marchFormationList, function(k, v)
        v:OnSelectClick(0)
      end)
    end
  end
end
local ShowFormationCreateTip = function(self, posX, posY, formationData)
end
local ShowFormationRallyTip = function(self, posX, posY, formationData)
end
local GetTimeInFormation = function(self, formationUuid)
  return self.view.ctrl:GetTimeFormCurPosToTarPos(formationUuid)
end
local OnAtkClick = function(self, uuid)
  if CS.SceneManager:IsInCity() then
  else
  end
end
local OnEditClick = function(self, uuid, needAutoFix)
  if CS.SceneManager:IsInCity() then
    self.view.ctrl:OnCreateMarchInGuide(uuid, needAutoFix)
  else
    self.view.ctrl:OnEditClick(uuid, needAutoFix)
  end
end
local OnCreateClick = function(self, uuid)
  if CS.SceneManager:IsInCity() then
  else
  end
end
local OnClickScoutTroopItem = function(self, tempIndex)
  if self.uIMainFormationScoutSelectList then
    return self.uIMainFormationScoutSelectList:OnSelectTroopBtnClick(tempIndex)
  end
end
local GetScoutTroopUnlockLv = function(self, formationIndex)
  if self.uIMainFormationScoutSelectList then
    return self.uIMainFormationScoutSelectList:GetUnlockLv(formationIndex)
  end
end
local ResetScoutSelectTipPosition = function(self, posX, posY)
  if self.uIMainFormationScoutSelectList then
    return self.uIMainFormationScoutSelectList:ResetTipPosition(posX, posY)
  end
end
local GetInvesFormationStateDes = function(self)
  if self.uIMainFormationScoutSelectList then
    return self.uIMainFormationScoutSelectList:GetInvesFormationStateDes()
  end
end
local GetInvesCostTime = function(self, targetPointID)
  if self.uIMainFormationScoutSelectList then
    return self.uIMainFormationScoutSelectList:GetInvesCostTime(targetPointID)
  end
end
local OnClickStartInvestigate = function(self)
  if self.uIMainFormationScoutSelectList then
    return self.uIMainFormationScoutSelectList:OnClickStartInvestigate()
  end
end
local AddTimer = function(self)
  if self.timer == nil then
    self.timer = TimerManager:GetInstance():GetTimer(1, self.timer_action, self, false, false, false)
  end
  self.timer:Start()
end
local DeleteTimer = function(self)
  if self.timer ~= nil then
    self.timer:Stop()
    self.timer = nil
  end
end
local RefreshFormationStamina = function(self)
  if self.marchFormationList ~= nil then
    table.walk(self.marchFormationList, function(k, v)
      v:UpdateTime()
    end)
  end
  if self.uIMainFormationScoutSelectList then
    self.uIMainFormationScoutSelectList:RefreshTime()
  end
end
local ShowTroopAction = function(self)
end
local OnRefreshMonsterRewardBag = function(self)
  self:RefreshListState()
end
local OnRefreshDetectData = function(self)
  self:RefreshListState()
end
local RefreshListState = function(self)
  if BattleFieldUtil.InBattleField() then
    self.isMarchListActive = true
    self.isMarchListOpen = true
    self.isDetectListActive = true
    self.isDetectListOpen = true
  else
    self.isMarchListActive = DataCenter.WorldMarchDataManager:IsHaveMarchInWorld() or RewardUtil.IsHaveWorldReward()
    self.isMarchListOpen = self.isMarchListActive
    self.isDetectListActive = self.view.ctrl:IsExistMarchInvesFormation() or not DataCenter.DetectResultDataManager:IsDataEmpty() or not DataCenter.SeasonBankReportManager:IsDataEmpty()
  end
  EventManager:GetInstance():Broadcast(EventId.MarchBtnStateChange, self.isMarchListOpen)
  EventManager:GetInstance():Broadcast(EventId.DetectBtnStateChange, self.isDetectListActive)
  if self.isDetectListActive == false then
    self.isDetectListOpen = false
  end
  self.delayTimer = TimerManager:GetInstance():DelayFrameInvoke(function()
    if self.march_list_content then
      if self.isMarchListOpen then
        self:ShowMarchItemList()
      else
        self:HideMarchItemList()
      end
      if self.isDetectListOpen then
        self:ShowDetectItemList()
      else
        self:HideDetectItemList()
      end
    end
  end, 5)
end
local ShowMarchItemList = function(self)
  local height = self.march_list_content.rectTransform.rect.height
  self.march_list_content.transform:DOKill()
  self.march_list_content.transform:DOLocalMoveY(0, 0.5)
  self.detect_queue_content.transform:DOKill()
  self.detect_queue_content.transform:DOLocalMoveY(-height - LIST_HEAD_HEIGHT, 0.5)
  self.isMarchListOpen = true
end
local ShowDetectItemList = function(self)
  self.detect_list_content.transform:DOKill()
  self.detect_list_content.transform:DOLocalMoveY(0, 0.5)
  self.isDetectListOpen = true
end
local HideMarchItemList = function(self)
  if not self.march_list_content then
    return
  end
  local height = self.march_list_content.rectTransform.rect.height
  self.march_list_content.transform:DOKill()
  self.march_list_content.transform:DOLocalMoveY(height, 0.5)
  self.detect_queue_content.transform:DOKill()
  local headOffset = self.isMarchListActive and -LIST_HEAD_HEIGHT or 0
  self.detect_queue_content.transform:DOLocalMoveY(headOffset, 0.5)
  self.isMarchListOpen = false
end

function MainTroopList:OnMarchItemTargetMeUpdate()
  if not DataCenter.ActMeteoriteBattleManager:IsInMeteoriteBattle() then
    return
  end
  if self.marchFormationList ~= nil then
    table.walk(self.marchFormationList, function(k, v)
      v:RefreshMeteoriteUnderAttackAlarm()
    end)
  end
end

local HideDetectItemList = function(self)
  local height = self.detect_list_content.rectTransform.rect.height
  self.detect_list_content.transform:DOKill()
  self.detect_list_content.transform:DOLocalMoveY(height, 0.5)
  self.isDetectListOpen = false
end
MainTroopList.OnCreate = OnCreate
MainTroopList.OnDestroy = OnDestroy
MainTroopList.OnRefresh = OnRefresh
MainTroopList.OnEnable = OnEnable
MainTroopList.OnDisable = OnDisable
MainTroopList.OnAddListener = OnAddListener
MainTroopList.OnRemoveListener = OnRemoveListener
MainTroopList.OnMarchRefresh = OnMarchRefresh
MainTroopList.OnMarchItemUpdateSelf = OnMarchItemUpdateSelf
MainTroopList.ShowFormationArmyTip = ShowFormationArmyTip
MainTroopList.ShowFormationRallyTip = ShowFormationRallyTip
MainTroopList.ShowFormationCreateTip = ShowFormationCreateTip
MainTroopList.ClearContent = ClearContent
MainTroopList.GetTimeInFormation = GetTimeInFormation
MainTroopList.OnAtkClick = OnAtkClick
MainTroopList.OnEditClick = OnEditClick
MainTroopList.OnCreateClick = OnCreateClick
MainTroopList.OnSelectClick = OnSelectClick
MainTroopList.ShowTroopBattleSignal = ShowTroopBattleSignal
MainTroopList.HideAllShowTip = HideAllShowTip
MainTroopList.OnClickScoutTroopItem = OnClickScoutTroopItem
MainTroopList.GetScoutTroopUnlockLv = GetScoutTroopUnlockLv
MainTroopList.ResetScoutSelectTipPosition = ResetScoutSelectTipPosition
MainTroopList.GetInvesFormationStateDes = GetInvesFormationStateDes
MainTroopList.GetInvesCostTime = GetInvesCostTime
MainTroopList.OnClickStartInvestigate = OnClickStartInvestigate
MainTroopList.SetFormationType = SetFormationType
MainTroopList.OnResetMarchTip = OnResetMarchTip
MainTroopList.ShowFormationSelect = ShowFormationSelect
MainTroopList.HideFormationSelect = HideFormationSelect
MainTroopList.OnFormationRefresh = OnFormationRefresh
MainTroopList.AddTimer = AddTimer
MainTroopList.DeleteTimer = DeleteTimer
MainTroopList.RefreshFormationStamina = RefreshFormationStamina
MainTroopList.ShowTroopAction = ShowTroopAction
MainTroopList.OnRefreshMonsterRewardBag = OnRefreshMonsterRewardBag
MainTroopList.OnRefreshDetectData = OnRefreshDetectData
MainTroopList.ShowMarchItemList = ShowMarchItemList
MainTroopList.ShowDetectItemList = ShowDetectItemList
MainTroopList.HideMarchItemList = HideMarchItemList
MainTroopList.HideDetectItemList = HideDetectItemList
MainTroopList.DataDefine = DataDefine
MainTroopList.DataDestroy = DataDestroy
MainTroopList.OnListComplete = OnListComplete
MainTroopList.RefreshListState = RefreshListState
MainTroopList.GetMarchingCountByMarchData = GetMarchingCountByMarchData
return MainTroopList
