package cc.winboll.studio.powerbell.receivers;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.powerbell.models.AppConfigBean;
import cc.winboll.studio.powerbell.models.NotificationMessage;
import cc.winboll.studio.powerbell.services.ControlCenterService;
import cc.winboll.studio.powerbell.threads.RemindThread;
import cc.winboll.studio.powerbell.utils.AppConfigUtils;
import cc.winboll.studio.powerbell.utils.BatteryUtils;
import cc.winboll.studio.powerbell.utils.NotificationManagerUtils;
import java.lang.ref.WeakReference;

/**
 * 控制中心广播接收器：监听电池状态变化、通知更新、线程启动指令，适配API29-30及小米手机
 */
public class ControlCenterServiceReceiver extends BroadcastReceiver {
    // ====================== 常量定义（顶部统一管理，清晰易维护） ======================
    public static final String TAG = ControlCenterServiceReceiver.class.getSimpleName();
    public static final String ACTION_UPDATE_SERVICENOTIFICATION = "cc.winboll.studio.powerbell.action.UPDATE_SERVICENOTIFICATION";
    public static final String ACTION_START_REMINDTHREAD = "cc.winboll.studio.powerbell.action.START_REMINDTHREAD";
    public static final String EXTRA_APP_CONFIG_BEAN = "extra_app_config_bean";

    // ====================== 成员变量（弱引用防泄漏，volatile保线程安全） ======================
    private WeakReference<ControlCenterService> mwrControlCenterService;
    private static volatile int sLastBatteryLevel = -1;
    private static volatile boolean sIsCharging = false;

    // ====================== 构造方法 ======================
    public ControlCenterServiceReceiver(ControlCenterService service) {
        LogUtils.d(TAG, "constructor: init receiver");
        this.mwrControlCenterService = new WeakReference<>(service);
    }

    // ====================== 广播核心接收逻辑 ======================
    @Override
    public void onReceive(Context context, Intent intent) {
        LogUtils.d(TAG, "onReceive: enter, action=" + intent.getAction());
        if (context == null || intent == null || intent.getAction() == null) {
            LogUtils.e(TAG, "onReceive: invalid params");
            return;
        }

        // 弱引用获取服务，双重校验服务有效性（核心防护，避免内存泄漏+空指针）
        ControlCenterService service = mwrControlCenterService != null ? mwrControlCenterService.get() : null;
        if (service == null || service.isDestroyed()) {
            LogUtils.e(TAG, "onReceive: ControlCenterService is destroyed or null");
            // 服务销毁后主动注销广播，彻底避免无效回调
            unregisterAction(context);
            return;
        }

        // 分action处理逻辑
        String action = intent.getAction();
        switch (action) {
            case ACTION_UPDATE_SERVICENOTIFICATION:
                handleUpdateServiceNotification(service);
                break;
            case Intent.ACTION_BATTERY_CHANGED:
                handleBatteryStateChanged(context, service, intent);
                break;
            case ACTION_START_REMINDTHREAD:
                handleStartRemindThread(service, intent);
                break;
            default:
                LogUtils.w(TAG, "onReceive: unknown action=" + action);
        }
        LogUtils.d(TAG, "onReceive: exit");
    }

    // ====================== 业务逻辑方法（全链路容错+逻辑优化） ======================
    /**
     * 处理前台服务通知更新（强化非空校验，适配工具类最新逻辑）
     */
    private void handleUpdateServiceNotification(ControlCenterService service) {
        LogUtils.d(TAG, "handleUpdateServiceNotification: start");
        try {
            NotificationManagerUtils notifyUtils = service.getNotificationManager();
            NotificationMessage notifyMsg = service.getForegroundNotifyMsg();
            // 三重非空校验，避免工具类/消息/通知实例为空
            if (notifyUtils == null || notifyMsg == null) {
                LogUtils.e(TAG, "handleUpdateServiceNotification: notify params null, rebuild notify first");
                // 兜底：通知实例为空时重建前台通知（适配工具类方法，避免空指针）
                if (notifyUtils != null) {
                    notifyUtils.startForegroundServiceNotify(service, notifyMsg);
                }
                return;
            }
            // 调用工具类更新通知，确保方法匹配
            notifyUtils.updateForegroundServiceNotify(notifyMsg);
            LogUtils.d(TAG, "handleUpdateServiceNotification: success");
        } catch (Exception e) {
            LogUtils.e(TAG, "handleUpdateServiceNotification: failed", e);
        }
    }

