using System;
using System.Collections.Generic;
using AppsFlyerSDK;
using ThinkingData.Analytics;
using tysdk;
using UnityEngine;
using UnityEngine.UI;

public class SDKTest : MonoBehaviour
{
    [SerializeField]
    private Button _InitBtn;
    [SerializeField]
    private Button _loginGuestBtn;
    [SerializeField]
    private Button _loginGoogleBtn;
    [SerializeField]
    private Button _loginFbBtn;
    [SerializeField]
    private Button _logOutBtn;
    [SerializeField]
    private Button _payTestBtn;
    [SerializeField]
    private Button _payListBtn;
    [SerializeField]
    private Button _gaTestBtn;
    [SerializeField]
    private Button _gaAppMaxBtn;
    [SerializeField]
    private Text _messageTxt;

    void Start()
    {
        //===============================================================================
        //======================      Test Server             ===========================
        UnityBridgeFunc.UnityResetServerUrl("http://128-hwsfsdk-sdk-test01.qijihdhk.com");
        //======================      Test Server             ===========================
        //===============================================================================
        //
        _InitBtn.onClick.AddListener(Init);
        _loginGuestBtn.onClick.AddListener(() => OnLogin(EAccoutType.hwGuest));
        _loginGoogleBtn.onClick.AddListener(() => OnLogin(EAccoutType.hwGoogle));
        _loginFbBtn.onClick.AddListener(() => OnLogin(EAccoutType.hwFacebook));
        _logOutBtn.onClick.AddListener(OnLogout);
        _payTestBtn.onClick.AddListener(OnPayTestBtn);
        _payListBtn.onClick.AddListener(OnPayListBtn);
        _gaTestBtn.onClick.AddListener(OnGaBtn);
        _gaAppMaxBtn.onClick.AddListener(OnAppMaxBtn);
    }

    void Init()
    {
        TYSdkFacade.Instance.Init();
        MaxSdkCallbacks.OnSdkInitializedEvent += (MaxSdkBase.SdkConfiguration sdkConfiguration) =>
        {
            Debug.Log($"[MaxSdk::OnSdkInitializedEvent] Init:{sdkConfiguration.IsSuccessfullyInitialized}");
        };
        MaxSdk.InitializeSdk();
        TDAnalytics.Init("0caf287574bd4a9bb08be8995705ef6f", "https://122-slg-online01.qijihdhk.com:8991");

        AppsFlyer.setIsDebug(true);
#if UNITY_IOS
        AppsFlyer.initSDK("rSySeWtvKabfbPZE7Lmx7C", "6505145935");
#elif UNITY_ANDROID
        AppsFlyer.initSDK("rSySeWtvKabfbPZE7Lmx7C", null);
#endif
        AppsFlyer.startSDK();
        // AppsFlyerAdRevenue.start();
    }

    int retryAttempt;

    public void InitializeRewardedAds()
    {
        // Attach callback
        MaxSdkCallbacks.Rewarded.OnAdLoadedEvent += OnRewardedAdLoadedEvent;
        MaxSdkCallbacks.Rewarded.OnAdLoadFailedEvent += OnRewardedAdLoadFailedEvent;
        MaxSdkCallbacks.Rewarded.OnAdDisplayedEvent += OnRewardedAdDisplayedEvent;
        MaxSdkCallbacks.Rewarded.OnAdClickedEvent += OnRewardedAdClickedEvent;
        MaxSdkCallbacks.Rewarded.OnAdRevenuePaidEvent += OnRewardedAdRevenuePaidEvent;
        MaxSdkCallbacks.Rewarded.OnAdHiddenEvent += OnRewardedAdHiddenEvent;
        MaxSdkCallbacks.Rewarded.OnAdDisplayFailedEvent += OnRewardedAdFailedToDisplayEvent;
        MaxSdkCallbacks.Rewarded.OnAdReceivedRewardEvent += OnRewardedAdReceivedRewardEvent;
    }

    private async void OnLogin(EAccoutType accoutType)
    {
        _messageTxt.text = string.Empty;
        Debug.LogError($"[AggSdk::OnLogin] accoutType : {accoutType}");
        var info = await TYSdkFacade.Instance.Login(accoutType);
        _messageTxt.text = $"Login:  {info.isSuccess}";
        if (info.isSuccess)
        {
            _messageTxt.text += $"\n{info.msg}";
            _messageTxt.text += $"\n{TYSdkFacade.Instance.TYAccountInfo.token}";
        }
    }

    private void OnLogout()
    {
        TYSdkFacade.Instance.Logout();
    }

