package com.unibuy.smartdevice;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.LayoutInflater;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.unibuy.smartdevice.database.SettingsDao;
import com.unibuy.smartdevice.databinding.ActivityMainBinding;
import com.unibuy.smartdevice.devices.DevNFCPay;
import com.unibuy.smartdevice.devices.DeviceType;
import com.unibuy.smartdevice.devices.Rs232Dev;
import com.unibuy.smartdevice.devices.UsbDev;
import com.unibuy.smartdevice.exception.LogsEmptyException;
import com.unibuy.smartdevice.exception.LogsIOException;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.exception.LogsUnsupportedOperationException;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.external.StarCloudAPI;
import com.unibuy.smartdevice.external.HttpTapPay;
import com.unibuy.smartdevice.structure.SettingStructure;
import com.unibuy.smartdevice.tools.ApiPostMainScheduler;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainSchedulerOnClick;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.ui.DebugActivity;
import com.unibuy.smartdevice.ui.FontendActivity;
import com.unibuy.smartdevice.ui.ProductListActivity;
import com.unibuy.smartdevice.ui.SettingActivity;
import com.unibuy.smartdevice.ui.SettingTestActivity;
import com.unibuy.smartdevice.ui.SystemSetActivity;
import com.unibuy.smartdevice.ui.XyshjTestActivity;
import com.unibuy.smartdevice.ui.devs.vmc.VmcSlotListActivity;
import com.unibuy.smartdevice.ui.tools.CashMachineSettings;
import com.unibuy.smartdevice.ui.tools.VideoImageMixedPlayer;
import com.unibuy.smartdevice.utils.LanguageHelper;

