import 'dart:async';
import 'package:autosos_flutter/api/user_api.dart';
import 'package:autosos_flutter/config/constant.dart';
import 'package:autosos_flutter/service/location_service.dart';
import 'package:flutter/foundation.dart';

/// 心跳服务（保持在线状态，上报位置）
class HeartbeatService {
  static final HeartbeatService instance = HeartbeatService._();
  HeartbeatService._();

  Timer? _timer;
  final Duration _interval = const Duration(seconds: 30);
  int _onlineSeconds = 0;
  bool _running = false;

  bool get running => _running;
  int get onlineSeconds => _onlineSeconds;

  /// 启动心跳
  void start() {
    if (_running) return;
    _running = true;
    _onlineSeconds = 0;
    _timer = Timer.periodic(_interval, (_) => _tick());
    debugPrint('Heartbeat started');
  }

  /// 停止心跳
  void stop() {
    _timer?.cancel();
    _timer = null;
    _running = false;
    _onlineSeconds = 0;
    debugPrint('Heartbeat stopped');
  }

  Future<void> _tick() async {
    _onlineSeconds += _interval.inSeconds;
    try {
      final loc = LocationService.instance.last;
      await UserApi.instance.heartbeat(
        lat: (loc?['latitude'] as num?)?.toDouble(),
        lng: (loc?['longitude'] as num?)?.toDouble(),
        onlineTime: _onlineSeconds,
      );
      Constant.heartbeatTime = DateTime.now().millisecondsSinceEpoch;
    } catch (e) {
      debugPrint('Heartbeat tick failed: $e');
      Constant.weberror = true;
    }
  }

  /// 重置在线时长（接单/完成后调用）
  void resetOnlineTime() {
    _onlineSeconds = 0;
  }

  void dispose() {
    stop();
  }
}