package cc.winboll.studio.powerbell.services;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.TextUtils;
import androidx.core.app.NotificationCompat;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.ToastUtils;
import cc.winboll.studio.powerbell.R;
import cc.winboll.studio.powerbell.handlers.ControlCenterServiceHandler;
import cc.winboll.studio.powerbell.models.AppConfigBean;
import cc.winboll.studio.powerbell.models.ControlCenterServiceBean;
import cc.winboll.studio.powerbell.models.NotificationMessage;
import cc.winboll.studio.powerbell.threads.RemindThread;
import cc.winboll.studio.powerbell.utils.NotificationManagerUtils;
import java.io.Serializable;
import java.util.List;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/12/17 15:48
 * @Describe 电池提醒核心服务：修复前台服务超时异常，优先在onCreate发送通知，适配Java7+API30
 */
public class ControlCenterService extends Service {
    // ================================== 静态常量（置顶统一管理，避免魔法值）=================================
    public static final String TAG = "ControlCenterService";
    // 服务指令常量（带包名前缀，防止冲突）
    public static final String ACTION_RESTART_REMIND_THREAD = "cc.winboll.studio.powerbell.action.RESTART_REMIND_THREAD";
    public static final String EXTRA_APP_CONFIG_BEAN = "cc.winboll.studio.powerbell.extra.APP_CONFIG_BEAN";

    // ================================== 成员变量（按功能分类，私有封装+并发锁保护）=================================
    // 服务控制核心
    private ControlCenterServiceBean mServiceControlBean;
    // 业务核心组件
    private ControlCenterServiceHandler mServiceHandler;
    private RemindThread mRemindThread;
    private NotificationManagerUtils mNotificationManager;
    private AppConfigBean mCurrentConfigBean;
    private NotificationMessage mForegroundNotifyMsg;
    // 状态标记（复用 isServiceRunning 替代原 isCoreBusinessStarted）
    private static volatile boolean isServiceRunning;
    private static volatile boolean mIsDestroyed;

    // ================================== 服务生命周期方法（核心流程入口）=================================
    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.d(TAG, "onCreate: 服务开始创建");

        // 调用抽取的核心运行函数
        runCoreServiceLogic();
        LogUtils.d(TAG, "onCreate: 服务创建完成，前台通知已发送，启用状态=" + mServiceControlBean.isEnableService());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.d(TAG, "onStartCommand: 服务启动指令触发");
        // 读取最新控制配置
        loadLatestServiceControlConfig();
        // 调用抽取的核心运行函数
        runCoreServiceLogic();

