using System;
using System.Collections;
using System.Collections.Generic;
using AppsFlyerSDK;
using ChillConnect;
using DG.Tweening;
using SGModule.Common.Helper;
using SGModule.Net;
using SGModule.NetKit;
using Unity.Advertisement.IosSupport;
using UnityEngine;

namespace DontConfuse
{

    internal class AppsFlyerObjectScript1 : MonoBehaviour, IAppsFlyerConversionData
    {
        public string appID;
        public bool is_init;
        public Coroutine m_Coroutine;

        void Start()
        {
            AddListener();

            AppsFlyer.setIsDebug(true);
#if UNITY_IOS && !UNITY_EDITOR
            appID = "6746832797";
            m_Coroutine = CrazyAsyKit.StartCoroutine(loopWaitInitAf());
#endif


#if UNITY_EDITOR
            NetworkDispatcher.Instance.Dispatch(NetworkMsg.Login);
#endif
        }

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

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

        void OnDestroy()
        {
            RemoveListener();
        }

        void RequestLogin(object obj = null)
        {
            if (GameHelper.IsConnect())
            {
                GameDispatcher.Instance.Dispatch(GameMsg.Network_reconnection);
            }

            CrazyAsyKit.StopCoroutine(m_Coroutine);

            m_Coroutine = CrazyAsyKit.StartCoroutine(loopWaitInitAf());
        }

        private IEnumerator loopWaitInitAf()
        {
           // yield return new WaitForSeconds(0.5f);
// #if !ChillConnectRelease
//             if (!GameHelper.IsConnect()) GameHelper.ShowTips($"is link network：{GameHelper.IsConnect()}");
// #endif
            var isConnect = GameHelper.IsConnect();
            if (!isConnect)
            {
                float retryTime = 0f;
                const float maxRetryTime = 3f;

                while (!GameHelper.IsConnect() && retryTime < maxRetryTime)
                {
                    yield return new WaitForSeconds(0.2f);
                    retryTime += 0.2f;
                }

                // 再次确认网络状态
                isConnect = GameHelper.IsConnect();

                if (!isConnect)
                {
                    // 超时且仍未连接，触发无网络提示
                    Action action = () =>
                    {
                        TimerHelper.mEasy.AddTimer(0.5f, () =>
                        {
                            NetworkDispatcher.Instance.Dispatch(NetworkMsg.NotNetwork);
                        });
                    };
                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.TipsViewUI_Open, action);
                }
            }
            if (isConnect)
            {
                TrackKit.TrackLoginFunnel(LoginFunnelEventType.AfSend);

                float a = 0;
                if (ATTrackingStatusBinding.GetAuthorizationTrackingStatus() ==
                    ATTrackingStatusBinding.AuthorizationTrackingStatus.NOT_DETERMINED)
                {
                    ATTrackingStatusBinding.RequestAuthorizationTracking();
                }

                while ((ATTrackingStatusBinding.GetAuthorizationTrackingStatus() ==
                        ATTrackingStatusBinding.AuthorizationTrackingStatus.NOT_DETERMINED) && (a < 5.0f))
                {
                    a += 0.5f;
                    yield return new WaitForSeconds(0.5f);
                }

                AppsFlyer.initSDK("ZRPEXnZD9jgqWx8RmiQbiT", appID, this);
                AppsFlyer.startSDK();
                AppsFlyer.AFLog("8888888888888888888",
                    ATTrackingStatusBinding.GetAuthorizationTrackingStatus().ToString());
            }

        }

        public void onConversionDataSuccess(string conversionData)
        {
            Debug.Log($"[AF] onConversionDataSuccess-------- {is_init}");
            if (is_init) return;
            is_init = true;
            AppsFlyer.AFLog("onConversionDataSuccess", conversionData);
            var conversionDataDictionary = AppsFlyer.CallbackStringToDictionary(conversionData);
            var json = SerializeUtil.ToJsonIndented(conversionDataDictionary);
            SuperApplication.Instance.attribution =
                conversionDataDictionary.TryGetValue("af_status", out var afStatus)
                    ? afStatus.ToString().ToLower()
                    : "organic";

            NetworkDispatcher.Instance.Dispatch(NetworkMsg.Login);
            TrackKit.TrackLoginFunnel(LoginFunnelEventType.AfRecv, "success");
        }

        public void onConversionDataFail(string error)
        {
            Debug.Log($"[AF] onConversionDataFail-------- {is_init}");
            if (is_init) return;
            is_init = true;
            AppsFlyer.AFLog("onConversionDataFail", error);
            NetworkDispatcher.Instance.Dispatch(NetworkMsg.Login);
            TrackKit.TrackLoginFunnel(LoginFunnelEventType.AfRecv, "fail");
        }

        public void onAppOpenAttribution(string attributionData)
        {
            AppsFlyer.AFLog("onAppOpenAttribution", attributionData);
            Dictionary<string, object> attributionDataDictionary =
                AppsFlyer.CallbackStringToDictionary(attributionData);
        }

        public void onAppOpenAttributionFailure(string error)
        {
            AppsFlyer.AFLog("onAppOpenAttributionFailure", error);
        }
    }
}
