﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using Xsolla.Catalog;
using Xsolla.Core;
using SysDebug = System.Diagnostics.Debug; // 为System.Diagnostics.Debug创建别名
using SysProcess = System.Diagnostics.Process; // 为Process创建别名
using SysProcessStartInfo = System.Diagnostics.ProcessStartInfo;
namespace NeoriginPCSDK
{
    // NeoriginPlatformBaseServer 用于处理与平台服务器的交互
    public class NeoriginPlatformBaseServer
    {
        protected class CoroutineMonoBehaviour : MonoBehaviour
        {
            // 定义一个静态事件，供外部订阅
            // bool 参数含义：true = 回到前台/获得焦点, false = 切到后台/失去焦点
            public event Action<bool> OnFocusChanged;

            void OnApplicationFocus(bool hasFocus)
            {
                // 触发事件
                OnFocusChanged?.Invoke(hasFocus);
            }

            void OnApplicationPause(bool pauseStatus)
            {
                // pauseStatus = true  => 暂停 (切后台)
                // pauseStatus = false => 恢复 (切前台)

                // 我们统一转换成 "hasFocus" 的概念：不暂停 = 有焦点
                bool hasFocus = !pauseStatus;
                OnFocusChanged?.Invoke(hasFocus);
            }
        }

        private CoroutineMonoBehaviour coroutineMonoBehaviour;
        protected string baseUrl; // 用于存储基础域名
        protected string platformH5Url; // h5基础域名
        protected string platformAppId;
        protected string platformAPPKey;
        protected string platformAppSecret;
        public string platformAihelpDomain;
        public string platformAihelpAppId;
        public string platformAihelpEntryId;
        public string platformGoogleClientId;
        protected string platformSDKVersion = "1.0.0"; // SDK版本
        protected string platformPayXsolla = "8";
        protected string platformH5PageEmailLogin = "mail_login.html";
        protected string platformH5PageUserCenter = "usercenter.html";
        protected string platformH5PageKefu = "aihelp.html";
        protected string platformH5PageGoogleLogin = "google_login.html";
        protected string platformH5PageGoogleBind = "google_bind.html";
        protected string platformH5PagePay = "pay.html";
        protected string platformH5Steam = "steam.html";

        protected bool platformIsDebug = false;

        protected virtual string PlatformAiHelpPlatformTag => "Platform_PC";
        protected JObject platformInitRepData = new JObject();

        // 确保在使用任何协程前实例化CoroutineMonoBehaviour
        protected CoroutineMonoBehaviour EnsureCoroutineMonoBehaviour()
        {
            if (coroutineMonoBehaviour == null)
            {
                GameObject coroutineHelper = new GameObject("NeoriginU8Server_Helper");
                coroutineMonoBehaviour = coroutineHelper.AddComponent<CoroutineMonoBehaviour>();
                UnityEngine.Object.DontDestroyOnLoad(coroutineHelper); // 确保跨场景不销毁
            }
            return coroutineMonoBehaviour;
        }

        // 初始化时设置基础域名
        public virtual void Initialize(NeoriginSDKConfig.Platform sdkConfig, NeoriginSDKDevice deviceData, NeoriginSDKParamsInit initData, NeoriginSDK.InitCallBack callBack)
        {
            platformIsDebug = initData?.isDebug ?? false;
            baseUrl = sdkConfig.platformUrl; // 设置基础域名
            platformH5Url = sdkConfig.platformH5Url;
            EnsureCoroutineMonoBehaviour();
            platformAppId = sdkConfig.platformAppId;
            platformAPPKey = sdkConfig.platformAppKey;
            platformAppSecret = sdkConfig.platformAppSecret;
            platformAihelpDomain = sdkConfig.platformAihelpDomain;
            platformAihelpAppId = sdkConfig.platformAihelpAppId;
            platformAihelpEntryId = sdkConfig.platformAihelpEntryId;
            platformGoogleClientId = sdkConfig.platformGoogleClientId;
            platformSDKVersion = sdkConfig.sdkVersion;
            if (string.IsNullOrEmpty(baseUrl) || string.IsNullOrEmpty(platformAppId) || string.IsNullOrEmpty(platformAPPKey) || string.IsNullOrEmpty(platformAppSecret))
            {
                Debug.LogError("NeoriginPlatformServer not initialized. Please call Initialize() first.");
                return;
            }
            bool h5TestEnv = platformH5Url.Contains("pc-pre-sdk-h5");//pre
            bool h5Env = platformH5Url.Contains("pc-pre3-sdk-h5");//neorigin
            bool h5MetaEnv = platformH5Url.Contains("pc-pre4-sdk-h5");//metajoy
            if (!h5Env && !h5TestEnv && !h5MetaEnv)
            {
                platformH5PageEmailLogin = "login";
                platformH5PageUserCenter = "account";
                platformH5PageKefu = "aihelp";
                platformH5PageGoogleLogin = "google-login";
                platformH5PageGoogleBind = "google-login";
                platformH5PagePay = "pay";
                platformH5Steam = "steam";
            }

            //初始化平台SDK
            Init((response) =>
            {
                if (response.isNetworkError || response.isHttpError)
                {
                    // 处理错误
                    Debug.Log($"NeoriginPlatformServer Error: {response.error},code {response.responseCode}");
                    callBack?.Invoke(code: NeoriginSDKStatusCode.BadRequest, msg: $"Platform request error.code:{response.responseCode},Error:{response.error}");
                }
                else
                {
                    // 成功接收到响应
                    string responseData = response.downloadHandler.text;  // 文本信息
                    Debug.Log($"NeoriginPlatformServer Received: {responseData}");
                    //dynamic rep = JsonConvert.DeserializeObject(responseData);//JsonUtility.FromJson<NeoriginSDKBaseResponse>(responseData);
                    // 解析整个JSON
                    JObject rep = JObject.Parse(responseData);
                    int errorCode = (int)rep["error"];
                    string message = (string)rep["msg"];
                    Debug.Log($"NeoriginPlatformServer rep: {errorCode} # {message}");
                    if (errorCode != 0)
                    {
                        Debug.Log($"NeoriginPlatformServer Error: {message}");
                        callBack?.Invoke(code: NeoriginSDKStatusCode.InternalError, msg: $"Platform return error.code:{errorCode},message:{message}");
                        return;
                    }
                    //保存返回数据
                    JObject repData = (JObject)rep["data"];
                    InitHandle(repData);

                    // 开始游戏逻辑...
                    callBack?.Invoke(code: NeoriginSDKStatusCode.Success, msg: "Init Success.");
                }
            });

        }

        public virtual void Login(string userAccount, int touristFlag, NeoriginSDK.LoginCallBack callBack)
        {
            //读取本地登录状态
            NeoriginSDKPlatformUserInfo userInfo = NeoriginSDKStorage.LoadPlatformUserInfo();
            if (userInfo == null || string.IsNullOrEmpty(userInfo.showName))
            {
                Debug.LogWarning($"Login loadPlatformUserInfo: No valid user info found for account {userAccount}. Creating new user info.");
                //本地登录信息不存在，需要调用游客登录，测试时打开
                if (touristFlag == 1)
                {
                    LoginTourist(userAccount, (response) =>
                    {
                        PlatformLoginRequestHandle("LoginTourist", response, (code, msg, res) =>
                        {
                            callBack?.Invoke(code, msg, res);
                        });
                    });
                }
                else
                {
                    //不需要游客登录，因为PC端必须要登录账号
                    callBack?.Invoke(NeoriginSDKStatusCode.LoginNoTourist, "LoginTourist", new NeoriginSDKCallbackDataLogin());
                }
            }
            else
            {
                //本地登录信息存在，需要调用token登录
                Debug.Log($"Login loadPlatformUserInfo: {userInfo.uuid} # {userInfo.token} # {userInfo.showName}");
                LoginToken(userInfo.uuid, userInfo.token, (response) =>
                {
                    PlatformLoginRequestHandle("LoginToken", response, (code, msg, res) =>
                    {
                        callBack?.Invoke(code, msg, res);
                    });
                });
            }
        }