		if (mServiceControlBean.isEnableService()) {
			LogUtils.d(TAG, "onStartCommand: 服务已启用，返回START_STICKY");
			return START_STICKY;
		} else {
			return super.onStartCommand(intent, flags, startId);
		}

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "onDestroy: 服务开始销毁");

        // 顺序释放资源
        stopForegroundService();
        stopRemindThreadSafely();
        destroyHandler();
        releaseNotificationResource();
        clearAllReferences();

		// 重置核心业务标记
		mCurrentConfigBean = null;
		mForegroundNotifyMsg = null;
		// 重置核心业务标记
		mServiceHandler = null;
		isServiceRunning = false;
		mIsDestroyed = true;
        LogUtils.d(TAG, "onDestroy: 服务销毁完成");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // ================================== 【核心抽取函数】运行服务核心逻辑 =================================
    /**
     * 抽取的服务核心运行逻辑，统一在onCreate和onStartCommand调用
     * 复用 isServiceRunning 做重复运行判断，避免重复初始化业务
     */
    private void runCoreServiceLogic() {
		loadLatestServiceControlConfig();

		// 核心校验：服务已启用 + 服务处于运行状态 + 未被销毁 + 业务未初始化（通过mServiceHandler判空）
		if (mServiceControlBean.isEnableService()) {
			if (!isServiceRunning) {
				isServiceRunning = true;
				mIsDestroyed = false;
				LogUtils.d(TAG, "runCoreServiceLogic: 开始执行服务核心业务");
				// 初始化通知 + 默认配置 + Handler + 线程
				// 优先发送前台通知，避免5秒超时异常
				initForegroundNotificationImmediately();
				// 加载本地服务控制配置

				//initNotificationManager();
				loadDefaultConfig();
				initServiceBusinessLogic();
				LogUtils.d(TAG, "runCoreServiceLogic: 核心业务执行完成");
			} else {
				LogUtils.d(TAG, "runCoreServiceLogic: 核心业务已在运行，无需重复执行");
			} 
		} else {
			LogUtils.d(TAG, "runCoreServiceLogic: 服务未启用，不执行核心业务");
		}

    }

    // ================================== 前台通知核心方法（优先执行，防止超时）=================================
    /**
     * 立即初始化前台通知，内置兜底方案
     */
    private void initForegroundNotificationImmediately() {
        LogUtils.d(TAG, "initForegroundNotificationImmediately: 初始化前台通知");
        try {
            if (mNotificationManager == null) {
                mNotificationManager = new NotificationManagerUtils(this);
            }
            if (mForegroundNotifyMsg == null) {
                mForegroundNotifyMsg = new NotificationMessage();
                mForegroundNotifyMsg.setTitle("电池监测服务");
                mForegroundNotifyMsg.setContent("后台运行中");
                mForegroundNotifyMsg.setRemindMSG("service_running");
            }
            mNotificationManager.startForegroundServiceNotify(this, mForegroundNotifyMsg);
			ToastUtils.show("startForegroundServiceNotify 已调用");
            LogUtils.d(TAG, "initForegroundNotificationImmediately: 前台通知发送成功，ID=" + NotificationManagerUtils.NOTIFY_ID_FOREGROUND_SERVICE);
        } catch (Exception e) {
            LogUtils.e(TAG, "initForegroundNotificationImmediately: 工具类发送失败，执行兜底方案", e);
            fallbackStartForeground();
        }
    }

    /**
     * 前台通知兜底方案，直接构建Notification
     */
    private void fallbackStartForeground() {
        try {
            Notification notification = new NotificationCompat.Builder(this, NotificationManagerUtils.CHANNEL_ID_FOREGROUND)
				.setContentTitle("电池监测服务")
				.setContentText("后台运行中")
				.setSmallIcon(R.drawable.ic_launcher)
				.setPriority(NotificationCompat.PRIORITY_LOW)
				.build();
            startForeground(NotificationManagerUtils.NOTIFY_ID_FOREGROUND_SERVICE, notification);
            LogUtils.d(TAG, "fallbackStartForeground: 兜底前台通知发送成功");
        } catch (Exception e) {
            LogUtils.e(TAG, "fallbackStartForeground: 兜底发送失败，服务会被系统杀死", e);
        }
    }

    // ================================== 服务控制配置管理（本地持久化+内存同步）=================================
    /**
     * 读取本地最新服务控制配置
     */
    private void loadLatestServiceControlConfig() {
        LogUtils.d(TAG, "loadLatestServiceControlConfig: 读取本地配置");
        ControlCenterServiceBean latestBean = ControlCenterServiceBean.loadBean(this, ControlCenterServiceBean.class);
		if (latestBean != null) {
			mServiceControlBean = latestBean;
			LogUtils.d(TAG, "loadLatestServiceControlConfig: 配置更新完成，启用状态=" + mServiceControlBean.isEnableService());
		} else {
			LogUtils.w(TAG, "loadLatestServiceControlConfig: 本地无配置，沿用当前状态");
		}
    }

    /**
     * 更新并持久化服务控制配置
     */
    private void updateAndSaveServiceControlConfig(ControlCenterServiceBean newControlBean) {
        ControlCenterServiceBean.saveBean(this, mServiceControlBean);
    }

    // ================================== 业务初始化与停止（按需加载，避免重复）=================================
    /**
     * 初始化通知管理工具类
     */