    /**
     * 处理电池状态变化（核心适配 BatteryUtils，修复解析逻辑）
     */
    private void handleBatteryStateChanged(Context context, ControlCenterService service, Intent intent) {
        LogUtils.d(TAG, "handleBatteryStateChanged: start");
        try {
            // 1. 适配 BatteryUtils 工具类：统一解析电池状态（删除错误的 getTheQuantityOfElectricity）
            boolean currentCharging = BatteryUtils.isCharging(context); // 调用工具类判断充电状态
            int currentBatteryLevel = BatteryUtils.getCurrentBattery(context); // 调用工具类获取电量（0-100）
            currentBatteryLevel = Math.min(Math.max(currentBatteryLevel, 0), 100); // 二次校验，确保范围有效
            LogUtils.d(TAG, "handleBatteryStateChanged: current state - charging=" + currentCharging + ", level=" + currentBatteryLevel);

            // 2. 状态无变化直接跳过，减少无效运算
            if (currentCharging == sIsCharging && currentBatteryLevel == sLastBatteryLevel) {
                LogUtils.d(TAG, "handleBatteryStateChanged: no state change, skip");
                return;
            }

            // 3. 加载最新配置（容错：配置加载失败用服务当前配置兜底）
            AppConfigBean latestConfig = loadLatestConfig(context);
            if (latestConfig == null) {
                LogUtils.e(TAG, "handleBatteryStateChanged: load latest config failed, use service current config");
                latestConfig = service.getCurrentConfigBean();
                // 服务配置也为空时，加载默认配置
                if (latestConfig == null) {
                    latestConfig = new AppConfigBean();
                }
            }

            // 4. 同步最新电池状态到配置，再更新服务配置（确保服务配置是最新的）
            latestConfig.setCurrentBatteryValue(currentBatteryLevel);
            latestConfig.setIsCharging(currentCharging);
            service.setCurrentConfigBean(latestConfig);

            // 5. 智能更新线程（线程已初始化则更新配置，未初始化则启动，避免重复重启）
            updateRemindThreadConfig(service, latestConfig, currentCharging, currentBatteryLevel);

            // 6. 缓存最新状态（volatile变量确保多线程可见性）
            sIsCharging = currentCharging;
            sLastBatteryLevel = currentBatteryLevel;
            LogUtils.d(TAG, "handleBatteryStateChanged: success");
        } catch (Exception e) {
            LogUtils.e(TAG, "handleBatteryStateChanged: failed", e);
        }
    }

    /**
     * 处理线程启动指令（优化配置解析逻辑，强化线程启动容错）
     */
    private void handleStartRemindThread(ControlCenterService service, Intent intent) {
        LogUtils.d(TAG, "handleStartRemindThread: start");
        try {
            // 安全解析配置（避免序列化异常）
            AppConfigBean appConfigBean = null;
            if (intent.hasExtra(EXTRA_APP_CONFIG_BEAN)) {
                Object configObj = intent.getSerializableExtra(EXTRA_APP_CONFIG_BEAN);
                if (configObj instanceof AppConfigBean) {
                    appConfigBean = (AppConfigBean) configObj;
                    // 配置补全：确保电池状态字段不为默认值（用缓存的最新状态）
                    appConfigBean.setIsCharging(sIsCharging);
                    appConfigBean.setCurrentBatteryValue(sLastBatteryLevel);
                }
            }

            if (appConfigBean != null) {
                // 先更新服务配置，再重启线程（确保线程启动时拿到最新配置）
                service.setCurrentConfigBean(appConfigBean);
                // 重启线程（服务已实现安全重启逻辑，直接调用）
                service.restartRemindThreadSafely();
                LogUtils.d(TAG, "handleStartRemindThread: success, thread restarted with new config");
            } else {
                LogUtils.e(TAG, "handleStartRemindThread: appConfigBean is null or invalid");
                // 配置无效时，用缓存状态重启线程兜底
                service.restartRemindThreadSafely();
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "handleStartRemindThread: failed", e);
        }
    }

