package cc.winboll.studio.positions.utils;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/11/05 15:49
 * @Describe LocalMotionDetector
 */
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import cc.winboll.studio.libappbase.LogUtils;

/**
 * 本机运动状态监测工具（无联网，纯传感器）
 */
public class LocalMotionDetector implements SensorEventListener {
    public static final String TAG = "LocalMotionDetector";

    // 配置参数（重点修改：调高运动阈值，适配坐立持机场景）
    private static final float MOTION_THRESHOLD = 1.8f; // 从0.5f调高到1.8f（过滤坐立轻微晃动）
    private static final long STATUS_CHECK_INTERVAL = 3000; // 3秒判断一次状态
    private static final int STEP_CHANGE_THRESHOLD = 2; // 3秒≥2步判定行走

    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private Sensor mStepCounter;
    private Handler mMainHandler;
    private MotionStatusCallback mCallback;

    private boolean mIsDetecting = false;
    private float mLastAccelMagnitude = 0f;
    private int mLastStepCount = 0;
    private int mCurrentStepCount = 0;
    private boolean mIsWalking = false;

    // 单例模式
    private static LocalMotionDetector sInstance;
    public static LocalMotionDetector getInstance() {
        if (sInstance == null) {
            synchronized (LocalMotionDetector.class) {
                if (sInstance == null) {
                    sInstance = new LocalMotionDetector();
                }
            }
        }
        return sInstance;
    }

    private LocalMotionDetector() {
        mMainHandler = new Handler(Looper.getMainLooper());
    }

    /**
     * 开始监测运动状态
     */
    public void startDetection(Context context, MotionStatusCallback callback) {
        if (mIsDetecting) return;
        mCallback = callback;
        mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);

        // 初始化传感器
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mStepCounter = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);

        // 注册传感器监听
        if (mAccelerometer != null) {
            mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL, mMainHandler);
        }
        if (mStepCounter != null) {
            mSensorManager.registerListener(this, mStepCounter, SensorManager.SENSOR_DELAY_NORMAL, mMainHandler);
            LogUtils.d(TAG, "计步传感器已启动");
        } else {
            LogUtils.d(TAG, "设备不支持计步传感器，仅用加速度判断");
        }

        // 启动定时状态检测
        mMainHandler.postDelayed(mStatusCheckRunnable, STATUS_CHECK_INTERVAL);
        mIsDetecting = true;
        LogUtils.d(TAG, "运动状态监测已启动");
    }

    /**
     * 停止监测
     */
    public void stopDetection() {
        if (!mIsDetecting) return;
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }
        mMainHandler.removeCallbacksAndMessages(null);
        mIsDetecting = false;
        mIsWalking = false;
        mCallback = null;
        LogUtils.d(TAG, "运动状态监测已停止");
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (!mIsDetecting) return;
        switch (event.sensor.getType()) {
            case Sensor.TYPE_ACCELEROMETER:
                // 计算加速度幅度（保留原逻辑，阈值已调高）
                float accelX = Math.abs(event.values[0]);
                float accelY = Math.abs(event.values[1]);
                float accelZ = Math.abs(event.values[2]);
                mLastAccelMagnitude = accelX + accelY + accelZ;
                break;
            case Sensor.TYPE_STEP_COUNTER:
                // 累计步数
                mCurrentStepCount = (int) event.values[0];
                break;
        }
    }

    /**
     * 定时判断运动状态（优化逻辑：计步为0时，即使有轻微加速度也判定为静止）
     */
    private final Runnable mStatusCheckRunnable = new Runnable() {
        @Override
        public void run() {
            if (!mIsDetecting || mCallback == null) return;

			//LogUtils.d(TAG, "mStatusCheckRunnable run");
			
            boolean newIsWalking = false;
            // 结合计步器+加速度判断（优化：优先计步，无步数时严格按高阈值判断）
            if (mStepCounter != null) {
                int stepChange = mCurrentStepCount - mLastStepCount;
                // 只有“步数达标” 或 “无步数但加速度远超坐立幅度”，才判定为行走
                newIsWalking = (stepChange >= STEP_CHANGE_THRESHOLD) 
					&& (mLastAccelMagnitude >= MOTION_THRESHOLD); // 增加步数+加速度双重校验
                mLastStepCount = mCurrentStepCount;
            } else {
                // 无计步器时，仅用高阈值判断
                newIsWalking = mLastAccelMagnitude >= MOTION_THRESHOLD;
            }

            // 状态变化时回调
            if (newIsWalking != mIsWalking) {
                mIsWalking = newIsWalking;
                String statusDesc = mIsWalking ? "行走状态" : "静止/低运动状态";
                LogUtils.d(TAG, "运动状态变化：" + statusDesc + " | 加速度幅度：" + mLastAccelMagnitude); // 增加日志便于调试
                mCallback.onMotionStatusChanged(mIsWalking, statusDesc);
            }
			
			LogUtils.d(TAG, String.format("运动状态 newIsWalking %s", newIsWalking));

            // 循环检测
            mMainHandler.postDelayed(this, STATUS_CHECK_INTERVAL);
        }
    };

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {}

    /**
     * 运动状态回调接口
     */
    public interface MotionStatusCallback {
        void onMotionStatusChanged(boolean isWalking, String statusDesc);
    }
}