//    private void initNotificationManager() {
//        LogUtils.d(TAG, "initNotificationManager: 初始化通知工具");
//        if (mNotificationManager == null) {
//            mNotificationManager = new NotificationManagerUtils(this);
//        }
//        if (mForegroundNotifyMsg == null) {
//            mForegroundNotifyMsg = new NotificationMessage();
//            mForegroundNotifyMsg.setTitle("电池提醒服务运行中");
//            mForegroundNotifyMsg.setContent("后台持续监测电池状态");
//            mForegroundNotifyMsg.setRemindMSG("service_running");
//        }
//    }

    /**
     * 加载默认应用配置
     */
    private void loadDefaultConfig() {
        LogUtils.d(TAG, "loadDefaultConfig: 加载默认配置");
        if (mCurrentConfigBean == null) {
            mCurrentConfigBean = new AppConfigBean();
            mCurrentConfigBean.setEnableChargeReminder(true);
            mCurrentConfigBean.setChargeReminderValue(80);
            mCurrentConfigBean.setEnableUsageReminder(true);
            mCurrentConfigBean.setUsageReminderValue(20);
            mCurrentConfigBean.setBatteryDetectInterval(1000);
            LogUtils.d(TAG, "loadDefaultConfig: 默认配置加载完成");
        }
    }

    /**
     * 初始化业务核心逻辑（Handler+线程）
     */
    private void initServiceBusinessLogic() {
        LogUtils.d(TAG, "initServiceBusinessLogic: 初始化Handler与线程");
        if (mServiceHandler == null) {
            mServiceHandler = new ControlCenterServiceHandler(this);
        }
        restartRemindThreadSafely();
    }

    // ================================== 提醒线程管理（安全启停，并发保护）=================================
    /**
     * 安全重启提醒线程
     */
    public void restartRemindThreadSafely() {
        LogUtils.d(TAG, "restartRemindThreadSafely: 开始重启线程");

		// 停止旧线程
		stopRemindThreadSafely();
		if (mServiceHandler == null) {
			// 创建新线程实例
			RemindThread.destroyInstance();
			mRemindThread = RemindThread.getInstance(this, mServiceHandler);
			syncConfigToRemindThread();
			// 启动线程
			if (mRemindThread != null && !mRemindThread.isAlive() && !mRemindThread.isThreadStarted()) {
				try {
					mRemindThread.start();
					LogUtils.d(TAG, "restartRemindThreadSafely: 新线程启动成功，ID=" + mRemindThread.getId());
				} catch (IllegalThreadStateException e) {
					LogUtils.e(TAG, "restartRemindThreadSafely: 线程重复启动异常", e);
					mRemindThread = null;
				}
			} else {
				LogUtils.w(TAG, "restartRemindThreadSafely: 线程状态异常，跳过启动");
			}
		} else {
			LogUtils.d(TAG, "mServiceHandler is null");
		}

    }

    /**
     * 安全停止提醒线程
     */
    private void stopRemindThreadSafely() {
        LogUtils.d(TAG, "stopRemindThreadSafely: 停止提醒线程");
        if (mRemindThread == null) {
            LogUtils.w(TAG, "stopRemindThreadSafely: 线程实例为空");
            return;
        }
        try {
            if (mRemindThread.isThreadStarted() || mRemindThread.isAlive()) {
                mRemindThread.setIsReminding(false);
                mRemindThread.stopThread();
                // 等待线程终止，超时1秒强制中断
                long waitStartTime = System.currentTimeMillis();
                while (mRemindThread.isAlive()) {
                    if (System.currentTimeMillis() - waitStartTime > 1000) {
                        LogUtils.w(TAG, "stopRemindThreadSafely: 线程停止超时，强制中断");
                        mRemindThread.interrupt();
                        break;
                    }
                    Thread.yield();
                }
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "stopRemindThreadSafely: 停止线程异常", e);
        } finally {
            mRemindThread = null;
            RemindThread.destroyInstance();
        }
    }

    /**
     * 同步配置到提醒线程
     */
    private void syncConfigToRemindThread() {
        LogUtils.d(TAG, "syncConfigToRemindThread: 同步配置");
		if (mRemindThread == null || mCurrentConfigBean == null) {
			LogUtils.e(TAG, "syncConfigToRemindThread: 线程或配置为空，同步失败");
			return;
		}
		mRemindThread.setAppConfigBean(mCurrentConfigBean);
		mRemindThread.setIsReminding(true);
    }

    // ================================== 外部指令处理（接收Intent指令）=================================
    /**
     * 处理外部发送的服务指令
     */
