local ActWinterStormManager = BaseClass("ActWinterStormManager")
local ActWinterStormInfoData = require("DataCenter.ActWinterStormManager.ActWinterStormInfoData")
local ActWinterStormLogData = require("DataCenter.ActWinterStormManager.ActWinterStormLogData")
local ActWinterStormMatchPushData = require("DataCenter.ActWinterStormManager.ActWinterStormMatchPushData")
local ActWinterStormResultData = require("DataCenter.ActWinterStormManager.ActWinterStormResultData")
local ActWinterMainTips = "ActWinterMainTips_"

function ActWinterStormManager:__init()
  self:ResetData()
  self:AddListener()
end

function ActWinterStormManager:__delete()
  self:ResetData()
  self:RemoveListener()
end

function ActWinterStormManager:ResetData()
  self.actInfo = nil
  self.logInfo = {}
  self.matchInfo = {}
  self.matchStartTime = 0
  self.matchPushInfo = nil
  self.resultInfo = nil
end

function ActWinterStormManager:AddListener()
  if self.__onApplicationPause == nil then
    function self.__onApplicationPause(isOn)
      self:OnApplicationPause(isOn)
    end
    
    EventManager:GetInstance():AddListener(EventId.APP_APPLICATION_PAUSE, self.__onApplicationPause)
  end
end

function ActWinterStormManager:RemoveListener()
  if self.__onApplicationPause ~= nil then
    EventManager:GetInstance():RemoveListener(EventId.APP_APPLICATION_PAUSE, self.__onApplicationPause)
  end
  self.__onApplicationPause = nil
end

function ActWinterStormManager:OnApplicationPause(isOn)
  if isOn then
    return
  end
  if self.matchStartTime > 0 then
    self:SendGetInfo()
  end
end

function ActWinterStormManager:OnEnterGame()
  local activityDatas = DataCenter.ActivityListDataManager:GetActivityDataByType(EnumActivity.ActWinterStorm.Type)
  local activityData = activityDatas ~= nil and activityDatas[1] or nil
  if activityData ~= nil then
    self:SendGetInfo()
  else
    self:ResetData()
  end
  BattleFieldUtil.OnReconnect(BattleFieldType.WinterStorm)
end

function ActWinterStormManager:SendGetInfo()
  SFSNetwork.SendMessage(MsgDefines.WinterStormActInfo)
end

function ActWinterStormManager:HandleGetInfo(message)
  if message == nil then
    return
  end
  local mr = self:GetMarchResult()
  local battleEndTime = mr ~= nil and mr.battleEndTime or 0
  local oneData = ActWinterStormInfoData.New()
  oneData:ParseData(message)
  self.actInfo = oneData
  if oneData.state == 1 then
    if self.matchStartTime == 0 then
      self.matchStartTime = UITimeManager:GetInstance():GetServerSeconds()
    end
  else
    if 0 < self.matchStartTime then
      self.matchStartTime = 0
    end
    if self.state == 2 and not UIManager:GetInstance():IsWindowOpen(UIWindowNames.UIWinterStormMatching) then
      self:SendMatchReady(false)
    end
  end
  local mr2 = self:GetMarchResult()
  local battleEndTime2 = mr2 ~= nil and mr2.battleEndTime or 0
  if battleEndTime2 == 0 and 0 < battleEndTime then
    DataCenter.ActWinterStormManager:SendResult()
  end
  EventManager:GetInstance():Broadcast(EventId.WinterStormInfoRefresh)
  EventManager:GetInstance():Broadcast(EventId.RefreshActivityRedDot)
  EventManager:GetInstance():Broadcast(EventId.RefreshRaceEntrance)
end

function ActWinterStormManager:GetActInfo()
  return self.actInfo
end

function ActWinterStormManager:GetCfgValue(key, season)
  return BattleFieldUtil.GetBattleFieldCfgValue(BattleFieldType.WinterStorm, key, season)
end

function ActWinterStormManager:CheckBattleStart()
  return self:BattleOpenCheck(false)
end

function ActWinterStormManager:BattleOpenCheck(bShowTip)
  local mr = DataCenter.ActWinterStormManager:GetMarchResult()
  if mr ~= nil then
    local curSec = UITimeManager:GetInstance():GetServerSeconds()
    if mr.battleBeginTime > 0 and curSec >= mr.battleBeginTime then
      return true
    end
  end
  if bShowTip then
    UIUtil.ShowTipsId("winter_battlefield_tips1007")
  end
  return false
