using System;
using System.Collections.Generic;
using RedHotRoast;
using DG.Tweening;
using FGUI.ZM_Common_01;
using UnityEngine;
using Newtonsoft.Json;
using SGModule.Common.Helper;
using SGModule.NetKit;
using System.Linq;

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

    AdExchangeManager()
    {

    }

    // public const string buy_one = "com.rainforestworld.space.24.99";
    // // public const string buy_gold_1 = "com.rainforestworld.shop.1.99";
    // // public const string buy_gold_2 = "com.rainforestworld.shop.3.99";
    // // public const string buy_gold_3 = "com.rainforestworld.shop.19.99";
    // // public const string buy_gold_4 = "com.rainforestworld.shop.39.99";
    // public const string remove_ad = "com.rainforestworld.remove.2.99";
    // public const string battle_pass = "com.rainforestworld.pass.9.99";
    // public const string pack_reward = "com.rainforestworld.reward.1.99";
    // public const string fail_pack = "com.rainforestworld.fail.1.99";
    // public const string three_days_gift = "com.rainforestworld.three.1.99";
    // public const string secret_albnums = "com.rainforestworld.secret_albnums.3.99";


    // private static readonly Dictionary<string, EventTrackMapping> _trackMappings = new()
    // {
    //     [pack_reward] = new EventTrackMapping
    //     {
    //         EventKey = ADEventTrack.Event,
    //         ClickProperty = _ => ADEventTrack.Property.lucky_gift_click,
    //         SuccessProperty = _ => ADEventTrack.Property.lucky_gift_receive
    //     },
    //     [remove_ad] = new EventTrackMapping
    //     {
    //         EventKey = ADEventTrack.Event,
    //         ClickProperty = _ => ADEventTrack.Property.remove_ad_click,
    //         SuccessProperty = _ => ADEventTrack.Property.remove_ad_receive
    //     },
    //     [battle_pass] = new EventTrackMapping
    //     {
    //         EventKey = ADEventTrack.Event,
    //         ClickProperty = _ => ADEventTrack.Property.master_pass_click,
    //         SuccessProperty = _ => ADEventTrack.Property.master_pass_receive
    //     },
    //     [buy_one] = new EventTrackMapping
    //     {
    //         EventKey = ADEventTrack.Event,
    //         ClickProperty = _ => ADEventTrack.Property.buy_one_click,
    //         SuccessProperty = _ => ADEventTrack.Property.buy_one_success
    //     },
    //     ["buy_gold"] = new EventTrackMapping
    //     {
    //         EventKey = ADEventTrack.Event,
    //         ClickProperty = suffix => ADEventTrack.Property.gold_click_ + suffix,
    //         SuccessProperty = suffix => ADEventTrack.Property.shop_receive_ + suffix
    //     }
    // };

    public void Exchange(AdExchangeData _data)
    {
        if (Time.time - SaveData.rm_time < 5)
        {
            GameHelper.ShowTips("click_too_frequent", true);
            return;
        }
        SaveData.rm_time = Time.time;

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

            SendEventClickByName(_data.type, "success");

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

            });

        }
        else
        {
            GameHelper.ShowTips("no_ad_count", true);
        }
    }

    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.GetCommonConf().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.GetCommonConf();
    private List<Paidgift> packdata = ConfigSystem.GetConfig<Paidgift>();
    private List<Multigift> threeDayData = ConfigSystem.GetConfig<Multigift>();
    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 == PurchasingManager.GetPaySku(PayType.three_days_gift))
        {
            double move_price = threeDayData[2].Paid_price;
            needAds = (int)Math.Ceiling(move_price);
        }
        else if (name == PurchasingManager.GetPaySku(PayType.buy_gold_1))
        {
            needAds = (int)Math.Ceiling(getCoinNeedAds(name));
        }
        else if (name == PurchasingManager.GetPaySku(PayType.buy_gold_2))
        {
            needAds = (int)Math.Ceiling(getCoinNeedAds(name));
        }
        else if (name == PurchasingManager.GetPaySku(PayType.buy_gold_3))
        {
            needAds = (int)Math.Ceiling(getCoinNeedAds(name));
        }
        else if (name == PurchasingManager.GetPaySku(PayType.buy_gold_4))
        {
            needAds = (int)Math.Ceiling(getCoinNeedAds(name));
        }
        else if (name == PurchasingManager.GetPaySku(PayType.buy_gold_5))
        {
            needAds = (int)Math.Ceiling(getCoinNeedAds(name));
        }

        return needAds;

    }
    private List<Paidcoins> coinList = ConfigSystem.GetConfig<Paidcoins>();
    private double getCoinNeedAds(string sku)
    {
        Paidcoins result = coinList.FirstOrDefault(c => c.SKU == sku);
        if (result != null)
        {
            return result.Payment_amount;
        }
        return 0;
    }

    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;

            item.SetClick(() =>
            {
                item.enabled = false;
                AdExchangeData adExchangeData = new AdExchangeData()
                {
                    type = key,
                    ad_count = GetCeilingNeedAds(key)
                };
                Exchange(adExchangeData);
            });
        }
        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
            {
                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()
    {
        return DataMgr.AdWatchCount.Value;
    }

    public void SetLookRewardADNum(int nums)
    {
        DataMgr.AdWatchCount.Value = nums;
    }

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

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

    public void SendEventClickByName(string name, string type)
    {
        string eventClickName = "";
        string eventSuccName = "";
        if (name == PurchasingManager.GetPaySku(PayType.pack_reward))
        {
            eventClickName = ADEventTrack.Property.lucky_gift_click;
            eventSuccName = ADEventTrack.Property.lucky_gift_receive;
        }
        else if (name == PurchasingManager.GetPaySku(PayType.remove_ad))
        {
            eventClickName = ADEventTrack.Property.remove_ad_click;
            eventSuccName = ADEventTrack.Property.remove_ad_receive;
        }
        else if (name == PurchasingManager.GetPaySku(PayType.battle_pass))
        {
            eventClickName = ADEventTrack.Property.master_pass_click;
            eventSuccName = ADEventTrack.Property.master_pass_receive;
        }
        else if (name == PurchasingManager.GetPaySku(PayType.buy_one))
        {
            eventClickName = ADEventTrack.Property.buy_one_click;
            eventSuccName = ADEventTrack.Property.buy_one_success;
        }
        // else if (name == PurchasingManager.GetPaySku(PayType.buy_one_off))
        // {
        //     eventClickName = ADEventTrack.Property.BuyOneOffClick;
        //     eventSuccName = ADEventTrack.Property.BuyOneOffSuccess;
        // }
        else if (name == PurchasingManager.GetPaySku(PayType.three_days_gift))
        {
            eventClickName = ADEventTrack.Property.three_days_gift_click;
            eventSuccName = ADEventTrack.Property.three_days_gift_buy_success;
        }
        else if (name.StartsWith("buy_gold"))
        {
            int startIndex = "buy_gold".Length;
            string suffix = name[startIndex..]; // 截取 "gold" 后的所有字符
            eventClickName = ADEventTrack.Property.gold_click_ + suffix;
            eventSuccName = ADEventTrack.Property.shop_receive_ + suffix;
        }

        if (type == "success" && eventSuccName != "")
        {
            TrackKit.SendEvent(ADEventTrack.Event, eventSuccName);
        }
        else if (type == "click" && eventClickName != "")
        {
            TrackKit.SendEvent(ADEventTrack.Event, eventClickName);
        }

    }
}

public class EventTrackMapping
{
    public string EventKey
    {
        get;
        set;
    }

    public Func<string, string> ClickProperty
    {
        get;
        set;
    }

    public Func<string, string> SuccessProperty
    {
        get;
        set;
    }
}
public class AdExchangeData
{
    [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;

}