//    private void handleExternalCommand(Intent intent) {
//        LogUtils.d(TAG, "handleExternalCommand: 处理外部指令");
//        if (intent == null || TextUtils.isEmpty(intent.getAction())) {
//            LogUtils.e(TAG, "handleExternalCommand: Intent或Action为空");
//            return;
//        }
//        String action = intent.getAction();
//        if (ACTION_RESTART_REMIND_THREAD.equals(action)) {
//            synchronized (mServiceLock) {
//                if (mServiceControlBean.isEnableService()) {
//                    AppConfigBean newConfig = (AppConfigBean) intent.getSerializableExtra(EXTRA_APP_CONFIG_BEAN);
//                    if (newConfig != null) {
//                        mCurrentConfigBean = newConfig;
//                        LogUtils.d(TAG, "handleExternalCommand: 收到配置更新，重启线程");
//                        restartRemindThreadSafely();
//                    } else {
//                        LogUtils.e(TAG, "handleExternalCommand: 配置为空，重启失败");
//                    }
//                } else {
//                    LogUtils.w(TAG, "handleExternalCommand: 服务已禁用，忽略指令");
//                }
//            }
//        }
//    }


    // ================================== 资源释放方法（防止内存泄漏）=================================
    /**
     * 停止前台服务
     */
    private void stopForegroundService() {
        LogUtils.d(TAG, "stopForegroundService: 停止前台服务");
        if (mNotificationManager != null) {
            mNotificationManager.cancelForegroundServiceNotify();
        }
        try {
            stopForeground(STOP_FOREGROUND_REMOVE);
        } catch (Exception e) {
            LogUtils.e(TAG, "stopForegroundService: 停止前台状态异常", e);
        }
    }

    /**
     * 销毁Handler
     */
    private void destroyHandler() {
        LogUtils.d(TAG, "destroyHandler: 销毁Handler");
        if (mServiceHandler != null) {
            mServiceHandler.removeCallbacksAndMessages(null);
            mServiceHandler = null;
        }
    }

    /**
     * 释放通知资源
     */
    private void releaseNotificationResource() {
        LogUtils.d(TAG, "releaseNotificationResource: 释放通知资源");
        if (mNotificationManager != null) {
            mNotificationManager.release();
            mNotificationManager = null;
        }
    }

    /**
     * 置空所有引用
     */
    private void clearAllReferences() {
        mForegroundNotifyMsg = null;
        mCurrentConfigBean = null;
        mServiceControlBean = null;
        LogUtils.d(TAG, "clearAllReferences: 所有引用已置空");
    }

    // ================================== 静态工具方法（对外提供服务入口）=================================
    /**
     * 启动服务
     */
    public static void startControlCenterService(Context context) {
        LogUtils.d(TAG, "startControlCenterService: 启动服务");
        if (context == null) {
            LogUtils.e(TAG, "startControlCenterService: Context为空");
            return;
        }

		// 保存服务启动配置
		ControlCenterServiceBean.saveBean(context, new ControlCenterServiceBean(true));

        Intent intent = new Intent(context, ControlCenterService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent);
			LogUtils.d(TAG, "startForegroundService 已调用");
        } else {
            context.startService(intent);
			LogUtils.d(TAG, "startService 已调用");
        }
    }

    /**
     * 停止服务
     */
    public static void stopControlCenterService(Context context) {
        LogUtils.d(TAG, "stopControlCenterService: 停止服务");
        if (context == null) {
            LogUtils.e(TAG, "stopControlCenterService: Context为空");
            return;
        }

		// 保存服务启动配置
		ControlCenterServiceBean.saveBean(context, new ControlCenterServiceBean(false));

        Intent intent = new Intent(context, ControlCenterService.class);
        context.stopService(intent);
    }

    /**
     * 更新服务控制配置并启停服务
     */