end

function ActWinterStormManager:GetMarchResult()
  return self.actInfo ~= nil and self.actInfo.marchResult or nil
end

function ActWinterStormManager:GetInBattleWorldLeftTime()
  local mr = DataCenter.ActWinterStormManager:GetMarchResult()
  if mr ~= nil then
    local endTime = mr.battleEndTime
    if endTime ~= nil and 0 < endTime then
      local curTime = UITimeManager:GetInstance():GetServerSeconds()
      local remainTime = endTime - curTime
      if 0 < remainTime then
        return remainTime
      end
    end
  end
  return 0
end

function ActWinterStormManager:GetMySide()
  local mr = self:GetMarchResult()
  if mr ~= nil then
    return mr:GetMySide()
  end
  return 0
end

function ActWinterStormManager:GetTeamArr(uid)
  local mr = self:GetMarchResult()
  if mr ~= nil then
    return mr:GetTeamArr(uid)
  end
  return nil
end

function ActWinterStormManager:GetWorldCampInWinterStorm(marchUuid)
  local mySide = self:GetMySide()
  local teamArr = self:GetTeamArr(marchUuid)
  if teamArr ~= nil and mySide == teamArr.side then
    return WorldCamp.WsTeammate
  end
  return WorldCamp.WsEnemy
end

function ActWinterStormManager:SendLogInfo(time, num)
  SFSNetwork.SendMessage(MsgDefines.WinterStormLog, time or 0, num or 20)
end

function ActWinterStormManager:HandleLog(message)
  if message == nil then
    return
  end
  if self.logInfo == nil then
    self.logInfo = {}
  end
  self.logInfo.totalFightCount = message.totalFightCount or 0
  self.logInfo.historyWinCount = message.historyWinCount or 0
  self.logInfo.keepWinCount = message.keepWinCount or 0
  local result = message.result
  if result ~= nil then
    local logs = self.logInfo.logs or {}
    local logTimes = {}
    for _, v in ipairs(logs) do
      logTimes[v.time] = true
    end
    for _, v in ipairs(result) do
      local time = v.battleBeginTime
      if not logTimes[time] then
        local logData = ActWinterStormLogData.New()
        logData:ParseData(v)
        table.insert(logs, logData)
      end
    end
    self.logInfo.logs = logs
  end
  if not table.IsNullOrEmpty(self.logInfo.logs) then
    table.sort(self.logInfo.logs, function(a, b)
      return a.time > b.time
    end)
  end
  UIManager:GetInstance():OpenWindow(UIWindowNames.UIWinterStormHistory)
end

function ActWinterStormManager:GetLogInfo()
  return self.logInfo or {}
end

function ActWinterStormManager:SendMatch()
  if LuaEntry.Player:IsInBlackRange(true) or LuaEntry.Player:IsInCityField(true) then
    UIUtil.ShowTipsId(458138)
    return
  end
  SFSNetwork.SendMessage(MsgDefines.WinterStormMatch)
end

function ActWinterStormManager:HandleMatch(message)
  if message == nil then
    return
  end
  self.matchStartTime = UITimeManager:GetInstance():GetServerSeconds()
  EventManager:GetInstance():Broadcast(EventId.WinterStormInfoRefresh)
end

function ActWinterStormManager:GetMatchStartTime()
  return self.matchStartTime
end

function ActWinterStormManager:CheckInBattleTime()
  local actInfo = self:GetActInfo()
  if actInfo == nil then
    return false
  end
  local curSec = UITimeManager:GetInstance():GetServerSeconds()
  local noticeEndTime = actInfo.noticeEndTime or 0
  if curSec < noticeEndTime then
    return false
  end
  local battleEndTime = actInfo.battleEndTime or 0
  if curSec >= battleEndTime then
    return false
  end
  local MyDate = os.date
  local MyModf = math.modf
  local offSet = MyModf(UITimeManager:GetInstance():GetTimezoneOffset() / 1000)
  local dateCur = MyDate("!*t", curSec + offSet)
  local battleBeginTime = actInfo.battleBeginTime or 0
  local dateBattle = MyDate("!*t", battleBeginTime + offSet)
  local hourTime = 3600
  local dayTime = hourTime * 24
  while dateCur.day > dateBattle.day do
    battleBeginTime = battleBeginTime + dayTime
    dateBattle = MyDate("!*t", battleBeginTime + offSet)
  end
  local k4 = actInfo.battleK4
  local k5 = actInfo.battleK5
  local nextTime
  for i = 1, 3 do
    local time = k4[i]
    if time ~= nil then
      local time1 = battleBeginTime + time * hourTime
      if nextTime == nil and curSec < time1 then
        nextTime = time1
      end
      local time2 = time1 + k5 * hourTime
      if curSec >= time1 and curSec < time2 then
        return true, time2
      end
    end
  end
  return false, nextTime
