package com.ruoyi.ibs.draw.utils;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.ibs.grid.domain.vo.AddressResultVO;
import com.ruoyi.ibs.grid.service.AddressAnalyseService;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.locationtech.jts.io.WKTWriter;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author 吴凯程
 * @Date 2024/12/18
 **/

public class DrawUtils {

    private static final WKTReader reader = new WKTReader();

    private static final WKTWriter writer = new WKTWriter();

    @Resource
    private static AddressAnalyseService addressAnalyseService;

    public static Geometry parseWkt(String wkt) {
        Geometry geometry;
        try {
            geometry = reader.read(wkt);
        } catch (ParseException e) {
            throw new ServiceException("WKT文本转换失败：" + e);
        }
        return geometry;
    }

    public static String transferWKT(Geometry geometry) {
        return writer.write(geometry);
    }

    public static boolean isIntersect(String wktA, String wktB) {
        Geometry geometryA = parseWkt(wktA);
        Geometry geometryB = parseWkt(wktB);
        return geometryA.intersects(geometryB);
    }

    public static boolean checkOverlap(String wkt, List<String> wktList) {
        Geometry geometry = parseWkt(wkt);
        for (String wktObj : wktList) {
            Geometry geometryObj = parseWkt(wktObj);
            if (geometryObj.intersects(geometry)) {
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }

    public static boolean checkWktValid(String wkt) {
        Geometry geometry = parseWkt(wkt);
        int geoCount = geometry.getNumGeometries();
        for (int i = 0; i < geoCount; i++) {
            Polygon polygon = (Polygon) geometry.getGeometryN(i);
            for (Coordinate coordinate : polygon.getExteriorRing().getCoordinates()) {
                AddressResultVO addressResultVO = addressAnalyseService.pointInGeometry(coordinate.getX(), coordinate.getY());
                if (addressResultVO.getStatus() != 0) {
                    return Boolean.FALSE;
                }
            }
        }
        return Boolean.TRUE;
    }
}
