package com.ruoyi.ibs.grid.domain.dto;


import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.ibs.grid.domain.vo.AddressResultVO;
import lombok.Data;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;

import java.util.List;
import java.util.Objects;

@Data
public class GeoInfoRedisDTO {

    private Integer id;

    /**
     * 省
     */
    private String province;

    /**
     * 市
     */
    private String city;

    /**
     * 区县
     */
    private String county;

    /**
     * 街道
     */
    private String town;

    /**
     * 村
     */
    private String village;

    /**
     * 行政编码
     */
    private String code;

    /**
     * 父级行政编码
     */
    private String parentCode;

    /**
     * 行政区划等级
     */
    private Integer level;

    /**
     * 地理围栏
     */


    private String grid;

    private List<GeoInfoRedisDTO> children;

    private final WKTReader reader = new WKTReader();

    public boolean contains(Point point) {
        Geometry geometry = null;
        try {
            geometry = reader.read(this.grid);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return geometry.contains(point);
    }

    public AddressResultVO childrenMatching(Point point) {
        if (this.level == 5) {
            AddressResultVO addressResultVO = new AddressResultVO();
            BeanUtils.copyProperties(this, addressResultVO);
            addressResultVO.setStatus(0);
            addressResultVO.setLng(point.getX());
            addressResultVO.setLat(point.getY());
            return addressResultVO;
        }
        for (GeoInfoRedisDTO geoInfoDTO : this.children) {
            if (Objects.isNull(geoInfoDTO.getGrid())) {
                continue;
            }
            if (geoInfoDTO.contains(point)) {
                return geoInfoDTO.childrenMatching(point);
            }
        }
        AddressResultVO addressResultVO = new AddressResultVO();
        BeanUtils.copyProperties(this, addressResultVO);
        addressResultVO.setStatus(0);
        addressResultVO.setLng(point.getX());
        addressResultVO.setLat(point.getY());
        return addressResultVO;
    }

}
