package cc.winboll.studio.powerbell;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import androidx.appcompat.widget.Toolbar;
import cc.winboll.studio.libaes.activitys.AboutActivity;
import cc.winboll.studio.libaes.models.APPInfo;
import cc.winboll.studio.libaes.utils.AESThemeUtil;
import cc.winboll.studio.libaes.utils.DevelopUtils;
import cc.winboll.studio.libaes.utils.WinBoLLActivityManager;
import cc.winboll.studio.libaes.views.ADsBannerView;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.powerbell.activities.BackgroundSettingsActivity;
import cc.winboll.studio.powerbell.activities.BatteryReportActivity;
import cc.winboll.studio.powerbell.activities.ClearRecordActivity;
import cc.winboll.studio.powerbell.activities.SettingsActivity;
import cc.winboll.studio.powerbell.activities.WinBoLLActivity;
import cc.winboll.studio.powerbell.models.AppConfigBean;
import cc.winboll.studio.powerbell.models.BackgroundBean;
import cc.winboll.studio.powerbell.models.ControlCenterServiceBean;
import cc.winboll.studio.powerbell.services.ControlCenterService;
import cc.winboll.studio.powerbell.threads.RemindThread;
import cc.winboll.studio.powerbell.unittest.MainUnitTestActivity;
import cc.winboll.studio.powerbell.utils.AppConfigUtils;
import cc.winboll.studio.powerbell.utils.BackgroundSourceUtils;
import cc.winboll.studio.powerbell.utils.PermissionUtils;
import cc.winboll.studio.powerbell.utils.ServiceUtils;
import cc.winboll.studio.powerbell.views.MainContentView;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/12/17 13:14
 * @Describe 主活动类：应用核心页面，管理电池监控、背景设置、服务控制等核心功能
 * 适配：Java7 | API30 | 小米手机，优化性能与稳定性，杜绝内存泄漏
 * 核心规则：UI开关仅管理本地配置，服务启停仅在应用启动时根据配置执行
 */
public class MainActivity extends WinBoLLActivity implements MainContentView.OnViewActionListener {
    // ======================== 静态常量（置顶统一，抽离魔法值，便于维护）========================
    public static final String TAG = "MainActivity";
    // 请求码
    private static final int REQUEST_READ_MEDIA_IMAGES = 1001; // 背景设置请求码
    // 延迟时间
    private static final int DELAY_LOAD_NON_CRITICAL = 500;     // 非核心视图延迟加载（ms）
    // Handler消息标识（按业务优先级排序）
    public static final int MSG_RELOAD_APPCONFIG = 0;          // 重新加载配置
    public static final int MSG_CURRENTVALUEBATTERY = 1;       // 更新当前电量
    public static final int MSG_LOAD_BACKGROUND = 2;           // 加载背景
    private static final int MSG_RESTART_REMIND_THREAD = 3;    // 重启RemindThread线程
    private static final int MSG_UPDATE_SERVICE_SWITCH = 4;    // 更新服务开关UI

    // ======================== 静态成员（全局共享，严格管控生命周期）========================
    private static MainActivity sMainActivity;  // 全局Activity实例（销毁时必须置空）
    private static Handler sGlobalHandler;      // 全局Handler（统一消息分发）

    // ======================== 成员属性（按「依赖→核心→辅助」分类，优先级递减）========================
    // 工具类实例（单例，避免重复初始化）
    private PermissionUtils mPermissionUtils;
    private AppConfigUtils mAppConfigUtils;
    private BackgroundSourceUtils mBgSourceUtils;
    // 应用核心实例
    private App mApplication;
    private MainContentView mMainContentView;   // 核心视图封装类
    // 基础视图组件
    private Toolbar mToolbar;
    private ViewStub mAdsViewStub;
    private ADsBannerView mADsBannerView;       // 广告视图（非核心，延迟加载）
    // 资源与菜单
    private Menu mMenu;
    private Drawable mFrameDrawable;            // 框架背景资源
    // 服务控制核心Bean
    private ControlCenterServiceBean mServiceControlBean;