end

function ActWinterStormManager:SendMatchReady(bReady)
  self.bReady = bReady
  SFSNetwork.SendMessage(MsgDefines.WinterStormMatchReady, bReady)
end

function ActWinterStormManager:HandleMatchReady(message)
  if message == nil then
    return
  end
  if message.ret ~= nil then
    local ret = message.ret or 0
    if ret == 1 and self.bReady == true then
      local info = DataCenter.ActWinterStormManager:getMatchPushInfo()
      if info ~= nil then
        info:UpdateBReady(LuaEntry.Player:GetUid())
        EventManager:GetInstance():Broadcast(EventId.WinterStormMatchRefresh)
      end
    else
    end
  end
  self.bReady = false
end

function ActWinterStormManager:TryCancelMatch(cType)
  local sendFlag = false
  if self.matchStartTime > 0 then
    sendFlag = true
  else
    local state = self.actInfo ~= nil and self.actInfo.state or 0
    if state == 1 then
      sendFlag = true
    end
  end
  if sendFlag then
    SFSNetwork.SendMessage(MsgDefines.WinterStormMatchCancel, cType)
    UIUtil.ShowTipsId("winter_battlefield_tips1009")
  end
end

function ActWinterStormManager:SendMatchCancel()
  SFSNetwork.SendMessage(MsgDefines.WinterStormMatchCancel, WinterStormCancelType.Default)
end

function ActWinterStormManager:HandleMatchCancel(message)
  if message == nil then
    return
  end
  if message.ret == true then
    self.matchStartTime = 0
    EventManager:GetInstance():Broadcast(EventId.WinterStormMatchRefresh)
  end
end

function ActWinterStormManager:HandleMatchForbid(message)
  if message == nil then
    return
  end
  if message.matchCDTime then
    local actInfo = self:GetActInfo()
    if actInfo then
      actInfo.matchCDTime = message.matchCDTime
    end
    EventManager:GetInstance():Broadcast(EventId.WinterStormMatchRefresh)
  end
end

function ActWinterStormManager:HandleMatchPush(message)
  if message == nil then
    return
  end
  local oneData = ActWinterStormMatchPushData.New()
  oneData:ParseData(message)
  self.matchPushInfo = oneData
  self.matchStartTime = 0
  if message ~= nil and message.team ~= nil then
    local mr = self:GetMarchResult()
    if mr ~= nil then
      mr:ParseTeamData(message.team)
    end
  end
  EventManager:GetInstance():Broadcast(EventId.WinterStormInfoRefresh)
  local canOpen = true
  if DataCenter.GuideManager:InGuide() or CS.ApplicationLaunch.Instance.Loading.IsLoading or CS.SceneManager.IsInPVE() then
    canOpen = false
  end
  if canOpen then
    UIManager:GetInstance():OpenWindow(UIWindowNames.UIWinterStormMatching)
  end
end

function ActWinterStormManager:getMatchPushInfo()
  return self.matchPushInfo
end

function ActWinterStormManager:HandleEnterPush(message)
  if message == nil then
    return
  end
  local mr = DataCenter.ActWinterStormManager:GetMarchResult()
  if mr ~= nil then
    if message.battleBeginTime ~= nil then
      mr.battleBeginTime = message.battleBeginTime
    end
    if message.battleEndTime ~= nil then
      mr.battleEndTime = message.battleEndTime
    end
    if message.team ~= nil then
      mr:ParseTeamData(message.team)
    end
  end
  local mySide = DataCenter.ActWinterStormManager:GetMySide()
  LuaEntry.Player:SetCurTeamSideId(mySide)
  UIManager:GetInstance():DestroyWindow(UIWindowNames.UIWinterStormMatching)
  self.matchStartTime = 0
  DataCenter.ActWinterStormManager:SendGetInfo()
  DataCenter.ActWinterStormManager:TryGotoMap()
