import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:injectable/injectable.dart';
import 'package:location/data/repositories/track_repository.dart';
import 'package:location/di/get_it.dart';
import 'package:location/handler/error_handler.dart';
import '../../data/bean/atmob_track_point.dart';
import '../../data/bean/track_daily_bean.dart';

@lazySingleton
class TodayTrackHelper {
  final RxMap<String, TodayTrackReportBean> todayTrackReportMap =
      <String, TodayTrackReportBean>{}.obs;

  final TrackRepository trackRepository;

  TodayTrackHelper(this.trackRepository);

  static TodayTrackHelper getInstance() {
    return getIt.get<TodayTrackHelper>();
  }

  void clear() {
    todayTrackReportMap.clear();
  }

  void requestTodayTrackReport(String userId) {
    todayTrackReportMap.putIfAbsent(userId, () => TodayTrackReportBean(userId));
    //确保一定有实例
    final reportBean = todayTrackReportMap[userId]!;

    if (reportBean.isRequesting) {
      // 正在请求中，跳过
      return;
    }
    if (reportBean.isRequestSuccess.value && !reportBean.isExpired) return;

    //重置数据
    reportBean.polylines = null;
    reportBean.markers = null;
    reportBean.trackPoints = null;
    reportBean.startPoint = null;
    reportBean.exceptionPoint = null;
    reportBean.isRequestSuccess.value = false;

    _requestTodayTrackReport(userId, reportBean);
  }

  void _requestTodayTrackReport(String userId, TodayTrackReportBean bean) {
    bean.isRequesting = true;
    trackRepository.trackDailyAction(userId).then((response) {
      bean.startPoint = response.startPoint;
      bean.exceptionPoint = response.exceptionPoint;
      bean.trackPoints = response.trackPoints;

      List<Marker> list = [];
      final startPoint = response.startPoint;
      if (startPoint != null && startPoint.addr?.isNotEmpty == true) {
        list.add(Marker(
            id: 'start',
            markerName: '',
            longitude: startPoint.lng,
            latitude: startPoint.lat,
            markerType: MarkerType.tracePassingPoint));
      }
      final exceptionPoint = response.exceptionPoint;
      if (exceptionPoint != null && exceptionPoint.addr?.isNotEmpty == true) {
        list.add(Marker(
            id: 'end',
            markerName: '',
            longitude: exceptionPoint.lng,
            latitude: exceptionPoint.lat,
            markerType: MarkerType.tracePassingPoint));
      }
      bean.markers = list;

      final points = response.trackPoints?.map((point) {
        return LatLng(latitude: point.latitude, longitude: point.longitude);
      }).toList();

      bean.polylines = [
        Polyline(
            lineId: 'small_trace',
            color: '#4476FF',
            width: 6.5,
            lineType: PolylineType.color,
            points: points ?? [])
      ];

      bean.isRequestSuccess.value = true;
      bean.lastRequestTime = DateTime.now();
    }).catchError((error) {
      ErrorHandler.toastError(error);
    }).whenComplete(() {
      bean.isRequesting = false;
    });
  }
}

class TodayTrackReportBean {
  final String userId;

  bool isRequesting = false;

  final RxBool isRequestSuccess = RxBool(false);

  final RxnBool noMember = RxnBool();

  TrackDailyBean? startPoint;

  TrackDailyBean? exceptionPoint;

  List<AtmobTrackPoint>? trackPoints;

  List<Polyline>? polylines;

  List<Marker>? markers;

  // 记录上一次请求成功的时间
  DateTime? lastRequestTime;

  TodayTrackReportBean(this.userId);

  MapPadding mapPadding =
      MapPadding(left: 10.w, right: 10.w, top: 10.w, bottom: 10.w);

  bool get isExpired {
    if (lastRequestTime == null) return true;
    return DateTime.now().difference(lastRequestTime!) >
        const Duration(minutes: 5);
  }
}