    // ======================== 生命周期方法（按系统调用顺序排列，逻辑闭环）========================
    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public String getTag() {
        return TAG;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogUtils.d(TAG, "onCreate: 进入");
        super.onCreate(savedInstanceState);
        // 1. 初始化全局Handler（优先初始化，避免消息丢失）
        initGlobalHandler();
        // 2. 加载布局+初始化核心流程
        setContentView(R.layout.activity_main);
        initPermissionUtils();
        initMainContentView();
        initCriticalView();
        initCoreUtilsAsync();
        loadNonCriticalViewDelayed();
        LogUtils.d(TAG, "onCreate: 退出");
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        LogUtils.d(TAG, "onPostCreate: 进入");
        super.onPostCreate(savedInstanceState);
        mPermissionUtils.startPermissionRequest(this);
        LogUtils.d(TAG, "onPostCreate: 退出");
    }

    @Override
    protected void onResume() {
        LogUtils.d(TAG, "onResume: 进入");
        super.onResume();
        // 恢复背景+同步服务开关UI（仅本地配置）
        if (sGlobalHandler != null) {
            sGlobalHandler.sendEmptyMessage(MSG_LOAD_BACKGROUND);
            sGlobalHandler.sendEmptyMessage(MSG_UPDATE_SERVICE_SWITCH);
            LogUtils.d(TAG, "onResume: 发送背景加载+服务开关更新消息");
        }
        // 恢复广告
        if (mADsBannerView != null) {
            mADsBannerView.resumeADs(this);
        }
//        // 设置RemindThread前台状态
//        setRemindThreadForeground(true);
        LogUtils.d(TAG, "onResume: 退出");
    }

    @Override
    protected void onPause() {
        LogUtils.d(TAG, "onPause: 进入");
        super.onPause();
//        // 设置RemindThread后台状态
//        setRemindThreadForeground(false);
        LogUtils.d(TAG, "onPause: 退出");
    }

    @Override
    protected void onDestroy() {
        LogUtils.d(TAG, "onDestroy: 进入");
        super.onDestroy();
        // 1. 释放广告资源
        if (mADsBannerView != null) {
            mADsBannerView.releaseAdResources();
            mADsBannerView = null;
        }
        // 2. 释放核心视图资源
        if (mMainContentView != null) {
            mMainContentView.releaseResources();
            mMainContentView = null;
        }
        // 3. 销毁线程+清理Handler
        RemindThread.destroyInstance();
        if (sGlobalHandler != null) {
            sGlobalHandler.removeCallbacksAndMessages(null);
            sGlobalHandler = null;
        }
        // 4. 释放Drawable+置空全局实例
        if (mFrameDrawable != null) {
            mFrameDrawable.setCallback(null);
            mFrameDrawable = null;
        }
        sMainActivity = null;
        // 5. 置空所有辅助实例
        mPermissionUtils = null;
        mAppConfigUtils = null;
        mBgSourceUtils = null;
        mServiceControlBean = null;
        mMenu = null;
        mApplication = null;
        mToolbar = null;
        mAdsViewStub = null;
        LogUtils.d(TAG, "onDestroy: 退出");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.d(TAG, "onActivityResult: 进入，requestCode=" + requestCode + "，resultCode=" + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
        mPermissionUtils.handlePermissionRequest(this, requestCode, resultCode, data);
        // 背景设置完成后重新加载背景
        if (requestCode == REQUEST_READ_MEDIA_IMAGES) {
            if (sGlobalHandler != null) {
                sGlobalHandler.sendEmptyMessage(MSG_LOAD_BACKGROUND);
            }
        }
        LogUtils.d(TAG, "onActivityResult: 退出");
    }

    // ======================== 菜单与导航方法 ========================
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        LogUtils.d(TAG, "onCreateOptionsMenu: 进入");
        mMenu = menu;
        AESThemeUtil.inflateMenu(this, menu);
        if (App.isDebugging()) {
            DevelopUtils.inflateMenu(this, menu);
            getMenuInflater().inflate(R.menu.toolbar_unittest, mMenu);
        }
        getMenuInflater().inflate(R.menu.toolbar_main, mMenu);
        LogUtils.d(TAG, "onCreateOptionsMenu: 退出");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        LogUtils.d(TAG, "onOptionsItemSelected: 进入，itemId=" + item.getItemId());
        if (AESThemeUtil.onAppThemeItemSelected(this, item)) {
            recreate();
            return true;
        }
        if (DevelopUtils.onDevelopItemSelected(this, item)) {
            return true;
        }
        switch (item.getItemId()) {
            case R.id.action_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                break;
            case R.id.action_battery_report:
                startActivity(new Intent(this, BatteryReportActivity.class));
                break;
            case R.id.action_clearrecord:
                startActivity(new Intent(this, ClearRecordActivity.class));
                break;
            case R.id.action_changepicture:
                startActivityForResult(new Intent(this, BackgroundSettingsActivity.class), REQUEST_READ_MEDIA_IMAGES);
                break;
            case R.id.action_unittestactivity:
                startActivity(new Intent(this, MainUnitTestActivity.class));
                break;
            case R.id.action_about:
                startAboutActivity();
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        LogUtils.d(TAG, "onOptionsItemSelected: 退出");
        return true;
    }

    @Override
    public void setupToolbar() {
        super.setupToolbar();
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        }
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
        LogUtils.d(TAG, "onBackPressed: 应用退到后台");
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return super.dispatchKeyEvent(event);
    }

