using UnityEngine;
using DG.Tweening;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections;
using UnityEngine.UI;
using System.Linq;
using System;
using IgnoreOPS;
// using SGModule.ApplePay;
using SGModule.Common.Helper;
using SGModule.NetKit;
using RedHotRoast;
using Unity.VisualScripting;

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

    public static bool isPay = false;

    // public static  Dictionary<string, int> statusDictionary = new();
    MaxPayManager()
    {
    }

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


    public static bool isIOSPay = false;

    // private static readonly Dictionary<string, PayTrackMapping> _payTrackMap = new()
    // {
    //     [buy_one] = new PayTrackMapping
    //     {
    //         EventKey = ADEventTrack.MaxPayEvent,
    //         ClickPropertyKey = _ => ADEventTrack.Property.buy_one_click,
    //     },
    //     [remove_ad] = new PayTrackMapping
    //     {
    //         EventKey = ADEventTrack.MaxPayEvent,
    //         ClickPropertyKey = _ => ADEventTrack.Property.remove_ad_click
    //     },
    //     [pack_reward] = new PayTrackMapping
    //     {
    //         EventKey = ADEventTrack.MaxPayEvent,
    //         ClickPropertyKey = _ => ADEventTrack.Property.lucky_gift_click
    //     },
    //     [battle_pass] = new PayTrackMapping
    //     {
    //         EventKey = ADEventTrack.MaxPayEvent,
    //         ClickPropertyKey = _ => ADEventTrack.Property.master_pass_click
    //     },
    //     ["buy_gold"] = new PayTrackMapping
    //     {
    //         EventKey = ADEventTrack.MaxPayEvent,
    //         ClickPropertyKey = suffix => ADEventTrack.Property.gold_click_ + suffix
    //     },
    //     ["secret_albnums"] = new PayTrackMapping
    //     {
    //         EventKey = ADEventTrack.MaxPayEvent,
    //         ClickPropertyKey = suffix => ADEventTrack.Property.secret_click_ + suffix
    //     },        
    //     ["vip_club"] = new PayTrackMapping
    //     {
    //         EventKey = ADEventTrack.MaxPayEvent,
    //         ClickPropertyKey = suffix => ADEventTrack.Property.vip_click_ + suffix
    //     },
    //     
    // };

    public void Buy(ApplePayClass _data)
    {
        if (!GameHelper.IsConnect())
        {
            GameHelper.ShowTips("no_connect", true);
            return;
        }
        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Open);
        System.Random random = new();
        int paymentMethod = random.Next(0, 100); // 生成0到100之间的随机整数，包括0-99
        int PayRate = GameHelper.GetCommonModel().PayRate;
        Debug.Log($"[max] paymentMethod:{paymentMethod}  PayRate:{PayRate} _data.sku=={_data.sku}");
        if ((!GameHelper.IsGiftSwitch() || paymentMethod < PayRate) && !_data.sku.Contains("secret_albnums"))
        {
            // Debug.Log("barry ios pay");
            // 调用官方支付逻辑
            isIOSPay = true;
            // var appleData = new ApplePayData
            // {
            //     sku = _data.sku,
            //     amount = _data.amount,
            //     currency = _data.currency,
            //     shopName = _data.shopName,
            //     type = _data.type
            // };
            // PurchasingManager.Purchase(appleData);
        }
        else
        {
            // Debug.Log("barry max pay");
            // 调用三方支付逻辑
            StopPayCoroutine();
            isIOSPay = false;
            SaveData.GetSaveObject().max_pay_object = _data;
            MaxPay(_data);
        }
    }

    /// <summary>
    /// 发起第三发支付
    /// </summary>
    public void MaxPay(ApplePayClass data_)
    {
        Debug.Log($"[barry] MaxPay----- {JsonConvert.SerializeObject(data_)}");

        ApplePayClass paydata = data_;
        SaveData.pay_time = Time.time;

        if (data_.sku == PurchasingManager.GetPaySku(PayType.buy_one))
        {
            TrackKit.SendEvent(ADEventTrack.MaxPayEvent, ADEventTrack.Property.buy_one_click);
        }
        else if (data_.sku == PurchasingManager.GetPaySku(PayType.buy_one_off))
        {
            // TrackKit.SendEvent(ADEventTrack.MaxPayEvent, ADEventTrack.Property.BuyOneOffClick);
        }
        else if (data_.sku != null && data_.sku == PurchasingManager.GetPaySku(PayType.remove_ad))
        {
            TrackKit.SendEvent(ADEventTrack.MaxPayEvent, ADEventTrack.Property.remove_ad_click);
        }
        else if (data_.sku == PurchasingManager.GetPaySku(PayType.pack_reward))
        {
            TrackKit.SendEvent(ADEventTrack.MaxPayEvent, ADEventTrack.Property.lucky_gift_click);
        }
        else if (data_.shopName != null && data_.shopName.StartsWith("buy_gold"))
        {
            int startIndex = "buy_gold".Length;
            string suffix = paydata.shopName[startIndex..]; // 截取 "gold" 后的所有字符
            string eventClickName = $"gold_click_{suffix}";
            TrackKit.SendEvent(ADEventTrack.MaxPayEvent, ADEventTrack.Property.gold_click_ + suffix);

        }
        else if (data_.sku.StartsWith("secret_albnums"))
        {
            string suffix = data_.sku["secret_albnums".Length..];
            TrackKit.SendEvent(ADEventTrack.MaxPayEvent, ADEventTrack.Property.secret_albums_click_ + suffix);
        }
        else if (data_.sku.StartsWith("vip_club"))
        {
            string suffix = data_.sku["vip_club".Length..];
            TrackKit.SendEvent(ADEventTrack.MaxPayEvent, ADEventTrack.Property.vip_click_ + suffix);
        }
        else if (data_.sku == PurchasingManager.GetPaySku(PayType.battle_pass))
        {
            TrackKit.SendEvent(ADEventTrack.MaxPayEvent, ADEventTrack.Property.master_pass_click);
        }
        else if (data_.sku == PurchasingManager.GetPaySku(PayType.fail_pack))
        {
            TrackKit.SendEvent(ADEventTrack.MaxPayEvent, ADEventTrack.Property.fail_click);
        }
        else if (data_.sku == PurchasingManager.GetPaySku(PayType.three_days_gift))
        {
            TrackKit.SendEvent(ADEventTrack.MaxPayEvent, ADEventTrack.Property.three_days_gift_click);
        }

        PayerData requestData = new PayerData()
        {
            amount = data_.amount,
        };

        //max 支付订单创建
        NetKit.Instance.Post<orderData>("shop/paMPayIn", requestData, response =>
        {
            if (response.IsSuccess)
            {
                UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close);

                // Debug.Log($"max 支付订单创建:{JsonConvert.SerializeObject(obj)}");
                SaveData.GetSaveObject().max_pay_object.innerOrderId = response.Data.order_id;
                paydata.status = 1;
                SavePayData(response.Data.order_id, paydata);
                isPay = true;
                OpenBrowser.OpenURL(response.Data.pay_url);
            }
        });
    }

    public void SavePayData(string orderId, ApplePayClass payData)
    {
        // Debug.Log($"max 支付 SavePayData: orderId={orderId} status={payData}");
        // 加载已保存的支付数据
        var payDataJson = PlayerPrefs.GetString("three_pay_data", "{}");
        var statusDictionary = JsonConvert.DeserializeObject<Dictionary<string, ApplePayClass>>(payDataJson);

        // Debug.Log($"max 支付 statusDictionary {statusDictionary}");
        // 判断是否已有相同的 orderId
        if (statusDictionary.ContainsKey(orderId))
        {
            // Debug.Log($"max 支付 statusDictionary 已存在 orderId {orderId}");
            // 更新现有条目的状态
            statusDictionary[orderId] = payData;
        }
        else
        {
            // 添加新的条目
            // Debug.Log($"max 支付 statusDictionary 不存在 orderId {orderId}");
            statusDictionary.Add(orderId, payData);
        }

        // 保存更新后的数据
        PlayerPrefs.SetString("three_pay_data", JsonConvert.SerializeObject(statusDictionary));
        // Debug.Log($"max 支付 three_pay_data {JsonConvert.SerializeObject(statusDictionary)}");
    }

    public ApplePayClass GetPayData(string orderId)
    {
        var payDataJson = PlayerPrefs.GetString("three_pay_data", "{}");
        var statusDictionary = JsonConvert.DeserializeObject<Dictionary<string, ApplePayClass>>(payDataJson);

        if (statusDictionary.ContainsKey(orderId))
        {
            return statusDictionary[orderId];
        }

        return null;
    }

    public bool GetPayStatus()
    {
        bool isCheck = false;

        var payDataJson = PlayerPrefs.GetString("three_pay_data", "{}");
        var statusDictionary = JsonConvert.DeserializeObject<Dictionary<string, ApplePayClass>>(payDataJson);
        if (statusDictionary == null) return false;
        foreach (var entry in statusDictionary)
        {
            if (entry.Value.status == 1)
            {
                isCheck = true;
                break;
            }
        }

        return isCheck;
    }

    private int PayStatus = -1;

    private Coroutine PayCoroutine;

    public IEnumerator ProcessPayData()
    {
        var payDataJson = PlayerPrefs.GetString("three_pay_data", "{}");
        var statusDictionary = JsonConvert.DeserializeObject<Dictionary<string, ApplePayClass>>(payDataJson);

        foreach (var entry in statusDictionary.OrderByDescending(pair => pair.Key))
        {
            // Debug.Log($"max 支付 ProcessPayData0======{entry.Key} status:{entry.Value}");
            if (entry.Value.status == 1)
            {
                bool keepRequesting = true;

                while (keepRequesting)
                {
                    // 发起请求
                    PaySuccess(entry.Key);
                    yield return new WaitForSeconds(5f);
                    // Debug.Log($"max 支付 ProcessPayData1======{entry.Key} status:{PayStatus}");
                    if (PayStatus == 1)
                    {
                        // 如果返回值为1，则等待5秒后再次请求
                    }
                    else
                    {
                        // 如果返回值不为1，则停止循环
                        PayStatus = -1;
                        keepRequesting = false;
                    }

                    yield return null; // 等待本次请求完成
                }
            }
        }
    }

    public void StopPayCoroutine()
    {
        if (PayCoroutine != null)
        {
            CrazyAsyKit.StopCoroutine(PayCoroutine);
        }
    }

    public void PaySuccess()
    {
        // Debug.Log("max 支付 StartCoroutine------");
        PayCoroutine = CrazyAsyKit.StartCoroutine(ProcessPayData());
    }

    public void PaySuccess(string orderId)
    {
        var test = new maxOrder();
        test.order_id = orderId;
        //max 支付订单查询
        NetKit.Instance.Post<orderState>("shop/paMPayOrderQuery", test, response =>
        {
            Debug.Log($"max 支付订单查询: id= {orderId}  is succ={response.IsSuccess}");
            if (response.IsSuccess)
            {
                // Debug.Log($"max 支付订单查询: 成功,statu====: {obj.status}");
                // Debug.Log($"max 支付订单查询: {JsonConvert.SerializeObject(obj)}");
                PayStatus = response.Data.status;

                //1:支付中,需要定时查询
                if (response.Data.status == 1)
                {
                    var paydata = GetPayData(orderId);
                    if (paydata != null)
                    {
                        paydata.status = 1;
                        SavePayData(response.Data.order_id, paydata);
                    }

                    // reCreatPur();
                }
                //2:支付成功,发奖
                else if (response.Data.status == 2)
                {
                    var paydata = GetPayData(orderId);
                    if (paydata != null)
                    {
                        paydata.status = 2;
                        SavePayData(response.Data.order_id, paydata);
                    }

                    UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close);

                    bool isOpen = false;
                    if (paydata.sku == PurchasingManager.GetPaySku(PayType.buy_one))
                    {
                        isOpen = HandleSku(paydata.sku, UIConst.AddViewUI, ADEventTrack.Property.buy_one_success);
                    }
                    // else if (paydata.sku == PurchasingManager.GetPaySku(PayType.buy_one_off))
                    // {
                    //     isOpen = HandleSku(paydata.sku, UIConst.AddViewUI, ADEventTrack.Property.BuyOneOffSuccess);
                    // }
                    else if (paydata.sku != null && paydata.sku == PurchasingManager.GetPaySku(PayType.remove_ad))
                    {
                        isOpen = HandleSku(paydata.sku, UIConst.PackrewardUI, ADEventTrack.Property.remove_ad_receive);
                    }
                    else if (paydata.sku == PurchasingManager.GetPaySku(PayType.pack_reward))
                    {
                        isOpen = HandleSku(paydata.sku, UIConst.PackrewardUI, ADEventTrack.Property.lucky_gift_receive);
                    }
                    else if (paydata.shopName != null && paydata.shopName.StartsWith("buy_gold"))
                    {
                        int startIndex = "buy_gold".Length;
                        string suffix = paydata.shopName[startIndex..]; // 截取 "gold" 后的所有字符
                        string eventSuccessName = ADEventTrack.Property.shop_receive_ + suffix;

                        isOpen = HandleSku(paydata.sku, UIConst.BuygoldUI, eventSuccessName);

                    }
                    else if (paydata.sku == PurchasingManager.GetPaySku(PayType.battle_pass))
                    {
                        isOpen = HandleSku(paydata.sku, UIConst.PassViewUI, ADEventTrack.Property.master_pass_receive);
                    }
                    else if (paydata.sku == PurchasingManager.GetPaySku(PayType.fail_pack))
                    {
                        isOpen = HandleSku(paydata.sku, UIConst.PackrewardUI, ADEventTrack.Property.fail_buy_success);
                    }
                    else if (paydata.sku == PurchasingManager.GetPaySku(PayType.three_days_gift))
                    {
                        isOpen = HandleSku(paydata.sku, UIConst.ThreeDaysGiftUI, ADEventTrack.Property.three_days_gift_buy_success);
                    }
                    else if (paydata.sku.StartsWith("secret_albnums"))
                    {
                        int startIndex = "secret_albnums".Length;
                        string suffix = paydata.sku[startIndex..]; // 截取 "secret_albnums" 后的所有字符
                        string eventSuccessName = ADEventTrack.Property.secret_albums_success_ + suffix;

                        isOpen = HandleSku(paydata.sku, UIConst.SecretAlbumsNextUI, eventSuccessName);
                    }
                    else if (paydata.shopName != null && paydata.shopName.StartsWith("vip_club"))
                    {
                        int startIndex = "vip_club".Length;
                        string suffix = paydata.shopName[startIndex..]; // 截取 "vip_club" 后的所有字符
                        string eventSuccessName = ADEventTrack.Property.vip_success_ + suffix;
                        isOpen = HandleSku(paydata.sku, UIConst.VipClubViewUI, eventSuccessName);
                    }
                    else
                    {
                        // 处理未知的 sku 值
                        Debug.LogError($"Unknown SKU: {paydata.sku}");
                        throw new ArgumentException("Unknown SKU");
                    }

                    string sku = "";
                    if (paydata.sku.Contains("shop") || paydata.sku.Contains("sub"))
                    {
                        sku = paydata.shopName;
                    }
                    else
                    {
                        sku = paydata.sku;
                    }

                    GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, sku);

                    DOVirtual.DelayedCall(1, () =>
                    {
                        SaveData.GetSaveObject().max_pay_object = null;
                        var paydata = GetPayData(orderId);
                        if (paydata != null)
                        {
                            paydata.status = 4;
                            SavePayData(response.Data.order_id, paydata);
                        }
                    });
                }
                //3:支付失败,已领奖或者支付失败,或者查询次数达到上限
                else if (response.Data.status == 3)
                {
                    var paydata = GetPayData(orderId);
                    if (paydata != null)
                    {
                        paydata.status = 3;
                        SavePayData(response.Data.order_id, paydata);
                    }

                    OnPayFailed(orderId);
                }
                //4:已发货,服务端记录已经发过奖,若客户端未发奖可发奖
                else
                {
                    DOVirtual.DelayedCall(1, () =>
                    {
                        var paydata = GetPayData(orderId);
                        if (paydata != null)
                        {
                            paydata.status = 4;
                            SavePayData(response.Data.order_id, paydata);
                        }

                        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close);
                        SaveData.GetSaveObject().max_pay_object = null;

                        string sku = "";
                        if (paydata.sku.Contains("shop"))
                        {
                            sku = paydata.shopName;
                        }
                        else
                        {
                            sku = paydata.sku;
                        }
                        GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, paydata.sku);
                    });
                }
            }
            else
            {
                // Debug.Log("max 支付 验证订单失败");
                // Debug.Log($"max 支付 验证订单失败: {JsonConvert.SerializeObject(obj)}");
                //验证订单失败
                // reCreatPur();
                // status = -1;
                PayStatus = -1;
            }
        });
    }

    bool HandleSku(string sku, string uiConst, string successEvent)
    {
        bool isOpen;
        try
        {
            isOpen = CheckIsOpen(uiConst);
            TrackKit.SendEvent(ADEventTrack.MaxPayEvent, successEvent);
        }
        catch (Exception ex)
        {
            // 记录异常信息
            Debug.LogError($"Error handling SKU {sku}: {ex.Message}");
            // 可以选择重新抛出异常或进行其他处理
            throw;
        }

        return isOpen;
    }

    public void reCreatPur() //重新验证订单
    {
        // Debug.Log($"max 支付 reCreatPur 重新验证订单: pay_object_data===: {JsonConvert.SerializeObject(SaveData.GetSaveObject().max_pay_object)}");

        // if (SaveData.GetSaveObject().max_pay_object != null)
        // {
        // CrazyAsyKit.StartCoroutine(ProcessPayData());
        // } 
    }

    public void OnPayFailed(string orderId)
    {
        var paydata = GetPayData(orderId);

        if (paydata == null)
        {
            return;
        }

        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close);
        // Debug.LogWarning("OnPurchaseFailedproduct:" + product.transactionID + "  failureReason:" + failureReason);

        BIManager.Instance.TrackPurchase(paydata.amount, paydata.currency, "1", paydata.sku, "paid_err");

        DOVirtual.DelayedCall(1, () => { SaveData.GetSaveObject().max_pay_object = null; });
    }


    private bool CheckIsOpen(string name)
    {
        var isOpen = UIManager.Instance.IsExistUI(name);

        return isOpen;
    }

    private static decimal GetGoldRewradNum(int index)
    {
        decimal rewardNum = 0;
        var list = ConfigSystem.GetConfig<Paidcoins>();
        if (list.Count > 0 && list.Count > index)
        {
            rewardNum = list[index].Actual_coins;
        }

        return rewardNum;
    }

    private void GetPayReward(decimal goldNum)
    {
        if (goldNum == 0) return;

        var start = new Vector2(540, 960);
        var rewardData = new RewardData();
        var rewardSingleData = new RewardSingleData(101, goldNum, RewardOrigin.AdTask)
        {
            startPosition = start,
        };
        rewardData.AddReward(rewardSingleData);
        rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange;

        GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData);
    }
}

public class maxOrder
{
    public string order_id;
}

public class ApplePayClass
{
    public string innerOrderId;
    public string transactionId;
    public int amount;
    public string sku;
    public string currency = "USD";
    public int status;
    public string shopName;
    public string type;
}


// public class ApplePayClass
// {
//     public string innerOrderId;
//     public int amount;
//     public string sku;
//     public string currency = "USD";
//     public int status;
// }

public class PayerData
{
    public string name;
    public string tel;
    public string email;
    public int amount;
}

// 假设 orderState 是返回对象的类型
// public class orderState
// {
//     public int State;
// }