using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SysDebug = System.Diagnostics.Debug; // 为System.Diagnostics.Debug创建别名
using SysProcess = System.Diagnostics.Process; // 为Process创建别名
using SysProcessStartInfo = System.Diagnostics.ProcessStartInfo;
using Xsolla.Catalog;
using Xsolla.Core;
namespace NeoriginPCSDK
{
    // NeoriginPlatformServer 用于处理与平台服务器的交互
    public static class NeoriginPlatformServer
    {
        private class CoroutineMonoBehaviour : MonoBehaviour { }

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

        private static bool platformIsDebug = false;

        private static string platformAiHelpPlatformTag = "Platform_PC";

        private static Dictionary<string, string> publicParams = new Dictionary<string, string>();
        private static JObject platformInitRepData = new JObject();

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

        // 初始化时设置基础域名
        public static 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";
            }

            publicParams["game_id"] = platformAppId;
            publicParams["channel"] = "3_PC"; // 渠道
            publicParams["device_type"] = deviceData.deviceType ?? "";
            publicParams["device"] = deviceData.deviceID ?? "";
            publicParams["device_id"] = deviceData.deviceID ?? "";
            publicParams["mac"] = deviceData.deviceMac ?? "";
            publicParams["sdk_game_name"] = ""; // 游戏名称
            publicParams["lang_code"] = GetLocalLanuage(); // 语言代码
            publicParams["system_version"] = deviceData.deviceOSVersion; // 系统版本
            publicParams["sdk_version"] = platformSDKVersion; // SDK 版本
            publicParams["server_id"] = ""; // 服务器id

