local this = class("loginManager", G_EventManagerBase)
require("ui.manager.login.loginConst")
local tag = this.getName()
this.SaveKey_ServerType = "[LoginManager]ServerType"
this.ServerType = {Develop = 1, PubReview = 100}
this.events = {
  hasSyncIsSeverOpen = "hasSyncIsSeverOpen",
  loginUiShow = "loginUiShow"
}
this.PagesDontCloseWhenLogout = {
  pageFps = true,
  confirm = true,
  loading = true,
  interactive = true
}
this.isDevLogin = not C_InfoManager.EnableSdk
this.isOpenInterim = false

function this:ctor()
  this.super.ctor(self)
  C_MJSDKManager.AddListener(C_EMJSDKType.Logout, function()
    self:_back2Login()
  end)
  C_MJSDKManager.AddListener(C_EMJSDKType.Abort, function(sdkData)
    self:_SdkAbort(sdkData)
  end)
  C_MJSDKManager.AddListener(C_EMJSDKType.BeginLogin, function(sdkData)
    self:sendEvent(self.events.loginUiShow, {showUi = false})
  end)
  C_MJSDKManager.AddListener(C_EMJSDKType.Login, function(sdkData)
    self:sendEvent(self.events.loginUiShow, {showUi = true})
  end)
end

function this:loginInit()
  L_StoreManager:allStoresDoClear()
  L_GuideManager:initialize()
  L_PriorityShowQueueManager:initialize()
  L_FlyMsgManager:initialize()
  L_TopBarManager:initialize()
  L_WaterMarkManager:initialize()
  L_ProductManager:initialize()
  L_MiniGameManager:initialize()
end

local setResolutionLimit = function()
  local detail = C_MJSDKManager.GetUserDetail()
  if detail and detail.adult == 0 then
    C_ResolutionUtility.s_LimitWindowMode = 1
  else
    C_ResolutionUtility.s_LimitWindowMode = 2
  end
end

function this:sdkLoginin(data)
  print("startBtn 4")
  local _connect = function(sdkData)
    print("startBtn callback 1" .. tostring(sdkData.code))
    if sdkData.code == 0 then
      pcall(setResolutionLimit)
      print("startBtn callback 2")
      CS.Azur.Gameplay.AzurEntry.instance:StartGame(function()
        print("startBtn callback 3")
        if data.account then
          C_MJSDKManager.userInfo.openId = data.account
        end
        L_LoginManager:connectAccountServer(data)
        C_LoginMovieHelper.StopLoginMovie()
      end)
    elseif sdkData.code == -1 then
      printf("\231\153\187\229\189\149\229\164\177\232\180\165\239\188\129")
    end
  end
  print("startBtn 5")
  C_MJSDKManager.Login(_connect)
end

function this:sdkLogout()
  if C_MJSDKManager.isLogin then
    local data = {
      txtContent = L_WordsTpl:getValue("ui_loginout_confirm"),
      confirmCallback = function()
        self:logoutAccount()
        C_MJSDKManager.Login()
      end
    }
    L_GameUtil.showCommonTip(data)
  else
    C_MJSDKManager.Login()
  end
end

function this:waterMaskFailed()
  if self.waterFailedCount == nil then
    self.waterFailedCount = 1
  else
    self.waterFailedCount = self.waterFailedCount + 1
  end
  local failedCount = L_GameConstTpl:getValue("WATER_MASK_FAILED_COUNT", true, 3)
  return failedCount >= self.waterFailedCount
end

function this:startReloadWaterMask(time, content)
  local maxTime = L_GameConstTpl:getValue("WATER_MASK_MAX_TIME", true, 660)
  if time > maxTime then
    self.waterTime = null
    return
  end
  self.waterTime = Timer.once(time, function()
    C_AlibabaCloudHelper.LoadWaterMask("", content, function(status, code)
      if status == true then
        printLog("[WaterMask] LoadSuccess", "WaterMask ReloadWaterMask SuccessTime : " .. time)
        self.waterTime = nil
      else
        printLog("[WaterMask] LoadError", "WaterMask ReloadWaterMask ErrorTime : " .. time)
        local addTime = L_GameConstTpl:getValue("WATER_MASK_LOOP_TIME", true, 120)
        self:startReloadWaterMask(time + addTime, content)
      end
    end)
  end)
end

