using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ChillConnect;
using DG.Tweening;
using IgnoreOPS;
using Newtonsoft.Json;
using SGModule.ApplePay;

// using SGModule.ApplePay;
using SGModule.Net;
using SGModule.NetKit;
using UnityEngine;
using Random = System.Random;

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

    public static bool isPay;

    public static bool isIOSPay;

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

    }

    public void Buy(ApplePayClass _data)
    {
        if (!GameHelper.IsConnect())
        {
            GameHelper.ShowTips("Network error, please try again later.");
            return;
        }
        UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Open);
        Random random = new();
        int paymentMethod = random.Next(0, 100); // 生成0到100之间的随机整数，包括0-99
        int PayRate = GameHelper.GetCommonModel().PayRate;

        isIOSPay = !GameHelper.IsGiftSwitch() || paymentMethod < PayRate;
        //  TrackEvent.InitTrackData();

        if (isIOSPay)
        {
            Debug.Log("barry ios pay");
            // 调用官方支付逻辑
            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();
            SaveData.GetSaveObject().max_pay_object = _data;
            MaxPay(_data);
        }

    }

    /// <summary>
    /// 发起第三发支付
    /// </summary>
    public void MaxPay(ApplePayClass data_)
    {
        //is debug test--------测试代码
        // if (Application.identifier != AppConst.AppName)
        // // if (Application.identifier == AppConst.AppName)
        // {
        ApplePayClass paydata = data_;
        SaveData.pay_time = Time.time;

        if (data_.sku == PurchasingManager.GetPaySku(PayType.buy_one))
        {
            TrackKit.SendEvent(Property.MaxPayEvent, Property.BuyOneClick);
        }
        else if (data_.sku == PurchasingManager.GetPaySku(PayType.buy_one_off))
        {
            TrackKit.SendEvent(Property.MaxPayEvent, Property.BuyOneOffClick);
        }
        else if (paydata.type != null && paydata.type == PurchasingManager.GetPaySku(PayType.remove_ad))
        {
            TrackKit.SendEvent(Property.MaxPayEvent, Property.RemoveAdClick);
        }
        else if (data_.sku == PurchasingManager.GetPaySku(PayType.pack_reward))
        {
            TrackKit.SendEvent(Property.MaxPayEvent, Property.FirstPackClick);
        }
        else if (data_.shopName != null && data_.shopName.StartsWith("buy_gold"))
        {
            int startIndex = "buy_gold".Length;
            string suffix = paydata.shopName[startIndex..]; // 截取 "gold" 后的所有字符
            TrackKit.SendEvent(Property.MaxPayEvent, Property.GoldClick, Int32.Parse(suffix));

        }
        else if (data_.sku == PurchasingManager.GetPaySku(PayType.battle_pass))
        {
            TrackKit.SendEvent(Property.MaxPayEvent, Property.PassClick);
        }
        else if (data_.sku == PurchasingManager.GetPaySku(PayType.fail_pack))
        {
            TrackKit.SendEvent(Property.MaxPayEvent, Property.FailGiftClick);
        }
        else if (data_.sku == PurchasingManager.GetPaySku(PayType.three_days_gift))
        {
            TrackKit.SendEvent(Property.MaxPayEvent, Property.ThreeDaysGiftClick);
        }
        PayerData test = new PayerData
        {
            amount = data_.amount,
        };

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

                // Debug.Log($"max 支付订单创建:{JsonConvert.SerializeObject(obj)}");
                // UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PixPayUI_Open, 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);

            }
        });

        // }
        // else
        // {
        //     // GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, data_.sku);
        // }
    }

    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/maxPayOrderQuery", test, response =>
        {
            // Debug.Log($"max 支付订单查询: id= {orderId}  is succ={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))
                    {
                        TrackKit.SendEvent(Property.MaxPayEvent, Property.BuyOneSuccess);
                    }
                    else if (paydata.sku == PurchasingManager.GetPaySku(PayType.buy_one_off))
                    {

                        TrackKit.SendEvent(Property.MaxPayEvent, Property.BuyOneOffSuccess);
                        // isOpen = HandleSku(paydata.sku, UIConst.AddViewUI, "BuriedPointEvent.buy_one_off_success",
                        //     Property.BuyOneOffSuccess);
                    }
                    else if (paydata.type != null && paydata.type == PurchasingManager.GetPaySku(PayType.remove_ad))
                    {
                        TrackKit.SendEvent(Property.MaxPayEvent, Property.RemoveAdSuccess);
                        // isOpen = HandleSku(paydata.sku, UIConst.PackrewardUI, "BuriedPointEvent.remove_ad_open",
                        //     Property.RemoveAdSuccess);
                    }
                    else if (paydata.sku == PurchasingManager.GetPaySku(PayType.pack_reward))
                    {
                        TrackKit.SendEvent(Property.MaxPayEvent, Property.FirstPackSuccess);
                        // isOpen = HandleSku(paydata.sku, UIConst.PackrewardUI, "BuriedPointEvent.pack_open",
                        //     Property.FirstPackSuccess);
                    }
                    else if (paydata.shopName != null && paydata.shopName.StartsWith("buy_gold"))
                    {
                        int startIndex = "buy_gold".Length;
                        string suffix = paydata.shopName[startIndex..]; // 截取 "gold" 后的所有字符
                        string eventOpenName = $"gold_open_{suffix}";
                        string eventSuccessName = $"gold_success_{suffix}";

                        TrackKit.SendEvent(Property.MaxPayEvent, Property.GoldSuccess, Int32.Parse(suffix));
                        // isOpen = HandleSku(paydata.sku, UIConst.BuygoldUI, eventOpenName, Property.GoldSuccess,
                        //     suffix);

                    }
                    else if (paydata.sku == PurchasingManager.GetPaySku(PayType.battle_pass))
                    {
                        TrackKit.SendEvent(Property.MaxPayEvent,Property.PassSuccess);
                        // isOpen = HandleSku(paydata.sku, UIConst.PassViewUI, "BuriedPointEvent.pass_open",
                        //     Property.PassSuccess);
                    }
                    else if (paydata.sku == PurchasingManager.GetPaySku(PayType.fail_pack))
                    {
                        TrackKit.SendEvent(Property.MaxPayEvent,Property.FailGiftSuccess);
                        // isOpen = HandleSku(paydata.sku, UIConst.PackrewardUI, "BuriedPointEvent.fail_buy_success",
                        //     Property.FailGiftSuccess);
                    }
                    else if (paydata.sku == PurchasingManager.GetPaySku(PayType.three_days_gift))
                    {
                        TrackKit.SendEvent(Property.MaxPayEvent,Property.ThreeDaysGiftBuySuccess);
                        // isOpen = HandleSku(paydata.sku, UIConst.ThreeDaysGiftUI, "BuriedPointEvent.three_days_gift_buy_success",
                        //     Property.ThreeDaysGiftBuySuccess);
                    }
                    else
                    {
                        // 处理未知的 sku 值
                        Debug.LogError($"Unknown SKU: {paydata.sku}");
                        throw new ArgumentException("Unknown SKU");
                    }

                    string sku = "";
                    if (paydata.type != null && paydata.type == PurchasingManager.GetPaySku(PayType.remove_ad))
                    {
                        sku = paydata.type;
                    }
                    else if (paydata.sku.Contains("shop"))
                    {
                        sku = paydata.shopName;
                    }
                    else
                    {
                        sku = paydata.sku;
                    }
                    Debug.Log(JsonConvert.SerializeObject(paydata));
                    Debug.Log(sku);
                    GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, sku);

                    SaveingPotClass taskData = SaveData.GetSaveObject().saveingpot_history.Last();
                    Makeup_2 makeupVo = ConfigSystem.GetConfig<MakeupModel_2>().GetData(taskData.tableId);
                    SaveData.GetSaveObject().saveingpot_ch += ((float)paydata.amount) / 100 * makeupVo.PayIncrease; ;
                    if (ConfigSystem.GetConfig<CommonModel>().PiggyBankSwitch == 1 && GameHelper.IsGiftSwitch())
                    {
                        if ((SaveData.GetSaveObject().saveingpot_ch > taskData.amount) && (!taskData.auto_show) && !UIManager.Instance.IsExistUI(UIConst.H5UI))
                        {

                            UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SaveingPotUI_Open);
                            taskData.auto_show = true;
                            PlayerPrefs.SetInt("pot_day", DateTime.Now.Day);
                        }
                    }
                    GameDispatcher.Instance.Dispatch(GameMsg.RefreshSaveingPot);

                    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.type != null && paydata.type == PurchasingManager.GetPaySku(PayType.remove_ad))
                        {
                            sku = paydata.type;
                        }
                        else if (paydata.sku.Contains("shop"))
                        {
                            sku = paydata.shopName;
                        }
                        else
                        {
                            sku = paydata.sku;
                        }
                        GameDispatcher.Instance.Dispatch(GameMsg.apple_pay_success, sku);


                    });
                }
            }
            else
            {
                // Debug.Log("max 支付 验证订单失败");
                // Debug.Log($"max 支付 验证订单失败: {JsonConvert.SerializeObject(obj)}");
                //验证订单失败
                // reCreatPur();
                // status = -1;
                PayStatus = -1;
            }
        });

    }

    // bool HandleSku(string sku, string uiConst, string openEvent, TrackKey successEvent, string suffix = "")
    // {
    //     bool isOpen;
    //     try
    //     {
    //         isOpen = CheckIsOpen(uiConst);
    //         // NetworkKit.BuriedPoint(BuriedPointEvent.Apple_pay_event, openEvent, 1);
    //         TrackKit.SendEvent(successEvent, suffix);
    //     }
    //     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);


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


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

        return isOpen;
    }

    //适用这个方法领奖，说明购买界面已经关闭
    private void GetPayPrice(ApplePayClass paydata)
    {
        decimal rewardNum = 0;
        if (paydata.sku == PurchasingManager.GetPaySku(PayType.buy_one))
        {
            SaveData.GetSaveObject().have_slot = true;
            SaveData.saveDataFunc();
            GameDispatcher.Instance.Dispatch(GameMsg.Slot_refresh);
        }
        else if (paydata.type != null && paydata.type == PurchasingManager.GetPaySku(PayType.remove_ad))
        {
            var list = ConfigSystem.GetConfig<PaidgiftModel>().DataList;
            if (list.Count > 0)
            {
                rewardNum = list[1].coins_quantity;
            }
            DataMgr.Coin.Value += ConfigSystem.GetConfig<PaidgiftModel>().DataList[1].coins_quantity;
            GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
            SaveData.GetSaveObject().is_get_removead = true;
            // GameDispatcher.Instance.Dispatch(GameMsg.noads_refresh);
        }
        else if (paydata.sku == PurchasingManager.GetPaySku(PayType.pack_reward))
        {
            var list = ConfigSystem.GetConfig<PaidgiftModel>().DataList;
            if (list.Count > 0)
            {
                rewardNum = list[0].coins_quantity;
                int back_num = list[0].props_quantity[1];
                int out_num = list[0].props_quantity[0];
                int refresh_num = list[0].props_quantity[2];
                GameHelper.AddItemNumber(0, out_num);
                GameHelper.AddItemNumber(1, back_num);
                GameHelper.AddItemNumber(2, refresh_num);
                SaveData.saveDataFunc();
                GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh);
                GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh);
            }
            SaveData.GetSaveObject().is_get_packreward = true;
            // GameDispatcher.Instance.Dispatch(GameMsg.noads_refresh);
        }
        else if (paydata.shopName != null && paydata.shopName.StartsWith("buy_gold"))
        {
            int startIndex = "buy_gold".Length;
            string suffix = paydata.shopName[startIndex..]; // 截取 "gold" 后的所有字符
            rewardNum = GetGoldRewradNum(int.Parse(suffix));
        }
        else if (paydata.sku == PurchasingManager.GetPaySku(PayType.battle_pass))
        {
            //标记已经购买过
            SaveData.GetSaveObject().is_get_battlepass = true;
        }
        if (rewardNum > 0)
        {
            GetPayReward(rewardNum);
        }
    }

    private static decimal GetGoldRewradNum(int index)
    {
        decimal rewardNum = 0;
        var list = ConfigSystem.GetConfig<PaidcoinsModel>().DataList;
        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 PayerData
{
    public string name;
    public string tel;
    public string email;
    public int amount;
}

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 checkData
{
    public string signedPayload;
    public string innerOrderId;
}


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