import 'dart:math';

import '../../flutter_map.dart';

class MapUtil {
  MapUtil._();

  static double calculateLineLatLngDistance(LatLng p1, LatLng p2) {
    if (p1.latitude == null ||
        p1.longitude == null ||
        p2.latitude == null ||
        p2.longitude == null) {
      throw ArgumentError("Invalid coordinates");
    }

    return calculateLineDistance(
        p1.longitude!, p1.latitude!, p2.longitude!, p2.latitude!);
  }

  static double calculateLineDistance(double longitudeP1, double latitudeP1,
      double longitudeP2, double latitudeP2) {
    try {
      // 转为弧度
      double lon1 = longitudeP1 * (pi / 180.0);
      double lat1 = latitudeP1 * (pi / 180.0);
      double lon2 = longitudeP2 * (pi / 180.0);
      double lat2 = latitudeP2 * (pi / 180.0);

      double sinLon1 = sin(lon1);
      double sinLat1 = sin(lat1);
      double cosLon1 = cos(lon1);
      double cosLat1 = cos(lat1);

      double sinLon2 = sin(lon2);
      double sinLat2 = sin(lat2);
      double cosLon2 = cos(lon2);
      double cosLat2 = cos(lat2);

      // 三维向量表示
      List<double> v1 = [
        cosLat1 * cosLon1,
        cosLat1 * sinLon1,
        sinLat1,
      ];

      List<double> v2 = [
        cosLat2 * cosLon2,
        cosLat2 * sinLon2,
        sinLat2,
      ];

      // 计算向量差的模长
      double dx = v1[0] - v2[0];
      double dy = v1[1] - v2[1];
      double dz = v1[2] - v2[2];

      double chordLength = sqrt(dx * dx + dy * dy + dz * dz);

      // 球面线距离（地球平均半径约 6371000m）
      return asin(chordLength / 2.0) * 12742001.5798544;
    } catch (e) {
      print("Error in calculateLineDistance: $e");
      return 0.0;
    }
  }

  static String format(double distanceInMeters) {
    if (distanceInMeters < 1000) {
      return '${distanceInMeters.round()}m';
    } else {
      double km = distanceInMeters / 1000;
      String kmStr = km.toStringAsFixed(1);
      if (kmStr.endsWith('.0')) {
        kmStr = kmStr.substring(0, kmStr.length - 2); // 去掉 .0
      }
      return '${kmStr}km';
    }
  }
}