end

function ActWinterStormManager:HandleMatchReadyPush(message)
  if message == nil then
    return
  end
  local info = DataCenter.ActWinterStormManager:getMatchPushInfo()
  if info ~= nil then
    info:UpdateReadyInfo(message)
    EventManager:GetInstance():Broadcast(EventId.WinterStormMatchRefresh)
  end
end

function ActWinterStormManager:HandleMatchFailPush(message)
  if message == nil then
    return
  end
  UIManager:GetInstance():DestroyWindow(UIWindowNames.UIWinterStormMatching)
  if message.clear then
    local ret = message.clear or 2
    self.matchPushInfo = nil
    self.matchStartTime = ret == 1 and UITimeManager:GetInstance():GetServerSeconds() or 0
    EventManager:GetInstance():Broadcast(EventId.WinterStormInfoRefresh)
    if ret == 1 then
      UIUtil.ShowTipsId("winter_battlefield_tips1010")
    end
  end
end

function ActWinterStormManager:SendTaskInfo()
  SFSNetwork.SendMessage(MsgDefines.WinterStormTaskInfo)
end

function ActWinterStormManager:SendResult()
  local now = UITimeManager:GetInstance():GetServerTime()
  local last = self.lastSendResultTime or 0
  if 5000 <= now - last then
    SFSNetwork.SendMessage(MsgDefines.WinterStormResult)
    self.lastSendResultTime = now
  end
end

function ActWinterStormManager:HandleResultPush(message)
  if message == nil then
    return
  end
  local oneData = ActWinterStormResultData.New()
  oneData:ParseData(message)
  self.resultInfo = oneData
  local actInfo = self:GetActInfo()
  if actInfo ~= nil then
    actInfo.state = 0
  end
  local mr = self:GetMarchResult()
  if mr then
    mr:UpdateTeamData(message.team)
    mr.battleEndTime = 0
  end
end

function ActWinterStormManager:GetResult()
  return self.resultInfo
end

function ActWinterStormManager:CleanResult()
  self.resultInfo = nil
  local mr = self:GetMarchResult()
  if mr ~= nil then
    mr.marchId = 0
  end
end

function ActWinterStormManager:HandleSideScorePush(message)
  if message == nil then
    return
  end
  local info = {}
  info.side = message.side or 0
  info.score = message.score or 0
  info.updateScore = message.updateScore or 0
  if message.uid then
    info.uid = message.uid
  end
  if message.buildingUUID then
    info.buildUUID = message.buildingUUID
    self:UpdateBuildingScore(info.buildUUID, message.buildingScore)
  end
  local battleScore = self.actInfo ~= nil and self.actInfo.battleScore or nil
  if battleScore then
    for side, v in pairs(battleScore) do
      if side == info.side then
        v = info.score
      end
    end
  end
  EventManager:GetInstance():Broadcast(EventId.WinterStormScoreChange, info)
end

function ActWinterStormManager:GetBuildPlayerInfo(buildUUID)
  return self.buildPlayerInfos ~= nil and self.buildPlayerInfos[buildUUID] or nil
end

function ActWinterStormManager:GetBuildScore(buildUUID)
  local info = self:GetBuildPlayerInfo(buildUUID)
  return info ~= nil and info.buildScore or 0
end

function ActWinterStormManager:UpdateBuildingScore(buildUUID, buildScore)
  local info = self:GetBuildPlayerInfo(buildUUID)
  if info == nil then
    info = {}
    info.buildUUID = buildUUID
  end
  if buildScore then
    info.buildScore = buildScore
  end
  if self.buildPlayerInfos == nil then
    self.buildPlayerInfos = {}
  end
  self.buildPlayerInfos[buildUUID] = info
  local world = CS.SceneManager.World
  local pointInfo = world ~= nil and world:GetPointInfoByUuid(buildUUID) or nil
  if pointInfo ~= nil then
    EventManager:GetInstance():Broadcast(EventId.WinterStormBuildHpChange, pointInfo.pointIndex)
  end
end

