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

public class GameManager : MonoBehaviour
{

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

    [Header("分享的本地资源图片")]
    [Tooltip("此 Texture 必须在 Inspector 中开启 'Read/Write Enabled'")]
    public Texture2D localResourceImage; // 从 Inspector 拖入

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


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

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

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

    private void ResetExitFlag()
    {
        isExiting = false;
    }

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

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

    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 = "滴滴滴答";

        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");
    }


    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);
    }


    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);
    }

    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);
    }

    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);
    }

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

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


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


    // 新增方法：使用指定索引的商品数据进行支付
    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
    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;
    }

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


    public void OnShareBtnClicked()
    {
        NativeLogger.I("Game_Unity_Log", "clicked shareData");
        //HoolaiSdkManager.ShareData(ShareType.WX_SHARE, ShareType.QQ_SESSION, "test");
    }

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

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



    public void OnWXShareText()
    {
        NativeLogger.I("Game_Unity_Log", "clicked OnWXShareText WECHAT_TIMELINE");

        ShareParams shareParams = new ShareParams
        {
            title = "我是分享测试Title",
            content = "我是分享测试Content",
            picPath = "我是图片地址",
            shareUrl = "我是分享的链接"

        };

        HoolaiSdkManager.ShareData(SharePlatformType.WECHAT_TIMELINE, ShareType.TEXT, shareParams);

    }
    public void OnWXShareImage()
    {
        NativeLogger.I("Game_Unity_Log", "开始截图分享流程...");
        // 因为截图是异步的，所以需要启动协程
        StartCoroutine(NativeShareHelper.CaptureAndSaveScreenshot(ShareWxScreenshotCallback));

    }

    private void ShareWxScreenshotCallback(string imagePath)
    {
        if (!string.IsNullOrEmpty(imagePath))
        {
            NativeLogger.I("Game_Unity_Log", $"截图已就绪，路径为: {imagePath}。准备调用原生分享接口...");

            NativeLogger.I("Game_Unity_Log", "clicked OnWXShareImage WECHAT_SESSION");


            ShareParams shareParams = new ShareParams
            {
                title = "我是分享测试Title",
                content = "我是分享测试Content",
                picPath = imagePath,
                shareUrl = "我是分享的链接",

            };

            HoolaiSdkManager.ShareData(SharePlatformType.WECHAT_SESSION,ShareType.IMG, shareParams);
        }
        else
        {
            Debug.LogError("截图失败，无法分享。");
        }
    }


    public void OnWXShareFavorite()
    {
        NativeLogger.I("Game_Unity_Log", "clicked OnWXShareFavorite WECHAT_FAVORITE");

        ShareParams shareParams = new ShareParams
        {
            title = "我是分享测试Title",
            content = "我是分享测试Content",
            picPath = "我是图片地址",
            shareUrl = "我是分享的链接"

        };

        HoolaiSdkManager.ShareData(SharePlatformType.WECHAT_FAVORITE, ShareType.TEXT, shareParams);

    }


    public void OnQQShareTEXT()
    {

        NativeLogger.I("Game_Unity_Log", "clicked OnQQShareImage QQ_LINK");

        ShareParams shareParams = new ShareParams
        {
            title = "我是分享测试Title",
            content = "我是分享测试Content",
            picPath = "我是图片地址",
            shareUrl = "https://img1.baidu.com/it/u=2172818577,3783888802&fm=253&app=138&f=JPEG"

        };

        HoolaiSdkManager.ShareData(SharePlatformType.QQ, ShareType.LINK, shareParams);

    }

    public void OnQQShareImage()
    {
        NativeLogger.I("Game_Unity_Log", "开始截图分享流程...");
        // 因为截图是异步的，所以需要启动协程
        StartCoroutine(NativeShareHelper.CaptureAndSaveScreenshot(ShareQQScreenshotCallback));

    }

    private void ShareQQScreenshotCallback(string imagePath)
    {
        if (!string.IsNullOrEmpty(imagePath))
        {
            NativeLogger.I("Game_Unity_Log", $"截图已就绪，路径为: {imagePath}。准备调用原生分享接口...");
            NativeLogger.I("Game_Unity_Log", "clicked OnQQShareTEXT QQ_IMG");

            ShareParams shareParams = new ShareParams
            {
                title = "我是分享测试Title",
                content = "我是分享测试Content",
                picPath = imagePath,
                shareUrl = "我是分享的链接"

            };

            HoolaiSdkManager.ShareData(SharePlatformType.QQ, ShareType.IMG, shareParams);
        }
        else
        {
            Debug.LogError("截图失败，无法分享。");
        }
    }
}