        public virtual void LoginAccount(NeoriginSDK.LoginAccountCallBack callBack, NeoriginSDK.LoginAccountProcessCallBack processCallBack = null)
        {
            Debug.Log("NeoriginPlatformServer LoginAccount");
            //读取本地登录状态
            string urlParameters = GetWebViewParameters();

            NeoriginSDKWebview sdkWebView = new NeoriginSDKWebview(
                onCloseListener: () =>
                {
                    // 用户关闭了WebView
                    Debug.Log("LoginAccount: User closed the WebView.");
                    callBack?.Invoke(NeoriginSDKStatusCode.WebViewUserCanceled, "User closed the login window.", null);
                }, isShowCloseBtn: false
            );
            sdkWebView.adjustmentProportion(0.82f, 0.82f);
            string h5File = platformH5PageEmailLogin;
            //sdkWebView.ShowWebView("https://login-test.topreels.com/googleauth.html");
            string htmlPath = Path.Combine(Application.streamingAssetsPath, h5File);
            //string h5Url = "file://" + htmlPath;
            string h5Url = platformH5Url + "/" + h5File;

            NeoriginSDKShowWebViewParams webviewParams = new NeoriginSDKShowWebViewParams
            {
                isDebug = platformIsDebug
            };
            sdkWebView.ShowWebView(h5Url + urlParameters, webviewParams, () =>
            {
                Debug.Log("LoginAccount loaded successfully");
            }, (args) =>
            {
                //判断参数是否正确
                if (args == null || args.Count < 2)
                {
                    Debug.Log("LogLoginAccountinH5 JS call arguments are invalid.");
                    sdkWebView.CallJsFunc("unity handle error:arguments are invalid");
                    return;
                }
                Debug.Log("LoginAccount JS call: " + args[0] + ", " + args[1]);

                //按args[0]的值判断登录类型，处理不同的业务逻辑
                if (args[0] == "login_google")
                {
                    // 处理登录逻辑
                    Debug.Log("LogiLoginAccountnH5: User logged in with google account: " + args[1]);
                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    string message = (string)jsonObject["msg"];
                    if (errorCode == 0)
                    {
                        JObject dataObject = (JObject)jsonObject["data"];
                        LoginHandle(dataObject);
                        NeoriginSDKCallbackDataLoginAccount user = new NeoriginSDKCallbackDataLoginAccount
                        {
                            sdkUserID = dataObject["showName"].ToString(),
                            sdkUserName = dataObject["showName"].ToString(),
                            sdkLogUserId = dataObject["displayName"].ToString(),
                            sdkLogThirdUserName = dataObject["sdkLogThirdUserName"]?.ToString() ?? "",//google登录没有返回三方用户名
                            isNew = (int)dataObject["isNew"],
                            thirdLoginType = 1,
                            thirdLoginTypeName = "google",
                            callbackFrom = 1
                        };
                        callBack?.Invoke(NeoriginSDKStatusCode.Success, "LoginH5 Google Success", user);
                        sdkWebView.CloseWebview();
                        return;
                    }

                    callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, "LoginH5 Google Fail " + args[1], null);
                    sdkWebView.CloseWebview();
                }
                else if (args[0] == "login_google_browser")
                {
                    // 处理登录逻辑
                    Debug.Log("LoginAccount: User logged in with account: " + args[1]);
                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    string message = (string)jsonObject["msg"];
                    if (errorCode == 0)
                    {
                        JObject dataObject = (JObject)jsonObject["data"];
                        string requestToken = dataObject["request_token"]?.ToString() ?? "";
                        Debug.Log("LoginAccount: User logged in with account requestToken: " + requestToken);
                        // 拉起浏览器，打开google授权
                        urlParameters += $"&google_client_id={platformGoogleClientId}";
                        string url = platformH5Url + "/" + platformH5PageGoogleLogin + urlParameters + $"&request_token={requestToken}";
                        Debug.Log("LoginAccount: User logged in with account url: " + url);
                        OpenBrowser(url);
                    }
                    //回调过程打点
                    processCallBack?.Invoke(args[0]);
                }
                else if (args[0] == "login_mail")
                {
                    // 处理登录邮箱成功逻辑
                    Debug.Log("LoginAccount: User logged in with account: " + args[1]);
                    //sdkWebView.CallJsFunc("mail login unity handle success");
                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    string message = (string)jsonObject["msg"];
                    if (errorCode == 0)
                    {
                        JObject dataObject = (JObject)jsonObject["data"];
                        LoginHandle(dataObject);
                        NeoriginSDKCallbackDataLoginAccount user = new NeoriginSDKCallbackDataLoginAccount
                        {
                            sdkUserID = dataObject["showName"].ToString(),
                            sdkUserName = dataObject["showName"].ToString(),
                            isNew = (int)dataObject["isNew"],
                            sdkLogUserId = dataObject["displayName"].ToString(),
                            sdkLogThirdUserName = dataObject["sdkLogThirdUserName"]?.ToString() ?? "",
                            thirdLoginType = 6,
                            thirdLoginTypeName = "mail",
                            callbackFrom = 1
                        };
                        callBack?.Invoke(NeoriginSDKStatusCode.Success, "Success", user);
                        sdkWebView.CloseWebview();
                        return;
                    }

                    callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, "LoginH5 Mail Fail " + args[1], null);
                    sdkWebView.CloseWebview();
                }
                else if (args[0] == "reg_mail")
                {
                    // 处理注册邮箱成功逻辑
                    Debug.Log("LoginAccount: User logged in with account: " + args[1]);
                    //sdkWebView.CallJsFunc("mail login unity handle success");

                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    string message = (string)jsonObject["msg"];
                    if (errorCode == 0)
                    {
                        JObject dataObject = (JObject)jsonObject["data"];
                        LoginHandle(dataObject);
                        NeoriginSDKCallbackDataLoginAccount user = new NeoriginSDKCallbackDataLoginAccount
                        {
                            sdkUserID = dataObject["showName"].ToString(),
                            sdkUserName = dataObject["showName"].ToString(),
                            isNew = (int)dataObject["isNew"],
                            sdkLogUserId = dataObject["displayName"].ToString(),
                            sdkLogThirdUserName = dataObject["sdkLogThirdUserName"]?.ToString() ?? "",
                            thirdLoginType = 6,
                            thirdLoginTypeName = "mail",
                            callbackFrom = 1
                        };
                        callBack?.Invoke(NeoriginSDKStatusCode.Success, "Success", user);
                        sdkWebView.CloseWebview();
                        return;
                    }

                    callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, "LoginH5 Mail Fail " + args[1], null);
                    sdkWebView.CloseWebview();

                }
                else if (args[0] == "reg_policy_entry")
                {
                    //注册协议访问
                    Debug.Log("LoginAccount: reg_policy_entry: " + args[1]);
                    //processCallBack?.Invoke(args[0]);
                    OpenPolicyBroswer();
                }
                else if (args[0] == "reg_policy_agree")
                {
                    //注册时同意协议弹窗
                    Debug.Log("LoginAccount: User agreed to policy: " + args[1]);
                    processCallBack?.Invoke(args[0]);

                }
                else if (args[0] == "change_password")
                {
                    //修改密码成功
                    Debug.Log("LoginAccount: User change password: " + args[1]);
                    processCallBack?.Invoke(args[0]);

                }
                else if (args[0] == "close_window")
                {
                    //关闭窗口
                    Debug.Log("LoginAccount: User closed the WebView." + args[1]);
                    callBack?.Invoke(NeoriginSDKStatusCode.WebViewUserCanceled, "User closed the login window.", null);
                    sdkWebView.CloseWebview();

                }
                else if (args[0] == "login_steam")
                {
                    // Steam登录 - 由Steam平台服务器处理
                    Debug.Log("LoginAccount: User wants to login with Steam: " + args[1]);
                    HandleSteamLoginFromH5(callBack, processCallBack, sdkWebView);
                }
                else
                {
                    Debug.Log("LogiLoginAccountnH5: Unknown action type: " + args[0]);
                    sdkWebView.CallJsFunc("unity handle error:Unknown action type");
                    //callBack?.Invoke(NeoriginSDKStatusCode.BadRequest, "Unknown action type " + args[0], null);
                }
            });
        }

        /// <summary>
        /// 处理从H5触发的Steam登录（子类可重写实现具体逻辑）
        /// </summary>
        protected virtual void HandleSteamLoginFromH5(NeoriginSDK.LoginAccountCallBack callBack, NeoriginSDK.LoginAccountProcessCallBack processCallBack, NeoriginSDKWebview webview = null)
        {
            Debug.LogWarning("HandleSteamLoginFromH5: Steam login not supported on this platform");
            callBack?.Invoke(NeoriginSDKStatusCode.BadRequest, "Steam login not supported on this platform", null);
        }

        /// <summary>
        /// 处理从H5触发的Steam绑定（子类可重写实现具体逻辑）
        /// </summary>
        protected virtual void HandleSteamBindFromH5(NeoriginSDK.OpenUserCenterCallBack callBack, NeoriginSDK.OpenUserCenterProcessCallBack processCallBack, NeoriginSDKWebview webview = null)
        {
            Debug.LogWarning("HandleSteamBindFromH5: Steam bind not supported on this platform");
            callBack?.Invoke(NeoriginSDKStatusCode.BadRequest, "Steam bind not supported on this platform", null);
        }

        public virtual void OpenUserCenter(NeoriginSDKCallbackDataUserInfo u8User, NeoriginSDKU8UserExtraData u8Role, NeoriginSDK.OpenUserCenterCallBack callBack, NeoriginSDK.OpenUserCenterProcessCallBack processCallBack = null)
        {
            //读取本地登录状态
            NeoriginSDKPlatformUserInfo user = NeoriginSDKStorage.LoadPlatformUserInfo();
            if (string.IsNullOrEmpty(user.token))
            {
                Debug.Log($"NeoriginPlatformServer OpenUserCenter user not login");
                callBack?.Invoke(code: NeoriginSDKStatusCode.PlatformUserNotLogin, msg: $"NeoriginPlatformServer OpenUserCenter user not login");
                return;
            }

            NeoriginSDKPlatformInitGameOtherCfg gameOtherConfig = NeoriginSDKStorage.LoadPlatformInitGameOtherCfg();
            string urlParameters = GetWebViewParameters();
            urlParameters += $"&aihelp_domain={platformAihelpDomain}";
            urlParameters += $"&aihelp_appid={platformAihelpAppId}";
            urlParameters += $"&aihelp_entryid={platformAihelpEntryId}";
            urlParameters += $"&aihelp_kfopen={gameOtherConfig.aihelp_config.kf_open}";
            //加入这俩条是否显示pgs
            if (NeoriginSDK.Instance.SDKConfig.platform.platformName == "mocogoogle")
            {
                urlParameters += $"&is_show_google_pgs={NeoriginSDK.Instance.SDKConfig.platform.platformName == "mocogoogle"}";
                urlParameters += $"&recall_session_id={GooglePlayData.instance.recall_session_id}";
            }

            string aihelpUserDataEncoded = GetAiHelpParams(u8User, u8Role);
            urlParameters += $"&aihelp_data={aihelpUserDataEncoded}";

            NeoriginSDKWebview sdkWebView = new NeoriginSDKWebview(
                onCloseListener: () =>
                {
                    // 用户关闭了WebView
                    Debug.Log("OpenUserCenter: User closed the WebView.");
                    processCallBack?.Invoke("ucenter_close");
                    //callBack?.Invoke(NeoriginSDKStatusCode.WebViewUserCanceled, "User closed the user center window.", null);
                }, isShowCloseBtn: false
            );
            sdkWebView.adjustmentProportion(0.82f, 0.82f);
            //sdkWebView.ShowWebView("https://login-test.topreels.com/googleauth.html");
            string h5File = platformH5PageUserCenter;
            string htmlPath = Path.Combine(Application.streamingAssetsPath, h5File);
            //string h5Url = "file://" + htmlPath;
            string h5Url = platformH5Url + "/" + h5File;
            Debug.Log("OpenUserCenter: open h5Url: " + h5Url + urlParameters);
            NeoriginSDKShowWebViewParams webviewParams = new NeoriginSDKShowWebViewParams
            {
                isDebug = platformIsDebug
            };
            sdkWebView.ShowWebView(h5Url + urlParameters, webviewParams, () =>
            {
                Debug.Log("OpenUserCenter loaded successfully");
            }, (args) =>
            {
                //判断参数是否正确
                if (args == null || args.Count < 2)
                {
                    Debug.Log("OpenUserCenter JS call arguments are invalid.");
                    sdkWebView.CallJsFunc("OpenUserCenter handle error:arguments are invalid");
                    return;
                }
                Debug.Log("OpenUserCenter JS call: " + args[0] + ", " + args[1]);

                //按args[0]的值判断登录类型，处理不同的业务逻辑
                if (args[0] == "ucenter_accountbind_click")
                {
                    Debug.Log("OpenUserCenter: ucenter_accountbind_click ");
                    processCallBack?.Invoke(args[0]);
                    //callBack?.Invoke(NeoriginSDKStatusCode.Success, "OpenUserCenter Success ", new NeoriginSDKCallbackDataLoginAccount());
                }
                else if (args[0] == "ucenter_accountchange_click")
                {
                    Debug.Log("OpenUserCenter: ucenter_accountchange_click ");
                    processCallBack?.Invoke(args[0]);
                    //callBack?.Invoke(NeoriginSDKStatusCode.Success, "OpenUserCenter Success ", new NeoriginSDKCallbackDataLoginAccount());
                }
                else if (args[0] == "ucenter_userservice_click")
                {
                    Debug.Log("OpenUserCenter: ucenter_userservice_click ");
                    processCallBack?.Invoke(args[0]);

                }
                else if (args[0] == "customer_service_click")
                {
                    Debug.Log("OpenUserCenter: customer_service_click ");
                    processCallBack?.Invoke(args[0]);

                }
                else if (args[0] == "switch_mail")
                {
                    Debug.Log("OpenUserCenter: switch_mail ");
                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    string message = (string)jsonObject["msg"];
                    if (errorCode == 0)
                    {
                        JObject dataObject = (JObject)jsonObject["data"];
                        LoginHandle(dataObject);
                        NeoriginSDKCallbackDataLoginAccount user = new NeoriginSDKCallbackDataLoginAccount
                        {
                            sdkUserID = dataObject["showName"].ToString(),
                            sdkUserName = dataObject["showName"].ToString(),
                            isNew = (int)dataObject["isNew"],
                            sdkLogUserId = dataObject["displayName"].ToString(),
                            sdkLogThirdUserName = dataObject["sdkLogThirdUserName"]?.ToString() ?? "",
                            thirdLoginType = 6,
                            thirdLoginTypeName = "mail",
                            callbackFrom = 2
                        };
                        callBack?.Invoke(NeoriginSDKStatusCode.Success, "OpenUserCenter Switch Mail Success", user);
                        sdkWebView.CloseWebview();
                        return;
                    }

                    //callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, "Switch Mail Fail ", null);
                    //sdkWebView.CloseWebview();

                }
                else if (args[0] == "reg_mail")
                {
                    // 处理注册邮箱成功逻辑
                    Debug.Log("OpenUserCenter: User logged in with account: " + args[1]);
                    //sdkWebView.CallJsFunc("mail login unity handle success");

                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    string message = (string)jsonObject["msg"];
                    if (errorCode == 0)
                    {
                        JObject dataObject = (JObject)jsonObject["data"];
                        LoginHandle(dataObject);
                        NeoriginSDKCallbackDataLoginAccount user = new NeoriginSDKCallbackDataLoginAccount
                        {
                            sdkUserID = dataObject["showName"].ToString(),
                            sdkUserName = dataObject["showName"].ToString(),
                            isNew = (int)dataObject["isNew"],
                            sdkLogUserId = dataObject["displayName"].ToString(),
                            sdkLogThirdUserName = dataObject["sdkLogThirdUserName"]?.ToString() ?? "",
                            thirdLoginType = 6,
                            thirdLoginTypeName = "mail",
                            callbackFrom = 2
                        };
                        callBack?.Invoke(NeoriginSDKStatusCode.Success, "Success", user);
                        sdkWebView.CloseWebview();
                        return;
                    }

                    callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, "OpenUserCenter reg Mail Fail " + args[1], null);
                    sdkWebView.CloseWebview();

                }
                else if (args[0] == "switch_google")
                {
                    Debug.Log("OpenUserCenter: switch_google ");
                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    string message = (string)jsonObject["msg"];
                    if (errorCode == 0)
                    {
                        JObject dataObject = (JObject)jsonObject["data"];
                        LoginHandle(dataObject);
                        NeoriginSDKCallbackDataLoginAccount user = new NeoriginSDKCallbackDataLoginAccount
                        {
                            sdkUserID = dataObject["showName"].ToString(),
                            sdkUserName = dataObject["showName"].ToString(),
                            isNew = (int)dataObject["isNew"],
                            sdkLogUserId = dataObject["displayName"].ToString(),
                            sdkLogThirdUserName = dataObject["sdkLogThirdUserName"]?.ToString() ?? "",
                            thirdLoginType = 6,
                            thirdLoginTypeName = "mail",
                            callbackFrom = 2
                        };
                        callBack?.Invoke(NeoriginSDKStatusCode.Success, "OpenUserCenter Switch Google Success", user);
                        sdkWebView.CloseWebview();
                        return;
                    }

                    //callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, "Switch Google Fail ", null);
                }
                else if (args[0] == "login_google_browser")
                {
                    // 处理登录逻辑
                    Debug.Log("LoginAccount: User switch_google with account: " + args[1]);
                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    string message = (string)jsonObject["msg"];
                    if (errorCode == 0)
                    {
                        JObject dataObject = (JObject)jsonObject["data"];
                        string requestToken = dataObject["request_token"]?.ToString() ?? "";
                        Debug.Log("LoginAccount: User switch_google with account requestToken: " + requestToken);
                        // 拉起浏览器，打开google授权
                        urlParameters += $"&google_client_id={platformGoogleClientId}&from_page=switch_google";
                        string url = platformH5Url + "/" + platformH5PageGoogleLogin + urlParameters + $"&request_token={requestToken}";
                        Debug.Log("LoginAccount: User switch_google with account url: " + url);
                        OpenBrowser(url);
                    }
                    //回调过程打点
                    processCallBack?.Invoke(args[0]);
                }
                else if (args[0] == "bind_mail")
                {
                    Debug.Log("OpenUserCenter: bind_mail ");
                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    string message = (string)jsonObject["msg"];
                    if (errorCode == 0)
                    {
                        JObject dataObject = (JObject)jsonObject["data"];
                        LoginHandle(dataObject);
                        NeoriginSDKCallbackDataLoginAccount user = new NeoriginSDKCallbackDataLoginAccount
                        {
                            sdkUserID = dataObject["showName"].ToString(),
                            sdkUserName = dataObject["showName"].ToString(),
                            isNew = 0,
                            sdkLogUserId = dataObject["displayName"].ToString(),
                            sdkLogThirdUserName = dataObject["sdkLogThirdUserName"]?.ToString() ?? "",
                            thirdLoginType = 6,
                            thirdLoginTypeName = "mail",
                            callbackFrom = 5
                        };
                        processCallBack?.Invoke(args[0], user);
                    }
                }
                else if (args[0] == "bind_google")
                {
                    Debug.Log("OpenUserCenter: bind_google ");
                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    string message = (string)jsonObject["msg"];
                    if (errorCode == 0)
                    {
                        JObject dataObject = (JObject)jsonObject["data"];
                        LoginHandle(dataObject);
                        NeoriginSDKCallbackDataLoginAccount user = new NeoriginSDKCallbackDataLoginAccount
                        {
                            sdkUserID = dataObject["showName"].ToString(),
                            sdkUserName = dataObject["showName"].ToString(),
                            isNew = 0,
                            sdkLogUserId = dataObject["displayName"].ToString(),
                            sdkLogThirdUserName = dataObject["sdkLogThirdUserName"]?.ToString() ?? "",
                            thirdLoginType = 1,
                            thirdLoginTypeName = "mail",
                            callbackFrom = 5
                        };
                        processCallBack?.Invoke(args[0], user);
                    }
                }
                else if (args[0] == "bind_google_browser")
                {
                    // 处理bind google逻辑
                    Debug.Log("LoginAccount: User bind google in with account: " + args[1]);
                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    string message = (string)jsonObject["msg"];
                    if (errorCode == 0)
                    {
                        JObject dataObject = (JObject)jsonObject["data"];
                        string requestToken = dataObject["request_token"]?.ToString() ?? "";
                        Debug.Log("LoginAccount: User bind google with account requestToken: " + requestToken);
                        // 拉起浏览器，打开google授权
                        urlParameters += $"&google_client_id={platformGoogleClientId}";
                        string url = platformH5Url + "/" + platformH5PageGoogleBind + urlParameters + $"&request_token={requestToken}&page=bind";
                        Debug.Log("LoginAccount: User bind google with account url: " + url);
                        OpenBrowser(url);
                    }
                    //回调过程打点
                    processCallBack?.Invoke(args[0]);
                }
                else if (args[0] == "bind_steam")
                {
                    // Steam绑定 - 由Steam平台服务器处理
                    Debug.Log("OpenUserCenter: bind_steam ");
                    HandleSteamBindFromH5(callBack, processCallBack, sdkWebView);
                }
                else if (args[0] == "ucenter_policy_entry")
                {
                    //用户中心协议点击
                    Debug.Log("OpenUserCenter: ucenter_policy_entry: " + args[1]);
                    processCallBack?.Invoke(args[0]);
                    OpenPolicyBroswer();
                }
                else if (args[0] == "reg_policy_entry")
                {
                    //注册协议访问
                    Debug.Log("OpenUserCenter: reg_policy_entry: " + args[1]);
                    //processCallBack?.Invoke(args[0]);
                    OpenPolicyBroswer();
                }
                else if (args[0] == "reg_policy_agree")
                {
                    //注册时同意协议弹窗
                    Debug.Log("OpenUserCenter: User agreed to policy: " + args[1]);
                    processCallBack?.Invoke(args[0]);

                }
                else if (args[0] == "close_window")
                {
                    //关闭窗口
                    Debug.Log("OpenUserCenter: User closed the WebView.");
                    processCallBack?.Invoke("ucenter_close");
                    sdkWebView.CloseWebview();

                }
                else
                {
                    Debug.Log("OpenUserCenter: Unknown action type: " + args[0]);
                    sdkWebView.CallJsFunc("OpenUserCenter unity handle error:Unknown action type");
                    //callBack?.Invoke(NeoriginSDKStatusCode.BadRequest, "Unknown action type " + args[0], new NeoriginSDKCallbackDataLoginAccount());
                }
            });
        }

        protected string GetAiHelpParams(NeoriginSDKCallbackDataUserInfo u8User, NeoriginSDKU8UserExtraData u8Role)
        {
            string lang = GetLocalLanuageAiHelp();
            string userTags = PlatformAiHelpPlatformTag + $",{lang}";
            if (!string.IsNullOrEmpty(u8Role.vip))
            {
                userTags += $",vip{u8Role.vip}";
            }
            if (!string.IsNullOrEmpty(u8Role.serverName))
            {
                userTags += $",Area_{u8Role.serverName}";
            }
            Debug.Log("GetAiHelpParams userTags: " + userTags);
            NeoriginSDKPlatformAihelpParameter aihelpUserData = new NeoriginSDKPlatformAihelpParameter
            {
                userId = u8Role.roleID ?? "",
                userName = u8Role.roleName ?? "",
                serverId = u8Role.serverID ?? "",
                userTags = userTags,
                LastPayTime = u8User.lastChargeTime ?? ""
            };
            // 转换为 JSON 字符串
            string aihelpUserDataJson = JsonUtility.ToJson(aihelpUserData);
            Debug.Log("aihelpUserDataJson Data: " + aihelpUserDataJson);
            // URL 编码
            string aihelpUserDataEncoded = System.Uri.EscapeDataString(aihelpUserDataJson);
            Debug.Log("aihelpUserDataEncoded Data: " + aihelpUserDataEncoded);

            return aihelpUserDataEncoded;
        }

        public virtual void OpenCustomerService(NeoriginSDKCallbackDataUserInfo u8User, NeoriginSDKU8UserExtraData u8Role, NeoriginSDK.OpenCustomerServiceCallBack callBack)
        {
            //读取本地登录状态
            string urlParameters = GetWebViewParameters();
            urlParameters += $"&aihelp_domain={platformAihelpDomain}";
            urlParameters += $"&aihelp_appid={platformAihelpAppId}";
            urlParameters += $"&aihelp_entryid={platformAihelpEntryId}";

            string aihelpUserDataEncoded = GetAiHelpParams(u8User, u8Role);
            urlParameters += $"&aihelp_data={aihelpUserDataEncoded}";
            WinProcessHelper.StartDialogForegroundAssist();

            NeoriginSDKWebview sdkWebView = new NeoriginSDKWebview(
                onCloseListener: () =>
                {
                    // 用户关闭了WebView
                    Debug.Log("OpenCustomerService: User closed the WebView.");
                    WinProcessHelper.StopDialogForegroundAssist();
                }, isShowCloseBtn: false
            );
            sdkWebView.adjustmentProportion(0.82f, 0.82f);
            //sdkWebView.ShowWebView("https://login-test.topreels.com/googleauth.html");
            string h5File = platformH5PageKefu;
            string htmlPath = Path.Combine(Application.streamingAssetsPath, h5File);
            //string h5Url = "file://" + htmlPath;
            string h5Url = platformH5Url + "/" + h5File + urlParameters;
            NeoriginSDKShowWebViewParams webviewParams = new NeoriginSDKShowWebViewParams
            {
                isDebug = platformIsDebug
            };
            sdkWebView.ShowWebView(h5Url, webviewParams, () =>
            {
                Debug.Log("OpenCustomerService loaded successfully");
            }, (args) =>
            {
                //判断参数是否正确
                if (args == null || args.Count < 2)
                {
                    Debug.Log("OpenCustomerService JS call arguments are invalid.");
                    sdkWebView.CallJsFunc("OpenCustomerService handle error:arguments are invalid");
                    return;
                }
                Debug.Log("OpenCustomerService JS call: " + args[0] + ", " + args[1]);

                //按args[0]的值判断登录类型，处理不同的业务逻辑
                if (args[0] == "customer_service_click")
                {
                    Debug.Log("OpenCustomerService: customer_service_click ");
                    callBack?.Invoke(NeoriginSDKStatusCode.Success, "OpenCustomerService Success ");
                } else if (args[0] == "close_window")
                {
                    //关闭窗口
                    Debug.Log("OpenCustomerService: User closed the WebView.");
                    WinProcessHelper.StopDialogForegroundAssist();
                    sdkWebView.CloseWebview();

                }
                else
                {
                    Debug.Log("OpenCustomerService: Unknown action type: " + args[0]);
                    sdkWebView.CallJsFunc("OpenCustomerService unity handle error:Unknown action type");
                    callBack?.Invoke(NeoriginSDKStatusCode.BadRequest, "Unknown action type " + args[0]);
                }
            });
        }

        public virtual void OpenPolicy(NeoriginSDK.OpenPolicyCallBack callBack)
        {
            string policyUrl = GetPolicyUrl("user_policy");
            Debug.Log("OpenPolicy: policy_url:" + policyUrl);
            NeoriginSDKWebview sdkWebView = new NeoriginSDKWebview(
                onCloseListener: () =>
                {
                    // 用户关闭了WebView
                    Debug.Log("OpenPolicy: User closed the WebView.");
                }, isShowCloseBtn: false
            );
            sdkWebView.adjustmentProportion(0.82f, 0.82f);
            sdkWebView.jsCodeSet("document.body.style.background = 'white'"); //设置背景色为白色
                                                                              //sdkWebView.ShowWebView("https://login-test.topreels.com/googleauth.html");
                                                                              //string htmlPath = Path.Combine(Application.streamingAssetsPath, "aihelp.html");
            NeoriginSDKShowWebViewParams webviewParams = new NeoriginSDKShowWebViewParams
            {
                isDebug = platformIsDebug
            };
            sdkWebView.ShowWebView(policyUrl, webviewParams, () =>
            {
                Debug.Log("OpenPolicy loaded successfully");
                callBack?.Invoke(NeoriginSDKStatusCode.Success, "OpenPolicy Success ");

            }, (args) =>
            {
            });
        }

        protected void OpenPolicyBroswer(NeoriginSDK.OpenPolicyCallBack callBack = null)
        {
            string policyUrl = GetPolicyUrl("user_policy");
            Debug.Log("OpenPolicyBroswer: policy_url:" + policyUrl);
            OpenBrowser(policyUrl);
            callBack?.Invoke(NeoriginSDKStatusCode.Success, "OpenPolicyBroswer Success ");
        }

        private string GetLocalLanuageAiHelp()
        {
            NeoriginSDKDevice deviceCfg = NeoriginSDKStorage.LoadDevice();
            string userLang = "Language_en";
            switch (deviceCfg.deviceLang)
            {
                case SystemLanguage.ChineseSimplified:
                    userLang = "Language_zhcn";
                    break;
                case SystemLanguage.ChineseTraditional:
                    userLang = "Language_zhtw";
                    break;
                case SystemLanguage.Japanese:
                    userLang = "Language_ja";
                    break;
                case SystemLanguage.Korean:
                    userLang = "Language_ko";
                    break;
                default:
                    userLang = "Language_en";
                    break;
            }
            return userLang;
        }

        private string GetLocalLanuageXsolla()
        {
            NeoriginSDKDevice deviceCfg = NeoriginSDKStorage.LoadDevice();
            string userLang = "en";
            switch (deviceCfg.deviceLang)
            {
                case SystemLanguage.ChineseSimplified:
                    userLang = "cn";
                    break;
                case SystemLanguage.ChineseTraditional:
                    userLang = "tw";
                    break;
                case SystemLanguage.Japanese:
                    userLang = "ja";
                    break;
                case SystemLanguage.Korean:
                    userLang = "ko";
                    break;
                default:
                    userLang = "en";
                    break;
            }
            Debug.Log("GetLocalLanuageXsolla:" + userLang + " # origin:" + deviceCfg.deviceLang.ToString());
            return userLang;
        }

        private string GetPolicyUrl(string policyType)
        {
            NeoriginSDKPlatformInitGameOtherCfg gameOtherConfig = NeoriginSDKStorage.LoadPlatformInitGameOtherCfg();

            string userLang = NeoLanguageUtils.GetLocalLanuage();

            string policyUrl = "";
            string originalUrl = "";
            if (policyType == "user_policy")
            {
                originalUrl = gameOtherConfig.user_policy;
            }
            else if (policyType == "privacy_policy")
            {
                originalUrl = gameOtherConfig.privacy_agreement_url;
            }
            else if (policyType == "delete_policy")
            {
                originalUrl = gameOtherConfig.delete_user_policy;
            }
            else
            {
                Debug.Log("GetPolicyUrl: Unknown policy type: " + policyType);
                return policyUrl;
            }

            if (originalUrl == "")
            {
                Debug.Log("GetPolicyUrl: No policy url found for type: " + policyType);
                return policyUrl;
            }
            // 移除末尾的 .html
            string baseUrl = originalUrl.Substring(0, originalUrl.LastIndexOf(".html"));
            policyUrl = $"{baseUrl}/{userLang.ToUpper()}.html";

            return policyUrl;
        }

        protected string GetWebViewParameters()
        {
            //读取本地登录状态
            NeoriginSDKPlatformUserInfo userInfo = NeoriginSDKStorage.LoadPlatformUserInfo();
            string urlParameters = $"?uuid={userInfo.uuid}&token={userInfo.token}&time={System.DateTimeOffset.UtcNow.ToUnixTimeSeconds()}&sign=dskfaskiowqhksadnjkasdfkasjdfkasdf"; // 示例签名，实际应使用正确的签名逻辑
            foreach (var kvp in NeoriginSDK.Instance.PublicParams)
            {
                urlParameters += $"&{kvp.Key}={UnityWebRequest.EscapeURL(kvp.Value)}";
            }

            //string sdkLangCode = GetLocalLanuage();
            //urlParameters += $"&lang_code={sdkLangCode}";

            return urlParameters;
        }

        private void OpenBrowser(string url)
        {
            //OpenDesktopBrowser(url);
            //Application.OpenURL(url);
            try
            {
                Debug.Log("OpenBrowser try : " + url);
                Application.OpenURL(url);
                Debug.Log("OpenBrowser try end: ");
            }
            catch (System.Exception e)
            {
                Debug.Log("OpenBrowser catch : " + url);
                Debug.Log("OpenBrowser catch : " + e.Message);
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = url,
                    UseShellExecute = true
                });
                Debug.Log("OpenBrowser catch end: ");
            }
        }

        // 桌面平台实现
        private void OpenDesktopBrowser(string url)
        {
#if UNITY_STANDALONE_WIN
            // Windows
            SysProcess.Start(new SysProcessStartInfo {
                FileName = url, // 关键：直接使用URL作为文件名
                UseShellExecute = true, // 使用系统Shell执行
                Verb = "open" // 指定"打开"操作
            });
#endif
        }

        // 发送GET请求
        protected void GetRequest(string endpoint, System.Action<UnityWebRequest> callback)
        {
            string fullUrl = CombineUrl(baseUrl, endpoint);
            Debug.Log("NeoriginPlatformServer GetRequest url:" + fullUrl);
            EnsureCoroutineMonoBehaviour().StartCoroutine(WebRequestCoroutine(fullUrl, UnityWebRequest.kHttpVerbGET, null, callback));
        }

        // 发送POST请求
        protected void PostRequest(string endpoint, WWWForm formData, System.Action<UnityWebRequest> callback)
        {
            string fullUrl = CombineUrl(baseUrl, endpoint);
            Debug.Log("NeoriginPlatformServer PostRequest url:" + fullUrl);
            EnsureCoroutineMonoBehaviour().StartCoroutine(WebRequestCoroutine(fullUrl, UnityWebRequest.kHttpVerbPOST, formData, callback));
        }

        private string CombineUrl(string baseUrl, string endpoint)
        {
            return $"{baseUrl.TrimEnd('/')}/{endpoint.TrimStart('/')}";
        }

        private IEnumerator WebRequestCoroutine(string url, string method, WWWForm formData, System.Action<UnityWebRequest> callback)
        {
            using (UnityWebRequest webRequest = new UnityWebRequest(url, method))
            {
                if (formData != null && method == UnityWebRequest.kHttpVerbPOST)
                {
                    webRequest.uploadHandler = new UploadHandlerRaw(formData.data);
                    webRequest.downloadHandler = new DownloadHandlerBuffer();
                    webRequest.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                }
                else if (method == UnityWebRequest.kHttpVerbGET)
                {
                    webRequest.downloadHandler = new DownloadHandlerBuffer();
                }

                yield return webRequest.SendWebRequest();
                callback?.Invoke(webRequest);
            }
        }

        protected string getMd5Value(string sign)
        {

            // 计算 MD5 哈希
            using (MD5 md5Hash = MD5.Create())
            {
                // 将输入字符串转换为字节数组并计算哈希
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(sign));

                // 创建一个新的 Stringbuilder 来收集字节并创建字符串
                StringBuilder sBuilder = new StringBuilder();

                // 遍历每个字节的数据并格式化为十六进制字符串
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }

                // 返回十六进制字符串
                string md5HashString = sBuilder.ToString();

                // md5HashString 即为 MD5 加密后的字符串
                return md5HashString;
            }

        }

        protected string getSignStr(Dictionary<string, string> parameters, string signKey = "")
        {
            Dictionary<string, string> newParams = new Dictionary<string, string>(NeoriginSDK.Instance.PublicParams);
            // 添加传入的参数
            if (parameters != null && parameters.Count > 0)
            {
                foreach (var kvp in parameters)
                {
                    newParams[kvp.Key] = kvp.Value;
                }
            }

            // 按照键排序参数
            var sortedKeys = newParams.OrderBy(kvp => kvp.Key);

            // 拼接所有参数值
            StringBuilder realSignBuilder = new StringBuilder();
            foreach (var kvp in sortedKeys)
            {
                realSignBuilder.Append(kvp.Value);
            }
            string realSign = realSignBuilder.ToString() + platformAPPKey;
            if (!string.IsNullOrEmpty(signKey))
            {
                realSign = realSignBuilder.ToString() + platformAppSecret;
            }

            return realSign;
        }
        // 初始化请求
        protected void Init(System.Action<UnityWebRequest> callback)
        {
            Debug.Log("Init #######:");
            WWWForm formData = new WWWForm();

            string time = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            // 添加公共参数
            Dictionary<string, string> reqParams = new Dictionary<string, string>
            {
                { "time", time }
            };
            // 构建签名字符串
            string signStr = getSignStr(reqParams);
            Debug.Log("Init signStr " + signStr);
            string sign = getMd5Value(signStr);
            // 构建请求数据

            formData.AddField("time", time);
            formData.AddField("sign", sign);
            foreach (var kvp in NeoriginSDK.Instance.PublicParams)
            {
                formData.AddField(kvp.Key, kvp.Value);
            }
            // 发送POST请求
            //PostRequest("login/pc/hwinits", formData, callback);
            PostRequest("login/pc/hwinits", formData, callback);
        }

        // 设置初始化响应数据
        protected void InitHandle(JObject data)
        {
            Debug.Log("InitCallback #######:");

            platformInitRepData = data;

            //游戏配置
            if (data["game_cfg"] is JObject gameCfg)
            {
                Debug.Log("===== 游戏配置 =====");
                Debug.Log($"InitCallback游戏名称: {NeoStringUtils.GetStringValue(gameCfg, "game_name")}");
                Debug.Log($"InitCallback支付方式: {NeoStringUtils.GetStringValue(gameCfg, "hw_pay_way")}");
                Debug.Log($"InitCallback时间戳: {NeoStringUtils.GetLongValue(gameCfg, "current_timestamp")}");
                NeoriginSDK.Instance.PublicParams["sdk_game_name"] = NeoStringUtils.GetStringValue(gameCfg, "game_name");

                // 时间戳转换
                long timestamp = NeoStringUtils.GetLongValue(gameCfg, "current_timestamp", 0);
                System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc)
                    .AddMilliseconds(timestamp)
                    .ToLocalTime();
                Debug.Log($"InitCallback时间: {dateTime.ToString("yyyy-MM-dd HH:mm:ss")}");

                NeoriginSDKPlatformInitGameCfg gameConfig = new NeoriginSDKPlatformInitGameCfg
                {
                    game_name = NeoStringUtils.GetStringValue(gameCfg, "game_name"),
                    hw_pay_way = NeoStringUtils.GetStringValue(gameCfg, "hw_pay_way"),
                    hw_pay_way_type = NeoStringUtils.GetStringValue(gameCfg, "hw_pay_way_type"),
                    company_entity = NeoStringUtils.GetStringValue(gameCfg, "company_entity"),
                    current_timestamp = NeoStringUtils.GetLongValue(gameCfg, "current_timestamp", 0)
                };
                NeoriginSDKStorage.SavePlatformInitGameCfg(gameConfig);
            }
            else
            {
                Debug.LogWarning("InitHandle未找到game_cfg配置");
            }
            //其他配置
            if (data["game_other_cfg"] is JObject gameOtherCfg)
            {
                List<NeoriginSDKPlatformInitGameOtherCfgThirdLogin> loginList = new List<NeoriginSDKPlatformInitGameOtherCfgThirdLogin>();

                JArray thirdLoginArray = (JArray)gameOtherCfg["third_login"];
                List<NeoriginSDKPlatformInitGameOtherCfgThirdLogin> thirdLoginItems = thirdLoginArray.ToObject<List<NeoriginSDKPlatformInitGameOtherCfgThirdLogin>>();
                foreach (var item in thirdLoginItems)
                {
                    loginList.Add(new NeoriginSDKPlatformInitGameOtherCfgThirdLogin
                    {
                        provider = item.provider,
                        appid = item.appid,
                        open = item.open,
                        type = item.type,
                    });
                }
                Dictionary<string, string> eventTokenDict = new Dictionary<string, string>();
                if (gameOtherCfg["event_token"] != null)
                {
                    try
                    {
                        eventTokenDict = gameOtherCfg["event_token"].ToObject<Dictionary<string, string>>();
                    }
                    catch (JsonSerializationException)
                    {
                        // 如果解析失败（比如是 []），则保持空字典
                    }
                }
                NeoriginSDKPlatformInitAihelp aihelpConfig = new NeoriginSDKPlatformInitAihelp();
                if (gameOtherCfg["aihelp_config"] != null)
                {
                    try
                    {
                        aihelpConfig = gameOtherCfg["aihelp_config"].ToObject<NeoriginSDKPlatformInitAihelp>();
                    }
                    catch (JsonSerializationException)
                    {
                        // 如果解析失败（比如是 []），则保持空字典

                    }
                }
                NeoriginSDKPlatformPayConfig payConfig = new NeoriginSDKPlatformPayConfig();
                if (gameOtherCfg["pay_config"] != null)
                {
                    try
                    {
                        payConfig = gameOtherCfg["pay_config"].ToObject<NeoriginSDKPlatformPayConfig>();
                    }
                    catch (JsonSerializationException)
                    {
                        // 如果解析失败（比如是 []），则保持空字典

                    }
                }
                NeoriginSDKPlatformInitGameOtherCfg gameOtherConfig = new NeoriginSDKPlatformInitGameOtherCfg
                {
                    third_login = loginList.ToArray(),
                    user_policy = NeoStringUtils.GetStringValue(gameOtherCfg, "user_policy"),
                    delete_user_policy = NeoStringUtils.GetStringValue(gameOtherCfg, "delete_user_policy"),
                    privacy_agreement_url = NeoStringUtils.GetStringValue(gameOtherCfg, "privacy_agreement_url"),
                    user_policy_open = NeoStringUtils.GetStringValue(gameOtherCfg, "user_policy_open"),
                    delete_open = NeoStringUtils.GetStringValue(gameOtherCfg, "delete_open"),
                    ironsource_server_callback_open = NeoStringUtils.GetIntValue(gameOtherCfg, "ironsource_server_callback_open", 0),
                    pic_code_open = NeoStringUtils.GetIntValue(gameOtherCfg, "pic_code_open", 0),
                    pic_verify_url = NeoStringUtils.GetStringValue(gameOtherCfg, "pic_verify_url"),
                    pic_platform_id = NeoStringUtils.GetStringValue(gameOtherCfg, "pic_platform_id"),
                    login_display = NeoStringUtils.GetStringValue(gameOtherCfg, "login_display"),
                    default_lang = NeoStringUtils.GetStringValue(gameOtherCfg, "default_lang"),
                    aihelp_config = aihelpConfig,
                    event_token = eventTokenDict,
                    pay_config = payConfig
                };

                NeoriginSDKStorage.SavePlatformInitGameOtherCfg(gameOtherConfig);
            }
            else
            {
                Debug.LogWarning("InitHandle未找到game_other_cfg配置");
            }

            //游戏商品
            if (data["game_product"] is JArray productArray)
            {
                List<NeoriginSDKPlatformInitGameProduct> productList = productArray.Select(p => new NeoriginSDKPlatformInitGameProduct
                {
                    product_id = (string)p["product_id"],
                    money = (string)p["money"],
                    product_name = (string)p["product_name"],
                    product_type = (string)p["product_type"]
                }).ToList();
                NeoriginSDKPlatformInitGameProductList productLists = new NeoriginSDKPlatformInitGameProductList
                {
                    items = productList.ToArray()
                };
                /*Debug.Log("InitHandle game_product count: " + productList.Count);
                foreach (var product in productList)
                {
                    Debug.Log($"InitHandle商品ID: {product.product_id}, 金额: {product.money}, 名称: {product.product_name}, 类型: {product.product_type}");
                }*/
                NeoriginSDKStorage.SavePlatformInitGameProduct(productLists);
                /*NeoriginSDKPlatformInitGameProductList a = NeoriginSDKStorage.loadPlatformInitGameProduct(); // 确保数据已保存
                Debug.Log("InitHandle load game_product count: " + a.items.Length);
                foreach (var product in a.items)
                {
                    Debug.Log($"InitHandle load 商品ID: {product.product_id}, 金额: {product.money}, 名称: {product.product_name}, 类型: {product.product_type}");
                }*/
            }
            else
            {
                Debug.LogWarning("InitHandle未找到game_product配置");
            }
        }

        // 游客登录请求
        protected void LoginTourist(string userAccount, System.Action<UnityWebRequest> callback)
        {
            Debug.Log("NeoriginPlatformServer LoginTourist #######:");
            WWWForm formData = new WWWForm();

            string time = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            // 添加公共参数
            Dictionary<string, string> reqParams = new Dictionary<string, string>
            {
                { "time", time }
            };
            // 构建签名字符串
            string signStr = getSignStr(reqParams);
            //Debug.Log("NeoriginPlatformServer LoginTourist signStr " + signStr);
            string sign = getMd5Value(signStr);
            // 构建请求数据

            formData.AddField("time", time);
            formData.AddField("sign", sign);
            foreach (var kvp in NeoriginSDK.Instance.PublicParams)
            {
                Debug.Log("NeoriginPlatformServer LoginTourist formData: " + kvp.Key + " = " + kvp.Value);
                formData.AddField(kvp.Key, kvp.Value);
            }
            // 发送POST请求
            PostRequest("v1.4.1/login/hwStandAlone", formData, callback);
            //GetRequest("login/android/hwinits", callback);
        }

        // 游客登录请求
        private void LoginToken(string uuid, string token, System.Action<UnityWebRequest> callback)
        {
            Debug.Log("NeoriginPlatformServer LoginToken #######:");
            WWWForm formData = new WWWForm();

            string time = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            // 添加公共参数
            Dictionary<string, string> reqParams = new Dictionary<string, string>
            {
                { "time", time },
                { "uuid", uuid },
                { "token", token }
            };
            // 构建签名字符串
            string signStr = getSignStr(reqParams);
            //Debug.Log("NeoriginPlatformServer LoginTourist signStr " + signStr);
            string sign = getMd5Value(signStr);
            // 构建请求数据

            formData.AddField("time", time);
            formData.AddField("sign", sign);
            formData.AddField("uuid", uuid);
            formData.AddField("token", token);
            foreach (var kvp in NeoriginSDK.Instance.PublicParams)
            {
                //Debug.Log("NeoriginPlatformServer LoginToken formData: " + kvp.Key + " = " + kvp.Value);
                formData.AddField(kvp.Key, kvp.Value);
            }
            // 发送POST请求
            PostRequest("v1.4.1/login/hw", formData, callback);
            //GetRequest("login/android/hwinits", callback);
        }

        //平台登录请求后的处理逻辑
        protected void PlatformLoginRequestHandle(string loginType, UnityWebRequest response, NeoriginSDK.LoginCallBack loginHandleCallback)
        {
            if (response.isNetworkError || response.isHttpError)
            {
                // 处理错误
                Debug.Log($"NeoriginPlatformServer {loginType} Error: {response.error},code {response.responseCode}");
                loginHandleCallback?.Invoke(NeoriginSDKStatusCode.BadRequest, $"Platform {loginType} request error.code:{response.responseCode},Error:{response.error}", null);
                return;
            }
            else
            {
                // 成功接收到响应
                string responseData = response.downloadHandler.text;  // 文本信息
                Debug.Log($"NeoriginPlatformServer {loginType} Received: {responseData}");
                JObject rep = JObject.Parse(responseData);
                int errorCode = (int)rep["error"];
                string message = (string)rep["msg"];
                Debug.Log($"NeoriginPlatformServer {loginType} rep: {errorCode} # {message}");
                if (errorCode != 0)
                {
                    if (loginType == "LoginToken")
                    {
                        //token登录失败，清除本地登录状态
                        NeoriginSDKStorage.DeletePlatformUserInfo();
                    }
                    Debug.Log($"NeoriginPlatformServer {loginType} Error: {message}");
                    loginHandleCallback?.Invoke(NeoriginSDKStatusCode.InternalError, $"Platform {loginType} return error.code:{errorCode},message:{message}", null);
                    return;
                }
                //保存返回数据
                JObject repData = (JObject)rep["data"];

                //处理平台用户数据
                LoginHandle(repData);

                // 调用回调函数
                NeoriginSDKCallbackDataLogin resultData = new NeoriginSDKCallbackDataLogin
                {
                    sdkUserID = (string)repData["showName"],
                    thirdLoginType = ((int)repData["third_login_type"]),
                    sdkLogUserId = (string)repData["displayName"]
                };
                loginHandleCallback?.Invoke(NeoriginSDKStatusCode.Success, $"Platform login Success.", resultData);

            }
        }

        // 处理登录响应数据
        protected void LoginHandle(JObject data)
        {
            JArray thirdLoginArray = (JArray)data["bind_third_login_type"];
            List<int> thirdLogin = thirdLoginArray.ToObject<List<int>>();
            Dictionary<string, string> thirdLoginDetail = new Dictionary<string, string>();
            if (data["bind_third_login_type_detail"] != null)
            {
                try
                {
                    thirdLoginDetail = data["bind_third_login_type_detail"].ToObject<Dictionary<string, string>>();
                }
                catch (JsonSerializationException)
                {
                    // 如果解析失败（比如是 []），则保持空字典
                }
            }

            NeoriginSDKPlatformUserInfo platformUserInfo = new NeoriginSDKPlatformUserInfo
            {
                uuid = NeoStringUtils.GetStringValue(data, "uuid"),
                token = NeoStringUtils.GetStringValue(data, "token"),
                expireTime = NeoStringUtils.GetStringValue(data, "expireTime"),
                showName = NeoStringUtils.GetStringValue(data, "showName"),
                displayName = NeoStringUtils.GetStringValue(data, "displayName"),
                isNew = NeoStringUtils.GetIntValue(data, "isNew", 0),
                third_login_type = NeoStringUtils.GetIntValue(data, "third_login_type", 0),
                third_identifier = NeoStringUtils.GetStringValue(data, "third_identifier"),
                suspendTime = NeoStringUtils.GetStringValue(data, "suspendTime"),
                suspendReason = NeoStringUtils.GetStringValue(data, "suspendReason"),
                note = NeoStringUtils.GetStringValue(data, "note"),
                delete_status = NeoStringUtils.GetIntValue(data, "delete_status", 0),
                delete_time = NeoStringUtils.GetIntValue(data, "delete_time", 0),
                bind_third_login_type = thirdLogin,
                bind_third_login_type_detail = thirdLoginDetail
            };
            //存入缓存
            //NeoriginSDKPlatformUserInfo platformUserInfo = data.ToObject<NeoriginSDKPlatformUserInfo>();
            NeoriginSDKStorage.SavePlatformUserInfo(platformUserInfo);
        }

        // 安全获取字符串值


        //支付
        public virtual void Pay(NeoriginSDKPlatformPayParameter payParams, NeoriginSDK.PayCallBack callBack, NeoriginSDK.PayProcessCallBack payProcessCallBack = null)
        {
            Debug.Log("NeoriginPlatformServer Pay #######:");
            NeoriginSDKPlatformUserInfo user = NeoriginSDKStorage.LoadPlatformUserInfo();
            if (string.IsNullOrEmpty(user.token))
            {
                Debug.Log($"NeoriginPlatformServer Pay user not login");
                callBack?.Invoke(code: NeoriginSDKStatusCode.PlatformUserNotLogin, msg: $"NeoriginPlatformServer Pay user not login");
                return;
            }

            // 补充公共参数
            NeoriginSDK.Instance.PublicParams["server_id"] = payParams.server_id;

            var interPayParams = new InterPayParams()  // 创建内部支付参数
            {
                gameOrderId = payParams.game_order_id,
                serverId = payParams.server_id,
                roleId = payParams.role_id,
                roleName = payParams.role_name,
                productDesc = payParams.desc,
                productId = payParams.product_id,
                extra = payParams.extra,
                orderMoney = payParams.order_money,
                payChannel = NeoPayFactory.PlatformPayXsolla
            };

            var gameOtherConfig = NeoriginSDKStorage.LoadPlatformInitGameOtherCfg();
            var payChannelIds = gameOtherConfig.pay_config.pay_channel_ids;
            bool hasVirtualCoinPay = payChannelIds.Contains(int.Parse(NeoPayFactory.PlatformPayVirtualCoin));
            List<int> thirdPayChannels = new List<int>();
            foreach (int channelId in payChannelIds)
            {
                if (channelId == int.Parse(NeoPayFactory.PlatformPayVirtualCoin))
                {
                    continue;
                }
                if (!thirdPayChannels.Contains(channelId))
                {
                    thirdPayChannels.Add(channelId);
                }
            }

            // 与移动端保持一致：优先按“当前真实支付渠道”直接支付；仅在虚拟币可用时显示支付选择面板
            string currentThirdChannel = NeoPayFactory.PlatformPayXsolla;
            if (!string.IsNullOrEmpty(payParams.pay_channel_id) &&
                payParams.pay_channel_id != NeoPayFactory.PlatformPayVirtualCoin &&
                NeoPayFactory.payChannelSupport(payChannelIds, payParams.pay_channel_id))
            {
                currentThirdChannel = payParams.pay_channel_id;
            }
            else if (thirdPayChannels.Count > 0)
            {
                currentThirdChannel = thirdPayChannels[0].ToString();
            }

            // 无虚拟币渠道：直接拉起真实支付
            if (!hasVirtualCoinPay)
            {
                interPayParams.payChannel = currentThirdChannel;
                ThirdPay(interPayParams, callBack, payProcessCallBack);
                return;
            }

            // 有虚拟币渠道：先检查虚拟币，充足显示H5，不足直接真实支付
            NeoBasePay.CheckVirtualCoin(payParams.product_id, data =>
            {
                bool virtualCoinAvailable = data.productVirtualCoin > 0 && data.virtualCoinNum >= data.productVirtualCoin && data.isEnough == 1;
                if (virtualCoinAvailable)
                {
                    ShowH5PayView(interPayParams, data, callBack, payProcessCallBack);
                }
                else
                {
                    interPayParams.payChannel = currentThirdChannel;
                    ThirdPay(interPayParams, callBack, payProcessCallBack);
                }
            });
        }

        //获取用户信息
        public virtual void GetUserInfo(NeoriginSDK.GetUserInfoCallBack callBack)
        {
            Debug.Log("NeoriginPlatformServer Pay #######:");
            NeoriginSDKPlatformUserInfo user = NeoriginSDKStorage.LoadPlatformUserInfo();
            if (string.IsNullOrEmpty(user.token))
            {
                Debug.Log($"NeoriginPlatformServer Pay user not login");
                callBack?.Invoke(code: NeoriginSDKStatusCode.PlatformUserNotLogin, msg: $"NeoriginPlatformServer Pay user not login");
                return;
            }

            string resultTime = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            Dictionary<string, string> resultParams = new Dictionary<string, string>
            {
                { "uuid", user.uuid },
                { "token", user.token },
                { "time", resultTime }
            };
            GetUserInfoRequest(resultParams, (response) =>
            {
                if (response.isNetworkError || response.isHttpError)
                {
                    // 处理错误
                    Debug.Log($"NeoriginPlatformServer GetUserInfoRequest Error: {response.error},code {response.responseCode}");
                    callBack?.Invoke(code: NeoriginSDKStatusCode.BadRequest, msg: $"Platform request error.code:{response.responseCode},Error:{response.error}");
                    return;
                }
                else
                {
                    // 成功接收到响应
                    string responseData = response.downloadHandler.text;  // 文本信息
                    Debug.Log($"NeoriginPlatformServer GetUserInfoRequest Received: {responseData}");
                    //dynamic rep = JsonConvert.DeserializeObject(responseData);//JsonUtility.FromJson<NeoriginSDKBaseResponse>(responseData);
                    // 解析整个JSON
                    JObject rep = JObject.Parse(responseData);
                    int errorCode = (int)rep["error"];
                    string message = (string)rep["msg"];
                    Debug.Log($"NeoriginPlatformServer GetUserInfoRequest rep: {errorCode} # {message}");
                    if (errorCode != 0)
                    {
                        Debug.Log($"NeoriginPlatformServer GetUserInfoRequest Error: {message}");
                        callBack?.Invoke(code: NeoriginSDKStatusCode.InternalError, msg: $"Platform return error.code:{errorCode},message:{message}");
                        return;
                    }
                    //保存返回数据
                    JObject repData = (JObject)rep["data"];
                    NeoriginSDKCallbackDataUserInfo userData = new NeoriginSDKCallbackDataUserInfo
                    {
                        sdkUserID = repData["showName"].ToString(),
                        sdkUserName = repData["showName"].ToString(),
                        //isNew = (int)repData["isNew"],
                        thirdLoginType = (int)repData["third_login_type"],
                        //thirdLoginTypeName = "mail",
                        callbackFrom = 4
                    };

                    callBack?.Invoke(NeoriginSDKStatusCode.Success, "Get User Info Success", userData);
                }
            });


        }

        //获取用户信息
        private void GetUserInfoRequest(Dictionary<string, string> payParams, System.Action<UnityWebRequest> callback)
        {
            Debug.Log("NeoriginPlatformServer GetUserInfoRequest #######:");
            WWWForm formData = new WWWForm();


            // 构建签名字符串
            string signStr = getSignStr(payParams, platformAppSecret);
            //Debug.Log("NeoriginPlatformServer PayRequest signStr " + signStr);
            string sign = getMd5Value(signStr);
            //Debug.Log("NeoriginPlatformServer PayRequest sign " + sign);
            // 构建请求数据

            formData.AddField("sign", sign);
            foreach (var kvp in NeoriginSDK.Instance.PublicParams)
            {
                //Debug.Log("NeoriginPlatformServer PayRequest formData: " + kvp.Key + " = " + kvp.Value);
                formData.AddField(kvp.Key, kvp.Value);
            }
            foreach (var kvp in payParams)
            {
                //Debug.Log("NeoriginPlatformServer PayRequest formData2: " + kvp.Key + " = " + kvp.Value);
                formData.AddField(kvp.Key, kvp.Value);
            }
            //Debug.Log("NeoriginPlatformServer PayRequest request##############");
            // 发送POST请求
            PostRequest("person/getUserInfo", formData, callback);
        }

        //获取本地用户信息
        public virtual NeoriginSDKPlatformUserInfo GetPlatformUserInfo()
        {
            Debug.Log("NeoriginPlatformServer GetPlatformUserInfo #######:");
            NeoriginSDKPlatformUserInfo user = NeoriginSDKStorage.LoadPlatformUserInfo();
            if (string.IsNullOrEmpty(user.token))
            {
                Debug.Log($"NeoriginPlatformServer Pay user not login");
                return new NeoriginSDKPlatformUserInfo { };
            }
            return user;
        }


        //获取商品信息
        public virtual void GetPayItems(NeoriginSDK.GetPayItemsCallBack callBack = null)
        {
            Debug.Log("NeoriginPlatformServer GetPayItems #######:");
        }

        public virtual void Logout(NeoriginSDK.LogoutCallBack callBack = null)
        {
            Debug.Log("NeoriginPlatformServer Logout #######:");
            NeoriginSDKStorage.DeletePlatformUserInfo();
            callBack?.Invoke(NeoriginSDKStatusCode.Success, "Success", null);
        }

        private void ShowH5PayView(InterPayParams payParams, NeoBasePay.CheckVirtualCoinData virtualCoinData, NeoriginSDK.PayCallBack callBack, NeoriginSDK.PayProcessCallBack payProcessCallBack = null)
        {
            Debug.Log("NeoriginPlatformServer ShowH5PayView");
            //读取本地登录状态
            string urlParameters = GetWebViewParameters();
            NeoriginSDKPlatformInitGameOtherCfg gameOtherConfig = NeoriginSDKStorage.LoadPlatformInitGameOtherCfg();
            // pay_channel_ids 用 "," 连接
            string payChannelIds = string.Join(",", gameOtherConfig.pay_config.pay_channel_ids);
            urlParameters += $"&pay_channel_ids={payChannelIds}";
            urlParameters += $"&virtual_coin_amount={virtualCoinData.productVirtualCoin}";
            urlParameters += $"&virtual_coin_num={virtualCoinData.virtualCoinNum}";
            urlParameters += $"&virtual_coin_name={virtualCoinData.virtualCoinName}";
            urlParameters += $"&price={payParams.orderMoney}";
            payParams.coinName = virtualCoinData.virtualCoinName;

            NeoriginSDKWebview sdkWebView = new NeoriginSDKWebview(
                onCloseListener: () =>
                {
                    // 用户关闭了WebView
                    Debug.Log("NeoriginPlatformServer ShowH5PayView: User closed the WebView.");
                    callBack?.Invoke(NeoriginSDKStatusCode.WebViewUserCanceled, "User closed the pay window.", null);
                }, isShowCloseBtn: false
            );

            sdkWebView.adjustmentProportion(0.82f, 0.82f);
            string h5File = platformH5PagePay;
            string h5Url = platformH5Url + "/" + h5File;
            Debug.Log("ShowH5PayView: open h5Url: " + h5Url + urlParameters);
            NeoriginSDKShowWebViewParams webviewParams = new NeoriginSDKShowWebViewParams
            {
                isDebug = platformIsDebug
            };

            sdkWebView.ShowWebView(h5Url + urlParameters, webviewParams, () =>
            {
                Debug.Log("ShowH5PayView loaded successfully");
            }, (args) =>
            {
                //判断参数是否正确
                if (args == null || args.Count < 2)
                {
                    Debug.Log("ShowH5PayView JS call arguments are invalid.");
                    sdkWebView.CallJsFunc("unity handle error:arguments are invalid");
                    return;
                }
                Debug.Log("ShowH5PayView JS call: " + args[0] + ", " + args[1]);

                //按args[0]的值判断登录类型，处理不同的业务逻辑
                if (args[0] == "close_window")
                {
                    //关闭窗口
                    Debug.Log("ShowH5PayView: User closed the WebView." + args[1]);
                    callBack?.Invoke(NeoriginSDKStatusCode.WebViewUserCanceled, "User closed the login window.", null);
                    sdkWebView.CloseWebview();
                }
                else if (args[0] == "virtual_coin_exchane")
                {
                    sdkWebView.CloseWebview();
                    payParams.payChannel = NeoPayFactory.PlatformPayVirtualCoin;
                    var payImpl = NeoPayFactory.CreatePayStrange(payParams.payChannel);
                    payImpl.Pay(payParams, callBack);
                }
                else if (args[0] == "third_pay")
                {
                    JObject jsonObject = JObject.Parse(args[1]);
                    int errorCode = (int)jsonObject["code"];
                    if (errorCode == 0)
                    {
                        sdkWebView.CloseWebview();
                        JObject dataObject = (JObject)jsonObject["data"];
                        string selectChannel = dataObject["select_channel"]?.ToString() ?? "";
                        Debug.Log("ShowH5PayView: User select with pay_channel: " + selectChannel);
                        if (!NeoPayFactory.payChannelSupport(gameOtherConfig.pay_config.pay_channel_ids, selectChannel)) // 不支持的支付渠道
                        {
                            callBack?.Invoke(NeoriginSDKStatusCode.PayChannelErr, "NeoriginPlatformServer pay channel not support");
                            return;
                        }
                        if (selectChannel == NeoPayFactory.PlatformPayVirtualCoin)  // 虚拟币支付
                        {
                            payParams.payChannel = NeoPayFactory.PlatformPayVirtualCoin;
                            var payImpl = NeoPayFactory.CreatePayStrange(payParams.payChannel);
                            payImpl.Pay(payParams, callBack);
                        }
                        else   // 其他第三方支付
                        {
                            payParams.payChannel = selectChannel;
                            ThirdPay(payParams, callBack, payProcessCallBack);
                        }
                    }
                }
                else if (args[0] == "pay_center")
                {
                    if (!string.IsNullOrEmpty(gameOtherConfig.pay_config.pay_center_url))
                    {
                        OpenBrowser(gameOtherConfig.pay_config.pay_center_url);
                    }
                }
                else
                {
                    Debug.Log("ShowH5PayView: Unknown action type: " + args[0]);
                    sdkWebView.CallJsFunc("unity handle error:Unknown action type");
                }
            });
        }

        public virtual void ShowInsufficientVirtualCoin(InterPayParams payParams)
        {
            Debug.Log("NeoriginPlatformServer ShowInsufficientVirtualCoin");

            string urlParameters = GetWebViewParameters();
            urlParameters += $"&pay_page=insufficient";
            urlParameters += $"&virtual_coin_name={payParams?.coinName}";
            NeoriginSDKPlatformInitGameOtherCfg gameOtherConfig = NeoriginSDKStorage.LoadPlatformInitGameOtherCfg();

            NeoriginSDKWebview sdkWebView = new NeoriginSDKWebview(
                onCloseListener: () =>
                {
                    // 用户关闭了WebView
                    Debug.Log("NeoriginPlatformServer ShowInsufficientVirtualCoin: User closed the WebView.");
                }, isShowCloseBtn: false
            );

            sdkWebView.adjustmentProportion(0.82f, 0.82f);
            string h5File = platformH5PagePay;
            string h5Url = platformH5Url + "/" + h5File;
            Debug.Log("ShowInsufficientVirtualCoin: open h5Url: " + h5Url + urlParameters);
            NeoriginSDKShowWebViewParams webviewParams = new NeoriginSDKShowWebViewParams
            {
                isDebug = platformIsDebug
            };

            sdkWebView.ShowWebView(h5Url + urlParameters, webviewParams, () =>
            {
                Debug.Log("ShowInsufficientVirtualCoin loaded successfully");
            }, (args) =>
            {
                //判断参数是否正确
                if (args == null || args.Count < 2)
                {
                    Debug.Log("ShowInsufficientVirtualCoin JS call arguments are invalid.");
                    sdkWebView.CallJsFunc("unity handle error:arguments are invalid");
                    return;
                }
                Debug.Log("ShowInsufficientVirtualCoin JS call: " + args[0] + ", " + args[1]);

                //按args[0]的值判断登录类型，处理不同的业务逻辑
                if (args[0] == "close_window")
                {
                    //关闭窗口
                    Debug.Log("ShowInsufficientVirtualCoin: User closed the WebView." + args[1]);
                    sdkWebView.CloseWebview();
                }
                else if (args[0] == "pay_center")
                {
                    if (!string.IsNullOrEmpty(gameOtherConfig.pay_config.pay_center_url))
                    {
                        OpenBrowser(gameOtherConfig.pay_config.pay_center_url);
                    }
                }
                else
                {
                    Debug.Log("ShowInsufficientVirtualCoin: Unknown action type: " + args[0]);
                    sdkWebView.CallJsFunc("unity handle error:Unknown action type");
                }
            });
        }
        protected NeoriginSDKWebview paycheckweb;
        protected NeoriginSDK.PayCallBack playCallBack;

        private void ThirdPay(InterPayParams interPayParams, NeoriginSDK.PayCallBack callBack, NeoriginSDK.PayProcessCallBack payProcessCallBack = null)
        {
            var payImpl = NeoPayFactory.CreatePayStrange(interPayParams.payChannel);
            if (interPayParams.payChannel == NeoPayFactory.PlatformPayGoogle || 
                interPayParams.payChannel == NeoPayFactory.PlatformPayXsolla || 
                interPayParams.payChannel == NeoPayFactory.PlatformPaySteam)
            {
                playCallBack = callBack;
                PayCheckHtml5();
            }
            payImpl.CreateOrderAndPay(interPayParams, (code, msg, data) => {
                //关闭这个
                paycheckweb?.CloseWebview();
                playCallBack?.Invoke(code, msg, data);
                paycheckweb = null;
            }, payProcessCallBack);
        }

        public void PayCheckHtml5()
        {

            paycheckweb = new NeoriginSDKWebview(
                          onCloseListener: () =>
                          {
                              // 用户关闭了WebView
                              Debug.Log("OpenCustomerService: User closed the WebView.");
                          }, isShowCloseBtn: false
                      );
            paycheckweb.adjustmentProportion(0.82f, 0.82f);
            string htmlPath = Path.Combine(Application.streamingAssetsPath, "paying.html");
            string urlParameters = $"?paying={NeoriginSDK.Instance.GetSDKLangTranslation("paying")}&close={NeoriginSDK.Instance.GetSDKLangTranslation("close")}&payover={NeoriginSDK.Instance.GetSDKLangTranslation("payover")}&payingdesc={NeoriginSDK.Instance.GetSDKLangTranslation("payingdesc")}";
            string h5Url = "file://" + htmlPath + urlParameters;
            NeoriginSDKShowWebViewParams webviewParams = new NeoriginSDKShowWebViewParams
            {
                isDebug = platformIsDebug
            };
            paycheckweb.ShowWebView(h5Url, webviewParams, () =>
            {
                Debug.Log("OpenCustomerService loaded successfully");
            }, (args) =>
            {
                //判断参数是否正确
                if (args == null || args.Count < 2)
                {
                    Debug.Log("OpenCustomerService JS call arguments are invalid.");
                    paycheckweb.CallJsFunc("OpenCustomerService handle error:arguments are invalid");
                    return;
                }
                Debug.Log("OpenCustomerService JS call: " + args[0] + ", " + args[1]);

                //按args[0]的值判断登录类型，处理不同的业务逻辑
                if (args[0] == "PayClose")
                {
                    //关闭这个界面
                    paycheckweb.CloseWebview();
                }
                if(args[0] == "PayCheck")
                {
                    Debug.Log("获取支付状态:" + NeoBasePay.pay_status.ToString());
                    //看支付状态
                    if(NeoBasePay.pay_status==PayStatus.PAYING)
                    {
                        NeoriginSDKToastManager.Instance.Show(NeoriginSDK.Instance.GetSDKLangTranslation("paying"));
                    }

                }
            });
        }
        
        protected static NeoriginSDKStatusCode MapServerErrorCodeToSDK(int serverErrorCode)
        {
          // 直接返回服务端错误码（如果它在枚举范围内）
          if (System.Enum.IsDefined(typeof(NeoriginSDKStatusCode), serverErrorCode))
          {
            return (NeoriginSDKStatusCode)serverErrorCode;
          }
          return NeoriginSDKStatusCode.BadRequest;
        }
    }
}
