package com.haraichi.top.Java;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class MainActivity extends AppCompatActivity {
    public static final String APPID = "应用标识常量";
    public static final String APPKEY = "应用KEY";
    public static final String RC4_KEY = "加密KEY";
    public static final String VERSION = "1.0";

    private long downloadId = -1;
    private BroadcastReceiver downloadReceiver;
    private DownloadManager downloadManager;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        try {
            verificationSystem(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (downloadReceiver != null) {
            try {
                unregisterReceiver(downloadReceiver);
            } catch (IllegalArgumentException e) {
                // Ignore
            }
        }
    }

    public static void verificationSystem(final Context context) {
        try {
            final String MARKCODE = getOrCreateMarkCode(context);
            final long timestamp = System.currentTimeMillis() / 1000;

            if (!isCardValid(context)) {
                showLoginDialog(context, MARKCODE, timestamp);
            }

            checkAutoLogin(context, MARKCODE, timestamp);
            showNotice(context);
            checkVersion(context);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean isCardValid(Context context) {
        try {
            File cardFile = new File(getCardFilePath(context));
            return cardFile.exists() && cardFile.length() > 0;
        } catch (Exception e) {
            return false;
        }
    }

    private static void checkAutoLogin(final Context context, final String MARKCODE, final long timestamp) {
        if (!isCardValid(context)) {
            return;
        }

        new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String card = readFile(getCardFilePath(context));
                        if (card == null || card.trim().isEmpty()) {
                            return;
                        }

                        card = card.trim();
                        final long currentTimestamp = System.currentTimeMillis() / 1000;
                        final String value = String.valueOf(new Random().nextInt(89999) + 1000) + currentTimestamp;

                        final String signStr = "kami=" + card + "&markcode=" + MARKCODE + "&t=" + currentTimestamp + "&" + APPKEY;
                        final String sign = md5(signStr);
                        final String dataStr = "kami=" + card + "&markcode=" + MARKCODE + "&t=" + currentTimestamp + "&sign=" + sign + "&value=" + value;
                        final String encryptedData = rc4Encrypt(dataStr, RC4_KEY);

                        final String response = makeRequest("https://haraichi.top/api.php?api=kmlogon&app=" + APPID + "&data=" + encryptedData);

                        Log.d("Verification", "自动登录响应: " + response);

                        ((Activity) context).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        final String code = jsonObject.getString("code");
                                        if ("200".equals(code)) {
                                            JSONObject msgObject = jsonObject.getJSONObject("msg");
                                            final String km = msgObject.getString("kami");
                                            final String vip = msgObject.getString("vip");
                                            Toast.makeText(context, "自动登录成功\n卡密：" + km + "\n到期时间：" + convertTimestamp(vip), Toast.LENGTH_LONG).show();
                                        } else {
                                            final String msg = jsonObject.getString("msg");
                                            Toast.makeText(context, "自动登录失败: " + msg, Toast.LENGTH_SHORT).show();
                                            new File(getCardFilePath(context)).delete();
                                        }
                                    } catch (JSONException e) {
                                        Toast.makeText(context, "自动登录失败，请手动登录", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
    }

    public static void showNotice(final Context context) {
        new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        final String response = makeRequest("https://haraichi.top/api.php?api=notice&app=" + APPID);

                        Log.d("Verification", "公告响应: " + response);

                        ((Activity) context).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        final String code = jsonObject.getString("code");
                                        if ("200".equals(code)) {
                                            JSONObject msgObject = jsonObject.getJSONObject("msg");
                                            final String appGgContent = msgObject.getString("app_gg");
                                            if (appGgContent != null && !appGgContent.isEmpty()) {
                                                showNoticeDialog(context, appGgContent);
                                            }
                                        }
                                    } catch (JSONException e) {
                                        // 静默失败
                                    }
                                }
                            });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
    }

    public static void checkVersion(final Context context) {
        new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        final String response = makeRequest("https://haraichi.top/api.php?api=ini&app=" + APPID);

                        Log.d("Verification", "版本检查响应: " + response);

                        ((Activity) context).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        final String code = jsonObject.getString("code");
                                        if ("200".equals(code)) {
                                            JSONObject msg = jsonObject.getJSONObject("msg");
                                            final String mversion = msg.getString("version");
                                            final String versionInfo = msg.getString("version_info");
                                            final String updateShow = msg.getString("app_update_show");
                                            final String updateUrl = msg.getString("app_update_url");
                                            final String updateMust = msg.getString("app_update_must");
                                            final int apiTotal = msg.getInt("api_total");

                                            if (compareVersions(mversion, VERSION) == 1) {
                                                if ("y".equals(updateMust)) {
                                                    showUpdateDialog(context, "发现新版本 V " + mversion + 
                                                                     "\n\n版本信息：" + versionInfo + 
                                                                     "\n\n更新内容：" + updateShow + 
                                                                     "\n\n更新：是" +
                                                                     "\n全网启动次数：" + apiTotal, 
                                                                     updateUrl, true);
                                                } else {
                                                    showUpdateDialog(context, "发现新版本 V " + mversion + 
                                                                     "\n\n版本信息：" + versionInfo + 
                                                                     "\n\n更新内容：" + updateShow + 
                                                                     "\n\n更新：否" +
                                                                     "\n全网启动次数：" + apiTotal, 
                                                                     updateUrl, false);
                                                }
                                            }
                                        }
                                    } catch (JSONException e) {
                                        // 静默失败
                                    }
                                }
                            });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
    }

    private static void showLoginDialog(final Context context, final String MARKCODE, final Long timestamp) {
        try {
            LinearLayout mainLayout = new LinearLayout(context);
            mainLayout.setLayoutParams(new LinearLayout.LayoutParams(
                                           LinearLayout.LayoutParams.MATCH_PARENT,
                                           LinearLayout.LayoutParams.MATCH_PARENT));
            mainLayout.setOrientation(LinearLayout.VERTICAL);
            mainLayout.setGravity(Gravity.CENTER);
            mainLayout.setBackgroundColor(Color.parseColor("#121212"));

            GradientDrawable mainBackground = new GradientDrawable();
            mainBackground.setCornerRadius(dpToPx(24, context));
            mainBackground.setColor(Color.parseColor("#1E1E1E"));
            mainBackground.setStroke(dpToPx(1, context), Color.parseColor("#333333"));
            mainLayout.setBackground(mainBackground);

            LinearLayout titleLayout = new LinearLayout(context);
            titleLayout.setOrientation(LinearLayout.VERTICAL);
            LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
            titleParams.setMargins(dpToPx(32, context), dpToPx(32, context), dpToPx(32, context), dpToPx(16, context));
            titleLayout.setLayoutParams(titleParams);

            TextView titleText = new TextView(context);
            titleText.setText("卡密验证");
            titleText.setTextSize(28);
            titleText.setTextColor(Color.WHITE);
            titleText.setGravity(Gravity.CENTER);
            titleText.setTypeface(null, android.graphics.Typeface.BOLD);
            titleText.setPadding(0, 0, 0, dpToPx(8, context));

            TextView subtitleText = new TextView(context);
            subtitleText.setText("请输入您的卡密进行验证");
            subtitleText.setTextSize(14);
            subtitleText.setTextColor(Color.parseColor("#AAAAAA"));
            subtitleText.setGravity(Gravity.CENTER);

            titleLayout.addView(titleText);
            titleLayout.addView(subtitleText);
            mainLayout.addView(titleLayout);

            LinearLayout inputLayout = new LinearLayout(context);
            inputLayout.setOrientation(LinearLayout.VERTICAL);
            LinearLayout.LayoutParams inputParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
            inputParams.setMargins(dpToPx(32, context), dpToPx(8, context), dpToPx(32, context), dpToPx(8, context));
            inputLayout.setLayoutParams(inputParams);

            LinearLayout editTextContainer = new LinearLayout(context);
            editTextContainer.setOrientation(LinearLayout.VERTICAL);
            LinearLayout.LayoutParams containerParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
            editTextContainer.setLayoutParams(containerParams);

            TextView inputLabel = new TextView(context);
            inputLabel.setText("卡密");
            inputLabel.setTextSize(12);
            inputLabel.setTextColor(Color.parseColor("#AAAAAA"));
            inputLabel.setPadding(dpToPx(4, context), 0, 0, dpToPx(4, context));
            editTextContainer.addView(inputLabel);

            final EditText editText = new EditText(context);
            LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                dpToPx(48, context));
            editText.setLayoutParams(editParams);
            editText.setHint("请输入卡密");
            editText.setHintTextColor(Color.parseColor("#666666"));
            editText.setTextColor(Color.WHITE);

            GradientDrawable editBackground = new GradientDrawable();
            editBackground.setCornerRadius(dpToPx(12, context));
            editBackground.setColor(Color.parseColor("#2D2D2D"));
            editBackground.setStroke(dpToPx(1, context), Color.parseColor("#424242"));
            editText.setBackground(editBackground);

            editText.setPadding(dpToPx(16, context), dpToPx(12, context), dpToPx(16, context), dpToPx(12, context));
            editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            editTextContainer.addView(editText);

            inputLayout.addView(editTextContainer);
            mainLayout.addView(inputLayout);

            LinearLayout purchaseLayout = new LinearLayout(context);
            purchaseLayout.setOrientation(LinearLayout.HORIZONTAL);
            purchaseLayout.setGravity(Gravity.END);
            LinearLayout.LayoutParams purchaseParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
            purchaseParams.setMargins(dpToPx(32, context), 0, dpToPx(32, context), dpToPx(16, context));
            purchaseLayout.setLayoutParams(purchaseParams);

            TextView noCodeText = new TextView(context);
            noCodeText.setText("没有卡密？");
            noCodeText.setTextSize(12);
            noCodeText.setTextColor(Color.parseColor("#AAAAAA"));

            TextView purchaseText = new TextView(context);
            purchaseText.setText("点击前往购买");
            purchaseText.setTextSize(12);
            purchaseText.setTextColor(Color.parseColor("#4CAF50"));
            purchaseText.setTypeface(null, android.graphics.Typeface.BOLD);
            purchaseText.setPadding(dpToPx(8, context), 0, 0, 0);

            purchaseLayout.addView(noCodeText);
            purchaseLayout.addView(purchaseText);
            mainLayout.addView(purchaseLayout);

            LinearLayout buttonLayout = new LinearLayout(context);
            buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
            LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
            buttonParams.setMargins(dpToPx(32, context), dpToPx(8, context), dpToPx(32, context), dpToPx(32, context));
            buttonLayout.setLayoutParams(buttonParams);

            Button unbindButton = new Button(context);
            LinearLayout.LayoutParams unbindParams = new LinearLayout.LayoutParams(
                0,
                dpToPx(44, context), 1);
            unbindParams.setMargins(0, 0, dpToPx(8, context), 0);
            unbindButton.setLayoutParams(unbindParams);
            unbindButton.setText("解绑");
            unbindButton.setTextColor(Color.WHITE);
            unbindButton.setTextSize(14);

            GradientDrawable unbindBackground = new GradientDrawable();
            unbindBackground.setCornerRadius(dpToPx(12, context));
            unbindBackground.setColor(Color.parseColor("#424242"));
            unbindButton.setBackground(unbindBackground);

            Button loginButton = new Button(context);
            LinearLayout.LayoutParams loginParams = new LinearLayout.LayoutParams(
                0,
                dpToPx(44, context), 1);
            loginParams.setMargins(dpToPx(8, context), 0, 0, 0);
            loginButton.setLayoutParams(loginParams);
            loginButton.setText("激活");
            loginButton.setTextColor(Color.WHITE);
            loginButton.setTextSize(14);

            GradientDrawable loginBackground = new GradientDrawable();
            loginBackground.setCornerRadius(dpToPx(12, context));
            loginBackground.setColor(Color.parseColor("#2196F3"));
            loginButton.setBackground(loginBackground);

            buttonLayout.addView(unbindButton);
            buttonLayout.addView(loginButton);
            mainLayout.addView(buttonLayout);

            LinearLayout footerLayout = new LinearLayout(context);
            footerLayout.setOrientation(LinearLayout.VERTICAL);
            footerLayout.setGravity(Gravity.CENTER);
            LinearLayout.LayoutParams footerParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
            footerParams.setMargins(dpToPx(32, context), 0, dpToPx(32, context), dpToPx(16, context));
            footerLayout.setLayoutParams(footerParams);

            TextView footerText1 = new TextView(context);
            footerText1.setText("This development document is supported by the verification system.");
            footerText1.setTextSize(10);
            footerText1.setTextColor(Color.parseColor("#666666"));
            footerText1.setGravity(Gravity.CENTER);
            footerText1.setLineSpacing(0, 1.2f);

            TextView footerText2 = new TextView(context);
            footerText2.setText("该对接示例由原一开发，未经允许禁止转载。");
            footerText2.setTextSize(10);
            footerText2.setTextColor(Color.parseColor("#666666"));
            footerText2.setGravity(Gravity.CENTER);
            footerText2.setLineSpacing(0, 1.2f);
            footerText2.setPadding(0, dpToPx(4, context), 0, 0);

            footerLayout.addView(footerText1);
            footerLayout.addView(footerText2);
            mainLayout.addView(footerLayout);

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setView(mainLayout);
            builder.setCancelable(false);

            final AlertDialog dialog = builder.create();

            Window window = dialog.getWindow();
            if (window != null) {
                window.setBackgroundDrawableResource(android.R.color.transparent);
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

                WindowManager.LayoutParams layoutParams = window.getAttributes();
                layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
                layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
                window.setAttributes(layoutParams);
            }

            // 完整实现购买功能
            purchaseText.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            final String purchaseUrl = "https://RseOgni.com";

                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse(purchaseUrl));
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                            if (intent.resolveActivity(context.getPackageManager()) != null) {
                                context.startActivity(intent);
                                Toast.makeText(context, "正在跳转到购买页面...", Toast.LENGTH_SHORT).show();
                            } else {
                                AlertDialog.Builder noBrowserDialog = new AlertDialog.Builder(context);
                                noBrowserDialog.setTitle("提示");
                                noBrowserDialog.setMessage("未检测到浏览器应用。\n\n请手动复制以下链接到浏览器打开：\n\n" + purchaseUrl);
                                noBrowserDialog.setPositiveButton("复制链接", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int which) {
                                            android.text.ClipboardManager clipboard = 
                                                (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                            if (clipboard != null) {
                                                clipboard.setText(purchaseUrl);
                                                Toast.makeText(context, "链接已复制到剪贴板", Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                noBrowserDialog.setNegativeButton("取消", null);
                                noBrowserDialog.show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast.makeText(context, "打开购买页面失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            unbindButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final String authCode = editText.getText().toString();
                        if (authCode.isEmpty()) {
                            Toast.makeText(context, "请输入卡密", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        final long currentTimestamp = System.currentTimeMillis() / 1000;
                                        final String value = String.valueOf(new Random().nextInt(89999) + 1000) + currentTimestamp;

                                        final String signStr = "kami=" + authCode + "&markcode=" + MARKCODE + "&t=" + currentTimestamp + "&" + APPKEY;
                                        final String sign = md5(signStr);
                                        final String dataStr = "kami=" + authCode + "&markcode=" + MARKCODE + "&t=" + currentTimestamp + "&sign=" + sign + "&value=" + value;
                                        final String encryptedData = rc4Encrypt(dataStr, RC4_KEY);

                                        final String response = makeRequest("https://haraichi.top/api.php?api=kmunmachine&app=" + APPID + "&data=" + encryptedData);

                                        Log.d("Verification", "解绑响应: " + response);

                                        ((Activity) context).runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        JSONObject jsonObject = new JSONObject(response);
                                                        final String code = jsonObject.getString("code");
                                                        if ("200".equals(code)) {
                                                            Toast.makeText(context, "解绑成功", Toast.LENGTH_SHORT).show();
                                                            new File(getCardFilePath(context)).delete();
                                                        } else if ("149".equals(code)) {
                                                            Toast.makeText(context, "卡密无效", Toast.LENGTH_SHORT).show();
                                                        } else {
                                                            final String msg = jsonObject.getString("msg");
                                                            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                                                        }
                                                    } catch (JSONException e) {
                                                        Toast.makeText(context, "解绑失败，请稍后重试", Toast.LENGTH_SHORT).show();
                                                    }
                                                }
                                            });
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        ((Activity) context).runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(context, "网络连接失败", Toast.LENGTH_SHORT).show();
                                                }
                                            });
                                    }
                                }
                            }).start();
                    }
                });

            loginButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final String authCode = editText.getText().toString();
                        if (authCode.isEmpty()) {
                            Toast.makeText(context, "请输入卡密", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        final long currentTimestamp = System.currentTimeMillis() / 1000;
                                        final String value = String.valueOf(new Random().nextInt(89999) + 1000) + currentTimestamp;

                                        final String signStr = "kami=" + authCode + "&markcode=" + MARKCODE + "&t=" + currentTimestamp + "&" + APPKEY;
                                        final String sign = md5(signStr);
                                        final String dataStr = "kami=" + authCode + "&markcode=" + MARKCODE + "&t=" + currentTimestamp + "&sign=" + sign + "&value=" + value;
                                        final String encryptedData = rc4Encrypt(dataStr, RC4_KEY);

                                        final String response = makeRequest("https://haraichi.top/api.php?api=kmlogon&app=" + APPID + "&data=" + encryptedData);

                                        Log.d("Verification", "登录响应: " + response);

                                        ((Activity) context).runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        JSONObject jsonObject = new JSONObject(response);
                                                        final String code = jsonObject.getString("code");
                                                        if ("200".equals(code)) {
                                                            JSONObject msgObject = jsonObject.getJSONObject("msg");
                                                            final String km = msgObject.getString("kami");
                                                            final String vip = msgObject.getString("vip");
                                                            Toast.makeText(context, "卡密【" + km + "】登录成功，到期时间：" + convertTimestamp(vip), Toast.LENGTH_LONG).show();
                                                            writeFile(getCardFilePath(context), km);
                                                            dialog.dismiss();
                                                        } else if ("147".equals(code)) {
                                                            Toast.makeText(context, "卡密无效", Toast.LENGTH_SHORT).show();
                                                        } else {
                                                            final String msg = jsonObject.getString("msg");
                                                            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                                                        }
                                                    } catch (JSONException e) {
                                                        Toast.makeText(context, "登录失败，请检查卡密或网络连接", Toast.LENGTH_SHORT).show();
                                                    }
                                                }
                                            });
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        ((Activity) context).runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    Toast.makeText(context, "网络连接失败", Toast.LENGTH_SHORT).show();
                                                }
                                            });
                                    }
                                }
                            }).start();
                    }
                });

            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "对话框创建失败", Toast.LENGTH_SHORT).show();
        }
    }

    private static int dpToPx(int dp, final Context context) {
        float density = context.getResources().getDisplayMetrics().density;
        return Math.round(dp * density);
    }

    public static void showNoticeDialog(Context context, String cont) {
        try {
            LinearLayout mainLayout = new LinearLayout(context);
            mainLayout.setLayoutParams(new LinearLayout.LayoutParams(
                                           ViewGroup.LayoutParams.MATCH_PARENT,
                                           ViewGroup.LayoutParams.WRAP_CONTENT));
            mainLayout.setOrientation(LinearLayout.VERTICAL);

            GradientDrawable mainBackground = new GradientDrawable();
            mainBackground.setCornerRadius(dpToPx(16, context));
            mainBackground.setColor(Color.parseColor("#1E1E1E"));
            mainBackground.setStroke(dpToPx(1, context), Color.parseColor("#333333"));
            mainLayout.setBackground(mainBackground);

            TextView titleText = new TextView(context);
            titleText.setText("公告");
            titleText.setTextSize(20);
            titleText.setTextColor(Color.WHITE);
            titleText.setGravity(Gravity.START);
            titleText.setTypeface(null, android.graphics.Typeface.BOLD);
            titleText.setPadding(dpToPx(20, context), dpToPx(20, context), dpToPx(20, context), dpToPx(12, context));
            mainLayout.addView(titleText);

            TextView contentText = new TextView(context);
            contentText.setText(cont);
            contentText.setTextSize(14);
            contentText.setTextColor(Color.parseColor("#CCCCCC"));
            contentText.setPadding(dpToPx(20, context), 0, dpToPx(20, context), dpToPx(20, context));
            contentText.setMaxHeight(dpToPx(400, context));
            mainLayout.addView(contentText);

            LinearLayout buttonLayout = new LinearLayout(context);
            buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
            buttonLayout.setGravity(Gravity.END);
            buttonLayout.setPadding(dpToPx(20, context), 0, dpToPx(20, context), dpToPx(20, context));

            Button okButton = new Button(context);
            LinearLayout.LayoutParams okParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                dpToPx(44, context));
            okButton.setLayoutParams(okParams);
            okButton.setText("确定");
            okButton.setTextColor(Color.WHITE);
            okButton.setTextSize(14);

            GradientDrawable okBackground = new GradientDrawable();
            okBackground.setCornerRadius(dpToPx(8, context));
            okBackground.setColor(Color.parseColor("#2196F3"));
            okButton.setBackground(okBackground);
            okButton.setPadding(dpToPx(24, context), 0, dpToPx(24, context), 0);

            buttonLayout.addView(okButton);
            mainLayout.addView(buttonLayout);

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setView(mainLayout);
            builder.setCancelable(false);

            final AlertDialog dialog = builder.create();

            Window window = dialog.getWindow();
            if (window != null) {
                window.setBackgroundDrawableResource(android.R.color.transparent);
                WindowManager.LayoutParams layoutParams = window.getAttributes();
                layoutParams.width = (int) (context.getResources().getDisplayMetrics().widthPixels * 0.85);
                window.setAttributes(layoutParams);
            }

            okButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void showUpdateDialog(final Context context, String cont, final String updateUrl, final boolean forceUpdate) {
        try {
            LinearLayout mainLayout = new LinearLayout(context);
            mainLayout.setLayoutParams(new LinearLayout.LayoutParams(
                                           ViewGroup.LayoutParams.MATCH_PARENT,
                                           ViewGroup.LayoutParams.WRAP_CONTENT));
            mainLayout.setOrientation(LinearLayout.VERTICAL);

            GradientDrawable mainBackground = new GradientDrawable();
            mainBackground.setCornerRadius(dpToPx(16, context));
            mainBackground.setColor(Color.parseColor("#1E1E1E"));
            mainBackground.setStroke(dpToPx(1, context), Color.parseColor("#333333"));
            mainLayout.setBackground(mainBackground);

            TextView titleText = new TextView(context);
            titleText.setText("版本更新");
            titleText.setTextSize(20);
            titleText.setTextColor(Color.WHITE);
            titleText.setGravity(Gravity.START);
            titleText.setTypeface(null, android.graphics.Typeface.BOLD);
            titleText.setPadding(dpToPx(20, context), dpToPx(20, context), dpToPx(20, context), dpToPx(12, context));
            mainLayout.addView(titleText);

            TextView contentText = new TextView(context);
            contentText.setText(cont);
            contentText.setTextSize(14);
            contentText.setTextColor(Color.parseColor("#CCCCCC"));
            contentText.setPadding(dpToPx(20, context), 0, dpToPx(20, context), dpToPx(20, context));
            contentText.setMaxHeight(dpToPx(400, context));
            mainLayout.addView(contentText);

            LinearLayout buttonLayout = new LinearLayout(context);
            buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
            buttonLayout.setGravity(Gravity.END);
            buttonLayout.setPadding(dpToPx(20, context), 0, dpToPx(20, context), dpToPx(20, context));

            final AlertDialog[] dialogRef = new AlertDialog[1];

            if (forceUpdate) {
                Button updateButton = new Button(context);
                LinearLayout.LayoutParams updateParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    dpToPx(44, context));
                updateButton.setLayoutParams(updateParams);
                updateButton.setText("立即更新");
                updateButton.setTextColor(Color.WHITE);
                updateButton.setTextSize(14);

                GradientDrawable updateBackground = new GradientDrawable();
                updateBackground.setCornerRadius(dpToPx(8, context));
                updateBackground.setColor(Color.parseColor("#2196F3"));
                updateButton.setBackground(updateBackground);
                updateButton.setPadding(dpToPx(24, context), 0, dpToPx(24, context), 0);

                buttonLayout.addView(updateButton);

                updateButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (updateUrl != null && !updateUrl.isEmpty()) {
                                boolean downloadStarted = downloadAndInstallApk(context, updateUrl);
                                if (downloadStarted) {
                                    Toast.makeText(context, "开始下载更新，请查看通知栏进度", Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(context, "下载启动失败", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(context, "更新链接无效", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
            } else {
                Button ignoreButton = new Button(context);
                LinearLayout.LayoutParams ignoreParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    dpToPx(44, context));
                ignoreParams.setMargins(0, 0, dpToPx(12, context), 0);
                ignoreButton.setLayoutParams(ignoreParams);
                ignoreButton.setText("忽略本次");
                ignoreButton.setTextColor(Color.WHITE);
                ignoreButton.setTextSize(14);

                GradientDrawable ignoreBackground = new GradientDrawable();
                ignoreBackground.setCornerRadius(dpToPx(8, context));
                ignoreBackground.setColor(Color.parseColor("#424242"));
                ignoreButton.setBackground(ignoreBackground);
                ignoreButton.setPadding(dpToPx(24, context), 0, dpToPx(24, context), 0);

                Button updateButton = new Button(context);
                LinearLayout.LayoutParams updateParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    dpToPx(44, context));
                updateButton.setLayoutParams(updateParams);
                updateButton.setText("立即更新");
                updateButton.setTextColor(Color.WHITE);
                updateButton.setTextSize(14);

                GradientDrawable updateBackground = new GradientDrawable();
                updateBackground.setCornerRadius(dpToPx(8, context));
                updateBackground.setColor(Color.parseColor("#2196F3"));
                updateButton.setBackground(updateBackground);
                updateButton.setPadding(dpToPx(24, context), 0, dpToPx(24, context), 0);

                buttonLayout.addView(ignoreButton);
                buttonLayout.addView(updateButton);

                ignoreButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (dialogRef[0] != null) {
                                dialogRef[0].dismiss();
                            }
                        }
                    });

                updateButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (updateUrl != null && !updateUrl.isEmpty()) {
                                boolean downloadStarted = downloadAndInstallApk(context, updateUrl);
                                if (downloadStarted) {
                                    Toast.makeText(context, "开始下载更新，请查看通知栏进度", Toast.LENGTH_LONG).show();
                                    if (dialogRef[0] != null) {
                                        dialogRef[0].dismiss();
                                    }
                                } else {
                                    Toast.makeText(context, "下载启动失败", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(context, "更新链接无效", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
            }

            mainLayout.addView(buttonLayout);

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setView(mainLayout);

            if (forceUpdate) {
                builder.setCancelable(false);
            } else {
                builder.setCancelable(true);
            }

            final AlertDialog dialog = builder.create();
            dialogRef[0] = dialog;

            Window window = dialog.getWindow();
            if (window != null) {
                window.setBackgroundDrawableResource(android.R.color.transparent);
                WindowManager.LayoutParams layoutParams = window.getAttributes();
                layoutParams.width = (int) (context.getResources().getDisplayMetrics().widthPixels * 0.85);
                window.setAttributes(layoutParams);
            }

            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean downloadAndInstallApk(Context context, String downloadUrl) {
        try {
            if (downloadUrl == null || downloadUrl.isEmpty()) {
                return false;
            }

            if (!downloadUrl.startsWith("http://") && !downloadUrl.startsWith("https://")) {
                return false;
            }

            String timestamp = String.valueOf(System.currentTimeMillis());
            String fileName = "app_update_" + timestamp + ".apk";

            File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            if (!downloadDir.exists()) {
                downloadDir.mkdirs();
            }

            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));

            File destinationFile = new File(downloadDir, fileName);
            request.setDestinationUri(Uri.fromFile(destinationFile));

            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setTitle("应用更新");
            request.setDescription("正在下载新版本...");
            request.setMimeType("application/vnd.android.package-archive");

            request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_WIFI | 
                DownloadManager.Request.NETWORK_MOBILE
            );

            request.setAllowedOverRoaming(true);

            final DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

            if (downloadManager != null) {
                final long downloadId = downloadManager.enqueue(request);

                android.content.SharedPreferences prefs = context.getSharedPreferences("download_prefs", Context.MODE_PRIVATE);
                prefs.edit().putLong("last_download_id", downloadId).apply();

                BroadcastReceiver downloadCompleteReceiver = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

                        if (id == downloadId) {
                            installDownloadedApk(context, downloadManager, id);

                            try {
                                context.unregisterReceiver(this);
                            } catch (IllegalArgumentException e) {
                                // Ignore
                            }
                        }
                    }
                };

                context.registerReceiver(
                    downloadCompleteReceiver,
                    new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
                );

                return true;
            } else {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static void installDownloadedApk(final Context context, DownloadManager downloadManager, long downloadId) {
        try {
            Uri downloadedUri = downloadManager.getUriForDownloadedFile(downloadId);

            if (downloadedUri == null) {
                android.content.SharedPreferences prefs = context.getSharedPreferences("download_prefs", Context.MODE_PRIVATE);
                String lastDownloadPath = prefs.getString("last_download_path", null);

                if (lastDownloadPath != null) {
                    File apkFile = new File(lastDownloadPath);
                    if (apkFile.exists()) {
                        downloadedUri = Uri.fromFile(apkFile);
                    }
                }
            }

            if (downloadedUri != null) {
                final Intent installIntent = new Intent(Intent.ACTION_VIEW);

                if (Build.VERSION.SDK_INT >= 24) {
                    File apkFile;

                    if ("file".equals(downloadedUri.getScheme())) {
                        apkFile = new File(downloadedUri.getPath());
                    } else {
                        DownloadManager.Query query = new DownloadManager.Query();
                        query.setFilterById(downloadId);
                        android.database.Cursor cursor = downloadManager.query(query);

                        if (cursor != null && cursor.moveToFirst()) {
                            String localUri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                            if (localUri != null) {
                                apkFile = new File(Uri.parse(localUri).getPath());
                            } else {
                                apkFile = new File(Environment.getExternalStoragePublicDirectory(
                                                       Environment.DIRECTORY_DOWNLOADS), "app_update.apk");
                            }
                            cursor.close();
                        } else {
                            apkFile = new File(Environment.getExternalStoragePublicDirectory(
                                                   Environment.DIRECTORY_DOWNLOADS), "app_update.apk");
                        }
                    }

                    if (apkFile.exists()) {
                        android.content.SharedPreferences prefs = context.getSharedPreferences("download_prefs", Context.MODE_PRIVATE);
                        prefs.edit().putString("last_download_path", apkFile.getAbsolutePath()).apply();

                        Uri apkUri = androidx.core.content.FileProvider.getUriForFile(
                            context,
                            context.getPackageName() + ".provider",
                            apkFile
                        );

                        installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                        installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        List<ResolveInfo> resInfoList = context.getPackageManager()
                            .queryIntentActivities(installIntent, PackageManager.MATCH_DEFAULT_ONLY);
                        for (ResolveInfo resolveInfo : resInfoList) {
                            String packageName = resolveInfo.activityInfo.packageName;
                            context.grantUriPermission(
                                packageName,
                                apkUri,
                                Intent.FLAG_GRANT_READ_URI_PERMISSION
                            );
                        }
                    } else {
                        ((Activity) context).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    AlertDialog.Builder errorDialog = new AlertDialog.Builder(context);
                                    errorDialog.setTitle("安装失败");
                                    errorDialog.setMessage("安装文件不存在");
                                    errorDialog.setPositiveButton("确定", null);
                                    errorDialog.show();
                                }
                            });
                        return;
                    }
                } else {
                    installIntent.setDataAndType(downloadedUri, "application/vnd.android.package-archive");
                    installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                }

                if (installIntent.resolveActivity(context.getPackageManager()) != null) {
                    ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    context.startActivity(installIntent);
                                    Toast.makeText(context, "正在安装更新...", Toast.LENGTH_SHORT).show();
                                } catch (Exception e) {
                                    ((Activity) context).runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                AlertDialog.Builder errorDialog = new AlertDialog.Builder(context);
                                                errorDialog.setTitle("安装失败");
                                                errorDialog.setMessage("启动安装失败");
                                                errorDialog.setPositiveButton("确定", null);
                                                errorDialog.show();
                                            }
                                        });
                                }
                            }
                        });
                } else {
                    ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                AlertDialog.Builder errorDialog = new AlertDialog.Builder(context);
                                errorDialog.setTitle("安装失败");
                                errorDialog.setMessage("没有可用的安装程序");
                                errorDialog.setPositiveButton("确定", null);
                                errorDialog.show();
                            }
                        });
                }
            } else {
                ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            AlertDialog.Builder errorDialog = new AlertDialog.Builder(context);
                            errorDialog.setTitle("安装失败");
                            errorDialog.setMessage("无法找到下载的文件");
                            errorDialog.setPositiveButton("确定", null);
                            errorDialog.show();
                        }
                    });
            }

        } catch (Exception e) {
            e.printStackTrace();
            ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        AlertDialog.Builder errorDialog = new AlertDialog.Builder(context);
                        errorDialog.setTitle("安装失败");
                        errorDialog.setMessage("安装失败");
                        errorDialog.setPositiveButton("确定", null);
                        errorDialog.show();
                    }
                });
        }
    }

    public static int compareVersions(String version1, String version2) {
        if (version1 == null || version2 == null) {
            return 0;
        }
        try {
            String[] v1Parts = version1.split("\\.");
            String[] v2Parts = version2.split("\\.");
            int maxLength = Math.max(v1Parts.length, v2Parts.length);
            for (int i = 0; i < maxLength; i++) {
                int num1 = (i < v1Parts.length) ? Integer.parseInt(v1Parts[i]) : 0;
                int num2 = (i < v2Parts.length) ? Integer.parseInt(v2Parts[i]) : 0;
                if (num1 < num2) return -1;
                if (num1 > num2) return 1;
            }
            return 0;
        } catch (Exception e) {
            return 0;
        }
    }

    public static String getOrCreateMarkCode(Context context) {
        try {
            String markCode = readFile(getMarkCodeFilePath(context));
            if (markCode != null && !markCode.trim().isEmpty()) {
                return markCode.trim();
            }

            markCode = String.valueOf(new Random().nextInt(1000000));
            writeFile(getMarkCodeFilePath(context), markCode);
            return markCode;
        } catch (Exception e) {
            return String.valueOf(new Random().nextInt(1000000));
        }
    }

    private static String getMarkCodeFilePath(Context context) {
        return context.getFilesDir().getAbsolutePath() + "/imei";
    }

    private static String getCardFilePath(Context context) {
        return context.getFilesDir().getAbsolutePath() + "/km";
    }

    public static String convertTimestamp(Object timestamp) {
        try {
            long timestampLong;
            if (timestamp instanceof String) {
                try {
                    timestampLong = Long.parseLong((String) timestamp);
                } catch (NumberFormatException e) {
                    return "无效时间戳";
                }
            } else if (timestamp instanceof Number) {
                timestampLong = ((Number) timestamp).longValue();
            } else {
                return "数据类型错误";
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(new java.util.Date(timestampLong * 1000));
        } catch (Exception e) {
            return "时间戳异常";
        }
    }

    public static String md5(String content) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(content.getBytes(Charset.forName("UTF-8")));
            byte[] messageDigest = digest.digest();

            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String h = Integer.toHexString(0xFF & b);
                if (h.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(h);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            return "";
        }
    }

    public static String rc4Encrypt(String data, String key) {
        try {
            int[] S = new int[256];
            for (int i = 0; i < 256; i++) {
                S[i] = i;
            }

            byte[] keyBytes = key.getBytes(Charset.forName("UTF-8"));
            int j = 0;
            for (int i = 0; i < 256; i++) {
                j = (j + S[i] + keyBytes[i % keyBytes.length]) % 256;
                int temp = S[i];
                S[i] = S[j];
                S[j] = temp;
            }

            byte[] input = data.getBytes(Charset.forName("UTF-8"));
            int i = 0;
            j = 0;
            byte[] output = new byte[input.length];

            for (int k = 0; k < input.length; k++) {
                i = (i + 1) % 256;
                j = (j + S[i]) % 256;
                int temp = S[i];
                S[i] = S[j];
                S[j] = temp;
                int t = (S[i] + S[j]) % 256;
                output[k] = (byte) (input[k] ^ S[t]);
            }

            return bytesToHex(output).toLowerCase();
        } catch (Exception e) {
            return "";
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }

    private static String makeRequest(String urlString) {
        HttpURLConnection connection = null;
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{
                                new X509TrustManager() {
                                    @Override
                                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                                    }

                                    @Override
                                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                                        try {
                                            if (chain == null || chain.length == 0) {
                                                throw new CertificateException("证书链为空");
                                            }

                                            X509Certificate serverCert = chain[0];
                                            serverCert.checkValidity();

                                        } catch (Exception e) {
                                            throw new CertificateException("证书验证失败: " + e.getMessage());
                                        }
                                    }

                                    @Override
                                    public X509Certificate[] getAcceptedIssuers() {
                                        return new X509Certificate[0];
                                    }
                                }
                            }, new java.security.SecureRandom());

            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();

            if (connection instanceof HttpsURLConnection) {
                HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
                httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory());
                httpsConnection.setHostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {
                            return true;
                        }
                    });
            }

            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(15000);
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();

                String responseStr = response.toString().trim();
                if (responseStr.matches("^[0-9a-fA-F]+$")) {
                    return rc4Decrypt(responseStr, RC4_KEY);
                } else {
                    return responseStr;
                }
            } else {
                return "{\"code\":\"500\",\"msg\":\"HTTP错误码: " + responseCode + "\"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"code\":\"500\",\"msg\":\"网络连接失败: " + e.getMessage() + "\"}";
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private static String getCertificateFingerprint(X509Certificate cert, String algorithm) throws NoSuchAlgorithmException, CertificateException {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        byte[] der = cert.getEncoded();
        md.update(der);
        byte[] digest = md.digest();
        return bytesToHex(digest).toUpperCase();
    }

    private static String rc4Decrypt(String data, String key) {
        try {
            if (data == null || data.trim().isEmpty() || !data.matches("^[0-9a-fA-F]+$")) {
                return data;
            }

            data = data.replaceAll("[\\s\\p{Punct}]", "").toUpperCase();

            int[] S = new int[256];
            for (int i = 0; i < 256; i++) {
                S[i] = i;
            }

            byte[] keyBytes = key.getBytes(Charset.forName("UTF-8"));
            int j = 0;
            for (int i = 0; i < 256; i++) {
                j = (j + S[i] + keyBytes[i % keyBytes.length]) % 256;
                int temp = S[i];
                S[i] = S[j];
                S[j] = temp;
            }

            byte[] input = hexToBytes(data);
            int i = 0;
            j = 0;
            byte[] output = new byte[input.length];

            for (int k = 0; k < input.length; k++) {
                i = (i + 1) % 256;
                j = (j + S[i]) % 256;
                int temp = S[i];
                S[i] = S[j];
                S[j] = temp;
                int t = (S[i] + S[j]) % 256;
                output[k] = (byte) (input[k] ^ S[t]);
            }

            return new String(output, Charset.forName("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"code\":\"500\",\"msg\":\"解密失败: " + e.getMessage() + "\"}";
        }
    }

    private static byte[] hexToBytes(String hex) {
        if (hex == null || hex.length() % 2 != 0) {
            return new byte[0];
        }

        byte[] data = new byte[hex.length() / 2];
        for (int i = 0; i < hex.length(); i += 2) {
            int firstDigit = Character.digit(hex.charAt(i), 16);
            int secondDigit = Character.digit(hex.charAt(i + 1), 16);

            if (firstDigit == -1 || secondDigit == -1) {
                return new byte[0];
            }

            data[i / 2] = (byte) ((firstDigit << 4) + secondDigit);
        }
        return data;
    }

    public static void writeFile(String filePath, String content) {
        FileOutputStream fos = null;
        try {
            File file = new File(filePath);
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            fos = new FileOutputStream(file);
            fos.write(content.getBytes(Charset.forName("UTF-8")));
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String readFile(String filePath) {
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return null;
            }
            fis = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            fis.read(buffer);
            return new String(buffer, Charset.forName("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

// 需要自己AndroidManifest.xml进行写入对应的申请，允许权限，然后让用户进行允许，否则部分功能例如更新，跳转，浏览器等功能可能无法使用。