package cc.winboll.studio.contacts.services;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import cc.winboll.studio.contacts.R;
import cc.winboll.studio.contacts.bobulltoon.TomCat;
import cc.winboll.studio.contacts.dun.Rules;
import cc.winboll.studio.contacts.handlers.MainServiceHandler;
import cc.winboll.studio.contacts.listenphonecall.CallListenerService;
import cc.winboll.studio.contacts.model.MainServiceBean;
import cc.winboll.studio.contacts.model.RingTongBean;
import cc.winboll.studio.contacts.receivers.MainReceiver;
import cc.winboll.studio.contacts.threads.MainServiceThread;
import cc.winboll.studio.contacts.utils.AppForegroundUtils;
import cc.winboll.studio.libappbase.LogUtils;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/02/13 06:56:41
 * @Describe 拨号主服务，负责核心业务逻辑、守护进程绑定、铃声音量监控及通话监听启动
 * 严格适配 Android API 30 + Java 7 语法规范 | 解决前台服务启动超时崩溃
 * 新增：统一在 mainService() 中启动电话监听服务 + 通话筛选服务
 */
public class MainService extends Service {
    // ====================== 常量定义区（全硬编码，杜绝高版本 API 依赖） ======================
    public static final String TAG = "MainService";
    public static final int MSG_UPDATE_STATUS = 0;
    // 铃声音量检查定时器参数
    private static final long VOLUME_CHECK_DELAY = 1000L;
    private static final long VOLUME_CHECK_PERIOD = 60000L;
    // 前台服务通知配置
    private static final String FOREGROUND_CHANNEL_ID = "main_service_foreground_channel";
    private static final int FOREGROUND_NOTIFICATION_ID = 1001;
    // 前台服务类型硬编码：dataSync(0x01) | 替代 Build.VERSION_CODES 高版本常量
    private static final int FOREGROUND_SERVICE_TYPE_DATA_SYNC = 0x00000001;
    // Android 版本常量硬编码 | Java 7 不支持 Build.VERSION_CODES 高版本引用
    private static final int ANDROID_8_API = 26;
    private static final int ANDROID_10_API = 29;
    private static final int ANDROID_12_API = 31;
    // 重试延迟时间 & 非核心服务延迟启动时间
    private static final long RETRY_DELAY_MS = 3000L;
    private static final long DELAY_NON_CORE_SERVICE_MS = 100L;

    // ====================== 静态成员变量区 ======================
    private static MainService sMainServiceInstance;
    private static volatile TomCat sTomCatInstance;

    // ====================== 成员变量区 ======================
    private volatile boolean mIsServiceRunning;
    private MainServiceBean mMainServiceBean;
    private MainServiceThread mMainServiceThread;
    private MainServiceHandler mMainServiceHandler;
    private MyServiceConnection mMyServiceConnection;
    private AssistantService mAssistantService;
    private boolean mIsBound;
    private MainReceiver mMainReceiver;
    private Timer mStreamVolumeCheckTimer;
    private Handler mDelayHandler;

    // ====================== Binder 内部类 ======================
    public class MyBinder extends Binder {
        public MainService getService() {
            LogUtils.d(TAG, "MyBinder.getService: 获取 MainService 实例");
            return MainService.this;
        }
    }

    // ====================== ServiceConnection 内部类 ======================
    private class MyServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (service == null) {
                LogUtils.w(TAG, "MyServiceConnection.onServiceConnected: 绑定的 IBinder 为 null");
                mIsBound = false;
                return;
            }