function ActWinterStormManager:HandleBuildPlayerInfo(message)
  if message == nil then
    return
  end
  local buildUUID = message.buildUUID
  local info = self:GetBuildPlayerInfo(buildUUID)
  if info == nil then
    info = {}
    info.buildUUID = buildUUID
  end
  info.uid = message.uid
  info.currentHp = message.currentHp
  info.totalHp = message.totalHp
  local buildScore = message.buildingScore
  if buildScore then
    info.buildScore = buildScore
  end
  if self.buildPlayerInfos == nil then
    self.buildPlayerInfos = {}
  end
  self.buildPlayerInfos[buildUUID] = info
  local world = CS.SceneManager.World
  local pointInfo = world ~= nil and world:GetPointInfoByUuid(buildUUID) or nil
  if pointInfo ~= nil then
    local pointIndex = pointInfo.pointIndex
    info.pointIndex = pointIndex
    EventManager:GetInstance():Broadcast(EventId.WinterStormBuildHpChange, pointIndex)
    EventManager:GetInstance():Broadcast(EventId.WinterStormEntityUpdate, pointIndex)
    local damage = message.damage or 0
    if 0 < damage then
      EventManager:GetInstance():Broadcast(EventId.WinterStormDamagePush, {
        pointIndex = pointIndex,
        damage = -damage
      })
    end
  end
end

function ActWinterStormManager:HandlePlayerBattleEnterPush(message)
  if message == nil then
    return
  end
  if message.effect ~= nil then
    BattleFieldUtil.HandleEffects(message.effect, BattleFieldType.WinterStorm)
  end
  if self.actInfo ~= nil and message.score ~= nil and self.actInfo:HandleBattleScore(message.score) then
    EventManager:GetInstance():Broadcast(EventId.WinterStormScoreChange)
  end
  self.buildPlayerInfos = {}
  local arr = message.buildHp
  if arr ~= nil then
    for _, v in pairs(arr) do
      self:HandleBuildPlayerInfo(v)
    end
  end
end

function ActWinterStormManager:ReqBattleScore()
  SFSNetwork.SendMessage(MsgDefines.WinterStormBattlePlayer)
end

function ActWinterStormManager:HandleBattlePushPlayer(message)
  if message == nil then
    return
  end
  local ret = message.ret
  if ret == 0 then
    return
  end
  local mr = self:GetMarchResult()
  if mr then
    mr:UpdateTeamData(message.team)
  end
  UIManager:GetInstance():OpenWindow(UIWindowNames.UIWinterStormBattleScore)
end

function ActWinterStormManager:TryGotoMap(pointId)
  local actInfo = DataCenter.ActWinterStormManager:GetActInfo()
  if actInfo == nil then
    return false
  end
  if LuaEntry.Player:IsInBlackRange(true) or LuaEntry.Player:IsInCityField(true) then
    UIUtil.ShowTipsId(458138)
    return false
  end
  BattleFieldUtil.testJump = false
  BattleFieldUtil.prePointId = pointId
  SFSNetwork.SendMessage(MsgDefines.WinterStormEnter)
  return true
end

function ActWinterStormManager:OnHandleEnterMessage(t)
  if LuaEntry.Player:IsInBlackRange(true) or LuaEntry.Player:IsInCityField(true) then
    UIUtil.ShowTipsId(458138)
    return
  end
  BattleFieldUtil.HandleEnterWorld(BattleFieldType.WinterStorm, t)
end

function ActWinterStormManager:GetGuideList()
  if self.theGuideList == nil then
    self.theGuideList = BattleFieldUtil.GetGuideList(BattleFieldType.WinterStorm)
  end
  return self.theGuideList
end

function ActWinterStormManager:GetRewardList()
  if self.theRewardList ~= nil then
    return self.theRewardList
  end
  local theRewardList = {}
  local tbName = self:GetCfgValue(BattleFieldTableKey.REWARD)
  LocalController:instance():visitTable(tbName, function(id, lineData)
    table.insert(theRewardList, {
      num = lineData:getIntValue("id"),
      type = lineData:getIntValue("type"),
      rewardId = lineData:getIntValue("rewardId"),
      desc = lineData:getValue("desc"),
      condition = lineData:getIntValue("condition"),
      para = lineData:getIntValue("para"),
      limit = lineData:getIntValue("limit")
    })
  end)
  self.theRewardList = theRewardList
  return theRewardList
end

function ActWinterStormManager:IsAllRewardFinish()
  local actInfo = self:GetActInfo()
  if actInfo == nil then
    return false
  end
  local list = self:GetRewardList()
  local taskParam = actInfo.taskRewardParam or 0
  local fightParam = actInfo.fightRewardParam or 0
  for _, v in pairs(list) do
    local needNum = v.para or 0
    local curNum = v.type == 1 and taskParam or fightParam
    if needNum > curNum then
      return false
    end
  end
  return true