function this:waterMaskCountDelete()
  self.waterFailedCount = 0
end

function this:logoutAccount()
  C_MJSDKManager.Logout()
end

function this:closeAccount()
  C_MJSDKManager.CloseAccount()
end

function this:_back2Login()
  if self.waterTime then
    Timer.remove(self.waterTime)
  end
  L_TaskManager:unLoadToCsharp()
  L_GuideManager:clear()
  self:closeNotStackWindow()
  L_Net:dispose(C_NetChannel.Main)
  L_WorldManager:dispose()
  L_UI:openRoot("pagePlatformLogin")
  L_StoreManager:allStoresDoClear()
  CS.Azur.Gameplay.AzurEntry.instance:ExitGame()
  C_AlibabaCloudHelper.ClearWaterMark()
  L_ProductManager:dispose()
end

function this:_SdkAbort(args)
  local abortMsg = args.msg
  local data_tip = {
    txtContent = abortMsg,
    closeCallback = function()
      self:_back2Login()
    end,
    hideConfirm = true,
    hideCancel = true,
    overrideSortingOrder = 50000
  }
  L_GameUtil.showCommonTip(data_tip)
end

function this:exitGame()
  L_GameUtil.showCommonTip({
    txtTitle = L_WordsTpl:getValue("title_notice_login_exit"),
    txtContent = L_WordsTpl:getValue("notice_login_exit"),
    confirmCallback = function()
      C_MJSDKManager.SdkExit()
    end
  })
end

function this:onKicked()
  self:_back2Login()
  printf(tag, "\232\162\171\232\184\162\228\184\139\231\186\191")
end

function this:connectAccountServer(data)
  L_LoadingManager:openLoading()
  self:loginInit()
  if self:getIsSeverOpen() == false then
    L_GameUtil.showCommonTip({
      txtContent = L_Lang:get(L_WordsTpl:getValue("ui_notice_server_not_open")),
      closeCallback = function()
        L_LoadingManager:closeLoading()
      end,
      hideConfirm = true,
      hideCancel = true,
      overrideSortingOrder = 30000
    })
    return
  end
  local _success = function()
    L_ReddotManager:checkStartReddotListener()
    self:reqEnterGame()
  end
  local _fail = function()
    printf(tag, "socket\232\191\158\230\142\165\229\164\177\232\180\165")
    L_Net:showNetCommonTip({
      txtTitle = L_WordsTpl:getValue("ui_connect_fail_title"),
      txtContent = L_WordsTpl:getValue("ui_connect_fail_text"),
      closeCallback = function()
        L_LoginManager:logoutAccount()
      end,
      hideConfirm = true,
      hideCancel = true
    })
    L_LoadingManager:closeLoading()
  end
  L_Net:connect(_success, _fail, data.ip, data.port)
end

function this:showSvrCloseTips()
  L_LoadingManager:openLoading()
  local value = L_WordsTpl:getValue("notice_no_server")
  local values = string.split(value, ",")
  L_GameUtil.showCommonTip({
    txtTitle = values[1],
    txtConfirm = values[2],
    txtContent = values[3],
    closeCallback = function()
      L_LoadingManager:closeLoading()
    end,
    hideConfirm = true,
    hideCancel = true,
    overrideSortingOrder = 10010
  })
end

function this:getAnnouncementOnLogin(callBack)
  L_LoginPlatformManager:openNetWorkMask(1, "")
  C_AnnouncementManager.ReqAnnouncementData(function(data, code)
    L_LoginPlatformManager:closeNetWorkMask(1, "")
    if callBack then
      callBack(data, code)
    end
  end)
end

function this:reqEnterGame()
  CS.Lens.Gameplay.Login.LoginManager.ReqEnterGame()
end

