using System.Collections;

namespace ScrewsMaster
{
    using DG.Tweening;
    using UnityEngine;

    public class LoginSystem : BaseSystem
    {
        private bool _loginSuccess = false;
        private LoginModel _loginModel;
        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)
        {
            var requestLoginData = new RequestLoginData
            {
#if !UNITY_EDITOR
                device_id = SystemInfo.deviceUniqueIdentifier,
#else
                device_id = "test004013",
#endif
                // pack_name = Application.identifier,
                app_version = Application.version,
                pack_name = NetworkManager.packName,
                channel = SuperApplication.Instance.attribution,
                sim = NetworkManager.haveSimCard
            };

            var reqData = new RespLoginFunnelData
            {
                type = "loginSend",
                payload = ""
            };
            NetworkKit.PostFunnelLogin(reqData);

            CrazyAsyKit.StartCoroutine(LoginCoroutine(requestLoginData));
        }

        private IEnumerator LoginCoroutine(RequestLoginData reqData)
        {
            var count = 0;
            while (count < 5)
            {

                yield return new WaitForSeconds(count == 0 ? 0 : 5f);
                yield return LoginRequest(reqData);

                if (_loginSuccess)
                {
                    OnLoginSuccess(_loginModel);
                    yield break;
                }

                if (count == 4)
                {
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.TipsUI_Open);
                }

                Debug.LogError($"登录失败重试 {count}");

                count++;
            }
        }

        private IEnumerator LoginRequest(RequestLoginData reqData)
        {
            yield return NetworkKit.Post<LoginModel>("login", reqData, (isSuccess, loginData) =>
            {
                _loginSuccess = isSuccess;
                _loginModel = loginData;
                TrackLoginActivity(_loginSuccess);
            });
        }

        private void OnLoginSuccess(LoginModel loginData)
        {
            var loginModel = GameHelper.GetLoginModel();
            loginModel.cdn_url = loginData.cdn_url;
            loginModel.setting = loginData.setting;
            loginModel.play_data = loginData.play_data;
            loginModel.token = loginData.token;
            loginModel.uid = loginData.uid;
            loginModel.country = loginData.country;
            loginModel.expires_at = loginData.expires_at;
            loginModel.is_magic = loginData.is_magic;
            loginModel.invite_code = loginData.invite_code;
            loginModel.invite_url = loginData.invite_url;
            loginModel.last_login_time = loginData.last_login_time;
            loginModel.login_time = loginData.login_time;
            loginModel.reg_time = loginData.reg_time;
            loginModel.new_player = loginData.new_player;
            loginModel.ConfigType = loginData.is_magic ? "_" : "_A";
            loginModel.play_data_ver = loginData.play_data_ver;
            loginModel.debug_log = loginData.debug_log;
            loginModel.enwp = loginData.enwp;

            if (loginData.is_magic)
            {
                if (PlayerPrefs.GetInt("is_gift") != 1)
                {
                    AppDispatcher.Instance.Dispatch(AppMsg.UI_DisplayLoadingUI);
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.LoginAUI_Close);
                }
                PlayerPrefs.SetInt("is_gift", 1);
            }
            else
            {
#if JarvisRelease
                BrigdeIOS.showGameA(true);
#else
                AppDispatcher.Instance.Dispatch(AppMsg.Show_uid);
                DOVirtual.DelayedCall(2, () =>
                {
                    BrigdeIOS.showGameA(true);
                });
#endif
                return;
            }

            loginModel.preferences = new Preferences();
            NetworkKit.CDNUrl = $"{loginData.cdn_url}/";
            NetworkKit.userId = loginData.uid;
            NetworkKit.SetCacheToken(loginData.token);
            RequestHeart();
            TimerHelper.UnscaleGeneral.AddLoopTimer(60, (timer) => { RequestHeart(); });
            NetworkDispatcher.Instance.Dispatch(NetworkMsg.GetPlayData);
            // MaxADKit.Init();
        }

        private void TrackLoginActivity(bool isSuccess)
        {
            var reqData = new RespLoginFunnelData
            {
                type = "loginRecv",
                payload = isSuccess ? "success" : "fail"
            };
            NetworkKit.PostFunnelLogin(reqData);
        }

        private void RequestHeart()
        {
            NetworkKit.PostWithHeader("user/health");
        }

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