end

function ActWinterStormManager:GetBuildData(pointId)
  local data = {}
  data.pointId = pointId
  data.serverId = LuaEntry.Player:GetCurServerId()
  data.cType = 0
  data.baseSide = 0
  data.size = 1
  data.effectList = {}
  data.name = ""
  data.shareName = ""
  data.iconPath = ""
  data.uuid = 0
  data.buildId = 0
  data.closeTime = 0
  data.openTime = 0
  data.occupyingStartTime = 0
  data.side = 0
  data.eventStartTime = 0
  data.eventFinishTime = 0
  data.findAimTime = 0
  data.aimDeadTime = 0
  data.targetEnemyUUID = nil
  data.state = 0
  data.ownerUid = ""
  local info = CS.SceneManager.World:GetPointInfo(pointId)
  if info ~= nil then
    data.targetEnemyUUID = info.targetEnemyUUID
    local detailInfo = info.detail
    if detailInfo then
      data.uuid = detailInfo.Uuid
      local buildId = detailInfo.BuildId
      data.buildId = buildId
      local template = DataCenter.WinterStormTemplateManager:GetTemplate(buildId)
      if template ~= nil then
        data.cType = template.type
        data.size = template.size
        data.effectList = template.effectList
        data.name = template.name
        data.shareName = template.name
        data.iconPath = template:GetIconPath()
      end
      data.template = template
      data.openTime = detailInfo.OpenTime
      data.state = detailInfo.State
      data.score = detailInfo.Score or 0
      data.overflowScore = detailInfo.OverflowScore or 0
      data.closeTime = detailInfo.CloseTime
      data.startTime = detailInfo.StartTime
      data.occupyingStartTime = detailInfo.OccupyingStartTime
      data.side = detailInfo.Side
      data.eventStartTime = detailInfo.EventStartTime
      data.eventFinishTime = detailInfo.EventFinishTime
      data.findAimTime = detailInfo.FindAimTime
      data.aimDeadTime = detailInfo.aimDeadTime
      data.ownerUid = detailInfo.OwnerUid
    end
  end
  return data
end

function ActWinterStormManager:FillBuildBtnList(point, btnList)
end

function ActWinterStormManager:GetClosestPos(target)
  local list = {}
  local baseList = CS.SceneManager.World:GetAllDragonPointList()
  if list ~= nil then
    local TileIndexToWorld = SceneUtils.TileIndexToWorld
    local insert = table.insert
    for _, v in pairs(baseList) do
      local detailInfo = v.detail
      if detailInfo ~= nil then
        local pos = TileIndexToWorld(v.mainIndex, ForceChangeScene.World)
        insert(list, pos)
      end
    end
  end
  local abs = math.abs
  local bestLen = 10
  for k, pos in pairs(list) do
    if bestLen > abs(pos.x - target.x) and bestLen > abs(pos.z - target.z) then
      return pos
    end
  end
  return target
end

function ActWinterStormManager:GetTotalRedCount()
  local actInfo = self:GetActInfo()
  if actInfo == nil then
    return 0
  end
  local now = UITimeManager:GetInstance():GetServerSeconds()
  if actInfo.noticeEndTime ~= nil and now < actInfo.noticeEndTime then
    return 0
  end
  if actInfo.battleEndTime == nil or now > actInfo.battleEndTime then
    return 0
  end
  local signTime = CommonUtil.PlayerPrefsGetInt(SettingKeys.WINTER_STORM_END_TIME, 0)
  if now > signTime then
    CommonUtil.PlayerPrefsSetInt(SettingKeys.WINTER_STORM_END_TIME, actInfo.actEndTime)
    CommonUtil.PlayerPrefsSetBool(SettingKeys.WINTER_STORM_RED_FLAG, true)
    return 1
  end
  local flag = CommonUtil.PlayerPrefsGetBool(SettingKeys.WINTER_STORM_RED_FLAG, true)
  return flag and 1 or 0
end

function ActWinterStormManager:SignRedCountClear()
  local actInfo = self:GetActInfo()
  if actInfo == nil then
    return
  end
  local redCnt = self:GetTotalRedCount()
  if redCnt == 0 then
    return
  end
  CommonUtil.PlayerPrefsSetInt(SettingKeys.WINTER_STORM_END_TIME, actInfo.actEndTime)
  CommonUtil.PlayerPrefsSetBool(SettingKeys.WINTER_STORM_RED_FLAG, false)
  EventManager:GetInstance():Broadcast(EventId.RefreshActivityRedDot)
  EventManager:GetInstance():Broadcast(EventId.RefreshRaceEntrance)