//    public static void updateServiceControlConfig(Context context, ControlCenterServiceBean controlBean) {
//        LogUtils.d(TAG, "updateServiceControlConfig: 更新控制配置，启用状态=" + controlBean.isEnableService());
//        if (context == null || controlBean == null) {
//            LogUtils.e(TAG, "updateServiceControlConfig: 参数为空");
//            return;
//        }
//        if (controlBean.isEnableService()) {
//            startControlCenterService(context);
//        } else {
//            stopControlCenterService(context);
//        }
//    }

    /**
     * 更新业务配置并触发线程重启
     */
    public static void updateStatus(Context context, AppConfigBean configBean) {
        LogUtils.d(TAG, "updateStatus: 发送配置更新指令");
        if (context == null || configBean == null) {
            LogUtils.e(TAG, "updateStatus: 参数为空");
            return;
        }
        Intent intent = new Intent(context, ControlCenterService.class);
        intent.setAction(ACTION_RESTART_REMIND_THREAD);
        intent.putExtra(EXTRA_APP_CONFIG_BEAN, (Serializable) configBean);
        intent.setPackage(context.getPackageName());
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "updateStatus: 发送指令异常", e);
        }
    }

    /**
     * 检查并引导用户开启忽略电池优化
     */
    public static void checkIgnoreBatteryOptimization(Context context) {
        LogUtils.d(TAG, "checkIgnoreBatteryOptimization: 检查电池优化状态");
        if (context == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return;
        }
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        if (powerManager == null) {
            LogUtils.e(TAG, "checkIgnoreBatteryOptimization: PowerManager获取失败");
            return;
        }
        try {
            boolean isIgnored = powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
            if (!isIgnored) {
                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(intent);
                LogUtils.d(TAG, "checkIgnoreBatteryOptimization: 引导用户开启忽略电池优化");
            }
        } catch (Exception e) {
            LogUtils.e(TAG, "checkIgnoreBatteryOptimization: 引导异常", e);
        }
    }

    /**
     * 判断服务是否运行（适配API30+）
     */
    private static boolean isServiceRunning(Context context, Class<?> serviceClass) {
        if (context == null || serviceClass == null) {
            return false;
        }
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (am == null) {
            LogUtils.e(TAG, "isServiceRunning: ActivityManager获取失败");
            return false;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            String packageName = context.getPackageName();
            List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();
            if (processes != null) {
                for (ActivityManager.RunningAppProcessInfo process : processes) {
                    if (packageName.equals(process.processName) &&
						(process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE ||
						process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)) {
                        return true;
                    }
                }
            }
            return isServiceStarted(context, serviceClass);
        } else {
            List<ActivityManager.RunningServiceInfo> runningServices = am.getRunningServices(100);
            if (runningServices != null) {
                String serviceClassName = serviceClass.getName();
                for (ActivityManager.RunningServiceInfo info : runningServices) {
                    if (serviceClassName.equals(info.service.getClassName())) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

    /**
     * 兜底判断服务是否已启动
     */
    private static boolean isServiceStarted(Context context, Class<?> serviceClass) {
        try {
            ControlCenterServiceBean controlBean = ControlCenterServiceBean.loadBean(context, ControlCenterServiceBean.class);
            return controlBean != null && controlBean.isEnableService();
        } catch (Exception e) {
            LogUtils.e(TAG, "isServiceStarted: 兜底判断异常", e);
            return false;
        }
    }

    // ================================== Getter/Setter 方法（线程安全）=================================
    public RemindThread getRemindThread() {
		return mRemindThread;
    }

    public void setCurrentConfigBean(AppConfigBean configBean) {
        LogUtils.d(TAG, "setCurrentConfigBean: 更新业务配置");
        if (configBean == null) {
            LogUtils.e(TAG, "setCurrentConfigBean: 配置为空");
            return;
        }
		this.mCurrentConfigBean = configBean;
		syncConfigToRemindThread();
    }

//    public void setServiceControlBean(ControlCenterServiceBean controlBean) {
//        LogUtils.d(TAG, "setServiceControlBean: 更新控制配置");
//        if (controlBean != null) {
//            updateAndSaveServiceControlConfig(controlBean);
//        }
//    }

    public ControlCenterServiceBean getServiceControlBean() {
		return mServiceControlBean;
    }

    public NotificationManagerUtils getNotificationManager() {
		return mNotificationManager;
    }

    public NotificationMessage getForegroundNotifyMsg() {
		return mForegroundNotifyMsg;
    }

    public AppConfigBean getCurrentConfigBean() {
		return mCurrentConfigBean;
    }

    public boolean isDestroyed() {
		return mIsDestroyed;
    }
}

