package com.ztmap.project.common;

import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;


public class MapDrawUtils {

    /**
     * 判断经纬度是否在圆内
     *
     * @param lon       目标经度
     * @param lat       目标纬度
     * @param dis       距离，米
     * @param centerLon 圆心经度
     * @param centerLat 圆心纬度
     * @return
     */
    public static boolean inCircle(double lon, double lat, long dis, double centerLon, double centerLat) {
        GlobalCoordinates source = new GlobalCoordinates(lat, lon);
        GlobalCoordinates target = new GlobalCoordinates(centerLat, centerLon);
        double meter2 = getDistanceMeter(source, target, Ellipsoid.WGS84);
        Boolean p1 = false;
        if (meter2 < dis) {
            p1 = true;
        }
        return p1;

    }

    public static double getDistanceMeter(GlobalCoordinates gpsFrom, GlobalCoordinates gpsTo, Ellipsoid ellipsoid) {
        //创建GeodeticCalculator，调用计算方法，传入坐标系、经纬度用于计算距离
        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(ellipsoid, gpsFrom, gpsTo);
        return geoCurve.getEllipsoidalDistance();
    }

    /**
     * 判断点是否在多边形
     * @param xys
     * @param x
     * @param y
     * @return
     */
    public static boolean withinAndIntersects(double[][] xys,double x,double y) {

        Coordinate[] polygon_array = new Coordinate[xys.length];
        int i = 0;
        for (double[] xy : xys) {
            Coordinate coordinate = new Coordinate(xy[0], xy[1]);
            polygon_array[i] = coordinate;
            i++;
        }

        boolean result = false;
        //小于3个点无法组成多边形
        if (polygon_array.length < 3) {
            return result;
        }

        //必须首尾坐标点相同组成闭合多边形
        if (!(polygon_array[0].equals2D(polygon_array[polygon_array.length - 1]))) {
            return result;
        }

        GeometryFactory geometryFactory = new GeometryFactory();
        Point point = geometryFactory.createPoint(new Coordinate(x,y));
        Polygon polygon = geometryFactory.createPolygon(polygon_array);

        if (point.within(polygon) || point.intersects(polygon)) {
            result = true;
        }

        return result;
    }
}
