package cc.winboll.studio.positions.services;

/**
 * @Author ZhanGSKen<zhangsken@qq.com>
 * @Date 2024/07/19 14:30:57
 * @Describe 应用主要服务组件类（适配运动状态GPS控制+静止10秒切换）
 */
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.text.TextUtils;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.ToastUtils;
import cc.winboll.studio.positions.models.PositionModel;
import cc.winboll.studio.positions.models.PositionTaskModel;
import cc.winboll.studio.positions.utils.AppConfigsUtil;
import cc.winboll.studio.positions.utils.DistanceCalculatorUtil;
import cc.winboll.studio.positions.utils.NotificationUtil;
import cc.winboll.studio.positions.utils.ServiceUtil;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import cc.winboll.studio.positions.utils.LocalMotionDetector;

public class MainService extends Service implements LocalMotionDetector.MotionStatusCallback {

    public static final String TAG = "MainService";
    public static final String EXTRA_IS_SETTING_TO_ENABLE = "EXTRA_IS_SETTING_TO_ENABLE";

    // ---------------------- 核心：LocalMotionDetector 实例（唯一运动状态检测工具） ----------------------
    private LocalMotionDetector mMotionDetector; // 本地运动状态检测器
    private static final long GPS_STATIC_INTERVAL = 30; // 静止时GPS间隔（30秒）

    // ---------------------- 定时器相关变量 ----------------------
    private ScheduledExecutorService gpsStaticTimer; // 静止时GPS定时任务
    private volatile boolean isGpsListening = false;  // GPS是否持续监听
    private static final long GPS_STATIC_DURATION = 3; // 单次GPS获取超时（秒）

    // ---------------------- 静止延迟切换配置（核心功能） ----------------------
    private static final long STATIC_DELAY_MS = 10 * 1000; // 静止10秒后切换
    private Handler staticDelayHandler; // 延迟执行切换逻辑的Handler
    private volatile boolean isDelaySwitching = false; // 标记是否正在等待延迟切换

    // GPS监听接口
    public interface GpsUpdateListener {
        void onGpsPositionUpdated(PositionModel currentGpsPos);
        void onGpsStatusChanged(String status);
    }

    // 任务更新监听接口
    public interface TaskUpdateListener {
        void onTaskUpdated();
    }

    // 监听管理
    private final Set<WeakReference<GpsUpdateListener>> mGpsListeners = new HashSet<WeakReference<GpsUpdateListener>>();
    private final Set<WeakReference<TaskUpdateListener>> mTaskListeners = new HashSet<WeakReference<TaskUpdateListener>>();
    private final Object mListenerLock = new Object();

    // 原有核心变量
    private LocalBinder mLocalBinder;
    private LocationManager mLocationManager;
    private LocationListener mGpsLocationListener;
    private static final long GPS_UPDATE_INTERVAL = 2000; // 实时GPS更新间隔：2秒
    private static final float GPS_UPDATE_DISTANCE = 1;   // 实时GPS更新距离：1米
    private boolean isGpsEnabled = false;
    private boolean isGpsPermissionGranted = false;

    // 数据存储集合
    private final ArrayList<PositionModel> mPositionList = new ArrayList<PositionModel>();
    private final ArrayList<PositionTaskModel> mAllTasks = new ArrayList<PositionTaskModel>();
    private static PositionModel _mCurrentGpsPosition;

    // 服务相关变量
    MyServiceConnection mMyServiceConnection;
    volatile static boolean _mIsServiceRunning;
    AppConfigsUtil mAppConfigsUtil;
    private ScheduledExecutorService distanceExecutor = Executors.newSingleThreadScheduledExecutor();
    private final Set<String> mVisiblePositionIds = new HashSet<String>();

    // 单例+应用上下文
    private static volatile MainService sInstance;
    private static Context sAppContext;