            //初始化平台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 static 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 static void LoginAccount(NeoriginSDK.LoginAccountCallBack callBack, NeoriginSDK.LoginAccountProcessCallBack processCallBack = null)
        {
            //读取本地登录状态
            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: true
            );
            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
                {
                    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);
                }
            });
        }

        public static 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;
            }

            string urlParameters = GetWebViewParameters();
            urlParameters += $"&aihelp_domain={platformAihelpDomain}";
            urlParameters += $"&aihelp_appid={platformAihelpAppId}";
            urlParameters += $"&aihelp_entryid={platformAihelpEntryId}";

            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: true
            );
            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] == "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());
                }
            });
        }

        private static 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 static 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}";

            NeoriginSDKWebview sdkWebView = new NeoriginSDKWebview(
                onCloseListener: () =>
                {
                    // 用户关闭了WebView
                    Debug.Log("OpenCustomerService: User closed the WebView.");
                }, isShowCloseBtn: true
            );
            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.");
                    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 static 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: true
            );
            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) =>
            {
            });
        }

        public static 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 static string GetLocalLanuage()
        {
            NeoriginSDKDevice deviceCfg = NeoriginSDKStorage.LoadDevice();
            /*string userLang = deviceCfg.deviceLang.ToString();
            if (userLang == "zh-CN" || userLang == "zh-Hans")
            {
                userLang = "zh";
            }
            else if (userLang == "zh-TW" || userLang == "zh-Hant")
            {
                userLang = "ft";
            }
            else if (userLang == "ko" || userLang == "ko-KR")
            {
                userLang = "ko";
            }
            else if (userLang == "ja" || userLang == "ja-JP")
            {
                userLang = "ja";
            }
            else
            {
                userLang = "en";
            }*/
            string userLang = "en";
            switch (deviceCfg.deviceLang)
            {
                case SystemLanguage.ChineseSimplified:
                    userLang = "zh";
                    break;
                case SystemLanguage.ChineseTraditional:
                    userLang = "ft";
                    break;
                case SystemLanguage.Japanese:
                    userLang = "ja";
                    break;
                case SystemLanguage.Korean:
                    userLang = "ko";
                    break;
                default:
                    userLang = "en";
                    break;
            }
            return userLang;
        }
        private static 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 static 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 static string GetPolicyUrl(string policyType)
        {
            NeoriginSDKPlatformInitGameOtherCfg gameOtherConfig = NeoriginSDKStorage.LoadPlatformInitGameOtherCfg();

            string userLang = 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;
        }

        private static 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 publicParams)
            {
                urlParameters += $"&{kvp.Key}={UnityWebRequest.EscapeURL(kvp.Value)}";
            }

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

            return urlParameters;
        }

        public static 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 static void OpenDesktopBrowser(string url)
        {
#if UNITY_STANDALONE_WIN
                // Windows
                SysProcess.Start(new SysProcessStartInfo{
                    FileName = url, // 关键：直接使用URL作为文件名
                    UseShellExecute = true, // 使用系统Shell执行
                    Verb = "open" // 指定"打开"操作
                });
#endif
        }

        // 发送GET请求
        private static 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请求
        private static 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 static string CombineUrl(string baseUrl, string endpoint)
        {
            return $"{baseUrl.TrimEnd('/')}/{endpoint.TrimStart('/')}";
        }

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

        private static 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;
            }

        }

        private static string getSignStr(Dictionary<string, string> parameters, string signKey = "")
        {
            Dictionary<string, string> newParams = new Dictionary<string, string>(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;
        }
        // 初始化请求
        public static 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 publicParams)
            {
                formData.AddField(kvp.Key, kvp.Value);
            }
            // 发送POST请求
            //PostRequest("login/pc/hwinits", formData, callback);
            PostRequest("login/pc/hwinits", formData, callback);
        }

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

            platformInitRepData = data;

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

                // 时间戳转换
                long timestamp = 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 = GetStringValue(gameCfg, "game_name"),
                    hw_pay_way = GetStringValue(gameCfg, "hw_pay_way"),
                    hw_pay_way_type = GetStringValue(gameCfg, "hw_pay_way_type"),
                    company_entity = GetStringValue(gameCfg, "company_entity"),
                    current_timestamp = 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)
                    {
                        // 如果解析失败（比如是 []），则保持空字典

                    }
                }

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

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

        // 游客登录请求
        public static 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 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);
        }

        // 游客登录请求
        public static 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 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);
        }

        //平台登录请求后的处理逻辑
        public static 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);

            }
        }

        // 处理登录响应数据
        public static 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 = GetStringValue(data, "uuid"),
                token = GetStringValue(data, "token"),
                expireTime = GetStringValue(data, "expireTime"),
                showName = GetStringValue(data, "showName"),
                displayName = GetStringValue(data, "displayName"),
                isNew = GetIntValue(data, "isNew", 0),
                third_login_type = GetIntValue(data, "third_login_type", 0),
                third_identifier = GetStringValue(data, "third_identifier"),
                suspendTime = GetStringValue(data, "suspendTime"),
                suspendReason = GetStringValue(data, "suspendReason"),
                note = GetStringValue(data, "note"),
                delete_status = GetIntValue(data, "delete_status", 0),
                delete_time = GetIntValue(data, "delete_time", 0),
                bind_third_login_type = thirdLogin,
                bind_third_login_type_detail = thirdLoginDetail
            };
            //存入缓存
            //NeoriginSDKPlatformUserInfo platformUserInfo = data.ToObject<NeoriginSDKPlatformUserInfo>();
            NeoriginSDKStorage.SavePlatformUserInfo(platformUserInfo);
        }

        // 安全获取字符串值
        static string GetStringValue(JObject obj, string key, string defaultValue = "")
        {
            return obj[key]?.Value<string>() ?? defaultValue;
        }

        // 安全获取整数值
        static int GetIntValue(JObject obj, string key, int defaultValue = 0)
        {
            if (obj[key] != null && obj[key].Type == JTokenType.Integer)
            {
                return obj[key].Value<int>();
            }
            return defaultValue;
        }

        // 安全获取长整型值
        static long GetLongValue(JObject obj, string key, long defaultValue = 0)
        {
            if (obj[key] != null && (obj[key].Type == JTokenType.Integer || obj[key].Type == JTokenType.Float))
            {
                return obj[key].Value<long>();
            }
            return defaultValue;
        }

        //支付
        public static 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;
            }
            string time = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            Dictionary<string, string> reqParams = new Dictionary<string, string>
            {
                { "game_order_id", payParams.game_order_id },
                { "server_id", payParams.server_id },
                { "role_name", payParams.role_name },
                { "role_id", payParams.role_id },
                { "pay_channel_id", platformPayXsolla },//xsolla支付
                { "desc", payParams.desc },
                { "product_id", payParams.product_id },
                { "extra", payParams.extra },
                { "uuid", user.uuid },
                { "token", user.token },
                { "time", time },
            };
            PayRequest(reqParams, (response) =>
            {
                if (response.isNetworkError || response.isHttpError)
                {
                    // 处理错误
                    Debug.Log($"NeoriginPlatformServer PayRequest 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 PayRequest 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 PayRequest rep: {errorCode} # {message}");
                    if (errorCode != 0)
                    {
                        Debug.Log($"NeoriginPlatformServer PayRequest Error: {message}");
                        callBack?.Invoke(code: NeoriginSDKStatusCode.InternalError, msg: $"Platform return error.code:{errorCode},message:{message}");
                        return;
                    }
                    //保存返回数据
                    JObject repData = (JObject)rep["data"];
                    string orderId = (string)repData["order_id"];
                    string channelOrderId = (string)repData["pay_channel_order_id"];
                    JObject payChannelInfo = ((JObject)repData["pay_channel_info"]);
                    Debug.Log($"NeoriginPlatformServer PayRequest payChannelInfo: {payChannelInfo}");

                    NeoriginSDKCallbackDataPayProcess payProcessData = new NeoriginSDKCallbackDataPayProcess
                    {
                        process_state = 0,
                        platform_order_id = orderId,
                        game_order_id = payParams.game_order_id,
                        product_id = payParams.product_id,
                        pay_channel_order_id = channelOrderId,
                        pay_channel_id = platformPayXsolla,
                        order_money = payParams.order_money,
                        order_time = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")

                    };
                    payProcessCallBack?.Invoke(payProcessData);

                    XsollaToken.Create((string)payChannelInfo["token"]);

                    PurchaseParams xsollaPurchaseParams = new PurchaseParams{
                        locale=GetLocalLanuageXsolla()
                    };

                    XsollaCatalog.Purchase(itemSku:payParams.product_id,purchaseParams:xsollaPurchaseParams,onSuccess:(complateStatus) =>
                    {
                        Debug.Log($"NeoriginPlatformServer xsolla Purchase completed:{complateStatus.status},{complateStatus.order_id}");
                        int channelOrderId = complateStatus.order_id;
                        OrderContent channelOrder = complateStatus.content;
                        string channelOrderAmount = channelOrder.price.amount;
                        string channelOrderCurrency = channelOrder.price.currency;
                        Debug.Log($"NeoriginPlatformServer xsolla Purchase detail:amount:{channelOrderAmount},currency:{channelOrderCurrency}");
                        OrderItem[] channelOrderItems = channelOrder.items;
                        foreach (var item in channelOrderItems)
                        {
                            Debug.Log($"NeoriginPlatformServer xsolla Purchase item: sku:{item.sku},quantity:{item.quantity},quantity:{item.quantity},price:{item.price.amount},currency:{item.price.currency}");
                        }
                        //支付订单结果上报
                        string payTime = System.DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
                        string resultTime = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
                        Dictionary<string, string> resultParams = new Dictionary<string, string>
                        {
                            { "pay_time", payTime },
                            { "receipt_signature", "" },
                            { "receipt_data", channelOrderId.ToString() },
                            { "transaction_id", channelOrderId.ToString() },
                            { "status", "1" },
                            { "order_id", orderId },
                            { "server_id", payParams.server_id },
                            { "uuid", user.uuid },
                            { "token", user.token },
                            { "pay_channel_id", platformPayXsolla },
                            { "time", resultTime }
                        };
                        PayResultRequest(resultParams, (resultResponse) =>
                        {
                            if (resultResponse.isNetworkError || resultResponse.isHttpError)
                            {
                                // 处理错误
                                Debug.Log($"NeoriginPlatformServer PayResultRequest Error: {resultResponse.error},code {resultResponse.responseCode}");
                                callBack?.Invoke(code: NeoriginSDKStatusCode.BadRequest, msg: $"Platform request error.code:{response.responseCode},Error:{response.error}");
                                return;
                            }
                            else
                            {
                                // 成功接收到响应
                                string resultResponseData = resultResponse.downloadHandler.text;  // 文本信息
                                Debug.Log($"NeoriginPlatformServer PayResultRequest Received: {resultResponseData}");
                                //dynamic rep = JsonConvert.DeserializeObject(responseData);//JsonUtility.FromJson<NeoriginSDKBaseResponse>(responseData);
                                // 解析整个JSON
                                JObject resultRep = JObject.Parse(resultResponseData);
                                int resultErrorCode = (int)resultRep["error"];
                                string resultMessage = (string)resultRep["msg"];
                                Debug.Log($"NeoriginPlatformServer PayResultRequest rep: {resultErrorCode} # {resultMessage}");
                                if (resultErrorCode != 0 && resultErrorCode != 7)
                                {
                                    Debug.Log($"NeoriginPlatformServer PayResultRequest Error: {resultMessage}");
                                    callBack?.Invoke(code: NeoriginSDKStatusCode.InternalError, msg: $"Platform return error.code:{resultErrorCode},message:{resultMessage}");
                                    return;
                                }

                                JObject ResultRepData = (JObject)resultRep["data"];
                                NeoriginSDKCallbackDataPay resultDataCallback = new NeoriginSDKCallbackDataPay
                                {
                                    state = 0,
                                    extension = payParams.extra,
                                    order_id = payParams.game_order_id
                                };
                                // 调用回调函数
                                callBack?.Invoke(NeoriginSDKStatusCode.Success, "Pay Success", resultDataCallback);
                            }
                        });

                    }, onError:(error) =>
                    {
                        Debug.Log($"NeoriginPlatformServer xsolla Error message: {error.errorMessage},errorCode:{error.errorCode},statusCode:{error.statusCode}");
                        callBack?.Invoke(code: NeoriginSDKStatusCode.InternalError, msg: $"xsolla Error message: {error.errorMessage},errorCode:{error.errorCode},statusCode:{error.statusCode}");
                        return;
                    });
                }
            });

        }

        private static void PayRequest(Dictionary<string, string> payParams, System.Action<UnityWebRequest> callback)
        {
            Debug.Log("NeoriginPlatformServer PayRequest #######:");
            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 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("v1.4.1/order/hw/add", formData, callback);
        }

        //支付订单结果上报
        private static void PayResultRequest(Dictionary<string, string> payParams, System.Action<UnityWebRequest> callback)
        {
            Debug.Log("NeoriginPlatformServer PayResultRequest #######:");
            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 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("order/hw/pay", formData, callback);
        }

        //获取用户信息
        public static 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 static 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 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 static 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 static void GetPayItems(NeoriginSDK.GetPayItemsCallBack callBack = null)
        {
            Debug.Log("NeoriginPlatformServer GetPayItems #######:");
            XsollaCatalog.GetPaginatedItems((storeItems) =>
            {
                if (storeItems != null && storeItems.items != null && storeItems.items.Length > 0)
                {
                    List<NeoriginSDKCallbackDataPayItem> payItemsList = new List<NeoriginSDKCallbackDataPayItem>();
                    Debug.Log($"NeoriginPlatformServer xsolla GetPayItems success:{storeItems.items.Length} items");
                    StoreItem[] items = storeItems.items;

                    foreach (var item in items)
                    {
                        if (item != null)
                        {
                            string sku = item.sku ?? "";
                            string name = item.name ?? "";
                            string type = item.type ?? "";
                            string description = item.description ?? "";

                            if (string.IsNullOrEmpty(sku))
                            {
                                Debug.LogWarning($"NeoriginPlatformServer xsolla Store item sku is null");
                                continue;
                            }
                            string amount = "";
                            string currency = "";

                            if (item.price != null)
                            {
                                amount = item.price.amount ?? "";
                                currency = item.price.currency ?? "";
                            }
                            if (string.IsNullOrEmpty(amount) || string.IsNullOrEmpty(currency))
                            {
                                Debug.LogWarning($"NeoriginPlatformServer xsolla Store item amount&currency is null");
                                continue;
                            }
                            NeoriginSDKCallbackDataPayItem payItem = new NeoriginSDKCallbackDataPayItem();
                            payItem.product_id = sku;
                            payItem.price = float.Parse(amount);
                            payItem.symbol = currency;
                            payItem.title = name;
                            payItem.localizedDescription = description;
                            payItem.countryCode = "";
                            payItem.priceCurrencyCode = currency;
                            payItemsList.Add(payItem);

                            Debug.Log($"NeoriginPlatformServer xsolla Store item: sku:{sku},name:{name},price:{amount},currency:{currency},type:{type},description:{description}");
                        }
                    }
                    if (payItemsList.Count == 0)
                    {
                        Debug.Log($"NeoriginPlatformServer xsolla GetPayItems no valid items");
                        callBack?.Invoke(NeoriginSDKStatusCode.PayErrorItems, "NeoriginPlatformServer xsolla GetPayItems no valid items");
                        return;
                    }

                    callBack?.Invoke(NeoriginSDKStatusCode.Success, "Success", payItemsList.ToArray());
                }
                else
                {
                    Debug.Log($"NeoriginPlatformServer xsolla GetPayItems no items");
                    callBack?.Invoke(NeoriginSDKStatusCode.PayNoItems, "NeoriginPlatformServer xsolla GetPayItems no items");
                }
            }, (error) =>
            {
                Debug.Log($"NeoriginPlatformServer GetPayItems xsolla Error message: {error.errorMessage},errorCode:{error.errorCode},statusCode:{error.statusCode}");
                callBack?.Invoke(code: NeoriginSDKStatusCode.InternalError, msg: $"GetPayItems xsolla Error message: {error.errorMessage},errorCode:{error.errorCode},statusCode:{error.statusCode}");
                return;
            }, 50, 0);

        }

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