function this:createEnterGameProtoArgs(isReconnect, isIndicator)
  local userInfo = C_MJSDKManager.userInfo
  local device = C_MJSDKManager.GetDeviceInfo()
  local deviceType = 0
  if Unity.Application.platform == Unity.RuntimePlatform.WindowsPlayer or Unity.Application.platform == Unity.RuntimePlatform.OSXPlayer or Unity.Application.platform == Unity.RuntimePlatform.LinuxPlayer then
    deviceType = 0
  elseif Unity.Application.platform == Unity.RuntimePlatform.Android then
    deviceType = 1
  elseif Unity.Application.platform == Unity.RuntimePlatform.IPhonePlayer then
    deviceType = 2
  end
  local data = {
    open_id = userInfo.openId,
    token = userInfo.token or string.empty,
    channel_code = C_MJSDKManager.GetChannelCode(),
    app_id = C_MJSDKManager.GetAppId(),
    reconnect = isReconnect == true,
    tour_indicator = isIndicator == true,
    channel_id = C_MJSDKManager.GetAppId(),
    app_version = C_InfoManager.AppVersion,
    device_id = device.device_id or string.empty,
    mac = device.device_mac or string.empty,
    platform_str = device.platform or string.empty,
    model = device.device_model or string.empty,
    os_version = device.device_os_version or string.empty,
    network = device.device_network or string.empty,
    game_id = C_MJSDKManager.GetGameId(),
    device_type = deviceType
  }
  if isReconnect then
    data.server_token = L_GameStore:getServerToken()
    data.queue_time = 1
  end
  return data
end

function this:getOpenInterim()
  if IS_EDITOR or IS_DEV_BUILD then
    return self.isOpenInterim
  else
    local gameConstTpl = L_GameTpl:getGameConstTpl()
    local isOpen = gameConstTpl:getValue("OPEN_PRELUDE_TASK", true, 1) == 1
    return isOpen
  end
end

function this:notOpenInterim()
  if L_ExternalGMManager ~= nil then
    local guideList = L_GameConstTpl:getValue("SKIP_FIRST_TASKID_GUIDE")
    for _, v in pairs(guideList) do
      L_GuideStore:updateGuideData(v, 0)
    end
    L_ExternalGMManager:SendGMCommand("SKIPPRELUDE")
  end
  L_UI:open("pageMOD")
end

function this:closeNotStackWindow(exDontCloseList)
  local exDontClose
  if exDontCloseList then
    exDontClose = {}
    for k, v in pairs(exDontCloseList) do
      exDontClose[v] = true
    end
  end
  for _, v in pairs(L_UI.groupKeys) do
    if v ~= L_UI.groupKeys.stack then
      local pages = L_UI:getAllPages(v)
      if type(pages) == "table" then
        for pName, p in pairs(pages) do
          local dontClose = self.PagesDontCloseWhenLogout[pName] or exDontClose and exDontClose[pName]
          if not dontClose then
            L_UI:close(pName)
          end
        end
      end
    end
  end
end

function this:getIsSeverOpen()
  if self.isSeverOpen ~= nil then
    return self.isSeverOpen
  end
  local csServerList = C_InfoManager.ServerList
  if csServerList == nil then
    return false
  end
  local serverNum = csServerList.Count
  local channel = C_InfoManager.SdkChannel
  if not C_InfoManager.EnableSdk and C_InfoManager.Channel ~= "master" then
    channel = string.format("%s_%s", C_InfoManager.SdkChannel, C_InfoManager.Channel)
  end
  local postUrl = string.format("%s/version/client/patch", C_InfoManager.ApiUrl)
  local isOutSever = channel == "C000" and postUrl == "https://l1-test-version-all-p3-cn.manjuu.com/version/client/patch"
  if not isOutSever then
    local GameTool = CS.Lens.Gameplay.Tools.GameTool
    if not GameTool.GetCheckGatewayInDev then
      return true
    end
    local targetCsSever
    for i = 0, serverNum - 1 do
      local csServer = csServerList[i]
      if csServer.name == "\229\134\133\231\189\145-gm" then
        targetCsSever = csServer
      end
    end
    if targetCsSever == nil then
      errorf("\229\134\133\231\189\145-gm\230\156\141\229\138\161\229\153\168\228\184\141\229\173\152\229\156\168\239\188\140\231\189\145\231\174\161\229\133\172\229\145\138\229\138\159\232\131\189\228\184\173\239\188\140\230\181\139\232\175\149\230\163\128\230\181\139\229\133\168\230\156\141\230\152\175\229\144\166\229\188\128\230\148\190\229\138\159\232\131\189\239\188\140\230\137\128\233\156\128\233\133\141\231\189\174\230\156\137\232\175\175")
      return true
    end
    self.isSeverOpen = targetCsSever.state == 0
  else
    local server = csServerList[0]
    self.isSeverOpen = server.state == 0
  end
  return self.isSeverOpen
end

return this