            try {
                AssistantService.MyBinder binder = (AssistantService.MyBinder) service;
                mAssistantService = binder.getService();
                mIsBound = true;
                LogUtils.d(TAG, "MyServiceConnection.onServiceConnected: 守护服务绑定成功 | AssistantService=" + mAssistantService);
            } catch (ClassCastException e) {
                LogUtils.e(TAG, "MyServiceConnection.onServiceConnected: IBinder 类型转换失败", e);
                mIsBound = false;
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            LogUtils.w(TAG, "MyServiceConnection.onServiceDisconnected: 守护服务连接断开");
            mAssistantService = null;
            mIsBound = false;

            // 服务启用则重试绑定
            if (mMainServiceBean != null && mMainServiceBean.isEnable()) {
                LogUtils.d(TAG, "MyServiceConnection.onServiceDisconnected: 重新唤醒并绑定守护服务");
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
						@Override
						public void run() {
							wakeupAndBindAssistant();
						}
					}, RETRY_DELAY_MS);
            } else {
                LogUtils.w(TAG, "MyServiceConnection.onServiceDisconnected: 服务未启用，跳过重试");
            }
        }
    }

    // ====================== 对外静态方法区 ======================
    public static boolean isPhoneInBoBullToon(String phone) {
        if (sTomCatInstance != null && phone != null && !phone.isEmpty()) {
            return sTomCatInstance.isPhoneBoBullToon(phone);
        }
        LogUtils.w(TAG, "isPhoneInBoBullToon: TomCat 未初始化或号码为空");
        return false;
    }

    public static void stopMainService(Context context) {
        if (context == null) {
            LogUtils.e(TAG, "stopMainService: Context 为 null，无法执行");
            return;
        }
        LogUtils.d(TAG, "stopMainService: 执行停止主服务操作");
        context.stopService(new Intent(context, MainService.class));
    }

    public static void startMainService(Context context) {
        if (context == null) {
            LogUtils.e(TAG, "startMainService: Context 为 null，无法执行");
            return;
        }
        LogUtils.d(TAG, "startMainService: 执行启动主服务操作");
        Intent intent = new Intent(context, MainService.class);
        // API 30 属于 Android 10+，按前台服务逻辑处理
        if (Build.VERSION.SDK_INT >= ANDROID_10_API && !AppForegroundUtils.isAppForeground(context)) {
            LogUtils.d(TAG, "startMainService: 应用后台，使用 startForegroundService 启动");
            context.startForegroundService(intent);
        } else {
            context.startService(intent);
        }
    }

    public static void restartMainService(Context context) {
        if (context == null) {
            LogUtils.e(TAG, "restartMainService: Context 为 null，无法执行");
            return;
        }
        LogUtils.d(TAG, "restartMainService: 执行重启主服务操作");

        MainServiceBean bean = MainServiceBean.loadBean(context, MainServiceBean.class);
        if (bean != null && bean.isEnable()) {
            stopMainService(context);
            startMainService(context);
            LogUtils.i(TAG, "restartMainService: 主服务重启完成");
        } else {
            LogUtils.w(TAG, "restartMainService: 主服务配置未启用，跳过重启");
        }
    }

    public static void stopMainServiceAndSaveStatus(Context context) {
        if (context == null) {
            LogUtils.e(TAG, "stopMainServiceAndSaveStatus: Context 为 null，无法执行");
            return;
        }
        LogUtils.d(TAG, "stopMainServiceAndSaveStatus: 停止服务并保存禁用状态");
        MainServiceBean bean = new MainServiceBean();
        bean.setIsEnable(false);
        MainServiceBean.saveBean(context, bean);
        stopMainService(context);
    }

    public static void startMainServiceAndSaveStatus(Context context) {
        if (context == null) {
            LogUtils.e(TAG, "startMainServiceAndSaveStatus: Context 为 null，无法执行");
            return;
        }
        LogUtils.d(TAG, "startMainServiceAndSaveStatus: 启动服务并保存启用状态");
        MainServiceBean bean = new MainServiceBean();
        bean.setIsEnable(true);
        MainServiceBean.saveBean(context, bean);
        startMainService(context);
    }

    // ====================== 成员方法区 ======================
    /**
     * 补充缺失的 appenMessage 方法
     */
    public void appenMessage(String message) {
        String msg = message == null ? "null" : message;
        LogUtils.d(TAG, "追加消息: " + msg);

        if (mMainServiceHandler != null) {
            android.os.Message handlerMsg = android.os.Message.obtain();
            handlerMsg.what = MSG_UPDATE_STATUS;
            handlerMsg.obj = msg;
            mMainServiceHandler.sendMessage(handlerMsg);
        }
    }

    /**
     * 服务启动前置校验
     */
    private boolean canStartService(Class<?> serviceClass) {
        // 服务未启用/已运行 → 禁止启动
        if (mMainServiceBean == null || !mMainServiceBean.isEnable()) {
            LogUtils.w(TAG, "canStartService: 主服务未启用，禁止启动 " + serviceClass.getSimpleName());
            return false;
        }
        if (isServiceRunning(serviceClass)) {
            LogUtils.d(TAG, "canStartService: " + serviceClass.getSimpleName() + " 已运行，跳过启动");
            return false;
        }
        // Android 12+ 应用后台 → 禁止启动非核心服务
        if (Build.VERSION.SDK_INT >= ANDROID_12_API && !AppForegroundUtils.isAppForeground(this)) {
            LogUtils.w(TAG, "canStartService: Android 12+ 应用后台，禁止启动 " + serviceClass.getSimpleName());
            return false;
        }
        return true;
    }

    /**
     * 延迟启动非核心服务
     */
    private void delayStartNonCoreService(final Class<?> serviceClass) {
        if (!canStartService(serviceClass)) {
            return;
        }
        mDelayHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					Intent intent = new Intent(MainService.this, serviceClass);
					try {
						if (Build.VERSION.SDK_INT >= ANDROID_10_API && !AppForegroundUtils.isAppForeground(MainService.this)) {
							startForegroundService(intent);
						} else {
							startService(intent);
						}
						LogUtils.d(TAG, "delayStartNonCoreService: " + serviceClass.getSimpleName() + " 启动成功");
					} catch (Exception e) {
						LogUtils.e(TAG, "delayStartNonCoreService: " + serviceClass.getSimpleName() + " 启动失败", e);
					}
				}
			}, DELAY_NON_CORE_SERVICE_MS);
    }

    /**
     * 创建前台服务通知
     */
    private Notification createForegroundNotification() {
        // 1. 创建通知渠道（Android 8.0+ 必需）
        if (Build.VERSION.SDK_INT >= ANDROID_8_API) {
            NotificationChannel channel = new NotificationChannel(
                FOREGROUND_CHANNEL_ID,
                "拨号主服务",
                NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("主服务后台运行，保障拨号功能正常");
            channel.setSound(null, null);
            channel.enableVibration(false);

            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            if (manager != null) {
                manager.createNotificationChannel(channel);
                LogUtils.d(TAG, "createForegroundNotification: 通知渠道创建成功");
            } else {
                LogUtils.e(TAG, "createForegroundNotification: NotificationManager 获取失败");
            }
        }

        // 2. 构建通知
        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= ANDROID_8_API) {
            builder = new Notification.Builder(this, FOREGROUND_CHANNEL_ID);
        } else {
            builder = new Notification.Builder(this);
        }
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle("拨号服务运行中");
        builder.setContentText("正在后台保障通话监听与号码识别");
        builder.setPriority(Notification.PRIORITY_LOW);
        builder.setOngoing(true);

        return builder.build();
    }

    /**
     * 启动电话监听服务（原有：CallListenerService）
     */
    private void startPhoneCallListener() {
        delayStartNonCoreService(CallListenerService.class);
    }

    /**
     * 新增：启动通话筛选服务（MyCallScreeningService，API 10+ 生效）
     */
    private void startCallScreeningService() {
        // 通话筛选服务仅 Android 10+（API 29+）支持，低版本跳过
        if (Build.VERSION.SDK_INT >= ANDROID_10_API) {
            delayStartNonCoreService(MyCallScreeningService.class);
        } else {
            LogUtils.d(TAG, "startCallScreeningService: 系统版本低于 Android 10，不支持通话筛选服务，跳过启动");
        }
    }

    /**
     * 检查服务是否正在运行
     */
    private boolean isServiceRunning(Class<?> serviceClass) {
        if (serviceClass == null) {
            LogUtils.e(TAG, "isServiceRunning: 服务类参数为 null");
            return false;
        }

        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (manager == null) {
            LogUtils.w(TAG, "isServiceRunning: ActivityManager 获取失败");
            return false;
        }

        for (ActivityManager.RunningServiceInfo info : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(info.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    // ====================== Service 生命周期方法区 ======================
    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.d(TAG, "===== onCreate: 主服务开始创建 =====");
        sMainServiceInstance = this;
        mIsServiceRunning = false;

        // 仅初始化核心组件
        mMainServiceBean = MainServiceBean.loadBean(this, MainServiceBean.class);
        mMyServiceConnection = new MyServiceConnection();
        mMainServiceHandler = new MainServiceHandler(this);
        mDelayHandler = new Handler(Looper.getMainLooper());

        // 初始化铃声音量检查定时器
        initVolumeCheckTimer();

        LogUtils.d(TAG, "===== onCreate: 主服务创建完成（仅初始化组件） =====");
    }

    @Override
    public IBinder onBind(Intent intent) {
        LogUtils.d(TAG, "onBind: 服务被绑定 | Intent=" + intent);
        return new MyBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtils.d(TAG, "onStartCommand: 服务被启动 | startId=" + startId);
        mainService();
        return (mMainServiceBean != null && mMainServiceBean.isEnable()) ? START_STICKY : super.onStartCommand(intent, flags, startId);
    }

    // ====================== onDestroy：强制全量清理，不改动 Bean 配置 ======================
    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.d(TAG, "===== onDestroy: 主服务开始销毁（强制清理所有资源） =====");

        // 1. 强制标记服务为未运行
        mIsServiceRunning = false;

        // 2. 释放延迟 Handler 资源
        if (mDelayHandler != null) {
            mDelayHandler.removeCallbacksAndMessages(null);
            mDelayHandler = null;
        }

        // 3. 释放定时器资源
        cancelVolumeCheckTimer();

        // 4. 强制解除守护服务绑定
        if (mIsBound && mMyServiceConnection != null) {
            try {
                unbindService(mMyServiceConnection);
                LogUtils.d(TAG, "onDestroy: 解除守护服务绑定成功");
            } catch (IllegalArgumentException e) {
                LogUtils.w(TAG, "onDestroy: 解除绑定失败，服务未绑定", e);
            }
            mIsBound = false;
            mMyServiceConnection = null;
        }

        // 5. 强制注销广播接收器
        if (mMainReceiver != null) {
            mMainReceiver.unregisterAction(this);
            mMainReceiver = null;
            LogUtils.d(TAG, "onDestroy: 广播接收器已注销");
        }

        // 6. 强制停止主业务线程
        if (mMainServiceThread != null) {
            mMainServiceThread.setIsExit(true);
            mMainServiceThread = null;
        }

        // 7. 强制停止所有子服务（新增：停止通话筛选服务 MyCallScreeningService）
        stopService(new Intent(this, AssistantService.class));
        stopService(new Intent(this, CallListenerService.class));
        stopService(new Intent(this, MyCallScreeningService.class));
        LogUtils.d(TAG, "onDestroy: 所有子服务已强制停止");

        // 8. 清空静态实例，避免内存泄漏（不改动 Bean 配置）
        sMainServiceInstance = null;
        sTomCatInstance = null;
        mMainServiceHandler = null;
        mAssistantService = null;
        mMainServiceBean = null;

        LogUtils.d(TAG, "===== onDestroy: 主服务销毁完成（资源全清理，Bean 配置无改动） =====");
    }

    // ====================== 核心业务逻辑：优先判断运行状态 → 再校验配置启用状态 ======================
    private void mainService() {
        LogUtils.d(TAG, "mainService: 执行核心业务逻辑");

        // 第一步：优先判断服务是否已运行，已运行则直接退出（不做任何动作）
        if (mIsServiceRunning) {
            LogUtils.d(TAG, "mainService: 服务已处于运行状态，直接退出");
            return;
        }

        // 第二步：加载最新配置，校验服务是否启用（未启用则退出）
        mMainServiceBean = MainServiceBean.loadBean(this, MainServiceBean.class);
        if (mMainServiceBean == null || !mMainServiceBean.isEnable()) {
            LogUtils.w(TAG, "mainService: 服务配置未启用/配置加载失败，退出启动流程");
            return;
        }

        // 第三步：配置启用且服务未运行，执行启动流程
        mIsServiceRunning = true;
        LogUtils.i(TAG, "mainService: 服务未运行且配置已启用，开始启动核心流程");

        // 1. 启动前台服务（优先执行，避免超时）
        try {
            Notification foregroundNotification = createForegroundNotification();
            if (Build.VERSION.SDK_INT >= ANDROID_10_API) {
                startForeground(FOREGROUND_NOTIFICATION_ID, foregroundNotification, FOREGROUND_SERVICE_TYPE_DATA_SYNC);
                LogUtils.d(TAG, "mainService: 主服务已启动为前台服务（dataSync 类型，API30+）");
            } else {
                startForeground(FOREGROUND_NOTIFICATION_ID, foregroundNotification);
                LogUtils.d(TAG, "mainService: 主服务已启动为前台服务（低版本兼容）");
            }
        } catch (IllegalArgumentException e) {
            LogUtils.e(TAG, "mainService: 启动前台服务失败，类型不匹配", e);
            mIsServiceRunning = false;
            stopSelf();
            return;
        } catch (Exception e) {
            LogUtils.e(TAG, "mainService: 启动前台服务异常", e);
            mIsServiceRunning = false;
            stopSelf();
            return;
        }

        // 2. 绑定守护服务
        wakeupAndBindAssistant();

        // 3. 初始化业务组件
        initTomCat();
        initMainReceiver();
        Rules.getInstance(this).loadRules();
        LogUtils.d(TAG, "mainService: 黑白名单规则已加载");

        // 4. 启动电话监听服务（原有：CallListenerService）
        startPhoneCallListener();

        // 5. 新增：启动通话筛选服务（MyCallScreeningService，API 10+ 生效）
        startCallScreeningService();

        // 6. 启动主业务线程
        mMainServiceThread = MainServiceThread.getInstance(this, mMainServiceHandler);
        mMainServiceThread.start();
        LogUtils.i(TAG, "mainService: 核心流程启动完成，主服务正常运行");
    }

    private void wakeupAndBindAssistant() {
        if (mMyServiceConnection == null) {
            LogUtils.e(TAG, "wakeupAndBindAssistant: 初始化失败，绑定失败");
            return;
        }
        Intent intent = new Intent(this, AssistantService.class);
        if (Build.VERSION.SDK_INT >= ANDROID_10_API && !AppForegroundUtils.isAppForeground(this)) {
            LogUtils.d(TAG, "wakeupAndBindAssistant: 应用后台，启动 AssistantService 为前台服务");
            startForegroundService(intent);
        } else {
            startService(intent);
        }
        bindService(intent, mMyServiceConnection, Context.BIND_IMPORTANT);
        LogUtils.d(TAG, "wakeupAndBindAssistant: 已启动并绑定守护服务");
    }

    // ====================== 铃声音量监控相关方法区 ======================
    private void initVolumeCheckTimer() {
        cancelVolumeCheckTimer();
        mStreamVolumeCheckTimer = new Timer();
        mStreamVolumeCheckTimer.schedule(new TimerTask() {
				@Override
				public void run() {
					checkAndRestoreRingerVolume();
				}
			}, VOLUME_CHECK_DELAY, VOLUME_CHECK_PERIOD);
        LogUtils.d(TAG, "initVolumeCheckTimer: 铃声音量检查定时器已启动");
    }

    private void checkAndRestoreRingerVolume() {
        AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioManager == null) {
            LogUtils.e(TAG, "checkAndRestoreRingerVolume: 获取 AudioManager 失败");
            return;
        }

        // 加载铃音配置（无配置则初始化）
        RingTongBean ringTongBean = RingTongBean.loadBean(this, RingTongBean.class);
        if (ringTongBean == null) {
            ringTongBean = new RingTongBean();
            RingTongBean.saveBean(this, ringTongBean);
            LogUtils.d(TAG, "checkAndRestoreRingerVolume: 铃音配置未存在，已初始化默认配置");
        }

        // 检查并恢复音量
        try {
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_RING);
            int configVolume = ringTongBean.getStreamVolume();
            if (currentVolume != configVolume) {
                audioManager.setStreamVolume(AudioManager.STREAM_RING, configVolume, 0);
                LogUtils.d(TAG, "checkAndRestoreRingerVolume: 铃声音量已恢复 | 配置值=" + configVolume + " | 当前值=" + currentVolume);
            }
        } catch (SecurityException e) {
            LogUtils.e(TAG, "checkAndRestoreRingerVolume: 音量设置权限不足", e);
        }
    }

    private void cancelVolumeCheckTimer() {
        if (mStreamVolumeCheckTimer != null) {
            mStreamVolumeCheckTimer.cancel();
            mStreamVolumeCheckTimer = null;
            LogUtils.d(TAG, "cancelVolumeCheckTimer: 铃声音量检查定时器已取消");
        }
    }

    // ====================== 辅助初始化方法区 ======================
    private void initTomCat() {
        sTomCatInstance = TomCat.getInstance(this);
        if (!sTomCatInstance.loadPhoneBoBullToon()) {
            LogUtils.w(TAG, "initTomCat: 未下载 BoBullToon 数据，参数加载失败");
        } else {
            LogUtils.d(TAG, "initTomCat: BoBullToon 数据加载成功");
        }
    }

    private void initMainReceiver() {
        if (mMainReceiver == null) {
            mMainReceiver = new MainReceiver(this);
            mMainReceiver.registerAction(this);
            LogUtils.d(TAG, "initMainReceiver: 广播接收器已注册");
        }
    }
}