    // ======================== 核心初始化方法 ========================
    private void initPermissionUtils() {
        LogUtils.d(TAG, "initPermissionUtils: 进入");
        mPermissionUtils = PermissionUtils.getInstance();
        LogUtils.d(TAG, "initPermissionUtils: 退出");
    }

    /**
     * 初始化全局Handler（核心优化：弱引用+生命周期校验，杜绝内存泄漏）
     */
    private void initGlobalHandler() {
        LogUtils.d(TAG, "initGlobalHandler: 进入");
        if (sGlobalHandler == null) {
            sGlobalHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    // 严格校验Activity状态，避免销毁后操作UI
                    if (sMainActivity == null || sMainActivity.isFinishing() || sMainActivity.isDestroyed()) {
                        LogUtils.w(TAG, "handleMessage: Activity已销毁，跳过消息处理");
                        return;
                    }
                    LogUtils.d(TAG, "handleMessage: 接收消息，what=" + msg.what);
                    switch (msg.what) {
                        case MSG_RELOAD_APPCONFIG:
                            sMainActivity.updateViewData();
                            break;
                        case MSG_CURRENTVALUEBATTERY:
                            if (sMainActivity.mMainContentView != null) {
                                sMainActivity.mMainContentView.updateCurrentBattery(msg.arg1);
                            }
                            break;
                        case MSG_LOAD_BACKGROUND:
                            sMainActivity.reloadBackground();
                            sMainActivity.setMainLayoutBackgroundColor();
                            break;
                        case MSG_RESTART_REMIND_THREAD:
                            AppConfigBean configBean = (AppConfigBean) msg.obj;
                            sMainActivity.restartRemindThread(configBean);
                            break;
                        case MSG_UPDATE_SERVICE_SWITCH:
                            sMainActivity.updateServiceSwitchUI();
                            break;
                    }
                    super.handleMessage(msg);
                }
            };
            LogUtils.d(TAG, "initGlobalHandler: 全局Handler初始化完成");
        }
        LogUtils.d(TAG, "initGlobalHandler: 退出");
    }

    private void initMainContentView() {
        LogUtils.d(TAG, "initMainContentView: 进入");
        View rootView = findViewById(android.R.id.content);
        mMainContentView = new MainContentView(this, rootView, this);
        LogUtils.d(TAG, "initMainContentView: 核心视图封装类初始化完成");
        LogUtils.d(TAG, "initMainContentView: 退出");
    }

    private void initCriticalView() {
        LogUtils.d(TAG, "initCriticalView: 进入");
        sMainActivity = this;
        mToolbar = findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        if (mToolbar != null) {
            mToolbar.setTitleTextAppearance(this, R.style.Toolbar_TitleText);
        }
        mAdsViewStub = findViewById(R.id.stub_ads_banner);
        LogUtils.d(TAG, "initCriticalView: 退出");
    }

    /**
     * 异步初始化核心工具类（保留服务启停逻辑：应用启动时根据配置执行）
     */
    private void initCoreUtilsAsync() {
        LogUtils.d(TAG, "initCoreUtilsAsync: 进入");
        new Thread(new Runnable() {
				@Override
				public void run() {
					LogUtils.d(TAG, "initCoreUtilsAsync: 异步线程启动");
					mApplication = (App) getApplication();
					mAppConfigUtils = AppConfigUtils.getInstance(getApplicationContext());
					mBgSourceUtils = BackgroundSourceUtils.getInstance(getActivity());

					// 初始化服务控制Bean（优先读取本地配置，无则创建默认）
					mServiceControlBean = ControlCenterServiceBean.loadBean(getApplicationContext(), ControlCenterServiceBean.class);
					if (mServiceControlBean == null) {
						mServiceControlBean = new ControlCenterServiceBean(false);
						ControlCenterServiceBean.saveBean(getApplicationContext(), mServiceControlBean);
						LogUtils.d(TAG, "initCoreUtilsAsync: 创建默认服务控制配置（禁用）");
					}

					// 应用启动时：根据本地配置执行服务启停（仅执行一次）
					if (mServiceControlBean.isEnableService()) {
						if (!ServiceUtils.isServiceAlive(getApplicationContext(), ControlCenterService.class.getName())) {
							runOnUiThread(new Runnable() {
									@Override
									public void run() {
										ControlCenterService.startControlCenterService(getApplicationContext());
										LogUtils.d(TAG, "initCoreUtilsAsync: 应用启动，根据配置启动服务");
									}
								});
						}
					} else {
						if (ServiceUtils.isServiceAlive(getApplicationContext(), ControlCenterService.class.getName())) {
							runOnUiThread(new Runnable() {
									@Override
									public void run() {
										ControlCenterService.stopControlCenterService(getApplicationContext());
										LogUtils.d(TAG, "initCoreUtilsAsync: 应用启动，根据配置停止服务");
									}
								});
						}
					}

					// 切换主线程更新UI
					runOnUiThread(new Runnable() {
							@Override
							public void run() {
								if (isFinishing() || isDestroyed()) {
									LogUtils.w(TAG, "initCoreUtilsAsync: Activity已销毁，跳过UI更新");
									return;
								}
								// 适配API30+主题加载Drawable
								if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
									mFrameDrawable = getResources().getDrawable(R.drawable.bg_frame, getTheme());
								} else {
									mFrameDrawable = getResources().getDrawable(R.drawable.bg_frame);
								}
								// 执行核心业务
								updateViewData();
								sGlobalHandler.sendEmptyMessage(MSG_LOAD_BACKGROUND);
								sGlobalHandler.sendEmptyMessage(MSG_UPDATE_SERVICE_SWITCH);
							}
						});
					LogUtils.d(TAG, "initCoreUtilsAsync: 异步线程结束");
				}
			}).start();
        LogUtils.d(TAG, "initCoreUtilsAsync: 退出");
    }

    private void loadNonCriticalViewDelayed() {
        LogUtils.d(TAG, "loadNonCriticalViewDelayed: 进入");
        new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if (isFinishing() || isDestroyed()) {
						return;
					}
					loadAdsView();
				}
			}, DELAY_LOAD_NON_CRITICAL);
        LogUtils.d(TAG, "loadNonCriticalViewDelayed: 退出");
    }

    // ======================== 视图操作方法 ========================
    private void loadAdsView() {
        LogUtils.d(TAG, "loadAdsView: 进入");
        if (mAdsViewStub == null) {
            LogUtils.e(TAG, "loadAdsView: 广告ViewStub为空");
            return;
        }
        if (mADsBannerView == null) {
            View adsView = mAdsViewStub.inflate();
            mADsBannerView = adsView.findViewById(R.id.adsbanner);
        }
        LogUtils.d(TAG, "loadAdsView: 退出");
    }

    private void updateViewData() {
        LogUtils.d(TAG, "updateViewData: 进入");
        if (mMainContentView == null || mFrameDrawable == null) {
            LogUtils.e(TAG, "updateViewData: 核心视图/框架资源为空");
            return;
        }
        mMainContentView.updateViewData(mFrameDrawable);
        LogUtils.d(TAG, "updateViewData: 视图数据更新完成");
        LogUtils.d(TAG, "updateViewData: 退出");
    }

    private void reloadBackground() {
        LogUtils.d(TAG, "reloadBackground: 进入");
        if (mMainContentView == null || mBgSourceUtils == null) {
            LogUtils.e(TAG, "reloadBackground: 核心视图/背景工具类为空");
            return;
        }
        BackgroundBean currentBgBean = mBgSourceUtils.getCurrentBackgroundBean();
        if (currentBgBean != null) {
            mMainContentView.backgroundView.loadBackgroundBean(currentBgBean);
        } else {
            mMainContentView.backgroundView.setBackgroundResource(R.drawable.default_background);
        }
        LogUtils.d(TAG, "reloadBackground: 退出");
    }

    private void setMainLayoutBackgroundColor() {
        LogUtils.d(TAG, "setMainLayoutBackgroundColor: 进入");
        if (isFinishing() || isDestroyed() || mMainContentView == null || mBgSourceUtils == null) {
            LogUtils.e(TAG, "setMainLayoutBackgroundColor: 环境无效");
            return;
        }
        BackgroundBean currentBgBean = mBgSourceUtils.getCurrentBackgroundBean();
        if (currentBgBean != null) {
            mMainContentView.mainLayout.setBackgroundColor(currentBgBean.getPixelColor());
        }
        LogUtils.d(TAG, "setMainLayoutBackgroundColor: 退出");
    }

    /**
     * 更新服务开关UI（仅同步本地配置，不校验服务状态）
     */
    private void updateServiceSwitchUI() {
        LogUtils.d(TAG, "updateServiceSwitchUI: 进入");
        if (mMainContentView == null || mServiceControlBean == null) {
            LogUtils.e(TAG, "updateServiceSwitchUI: 核心视图/服务控制Bean为空");
            return;
        }
        // 仅读取本地配置状态，不涉及服务状态校验
        boolean configEnabled = mServiceControlBean.isEnableService();
        LogUtils.d(TAG, "updateServiceSwitchUI: 本地配置状态=" + configEnabled);

        // 仅更新UI开关状态
        mMainContentView.setServiceSwitchEnabled(false);
        mMainContentView.setServiceSwitchChecked(configEnabled);
        mMainContentView.setServiceSwitchEnabled(true);
        LogUtils.d(TAG, "updateServiceSwitchUI: 退出");
    }

    // ======================== 服务与线程管理方法 ========================
    /**
     * 重启提醒线程（仅由配置变更触发，不与UI开关联动）
     */
    private void restartRemindThread(AppConfigBean configBean) {
        LogUtils.d(TAG, "restartRemindThread: 进入");
        if (configBean == null || mServiceControlBean == null) {
            LogUtils.e(TAG, "restartRemindThread: 配置/服务控制Bean为空");
            return;
        }
        if (!mServiceControlBean.isEnableService()) {
            LogUtils.w(TAG, "restartRemindThread: 服务已禁用，跳过线程重启");
            return;
        }
        if (!ServiceUtils.isServiceAlive(getApplicationContext(), ControlCenterService.class.getName())) {
            ControlCenterService.startControlCenterService(getApplicationContext());
        }
        RemindThread.destroyInstance();
        ControlCenterService.updateStatus(getApplicationContext(), configBean);
        LogUtils.d(TAG, "restartRemindThread: 退出");
    }

    /**
     * 设置线程前后台状态（依赖服务运行状态）
     */
