package com.sqx.modules.orders.utils;

import java.math.BigDecimal;

public class LocationUtils {

    // 计算两点连线与正东方向的夹角（0 - 360度）
    public static double calculateAngle(double[] start, double[] end) {
        double dx = end[1] - start[1];
        double dy = end[0] - start[0];
        double angle = Math.toDegrees(Math.atan2(dy, dx));
        if (angle < 0) {
            angle += 360;
        }
        return angle;
    }

    // 计算两个角度的相似度（0 - 1）
    public static double calculateSimilarity(double angle1, double angle2) {
        double diff = Math.abs(angle1 - angle2);
        if (diff > 180) {
            diff = 360 - diff;
        }
        return 1 - (diff / 180);
    }

    // 计算两组经纬度顺路百分比
    /*public static double calculateRouteSimilarity(double[] start1, double[] end1, double[] start2, double[] end2) {
        double angle1 = calculateAngle(start1, end1);
        double angle2 = calculateAngle(start2, end2);
        return calculateSimilarity(angle1, angle2) * 100;
    }*/

    // 计算两组经纬度顺路百分比
    public static BigDecimal calculateRouteSimilarity(double[] start1, double[] end1, double[] start2, double[] end2) {
        //计算从start1 到start2 再到end2 再到end1的距离
        double distance1 = calculateDistanceUsingHaversine(start1, start2);
        double distance2 = calculateDistanceUsingHaversine(start2, end2);
        double distance3 = calculateDistanceUsingHaversine(end2, end1);
        double a=distance1+distance2+distance3;
        //计算从start1 到end1的距离
        double distance = calculateDistanceUsingHaversine(start1, end1);
        BigDecimal divide = BigDecimal.valueOf(distance).divide(BigDecimal.valueOf(a), 2, BigDecimal.ROUND_DOWN);
        divide=divide.multiply(BigDecimal.valueOf(100));
        if(divide.doubleValue()>100){
            divide=BigDecimal.valueOf(100);
        }else if(divide.doubleValue()<0){
            divide=BigDecimal.valueOf(0);
        }
        return divide;
    }

    private static final double EARTH_RADIUS_KM = 6371.0; // 地球半径，单位：千米

    // 使用Haversine公式计算两组经纬度之间的距离
    public static double calculateDistanceUsingHaversine(double[] latLng1, double[] latLng2) {
        double lat1 = Math.toRadians(latLng1[0]);
        double lon1 = Math.toRadians(latLng1[1]);
        double lat2 = Math.toRadians(latLng2[0]);
        double lon2 = Math.toRadians(latLng2[1]);

        double dLat = lat2 - lat1;
        double dLon = lon2 - lon1;

        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return EARTH_RADIUS_KM * c;
    }

}
