local SeasonTradeDataManager = BaseClass("SeasonTradeDataManager")
local TradeStationItemData = require("DataCenter.WorldAllianceCityData.TradeStationItemData")
local Localization = CS.GameEntry.Localization

function SeasonTradeDataManager:__init()
  self.activityId = nil
  self.curServerTradeStationData = {}
  self.titleList = {
    10005,
    10004,
    10003,
    10002,
    10001
  }
  self.titleListSeason = {}
end

function SeasonTradeDataManager:__delete()
end

function SeasonTradeDataManager:InitData(data)
  self.activityId = data.id
end

function SeasonTradeDataManager:IsActive(includePrepare)
  return SeasonUtil.IsSeasonActivityOpen(self.activityId, SeasonMapType.Mummy, includePrepare)
end

function SeasonTradeDataManager:GetActivityData(includePrepare)
  if not self:IsActive(includePrepare) then
    return
  end
  return DataCenter.ActivityListDataManager:GetActivityDataById(self.activityId)
end

function SeasonTradeDataManager:GetTitleTemplateByLevel(level)
  local titleList = self:GetTitleList()
  local id = titleList[level]
  return id and DataCenter.PlayerTitleTemplateManager:GetTitleInfo(id)
end

function SeasonTradeDataManager:GetSelfTitle(needRequest)
  local playerInfo = DataCenter.PlayerInfoDataManager:GetPlayerDataByUid(LuaEntry.Player.uid)
  local titleId = playerInfo and playerInfo.title
  if titleId == nil or titleId <= 0 then
    return
  end
  local titleList = self:GetTitleList()
  for i, id in ipairs(titleList) do
    if id == titleId then
      return DataCenter.PlayerTitleTemplateManager:GetTitleInfo(id)
    end
  end
end

function SeasonTradeDataManager:GetTitleList()
  if SeasonUtil.IsInSeason() then
    local seasonType = SeasonUtil.GetSeasonType()
    if self.titleListSeason[seasonType] then
      return self.titleListSeason[seasonType]
    end
    local str
    if seasonType == SeasonMapType.Darkness then
      str = LuaEntry.DataConfig:TryGetStr("season_new_s4_station", "k8")
    elseif seasonType == SeasonMapType.Mummy then
      str = LuaEntry.DataConfig:TryGetStr("season_new_s3_station", "k8")
    elseif seasonType == SeasonMapType.NineNation then
      str = LuaEntry.DataConfig:TryGetStr("season_new_s5_station", "k8")
    end
    local strList = not string.IsNullOrEmpty(str) and string.split(str, "|")
    if not table.IsNullOrEmpty(strList) then
      local list = {}
      self.titleListSeason[seasonType] = list
      for i, v in ipairs(strList) do
        list[i] = tonumber(v)
      end
      return list
    end
  end
  return self.titleList
end

function SeasonTradeDataManager:SetServerTradeStationData(msg)
  if not msg or not msg.worldCityTradeArr then
    return
  end
  if msg.serverId == LuaEntry.Player:GetCurServerId() then
    for j, jV in ipairs(msg.worldCityTradeArr) do
      local tradeId = jV.tradeId
      local data = self.curServerTradeStationData[tradeId]
      if data == nil then
        data = TradeStationItemData.New()
        self.curServerTradeStationData[tradeId] = data
      end
      data:ParseData(jV)
    end
    EventManager:GetInstance():Broadcast(EventId.UpdateAllServerTradeInfo)
    EventManager:GetInstance():Broadcast(EventId.UpdateAllServerTradeInfoWithServer, {
      serverId = msg.serverId,
      list = self.curServerTradeStationData
    })
  else
    local list = {}
    for j, jV in ipairs(msg.worldCityTradeArr) do
      local tradeId = jV.tradeId
      local data = TradeStationItemData.New()
      data:ParseData(jV)
      list[tradeId] = data
    end
    EventManager:GetInstance():Broadcast(EventId.UpdateAllServerTradeInfoWithServer, {
      serverId = msg.serverId,
      list = list
    })
  end
end

function SeasonTradeDataManager:GetServerTradeStationData(tradeId)
  local data = self.curServerTradeStationData[tradeId]
  return data
end

function SeasonTradeDataManager:GetServerTradeStationLatestData()
  local curMillisecond = UITimeManager:GetInstance():GetServerTime()
  local result
  for k, v in pairs(self.curServerTradeStationData) do
    if curMillisecond >= v.battleStartTime and curMillisecond <= v.battleEndTime then
      result = v
      break
    end
  end
  if result then
    return result
  end
  for k, v in pairs(self.curServerTradeStationData) do
    if curMillisecond < v.battleStartTime and (result == nil or v.battleStartTime < result.battleStartTime) then
      result = v
    end
  end
  if result then
    return result
  end
  for k, v in pairs(self.curServerTradeStationData) do
    if result == nil or v.battleEndTime > result.battleEndTime then
      result = v
    end
  end
  return result
end

function SeasonTradeDataManager:GetTradeDistance(trade)
  local curPos = LuaEntry.Player.world_main_pos
  if curPos and 0 < curPos then
    curPos = SceneUtils.IndexToTilePos(LuaEntry.Player.world_main_pos, ForceChangeScene.World)
    return Vector2.Distance(curPos, trade.pos)
  end
  return 0
end

