using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Scripting;

[Preserve]
public class GameManager : MonoBehaviour
{

    public ExitConfirmationDialog exitDialog; // 在 Inspector 中设置
    private bool isExiting = false; // 防止重复调用退出

    [Preserve]
    private void Awake()
    {
        // 触发单例构造，内部会调用 PlatformCallback.SetListener(this)
        var _ = HoolaiListener.Instance;
        HoolaiListener.Instance.SetExitConfirmationDialog(exitDialog);
    }


    //Android 需监听返回事件，如果当前场景没有游戏业务处理了（比如拦截返回上一个场景，此时无需调用，但返回到顶级场景后继续返回需处理此逻辑）需调用 SDK 的退出接口
    [Preserve]
    void Update()
    {
        if (Input.GetKey(KeyCode.Escape))
        {
            NativeLogger.I("Game_Unity_Log", "clicked Exit");
            HandleExit();
        }
    }

    [Preserve]
    private void HandleExit()
    {
        // 防止重复调用
        if (isExiting) return;

        isExiting = true;
        NativeLogger.I("Game_Unity_Log", "clicked Exit");
        HoolaiSdkManager.ExitGame();

        // 延迟重置标志位，防止短时间内重复触发
        Invoke("ResetExitFlag", 0.5f);
    }

    [Preserve]
    private void ResetExitFlag()
    {
        isExiting = false;
    }

    [Preserve]
    public void OnLoginBtnClicked()
    {
        NativeLogger.I("Game_Unity_Log", "clicked login");
        //SdkPluginManager.CallSdkLogin();
        HoolaiSdkManager.Login();
    }

    [Preserve]
    public void OnLogoutBtnClicked()
    {
        NativeLogger.I("Game_Unity_Log", "clicked logout");
        HoolaiSdkManager.Logout();
    }

    [Preserve]
    public void OnEnterServerBtnClicked()
    {
        NativeLogger.I("Game_Unity_Log", "clicked EnterServer");
        PlayerInfo playerInfo = new PlayerInfo();
        playerInfo.RoleId = "1234567";
        playerInfo.RoleName = "大鹏一日同风起";
        playerInfo.RoleLevel = "999";
        playerInfo.ZoneId = "1";
        playerInfo.ZoneName = "傲视九重天";
        playerInfo.ServerId = "1";
        playerInfo.ServerName = "傲视九重天";
        playerInfo.Balance = "9999";
        playerInfo.Vip = "99";
        playerInfo.PartyName = "少林寺";
        playerInfo.AppVersion = "1.0.1";
        playerInfo.AppResVersion = "100";
        playerInfo.ExtendAction = "无敌";
        playerInfo.RoleCreateTime = "";
        playerInfo.Phylum = "100";
        playerInfo.ClassField = "滴滴滴答";

        //Game Extra sample Data(optional)
        playerInfo.AddExtra("intKey", 55);
        playerInfo.AddExtra("longLongKey", 66786658787676);
        playerInfo.AddExtra("stringKey", "Hello111");

        HoolaiSdkManager.SendEvent(EventType.EnterServer, playerInfo);
        NativeLogger.I("Game_Unity_Log", "clicked EnterServer");
        HoolaiSdkManager.SendEvent(EventType.CreateRole, playerInfo);
        NativeLogger.I("Game_Unity_Log", "clicked CreateRole");
        HoolaiSdkManager.SendEvent(EventType.LevelUp, playerInfo);
        NativeLogger.I("Game_Unity_Log", "clicked LevelUp");
        HoolaiSdkManager.SendEvent(EventType.CustomerAction, playerInfo);
        NativeLogger.I("Game_Unity_Log", "clicked CustomerAction");
    }


    [Preserve]
    public void OnPayBtnClicked1()
    {
        NativeLogger.I("Game_Unity_Log", "clicked Pay");

        // 1. 创建并填充对象
        PayParams payParams = new PayParams
        {
            Amount = 100,// 单位：分
            ItemId = "com.nekki.sf3.cn_1",
            ItemName = "礼包0",
            CallbackInfo = "123456_8888_987654321",
            NotifyUrl = "",
            Count = 1,
            Currency = "CNY"
        };
        payParams.AddOptionalParameter("test", "daily_bonus");
        payParams.AddOptionalParameter("player_id", "p-98765");

        NativeLogger.I("Game_Unity_Log", $"clicked Exit jsonString: {payParams}");
        HoolaiSdkManager.StartPay(payParams);
    }


    [Preserve]
    public void OnPayBtnClicked6()
    {
        NativeLogger.I("Game_Unity_Log", "clicked Pay");

        // 1. 创建并填充对象
        PayParams payParams = new PayParams
        {
            Amount = 600, // 单位：分
            ItemId = "com.nekki.sf3.cn_6",
            ItemName = "礼包1",
            CallbackInfo = "123456_8888_987654321",
            NotifyUrl = "",
            Count = 1,
            Currency = "CNY"
        };
        payParams.AddOptionalParameter("test", "daily_bonus");
        payParams.AddOptionalParameter("player_id", "p-98765");

        NativeLogger.I("Game_Unity_Log", $"clicked Exit jsonString: {payParams}");
        HoolaiSdkManager.StartPay(payParams);
    }