    public async void OnPayTestBtn()
    {
        string prodId = "comarkgameft1chooseone0199";
        string pType = "googleiab.global.app";
        string prodPrice = "2,616";
        string prodName = "test:￦2,616";
        int count = 1;

        Debug.LogError($"[AggSdk::Pay] prodId : {prodId} prodPrice : {prodPrice} prodName : {prodName} ");
        PaymentInfo payResult = await TYSdkFacade.Instance.Pay(prodId, prodPrice, prodName, count, pType);

    }

    public async void OnPayListBtn()
    {
        ProductListInfo result = await TYSdkFacade.Instance.GetSKUList();
        if (result.code == 0)
        {
            Debug.LogError("products count:::" + result.products.Count);
        }
        else
        {
            Debug.LogError("get products fail ,code:" + result.code);
        }

    }

    public void OnGaBtn()
    {
        Debug.LogError("Ga ask");
        using (var e = GAEvent.TackEvent("idcheckdone"))
        {
            e.AddContent("test ga", true);
        }
    }

    const string AD_ID = "427b872c314ad1f3";

    public void OnAppMaxBtn()
    {
        if (MaxSdk.IsRewardedAdReady(AD_ID))
        {
            MaxSdk.ShowRewardedAd(AD_ID);
        }
        else
        {
            _messageTxt.text = "AD Not Ready, Load now";
            LoadAd();
        }
    }

    private void LoadAd()
    {
        MaxSdk.LoadRewardedAd("427b872c314ad1f3");
    }

    private void OnRewardedAdLoadedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
        _messageTxt.text = $"Rewarded ad loaded. ID: {adInfo.AdUnitIdentifier}";
        retryAttempt = 0;
    }

    private void OnRewardedAdLoadFailedEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo)
    {
        // Rewarded ad failed to load
        // AppLovin recommends that you retry with exponentially higher delays, up to a maximum delay (in this case 64 seconds).

        retryAttempt++;
        double retryDelay = Math.Pow(2, Math.Min(6, retryAttempt));
        _messageTxt.text = $"Rewarded ad failed to load. ID: {adUnitId}. Reason: {errorInfo.Message}. Attempt: {retryAttempt}. Delay: {retryDelay}s.";

        Invoke("LoadAd", (float)retryDelay);
    }

    private void OnRewardedAdDisplayedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) { }

    private void OnRewardedAdFailedToDisplayEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo, MaxSdkBase.AdInfo adInfo)
    {
        // Rewarded ad failed to display. AppLovin recommends that you load the next ad.
        _messageTxt.text = $"Rewarded ad failed to display. ID: {adUnitId}. Reason: {errorInfo.Message}";
        LoadAd();
    }

    private void OnRewardedAdClickedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) { }

    private void OnRewardedAdHiddenEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
        // Rewarded ad is hidden. Pre-load the next ad
        _messageTxt.text = $"Rewarded ad hidden. ID: {adUnitId}.";
        LoadAd();
    }

    private void OnRewardedAdReceivedRewardEvent(string adUnitId, MaxSdk.Reward reward, MaxSdkBase.AdInfo adInfo)
    {
        _messageTxt.text = $"Rewarded ad received reward. ID: {adUnitId}. Type: {reward}. Amount: {reward.Amount}";
    }

    private void OnRewardedAdRevenuePaidEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
        _messageTxt.text = $"Rewarded ad revenue paid. ID: {adUnitId}.";
    }

    /*
    public void OnTaBtn()
    {
        // 初始化SDK
        TDAnalytics.Init("0caf287574bd4a9bb08be8995705ef6f", "https://122-slg-online01.qijihdhk.com:8991");
        // //如果用户已登录，可以设置用户的账号ID作为身份唯一标识
        // TDAnalytics.Login("TA");
        //设置公共事件属性以后，每个事件都会带有公共事件属性
        // Dictionary<string, object> superProperties = new Dictionary<string, object>();
        // superProperties["channel"] = "ta";//字符串
        // superProperties["age"] = 1;//数字
        // superProperties["isSuccess"] = true;//布尔
        // superProperties["birthday"] = DateTime.Now;//时间
        // superProperties["object"] = new Dictionary<string, object>(){{ "key", "value"}};//对象
        // superProperties["object_arr"] = new List<object>() {new Dictionary<string, object>(){{ "key", "value" }}};//对象组
        // superProperties["arr"] = new List<object>() { "value" };//数组
        // TDAnalytics.SetSuperProperties(superProperties);//设置公共事件属性
        //开启自动采集事件
        // TDAnalytics.EnableAutoTrack(TDAutoTrackEventType.AppInstall | TDAutoTrackEventType.AppStart | TDAutoTrackEventType.AppEnd);
        //发送事件
        // Dictionary<string, object> properties = new Dictionary<string, object>(){{"product_name", "商品名")}};
        // TDAnalytics.Track("product_buy", properties);
        //设置用户属性
        // TDAnalytics.UserSet(new Dictionary<string, object>(){{"user_name", "TA"}});

    }
    */


}
