package cn.freemud.utils;

import org.apache.commons.lang.StringUtils;

import java.awt.geom.Point2D;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class LocationUtil {
    private static double EARTH_RADIUS = 6378.137;
    private static double EARTH_RADIUS_NEW = 6378137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 通过经纬度获取距离(单位：米)
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static double getDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(
                Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS_NEW;
        return s;
    }

    /// <summary>
    /// 给定的经度1，纬度1；经度2，纬度2. 计算2个经纬度之间的距离。
    /// </summary>
    /// <param name="lat1">经度1</param>
    /// <param name="lon1">纬度1</param>
    /// <param name="lat2">经度2</param>
    /// <param name="lon2">纬度2</param>
    /// <returns>距离（公里、千米）</returns>
    public static double distance(double lat1, double lon1, double lat2, double lon2) {
        //用haversine公式计算球面两点间的距离。
        //经纬度转换成弧度
        lat1 = convertDegreesToRadians(lat1);
        lon1 = convertDegreesToRadians(lon1);
        lat2 = convertDegreesToRadians(lat2);
        lon2 = convertDegreesToRadians(lon2);

        //差值
        double vLon = Math.abs(lon1 - lon2);
        double vLat = Math.abs(lat1 - lat2);

        //h is the great circle distance in radians, great circle就是一个球体上的切面，它的圆心即是球心的一个周长最大的圆。
        double h = haverSin(vLat) + Math.cos(lat1) * Math.cos(lat2) * haverSin(vLon);

        double distance = 2 * EARTH_RADIUS * Math.asin(Math.sqrt(h));
        //返回的距离保留5位小数（思舍五入）
        //BigDecimal bg = new BigDecimal(distance);
        BigDecimal bg = BigDecimal.valueOf(distance);

        distance = bg.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
        return distance;
    }

    public static double haverSin(double theta) {
        double v = Math.sin(theta / 2);
        return v * v;
    }


    /// <summary>
    /// 将角度换算为弧度。
    /// </summary>
    /// <param name="degrees">角度</param>
    /// <returns>弧度</returns>
    public static double convertDegreesToRadians(double degrees) {
        return degrees * Math.PI / 180;
    }

    public static double ConvertRadiansToDegrees(double radian) {
        return radian * 180.0 / Math.PI;
    }


    /**
     * 判断2个经纬度的距离是否在半径范围内
     *
     * @param orgLongitude 门店经度
     * @param orgLatitude  门店纬度
     * @param longitude
     * @param latitude
     * @param radius       半径（米）
     * @return
     */
    public static boolean checkDistance(String orgLongitude, String orgLatitude, String longitude, String latitude, String radius) {
        double distance = LocationUtil.distance(Double.parseDouble(orgLatitude), Double.parseDouble(orgLongitude),
                Double.parseDouble(latitude), Double.parseDouble(longitude));
        if (StringUtils.isNotEmpty(radius)) {
            if (distance * 1000 <= Double.parseDouble(radius)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取坐标是否在多边形范围里
     *
     * @param longitude
     * @param latitude
     * @param DistributionScopeforshow 多边形点集合 [[113.8524341583252,22.56028129823027],[113.8524341583252,22.56028129823027],...]
     * @return
     */
    public static boolean gpsIsInclude(String longitude, String latitude, String DistributionScopeforshow) {
        if (StringUtils.isEmpty(longitude) || StringUtils.isEmpty(latitude)) {
            return false;
        }
        Point2D.Double point = new Point2D.Double(Double.parseDouble(longitude), Double.parseDouble(latitude));
        List<Point2D.Double> pts = new ArrayList<Point2D.Double>();
        if (null != DistributionScopeforshow && DistributionScopeforshow.length() > 0) {
            DistributionScopeforshow = DistributionScopeforshow.replaceAll("\\[", "").replaceAll("\\]", "");
            String[] strDis = DistributionScopeforshow.split(",");
            if (strDis.length > 0) {
                for (int i = 0; i < strDis.length; i++) {
                    pts.add(new Point2D.Double(Double.parseDouble(strDis[i]), Double.parseDouble(strDis[i + 1])));
                    i++;
                }
            }
            //Map map = new HashMap();
            //map.put("isInclude", "true");
            //map.put("isInclude", "false");
            return isPtInPoly(point, pts);
        }
        return false;
    }

    /**
     * 判断点是否在多边形内
     *
     * @param point 检测点
     * @param pts   多边形的顶点
     * @return 点在多边形内返回true, 否则返回false
     */
    public static boolean isPtInPoly(Point2D.Double point, List<Point2D.Double> pts) {

        int N = pts.size();
        boolean boundOrVertex = true; // 如果点位于多边形的顶点或边上，也算做点在多边形内，直接返回true
        int intersectCount = 0;// cross points count of x
        double precision = 2e-10; // 浮点类型计算时候与0比较时候的容差
        Point2D.Double p1, p2;// neighbour bound vertices
        Point2D.Double p = point; // 当前点

        p1 = pts.get(0);// left vertex
        for (int i = 1; i <= N; ++i) {// check all rays
            if (p.equals(p1)) {
                return boundOrVertex;// p is an vertex
            }

            p2 = pts.get(i % N);// right vertex
            if (p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)) {// ray is outside of our interests
                p1 = p2;
                continue;// next ray left point
            }

            if (p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)) {// ray is crossing over by the algorithm
                // (common part of)
                if (p.y <= Math.max(p1.y, p2.y)) {// x is before of ray
                    if (p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)) {// overlies on a horizontal ray
                        return boundOrVertex;
                    }

                    if (p1.y == p2.y) {// ray is vertical
                        if (p1.y == p.y) {// overlies on a vertical ray
                            return boundOrVertex;
                        } else {// before ray
                            ++intersectCount;
                        }
                    } else {// cross point on the left side
                        double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;// cross point of y
                        if (Math.abs(p.y - xinters) < precision) {// overlies on a ray
                            return boundOrVertex;
                        }

                        if (p.y < xinters) {// before ray
                            ++intersectCount;
                        }
                    }
                }
            } else {// special case when ray is crossing through the vertex
                if (p.x == p2.x && p.y <= p2.y) {// p crossing over p2
                    Point2D.Double p3 = pts.get((i + 1) % N); // next vertex
                    if (p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)) {// p.x lies between p1.x & p3.x
                        ++intersectCount;
                    } else {
                        intersectCount += 2;
                    }
                }
            }
            p1 = p2;// next ray left point
        }

        if (intersectCount % 2 == 0) {// 偶数在多边形外
            return false;
        } else { // 奇数在多边形内
            return true;
        }

    }
}

