package com.sysu.admin.utils.shape;
 
import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.geotools.data.FeatureWriter;
import org.geotools.data.FileDataStoreFactorySpi;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.io.WKTReader;
import org.locationtech.jts.io.WKTWriter;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
 
public class ProjectTrans {
	private static GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory( null );
	private static WKTReader reader = new WKTReader( geometryFactory );
	private static WKTWriter write = new WKTWriter();
	static ProjectTrans proj = new ProjectTrans();
	
	
	final String strWKTMercator = "PROJCS[\"CGCS2000_3_Degree_GK_CM_114E\",GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",114.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]";
//	/**
//	 * 经纬度转WEB墨卡托
//	 * @param geom
//	 * @return
//	 */
//	public Geometry lonlat2WebMactor(Geometry geom){
//		try{
//			//这里是以OGC WKT形式定义的是World Mercator投影，网页地图一般使用该投影
//
////			CoordinateReferenceSystem crsTarget = CRS.parseWKT(strWKTMercator);
//	        CoordinateReferenceSystem crsTarget = CRS.decode("EPSG:3857");
//
//	        // 投影转换
//	        MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, crsTarget);
//	        return JTS.transform(geom, transform);
//		}
//		catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			return null;
//		}
//	}

	/**
	 * 经纬度转WEB墨卡托
	 * @param geom
	 * @return
	 */
	public Geometry webMactor2lonlat(Geometry geom){
		try{
			//这里是以OGC WKT形式定义的是World Mercator投影，网页地图一般使用该投影

			CoordinateReferenceSystem crsTarget = CRS.parseWKT(strWKTMercator);
//			CoordinateReferenceSystem crsTarget = CRS.decode("EPSG:3857");

			// 投影转换
			MathTransform transform = CRS.findMathTransform(crsTarget, DefaultGeographicCRS.WGS84);
			return JTS.transform(geom, transform);
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public void projectShape(String inputShp, String outputShp){
		try {
			//源shape文件
			ShapefileDataStore shapeDS = (ShapefileDataStore) new ShapefileDataStoreFactory().createDataStore(new File(inputShp).toURI().toURL());
			//创建目标shape文件对象
			Map<String, Serializable> params = new HashMap<String, Serializable>();
	        FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory();
	        params.put(ShapefileDataStoreFactory.URLP.key, new File(outputShp).toURI().toURL());
	        ShapefileDataStore ds = (ShapefileDataStore) factory.createNewDataStore(params);
	        // 设置属性
	        SimpleFeatureSource fs = shapeDS.getFeatureSource(shapeDS.getTypeNames()[0]);
	        //下面这行还有其他写法，根据源shape文件的simpleFeatureType可以不用retype，而直接用fs.getSchema设置
	        CoordinateReferenceSystem crs = CRS.parseWKT(strWKTMercator);
	        ds.createSchema(SimpleFeatureTypeBuilder.retype(fs.getSchema(), crs));
	        
	        //设置writer
	        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
	        
	        //写记录
	        SimpleFeatureIterator it = fs.getFeatures().features();
	        try {
	            while (it.hasNext()) {
	                SimpleFeature f = it.next();
	                SimpleFeature fNew = writer.next();
	                fNew.setAttributes(f.getAttributes());
	                Geometry geom = proj.webMactor2lonlat((Geometry)f.getAttribute("the_geom"));
	                fNew.setAttribute("the_geom", geom);
	            }
	        } 
	        finally {
	            it.close();
	        }
	        writer.write();
	        writer.close();
	        ds.dispose();
	        shapeDS.dispose();
		} 
		catch (Exception e) { 
			e.printStackTrace();	
		}
	}
	
	
	/**
	 * 工具类测试方法
	 * @param args
	 */
	public static void main(String[] args){
		try {
			long start = System.currentTimeMillis();
			String inputShp = "E:\\zcjy\\bhjc\\gdsdcj\\gdsdcj2.shp",
					outputShp = "E:\\zcjy\\bhjc\\gdsdcj\\output\\gdsdcj.shp";
			proj.projectShape(inputShp, outputShp);
			System.out.println("坐标转换完成，共耗时"+(System.currentTimeMillis() - start)+"ms");
		} 
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
