using NeoriginPCSDK;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PlayPcSdkManaged.Billing;
using PlayPcSdkManaged.Initialization;
using PlayPcSdkManaged.Integrity;
using PlayPcSdkManaged.Unity;
using PlayPcSdkManaged.Unity.InstallReferrer;
using PuppeteerSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using ThinkingData.Analytics;
using Unity.VisualScripting.Antlr3.Runtime;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using static ZenFulcrum.EmbeddedBrowser.Browser;
namespace NeoriginPCSDK
{
    public class NeoriginPlatformGoogleServer : NeoriginPlatformBaseServer
    {
        public override void Initialize(NeoriginSDKConfig.Platform sdkConfig, NeoriginSDKDevice deviceData, NeoriginSDKParamsInit initData, NeoriginSDK.InitCallBack callBack)
        {
           // IntegrityQuitGame();
            InitializeGoogleSDK(sdkConfig, deviceData, initData, callBack);
        }

        private void InitializeGoogleSDK(NeoriginSDKConfig.Platform sdkConfig, NeoriginSDKDevice deviceData, NeoriginSDKParamsInit initData, NeoriginSDK.InitCallBack callBack)
        {
            // 工厂为初始化提供了必要的 Unity 特定处理程序。
            var initializationHandler = PlayPcSdkFactory.InitializationHandler;
            var task = GooglePlayInitialization.InitializeAsync(initializationHandler);

            // 这里使用 TaskScheduler 确保回调在主线程执行，避免 Unity API 报错
            task.ContinueWith(t =>
            {
                var result = t.Result;
                if (result.IsOk)
                {
                    Debug.Log("<color=green>成功连接到商店！</color>");
                    GooglePlayData.instance.billingClient = PlayPcSdkFactory.CreateBillingClient();
                    GooglePlayData.instance.integrityClient = PlayPcSdkFactory.CreateIntegrityClient();
                    GooglePlayData.instance.recallClient = PlayPcSdkFactory.CreateRecallClient();
                    GooglePlayData.instance.installReferrerClient = PlayPcSdkFactory.CreateInstallReferrerClient();
                    base.Initialize(sdkConfig, deviceData, initData, (code, msg, data) =>
                    {
                        callBack.Invoke(code, msg, data);
                        CheckIntegrity(3);
                    });
                  
                }
                else
                {
                    Debug.Log($"<color=red>连接失败！代码: {result.Code}, 消息: {result.ErrorMessage}</color>");
                    // ... 错误处理 ...
                    callBack?.Invoke(code: NeoriginSDKStatusCode.GoogleSDKError, msg: $"google sdk init error.code:{result.Code},Error:{result.ErrorMessage}");
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void CheckIntegrity(int retryCount)
        {
            var prepareParams = new PrepareIntegrityTokenParams { CloudProjectNumber = GooglePlayData.instance.cloudProjectNumber };
            var task = GooglePlayData.instance.integrityClient.PrepareIntegrityTokenAsync(prepareParams);
            task.ContinueWith(t => {
                var result = t.Result;
                if (!result.IsOk)
                {
                    if (retryCount < 3) 
                    {
                        Task.Delay(1000).ContinueWith(delayTask =>
                        {
                            CheckIntegrity( retryCount + 1);
                        }, TaskScheduler.FromCurrentSynchronizationContext());
                    }
                    else
                    {
                        //弹出h5提示
                        IntegrityQuitGame();
                    }
                    return;
                }

                string time = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
                var hash_dic=new Dictionary<string, string>();
                foreach (var item in NeoriginSDK.Instance.PublicParams)
                {
                    hash_dic[item.Key]=item.Value;
                }
                hash_dic["time"] = time;
                var RequestHash = GenerateRequestHash(hash_dic);
                var requestParams = new RequestIntegrityTokenParams
                {
                    RequestTokenData = result.Value.RequestTokenData,
                    RequestHash = RequestHash // 在真实游戏中，这应该是请求数据的哈希值
                };
                var tokenTask = GooglePlayData.instance.integrityClient.RequestIntegrityTokenAsync(requestParams);
                tokenTask.ContinueWith(ttoken => {
                    var tokenresult = ttoken.Result;
                    if (!tokenresult.IsOk)
                    {
                        if (retryCount < 3) 
                        {
                            Task.Delay(1000).ContinueWith(delayTask =>
                            {
                                CheckIntegrity(retryCount + 1);
                            }, TaskScheduler.FromCurrentSynchronizationContext());
                        }
                        else
                        {
                            //弹出h5提示
                            IntegrityQuitGame();
                        }
                        return;
                    }
                    RequestIntegrityToekn(tokenresult.Value.TokenBytes,time, () => 
                    {
                        Debug.Log("检查安全性通过");
                    },(code,msg) => {
                        if (retryCount < 3)
                        {
                            Task.Delay(1000).ContinueWith(delayTask =>
                            {
                                CheckIntegrity(retryCount + 1);
                            }, TaskScheduler.FromCurrentSynchronizationContext());
                        }
                        else
                        {
                            //这一块弹出h5提示
                            IntegrityQuitGame();
                        }
                    });
                }, TaskScheduler.FromCurrentSynchronizationContext());

            }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void RequestIntegrityToekn(string integrity_token,string time,Action success_action,Action<int,string> fail_action)
        {
            WWWForm form = new WWWForm();
          
            Dictionary<string, string> reqParams = new Dictionary<string, string>
            {
                { "integrity_token",integrity_token},
                { "time",time}
            };
            string signStr = getSignStr(reqParams);
            string sign = getMd5Value(signStr);
            form.AddField("integrity_token", integrity_token);
            form.AddField("sign", sign);
            form.AddField("time", time);
            foreach (var kvp in NeoriginSDK.Instance.PublicParams)
            {
                form.AddField(kvp.Key, kvp.Value);
            }
            PostRequest("/v1.4.1/login/pc/hwPcGoogleIntegrity", form, (bindresponse) =>
            {

                if (bindresponse.isNetworkError || bindresponse.isHttpError)
                {
                    fail_action?.Invoke(999,"error");
                    return;
                }
                string bindresponseData = bindresponse.downloadHandler.text;
                Debug.Log($"NeoriginPlatformServer Integrity : received:{bindresponseData}");
                JObject jsonObject = JObject.Parse(bindresponseData);
                int errorCode = (int)jsonObject["error"];
                string message = (string)jsonObject["msg"];
                if (errorCode == 0)
                {
                    success_action?.Invoke();
                }
                else
                {
                    fail_action?.Invoke(errorCode,message);
                }
            });
        }

        public override void Login(string userAccount, int touristFlag, NeoriginSDK.LoginCallBack callBack)
        {
            base.Login(userAccount, touristFlag, (code, msg, res) => {
                if (code == NeoriginSDKStatusCode.Success)
                {
                    var task = GooglePlayData.instance.recallClient.RequestRecallAccessAsync();
                    task.ContinueWith(t =>
                    {
                        var result = t.Result;
                        if (result.IsOk)
                        {
                            GooglePlayData.instance.recall_session_id = result.Value.recall_session_id;
                            BindRecall(result.Value.recall_session_id);
                        }

                    }, TaskScheduler.FromCurrentSynchronizationContext());
                }
                callBack?.Invoke(code, msg, res);
            });

        }

        public override void LoginAccount(NeoriginSDK.LoginAccountCallBack callBack, NeoriginSDK.LoginAccountProcessCallBack processCallBack = null)
        {
            //这边 要先进行recall的如果recall绑定数据不为空  则 进行下面的操作 
            var task = GooglePlayData.instance.recallClient.RequestRecallAccessAsync();
            task.ContinueWith(t => {
                var result = t.Result;
                if (result.IsOk)
                {
                    GooglePlayData.instance.recall_session_id = result.Value.recall_session_id;
                    Debug.Log($"<color=green>获取recall id 成功值为: {result.Value.recall_session_id}</color>");
                    LoginByRecall(result.Value.recall_session_id, (response) =>
                    {
                        if(response.isNetworkError || response.isHttpError)
                        {
                            Debug.Log($"NeoriginPlatformServer recalllogin Error: {response.error},code {response.responseCode}");
                            callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, "Loginrecall Fail " , null);
                            return;
                        }
                        string responseData = response.downloadHandler.text;
                        Debug.Log($"NeoriginPlatformServer recalllogin : received:{responseData}");
                        JObject rep = JObject.Parse(responseData);
                        int errorCode = (int)rep["error"];
                        string message=(string)rep["msg"];
                        if(errorCode!=0)
                        {
                            Debug.Log($"NeoriginPlatformServer recalllogin Error: {message}");
                           // 则进行h5登录
                            base.LoginAccount((code, msg, res) =>
                            {

                                if (code == NeoriginSDKStatusCode.Success)
                                {
                                    //recallbangding
                                    BindRecall(result.Value.recall_session_id);

                                }
                                callBack(code, msg, res);
                            }, (processAction) =>
                            {
                                //这一块进行进度更新
                                processCallBack(processAction);


                            });
                            //base.LoginTourist("test11111", (resposeres) =>
                            //{
                            //    PlatformLoginRequestHandle("LoginTourist", resposeres, (code, msg, res) =>
                            //    {
                            //        if(code== NeoriginSDKStatusCode.Success)
                            //        {
                            //            BindRecall(result.Value.recall_session_id);
                            //        }
                            //        NeoriginSDKCallbackDataLoginAccount resultData = new NeoriginSDKCallbackDataLoginAccount
                            //        {
                            //            sdkUserID = res.sdkUserID,
                            //            sdkUserName = res.sdkUserName,
                            //            sdkLogUserId = res.sdkLogUserId,
                            //            thirdLoginType = res.thirdLoginType,
                            //            sdkLogThirdUserName = res.sdkLogThirdUserName,
                            //            isNew = res.isNew,
                            //            thirdLoginTypeName = res.extension,
                            //            callbackFrom = res.callbackFrom
                            //        };
                            //        callBack(code, msg, resultData);
                            //    });

                            //});
                            return;
                        }
                        //这边要进行登录处理
                        JObject repData = (JObject)rep["data"];
                        LoginHandle(repData);
                        NeoriginSDKCallbackDataLoginAccount resultData = new NeoriginSDKCallbackDataLoginAccount
                        {
                            sdkUserID = (string)repData["showName"],
                            sdkUserName = (string)repData["showName"],
                            sdkLogUserId = (string)repData["displayName"],
                            thirdLoginType = ((int)repData["third_login_type"]),
                            sdkLogThirdUserName ="",
                            isNew = (int)repData["isNew"],
                            thirdLoginTypeName = "",
                            callbackFrom =0
                        };
                        callBack?.Invoke(NeoriginSDKStatusCode.Success, "LoginH5 Google Success", resultData);
                    });
                }
                else
                {
                    Debug.Log($"<color=red>无法获取recall id。错误: {result.Code}, 消息: {result.ErrorMessage}</color>");
                    callBack?.Invoke(NeoriginSDKStatusCode.LoginFailed, "Loginrecall Fail ", null);
                    return;
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void LoginByRecall(string recall_session_id, System.Action<UnityWebRequest> callback)
        {
            Debug.Log("recall login##########################");
            WWWForm form = new WWWForm();
            string time=System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            Dictionary<string, string> reqParams = new Dictionary<string, string>
            {
                {"time",time},
                { "recall_session_id",recall_session_id}
            };
            string signStr = getSignStr(reqParams);
            string sign=getMd5Value(signStr);
            form.AddField("time", time);
            form.AddField("recall_session_id", recall_session_id);
            form.AddField("sign", sign);
            foreach(var kvp in NeoriginSDK.Instance.PublicParams)
            {
                form.AddField(kvp.Key, kvp.Value);
            }

            PostRequest("v1.4.1/login/hwLoginRecall", form, callback);
        }

        private void BindRecall(string recall_session_id)
        {
            Debug.Log("recall login##########################");
            WWWForm form = new WWWForm();
            string time = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            NeoriginSDKPlatformUserInfo userInfo = NeoriginSDKStorage.LoadPlatformUserInfo();
            Dictionary<string, string> reqParams = new Dictionary<string, string>
            {
                {"time",time},
                { "uuid", userInfo.uuid },
                { "token", userInfo.token},
                { "recall_session_id",recall_session_id}
            };
            string signStr = getSignStr(reqParams);
            string sign = getMd5Value(signStr);
            form.AddField("time", time);
            form.AddField("recall_session_id", recall_session_id);
            form.AddField("uuid", userInfo.uuid);
            form.AddField("token", userInfo.token);
            form.AddField("sign", sign);
            foreach (var kvp in NeoriginSDK.Instance.PublicParams)
            {
                form.AddField(kvp.Key, kvp.Value);
            }
            PostRequest("v1.4.1/login/hwBindRecall", form, (bindresponse) =>
            {

                if (bindresponse.isNetworkError || bindresponse.isHttpError)
                {
                    Debug.Log($"NeoriginPlatformServer recalllogin Error: {bindresponse.error},code {bindresponse.responseCode}");
                    return;
                }
                string bindresponseData = bindresponse.downloadHandler.text;
                Debug.Log($"NeoriginPlatformServer bindrecall : received:{bindresponseData}");
                JObject jsonObject = JObject.Parse(bindresponseData);
                int errorCode = (int)jsonObject["error"];
                string message = (string)jsonObject["msg"];
                if (errorCode == 0)
                {
                    JObject dataObject = (JObject)jsonObject["data"];
                    LoginHandle(dataObject);

                    //在这边写入事件上报
                    NeoriginSDKPlatformUserInfo user = NeoriginSDKStorage.LoadPlatformUserInfo();
                    Dictionary<string, object> dicReg = new Dictionary<string, object>();
                    dicReg.Add("mj_channel", NeoriginSDK.Instance.SDKConfig.sdk.u8ChannelId);
                    dicReg.Add("account_type", user.third_login_type);
                    dicReg.Add("SDKID",user.displayName);
                    var bind_pgs_token = "";
                    if (user.bind_third_login_type_detail.ContainsKey("9"))
                    {
                        bind_pgs_token = user.bind_third_login_type_detail["9"];
                    }
                    dicReg.Add("bind_token", bind_pgs_token);
                    NeoriginSDK.Instance.SubmitTAUserInfo(0, "mj_pc_pgs_binding", dicReg, (taCode, taMsg, taData) =>
                    {
                        Debug.Log("SubmitTAUserInfo mj_pc_pgs_binding code: " + taCode + ", taMsg: " + taMsg);
                    });
                    //用户属性上报
                    Dictionary<string, object> taDic = new Dictionary<string, object>();
                    taDic.Add("bind_token", bind_pgs_token);
                    NeoriginSDK.Instance.SubmitTAUserInfo(2, "", taDic, (taCode, taMsg, taData) =>
                    {
                        Debug.Log("SubmitTAUserInfo mj_pc_pgs_binding UserSet code: " + taCode + ", msg: " + taMsg);
                    });
                }
          
            });
        }



        public override void GetPayItems(NeoriginSDK.GetPayItemsCallBack callBack = null)
        {
            base.GetPayItems(callBack);
            var neorigin_products=NeoriginSDKStorage.LoadPlatformInitGameProduct();
            var google_productids=new List<ProductId>();
            foreach(var item in neorigin_products.items)
            {
                google_productids.Add(new ProductId { Id = item.product_id, ProductType = ProductType.InApp });
            }
            var queryParams = new QueryProductDetailsParams { ProductIds = google_productids };
            var task = GooglePlayData.instance.billingClient.QueryProductDetailsAsync(queryParams);
            task.ContinueWith(t => {
                var result = t.Result;
                if(result.IsOk)
                {
                    List<NeoriginSDKCallbackDataPayItem> payItemsList = new List<NeoriginSDKCallbackDataPayItem>();
                    if(result.Value.ProductDetailsList!=null && result.Value.ProductDetailsList.Count>0)
                    {
                        foreach (var item in result.Value.ProductDetailsList)
                        {
                            NeoriginSDKCallbackDataPayItem payItem = new NeoriginSDKCallbackDataPayItem();
                            payItem.product_id = item.Id;
                            var (symbol, amount) = SplitFormattedPrice(item.ProductOffers[0].FormattedPrice);
                            payItem.price = float.Parse(amount);
                            payItem.symbol = symbol;
                            payItem.title = item.Title;
                            payItem.localizedDescription = item.Description;
                            payItem.countryCode = item.ProductOffers[0].CurrencyCode;
                            payItem.priceCurrencyCode = symbol;
                            payItemsList.Add(payItem);
                            GooglePlayData.instance.SetGoogleProductToken(payItem.product_id, item.ProductOffers[0].OfferToken);
                        }
                    }
                    if (payItemsList.Count == 0)
                    {
                        Debug.Log($"NeoriginPlatformServer google GetPayItems no valid items");
                        callBack?.Invoke(NeoriginSDKStatusCode.PayErrorItems, "NeoriginPlatformServer google GetPayItems no valid items");
                        return;
                    }

                    callBack?.Invoke(NeoriginSDKStatusCode.Success, "Success", payItemsList.ToArray());


                }
                else
                {
                    callBack?.Invoke(NeoriginSDKStatusCode.PayNoItems, $"GetPayItems google Errorcode:{result.Code} message:{result.ErrorMessage}");
                }


            }, TaskScheduler.FromCurrentSynchronizationContext());
            StartOnFocusChanged();
        }

        private void StartOnFocusChanged()
        {
            Debug.Log("开始实行监听");
            base.EnsureCoroutineMonoBehaviour().OnFocusChanged += (state) =>
            {
                if (state)
                {
                    Budan();
                }

            };
            Budan();
        }

        private void Budan()
        {
            Debug.Log("开始补单");
            var task = GooglePlayData.instance.billingClient.QueryPurchasesAsync();
            task.ContinueWith(t => {
                var result = t.Result;
                if (result.IsOk)
                {
                    
                    foreach (var item in result.Value.ProductPurchaseDetails)
                    {
                        Dictionary<string, object> receipt_data_dic = new Dictionary<string, object> {
                            {"orderId",item.OrderId},
                            {"packageName",item.PackageName},
                            {"productId",item.ProductId},
                            {"purchaseTime",item.PurchaseTime.ToUnixTimeMilliseconds()},
                            {"purchaseState",(int)item.PurchaseState},
                            {"purchaseToken",item.PurchaseToken},
                            {"obfuscatedAccountId",item.ObfuscatedAccountId},
                            {"quantity",item.Quantity},
                            {"acknowledged",item.IsAcknowledged},
                        };
                        var order_token_and_serverid = item.ObfuscatedProfileId.Split(":");
                        Dictionary<string, string> resultParams = new Dictionary<string, string>
                        {
                            { "receipt_signature", ""},
                            { "receipt_data",JsonConvert.SerializeObject(receipt_data_dic) },
                            { "transaction_id", item.OrderId},
                            { "order_id", item.ObfuscatedAccountId },
                            { "server_id", order_token_and_serverid[1]},
                            { "order_token",  order_token_and_serverid[0]},
                            { "pay_time",  item.PurchaseTime.ToUnixTimeMilliseconds().ToString()},
                            { "pay_token", item.PurchaseToken},
                        };
                        PayResultReport(resultParams, (code, msg, status, resultResponse) => {
 
                            if (code != NeoriginSDKStatusCode.Success)
                            {
                                Debug.Log($"googlepayImpl budan PayResultRequest Error: {msg},code {code}");
                                NeoriginSDKToastManager.Instance.Show(NeoriginSDK.Instance.GetSDKLangTranslation("pay_fail"));
                            }
                            else
                            {
                                Debug.Log($"budan code {code},status:{status}");
                            }
                        });
                    }
                    if(result.Value.ProductPurchaseDetails.Count>0)
                    {

                        NeoriginSDKCallbackDataPay resultDataCallback = new NeoriginSDKCallbackDataPay
                        {
                            state = 0,
                            extension = "",
                            order_id = result.Value.ProductPurchaseDetails[0].ObfuscatedAccountId
                        };
                        Debug.Log("补单之后关闭支付进行h5");
                        paycheckweb?.CloseWebview();
                        paycheckweb = null;
                    }
                }
                else
                {
                    Debug.Log("没有补单信息");
                }
            }, TaskScheduler.FromCurrentSynchronizationContext());
        }

        protected new void PayResultReport(Dictionary<string, string> resultDict, NeoHttpUtils.HttpRequestCallBack callback)
        {
            Debug.Log("ABasePay PayResultRequest #######:");
            //Debug.Log("NeoriginPlatformServer PayRequest request##############");
            //支付订单结果上报
            string payTime = System.DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
            string resultTime = System.DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
            NeoriginSDKPlatformUserInfo user = NeoriginSDKStorage.LoadPlatformUserInfo();

            resultDict.Add("uuid", user.uuid);
            resultDict.Add("token", user.token);
            resultDict.Add("time", resultTime);
            resultDict.Add("status", "1");

            // 发送POST请求
            NeoHttpUtils.MakePostResult("/order/google/pay", resultDict, callback);
        }


        private (string Symbol, string Amount) SplitFormattedPrice(string formattedPrice)
        {
            if (string.IsNullOrEmpty(formattedPrice))
                return ("", "0.00");

            // 找到第一个数字的位置
            int firstDigitIndex = formattedPrice.IndexOf(formattedPrice.FirstOrDefault(c => char.IsDigit(c)));

            if (firstDigitIndex == -1) // 没有数字
                return ("", "0.00");

            // 符号在数字前面
            string symbol = formattedPrice.Substring(0, firstDigitIndex).Trim();
            string amount = formattedPrice.Substring(firstDigitIndex).Trim();

            // 如果符号为空，可能符号在数字后面
            if (string.IsNullOrEmpty(symbol))
            {
                // 找到最后一个数字的位置
                int lastDigitIndex = formattedPrice.LastIndexOf(formattedPrice.Last(c => char.IsDigit(c)));

                amount = formattedPrice.Substring(0, lastDigitIndex + 1).Trim();
                symbol = formattedPrice.Substring(lastDigitIndex + 1).Trim();
            }
            return (symbol, amount);
        }


        /// <summary>
        /// 生成请求哈希
        /// </summary>
        /// <param name="parameters">参数字典</param>
        /// <returns>SHA-256 哈希值（小写十六进制）</returns>
        public static string GenerateRequestHash(Dictionary<string, string> parameters)
        {
            // 1. 定义不需要参与 Hash 的字段
            // sign: 通常签名本身不参与，避免逻辑死循环
            // integrity_token: 这是结果，还没生成，肯定不参与
            // request_hash: 防止误传
            HashSet<string> excludeKeys = new HashSet<string>
            {
                "sign",
                "integrity_token",
                "request_hash"
            };

            // 2. 过滤参数（移除排除的键）
            var filteredParams = parameters
                .Where(kvp => !excludeKeys.Contains(kvp.Key))
                .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            // 3. 按键名(Key)升序排序
            var sortedParams = filteredParams
                .OrderBy(kvp => kvp.Key)
                .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            // 4. 拼接字符串
            // 格式：key1=value1&key2=value2...
            var kvPairs = new List<string>();
            foreach (var kvp in sortedParams)
            {
                // 确保 value 转为字符串
                string valStr = kvp.Value?.ToString() ?? string.Empty;
                kvPairs.Add($"{kvp.Key}={valStr}");
            }

            string canonicalString = string.Join("&", kvPairs);

            // 调试用：打印拼接后的原文，开发阶段用来和服务端/客户端比对
            // Debug.Log($"Canonical String: {canonicalString}");

            // 5. 计算 SHA-256
            return ComputeSha256Hash(canonicalString);
        }

        /// <summary>
        /// 计算字符串的 SHA-256 哈希值
        /// </summary>
        private static string ComputeSha256Hash(string input)
        {
            using (SHA256 sha256 = SHA256.Create())
            {
                // 将字符串转换为字节数组
                byte[] bytes = Encoding.UTF8.GetBytes(input);

                // 计算哈希值
                byte[] hashBytes = sha256.ComputeHash(bytes);

                // 将字节数组转换为十六进制字符串（小写）
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    builder.Append(hashBytes[i].ToString("x2")); // x2 表示两位小写十六进制
                }

                return builder.ToString();
            }
        }

        private void IntegrityQuitGame()
        {

            NeoriginSDKWebview sdkWebView = new NeoriginSDKWebview(
                          onCloseListener: () =>
                          {
                              // 用户关闭了WebView
                              Debug.Log("OpenCustomerService: User closed the WebView.");
                          }, isShowCloseBtn: false
                      );
            sdkWebView.adjustmentProportion(0.82f, 0.82f);
            string htmlPath = Path.Combine(Application.streamingAssetsPath, "integrity_alert.html");
            string urlParameters = $"?message={NeoriginSDK.Instance.GetSDKLangTranslation("IntegrityMessage")}&exit={NeoriginSDK.Instance.GetSDKLangTranslation("exit")}";
            string h5Url = "file://" + htmlPath+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] == "integrity_quit")
                {
                    Debug.Log("Quit button clicked");
                    Application.Quit();
                }
            });
        }
    }
}
