package com.sysu.admin.controller.analyse;

import com.sysu.admin.support.base.ServiceContext;
import com.sysu.admin.utils.shape.DataTypeConvert;
import com.sysu.admin.utils.shape.GeoServerCQLECQL;
import com.sysu.admin.utils.shape.postgis.PostGisUtil;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.operation.overlay.snap.SnapOverlayOp;
import org.opengis.feature.simple.SimpleFeature;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @author shu hao
 * @description:
 * @date 2022/5/19 15:27
 */
@Service
public class TownsAnalyseService extends ServiceContext implements AnalyseService{
    @Override
    public AnalyseTable analyse(String wkt) throws IOException {
        DecimalFormat df = new DecimalFormat("######0.00");
        PostGisUtil postGisUtil = new PostGisUtil();
        postGisUtil.connPostGis();
        postGisUtil.openConnection();
        Geometry geometry = DataTypeConvert.wkt2Geometry(wkt);

//        List<Param> params = new ArrayList<>();
//        params.add(new Param(new String[]{}, new Object[]{}));
//        FileFormat.toShp(Arrays.asList(new Geometry[]{geometry}), "E:\\zcjy\\bhjc\\test.shp", new ParamType[0], params);

        //查询出与测量面积相交的区域
        StringBuffer filter = new StringBuffer(500);
        filter.append(" FROM \"qy-z\"  WHERE ST_Relate(geom,'")
                .append(wkt )
                .append("','T********') = true");
        System.out.println("长度："+filter.length());

        List<SimpleFeature> featureList = null;
        try {
            featureList = postGisUtil.queryMethod(filter.toString(),null,"qy-z", true);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            postGisUtil.closeConnection();
            postGisUtil.dispose();
        }
        List<AnalyseRow> analyseResults = new ArrayList<>();
        Double sumArea = DataTypeConvert.getArea(geometry);

        for(SimpleFeature feature : featureList) {
            Map<String, Object> map = new HashMap();
            map.put("name", feature.getAttribute("name").toString());
            map.put("objectid", feature.getAttribute("objectid").toString());
            Geometry newGeometry = SnapOverlayOp.intersection(geometry,(Geometry)feature.getDefaultGeometry());

            Double area = DataTypeConvert.getArea(newGeometry);
            map.put("area", df.format(area));
            map.put("percent", df.format(area / sumArea * 100));
            feature.setDefaultGeometry(newGeometry);
            String json = GeoServerCQLECQL.featureToGeoJson(feature);
            analyseResults.add(new AnalyseRow(json, map));
        }
        return new AnalyseTable(analyseResults, Double.parseDouble(df.format(sumArea)));
    }
}
