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.Component;

import java.io.IOException;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

        //查询出与测量面积相交的区域
        StringBuffer filter = new StringBuffer(500);
        filter.append(" FROM \"qysdcj\"  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,"qysdcj", true);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            postGisUtil.closeConnection();
            postGisUtil.dispose();
        }
        List<AnalyseRow> analyseResults = new ArrayList<>();
        int i = 0;
        Double sumArea = DataTypeConvert.getArea(geometry);

        for(SimpleFeature feature : featureList) {
            Map<String, Object> map = new HashMap();
            map.put("name", feature.getAttribute("zldwmc").toString());
            map.put("objectid", feature.getAttribute("objectid").toString());
            Geometry newGeometry = SnapOverlayOp.intersection(geometry.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)));
    }
}
