using System;
using System.Collections.Generic;
using ChillConnect;
using DG.Tweening;
using FGUI.Common_01;
using Newtonsoft.Json;
using SGModule.Net;
using SGModule.NetKit;
using UnityEngine;

public class AdRedeemManager
{
    public static readonly AdRedeemManager Instance = new AdRedeemManager();

    AdRedeemManager()
    {

    }
    public const string MakeupAd = "MakeupAd";
    public const string SavingPotMakeupAd = "SavingPotMakeupAd";
    public const string MakeupLVAd = "MakeupLVAd";

    public void Redeem(AdRedeemData _data)
    {
        if (Time.time - SaveData.redeem_time < 2)
        {
            GameHelper.ShowTips("Clicks are too frequent");
            return;
        }
        SaveData.redeem_time = Time.time;

        int myAdNum = GetLookRewardADNum();
        if (myAdNum >= _data.ad_count)
        {
            SetLookRewardADNum(myAdNum - _data.ad_count);

            string name = _data.type.Contains("shop") ? _data.shopName : _data.type;
            SendEventClickByName(name, "success");

            DOVirtual.DelayedCall(0.1f, () =>
            {
                GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, name);
            });

        }
        else
        {
            GameHelper.ShowTips("Your ADs count is insufficient!");
        }
    }

    public void ShowVideoAd(string adName, Action _action)
    {
        GameHelper.ShowVideoAd(adName, isSuccess =>
            {
                if (isSuccess)
                {
                    _action?.Invoke();
                }
            });
    }

    // private btn_watchAd btn_WatchAd = null;
    private Dictionary<string, btn_watchAd> btn_WatchAd = new Dictionary<string, btn_watchAd>();
    private Dictionary<string, Action> ActionSetText = new Dictionary<string, Action>(); //广告数量的显示

    public void SetWatchAd(string key, btn_watchAd _btn, Action action)
    {
        if (!btn_WatchAd.ContainsKey(key))
        {
            btn_WatchAd.Add(key, _btn);
        }
        else
        {
            btn_WatchAd[key] = _btn;
        }

        if (!ActionSetText.ContainsKey(key))
        {
            ActionSetText.Add(key, action);
        }
        else
        {
            ActionSetText[key] = action;
        }
    }
    private void removeWatchAd()
    {
        btn_WatchAd.Clear();
    }
    private int ad_cool_down = ConfigSystem.GetConfig<CommonModel>().exchangeCD;

    private void updateWatchCD()
    {
        var lastTimes = SaveData.GetSaveObject()._watch_ad_cd;
        foreach (var item in btn_WatchAd)
        {
            bool is_get = item.Key == PurchasingManager.GetPaySku(PayType.pack_reward) && SaveData.GetSaveObject().is_get_packreward;
            bool is_get1 = item.Key == PurchasingManager.GetPaySku(PayType.remove_ad) && SaveData.GetSaveObject().is_get_removead;

            if (is_get || is_get1)
            {
                item.Value.enabled = false;
            }
            else if (GameHelper.GetNowTime() < lastTimes && !checkIsCanReceive(item.Key))
            {
                item.Value.enabled = false;
                item.Value.can_buy.selectedIndex = btn_watchAd.Can_buy_cd;
                item.Value.btn_text.text = CommonHelper.TimeFormat(lastTimes - Convert.ToInt32(GameHelper.GetNowTime()), CountDownType.Hour);
            }
            else
            {
                // stopAction();
                item.Value.enabled = true;
                item.Value.can_buy.selectedIndex = btn_watchAd.Can_buy_can;
                checkBtnState(item.Value, item.Key);
            }
        }

    }

    private CommonModel config = ConfigSystem.GetConfig<CommonModel>();
    private List<Paidgift> packdata = ConfigSystem.GetConfig<PaidgiftModel>().DataList;
    private List<Paidcoins> coinList = ConfigSystem.GetConfig<PaidcoinsModel>().DataList;

    public int GetCeilingNeedAds(string name)
    {

        int needAds = -1;
        if (name == PurchasingManager.GetPaySku(PayType.buy_one))
        {
            double addspace = config.addspace;
            needAds = (int)Math.Ceiling(addspace);
        }
        else if (name == PurchasingManager.GetPaySku(PayType.buy_one_off))
        {
            double addspace1 = config.AddDiscount;
            needAds = (int)Math.Ceiling(addspace1);
        }
        else if (name == PurchasingManager.GetPaySku(PayType.battle_pass))
        {
            double Passportgift = config.Passportgift;
            needAds = (int)Math.Ceiling(Passportgift);
        }
        else if (name == PurchasingManager.GetPaySku(PayType.pack_reward))
        {
            double Paid_price = packdata[0].Paid_price;
            needAds = (int)Math.Ceiling(Paid_price);
        }
        else if (name == PurchasingManager.GetPaySku(PayType.remove_ad))
        {
            double move_price = packdata[1].Paid_price;
            needAds = (int)Math.Ceiling(move_price);
        }
        else if (name == MakeupAd || name == SavingPotMakeupAd || name == MakeupLVAd)
        {

            needAds = 9999;
        }

        // else if (name == PurchasingManager.GetPaySku(PayType.buy_gold_1))
        // {
        //     double gold_price1 = coinList[1].Payment_amount;
        //     needAds = (int)Math.Ceiling(gold_price1);
        // }
        // else if (name == PurchasingManager.GetPaySku(PayType.buy_gold_2))
        // {
        //     double gold_price2 = coinList[2].Payment_amount;
        //     needAds = (int)Math.Ceiling(gold_price2);
        // }
        // else if (name == PurchasingManager.GetPaySku(PayType.buy_gold_3))
        // {
        //     double gold_price3 = coinList[3].Payment_amount;
        //     needAds = (int)Math.Ceiling(gold_price3);
        // }
        // else if (name == PurchasingManager.GetPaySku(PayType.buy_gold_4))
        // {
        //     double gold_price4 = coinList[4].Payment_amount;
        //     needAds = (int)Math.Ceiling(gold_price4);
        // }
        // else if (name == PurchasingManager.GetPaySku(PayType.buy_gold_5))
        // {
        //     double gold_price5 = coinList[5].Payment_amount;
        //     needAds = (int)Math.Ceiling(gold_price5);
        // }

        if (name.StartsWith("buy_gold"))
        {
            List<Paidcoins> coinList = ConfigSystem.GetConfig<PaidcoinsModel>().DataList;

            int startIndex = "buy_gold".Length;
            string suffix = name[startIndex..]; // 截取 "gold" 后的所有字符
            int suffix_num = int.Parse(suffix);

            double gold_price = coinList[suffix_num].Payment_amount;
            needAds = (int)Math.Ceiling(gold_price);
        }

        return needAds;

    }

    private bool checkIsCanReceive(string name)
    {
        int myAd = GetLookRewardADNum();
        return myAd >= GetCeilingNeedAds(name);
    }
    private void checkBtnState(btn_watchAd item, string key)
    {
        // stopAction();
        // foreach (var item in btn_WatchAd)
        // {
        item.SetClick(() => { });

        if (checkIsCanReceive(key))
        {
            item.buy_state.selectedIndex = btn_watchAd.Buy_state_buy;
            if (item.GetChild("img_saveingpot") != null)
            {
                item.GetChild("img_saveingpot").visible = false;
            }

            item.SetClick(() =>
            {
                item.enabled = false;
                AdRedeemData adRedeemData = new AdRedeemData
                {
                    type = key,
                    ad_count = GetCeilingNeedAds(key)
                };
                Redeem(adRedeemData);
            });
        }
        else
        {
            item.buy_state.selectedIndex = btn_watchAd.Buy_state_ad;
            bool is_get = key == PurchasingManager.GetPaySku(PayType.pack_reward) && SaveData.GetSaveObject().is_get_packreward;
            bool is_get1 = key == PurchasingManager.GetPaySku(PayType.remove_ad) && SaveData.GetSaveObject().is_get_removead;

            if (is_get || is_get1)
            {
                item.enabled = false;
                item.SetClick(() => { });
            }
            else
            {
                if (item.GetChild("img_saveingpot") != null && GameHelper.IsGiftSwitch() && ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1)
                {
                    item.GetChild("img_saveingpot").visible = true;
                }

                item.SetClick(() =>
                {
                    SendEventClickByName(key, "click");
                    ShowVideoAd("buy_add_one", () =>
                    {
                        RunAllAction();
                        item.enabled = false;
                        TimerHelper.mEasy.AddTimer(0.1f, () =>
                        {
                            var ad_times = Convert.ToInt32(GameHelper.GetNowTime());
                            SaveData.GetSaveObject()._watch_ad_cd = ad_times + ad_cool_down;
                            startAction();
                        });
                    });
                });
            }
            // }
        }
    }

    private void RunAllAction()
    {
        foreach (var item in ActionSetText)
        {
            item.Value?.Invoke();
        }
    }

    private void startAction()
    {
        stopAction();
        HallManager.Instance.UpdateSecondEvent += updateWatchCD;
    }

    private void stopAction()
    {
        HallManager.Instance.UpdateSecondEvent -= updateWatchCD;
    }

    public int GetLookRewardADNum()
    {
        int nums = PlayerPrefs.GetInt("get_look_reward_ad_num", 0);
        return nums;
    }

    public void SetLookRewardADNum(int nums)
    {
        PlayerPrefs.SetInt("get_look_reward_ad_num", nums);
    }

    public void Start()
    {
        startAction();
        updateWatchCD();
    }

    public void Destroy()
    {
        stopAction();
        removeWatchAd();
        ActionSetText.Clear();
    }

    public void SendEventClickByName(string name, string type)
    {
        string clickTrackKey = null;
        string successTrackKey = null;
        string suffix = "";
        if (name == PurchasingManager.GetPaySku(PayType.pack_reward))
        {
            clickTrackKey = Property.FirstPackClick;
            successTrackKey = Property.FirstPackSuccess;
        }
        else if (name == PurchasingManager.GetPaySku(PayType.remove_ad))
        {
            clickTrackKey = Property.RemoveAdClick;
            successTrackKey = Property.RemoveAdSuccess;
        }
        // case buy_gold_1:
        //     eventClickName = BuriedPointEvent.gold_click_1;
        //     eventSuccName = BuriedPointEvent.gold_success_1;
        //     break;
        // case buy_gold_2:
        //     eventClickName = BuriedPointEvent.gold_click_2;
        //     eventSuccName = BuriedPointEvent.gold_success_2;
        //     break;
        // case buy_gold_3:
        //     eventClickName = BuriedPointEvent.gold_click_3;
        //     eventSuccName = BuriedPointEvent.gold_success_3;
        //     break;
        // case buy_gold_4:
        //     eventClickName = BuriedPointEvent.gold_click_4;
        //     eventSuccName = BuriedPointEvent.gold_success_4;
        //     break;
        else if (name == PurchasingManager.GetPaySku(PayType.battle_pass))
        {
            clickTrackKey = Property.PassClick;
            successTrackKey = Property.PassSuccess;
        }
        else if (name == PurchasingManager.GetPaySku(PayType.buy_one))
        {
            clickTrackKey = Property.BuyOneClick;
            successTrackKey = Property.BuyOneSuccess;
        }
        else if (name == PurchasingManager.GetPaySku(PayType.buy_one_off))
        {
            clickTrackKey = Property.BuyOneOffClick;
            successTrackKey = Property.BuyOneOffSuccess;
        }

        if (name.StartsWith("buy_gold"))
        {
            int startIndex = "buy_gold".Length;
            suffix = name[startIndex..]; // 截取 "gold" 后的所有字符
            clickTrackKey = Property.GoldClick;
            successTrackKey = Property.GoldSuccess;
        }

        if (type == "success" && successTrackKey != null)
        {
          //  TrackKit.SendEvent(Property.adEvent, successTrackKey, Int32.Parse(suffix));
        }
        else if (type == "click" && clickTrackKey != null)
        {
           // TrackKit.SendEvent(Property.adEvent, clickTrackKey, Int32.Parse(suffix));
        }

    }
}


public class AdRedeemData
{

    [JsonProperty("type")]
    public string type;
    [JsonProperty("ad_count")]
    public int ad_count;
    [JsonProperty("shopName")]
    public string shopName;
}
public class orderState
{
    [JsonProperty("order_id")]
    public string order_id;
    [JsonProperty("status")]
    public int status;

}
public class orderData
{
    [JsonProperty("order_id")]
    public string order_id;
    [JsonProperty("pay_url")]
    public string pay_url;
    [JsonProperty("code")]
    public int code;
}