function SeasonTradeDataManager:GetServerTradeStationLatestList()
  local curMillisecond = UITimeManager:GetInstance():GetServerTime()
  local result1 = {}
  for k, v in pairs(self.curServerTradeStationData) do
    if curMillisecond >= v.battleStartTime and curMillisecond <= v.battleEndTime then
      local last = result1[v.level]
      if last == nil or self:GetTradeDistance(v) < self:GetTradeDistance(last) then
        result1[v.level] = v
      end
    end
  end
  local result2 = {}
  for k, v in pairs(self.curServerTradeStationData) do
    if curMillisecond < v.battleStartTime then
      local last = result2[v.level]
      if last == nil or v.battleStartTime < last.battleStartTime or self:GetTradeDistance(v) < self:GetTradeDistance(last) then
        result2[v.level] = v
      end
    end
  end
  local result3 = {}
  for k, v in pairs(self.curServerTradeStationData) do
    local last = result3[v.level]
    if last == nil or v.battleEndTime > last.battleEndTime or self:GetTradeDistance(v) < self:GetTradeDistance(last) then
      result3[v.level] = v
    end
  end
  local result = {}
  for k, v in pairs(result1) do
    result[k] = v
  end
  for k, v in pairs(result2) do
    if result[k] == nil then
      result[k] = v
    end
  end
  for k, v in pairs(result3) do
    if result[k] == nil then
      result[k] = v
    end
  end
  local sortList = {}
  for k, v in pairs(result) do
    table.insert(sortList, v)
  end
  table.sort(sortList, function(a, b)
    return a.level < b.level
  end)
  return sortList
end

function SeasonTradeDataManager:GetTradeStationOpenTime(level)
  local curMillisecond = UITimeManager:GetInstance():GetServerTime()
  for k, v in pairs(self.curServerTradeStationData) do
    if v.level == level and curMillisecond < v.battleStartTime then
      return v.battleStartTime
    end
  end
end

function SeasonTradeDataManager:GetTradeStationDataByState(state)
  for k, v in pairs(self.curServerTradeStationData) do
    if v:GetTimeState() == state then
      return v
    end
  end
end

function SeasonTradeDataManager:GetShowBuffData()
  local effectId = 0
  local effectVelue = 0
  if 0 < LuaEntry.Effect:GetGameEffect(EffectDefine.TradeOfficial_5) then
    effectId = EffectDefine.TradeOfficial_5
    effectVelue = LuaEntry.Effect:GetGameEffect(EffectDefine.TradeOfficial_5)
  elseif 0 < LuaEntry.Effect:GetGameEffect(EffectDefine.TradeOfficial_4) then
    effectId = EffectDefine.TradeOfficial_4
    effectVelue = LuaEntry.Effect:GetGameEffect(EffectDefine.TradeOfficial_4)
  elseif 0 < LuaEntry.Effect:GetGameEffect(EffectDefine.TradeOfficial_3) then
    effectId = EffectDefine.TradeOfficial_3
    effectVelue = LuaEntry.Effect:GetGameEffect(EffectDefine.TradeOfficial_3)
  elseif 0 < LuaEntry.Effect:GetGameEffect(EffectDefine.TradeOfficial_2) then
    effectId = EffectDefine.TradeOfficial_2
    effectVelue = LuaEntry.Effect:GetGameEffect(EffectDefine.TradeOfficial_2)
  elseif 0 < LuaEntry.Effect:GetGameEffect(EffectDefine.TradeOfficial_1) then
    effectId = EffectDefine.TradeOfficial_1
    effectVelue = LuaEntry.Effect:GetGameEffect(EffectDefine.TradeOfficial_1)
  end
  if 0 < effectId then
    local buffViewData = {}
    local effectLine = LocalController:instance():getLine(TableName.LW_Effect_Number, effectId)
    buffViewData.icon = effectLine.icon
    buffViewData.name = Localization:GetString(effectLine.name)
    buffViewData.desc = Localization:GetString(effectLine.desc)
    buffViewData.effectId = effectId
    buffViewData.effectValue = effectVelue
    buffViewData.nameKey = effectLine.name
    buffViewData.descKey = effectLine.desc
    return buffViewData
  end
end

function SeasonTradeDataManager:GotoTradeStationShop()
  local result, nearestDis
  local curPos = LuaEntry.Player.world_main_pos
  if curPos and 0 < curPos then
    curPos = SceneUtils.IndexToTilePos(LuaEntry.Player.world_main_pos, ForceChangeScene.World)
    for k, v in pairs(self.curServerTradeStationData) do
      if v:GetShopState() == 1 then
        local dis = Vector2.Distance(curPos, v.pos)
        if nearestDis == nil or nearestDis > dis then
          nearestDis = dis
          result = v
        end
      end
    end
  end
  self:GotoTradeStation(result)
end

function SeasonTradeDataManager:GotoTradeStation(target)
  if target then
    SceneUtils.ChangeToWorld(function()
      local worldPos = SceneUtils.TileToWorld(target.pos)
      local onComplete = function()
        WorldArrowManager:GetInstance():ShowArrowEffect(0, worldPos)
      end
      GoToUtil.GotoPos(worldPos, nil, nil, onComplete, LuaEntry.Player:GetCurServerId())
      GoToUtil.CloseAllWindows()
    end)
    return
  end
  UIUtil.ShowTipsId("season_s3_trading_post_desc11")
end

function SeasonTradeDataManager:ChangeSkin(mgr)
  mgr:SetAsync(true)
  if SeasonUtil.IsInSeasonDarknessMode() then
    if DataCenter.BloodyNightDataManager:IsBloodyNight() then
      mgr:ActiveSkin(SeasonMapType.Nothing)
    else
      mgr:ActiveSkin(SeasonMapType.Darkness)
    end
    return
  end
  mgr:ActiveSkin(SeasonMapType.Mummy)
end

return SeasonTradeDataManager