end

function ActWinterStormManager:RecordGotoTipStatus()
  local now = UITimeManager:GetInstance():GetServerSeconds()
  local strK = ActWinterMainTips .. LuaEntry.Player.uid
  Setting:SetInt(strK, now)
end

function ActWinterStormManager:CheckGotoTipStatus()
  if not RaceEntranceUtil.IsOldEntranceOpen() then
    return nil
  end
  local activityDatas = DataCenter.ActivityListDataManager:GetActivityDataByType(EnumActivity.ActWinterStorm.Type)
  if activityDatas == nil or activityDatas[1] == nil then
    return nil
  end
  if table.IsNullOrEmpty(self.actInfo) then
    return ""
  end
  local flag = self:CheckInBattleTime()
  if flag then
    local strK = ActWinterMainTips .. LuaEntry.Player.uid
    local lastTime = Setting:GetInt(strK, 0)
    local now = UITimeManager:GetInstance():GetServerSeconds()
    if now - lastTime < 7200 then
      return nil
    end
    return "winter_battlefield_tips1035"
  end
  return nil
end

function ActWinterStormManager:PrepareSound(bNow)
  local soundCheckTime = -1
  local func = function()
    local bUp = false
    local detailInfo = BattleFieldUtil.GetDetailInfoByCfgId(201)
    if detailInfo and detailInfo.State == WinterEntityState.Fixing then
      local curSec = UITimeManager:GetInstance():GetServerSeconds()
      if curSec < detailInfo.OpenTime then
        soundCheckTime = detailInfo.OpenTime
      else
        bUp = true
      end
    end
    DataCenter.LWSoundManager:PlaySound(bUp and 30004 or 30003, true, true)
  end
  if bNow then
    func()
  else
    TimerManager:GetInstance():DelayInvoke(func, 0.5)
  end
  return soundCheckTime
end

function ActWinterStormManager:UpdateMapBR()
  local baseObj = BattleFieldUtil.GetMapObj(BattleFieldType.WinterStorm)
  if IsNull(baseObj) then
    return
  end
  local mapHandle = baseObj:GetComponent(typeof(CS.BattlefieldHandle))
  if mapHandle == nil then
    return
  end
  local mySide = DataCenter.ActWinterStormManager:GetMySide()
  local myIdx = mySide == 1 and 1 or 0
  for i = 0, 1 do
    local colorIdx = myIdx == i and 1 or 0
    local renderer = mapHandle:GetRenderer(i)
    if IsNotNull(renderer) then
      renderer.sharedMaterial = mapHandle:GetMaterial(colorIdx)
    end
  end
end

function ActWinterStormManager:BuildOpenCheck(state)
  if state == WinterEntityState.Fixing then
    UIUtil.ShowTipsId(458279)
    return false
  end
  return DataCenter.ActWinterStormManager:BattleOpenCheck(true)
end

local bi_cls = "UI.UIActivityCenterTable.Component.ActWinterStorm.WinterStormBattleTopItemNew"
local bi_prefab = "Assets/Main/Prefabs/UI/ActivityCenter/WinterStorm/WinterStormBattleTopItemNew.prefab"

function ActWinterStormManager:CreateBattleInfoAsync(compCreate, compParent, posY, cb)
  local battle_info
  battle_info = compCreate:LoadComponentAsync(bi_cls, bi_prefab, compParent, function()
    battle_info.gameObject.name = "BattleInfo"
    battle_info:SetOffsetMaxXY(0, 61)
    battle_info:SetOffsetMinXY(0, 0)
    battle_info:SetAnchoredPositionXY(0, posY)
    battle_info:SetLocalScaleXYZ(ResetScale.x, ResetScale.y, ResetScale.z)
    if cb then
      cb()
    end
  end)
  return battle_info
end

function ActWinterStormManager:Description()
  local sb = StringBuilder.New()
  sb:AppendLine(self.actInfo ~= nil and self.actInfo:Description() or "")
  return sb:ToString()
end

