using System.Collections;
using SGModule.Common;
using SGModule.Common.Base;
using SGModule.Common.Helper;
using SGModule.Net;
using UnityEngine;
using UnityEngine.Events;

namespace SGModule.NetKit
{
    public class LoginKit : SingletonMonoBehaviour<LoginKit>
    {
        private string _channel;
        private bool _sim;
        private bool _loginSuccess;
        private LoginModel _loginModel;
        private bool _isFirstLoginSuccess = true;
        private RequestLoginData _requestLoginData;
        private string _packName;


        public string Channel => _channel;

        public void LoginRequest(string channel, bool haveSimCard, UnityAction<bool, LoginModel> onCompleted)
        {
            _packName = ConfigManager.GameConfig.packageName;
            _channel = string.IsNullOrEmpty(channel) ? "organic" : channel;
            _sim = haveSimCard;

            _requestLoginData = new RequestLoginData
            {
                DeviceID = DeviceHelper.GetDeviceID(),
                AppVersion = Application.version,
                PackName = _packName,
                Channel = _channel,
                Sim = _sim
            };
            StartCoroutine(LoginCoroutine(_requestLoginData, (isSuccess, loginModel) =>
            {
                if (isSuccess)
                {
                    OnLoginSuccess();
                }

                onCompleted?.Invoke(isSuccess, loginModel);
            }));
        }

        public IEnumerator ReauthenticateOnExpiration(UnityAction<bool> onCompleted)
        {
            if (_requestLoginData == null)
            {
                Log.NetKit.Error("登录数据为空，重新登录失败");
                onCompleted?.Invoke(false);
                yield break;
            }

            yield return LoginCoroutine(_requestLoginData, (isSuccess, _) =>
            {
                onCompleted?.Invoke(isSuccess);
            });
        }

        private IEnumerator LoginCoroutine(RequestLoginData reqData, UnityAction<bool, LoginModel> onCompleted)
        {
            const int maxRetry = 5;
            for (var attempt = 0; attempt < maxRetry; attempt++)
            {
                if (attempt > 0)
                {
                    Log.NetKit.Warning($"登录失败，重试第 {attempt} 次...");
                    yield return new WaitForSeconds(5f);
                }

                yield return DoLoginRequest(reqData);

                if (_loginSuccess)
                {
                    onCompleted?.Invoke(true, _loginModel);
                    yield break;
                } 
            }

//            Log.NetKit.Error("登录最终失败");
            onCompleted?.Invoke(false, null);
        }

        private IEnumerator DoLoginRequest(RequestLoginData reqData)
        {
            yield return NetKit.Instance.PostAsync<LoginModel>(
                "login",
                reqData,
                response =>
                {
                    _loginSuccess = response.IsSuccess;
                    _loginModel = response.Data;
                },
                withToken: false
            );
        }

        private void OnLoginSuccess()
        {
            Log.NetKit.Info("登录成功，处理登录后逻辑");

            ServerClock.Init(_loginModel.LoginTime);

            Net.TokenManager.Instance.UpdateTokenCache(_loginModel.Token, _loginModel.ExpiresAt);

            ErrorLogKit.Init(_loginModel.DebugLog);


            // 开始心跳
            HeartbeatKit.Instance.StartHeartbeat();


            StartCoroutine(TrackKit.NoSentTrackProcessing()); // 处理堆积的打点数据
        }


        public LoginModel LoginModel => _loginModel ??= new LoginModel();



        public bool LoginSuccess => _loginSuccess;
    }
}
