package com.sysu.admin.utils.shape;

import com.sysu.admin.utils.shape.postgis.PostGisConfig;
import com.sysu.admin.utils.shape.postgis.PostGisUtil;
import org.locationtech.jts.geom.Coordinate;

import java.io.File;

public class CoordinateConversion {


    /**
     * 经纬度转墨卡托
     * @param mercator 经纬度坐标
     * @return
     */
    public static Coordinate lonLatToMercator(Coordinate mercator){
        double x =  (mercator.getX() * 20037508.342789 / 180);
        double y =  (Math.log(Math.tan((90 + mercator.getY()) * Math.PI / 360)) / (Math.PI / 180));
        y =  (double)(y * 20037508.342789 / 180);
        mercator.setX(x);
        mercator.setY(y);
        return mercator;
    }

    /**
     * 墨卡托转经纬度
     * @param mercator 墨卡托坐标
     * @return
     */
    public static Coordinate mercatorToLonLat(Coordinate mercator){
        double x =   (mercator.getX() / 20037508.342789 * 180);
        double y =  (mercator.getY() / 20037508.342789 * 180);
        y = (double) (180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2));
        mercator.setX(x);
        mercator.setY(y);
        return mercator;
    }


    /**
     *   url: localhost
     *   port: 5432
     *   database: nyc
     *   user: postgres
     *   password: root
     * @param filePath
     */
    public static void mercatorToLonLat(String filePath){
        File file = new File(filePath);
        PostGisUtil postGisUtil = new PostGisUtil();
        PostGisConfig postGisConfig = new PostGisConfig();
        postGisConfig.setUrl("localhost");
        postGisConfig.setPort(5432);
        postGisConfig.setPassword("root");
        postGisConfig.setUser("postgres");
        postGisConfig.setDatabase("nyc");
        postGisUtil.connPostGis(postGisConfig);
        postGisUtil.openConnection();

        postGisUtil.insertShp("qingyuan_crop_2", file, geometry -> {
            Coordinate[] coordinates = geometry.getCoordinates();
            for(Coordinate coordinate : coordinates){
                mercatorToLonLat(coordinate);
            }
            return geometry;
        }, false, null);

        postGisUtil.closeConnection();
        postGisUtil.dispose();
    }

    public static void main(String[] args) {
        mercatorToLonLat("E:\\zcjy\\bhjc\\QY_crop\\qingyuan_crop_2.shp");
    }


}