    [Preserve]
    public void OnPayBtnClicked68()
    {
        NativeLogger.I("Game_Unity_Log", "clicked Pay");

        // 1. 创建并填充对象
        PayParams payParams = new PayParams
        {
            Amount = 6800,// 单位：分
            ItemId = "com.nekki.sf3.ch_68",
            ItemName = "礼包10",
            CallbackInfo = "123456_8888_987654321",
            NotifyUrl = "",
            Count = 1,
            Currency = "CNY"
        };
        payParams.AddOptionalParameter("test", "daily_bonus");
        payParams.AddOptionalParameter("player_id", "p-98765");

        NativeLogger.I("Game_Unity_Log", $"clicked Exit jsonString: {payParams}");
        HoolaiSdkManager.StartPay(payParams);
    }

    [Preserve]
    public void OnPayBtnClicked128()
    {
        NativeLogger.I("Game_Unity_Log", "clicked Pay");

        // 1. 创建并填充对象
        PayParams payParams = new PayParams
        {
            Amount = 12800,// 单位：分
            ItemId = "com.nekki.sf3.cn_128",
            ItemName = "礼包20",
            CallbackInfo = "123456_8888_987654321",
            NotifyUrl = "",
            Count = 1,
            Currency = "CNY"
        };
        payParams.AddOptionalParameter("test", "daily_bonus");
        payParams.AddOptionalParameter("player_id", "p-98765");

        NativeLogger.I("Game_Unity_Log", $"clicked Exit jsonString: {payParams}");
        HoolaiSdkManager.StartPay(payParams);
    }

    [Preserve]
    public void OnExitBtnClicked()
    {
        NativeLogger.I("Game_Unity_Log", "clicked Exit");
        HoolaiSdkManager.ExitGame();
    }

    [Preserve]
    public void OnGetProductInfoBtnClicked()
    {
        NativeLogger.I("Game_Unity_Log", "clicked QueryGoodsInfo");
        HoolaiSdkManager.QueryGoodsInfo();
    }


    // 添加方法用于根据索引获取单个商品信息
    [Preserve]
    public static GoodsInfo GetGoodsInfoByIndex(List<GoodsInfo> goodsList, int index)
    {
        if (goodsList != null &&
            index >= 0 &&
            index < goodsList.Count)
        {
            return goodsList[index];
        }
        return null;
    }


    // 新增方法：使用指定索引的商品数据进行支付
    [Preserve]
    public void OnPayWithSpecificGoodsBtnClicked(int goodsIndex)
    {
        NativeLogger.I("Game_Unity_Log", "clicked Pay With Random Goods");

        // 获取缓存的商品列表
        List<GoodsInfo> goodsList = HoolaiListener.Instance.GetCachedGoodsList();

        if (goodsList == null || goodsList.Count == 0)
        {
            NativeLogger.I("Game_Unity_Log", "No goods list available. Please query goods info first.");
            return;
        }

        System.Random random = new System.Random();
        int randomIndex = random.Next(0, goodsList.Count);
        GoodsInfo randomGoods = GetGoodsInfoByIndex(goodsList, randomIndex);

        if (randomGoods != null)
        {
            // 将GoodsInfo转换为PayParams
            PayParams payParams = ConvertGoodsInfoToPayParams(randomGoods, 1);

            if (payParams != null)
            {
                NativeLogger.I("Game_Unity_Log", $"Paying with random goods: {randomGoods.itemName} at index {randomIndex}");
                HoolaiSdkManager.StartPay(payParams);
            }
            else
            {
                NativeLogger.I("Game_Unity_Log", "Failed to convert goods info to pay params");
            }
        }
        else
        {
            NativeLogger.I("Game_Unity_Log", "No goods available at random index");
        }
    }


    // 添加方法用于将GoodsInfo转换为PayParams
    [Preserve]
    public PayParams ConvertGoodsInfoToPayParams(GoodsInfo goodsInfo, int count = 1)
    {
        if (goodsInfo == null) return null;
        System.Random random = new System.Random();
        int randomIndex = random.Next(0, 100);
        PayParams payParams = new PayParams
        {
            // 根据GoodsInfo的数据填充PayParams
            Amount = int.TryParse(goodsInfo.itemPrice, out int price) ? price : 1,
            ItemId = goodsInfo.itemId ?? "goods_info_6",
            ItemName = goodsInfo.itemName ?? "宝石",
            Count = count,
            CallbackInfo = "Game_itemId_"+ randomIndex, // 游戏透传参数，必传
            NotifyUrl = "",    // 支付回调地址，默认使用客户端传递的
            Currency = goodsInfo.currency ?? "USD"
        };

        return payParams;
    }

    [Preserve]
    public void OnCDKBtnClicked()
    {
        NativeLogger.I("Game_Unity_Log", "clicked CDKey");
        HoolaiSdkManager.AccessParticipate(AccessActivityType.CD_KEY, "123456789");
    }


    [Preserve]
    public void OnShareBtnClicked()
    {
        NativeLogger.I("Game_Unity_Log", "clicked shareData");
        HoolaiSdkManager.ShareData(1, 1, "test");
    }

    [Preserve]
    public void OnOpenServiceBtnClicked()
    {
        NativeLogger.I("Game_Unity_Log", "clicked openService");
        HoolaiSdkManager.OpenService();
    }

    [Preserve]
    public void OnOpenAccountBtnClicked()
    {
        NativeLogger.I("Game_Unity_Log", "clicked openAccount");
        HoolaiSdkManager.OpenAccountCenter();
    }

}