//    private void setRemindThreadForeground(boolean isForeground) {
//        LogUtils.d(TAG, "setRemindThreadForeground: 进入，前台状态=" + isForeground);
//        if (!ServiceUtils.isServiceAlive(getApplicationContext(), ControlCenterService.class.getName())) {
//            LogUtils.w(TAG, "setRemindThreadForeground: 服务未运行，跳过状态设置");
//            return;
//        }
//        try {
//            RemindThread.getInstance(getApplicationContext(), null).setAppForeground(isForeground);
//        } catch (IllegalArgumentException e) {
//            LogUtils.w(TAG, "setRemindThreadForeground: 线程未初始化", e);
//        }
//        LogUtils.d(TAG, "setRemindThreadForeground: 退出");
//    }

    /**
     * 切换服务启用状态（仅持久化本地配置，点击UI开关时不联动服务启停）
     */
    private void toggleServiceEnableState(boolean isEnable) {
        LogUtils.d(TAG, "toggleServiceEnableState: 进入，目标状态=" + isEnable);
        if (mServiceControlBean == null) {
            LogUtils.e(TAG, "toggleServiceEnableState: 服务控制Bean为空");
            return;
        }
        // 仅更新本地配置并持久化
        mServiceControlBean.setIsEnableService(isEnable);
        ControlCenterServiceBean.saveBean(getApplicationContext(), mServiceControlBean);
        LogUtils.d(TAG, "toggleServiceEnableState: 本地服务控制配置已持久化，状态=" + isEnable);

        // 仅更新UI，无服务启停操作
        sGlobalHandler.sendEmptyMessage(MSG_UPDATE_SERVICE_SWITCH);
        LogUtils.d(TAG, "toggleServiceEnableState: 退出");
    }

    // ======================== 页面跳转方法 ========================
    private void startAboutActivity() {
        LogUtils.d(TAG, "startAboutActivity: 进入");
        Intent aboutIntent = new Intent(getApplicationContext(), AboutActivity.class);
        APPInfo appInfo = genDefaultAppInfo();
        aboutIntent.putExtra(AboutActivity.EXTRA_APPINFO, appInfo);
        WinBoLLActivityManager.getInstance().startWinBoLLActivity(getApplicationContext(), aboutIntent, AboutActivity.class);
        LogUtils.d(TAG, "startAboutActivity: 退出");
    }

    // ======================== 消息发送方法 ========================
    private void sendRestartRemindThreadMessage() {
        LogUtils.d(TAG, "sendRestartRemindThreadMessage: 进入");
        if (sGlobalHandler == null || mAppConfigUtils == null || mAppConfigUtils.mAppConfigBean == null) {
            LogUtils.e(TAG, "sendRestartRemindThreadMessage: 环境无效");
            return;
        }
        Message msg = sGlobalHandler.obtainMessage(MSG_RESTART_REMIND_THREAD);
        msg.obj = mAppConfigUtils.mAppConfigBean;
        sGlobalHandler.sendMessage(msg);
        LogUtils.d(TAG, "sendRestartRemindThreadMessage: 退出");
    }

    // ======================== 静态工具方法 ========================
    public static void reloadAppConfig() {
        LogUtils.d(TAG, "reloadAppConfig: 发送配置更新消息");
        if (sGlobalHandler != null) {
            sGlobalHandler.sendEmptyMessage(MSG_RELOAD_APPCONFIG);
        }
    }

    public static void sendCurrentBatteryValueMessage(int value) {
        LogUtils.d(TAG, "sendCurrentBatteryValueMessage: 电量=" + value);
        if (sGlobalHandler != null) {
            Message msg = sGlobalHandler.obtainMessage(MSG_CURRENTVALUEBATTERY);
            msg.arg1 = value;
            sGlobalHandler.sendMessage(msg);
        }
    }

    // ======================== 辅助工具方法 ========================
    private String getRealPathFromUri(Uri contentUri) {
        LogUtils.d(TAG, "getRealPathFromUri: 进入");
        if (contentUri == null) {
            LogUtils.e(TAG, "getRealPathFromUri: URI为空");
            return null;
        }
        String realPath = null;
        String[] projection = {MediaStore.MediaColumns.DATA};
        Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);
        if (cursor != null) {
            try {
                if (cursor.moveToNext()) {
                    int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
                    if (columnIndex > -1) {
                        realPath = cursor.getString(columnIndex);
                    }
                }
            } finally {
                cursor.close();
            }
        }
        LogUtils.d(TAG, "getRealPathFromUri: 退出，路径=" + realPath);
        return realPath;
    }

    private APPInfo genDefaultAppInfo() {
        LogUtils.d(TAG, "genDefaultAppInfo: 进入");
        String branchName = "powerbell";
        APPInfo appInfo = new APPInfo();
        appInfo.setAppName(getString(R.string.app_name));
        appInfo.setAppIcon(R.drawable.ic_launcher);
        appInfo.setAppDescription(getString(R.string.app_description));
        appInfo.setAppGitName("WinBoLL");
        appInfo.setAppGitOwner("Studio");
        appInfo.setAppGitAPPBranch(branchName);
        appInfo.setAppGitAPPSubProjectFolder(branchName);
        appInfo.setAppHomePage("https://www.winboll.cc/apks/index.php?project=PowerBell");
        appInfo.setAppAPKName("PowerBell");
        appInfo.setAppAPKFolderName("PowerBell");
        LogUtils.d(TAG, "genDefaultAppInfo: 退出");
        return appInfo;
    }

    // ======================== MainContentView 事件回调 ========================
    @Override
    public void onChargeReminderSwitchChanged(boolean isChecked) {
        LogUtils.d(TAG, "onChargeReminderSwitchChanged: 状态=" + isChecked);
        sendRestartRemindThreadMessage();
    }

    @Override
    public void onUsageReminderSwitchChanged(boolean isChecked) {
        LogUtils.d(TAG, "onUsageReminderSwitchChanged: 状态=" + isChecked);
        sendRestartRemindThreadMessage();
    }

    @Override
    public void onServiceSwitchChanged(boolean isChecked) {
        LogUtils.d(TAG, "onServiceSwitchChanged: 状态=" + isChecked);
        // 仅更新本地配置，不触发服务启停
        toggleServiceEnableState(isChecked);
    }

    @Override
    public void onChargeReminderProgressChanged(int progress) {
        LogUtils.d(TAG, "onChargeReminderProgressChanged: 进度=" + progress);
        sendRestartRemindThreadMessage();
    }

    @Override
    public void onUsageReminderProgressChanged(int progress) {
        LogUtils.d(TAG, "onUsageReminderProgressChanged: 进度=" + progress);
        sendRestartRemindThreadMessage();
    }
}

