using System;
using IgnoreOPS;
using SGModule.Common.Extensions;
using SGModule.NetKit;
using UnityEngine;

namespace RedHotRoast
{
    public class LoginSystem : BaseSystem
    {
        private int loginCount = 0;

        private TimerTask timerTask = null;

        public LoginSystem(bool isAutoInit = true)
        {
            if (isAutoInit)
            {
                Init();
            }
        }

        public sealed override void Init()
        {
            base.Init();
            InitData();
            AddListener();
        }

        private void InitData()
        {
        }

        private void AddListener()
        {
            NetworkDispatcher.Instance.AddListener(NetworkMsg.Login, RequestLogin);
        }

        private void RemoveListener()
        {
            NetworkDispatcher.Instance.RemoveListener(NetworkMsg.Login, RequestLogin);
        }

        private void RequestLogin(object obj = null)
        {

            // if (!GameHelper.IsConnect())
            // {
            //     LoginFail();
            // }
            // else
            // {
            TrackKit.TrackLoginFunnel(LoginFunnelEventType.LoginSend);
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetworkErrorTipsUI_Open);
            LoginKit.Instance.LoginRequest(SuperApplication.Instance.attribution, NetworkManager.haveSimCard, (isSuccess, loginData) =>
            {
                Debug.Log($"登陆结果： {isSuccess}");
                TrackKit.TrackLoginFunnel(LoginFunnelEventType.LoginRecv, isSuccess ? "success" : "fail");

                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetworkErrorTipsUI_Close);

                if (isSuccess)
                {
                    BIManager.Instance.TrackABConfig(loginData.IsMagic ? 30 : 15);
                    DateTimeManager.Instance.SetServerCurrTimestamp(loginData.LoginTime);

                    NetworkDispatcher.Instance.Dispatch(NetworkMsg.GetPlayData);

                    MaxADKit.SetUserID(loginData.Uid.As<string>());
                    if (loginData.IsMagic) UnityManager.DakaiACT();
                }
                else
                {
                    LoginFail();
                }
            });
            // }
        }

        private static void LoginFail()
        {
            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Close);

            void OnFail()
            {
                NetworkDispatcher.Instance.Dispatch(NetworkMsg.Login);
            }

            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.TipsViewUI_Open, (Action)OnFail);
        }

        public override void Dispose()
        {
            base.Dispose();
            RemoveListener();
        }
    }
}