function ActWinterStormManager:GetNextBattleTime()
  local actInfo = self:GetActInfo()
  if actInfo == nil then
    return -1
  end
  local curSec = UITimeManager:GetInstance():GetServerSeconds()
  local battleEndTime = actInfo.battleEndTime or 0
  if curSec >= battleEndTime then
    return -1
  end
  local MyDate = os.date
  local MyModf = math.modf
  local offSet = MyModf(UITimeManager:GetInstance():GetTimezoneOffset() / 1000)
  local dateCur = MyDate("!*t", curSec + offSet)
  local battleBeginTime = actInfo.battleBeginTime or 0
  local dateBattle = MyDate("!*t", battleBeginTime + offSet)
  local hourTime = 3600
  local dayTime = hourTime * 24
  while dateCur.day > dateBattle.day do
    battleBeginTime = battleBeginTime + dayTime
    dateBattle = MyDate("!*t", battleBeginTime + offSet)
  end
  local k4 = actInfo.battleK4
  for i = 1, 3 do
    local time = k4[i]
    if time ~= nil then
      local time1 = battleBeginTime + time * hourTime
      if curSec < time1 then
        return time1
      end
    end
  end
  return -1
end

function ActWinterStormManager:TestDrop()
  if not CommonUtil.IsDebug() then
    return
  end
  if self.seqJls ~= nil then
    self.seqJls:Kill()
    self.seqJls = nil
  end
  if self.jlsReq ~= nil then
    self.jlsReq:Destroy()
    self.jlsReq = nil
  end
  if self.boxReq ~= nil then
    self.boxReq:Destroy()
    self.boxReq = nil
  end
  self.jlsReq = CS.GameEntry.Resource:InstantiateAsync(UIAssets.LWWorldWinterDrop)
  self.jlsReq:completed("+", function(req)
    if req.isError then
      if self.jlsReq ~= nil then
        self.jlsReq:Destroy()
        self.jlsReq = nil
      end
      return
    end
    local tf = req.gameObject.transform
    tf:SetParent(CS.SceneManager.World.DynamicObjNode)
    local pointId = SceneUtils.WorldToTileIndex(CS.SceneManager.World.CurTarget)
    local startPos = SceneUtils.TileIndexToWorld(pointId, ForceChangeScene.World, LuaEntry.Player:GetCurServerId())
    tf:Set_localPosition(startPos.x, startPos.y, startPos.z)
    self:_PlayDrop(tf)
  end)
end

function ActWinterStormManager:_PlayDrop(tf)
  if not CommonUtil.IsDebug() then
    return
  end
  local animation = tf:GetComponentInChildren(typeof(CS.SimpleAnimation))
  local flag = IsNull(animation)
  tf.gameObject:SetActive(not flag)
  if flag then
    return
  end
  local boxPt = animation.transform:Find("To_unity/Root/box02")
  if IsNotNull(boxPt) then
    local config = DataCenter.WinterStormTemplateManager:GetTemplate(100)
    self:_AddBox(boxPt, config:GetModelPath())
  end
  local JlsAct = "Default"
  if animation:IsPlaying(JlsAct) then
    animation:Rewind(JlsAct)
  else
    animation:Play(JlsAct)
  end
  local clipL = animation:GetClipLength(JlsAct)
  self.seqJls = CS.DG.Tweening.DOTween.Sequence()
  self.seqJls:AppendInterval(clipL)
  self.seqJls:OnComplete(function()
    self.seqJls = nil
    tf.gameObject:SetActive(false)
  end)
end

function ActWinterStormManager:_AddBox(boxPt, modelPath)
  if not CommonUtil.IsDebug() then
    return
  end
  self.boxReq = CS.GameEntry.Resource:InstantiateAsync(modelPath)
  self.boxReq:completed("+", function(req)
    if req.isError then
      if self.boxReq ~= nil then
        self.boxReq:Destroy()
        self.boxReq = nil
      end
      return
    end
    local _go = req.gameObject
    local goTrans = _go.transform
    goTrans:SetParent(boxPt)
    goTrans:Set_localPosition(0, 0, 0)
    goTrans:Set_localScale(1, 1, 1)
    goTrans.rotation = Quaternion.Euler(0, -45, 0)
  end)
end

function ActWinterStormManager:CheckCanEnterBattlefield(checkType)
  return true
end

Implement(ActWinterStormManager, InterfaceConfig.BattlefieldManager, InterfaceConfig.BattlefieldEnterCheck)
return ActWinterStormManager