import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivityAbstract {
    @Override
    protected Context setCtx() {
        return this;
    }

    @Override
    protected Class<?> setCls() {
        return this.getClass();
    }

    private AlertDialog activeLoginDialog;

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs()) {
            @Override
            public void execute(Context context, int commandCode, String message) {
                super.execute(context, commandCode, message);
                if ("登入成功".equals(message)) {
                    if (pendingLoginTraceId != null) {
                        long now = System.currentTimeMillis();
                        getLogs().info("[LoginTrace][" + pendingLoginTraceId + "] callback=success totalMs="
                                + (now - pendingLoginStartMs) + " msg=" + message);
                    }
                    updateLoginStatus();
                    if (activeLoginDialog != null && activeLoginDialog.isShowing()) {
                        activeLoginDialog.dismiss();
                        activeLoginDialog = null;
                    }
                    if (pendingAction != null) {
                        pendingAction.run();
                        pendingAction = null;
                    }
                    pendingLoginTraceId = null;
                    pendingLoginStartMs = 0L;
                } else if (pendingLoginTraceId != null && message != null
                        && (message.contains("登入失敗") || message.contains("網路錯誤") || message.contains("解析失敗"))) {
                    long now = System.currentTimeMillis();
                    getLogs().info("[LoginTrace][" + pendingLoginTraceId + "] callback=failure totalMs="
                            + (now - pendingLoginStartMs) + " msg=" + message + " code=" + commandCode);
                    pendingLoginTraceId = null;
                    pendingLoginStartMs = 0L;
                }
            }
        };
    }

    private ActivityMainBinding binding;
    private HttpAPI httpAPI;
    private StarCloudAPI starCloudAPI;
    private Runnable pendingAction;
    private String pendingLoginTraceId;
    private long pendingLoginStartMs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 讀取最後設定語言的設定
        // LanguageHelper.applySavedLanguage(this);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        httpAPI = new HttpAPI(getHandlerMain());
        starCloudAPI = new StarCloudAPI(getHandlerMain(), getHandlerMain());

        // ---- 環境尺寸設定 ----
        ViewCompat.setOnApplyWindowInsetsListener(binding.main, (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        // ---- 環境尺寸設定 ----

        initialData();
        updateLoginStatus();

        binding.btnStatusAction.setOnClickListener(v -> {
            if (MyApp.getInstance().getSuAccess().isEmpty()) {
                showLoginDialog(getCtx(), this::updateLoginStatus);
            } else {
                MyApp.getInstance().setSuAccess("");
                updateLoginStatus();
                Toast.makeText(getCtx(), "已登出後台權限", Toast.LENGTH_SHORT).show();
            }
        });

        binding.buttonGotoSetting.setOnClickListener(v -> {
            Runnable action = () -> getTools().gotoActivity(SettingActivity.class);
            if (!MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                if (MyApp.getInstance().getSuAccess().isEmpty()) {
                    showLoginDialog(getCtx(), action);
                    return;
                }
            }
            action.run();
        });

        binding.buttonGotoSystemSet.setOnClickListener(v -> {
            Runnable action = () -> getTools().gotoActivity(SystemSetActivity.class);
            if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                getHandlerMain().start("MainActivity", "＠先綁定機器");
                return;
            }
            if (MyApp.getInstance().getSuAccess().isEmpty()) {
                showLoginDialog(getCtx(), action);
                return;
            }
            action.run();
        });

        binding.buttonGotoProductList.setOnClickListener(v -> {
            Runnable action = () -> getTools().gotoActivity(ProductListActivity.class);
            if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                getHandlerMain().start("MainActivity", "＠先綁定機器");
                return;
            }
            if (MyApp.getInstance().getSuAccess().isEmpty()) {
                showLoginDialog(getCtx(), action);
                return;
            }
            action.run();
        });

        binding.buttonGotoSlotList.setOnClickListener(v -> {
            Runnable action = () -> getTools().gotoActivity(VmcSlotListActivity.class);
            if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                getHandlerMain().start("MainActivity", "＠先綁定機器");
                return;
            }
            if (MyApp.getInstance().getSuAccess().isEmpty()) {
                showLoginDialog(getCtx(), action);
                return;
            }
            action.run();
        });

        binding.buttonGotoShoppingPlatform.setOnClickListener(v -> {
            if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                getHandlerMain().start("MainActivity", "＠先綁定機器");
                return;
            }

            enterShoppingPlatform();
        });

        // 🛠️ 開發者後門：長按 3 秒強制進入購物平台 (適合手機開發測試)
        final Handler longPressHandler = new Handler();
        final Runnable longPressRunnable = () -> {
            Toast.makeText(getCtx(), "🛠️ 開發者模式：強制進入購物平台", Toast.LENGTH_SHORT).show();
            enterShoppingPlatform();
        };

        binding.buttonGotoShoppingPlatform.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case android.view.MotionEvent.ACTION_DOWN:
                    longPressHandler.postDelayed(longPressRunnable, 2000); // 2秒
                    break;
                case android.view.MotionEvent.ACTION_UP:
                case android.view.MotionEvent.ACTION_CANCEL:
                    longPressHandler.removeCallbacks(longPressRunnable);
                    break;
            }
            return false; // 回傳 false 以確保 setOnClickListener 仍能接收到點擊事件
        });

        binding.buttonGotoSettingTest.setOnClickListener(v -> getTools().gotoActivity(SettingTestActivity.class));

        binding.buttonGotoDebug.setOnClickListener(v -> getTools().gotoActivity(DebugActivity.class));

        binding.buttonNfcCheckout.setOnClickListener(new ButtonNfcCheckoutOnClick(getHandlerMain()));

        binding.buttonNfcReset.setOnClickListener(new ButtonNfcResetOnClick(getHandlerMain()));

        binding.buttonQrCodeTest.setOnClickListener(new ButtonQrCodeTestOnClick(getHandlerMain()));

        // binding.buttonOtherTest.setOnClickListener(new
        // ButtonOtherTextOnClick(getHandlerMain()));

        binding.buttonGotoXyshj.setOnClickListener(new ButtonGotoXyshjOnClick(getHandlerMain()));

        binding.buttonClearAds.setOnClickListener(view -> {
            VideoImageMixedPlayer.clearAdsCache(this);
        });

        // 鈔票機設定
        binding.buttonGotoCash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 建立 Intent，從目前 Activity 跳轉到 CashMachineSettings
                Intent intent = new Intent(MainActivity.this, CashMachineSettings.class);
                startActivity(intent);

            }
        });

        binding.buttonGotoXyshjTest.setOnClickListener(v -> {
            Runnable action = () -> getTools().gotoActivity(XyshjTestActivity.class);
            if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
                getHandlerMain().start("MainActivity", "＠先綁定機器");
                return;
            }

            if (MyApp.getInstance().getSuAccess().isEmpty()) {
                showLoginDialog(getCtx(), action);
                return;
            }

            action.run();
        });

        binding.buttonresetapp.setOnClickListener(v -> {
            // 管理員手動重啟，直接執行不再檢查導覽列
            ReSetAPP();
        });

        binding.buttonGotoAndroidSettings.setOnClickListener(v -> {
            try {
                Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                startActivity(intent);
            } catch (Exception e) {
                Toast.makeText(getCtx(), "無法開啟安卓設定頁", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private static class ButtonQrCodeTestOnClick extends HandlerMainSchedulerOnClick {
        public ButtonQrCodeTestOnClick(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            boolean openBarcode = true;
            try {
                UsbDev usbDev = new UsbDev(DeviceType.QRCODE_SCANNER);
                handlerMain.start(getClass().getSimpleName(), "@40秒內刷條碼");
                byte[] buffer = new byte[1000];
                usbDev.read(buffer, 100);
                for (int i = 0; i < 7; i++) {
                    if (isRun() && openBarcode) {
                        int size = usbDev.read(buffer, 5000);
                        if (size > 5) {
                            String barCodeString = new String(buffer, 0, size);
                            int sorLength = barCodeString.length();
                            barCodeString = barCodeString.trim();
                            int newLength = barCodeString.length();
                            getLogs().info(barCodeString + " 原碼長：" + sorLength + " 新碼長:" + newLength);
                            handlerMain.start(getClass().getSimpleName(), getLogs().getMessage());
                            getLogs().clearMessage();
                            openBarcode = false;
                        }
                    }
                }
                usbDev.closePort();
            } catch (LogsUnsupportedOperationException | LogsIOException | LogsEmptyException e) {
                // getLogs().warning(e);
                getLogs().warning(e);
            }
        }

        @Override
        public void onClick(View v) {
            new ButtonQrCodeTestOnClick(getHandlerMain()).start();
        }

        @Override
        public boolean onLongClick(View v) {
            return false;
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    public static class ButtonNfcResetOnClick extends HandlerMainSchedulerOnClick {

        public ButtonNfcResetOnClick(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            try {
                Rs232Dev comPort2 = new Rs232Dev(MyApp.getInstance().getComPort2ByNFCPay());
                DevNFCPay devNFCPay = new DevNFCPay(handlerMain.getContext());
                comPort2.send(devNFCPay.reset());
                handlerMain.start(getClass().getSimpleName(), "刷卡機重啟啟動");
            } catch (LogsUnsupportedOperationException | LogsIOException e) {
                getLogs().warning(e);
            }
        }

        @Override
        public void onClick(View v) {
            start();
        }

        @Override
        public boolean onLongClick(View v) {
            return false;
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    private class ButtonGotoXyshjOnClick extends HandlerMainSchedulerOnClick {

        public ButtonGotoXyshjOnClick(HandlerMain srcHandlerMain) {
            super(srcHandlerMain);
        }

        @Override
        public void onClick(View view) {
            start();
        }

        @Override
        public boolean onLongClick(View view) {
            return false;
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            try {
                MainActivity.this.getPackageManager().getPackageInfo("com.xyshj.machine", 0);

                Intent it = new Intent("android.intent.action.xinyuan.setting");
                it.putExtra("showLoginDialog", true);
                MainActivity.this.startActivity(it);
                android.os.Process.killProcess(Process.myPid());

            } catch (PackageManager.NameNotFoundException e) {
                handlerMain.start(getSrcHandlerMain().getLogs().getClassName(), "請先安裝興元管理程式");
            }

            // List<PackageInfo> packages =
            // MainActivity.this.getPackageManager().getInstalledPackages(0);
            // for (PackageInfo packageInfo : packages) {
            // if ("com.xyshj.machine".equals(packageInfo.packageName)) {
            // Intent it = new Intent("android.intent.action.xinyuan.setting");
            // it.putExtra("showLoginDialog", true);
            // MainActivity.this.startActivity(it);
            // android.os.Process.killProcess(Process.myPid());
            // return;
            // }
            // }
            // handlerMain.start(getSrcHandlerMain().getLogs().getClassName(),
            // "請先安裝興元管理程式");
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    public static class ButtonNfcCheckoutOnClick extends HandlerMainSchedulerOnClick {

        public ButtonNfcCheckoutOnClick(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void execute(HandlerMain handlerMain) {
            try {
                Rs232Dev comPort2 = new Rs232Dev(MyApp.getInstance().getComPort2ByNFCPay());
                DevNFCPay devNFCPay = new DevNFCPay(handlerMain.getContext());
                comPort2.send(devNFCPay.checkout());
                handlerMain.start(getClass().getSimpleName(), "刷卡機結帳啟動");
            } catch (LogsUnsupportedOperationException | LogsIOException e) {
                getLogs().warning(e);
            }
        }

        @Override
        public void onClick(View v) {
            start();
        }

        @Override
        public boolean onLongClick(View v) {
            return false;
        }

        @Override
        protected Class<?> setCls() {
            return getClass();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.isLongPress()) {
                Toast.makeText(this, "返回主頁", Toast.LENGTH_SHORT).show();
                return true;
            }
        }

        return super.dispatchKeyEvent(event);
    }

    private void initialData() {
        if (MyApp.getInstance().getMachine() != null && MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
            SettingsDao settingsDao = new SettingsDao(this);
            SettingStructure setting = settingsDao.getOne(MyApp.getInstance().getMachine().getClass().getSimpleName());
            if (setting != null && setting.getDataCount() >= 2) {
                MyApp.getInstance().getMachine().setApiKey(setting.getData(0));
                MyApp.getInstance().getMachine().setMachineID(setting.getData(1));
                if (setting.getDataCount() >= 3 && setting.getData(2) != null && !setting.getData(2).isEmpty()) {
                    MyApp.getInstance().getMachine().setMqttEnv(setting.getData(2));
                }
            }
            settingsDao.close();
        }
    }

    public boolean isNavigationReallyHidden() {
        WindowInsetsCompat insets = ViewCompat.getRootWindowInsets(binding.main);
        if (insets == null)
            return false;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            // Android 10+ (含 12): 使用 SystemGestures 判斷
            // 若 Ges.bottom > 0，代表是「自動隱藏/全螢幕」模式 (可滑出)，不允許通過
            // 若 Ges.bottom == 0，代表是「強制隱藏」模式 (不可滑出)，允許通過
            androidx.core.graphics.Insets gestureInsets = insets.getInsets(WindowInsetsCompat.Type.systemGestures());
            return gestureInsets.bottom == 0;
        } else {
            // Android 9 及以下: 維持原有的判斷方式 (檢查導航列高度)
            androidx.core.graphics.Insets navInsets = insets.getInsets(WindowInsetsCompat.Type.navigationBars());
            return navInsets.bottom == 0;
        }
    }

    // 提示對話框 (還原為不帶參數)
    private void showMustHideSystemBarsDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("無法進入購物平台")
                .setMessage("進入購物平台前，請先使用 Vol- 按鍵隱藏系統導覽列。")
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 點擊確定後關閉對話框，等待使用者按下 V- 按鍵
                    }
                })
                .create();
        dialog.show();
    }

    public void showLoginDialog(Context context) {
        showLoginDialog(context, null);
    }

    public void showLoginDialog(Context context, Runnable onSuccess) {
        // 使用 LayoutInflater 載入自訂佈局
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_admin_login, null);

        final EditText accessInput = view.findViewById(R.id.etAccess);
        final EditText passwordInput = view.findViewById(R.id.etPassword);
        final CheckBox rememberAccountCb = view.findViewById(R.id.cbRemember);
        androidx.appcompat.widget.AppCompatButton positiveButton = view.findViewById(R.id.btnLogin);
        androidx.appcompat.widget.AppCompatButton negativeButton = view.findViewById(R.id.btnCancel);

        getTools().setImmHideByFocusChange(accessInput);
        getTools().setImmOpenByFocusChange(accessInput);
        getTools().setImmHideByFocusChange(passwordInput);

        // 讀取紀錄的帳號
        android.content.SharedPreferences prefs = context.getSharedPreferences("LoginPrefs", Context.MODE_PRIVATE);
        String savedAccount = prefs.getString("saved_account", "");
        if (!savedAccount.isEmpty()) {
            accessInput.setText(savedAccount);
        }
        rememberAccountCb.setChecked(!savedAccount.isEmpty()); // 如果有存過帳號，預設打勾

        // 建立對話框
        AlertDialog dialog = new AlertDialog.Builder(context)
                .setView(view)
                .create();
        activeLoginDialog = dialog;

        // 設定對話框視窗背景為透明，以便呈現圓角設計
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        }

        // 設定點擊事件
        positiveButton.setOnClickListener(v -> {
            long clickStartMs = System.currentTimeMillis();
            String access = accessInput.getText().toString().trim();
            String password = passwordInput.getText().toString().trim();
            String traceId = String.format(Locale.US, "L%tH%<tM%<tS-%03d", clickStartMs, clickStartMs % 1000);
            getLogs().info("[LoginTrace][" + traceId + "] click_login accountLen=" + access.length());

            if (access.isEmpty() || password.isEmpty()) {
                getLogs().info("[LoginTrace][" + traceId + "] blocked_empty_input");
                Toast.makeText(context, "請輸入帳號和密碼", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "正在驗證登入...", Toast.LENGTH_SHORT).show();
                
                // 為了處理 StarCloudAPI 登入成功後的回調
                // 我們重新設計 handlerMain 讓它能夠在 onSuccess 回調中跑 pendingAction
                pendingAction = onSuccess;
                pendingLoginTraceId = traceId;
                pendingLoginStartMs = clickStartMs;
                getLogs().info("[LoginTrace][" + traceId + "] dispatch_starcloud_login");
                starCloudAPI.login(access, password, traceId, clickStartMs);
                
                if (rememberAccountCb.isChecked()) {
                    prefs.edit().putString("saved_account", access).apply();
                    getLogs().info("[LoginTrace][" + traceId + "] remember_account=save");
                } else {
                    prefs.edit().remove("saved_account").apply();
                    getLogs().info("[LoginTrace][" + traceId + "] remember_account=clear");
                }
                // 🛠️ 關鍵優化：不再此處立即 dismiss()，改由 API 回報成功時關閉
            }
            getTools().hideSystemBars((Activity) getCtx());
        });

        negativeButton.setOnClickListener(v -> {
            getTools().hideSystemBars((Activity) getCtx());
            dialog.dismiss();
            activeLoginDialog = null;
        });

        dialog.show();
    }

    /**
     * 更新右上角登入狀態顯示
     */
    private void updateLoginStatus() {
        String suAccess = MyApp.getInstance().getSuAccess();
        if (suAccess.isEmpty()) {
            binding.tvWelcomeTitle.setText("歡迎使用 AAT\n智能販賣機系統");
            binding.tvWelcomeHint.setText("請點擊右上角登入帳號");
            binding.btnStatusAction.setText("登入");
            binding.btnStatusAction.setBackgroundTintList(android.content.res.ColorStateList.valueOf(getResources().getColor(R.color.primary)));
        } else {
            binding.tvWelcomeTitle.setText("歡迎使用 AAT\n" + suAccess);
            binding.tvWelcomeHint.setText("請點擊下方按鈕操作");
            binding.btnStatusAction.setText("登出");
            binding.btnStatusAction.setBackgroundTintList(android.content.res.ColorStateList.valueOf(getResources().getColor(R.color.error)));
        }
    }

    private void enterShoppingPlatform() {
        MyApp.getInstance().setSuAccess("");
        getTools().gotoActivity(FontendActivity.class);
        finish();
    }

    public void ReSetAPP() {
        getLogs().info("🔄MainActivity - Manual App restarting via gracefulDisconnect...");
        com.unibuy.smartdevice.external.mqtt.MqttManager.getInstance().gracefulDisconnect(() -> {
            new android.os.Handler(android.os.Looper.getMainLooper()).post(() -> {
                Intent intent = new Intent(getApplicationContext(), AppEntry.initialActivity());
                // 清空所有 Task，重新啟動
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);

                // 建議搭配 finishAffinity()，確保所有舊的 Activity 都被清掉
                finishAffinity();
                
                android.os.Process.killProcess(android.os.Process.myPid());
            });
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
            binding.wrapButtonGotoSystemSet.setVisibility(View.GONE);
            binding.wrapButtonGotoProductList.setVisibility(View.GONE);
            binding.wrapButtonGotoSlotList.setVisibility(View.GONE);
            binding.wrapButtonGotoShoppingPlatform.setVisibility(View.GONE);
        } else {
            binding.wrapButtonGotoSystemSet.setVisibility(View.VISIBLE);
            binding.wrapButtonGotoProductList.setVisibility(View.VISIBLE);
            binding.wrapButtonGotoSlotList.setVisibility(View.VISIBLE);
            binding.wrapButtonGotoShoppingPlatform.setVisibility(View.VISIBLE);
        }
    }
}