    // ====================== 内部辅助方法（拆分逻辑+统一容错） ======================
    /**
     * 加载最新配置（适配AppConfigUtils单例逻辑，强化异常捕获）
     */
    private AppConfigBean loadLatestConfig(Context context) {
        try {
            if (context == null) {
                LogUtils.e(TAG, "loadLatestConfig: context is null");
                return null;
            }
            AppConfigUtils configUtils = AppConfigUtils.getInstance(context);
            if (configUtils == null) {
                LogUtils.e(TAG, "loadLatestConfig: AppConfigUtils instance is null");
                return null;
            }
            // 强制重载配置，确保拿到最新用户设置
            configUtils.reloadAllConfig();
            return configUtils.mAppConfigBean;
        } catch (Exception e) {
            LogUtils.e(TAG, "loadLatestConfig: failed to load config", e);
            return null;
        }
    }

    /**
     * 更新提醒线程配置（智能判断线程状态，避免唤醒/启动冲突）
     */
    private void updateRemindThreadConfig(ControlCenterService service, AppConfigBean config, boolean isCharging, int batteryLevel) {
        try {
            RemindThread remindThread = service.getRemindThread();
            if (remindThread == null) {
                LogUtils.w(TAG, "updateRemindThreadConfig: remindThread is null, start thread first");
                // 线程未初始化，安全启动线程（服务方法已实现容错）
                service.restartRemindThreadSafely();
                return;
            }

            // 先同步完整配置（核心：setAppConfigBean已包含状态同步，无需重复设置）
            remindThread.setAppConfigBean(config);
            // 额外同步实时状态（兜底，确保最新）
            remindThread.setIsCharging(isCharging);
            remindThread.setQuantityOfElectricity(batteryLevel);
            // 确保线程开启提醒功能
            remindThread.setIsReminding(true);

            // 线程未运行时唤醒，已运行时无需操作（避免重复唤醒导致逻辑紊乱）
            if (!remindThread.isRunning()) {
                synchronized (remindThread) {
                    remindThread.notify();
                    LogUtils.d(TAG, "updateRemindThreadConfig: remindThread is woken up");
                }
            }
            LogUtils.d(TAG, "updateRemindThreadConfig: success, thread config updated");
        } catch (Exception e) {
            LogUtils.e(TAG, "updateRemindThreadConfig: failed", e);
            // 配置更新失败时，重启线程兜底
            service.restartRemindThreadSafely();
        }
    }

    // ====================== 广播注册/注销（强化容错，避免重复注册/注销） ======================
    public void registerAction(Context context) {
        LogUtils.d(TAG, "registerAction: start");
        if (context == null) {
            LogUtils.e(TAG, "registerAction: context is null");
            return;
        }

        try {
            // 先注销再注册，避免重复注册导致异常
            unregisterAction(context);
            IntentFilter filter = new IntentFilter();
            filter.addAction(ACTION_UPDATE_SERVICENOTIFICATION);
            filter.addAction(ACTION_START_REMINDTHREAD);
            filter.addAction(Intent.ACTION_BATTERY_CHANGED);
            // 优先级设置（低于系统最高优先级，避免被系统拦截）
            filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY - 10);
            context.registerReceiver(this, filter);
            LogUtils.d(TAG, "registerAction: success, broadcast receiver registered");
        } catch (Exception e) {
            LogUtils.e(TAG, "registerAction: failed to register receiver", e);
        }
    }

    public void unregisterAction(Context context) {
        LogUtils.d(TAG, "unregisterAction: start");
        if (context == null) {
            LogUtils.e(TAG, "unregisterAction: context is null");
            return;
        }

        try {
            // 捕获注销异常（避免未注册时注销抛错）
            context.unregisterReceiver(this);
            LogUtils.d(TAG, "unregisterAction: success, broadcast receiver unregistered");
        } catch (IllegalArgumentException e) {
            LogUtils.w(TAG, "unregisterAction: receiver not registered, skip");
        } catch (Exception e) {
            LogUtils.e(TAG, "unregisterAction: failed to unregister receiver", e);
        }
    }

    // ====================== Getter方法（提供外部状态访问，强化线程安全） ======================
    public static int getLastBatteryLevel() {
        return sLastBatteryLevel;
    }

    public static boolean isLastCharging() {
        return sIsCharging;
    }

    // ====================== 主动释放资源（修复语法错误，彻底防泄漏） ======================
    public void release() {
        LogUtils.d(TAG, "release: receiver release resources");
        // 置空弱引用，帮助GC回收
        if (mwrControlCenterService != null) {
            mwrControlCenterService.clear();
            mwrControlCenterService = null;
        }
        // 重置静态状态缓存（修复重复赋值语法错误）
        sLastBatteryLevel = -1;
        sIsCharging = false;
    }
}

