using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Xml.Linq;
using ThinkingData.Analytics;
using UnityEngine;
using UnityEngine.Networking;
using Debug = UnityEngine.Debug;
using SysDebug = System.Diagnostics.Debug; // 为System.Diagnostics.Debug创建别名
using SysProcess = System.Diagnostics.Process; // 为Process创建别名
using SysProcessStartInfo = System.Diagnostics.ProcessStartInfo;
#if UNITY_STANDALONE_WIN && !UNITY_EDITOR
using Steamworks;
#endif
#if UNITY_ANDROID
using UnityEngine.Android;
#endif


namespace NeoriginPCSDK
{

    public class NeoriginSDK
    {
        // 静态变量保存类的实例
        private static NeoriginSDK instance = null;
        public static readonly string SDKCompany = "Neorigin";

        // 公共访问点
        public static NeoriginSDK Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new NeoriginSDK();
                }
                return instance;
            }
        }
        
        // 初始化标志
        private bool isInitialized = false;
        private bool isDebug = false;
        private string gameVersion;
        private string pcSdkVersion = "1.4.026051509";

        private SystemLanguage _currentLanguage;

        private string _NeoriginSDKCurrentLanguage;
        private bool _agreementPopupReportedInLoginFlow = false;

        private Dictionary<string, string> _NeoriginSDKLanguageDict = new Dictionary<string, string>();
        private Dictionary<string, string> publicParams = new Dictionary<string, string>();

        public Dictionary<string, string> PublicParams
        {
            get => publicParams;
            set => publicParams = value;
        }


        // 私有构造函数
        private NeoriginSDK()
        {
            // 私有构造防止外部实例化
        }


        private NeoriginSDKConfig sdkConfig;

        public NeoriginSDKConfig SDKConfig
        {
            get => sdkConfig;
        }

        private const string decKey = "rM8mg~Y5g2fF*Neorining3ApbEx8rc2";
        private const string decIv = "sdks-secure-iv618";
        private void LoadConfig()
        {
            try
            {

                // 获取当前项目Asset目录
                //string assetsPath = Application.dataPath;
                // 构建配置文件的完整路径
                //string configFilePath = Path.Combine(assetsPath, "SDKScripts", "NeoriginSDKConfig.json");
                //string configFilePath = Path.Combine(Application.dataPath, "SDKScripts/NeoriginSDKConfig.senc");
                var channelconfig = Resources.Load<ChannelConfig>("ChannelConfig");
                ChannelType channeltype = ChannelType.OfficialWebsite;
                if (channelconfig != null)
                {
                    Debug.Log("选择的渠道:" + channelconfig.currentChannel.ToString());
                    channeltype = channelconfig.currentChannel;
                }
                TextAsset configFile = null;
                switch (channeltype)
                {
                    case ChannelType.OfficialWebsite:
                        configFile = Resources.Load<TextAsset>("OfficialWebsite/NeoriginSDKConfig");
                        break;
                    case ChannelType.GooglePlay:
                        configFile = Resources.Load<TextAsset>("GooglePlay/NeoriginSDKConfig");
                        break;
                    case ChannelType.Steam:
                        configFile = Resources.Load<TextAsset>("Steam/NeoriginSDKConfig");
                        break;
                    default:
                        throw new Exception($"NeoriginPlatformFactory Unsupported platform: {channeltype.ToString()}");
                }
                string fileStr = "";
                if (configFile != null)
                {
                    fileStr = configFile.text;
                    Debug.Log("Configuration loaded successfully");
                }
                else
                {
                    throw new FileNotFoundException("Configuration file not found.");
                }
                /*
                // 打印文件路径
                Debug.Log("Configuration file path: " + configFilePath);

                if (!File.Exists(configFilePath))
                {
                    throw new FileNotFoundException("Configuration file not found.");
                }*/

                //string fileStr = File.ReadAllText(configFilePath);
                Debug.Log($"NeoriginSDK Config fileStr {fileStr} # {fileStr.Length}");
                if (string.IsNullOrEmpty(fileStr))
                {
                    throw new FileNotFoundException("Configuration file is empty.");
                }

                //解密
                string json = NeoriginSDKLibrary.DecryptCBC(fileStr, decKey, decIv);
                Debug.Log("NeoriginSDK Config Json " + json);
                sdkConfig = JsonUtility.FromJson<NeoriginSDKConfig>(json);
                /*
                // 从Resources加载（无需路径）
                TextAsset configFile = Resources.Load<TextAsset>("NeoriginSDKConfig");
                if (configFile == null)
                {
                    Debug.Log("Config not found in Resources");
                    return;
                    //throw new FileNotFoundException("Configuration file not found.");
                }

                // 使用配置内容
                string jsonContent = configFile.text;
                var sdkConfig = JsonUtility.FromJson<NeoriginSDKConfig>(jsonContent);

                Debug.Log("Configuration loaded successfully." + JsonUtility.ToJson(sdkConfig, true));
                return;*/
            }
            catch (Exception ex)
            {
                Debug.Log("Failed to load configuration: " + ex.Message);
                throw; // Re-throw the caught exception
            }
        }


        //获取ProjectId
        public static string GetProjectIdFromManifest()
        {
            // 1. 获取文件路径
            // System.AppDomain.CurrentDomain.BaseDirectory 在 PC Build 模式下指向 .exe 所在的文件夹
            // 在 Editor 模式下通常指向项目根目录
            string directory = System.AppDomain.CurrentDomain.BaseDirectory;
            string filePath = Path.Combine(directory, "manifest.xml");

            Debug.Log($"尝试读取 Manifest 文件路径: {filePath}");

            // 2. 检查文件是否存在
            if (!File.Exists(filePath))
            {
                Debug.LogError($"文件未找到: {filePath}");
                return null;
            }

            try
            {
                // 3. 加载 XML
                XDocument doc = XDocument.Load(filePath);

                // 4. 解析节点 Manifest -> Application -> PlayGamesServices -> ProjectId
                // 使用 ?. 操作符防止节点不存在时报错
                string projectId = doc.Element("Manifest")
                                    ?.Element("Application")
                                    ?.Element("PlayGamesServices")
                                    ?.Element("ProjectId")
                                    ?.Value;

                if (string.IsNullOrEmpty(projectId))
                {
                    Debug.LogError("XML 结构解析成功，但 ProjectId 为空或节点不存在。");
                }

                return projectId;
            }
            catch (System.Exception ex)
            {
                Debug.LogError($"读取或解析 XML 时发生错误: {ex.Message}");
                return null;
            }
        }



        /*
         * 检测是否重启游戏
         * true ：需要重启游戏，游戏需要退出   false ：不需要重启游戏, 游戏无需任何操作
         */
        public bool RestartAppIfNecessary()
        {
            #if UNITY_STANDALONE_WIN && !UNITY_EDITOR
            try
            {
                LoadConfig();
            }
            catch (FileNotFoundException ex)
            {
                Debug.Log("RestartAppIfNecessary aborted: " + ex.Message);
                return true;
            }

            // Steam渠道检测 - Steam需要在启动最早期检测
            if (sdkConfig.platform.platformName.ToLower() == "mocosteam")
            {
                Debug.Log("RestartAppIfNecessary: Steam渠道检测");

                // 从配置获取Steam AppID
                string steamAppIdStr = sdkConfig.platform?.platformSteamAppId ?? "480";
                uint steamAppId = uint.Parse(steamAppIdStr);
                // SteamAPI.RestartAppIfNecessary 会在必要时启动Steam客户端并返回true
                // 游戏需要立即退出
                if (SteamAPI.RestartAppIfNecessary((AppId_t)steamAppId))
                {
                    Debug.Log("RestartAppIfNecessary: 需要通过Steam启动，正在启动Steam客户端...");
                    return true;
                }

                Debug.Log("RestartAppIfNecessary: Steam渠道启动检测通过");
                return false;
            }

            string[] args = System.Environment.GetCommandLineArgs();
            if (args.Length > 1)
            {
                // 获取参数是否附带gid=gameid
                if (args[1].ToLower().Contains($"gid={sdkConfig.platform.platformAppId}"))
                {
                    return false;
                }
            }
            
            // 读取NSIS写入的PcLancher.exe的安装路径  C:\Program Files\Neorigin\152
            string launcherInfoPath =
                $@"{NeoriginLauncherInfoPath.InfoPath}\{SDKCompany}\{sdkConfig.platform.platformAppId}\{NeoriginLauncherInfoPath.InfoFileName}";
            if (!File.Exists(launcherInfoPath))
            {
                Debug.Log("RestartAppIfNecessary path not exist:" + launcherInfoPath);
                return false;
            }
            
            var info = JsonUtility.FromJson<NeoriginLauncherInfo>(
                File.ReadAllText(launcherInfoPath)
            );
            if (string.IsNullOrEmpty(info.Install_path))
            {
                Debug.Log("RestartAppIfNecessary file is empty:" + info.Install_path);
                return false;
            }

            if (!File.Exists(info.Install_path))
            {
                Debug.Log("RestartAppIfNecessary file not exist:" + info.Install_path);
                return false;
            }

            // 步骤 1: 尝试激活已运行的 PcLancher 窗口
            if (WinProcessHelper.ActivateExistingLauncherWindow())
            {
                // 如果成功激活，说明程序已经在运行，任务完成
                return true;
            }
                            
            // 存在PcLauncher.exe 启动它
            string exePath = info.Install_path; // 完整路径
            string arg = $"gid={sdkConfig.platform.platformAppId}";
            
            bool success = WinProcessHelper.StartExternalAppWin32(exePath, arg);
    
            if (!success)
            {
                Debug.LogError($"RestartAppIfNecessary WinProcessHelper.StartExternalAppWin32 error");
            }
            Debug.Log("RestartAppIfNecessary launcherProcess: " + info.Install_path);
            return true;
            #else
            try
            {
                Debug.Log("RestartAppIfNecessary load normal");
                LoadConfig();
            }
            catch (FileNotFoundException ex)
            {
                Debug.Log("RestartAppIfNecessary aborted: " + ex.Message);
            } 
            return false;
            #endif
        }

        /**
        * 初始化SDK
        * @return Task
        */
        public delegate void InitCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", NeoriginSDKCallbackDataInit data = null);
        public InitCallBack initCallBack = null;
        public void Init(NeoriginSDKParamsInit initData, InitCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK Version:" + pcSdkVersion);
            Debug.Log("NeoriginSDK Init:" + initData.ToString());
            initCallBack = callBack;
            if (isInitialized)
            {
                callBack?.Invoke(code: NeoriginSDKStatusCode.Success, msg: "SDK is already initialized.");
                return;
            }

            if (sdkConfig == null)
            {
                try
                {
                    LoadConfig();
                }
                catch (FileNotFoundException ex)
                {
                    Debug.Log("Initialization aborted: " + ex.Message);
                    initCallBack?.Invoke(code: NeoriginSDKStatusCode.ConfigNotFound, msg: "Config File NeoriginSDKConfig.json Not Found.");
                    return;
                }
                
                if (sdkConfig == null)
                {
                    Debug.Log("Failed to load SDK configuration. Initialization aborted.");
                    initCallBack?.Invoke(code: NeoriginSDKStatusCode.ConfigLoadFail, msg: "Config File NeoriginSDKConfig.json Load Fail.");
                    return;
                }
            }
            
            gameVersion = initData.gameVersion;
            isDebug = initData?.isDebug ?? false;
            //Debug.Log("NeoriginSDK Config" + JsonUtility.ToJson(sdkConfig, true));
            //获取客户端标识
            NeoriginSDKDevice device = new NeoriginSDKDevice();
            device.deviceID = SystemInfo.deviceUniqueIdentifier;
            device.deviceDpi = NeoriginSDKLibrary.GetScreenResolution();//Screen.dpi.ToString();
            device.deviceGraphicsDeviceID = SystemInfo.graphicsDeviceID.ToString();
            device.deviceOS = SystemInfo.operatingSystem;//操作系统
            device.deviceOSVersion = Environment.OSVersion.VersionString;//操作系统版本
            device.deviceType = SystemInfo.processorType; //CPU型号
            device.deviceLang = Application.systemLanguage;
            device.deviceBrand = NeoriginSDKLibrary.GetPCModel();//品牌型号
            device.deviceDiskTotal = 0;//NeoriginSDKLibrary.GetTotalDiskSpace(); //总存储空间
            device.deviceDiskFree = 0;//NeoriginSDKLibrary.GetFreeDiskSpace(); //剩余存储空间
            device.deviceGraphicsDeviceName = SystemInfo.graphicsDeviceName + " (" + SystemInfo.graphicsMemorySize + " MB)"; //显卡
            device.deviceMemorySize = SystemInfo.systemMemorySize; //内存
            device.deviceMachineName = Environment.MachineName; //机器名
            device.deviceTimeZone = NeoriginSDKLibrary.GetUtcOffset(); //时区
            device.deviceNetFramework = Environment.Version.ToString(); //.net版本
            device.deviceMac = NeoriginSDKLibrary.GetMacAddress(); //MAC地址
            device.deviceNetwork = NeoriginSDKLibrary.GetNetworkType();
            NeoriginSDKStorage.SaveDevice(device);
            Debug.Log("NeoriginPlatformServer deviceMac " + device.deviceMac + "#" + NeoriginSDKLibrary.GetMacAddress() + "#" + SystemInfo.operatingSystem+ "# deviceDpi:" + device.deviceDpi+ "# device.deviceNetwork:"+device.deviceNetwork);

            //初始化方式一
            TDAnalytics.Init(sdkConfig.tdAnalytics.appId, sdkConfig.tdAnalytics.serverUrl);
            //设置访客ID,不做则按数数的来String distinctId = TDAnalytics.GetDistinctId();
            TDAnalytics.SetDistinctId(device.deviceID);
            //开启安装、启动、关闭事件的自动采集
            TDAnalytics.EnableAutoTrack(TDAutoTrackEventType.AppInstall | TDAutoTrackEventType.AppStart | TDAutoTrackEventType.AppEnd | TDAutoTrackEventType.AppCrash);

            //初始化多语言
            _currentLanguage = device.deviceLang;
            InitializeLanguageSystem(device.deviceLang);

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

            if (sdkConfig.platform.platformName == "mocogoogle")
            {
                var cloudProjectNumber=GetProjectIdFromManifest();
                if (cloudProjectNumber != null && !string.IsNullOrEmpty(cloudProjectNumber))
                {
                    GooglePlayData.instance.cloudProjectNumber =long.Parse(cloudProjectNumber);
                }
            }
            //sdkConfig.platform.platformUrl = "http://127.0.0.1:8000";
            //初始化服务端API配置
            NeoriginU8Server.Initialize(sdkConfig.sdk, gameVersion, device);

            //平台初始化
            NeoriginPlatformManager.Initialize(sdkConfig, device,initData, (code, msg, res) =>
            {
                // 初始化成功后
                if (code == NeoriginSDKStatusCode.Success)
                {
                    isInitialized = true;
                    Debug.Log("NeoriginPlatformServer initialized successfully!");

                    //数数用户激活时属性设置
                    Dictionary<string, object> taDic = new Dictionary<string, object>();
                    string deviceTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    taDic.Add("mj_device_active_time", deviceTime);
                    SubmitTAUserInfo(2, "", taDic, (code, msg, data) =>
                    {
                        Debug.Log("SubmitTAUserInfo mj_device_active_time UserSetOnce code: " + code + ", msg: " + msg + ",deviceTime:" + deviceTime);
                    });
                }

                initCallBack?.Invoke(code: code, msg: msg, data: res);
            });


            NeoriginU8Server.AddDevice((response) =>
            {
                if (response.isNetworkError || response.isHttpError)
                {
                    // 处理错误
                    Debug.Log($"Error: {response.error},code {response.responseCode}");
                }
                else
                {
                    // 成功接收到响应
                    string responseData = response.downloadHandler.text;  // 文本信息
                    Debug.Log($"NeoriginU8Server.AddDevice Received: {responseData}");

                    // 如果响应是JSON，您可以进一步处理它：
                    // YourDataType data = JsonUtility.FromJson<YourDataType>(responseData);
                }
            });
        }


        public delegate void LoginCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", NeoriginSDKCallbackDataLogin data = null);
        public LoginCallBack loginCallBack = null;
        public void Login(NeoriginSDKParamsLogin loginData, LoginCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK Login " + loginData.ToString());
            loginCallBack = callBack;
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling Login method.");
                loginCallBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                //提示框弹出
                //NeoriginSDKToastManager.Instance.Show(GetSDKLangTranslation("login_failed"), 2f);
                return;
            }


            //获取缓存
            NeoriginSDKDevice device = new NeoriginSDKDevice();
            device = NeoriginSDKStorage.LoadDevice();
            Debug.Log($"Login loadDevice: {device.deviceID} # {device.deviceDpi} # {device.deviceGraphicsDeviceID}");

            string userAccount = device.deviceID;
            if (!string.IsNullOrWhiteSpace(loginData.account))
            {
                userAccount = loginData.account;
            }
            //调用平台登录
            NeoriginPlatformManager.Login(userAccount, loginData.touristFlag, (code, msg, res) =>
            {
                if (code == NeoriginSDKStatusCode.Success)
                {
                    //调用u8登录接口
                    U8Login(res.sdkUserID, (u8LoginCode, u8LoginMsg, u8LoginData) =>
                    {
                        if (u8LoginCode != NeoriginSDKStatusCode.Success)
                        {
                            loginCallBack?.Invoke(code: u8LoginCode, msg: u8LoginMsg);
                            //提示框弹出
                            NeoriginSDKToastManager.Instance.Show(GetSDKLangTranslation("login_failed"), 2f);
                            return;
                        }

                        //调用登录回调
                        // 自动登录成功也复用 LoginAccountAction 的埋点逻辑，保持口径一致
                        ReportLoginTaFromLoginResult(res, u8LoginData);

                        NeoriginSDKCallbackDataLogin loginData = new NeoriginSDKCallbackDataLogin
                        {
                            userID = u8LoginData.userID,
                            username = u8LoginData.username,
                            sdkUserID = u8LoginData.sdkUserID,
                            sdkUserName = u8LoginData.sdkUserName,
                            token = u8LoginData.token,
                            isNew = u8LoginData.isNew,
                            thirdLoginType = int.Parse(res.thirdLoginType.ToString()),
                            extension = u8LoginData.extension,
                            callbackFrom = 0
                        };
                        loginCallBack?.Invoke(NeoriginSDKStatusCode.Success, "Login Success.", loginData);

                        //提示框弹出
                        NeoriginSDKToastManager.Instance.Show(GetSDKLangTranslation("login_success", formatShowUserName(res.sdkLogUserId, loginData.thirdLoginType)), 2f);
                        return;

                    });
                }
                else
                {
                    loginCallBack?.Invoke(code: code, msg: msg);
                    //提示框弹出
                    //NeoriginSDKToastManager.Instance.Show(GetSDKLangTranslation("login_failed"), 2f);
                }
            });
        }

        private void U8Login(string platformAccount, System.Action<NeoriginSDKStatusCode, string, NeoriginSDKU8UserInfo> u8LoginCallback)
        {
            //调用u8登录接口
            Dictionary<string, string> parameters = new Dictionary<string, string>()
            {
                { "extension", "{\"platformUserName\":\""+platformAccount+"\"}" }
            };
            NeoriginU8Server.GetToken(parameters, (u8response) =>
            {
                if (u8response.isNetworkError || u8response.isHttpError)
                {
                    // 处理错误
                    Debug.Log($"NeoriginU8Server.GetToken Error: {u8response.error},code {u8response.responseCode}");
                    u8LoginCallback?.Invoke(NeoriginSDKStatusCode.BadRequest, $"NeoriginU8Server.GetToken request error.code:{u8response.responseCode},Error:{u8response.error}", null);
                }
                else
                {
                    // 成功接收到响应
                    string u8responseData = u8response.downloadHandler.text;  // 文本信息
                    Debug.Log($"NeoriginU8Server.GetToken Received: {u8responseData}");
                    JObject u8rep = JObject.Parse(u8responseData);
                    int u8state = (int)u8rep["state"];
                    if (u8state != 1)
                    {
                        //Debug.Log($"NeoriginU8Server.GetToken Error: {message}");
                        u8LoginCallback?.Invoke(NeoriginSDKStatusCode.InternalError, $"u8 return error.code:{u8state}", null);
                        return;
                    }
                    JObject repData = (JObject)u8rep["data"];
                    //缓存用户数据
                    NeoriginSDKU8UserInfo userInfo = new NeoriginSDKU8UserInfo
                    {
                        extension = platformAccount,
                        retainedDays = (int)repData["retainedDays"],
                        isNew = (int)repData["isNew"],
                        sdkUserName = (string)repData["sdkUserName"],
                        userID = (long)repData["userID"],
                        sdkUserID = (string)repData["sdkUserID"],
                        username = (string)repData["username"],
                        token = (string)repData["token"]
                    };
                    NeoriginSDKStorage.SaveU8UserInfo(userInfo);
                    u8LoginCallback?.Invoke(NeoriginSDKStatusCode.Success, $"success", userInfo);

                }
            });
        }

        public delegate void LoginAccountCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", NeoriginSDKCallbackDataLoginAccount data = null);
        public LoginAccountCallBack loginAccountCallBack = null;
        public delegate void LoginAccountProcessCallBack(string processAction);
        public LoginAccountProcessCallBack loginAccountProcessCallBack = null;
        public void LoginAccount(NeoriginSDKParamsLogin loginParams, LoginAccountCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK LoginAccount");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling LoginAccount method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            loginAccountCallBack = callBack;
            Debug.Log($"LoginAccount loginParams: {loginParams.loginType} # {loginParams.account} # {loginParams.touristFlag}");

            //根据loginType决定登录方式
            if (loginParams.loginType == 1)
            {
                //仅拉起登录框
                LoginAccountAction(callBack);
                return;
            }
            else
            {
                NeoriginSDKParamsLogin loginParam = new NeoriginSDKParamsLogin
                {
                    account = loginParams.account,
                    touristFlag = loginParams.touristFlag //不允许游客登录
                };
                //先调用登录态登录，失败则拉起登录框
                Login(loginParam, (loginCode, loginMsg, loginData) =>
                {
                    if (loginCode == NeoriginSDKStatusCode.Success)
                    {
                        //已经登录成功
                        NeoriginSDKCallbackDataLoginAccount loginAccountData = new NeoriginSDKCallbackDataLoginAccount
                        {
                            userID = loginData.userID,
                            username = loginData.username,
                            sdkUserID = loginData.sdkUserID,
                            sdkUserName = loginData.sdkUserName,
                            token = loginData.token,
                            isNew = loginData.isNew,
                            thirdLoginType = loginData.thirdLoginType,
                            //extension = loginData.extension,
                            callbackFrom = loginData.callbackFrom,
                            sdkLogUserId = loginData.sdkUserID,
                            sdkLogThirdUserName = loginData.extension
                        };
                        callBack?.Invoke(NeoriginSDKStatusCode.Success, "LoginAccount Success.", loginAccountData);
                        return;
                    }
                    else
                    {
                        //拉起平台登录框
                        LoginAccountAction(callBack);
                        return;
                    }
                });
            }
        }

        //平台登录框
        private void LoginAccountAction(LoginAccountCallBack callBack = null)
        {
            ResetAgreementPopupReportState();
            NeoriginPlatformManager.LoginAccount((code, msg, res) =>
            {
                if (code == NeoriginSDKStatusCode.Success)
                {
                    //上报数数
                    handleLoginTaReport(res);

                    //调用U8登录接口
                    U8Login(res.sdkUserID, (u8LoginCode, u8LoginMsg, u8LoginData) =>
                    {
                        if (u8LoginCode != NeoriginSDKStatusCode.Success)
                        {
                            callBack?.Invoke(code: u8LoginCode, msg: u8LoginMsg);
                            //提示框弹出
                            NeoriginSDKToastManager.Instance.Show(GetSDKLangTranslation("login_failed"), 2f);
                            return;
                        }

                        //调用登录回调
                        res.userID = u8LoginData.userID;
                        res.username = u8LoginData.username;
                        res.token = u8LoginData.token;

                        //提示框弹出
                        NeoriginSDKToastManager.Instance.Show(GetSDKLangTranslation("login_success", formatShowUserName(res.sdkLogUserId + "", res.thirdLoginType)), 2f);
                        callBack?.Invoke(code: code, msg: msg, data: res);
                        return;
                    });
                }
                else
                {
                    //提示框弹出
                    NeoriginSDKToastManager.Instance.Show(GetSDKLangTranslation("login_failed"), 2f);
                    callBack?.Invoke(code: code, msg: msg, data: res);
                }
            }, (processAction) =>
            {
                //中间过程一些处理
                Debug.Log("LoginAccount processAction: " + processAction);
                if (processAction == "reg_policy_agree")
                {
                    ReportAgreementPopupEvent();
                }
            });
        }

        //处理登录注册切换的数数数据上报
        public void ReportAgreementPopupEvent()
        {
            if (_agreementPopupReportedInLoginFlow)
            {
                return;
            }

            _agreementPopupReportedInLoginFlow = true;
            SubmitTAUserInfo(0, "mj_pc_agreement_popup", new Dictionary<string, object>(), (taCode, taMsg, taData) =>
            {
                Debug.Log("SubmitTAUserInfo mj_pc_agreement_popup code: " + taCode + ", msg: " + taMsg);
            });
        }

        public void ResetAgreementPopupReportState()
        {
            _agreementPopupReportedInLoginFlow = false;
        }

        private void handleLoginTaReport(NeoriginSDKCallbackDataLoginAccount res)
        {
            // 1. 数据准备
            NeoriginSDKDevice device = NeoriginSDKStorage.LoadDevice();
            NeoriginSDKPlatformUserInfo user = NeoriginSDKStorage.LoadPlatformUserInfo();
            
            // 2. 基础属性初始化 (通用字段)
            Dictionary<string, object> dicReg = new Dictionary<string, object>
            {
                { "mj_channel", sdkConfig.sdk.u8ChannelId },
                { "bind_account", res.sdkLogThirdUserName },
                { "SDKID", res.sdkLogUserId }
            };

            var bind_pgs_token = "";
            if (user != null && user.bind_third_login_type_detail != null && 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);

            // 3. 预处理：如果是“新用户注册”，提前准备好设备硬件信息（解决重复赋值问题）
            if (res.isNew == 1)
            {
                dicReg.Add("pc_brand", device.deviceBrand);
                dicReg.Add("system_version", device.deviceOSVersion);
                dicReg.Add("graphic_card", device.deviceGraphicsDeviceName);
                dicReg.Add("RAM", device.deviceMemorySize);
                dicReg.Add("processer", device.deviceType);
                dicReg.Add("pc_name", device.deviceMachineName);
                dicReg.Add("system_language", _NeoriginSDKCurrentLanguage);
                dicReg.Add("pc_time_zone", device.deviceTimeZone);
                dicReg.Add("netframework", device.deviceNetFramework);
            }

            // 4. 核心逻辑：按登录类型分发
            if (res.thirdLoginType == 1) // Google
            {
                ProcessChannelReport(res, dicReg, "Google", "mj_bind_Google", true);
            }
            else if (res.thirdLoginType == 6) // 邮箱
            {
                ProcessChannelReport(res, dicReg, "邮箱", "mj_bind_email", false);
            }
            else if (res.thirdLoginType == NeoriginThirdLoginType.ThirdLogin_Steam) // Steam
            {
                ProcessChannelReport(res, dicReg, "Steam", "mj_bind_Steam", false);
            }
        }

        // 提取的通用分发方法：逻辑完全对齐原始代码
        private void ProcessChannelReport(NeoriginSDKCallbackDataLoginAccount res, Dictionary<string, object> baseDic, string accountType, string bindKey, bool needExtraAuthReport)
        {
            // 特殊处理：Google 需要额外上报一个授权事件
            if (needExtraAuthReport)
            {
                Dictionary<string, object> authDic = new Dictionary<string, object>
                {
                    { "mj_channel", sdkConfig.sdk.u8ChannelId },
                    { "SDKID", res.sdkLogUserId }
                };
                SubmitTAUserInfo(0, "mj_pc_google_auth", authDic, (taCode, taMsg, taData) => {
                    Debug.Log($"SubmitTAUserInfo mj_pc_google_auth code: {taCode}, taMsg: {taMsg}");
                });
            }

            if (res.isNew == 1)
            {
                // 注册行为
                baseDic.Add("account_type", accountType);
                SubmitTAUserInfo(0, "mj_pc_creat_account", baseDic, (taCode, taMsg, taData) => {
                    Debug.Log($"SubmitTAUserInfo mj_pc_creat_account ({accountType}) code: {taCode}, taMsg: {taMsg}");
                });

                // 用户属性设置 (UserSet)
                Dictionary<string, object> userSetDic = new Dictionary<string, object>
                {
                    { bindKey, res.sdkLogThirdUserName },
                    { "mj_register_time", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") }
                };
                SubmitTAUserInfo(2, "", userSetDic, (taCode, taMsg, taData) => {
                    Debug.Log($"SubmitTAUserInfo {bindKey} UserSet code: {taCode}, msg: {taMsg}");
                });
            }
            else
            {
                // 登录行为
                baseDic.Add("mj_login_method", accountType);
                SubmitTAUserInfo(0, "mj_pc_login_account", baseDic, (taCode, taMsg, taData) => {
                    Debug.Log($"SubmitTAUserInfo mj_pc_login_account ({accountType}) code: {taCode}, taMsg: {taMsg}");
                });
            }
        }

        private void ReportLoginTaFromLoginResult(NeoriginSDKCallbackDataLogin loginRes, NeoriginSDKU8UserInfo u8LoginData)
        {
            if (loginRes == null)
            {
                return;
            }

            NeoriginSDKCallbackDataLoginAccount reportData = new NeoriginSDKCallbackDataLoginAccount
            {
                sdkUserID = !string.IsNullOrEmpty(u8LoginData?.sdkUserID) ? u8LoginData.sdkUserID : loginRes.sdkUserID,
                sdkUserName = !string.IsNullOrEmpty(u8LoginData?.sdkUserName) ? u8LoginData.sdkUserName : loginRes.sdkUserName,
                sdkLogUserId = !string.IsNullOrEmpty(loginRes.sdkLogUserId)
                    ? loginRes.sdkLogUserId
                    : (!string.IsNullOrEmpty(u8LoginData?.sdkUserID) ? u8LoginData.sdkUserID : loginRes.sdkUserID),
                sdkLogThirdUserName = !string.IsNullOrEmpty(loginRes.sdkLogThirdUserName) ? loginRes.sdkLogThirdUserName : loginRes.extension,
                isNew = u8LoginData != null ? u8LoginData.isNew : loginRes.isNew,
                thirdLoginType = loginRes.thirdLoginType
            };

            handleLoginTaReport(reportData);
        }

        private string formatShowUserName(string displayName, int loginType)
        {
            if (string.IsNullOrEmpty(displayName))
            {
                return "";
            }

            string showLoginType;   // MVFN: 默认游客
            switch (loginType)
            {
                case NeoriginThirdLoginType.ThirdLogin_Google:
                  showLoginType = "GOGL";
                  break;
                case NeoriginThirdLoginType.ThirdLogin_Email:
                  showLoginType = "Email";
                  break;
                case NeoriginThirdLoginType.ThirdLogin_Steam:
                  showLoginType = "Steam";
                  break;
                default:
                  showLoginType = "MVFN";
                  break;
            }
            return $"{showLoginType}:{displayName}";
        }

        private void InitializeLanguageSystem(SystemLanguage language)
        {
            Debug.Log("InitializeLanguageSystem: language: " + language.ToString());

            string languageCode = "en";
            switch (language)
            {
                case SystemLanguage.ChineseSimplified:
                    languageCode = "zh-CN";
                    break;
                case SystemLanguage.ChineseTraditional:
                    languageCode = "zh-TW";
                    break;
                case SystemLanguage.Japanese:
                    languageCode = "ja";
                    break;
                case SystemLanguage.Korean:
                    languageCode = "ko";
                    break;
                default:
                    languageCode = "en";
                    break;
            }
            _NeoriginSDKCurrentLanguage = languageCode;

            TextAsset configFile = Resources.Load<TextAsset>($"NeoriginSDKLanguages/{languageCode}");
            string fileStr = "";
            if (configFile != null)
            {
                fileStr = configFile.text;
                Debug.Log("InitializeLanguageSystem Configuration loaded successfully");
            }
            else
            {
                throw new FileNotFoundException("InitializeLanguageSystem Configuration file not found.");
            }
            /*
            string configFilePath = Path.Combine(Application.dataPath, $"SDKScripts/NeoriginSDKLanguages/{languageCode}.json");

            if (!File.Exists(configFilePath))
            {
                throw new FileNotFoundException($"InitializeLanguageSystem Lang Configuration file not found.{configFilePath}");
            }

            string fileStr = File.ReadAllText(configFilePath);*/
            if (string.IsNullOrEmpty(fileStr))
            {
                throw new FileNotFoundException("InitializeLanguageSystem Lang Configuration file is empty.");
            }

            _NeoriginSDKLanguageDict.Clear();

            try
            {
                NeoriginSDKLanguageData langData = JsonUtility.FromJson<NeoriginSDKLanguageData>(fileStr);
                foreach (var entry in langData.entries)
                {
                    _NeoriginSDKLanguageDict[entry.key] = entry.value;
                }
                Debug.Log($"InitializeLanguageSystem Language loaded: {_currentLanguage}");
            }
            catch (Exception e)
            {
                Debug.Log($"InitializeLanguageSystem Error parsing language file: {e.Message}");
            }
        }
        //多语言翻译方法，对外展示需调用此方法
        public string GetSDKLangTranslation(string key, params object[] args)
        {
            if (_NeoriginSDKLanguageDict.TryGetValue(key, out string value))
            {
                return string.Format(value, args);
            }

            Debug.LogWarning($"[SDK] Translation key not found: {key}");
            return $"<{key}>";
        }


        public delegate void OpenUserCenterCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", NeoriginSDKCallbackDataLoginAccount data = null);
        public OpenUserCenterCallBack openUserCenterCallBack = null;
        public delegate void OpenUserCenterProcessCallBack(string processAction, NeoriginSDKCallbackDataLoginAccount data = null);
        public OpenUserCenterProcessCallBack openUserCenterProcessCallBack = null;
        //打开用户中心
        public void OpenUserCenter(OpenUserCenterCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK OpenUserCenter");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling OpenUserCenter method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            openUserCenterCallBack = callBack;

            NeoriginSDKU8UserExtraData u8Role = NeoriginSDKStorage.LoadU8RoleInfo();

            NeoriginSDKCallbackDataUserInfo u8User = new NeoriginSDKCallbackDataUserInfo();
            GetU8userInfo(u8User, (infoCode,infoMsg,infoRes) =>
            {
                NeoriginPlatformManager.OpenUserCenter(u8User,u8Role,(code, msg, res) =>
                {
                    if (code == NeoriginSDKStatusCode.Success)
                    {
                        if (res.callbackFrom == 2)
                        {
                            //上报数数
                            handleLoginTaReport(res);
                            //假如是操作了切换账号，需要重新调用U8登录接口
                            U8Login(res.sdkUserID, (u8LoginCode, u8LoginMsg, u8LoginData) =>
                            {
                                if (u8LoginCode != NeoriginSDKStatusCode.Success)
                                {
                                    callBack?.Invoke(code: u8LoginCode, msg: u8LoginMsg);
                                    //提示框弹出
                                    NeoriginSDKToastManager.Instance.Show(GetSDKLangTranslation("login_failed"), 2f);
                                    return;
                                }

                                //调用登录回调
                                res.userID = u8LoginData.userID;
                                res.username = u8LoginData.username;

                                //提示框弹出
                                NeoriginSDKToastManager.Instance.Show(GetSDKLangTranslation("login_success", formatShowUserName(res.sdkLogUserId + "", res.thirdLoginType)), 2f);
                                callBack?.Invoke(code: code, msg: msg, data: res);
                                return;

                            });
                        }
                        callBack?.Invoke(code: code, msg: msg, data: res);
                        return;
                    }
                    else
                    {
                        //提示框弹出
                        //NeoriginSDKToastManager.Instance.Show(GetSDKLangTranslation("login_failed"), 2f);
                        callBack?.Invoke(code: code, msg: msg, data: res);
                    }

                }, (processAction, processData) =>
                {
                    //中间过程一些处理
                    if (processAction == "ucenter_policy_entry")
                    {
                        //用户中心点击协议，上报数数
                        SubmitTAUserInfo(0, "mj_pc_agreement_entry", new Dictionary<string, object>(), (taCode, taMsg, taData) =>
                        {
                            Debug.Log("SubmitTAUserInfo mj_pc_agreement_entry code: " + taCode + ", msg: " + taMsg);
                        });
                    }
                    else if (processAction == "ucenter_userservice_click")
                    {
                        //用户中心点击客服，上报数数
                        SubmitTAUserInfo(0, "mj_customerservice", new Dictionary<string, object>(), (taCode, taMsg, taData) =>
                        {
                            Debug.Log("SubmitTAUserInfo mj_customerservice code: " + taCode + ", msg: " + taMsg);
                        });
                    }
                    else if (processAction == "bind_mail" || processAction == "bind_google")
                    {
                        //绑定上报
                        NeoriginSDKU8UserExtraData roleInfo = NeoriginSDKStorage.LoadU8RoleInfo();
                        Dictionary<string, object> dic = new Dictionary<string, object>();
                        dic.Add("mj_channel", sdkConfig.sdk.u8ChannelId);
                        dic.Add("SDKID", processData.sdkLogUserId);
                        dic.Add("bind_account", processData.sdkLogThirdUserName);
                        if (processAction == "bind_mail")
                        {
                            dic.Add("mj_bind_name", "邮箱");
                            Dictionary<string, object> taDic = new Dictionary<string, object>();
                            taDic.Add("mj_bind_email", processData.sdkLogThirdUserName);
                            SubmitTAUserInfo(2, "", taDic, (taCode, taMsg, taData) =>
                            {
                                Debug.Log("SubmitTAUserInfo mj_bind_email2 UserSet code: " + taCode + ", msg: " + taMsg);
                            });
                        }
                        else
                        {
                            dic.Add("mj_bind_name", "Google");
                            Dictionary<string, object> taDic = new Dictionary<string, object>();
                            taDic.Add("mj_bind_Google", processData.sdkLogThirdUserName);
                            SubmitTAUserInfo(2, "", taDic, (taCode, taMsg, taData) =>
                            {
                                Debug.Log("SubmitTAUserInfo mj_bind_Google2 UserSet code: " + taCode + ", msg: " + taMsg);
                            });
                        }
                        dic.Add("role_id", roleInfo.roleID);
                        dic.Add("role_name", roleInfo.roleName);
                        dic.Add("server_name", roleInfo.serverName);
                        SubmitTAUserInfo(0, "mj_pc_bind_account", dic, (taCode, taMsg, taData) =>
                        {
                            Debug.Log("SubmitTAUserInfo mj_pc_bind_account code: " + taCode + ", taMsg: " + taMsg);
                        });
                    }

                });
                
            });

            

        }


        public delegate void OpenCustomerServiceCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", string data = null);
        public OpenCustomerServiceCallBack openCustomerServiceCallBack = null;
        //打开用户中心
        public void OpenCustomerService(OpenCustomerServiceCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK OpenCustomerService");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling OpenCustomerService method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            openCustomerServiceCallBack = callBack;

            NeoriginSDKU8UserExtraData u8Role = NeoriginSDKStorage.LoadU8RoleInfo();

            NeoriginSDKCallbackDataUserInfo u8User = new NeoriginSDKCallbackDataUserInfo();
            GetU8userInfo(u8User, (infoCode,infoMsg,infoRes) =>
            {
                if (infoCode == NeoriginSDKStatusCode.Success)
                {
                    NeoriginPlatformManager.OpenCustomerService(u8User, u8Role,(code, msg, res) =>
                    {
                        if (code == NeoriginSDKStatusCode.Success)
                        {
                            SubmitTAUserInfo(0, "mj_customerservice", new Dictionary<string, object>(), (taCode, taMsg, taData) =>
                            {
                                Debug.Log("SubmitTAUserInfo mj_customerservice code: " + taCode + ", msg: " + taMsg);
                            });
                        }
                        callBack?.Invoke(code: code, msg: msg, data: res);
                    });
                }
                else
                {
                    callBack?.Invoke(code: infoCode, msg: infoMsg, data: null);
                }
                
            });
        }


        public delegate void OpenPolicyCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", string data = null);
        public OpenPolicyCallBack openPolicyCallBack = null;
        //打开用户中心
        public void OpenPolicy(OpenPolicyCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK OpenPolicy");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling OpenPolicy method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            openPolicyCallBack = callBack;

            //上报数数
            SubmitTAUserInfo(0, "mj_pc_agreement_entry", new Dictionary<string, object>(), (code, msg, data) =>
            {
                Debug.Log("SubmitTAUserInfo mj_pc_agreement_entry code: " + code + ", msg: " + msg);
            });

            NeoriginPlatformManager.OpenPolicy((code, msg, res) =>
            {
                callBack?.Invoke(code: code, msg: msg, data: res);
            });

        }


        public delegate void GetConfigCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", string data = "");
        public GetConfigCallBack getConfigCallBack = null;
        //打开用户中心
        public void GetConfig(string k, GetConfigCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK GetConfig");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling GetConfig method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            getConfigCallBack = callBack;
            if (k != "NeoriginSDKConfig2jaksdfj#123aksdfj")
            {
                callBack?.Invoke(NeoriginSDKStatusCode.ParameterError, "GetConfig Fail ", "");
                return;
            }
            callBack?.Invoke(NeoriginSDKStatusCode.Success, "GetConfig Success ", JsonConvert.SerializeObject(sdkConfig, Formatting.Indented));

        }

        public delegate void GetDeviceInfoCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", string data = "");
        public GetDeviceInfoCallBack getDeviceInfoCallBack = null;
        //打开用户中心
        public void GetDeviceInfo(GetDeviceInfoCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK GetDeviceInfo");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling GetDeviceInfo method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            getDeviceInfoCallBack = callBack;
            NeoriginSDKDevice device = NeoriginSDKStorage.LoadDevice();
            callBack?.Invoke(NeoriginSDKStatusCode.Success, "GetDeviceInfo Success ", JsonConvert.SerializeObject(device, Formatting.Indented));

        }

        public delegate void SubmitExtraDataCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", string data = "");
        public SubmitExtraDataCallBack submitExtraCallBack = null;
        //上报数据
        public void SubmitExtraData(NeoriginSDKU8UserExtraData extraData, SubmitExtraDataCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK SubmitExtraData");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling SubmitExtraData method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            submitExtraCallBack = callBack;

            //判断参数
            if (extraData != null && extraData.dataType != NeoriginSDKU8UserExtraDataType.None)
            {
                NeoriginSDKU8UserInfo userInfo = NeoriginSDKStorage.LoadU8UserInfo();
                //上报U8
                if (extraData.dataType == NeoriginSDKU8UserExtraDataType.TYPE_CREATE_ROLE || extraData.dataType == NeoriginSDKU8UserExtraDataType.TYPE_LOGIN_ROLE || extraData.dataType == NeoriginSDKU8UserExtraDataType.TYPE_ENTER_GAME)
                {
                    NeoriginU8Server.AddUserLog(userInfo, extraData, (response) =>
                    {
                        if (response.isNetworkError || response.isHttpError)
                        {
                            // 处理错误
                            Debug.Log($"NeoriginU8Server.SubmitExtraData Error: {response.error},code {response.responseCode}");
                            callBack?.Invoke(NeoriginSDKStatusCode.BadRequest, $"NeoriginU8Server.SubmitExtraData request error.code:{response.responseCode},Error:{response.error}", "");
                            return;
                        }
                        else
                        {
                            // 成功接收到响应
                            string responseData = response.downloadHandler.text;  // 文本信息
                            Debug.Log($"NeoriginU8Server.SubmitExtraData Received: {responseData}");
                            JObject rep = JObject.Parse(responseData);
                            int errorCode = (int)rep["state"];
                            string message = (string)rep["msg"];
                            Debug.Log($"NeoriginU8Server.SubmitExtraData rep: {errorCode} # {message}");
                            if (errorCode != 1)
                            {
                                Debug.Log($"NeoriginU8Server.SubmitExtraData Error: {message}");
                                callBack?.Invoke(NeoriginSDKStatusCode.InternalError, $"u8 return error.code:{errorCode},message:{message}", "");
                                return;
                            }
                            NeoriginSDKStorage.SaveU8RoleInfo(extraData);

                            callBack?.Invoke(NeoriginSDKStatusCode.Success, "SubmitExtraData Success ", "");
                        }
                    });
                }
                //获取平台用户信息
                NeoriginSDKPlatformUserInfo platformUserInfo = NeoriginPlatformManager.GetPlatformUserInfo();
                Dictionary<string, object> dic = new Dictionary<string, object>();
                dic.Add("role_id", extraData.roleID);
                dic.Add("role_name", extraData.roleName);
                dic.Add("server_name", extraData.serverName);
                dic.Add("server_id", extraData.serverID);
                dic.Add("mj_channel", sdkConfig.sdk.u8ChannelId);
                dic.Add("SDKID", platformUserInfo.displayName);

                //上报数数
                if (extraData.dataType == NeoriginSDKU8UserExtraDataType.TYPE_CREATE_ROLE)
                {
                    //设置数数account_id
                    TDAnalytics.Login(extraData.serverID + "_" + extraData.roleID);
                    //创建角色
                    SubmitTAUserInfo(0, "mj_pc_create_role", dic, (code, msg, data) =>
                    {
                        Debug.Log("SubmitTAUserInfo TYPE_CREATE_ROLE code: " + code + ", msg: " + msg);
                    });

                    //用户属性
                    Dictionary<string, object> roleDic = new Dictionary<string, object>();
                    roleDic.Add("mj_role_name", extraData.roleName);
                    SubmitTAUserInfo(1, "", roleDic, (code, msg, data) =>
                    {
                        Debug.Log("SubmitTAUserInfo TYPE_CREATE_ROLE UserSet code: " + code + ", msg: " + msg);
                    });
                    //一次性用户属性
                    Dictionary<string, object> roleOnceDic = new Dictionary<string, object>();
                    roleOnceDic.Add("mj_role_id", extraData.roleID);
                    roleOnceDic.Add("mj_rolename", extraData.roleName);
                    roleOnceDic.Add("mj_server_id", extraData.serverID);
                    roleOnceDic.Add("mj_register_platform", "PC");
                    NeoriginSDKDevice device = NeoriginSDKStorage.LoadDevice();
                    roleOnceDic.Add("mj_device_number", device.deviceID);
                    string roleCreateTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    roleOnceDic.Add("mj_role_create_time", roleCreateTime);
                    roleOnceDic.Add("mj_version_sdk", pcSdkVersion);
                    roleOnceDic.Add("mj_channel_id", sdkConfig.sdk.u8ChannelId);
                    roleOnceDic.Add("mj_version_game", gameVersion);
                    SubmitTAUserInfo(2, "", roleOnceDic, (code, msg, data) =>
                    {
                        Debug.Log("SubmitTAUserInfo TYPE_CREATE_ROLE UserSetOnce code: " + code + ", msg: " + msg);
                    });

                }
                else if (extraData.dataType == NeoriginSDKU8UserExtraDataType.TYPE_LOGIN_ROLE || extraData.dataType == NeoriginSDKU8UserExtraDataType.TYPE_ENTER_GAME)
                {
                    //设置数数account_id
                    TDAnalytics.Login(extraData.serverID + "_" + extraData.roleID);
                    //登录角色
                    SubmitTAUserInfo(0, "mj_pc_login_role", dic, (code, msg, data) =>
                    {
                        Debug.Log("SubmitTAUserInfo TYPE_LOGIN_ROLE code: " + code + ", msg: " + msg);
                    });

                    //用户属性
                    Dictionary<string, object> roleDic = new Dictionary<string, object>();
                    roleDic.Add("mj_role_name", extraData.roleName);
                    SubmitTAUserInfo(1, "", roleDic, (code, msg, data) =>
                    {
                        Debug.Log("SubmitTAUserInfo TYPE_LOGIN_ROLE UserSet code: " + code + ", msg: " + msg);
                    });
                }
                else if (extraData.dataType == NeoriginSDKU8UserExtraDataType.TYPE_CHANGE_ROLE)
                {
                    //切换角色
                    SubmitTAUserInfo(0, "mj_pc_change_role", dic, (code, msg, data) =>
                    {
                        Debug.Log("SubmitTAUserInfo TYPE_CHANGE_ROLE code: " + code + ", msg: " + msg);
                    });

                    Dictionary<string, object> roleDic = new Dictionary<string, object>();
                    roleDic.Add("mj_role_name", extraData.roleName);
                    SubmitTAUserInfo(1, "", roleDic, (code, msg, data) =>
                    {
                        Debug.Log("SubmitTAUserInfo TYPE_CHANGE_ROLE UserSet code: " + code + ", msg: " + msg);
                    });
                }
                //callBack?.Invoke(NeoriginSDKStatusCode.Success, "SubmitExtraData Success ","");

            }
            else
            {
                Debug.Log("SubmitExtraData parameters are invalid.");
                callBack?.Invoke(NeoriginSDKStatusCode.ParameterError, "SubmitExtraData Fail ", "");
                return;
            }

        }

        public delegate void SubmitTAUserInfoCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", string data = "");
        public SubmitTAUserInfoCallBack submitTAUserInfoCallBack = null;
        //上报数数
        public void SubmitTAUserInfo(int eventType, string eventId, Dictionary<string, object> properties, SubmitTAUserInfoCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK SubmitTAUserInfo");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling SubmitTAUserInfo method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            submitTAUserInfoCallBack = callBack;

            //判断参数
            if (eventType == 0)
            {
                //事件上报
                if (string.IsNullOrEmpty(eventId))
                {
                    Debug.Log("SubmitTAUserInfo eventId is empty.");
                    callBack?.Invoke(NeoriginSDKStatusCode.ParameterError, "SubmitTAUserInfo eventId is empty.", "");
                    return;
                }
                TDAnalytics.Track(eventId, properties);

            }
            else if (eventType == 1)
            {
                //用户数据上报set
                TDAnalytics.UserSet(properties);
            }
            else if (eventType == 2)
            {
                //用户数据上报setOnce
                TDAnalytics.UserSetOnce(properties);
            }
            else if (eventType == 3)
            {
                //用户数据上报add
                TDAnalytics.UserAdd(properties);
            }
            else if (eventType == 6)
            {
                //设置一次性事件上报
                TDFirstEventModel firstEventModel = new TDFirstEventModel(eventId, "first_check_id");
                firstEventModel.Properties = properties;
                TDAnalytics.Track(firstEventModel);
            }
            else if (eventType == 7)
            {
                //设置可更新事件上报
                TDUpdatableEventModel updatableEventModel = new TDUpdatableEventModel("updatable_event", eventId);
                updatableEventModel.Properties = properties;
                TDAnalytics.Track(updatableEventModel);
            }
            else
            {
                Debug.Log("SubmitTAUserInfo parameters are invalid.");
                callBack?.Invoke(NeoriginSDKStatusCode.ParameterError, "SubmitTAUserInfo parameters error ", "");
                return;
            }
            callBack?.Invoke(NeoriginSDKStatusCode.Success, "SubmitTAUserInfo success ", "");

        }

        public delegate void PayCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", NeoriginSDKCallbackDataPay data = null);
        public PayCallBack payCallBack = null;
        public delegate void PayProcessCallBack(NeoriginSDKCallbackDataPayProcess data = null);
        public PayCallBack payProcessCallBack = null;
        //上报数数
        public void Pay(NeoriginSDKU8PayData payParams, PayCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK Pay");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling Pay method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            payCallBack = callBack;
            NeoriginSDKU8UserInfo u8User = NeoriginSDKStorage.LoadU8UserInfo();

            // 获取U8订单号
            NeoriginU8Server.GetOrderID(u8User, payParams, (u8response) =>
            {
                if (u8response.isNetworkError || u8response.isHttpError)
                {
                    // 处理错误
                    Debug.Log($"NeoriginU8Server.GetOrderID Error: {u8response.error},code {u8response.responseCode}");
                    payCallBack?.Invoke(NeoriginSDKStatusCode.BadRequest, $"NeoriginU8Server.GetOrderID request error.code:{u8response.responseCode},Error:{u8response.error}", null);
                }
                else
                {
                    // 成功接收到响应
                    string u8responseData = u8response.downloadHandler.text;  // 文本信息
                    Debug.Log($"NeoriginU8Server.GetOrderID Received: {u8responseData}");
                    JObject u8rep = JObject.Parse(u8responseData);
                    int u8state = (int)u8rep["state"];
                    if (u8state != 1)
                    {
                        payCallBack?.Invoke(NeoriginSDKStatusCode.InternalError, $"u8 return error.code:{u8state}", null);
                        return;
                    }
                    JObject repData = (JObject)u8rep["data"];



                    //调用平台支付
                    string gameOrderId = (string)repData["orderID"];
                    string extension = (string)repData["extension"];
                    float amount = (float)((payParams.price * payParams.buyNum) / 100.0f);
                    NeoriginSDKPlatformPayParameter platformPayParams = new NeoriginSDKPlatformPayParameter
                    {
                        game_order_id = gameOrderId,
                        server_id = payParams.serverId,
                        role_name = payParams.roleName,
                        role_id = payParams.roleID,
                        desc = payParams.productName,
                        product_id = payParams.productId,
                        extra = extension,
                        order_money = amount,
                    };
                    NeoriginPlatformManager.Pay(platformPayParams, (payCode, payMsg, payData) =>
                    {
                        if (payCode != NeoriginSDKStatusCode.Success)
                        {
                            payCallBack?.Invoke(payCode, payMsg, payData);
                            return;
                        }
                        //提示框弹出
                        NeoriginSDKToastManager.Instance.Show(GetSDKLangTranslation("pay_success"), 2f);
                        payCallBack?.Invoke(payCode, payMsg, payData);


                    }, (processData) =>
                    {
                        try
                        {
                            if (processData == null)
                            {
                                Debug.LogWarning("NeoriginU8Server.PayProcessCallBack: processData is null");
                                return;
                            }

                            Debug.Log($"NeoriginU8Server.PayProcessCallBack Received: " +
                                    $"{processData.process_state}, " +
                                    $"{processData.platform_order_id ?? "null"}, " +
                                    $"{processData.game_order_id ?? "null"}, " +
                                    $"{processData.product_id ?? "null"}, " +
                                    $"{processData.pay_channel_order_id ?? "null"}, " +
                                    $"{processData.pay_channel_id ?? "null"}, " +
                                    $"{processData.order_time?.ToString() ?? "null"}, " +
                                    $"{processData.order_money}");
                            if (processData.process_state == 0)
                            {
                                //上报数数
                                Dictionary<string, object> dic = new Dictionary<string, object>();
                                dic.Add("mj_product_id", processData.product_id);
                                dic.Add("mj_order_id", processData.pay_channel_order_id);
                                dic.Add("mj_receipt_id", processData.platform_order_id);
                                dic.Add("mj_num", processData.order_money);
                                dic.Add("mj_order_time", processData.order_time);
                                dic.Add("mj_channel", sdkConfig.sdk.u8ChannelId);
                                SubmitTAUserInfo(0, "mj_pc_order_init", dic, (taCode, taMsg, taData) =>
                                {
                                    Debug.Log("SubmitTAUserInfo mj_pc_order_init code: " + taCode + ", taMsg: " + taMsg);
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.Log($"NeoriginU8Server.PayProcessCallBack error: {ex.Message}");
                        }

                    });
                }
            });
        }

        public delegate void GetUserInfoCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", NeoriginSDKCallbackDataUserInfo data = null);
        public GetUserInfoCallBack getUserInfoCallBack = null;
        //获取用户信息
        public void GetUserInfo(GetUserInfoCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK GetUserInfo");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling GetUserInfo method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            getUserInfoCallBack = callBack;
            NeoriginPlatformManager.GetUserInfo((code, msg, res) =>
            {
                if (code == NeoriginSDKStatusCode.Success)
                {
                    GetU8userInfo(res, callBack);
                    return;
                }
                callBack?.Invoke(code: code, msg: msg, data: res);
            });
        }

        private void GetU8userInfo(NeoriginSDKCallbackDataUserInfo res,GetUserInfoCallBack callBack = null)
        {
            NeoriginSDKU8UserInfo u8User = NeoriginSDKStorage.LoadU8UserInfo();
            if (u8User == null)
            {
                Debug.Log("GetUserInfo u8User is null, please login first.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.U8UserNotLogin, msg: "u8User is null, please login first.", data: null);
                return;
            }
            res.userID = u8User.userID;
            res.username = u8User.username;
            NeoriginU8Server.GetUserInfo(u8User, (response) =>
            {
                if (response.isNetworkError || response.isHttpError)
                {
                    // 处理错误
                    Debug.Log($"NeoriginU8Server.GetUserInfo Error: {response.error},code {response.responseCode}");
                    callBack?.Invoke(NeoriginSDKStatusCode.BadRequest, $"NeoriginU8Server.GetUserInfo request error.code:{response.responseCode},Error:{response.error}", null);
                    return;
                }
                else
                {
                    // 成功接收到响应
                    string responseData = response.downloadHandler.text;  // 文本信息
                    Debug.Log($"NeoriginU8Server.GetUserInfo Received: {responseData}");
                    JObject rep = JObject.Parse(responseData);
                    int errorCode = (int)rep["state"];
                    string message = (string)rep["msg"];
                    Debug.Log($"NeoriginU8Server.GetUserInfo rep: {errorCode} # {message}");
                    if (errorCode != 1)
                    {
                        Debug.Log($"NeoriginU8Server.GetUserInfo Error: {message}");
                        callBack?.Invoke(NeoriginSDKStatusCode.InternalError, $"u8 return error.code:{errorCode},message:{message}", null);
                        return;
                    }

                    JObject repData = (JObject)rep["data"];

                    res.country = (string)repData["country"];
                    res.totalCharge = (float)repData["totalCharge"];
                    res.totalChargeNum = (int)repData["totalChargeNum"];
                    res.regTime = (string)repData["regTime"];
                    res.firstChargeTime = (string)repData["firstChargeTime"];
                    res.currentCountry = (string)repData["currentCountry"];
                    res.lastChargeTime = (string)repData["lastChargeTime"];
                    res.retainedDays = (string)repData["retainedDays"];

                    callBack?.Invoke(code: NeoriginSDKStatusCode.Success, msg: "GetInfo Success", data: res);
                }
            });
        }

        public delegate void GetPayItemsCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", NeoriginSDKCallbackDataPayItem[] data = null);
        public GetPayItemsCallBack getPayItemsCallBack = null;
        //获取用户信息
        public void GetPayItems(GetPayItemsCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK GetPayItems");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling GetPayItems method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            getPayItemsCallBack = callBack;
            NeoriginPlatformManager.GetPayItems((code, msg, res) =>
            {

                callBack?.Invoke(code: code, msg: msg, data: res);
            });


        }

        public delegate void LogoutCallBack(NeoriginSDKStatusCode code = NeoriginSDKStatusCode.Success, string msg = "", string data = null);
        public LogoutCallBack logoutCallBack = null;
        //获取用户信息
        public void Logout(LogoutCallBack callBack = null)
        {
            Debug.Log("NeoriginSDK Logout");
            if (!isInitialized)
            {
                Debug.Log("Please initialize SDK before calling Logout method.");
                callBack?.Invoke(code: NeoriginSDKStatusCode.NotInited, msg: "SDK Not Inited.");
                return;
            }
            logoutCallBack = callBack;
            NeoriginPlatformManager.Logout((code, msg, res) =>{
                
                NeoriginSDKStorage.DeleteU8UserInfo();
                NeoriginSDKStorage.DeleteU8RoleInfo();
                callBack?.Invoke(code: code, msg: msg, data: res);
            });


        }

    }
}