    // =========================================================================
    // 核心：运动状态回调（仅通过LocalMotionDetector触发，低运动归类为静止）
    // =========================================================================
    @Override
    public void onMotionStatusChanged(boolean isWalking, String statusDesc) {
        LogUtils.d(TAG, "运动状态回调：" + statusDesc + "（isWalking=" + isWalking + "）");
        updateNotificationGpsStatus("当前状态：" + statusDesc);

        // 仅行走状态切实时GPS，非行走（静止+低运动）统一按静止处理
        if (isWalking) {
            // 行走状态：立即切回实时GPS（取消未执行的延迟任务）
            if (staticDelayHandler != null) {
                staticDelayHandler.removeCallbacksAndMessages(null); // 清空延迟任务
                isDelaySwitching = false; // 重置标记
            }
            stopGpsStaticTimer(); // 停止定时GPS
            startGpsLocation();   // 启动实时GPS
            LogUtils.d(TAG, "行走状态：已切换为实时GPS（2秒/1米）");

        } else {
            // 非行走状态：延迟10秒切换为定时GPS
            if (isGpsListening && !isDelaySwitching) { // 仅实时GPS运行且无延迟任务时触发
                isDelaySwitching = true;
                staticDelayHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							stopGpsLocation(); // 停止实时GPS
							startGpsStaticTimer(GPS_STATIC_INTERVAL); // 启动30秒定时GPS
							LogUtils.d(TAG, "静止/低运动10秒：已切换为30秒定时GPS");
							isDelaySwitching = false; // 重置标记
						}
					}, STATIC_DELAY_MS);
                LogUtils.d(TAG, "检测到静止/低运动：将在10秒后切换为定时GPS（若持续非行走）");
            }
            LogUtils.d(TAG, "静止/低运动状态：等待延迟切换GPS");
        }
    }


    // =========================================================================
    // 静止GPS定时任务方法（适配Java7）
    // =========================================================================
    // 启动静止时GPS定时获取（间隔：秒）
    public void startGpsStaticTimer(long intervalSeconds) {
        stopGpsStaticTimer();

        gpsStaticTimer = Executors.newSingleThreadScheduledExecutor();
        gpsStaticTimer.scheduleAtFixedRate(new Runnable() {
				@Override
				public void run() {
					LogUtils.d(TAG, "静止时GPS定时任务触发：开始单次GPS获取");
					startSingleGpsRetrieve();
				}
			}, 0, intervalSeconds, TimeUnit.SECONDS);

        LogUtils.d(TAG, "静止时GPS定时任务已启动（间隔：" + intervalSeconds + "秒）");
    }

    // 停止静止时GPS定时任务
    public void stopGpsStaticTimer() {
        if (gpsStaticTimer != null && !gpsStaticTimer.isShutdown()) {
            gpsStaticTimer.shutdown();
            try {
                if (!gpsStaticTimer.awaitTermination(1, TimeUnit.SECONDS)) {
                    gpsStaticTimer.shutdownNow();
                }
            } catch (InterruptedException e) {
                gpsStaticTimer.shutdownNow();
                Thread.currentThread().interrupt();
            } finally {
                gpsStaticTimer = null;
                LogUtils.d(TAG, "静止时GPS定时任务已销毁");
            }
        }
    }

    // 单次GPS获取（获取后关闭监听）
    private void startSingleGpsRetrieve() {
        if (!checkGpsReady()) {
            LogUtils.w(TAG, "单次GPS获取：GPS未就绪，跳过");
            return;
        }

        try {
            mLocationManager.requestSingleUpdate(
                LocationManager.GPS_PROVIDER,
                new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        if (location != null) {
                            PositionModel gpsPos = new PositionModel();
                            gpsPos.setLatitude(location.getLatitude());
                            gpsPos.setLongitude(location.getLongitude());
                            gpsPos.setPositionId("CURRENT_GPS_POS");
                            gpsPos.setMemo("静止时单次GPS位置");
                            syncCurrentGpsPosition(gpsPos);
                            LogUtils.d(TAG, "单次GPS获取成功：纬度=" + location.getLatitude());
                        }
                        mLocationManager.removeUpdates(this);
                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) {}

                    @Override
                    public void onProviderEnabled(String provider) {}

                    @Override
                    public void onProviderDisabled(String provider) {
                        mLocationManager.removeUpdates(this);
                    }
                },
                Looper.getMainLooper()
            );

            // 超时处理
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
					@Override
					public void run() {
						mLocationManager.removeUpdates(new LocationListener() {
								@Override public void onLocationChanged(Location location) {}
								@Override public void onStatusChanged(String provider, int status, Bundle extras) {}
								@Override public void onProviderEnabled(String provider) {}
								@Override public void onProviderDisabled(String provider) {}
							});
						LogUtils.d(TAG, "单次GPS获取超时（" + GPS_STATIC_DURATION + "秒）");
					}
				}, GPS_STATIC_DURATION * 1000);

        } catch (SecurityException e) {
            LogUtils.e(TAG, "单次GPS获取失败（权限异常）：" + e.getMessage());
        } catch (Exception e) {
            LogUtils.e(TAG, "单次GPS获取失败：" + e.getMessage());
        }
    }


    // =========================================================================
    // 任务操作核心接口
    // =========================================================================
    public void addTask(PositionTaskModel newTask) {
        if (newTask == null || TextUtils.isEmpty(newTask.getPositionId())) {
            LogUtils.w(TAG, "addPositionTask：任务为空或未绑定位置ID，新增失败");
            return;
        }

        boolean isDuplicate = false;
        Iterator<PositionTaskModel> taskIter = mAllTasks.iterator();
        while (taskIter.hasNext()) {
            PositionTaskModel task = taskIter.next();
            if (newTask.getTaskId().equals(task.getTaskId())) {
                isDuplicate = true;
                break;
            }
        }
        if (isDuplicate) {
            LogUtils.w(TAG, "addPositionTask：任务ID已存在（" + newTask.getTaskId() + "），新增失败");
            return;
        }

        mAllTasks.add(newTask);
        saveAllTasks();
        notifyTaskUpdated();
        LogUtils.d(TAG, "addPositionTask：成功（位置ID=" + newTask.getPositionId() + "，任务ID=" + newTask.getTaskId() + "）");
    }

    public ArrayList<PositionTaskModel> getTasksByPositionId(String positionId) {
        ArrayList<PositionTaskModel> posTasks = new ArrayList<PositionTaskModel>();
        if (TextUtils.isEmpty(positionId) || mAllTasks.isEmpty()) {
            return posTasks;
        }

        Iterator<PositionTaskModel> taskIter = mAllTasks.iterator();
        while (taskIter.hasNext()) {
            PositionTaskModel task = taskIter.next();
            if (positionId.equals(task.getPositionId())) {
                posTasks.add(task);
            }
        }
        return posTasks;
    }

    public ArrayList<PositionTaskModel> getAllTasks() {
        return mAllTasks;
    }

    public void updateTask(PositionTaskModel updatedTask) {
        if (updatedTask == null || updatedTask.getTaskId() == null) return;
        for (int i = 0; i < mAllTasks.size(); i++) {
            PositionTaskModel task = mAllTasks.get(i);
            if (updatedTask.getTaskId().equals(task.getTaskId())) {
                mAllTasks.set(i, updatedTask);
                break;
            }
        }
        saveAllTasks();
    }

    public void updateTaskStatus(PositionTaskModel task) {
        if (task == null || task.getTaskId() == null) return;
        for (PositionTaskModel item : mAllTasks) {
            if (task.getTaskId().equals(item.getTaskId())) {
                item.setIsEnable(task.isEnable());
                break;
            }
        }
        saveAllTasks();
    }

    public void deleteTask(String taskId) {
        if (TextUtils.isEmpty(taskId) || mAllTasks.isEmpty()) {
            LogUtils.w(TAG, "deletePositionTask：任务ID为空或列表为空，删除失败");
            return;
        }

        Iterator<PositionTaskModel> taskIter = mAllTasks.iterator();
        while (taskIter.hasNext()) {
            PositionTaskModel task = taskIter.next();
            if (taskId.equals(task.getTaskId())) {
                taskIter.remove();
                saveAllTasks();
                notifyTaskUpdated();
                LogUtils.d(TAG, "deletePositionTask：成功（任务ID=" + taskId + "）");
                break;
            }
        }
    }

    public void registerTaskUpdateListener(TaskUpdateListener listener) {
        if (listener == null) {
            LogUtils.w(TAG, "registerTaskUpdateListener：监听者为空，跳过");
            return;
        }
        synchronized (mListenerLock) {
            mTaskListeners.add(new WeakReference<TaskUpdateListener>(listener));
        }
    }

    public void unregisterTaskUpdateListener(TaskUpdateListener listener) {
        if (listener == null) {
            LogUtils.w(TAG, "unregisterTaskUpdateListener：监听者为空，跳过");
            return;
        }
        synchronized (mListenerLock) {
            Iterator<WeakReference<TaskUpdateListener>> iter = mTaskListeners.iterator();
            while (iter.hasNext()) {
                WeakReference<TaskUpdateListener> ref = iter.next();
                if (ref.get() == listener || ref.get() == null) {
                    iter.remove();
                }
            }
        }
    }

    private void notifyTaskUpdated() {
        synchronized (mListenerLock) {
            Iterator<WeakReference<TaskUpdateListener>> iter = mTaskListeners.iterator();
            while (iter.hasNext()) {
                final WeakReference<TaskUpdateListener> ref = iter.next();
                if (ref.get() != null) {
                    if (Looper.myLooper() == Looper.getMainLooper()) {
                        ref.get().onTaskUpdated();
                    } else {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
								@Override
								public void run() {
									ref.get().onTaskUpdated();
								}
							});
                    }
                } else {
                    iter.remove();
                }
            }
        }
    }


    // =========================================================================
    // 服务基础方法（初始化LocalMotionDetector，删除Receiver相关逻辑）
    // =========================================================================
    public static synchronized MainService getInstance(Context context) {
        if (sInstance == null) {
            if (AppConfigsUtil.getInstance(context).isEnableMainService(true)) {
                Intent intent = new Intent(context.getApplicationContext(), MainService.class);
                context.getApplicationContext().startService(intent);
            }
            return null;
        }
        if (sAppContext == null) {
            sAppContext = sInstance.getApplicationContext();
        }
        return sInstance;
    }

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

    @Override
    public void onCreate() {
        LogUtils.d(TAG, "onCreate");
        super.onCreate();
        sInstance = this;
        sAppContext = getApplicationContext();

        mLocalBinder = new LocalBinder(this);
        _mIsServiceRunning = false;
        mAppConfigsUtil = AppConfigsUtil.getInstance(this);

        if (mMyServiceConnection == null) {
            mMyServiceConnection = new MyServiceConnection();
        }

        // 初始化：LocalMotionDetector+延迟切换Handler（Java7兼容）
        mMotionDetector = LocalMotionDetector.getInstance();
        staticDelayHandler = new Handler(Looper.getMainLooper());

        if (mAppConfigsUtil.isEnableMainService(true)) {
            run();
        }
    }

    // 服务核心运行方法（删除Receiver注册逻辑）
    public void run() {
        if (mAppConfigsUtil.isEnableMainService(true)) {
            if (!_mIsServiceRunning) {
                _mIsServiceRunning = true;
                wakeupAndBindAssistant();

                // 启动前台服务
                String initialStatus = "[ Positions ] is in Service.";
				NotificationUtil.createForegroundServiceNotification(this, initialStatus);
                startForeground(NotificationUtil.FOREGROUND_SERVICE_NOTIFICATION_ID,
								NotificationUtil.createForegroundServiceNotification(this, initialStatus));

                // 初始化LocationManager
                mLocationManager = (LocationManager) sInstance.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

                // 加载本地数据
                PositionModel.loadBeanList(MainService.this, mPositionList, PositionModel.class);
                PositionTaskModel.loadBeanList(MainService.this, mAllTasks, PositionTaskModel.class);

                // 核心：启动LocalMotionDetector监测（唯一运动状态来源）
                mMotionDetector.startDetection(this, this);

                // 提示与日志
                ToastUtils.show(initialStatus);
                LogUtils.i(TAG, initialStatus);
            }
        }
    }

    public boolean isServiceRunning() {
        return _mIsServiceRunning;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sInstance = null;

        // 核心：停止LocalMotionDetector（避免传感器内存泄漏）
        if (mMotionDetector != null) {
            mMotionDetector.stopDetection();
            LogUtils.d(TAG, "LocalMotionDetector 已停止检测");
        }

        // 清理延迟Handler任务（避免内存泄漏）
        if (staticDelayHandler != null) {
            staticDelayHandler.removeCallbacksAndMessages(null);
            staticDelayHandler = null;
        }

        // 原有清理逻辑（已删除Receiver注销代码）
        stopGpsLocation();
        stopGpsStaticTimer();
        clearAllData();
        stopForeground(true);

        synchronized (mListenerLock) {
            mGpsListeners.clear();
            mTaskListeners.clear();
        }

        if (distanceExecutor != null && !distanceExecutor.isShutdown()) {
            distanceExecutor.shutdown();
        }

        _mIsServiceRunning = false;
        isGpsEnabled = false;
        isGpsListening = false;
        isDelaySwitching = false;
        mLocationManager = null;
        LogUtils.d(TAG, "MainService 销毁完成，所有资源已清理");
    }


    // =========================================================================
    // 位置操作方法
    // =========================================================================
    public ArrayList<PositionModel> getPositionList() {
        return mPositionList;
    }

    public PositionModel getCurrentGpsPosition() {
        return _mCurrentGpsPosition;
    }

    public boolean isGpsListening() {
        return isGpsListening;
    }

    public void removePosition(String targetPosId) {
        if (TextUtils.isEmpty(targetPosId) || mPositionList.isEmpty()) {
            LogUtils.w(TAG, "removePosition：参数无效");
            return;
        }
        Iterator<PositionModel> iter = mPositionList.iterator();
        while (iter.hasNext()) {
            PositionModel pos = iter.next();
            if (targetPosId.equals(pos.getPositionId())) {
                iter.remove();
                savePositionList();
                break;
            }
        }
    }

    public void updatePosition(PositionModel updatedPos) {
        if (updatedPos == null || TextUtils.isEmpty(updatedPos.getPositionId()) || mPositionList.isEmpty()) {
            LogUtils.w(TAG, "updatePosition：参数无效");
            return;
        }
        for (int i = 0; i < mPositionList.size(); i++) {
            PositionModel oldPos = mPositionList.get(i);
            if (updatedPos.getPositionId().equals(oldPos.getPositionId())) {
                mPositionList.set(i, updatedPos);
                savePositionList();
                break;
            }
        }
    }

    public void syncAllPositionTasks(ArrayList<PositionTaskModel> newTaskList) {
        if (newTaskList == null) {
            LogUtils.w(TAG, "syncAllPositionTasks：新列表为空");
            return;
        }
        mAllTasks.clear();
        mAllTasks.addAll(newTaskList);
        saveAllTasks();
        notifyTaskUpdated();
    }

    public void addPosition(PositionModel newPos) {
        if (newPos == null) {
            LogUtils.w(TAG, "addPosition：位置为空");
            return;
        }
        boolean isDuplicate = false;
        for (PositionModel pos : mPositionList) {
            if (newPos.getPositionId().equals(pos.getPositionId())) {
                isDuplicate = true;
                break;
            }
        }
        if (!isDuplicate) {
            mPositionList.add(newPos);
            savePositionList();
        }
    }

    void savePositionList() {
        LogUtils.d(TAG, String.format("savePositionList : size=%d", mPositionList.size()));
        PositionModel.saveBeanList(MainService.this, mPositionList, PositionModel.class);
    }

    public void saveAllTasks() {
        LogUtils.d(TAG, String.format("saveTaskList : size=%d", mAllTasks.size()));
        PositionTaskModel.saveBeanList(MainService.this, mAllTasks, PositionTaskModel.class);
    }

    public void clearAllData() {
        mPositionList.clear();
        mAllTasks.clear();
        _mCurrentGpsPosition = null;
        LogUtils.d(TAG, "clearAllData：已清空所有数据");
    }

    public void syncCurrentGpsPosition(PositionModel position) {
        if (position == null) {
            LogUtils.w(TAG, "syncCurrentGpsPosition：位置为空");
            return;
        }
        this._mCurrentGpsPosition = position;
        LogUtils.d(TAG, "syncCurrentGpsPosition：成功（纬度=" + position.getLatitude() + "，经度=" + position.getLongitude() + "）");
        notifyAllGpsListeners(position);

        if (_mIsServiceRunning) {
            syncGpsStatusToNotification();
        }
    }

    private void syncGpsStatusToNotification() {
        if (!_mIsServiceRunning || _mCurrentGpsPosition == null) {
            return;
        }
        final String gpsStatus = String.format(
            "GPS位置：北纬%.4f° 东经%.4f° | 可见位置：%d个",
            _mCurrentGpsPosition.getLatitude(),
            _mCurrentGpsPosition.getLongitude(),
            mVisiblePositionIds.size()
        );
        if (Looper.myLooper() == Looper.getMainLooper()) {
            NotificationUtil.updateForegroundServiceStatus(this, gpsStatus);
        } else {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
					@Override
					public void run() {
						NotificationUtil.updateForegroundServiceStatus(MainService.this, gpsStatus);
					}
				});
        }
    }


    // =========================================================================
    // 服务生命周期+辅助服务相关
    // =========================================================================
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        boolean isSettingToEnable = false;
        if (intent != null) {
            isSettingToEnable = intent.getBooleanExtra(EXTRA_IS_SETTING_TO_ENABLE, false);
            if (isSettingToEnable) {
                run();
            }
        }
        return isSettingToEnable ? Service.START_STICKY : super.onStartCommand(intent, flags, startId);
    }

    private class MyServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {}

        @Override
        public void onServiceDisconnected(ComponentName name) {
            if (mAppConfigsUtil.isEnableMainService(true)) {
                wakeupAndBindAssistant();
            }
        }
    }

    void wakeupAndBindAssistant() {
        if (!ServiceUtil.isServiceAlive(getApplicationContext(), AssistantService.class.getName())) {
            startService(new Intent(MainService.this, AssistantService.class));
            bindService(new Intent(MainService.this, AssistantService.class), mMyServiceConnection, Context.BIND_IMPORTANT);
        }
    }


    // =========================================================================
    // GPS相关核心方法
    // =========================================================================
    public MainService() {
        distanceExecutor = Executors.newSingleThreadScheduledExecutor();
        initGpsLocationListener();
    }

    private void initGpsLocationListener() {
        LogUtils.d(TAG, "initGpsLocationListener");
        mGpsLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                if (location != null) {
                    PositionModel gpsPos = new PositionModel();
                    gpsPos.setLatitude(location.getLatitude());
                    gpsPos.setLongitude(location.getLongitude());
                    gpsPos.setPositionId("CURRENT_GPS_POS");
                    gpsPos.setMemo("实时GPS位置");

                    syncCurrentGpsPosition(gpsPos);
                    DistanceCalculatorUtil.getInstance(MainService.this).checkAllTaskTriggerCondition(gpsPos);
                    LogUtils.d(TAG, "GPS位置更新：纬度=" + location.getLatitude() + "，经度=" + location.getLongitude());
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                if (provider.equals(LocationManager.GPS_PROVIDER)) {
                    String statusDesc = "";
                    switch (status) {
                        case LocationProvider.AVAILABLE:
                            statusDesc = "GPS状态：已就绪（可用）";
                            break;
                        case LocationProvider.OUT_OF_SERVICE:
                            statusDesc = "GPS状态：无服务（信号弱）";
                            break;
                        case LocationProvider.TEMPORARILY_UNAVAILABLE:
                            statusDesc = "GPS状态：临时不可用（遮挡）";
                            break;
                    }
                    LogUtils.d(TAG, statusDesc);
                    notifyAllGpsStatusListeners(statusDesc);
                    updateNotificationGpsStatus(statusDesc);
                }
            }

            @Override
            public void onProviderEnabled(String provider) {
                if (provider.equals(LocationManager.GPS_PROVIDER)) {
                    isGpsEnabled = true;
                    String statusDesc = "GPS已开启（用户手动打开）";
                    LogUtils.d(TAG, statusDesc);
                    notifyAllGpsStatusListeners(statusDesc);
                    updateNotificationGpsStatus("GPS已开启，等待运动状态触发...");
                }
            }

            @Override
            public void onProviderDisabled(String provider) {
                if (provider.equals(LocationManager.GPS_PROVIDER)) {
                    isGpsEnabled = false;
                    isGpsListening = false;
                    _mCurrentGpsPosition = null;
                    String statusDesc = "GPS已关闭（用户手动关闭）";
                    LogUtils.w(TAG, statusDesc);
                    notifyAllGpsStatusListeners(statusDesc);
                    updateNotificationGpsStatus("GPS已关闭，请在设置中开启");
                    ToastUtils.show("GPS已关闭，无法获取位置，请在设置中开启");
                }
            }
        };
    }

    private boolean checkGpsReady() {
        isGpsPermissionGranted = checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED;

        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        }
        isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (!isGpsPermissionGranted) {
            String tip = "GPS准备失败：缺少精确定位权限";
            LogUtils.e(TAG, tip);
            notifyAllGpsStatusListeners(tip);
            updateNotificationGpsStatus("缺少定位权限，无法获取GPS");
            ToastUtils.show("请授予定位权限，否则无法获取GPS位置");
            return false;
        }
        if (!isGpsEnabled) {
            String tip = "GPS准备失败：系统GPS未开启";
            LogUtils.e(TAG, tip);
            notifyAllGpsStatusListeners(tip);
            updateNotificationGpsStatus("GPS未开启，请在设置中打开");
            ToastUtils.show("GPS已关闭，请在设置中开启以获取位置");
            return false;
        }

        LogUtils.d(TAG, "GPS准备就绪：权限已获取，GPS已开启");
        return true;
    }

    // 启动GPS持续监听（运动状态回调调用）
    public void startGpsLocation() {
        if (!checkGpsReady() || isGpsListening) {
            return;
        }

        try {
            mLocationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                GPS_UPDATE_INTERVAL,
                GPS_UPDATE_DISTANCE,
                mGpsLocationListener,
                Looper.getMainLooper()
            );

            isGpsListening = true;

            // 获取最后已知位置
            Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (lastKnownLocation != null) {
                PositionModel lastGpsPos = new PositionModel();
                lastGpsPos.setLatitude(lastKnownLocation.getLatitude());
                lastGpsPos.setLongitude(lastKnownLocation.getLongitude());
                lastGpsPos.setPositionId("CURRENT_GPS_POS");
                syncCurrentGpsPosition(lastGpsPos);
                LogUtils.d(TAG, "已获取缓存GPS位置：纬度=" + lastKnownLocation.getLatitude());
            } else {
                String tip = "无缓存GPS位置，等待实时定位...";
                LogUtils.d(TAG, tip);
                notifyAllGpsStatusListeners(tip);
                updateNotificationGpsStatus("GPS搜索中（请移至开阔地带）");
            }

        } catch (SecurityException e) {
            String error = "启动GPS失败（权限异常）：" + e.getMessage();
            LogUtils.e(TAG, error);
            notifyAllGpsStatusListeners(error);
            isGpsPermissionGranted = false;
            isGpsListening = false;
            updateNotificationGpsStatus("定位权限异常，无法获取GPS");
        } catch (Exception e) {
            String error = "启动GPS失败：" + e.getMessage();
            LogUtils.e(TAG, error);
            notifyAllGpsStatusListeners(error);
            isGpsListening = false;
            updateNotificationGpsStatus("GPS启动失败，尝试重试...");
        }
    }

    // 停止GPS持续监听（运动状态回调调用）
    public void stopGpsLocation() {
        if (mLocationManager != null && mGpsLocationListener != null && isGpsPermissionGranted) {
            try {
                mLocationManager.removeUpdates(mGpsLocationListener);
                String tip = "GPS定位已停止（移除监听器）";
                LogUtils.d(TAG, tip);
                notifyAllGpsStatusListeners(tip);
                isGpsListening = false;
            } catch (Exception e) {
                String error = "停止GPS失败：" + e.getMessage();
                LogUtils.e(TAG, error);
                notifyAllGpsStatusListeners(error);
                isGpsListening = false;
            }
        }
    }

    // 发送任务触发通知
    public void sendTaskTriggerNotification(final PositionTaskModel task, PositionModel bindPos, double currentDistance) {
        if (!_mIsServiceRunning) {
            return;
        }

        final String triggerContent = String.format(
            "任务触发：%s\n位置：%s\n当前距离：%.1f米（条件：%s%d米）",
            task.getTaskDescription(),
            bindPos.getMemo(),
            currentDistance,
            task.isGreaterThan() ? ">" : "<",
            task.getDiscussDistance()
        );

        updateNotificationGpsStatus(triggerContent);

        if (Looper.myLooper() == Looper.getMainLooper()) {
            ToastUtils.show(triggerContent);
            NotificationUtil.show(MainService.this, task.getTaskId(), task.getPositionId(), task.getTaskDescription());
        } else {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
					@Override
					public void run() {
						ToastUtils.show(triggerContent);
						NotificationUtil.show(MainService.this, task.getTaskId(), task.getPositionId(), task.getTaskDescription());
					}
				});
        }
        LogUtils.i(TAG, "任务触发通知：" + triggerContent);
    }

    // 更新前台通知的GPS状态
    void updateNotificationGpsStatus(final String statusText) {
        if (_mIsServiceRunning) {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                NotificationUtil.updateForegroundServiceStatus(this, statusText);
            } else {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
						@Override
						public void run() {
							NotificationUtil.updateForegroundServiceStatus(MainService.this, statusText);
						}
					});
            }
        }
    }


    // =========================================================================
    // GPS监听通知相关方法
    // =========================================================================
    public void notifyAllGpsListeners(PositionModel currentGpsPos) {
        if (currentGpsPos == null || mGpsListeners.isEmpty()) {
            return;
        }
        synchronized (mListenerLock) {
            Iterator<WeakReference<GpsUpdateListener>> iter = mGpsListeners.iterator();
            while (iter.hasNext()) {
                WeakReference<GpsUpdateListener> ref = iter.next();
                GpsUpdateListener listener = ref.get();
                if (listener != null) {
                    notifySingleListener(listener, currentGpsPos);
				} else {
					iter.remove();
				}
			}
		}
	}

	private void notifySingleListener(final GpsUpdateListener listener, final PositionModel currentGpsPos) {
		if (Looper.myLooper() == Looper.getMainLooper()) {
			listener.onGpsPositionUpdated(currentGpsPos);
		} else {
			new Handler(Looper.getMainLooper()).post(new Runnable() {
					@Override
					public void run() {
						listener.onGpsPositionUpdated(currentGpsPos);
					}
				});
		}
	}

	private void notifyAllGpsStatusListeners(final String status) {
		if (status == null || mGpsListeners.isEmpty()) {
			return;
		}
		synchronized (mListenerLock) {
			Iterator<WeakReference<GpsUpdateListener>> iter = mGpsListeners.iterator();
			while (iter.hasNext()) {
				WeakReference<GpsUpdateListener> ref = iter.next();
				final GpsUpdateListener listener = ref.get();
				if (listener != null) {
					if (Looper.myLooper() == Looper.getMainLooper()) {
						listener.onGpsStatusChanged(status);
					} else {
						new Handler(Looper.getMainLooper()).post(new Runnable() {
								@Override
								public void run() {
									listener.onGpsStatusChanged(status);
								}
							});
					}
				} else {
					iter.remove();
				}
			}
		}
	}

	public void registerGpsUpdateListener(GpsUpdateListener listener) {
		if (listener == null) {
			LogUtils.w(TAG, "registerGpsUpdateListener：监听者为空");
			return;
		}
		synchronized (mListenerLock) {
			mGpsListeners.add(new WeakReference<GpsUpdateListener>(listener));
			LogUtils.d(TAG, "GPS监听注册成功，当前数量：" + mGpsListeners.size());
			if (_mCurrentGpsPosition != null) {
				notifySingleListener(listener, _mCurrentGpsPosition);
			}
		}
	}

	public void unregisterGpsUpdateListener(GpsUpdateListener listener) {
		if (listener == null) {
			LogUtils.w(TAG, "unregisterGpsUpdateListener：监听者为空");
			return;
		}
		synchronized (mListenerLock) {
			Iterator<WeakReference<GpsUpdateListener>> iter = mGpsListeners.iterator();
			while (iter.hasNext()) {
				WeakReference<GpsUpdateListener> ref = iter.next();
				if (ref.get() == listener || ref.get() == null) {
					iter.remove();
					LogUtils.d(TAG, "GPS监听反注册成功，当前数量：" + mGpsListeners.size());
					break;
				}
			}
		}
	}


// =========================================================================
// LocalBinder 定义（无修改）
// =========================================================================
	public class LocalBinder extends android.os.Binder {
		private MainService mService;

		public LocalBinder(MainService service) {
			this.mService = service;
		}

		public MainService getService() {
			return mService;
		}
	}
}



