LsStationRouteServiceImpl.java 21.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
package com.bsth.service.impl;

import com.bsth.annotation.BusinessDescription;
import com.bsth.entity.*;
import com.bsth.entity.search.CustomerSpecs;
import com.bsth.repository.*;
import com.bsth.service.LsStationRouteService;
import com.bsth.util.CustomBeanUtils;
import com.bsth.util.Geo.GeoUtils;
import com.bsth.util.Geo.Point;
import com.bsth.util.GeoConverter;
import org.geolatte.geom.LineString;
import org.geolatte.geom.Polygon;
import org.geolatte.geom.Position;
import org.geolatte.geom.codec.Wkt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
 * @author Hill
 */
@Service
public class LsStationRouteServiceImpl extends BaseServiceImpl<LsStationRoute, Integer> implements LsStationRouteService {

    @Autowired
    private LsStationRouteRepository lsStationRouteRepository;

    @Autowired
    private StationRouteRepository stationRouteRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private LsSectionRouteRepository lsSectionRouteRepository;

    @Autowired
    private SectionRouteRepository sectionRouteRepository;

    @Autowired
    private SectionRepository sectionRepository;

    @Autowired
    private LineRepository lineRepository;

    @Autowired
    private LineVersionsRepository lineVersionsRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Iterable<LsStationRoute> findAllByParams(Map<String, Object> map) {
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.ASC, "directions"));
        orders.add(new Sort.Order(Sort.Direction.ASC, "stationRouteCode"));

        return lsStationRouteRepository.findAll(new CustomerSpecs<>(map), Sort.by(orders));
    }

    /**
     * 获取历史站点和路段路由
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> findRoutes(Map<String, Object> map) {
        Map<String, Object> result = new HashMap<>();
        List<LsStationRoute> stationList = lsStationRouteRepository.findAll(new CustomerSpecs<>(map), Sort.by(Sort.Direction.ASC, "directions", "stationRouteCode"));
        List<LsSectionRoute> sectionList = lsSectionRouteRepository.findAll(new CustomerSpecs<>(map), Sort.by(Sort.Direction.ASC, "directions", "sectionrouteCode"));

        result.put("stationRoutes", stationList);
        result.put("sectionRoutes", sectionList);

        return result;
    }

    /**
     * 获取历史站点路由
     * @param map
     * @return
     */
    public List<LsStationRoute> findStationRoutes(Map<String, Object> map) {
        return lsStationRouteRepository.findAll(new CustomerSpecs<>(map), Sort.by(Sort.Direction.ASC, "directions", "stationRouteCode"));
    }

    /**
     * 获取当前站点以及下一站点路由
     * @param id
     * @return
     */
    @Override
    public List<LsStationRoute> findCurrentAndNext(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("需正确传入站点路由ID参数");
        }
        List<LsStationRoute> stationRoutes = new ArrayList<>();
        LsStationRoute stationRoute = lsStationRouteRepository.findById(id).get();
        Map<String, Object> params = new HashMap<>();
        params.put("line.id_eq", stationRoute.getLine().getId());
        params.put("versions_eq", stationRoute.getVersions());
        params.put("directions_eq", stationRoute.getDirections());
        params.put("destroy_eq", 0);
        params.put("stationRouteCode_gt", stationRoute.getStationRouteCode());
        List<LsStationRoute> stationRoutes1 = lsStationRouteRepository.findAll(new CustomerSpecs<>(params), Sort.by(Sort.Order.asc("stationRouteCode")));
        stationRoutes.add(stationRoute);
        if (stationRoutes1.size() > 0) {
            stationRoutes.add(stationRoutes1.get(0));
        }

        return stationRoutes;
    }

    /**
     * 批量撤销站点路由
     * @param ids
     */
    @BusinessDescription(value = "批量撤销站点路由")
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void batchDestroy(List<Integer> ids) {
        if (ids.size() > 0) {
            Integer id = ids.get(0);
            LsStationRoute stationRoute = lsStationRouteRepository.findById(id).get();
            Integer lineId = stationRoute.getLine().getId();
            Integer currentVersion = lineVersionsRepository.findCurrentVersion(lineId);
            if (stationRoute.getVersions() < currentVersion) {
                throw new IllegalArgumentException("历史版本不可变更");
            }

            lsStationRouteRepository.batchDestroy(ids);
            remark(stationRoute);
            if (stationRoute.getVersions().equals(currentVersion)) {
                refreshCurrent(lineId, currentVersion);
            }
        }
    }

    /**
     * 批量恢复撤销站点路由
     * @param ids
     */
    @BusinessDescription(value = "批量恢复撤销站点路由")
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void batchRecover(List<Integer> ids) {
        if (ids.size() > 0) {
            Integer id = ids.get(0);
            LsStationRoute stationRoute = lsStationRouteRepository.findById(id).get();
            Integer lineId = stationRoute.getLine().getId();
            Integer currentVersion = lineVersionsRepository.findCurrentVersion(lineId);
            if (stationRoute.getVersions() < currentVersion) {
                throw new IllegalArgumentException("历史版本不可变更");
            }

            lsStationRouteRepository.batchRecover(ids);
            remark(stationRoute);
            if (stationRoute.getVersions().equals(currentVersion)) {
                refreshCurrent(lineId, currentVersion);
            }
        }
    }

    @Transactional
    @Override
    public Map<String, Object> addRoutes(Integer lineId, Integer versions, Integer directions, List<LsStationRoute> stationRoutes, List<LsSectionRoute> sectionRoutes) {
        Map<String, Object> result = new HashMap<>();
        Line line = lineRepository.findById(lineId).get();
        Integer version = lineVersionsRepository.findCurrentVersion(lineId);
        if (line == null) {
            throw new RuntimeException(String.format("未找到ID为%d的线路信息", lineId));
        }
        List<Station> stations = stationRoutesHandle(line, versions, directions, stationRoutes);
        List<Section> sections = sectionRoutesHandle(line, versions, directions, sectionRoutes);

        stationRepository.saveAll(stations);
        sectionRepository.saveAll(sections);
        lsStationRouteRepository.saveAll(stationRoutes);
        lsSectionRouteRepository.saveAll(sectionRoutes);
        if (versions.equals(version)) {
            refreshCurrent(lineId, version);
        }

        return result;
    }

    private List<Station> stationRoutesHandle(Line line, Integer versions, Integer directions, List<LsStationRoute> stationRoutes) {
        List<Station> stations = new ArrayList<>();
        int currentId = stationRepository.findLatestStationId(), count = 0;
        for (int len = stationRoutes.size();count < len;) {
            LsStationRoute stationRoute = stationRoutes.get(count);
            stationRoute.setStationMark(count == 0 ? "B" : count == len - 1 ? "E" : "Z");
            count++;
            stationRoute.setLine(line);
            stationRoute.setVersions(versions);
            stationRoute.setDirections(directions);
            stationRoute.setLineCode(line.getLineCode());
            stationRoute.setStationRouteCode(100 * count);
            stationRoute.setStationCode(stationRoute.getStation().getStationCode());

            Station station = stationRoute.getStation();
            if (station.getId() == null) {
                station.setId(currentId + count);
                station.setStationCode(station.getId().toString());
                stationRoute.setStationCode(station.getStationCode());
                centerPoint(station);
                stations.add(station);
            }
        }

        return stations;
    }

    private List<Section> sectionRoutesHandle(Line line, Integer versions, Integer directions, List<LsSectionRoute> sectionRoutes) {
        List<Section> sections = new ArrayList<>();
        int currentId = sectionRepository.findLatestSectionId(), count = 0;
        for (int len = sectionRoutes.size();count < len;) {
            LsSectionRoute sectionRoute = sectionRoutes.get(count++);
            sectionRoute.setLine(line);
            sectionRoute.setVersions(versions);
            sectionRoute.setDirections(directions);
            sectionRoute.setLineCode(line.getLineCode());
            sectionRoute.setSectionrouteCode(100 * count);
            String wkt = sectionRoute.getSection().getBsectionVectorWkt();
            Section section = sectionRoute.getSection();
            section.setBsectionVector((LineString) Wkt.fromWkt(wkt));
            section.setGsectionVector(GeoConverter.lineStringBd2wgs(wkt));
            section.setId(currentId + count);
            section.setSectionCode(section.getId().toString());
            sectionRoute.setSectionCode(section.getSectionCode());
            sections.add(section);
        }

        return sections;
    }

    @BusinessDescription(value = "添加站点路由")
    @Transactional
    @Override
    public Map<String, Object> add(LsStationRoute stationRoute) {
        Station station = stationRoute.getStation();
        Line line = lineRepository.findById(stationRoute.getLine().getId()).get();
        Integer currentVersion = lineVersionsRepository.findCurrentVersion(line.getId());
        boolean isPresent = stationRepository.findById(station.getId()).isPresent();
        stationRoute.setLineCode(line.getLineCode());
        if (stationRoute.getVersions() < currentVersion) {
            throw new IllegalArgumentException("历史版本不可变更");
        }

        // 中心点坐标信息
        if (!isPresent) {
            centerPoint(station);
            stationRoute.setCenterPoint(station.getCenterPoint());
            stationRoute.setCenterPointWgs(station.getCenterPointWgs());
        }

        // 多边形缓冲区
        if ("d".equals(stationRoute.getShapedType())) {
            bufferPolygon(stationRoute);
        }

        lsStationRouteRepository.updateStatiouRouteCode(stationRoute);
        if (!isPresent) {
            stationRepository.save(station);
        }
        lsStationRouteRepository.save(stationRoute);
        remark(stationRoute);
        if (stationRoute.getVersions().equals(currentVersion)) {
            refreshCurrent(line.getId(), currentVersion);
        }

        return new HashMap<>();
    }

    @Transactional
    @Override
    public Map<String, Object> modify(LsStationRoute stationRoute) {
        LsStationRoute stationRoute1 = lsStationRouteRepository.findById(stationRoute.getId()).get();
        Integer currentVersion = lineVersionsRepository.findCurrentVersion(stationRoute1.getLine().getId());
        if (stationRoute1.getVersions() < currentVersion) {
            throw new IllegalArgumentException("历史版本不可变更");
        }

        if (!StringUtils.isEmpty(stationRoute.getCenterPointWkt())) {
            centerPoint(stationRoute);
        }

        // 多边形缓冲区
        if ("d".equals(stationRoute.getShapedType())) {
            bufferPolygon(stationRoute);
        }

        lsStationRouteRepository.updateStatiouRouteCode(stationRoute);
        CustomBeanUtils.copyPropertiesIgnoredNull(stationRoute, stationRoute1);
        lsStationRouteRepository.save(stationRoute1);
        remark(stationRoute1);
        if (stationRoute.getVersions().equals(currentVersion)) {
            refreshCurrent(stationRoute1.getLine().getId(), currentVersion);
        }

        return new HashMap<>();
    }

    @Transactional
    @Override
    public Map<String, Object> exchangeDirection(int lineId, int version) {
        lsStationRouteRepository.exchangeDirection(lineId, version);
        lsSectionRouteRepository.exchangeDirection(lineId, version);

        return new HashMap<>();
    }

    @Transactional
    @Override
    public Map<String, Object> modifyDistance(List<Integer> ids, List<Double> distances) {
        LsStationRoute stationRoute = lsStationRouteRepository.findById(ids.get(0)).get();
        int currentVersion = lineVersionsRepository.findCurrentVersion(stationRoute.getLine().getId());
        if (stationRoute.getVersions() < currentVersion) {
            throw new IllegalArgumentException("历史版本不可变更");
        }

        jdbcTemplate.batchUpdate("UPDATE bsth_c_ls_stationroute SET distances = ? WHERE id = ?", new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                ps.setDouble(1, distances.get(i));
                ps.setInt(2, ids.get(i));
            }

            @Override
            public int getBatchSize() {
                return ids.size();
            }
        });

        if (stationRoute.getVersions() == currentVersion) {
            refreshCurrent(stationRoute.getLine().getId(), currentVersion);
        }

        return new HashMap<>();
    }

    @Transactional
    @Override
    public Map<String, Object> circularRouteHandle(Integer lineId, Integer version) {
        Line line = lineRepository.findById(lineId).get();
        Integer currentVersion = lineVersionsRepository.findCurrentVersion(lineId);
        if (version < currentVersion) {
            throw new IllegalArgumentException("历史版本不可变更");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("line.id_eq", lineId);
        params.put("versions_eq", version);
        params.put("destroy_eq", 0);
        params.put("stationMark_in", "B,E");

        Sort sort = Sort.by(Sort.Order.asc("directions"), Sort.Order.asc("stationRouteCode"));
        List<LsStationRoute> routes = lsStationRouteRepository.findAll(new CustomerSpecs<>(params), sort);
        LsStationRoute route = routes.get(0);
        for (int i = 1;i < routes.size();i++) {
            LsStationRoute route1 = routes.get(i);
            if (line.getLinePlayType() == 1 && route1.getDirections() == 1) {
                break;
            }
            route1.setStationCode(route.getStationCode());
            route1.setStation(route.getStation());
        }
        lsStationRouteRepository.saveAll(routes);
        if (version.equals(currentVersion)) {
            refreshCurrent(lineId, version);
        }

        return new HashMap<>();
    }

    @Override
    public Map<String, Object> analyzeRoutes(Integer lineId, Integer version, Integer direction) {
        Map<String, Object>  result = new HashMap<>(), params = new HashMap<>();
        params.put("line.id_eq", lineId);
        params.put("versions_eq", version);
        params.put("directions_eq", direction);
        params.put("destroy_eq", 0);
        List<Sort.Order> orders1 = new ArrayList<>(), orders2 = new ArrayList<>();
        orders1.add(new Sort.Order(Sort.Direction.ASC, "directions"));
        orders1.add(new Sort.Order(Sort.Direction.ASC, "stationRouteCode"));
        orders2.add(new Sort.Order(Sort.Direction.ASC, "directions"));
        orders2.add(new Sort.Order(Sort.Direction.ASC, "sectionrouteCode"));

        boolean isCircularRoute = false;
        List<LsStationRoute> stationRoutes = lsStationRouteRepository.findAll(new CustomerSpecs<>(params), Sort.by(orders1));
        List<LsSectionRoute> sectionRoutes = lsSectionRouteRepository.findAll(new CustomerSpecs<>(params), Sort.by(orders2));
        List<String> indexes = new ArrayList<>();
        if (stationRoutes.get(0).getStationCode().equals(stationRoutes.get(stationRoutes.size() - 1).getStationCode())) {
            isCircularRoute = true;
        }
        for (LsSectionRoute sectionRoute : sectionRoutes) {
            LineString lineString = sectionRoute.getSection().getGsectionVector();
            for (int i = 0;i < lineString.getNumPositions() - 1;i++) {
                List<Point> points = new ArrayList<>();
                Position start = lineString.getPositionN(i), end = lineString.getPositionN(i + 1);
                Point point1 = new Point(start.getCoordinate(0), start.getCoordinate(1));
                Point point2 = new Point(end.getCoordinate(0), end.getCoordinate(1));
                int size = (int) (GeoUtils.getDistance(point1, point2) / 10) + 1;
                points.add(point1);
                if (size > 1) {
                    double offsetLon = (point2.getLon() - point1.getLon()) / size;
                    double offsetLat = (point2.getLat() - point1.getLat()) / size;
                    for (int j = 1;j < size;j++) {
                        Point mid = new Point(point1.getLon() + offsetLon * j, point1.getLat() + offsetLat * j);
                        points.add(mid);
                    }
                }
                points.add(point2);
                for (Point p : points) {
                    for (int j = 0;j < stationRoutes.size();j++) {
                        LsStationRoute stationRoute = stationRoutes.get(j);
                        if ("r".equals(stationRoute.getShapedType())) {
                            org.geolatte.geom.Point center = stationRoute.getStation().getCenterPointWgs();
                            if (GeoUtils.getDistance(p, new Point(center.getPositionN(0).getCoordinate(0), center.getPositionN(0).getCoordinate(1))) <= stationRoute.getRadius()) {
                                if (indexes.size() == 0 || !indexes.get(indexes.size() - 1).endsWith(String.format("-%d", j))) {
                                    indexes.add(String.format("%s-%d", stationRoute.getStationCode(), j));
                                }
                            }
                        } else {
                            Polygon polygon = stationRoute.getBufferPolygonWgs();
                            List<com.bsth.util.Geo.Point> polygonPoint = new ArrayList<>();
                            for (int k = 0;k < polygon.getNumPositions();k++) {
                                polygonPoint.add(new Point(polygon.getPositionN(k).getCoordinate(0), polygon.getPositionN(k).getCoordinate(1)));
                            }
                            com.bsth.util.Geo.Polygon polygon1 = new com.bsth.util.Geo.Polygon(polygonPoint);
                            if (GeoUtils.isPointInPolygon(p, polygon1)) {
                                if (indexes.size() == 0 || !indexes.get(indexes.size() - 1).endsWith(String.format("-%d", j))) {
                                    indexes.add(String.format("%s-%d", stationRoute.getStationCode(), j));
                                }
                            }
                        }
                    }
                }
            }
        }
        Set<String> specialStations = new LinkedHashSet<>();
        result.put("data", specialStations);
        for (int i = 0;i < stationRoutes.size();) {
            if (indexes.size() == 0) {
                break;
            }
            String lastMatch = null;
            int j = 0;
            for (;j < indexes.size();j++) {
                String index = indexes.get(j), suffix = String.format("-%d", i);
                if (index.endsWith(suffix) || isCircularRoute && i == stationRoutes.size() - 1 && index.endsWith("-0")) {
                    lastMatch = index;
                    i++;
                } else {
                    if (!index.equals(lastMatch)) {
                        specialStations.add(String.format("%s, %s", index, lastMatch));
                    }
                }
            }
            if (j == indexes.size()) {
                break;
            }
        }

        return result;
    }

    protected void centerPoint(Station station) {
        // 中心点坐标信息
        String wkt = station.getCenterPointWkt();
        if (!StringUtils.isEmpty(wkt)) {
            org.geolatte.geom.Point baidu = (org.geolatte.geom.Point) Wkt.fromWkt(wkt);
            org.geolatte.geom.Point wgs = GeoConverter.pointBd2wgs(wkt);
            station.setCenterPoint(baidu);
            station.setCenterPointWgs(wgs);
        }
    }

    protected void centerPoint(LsStationRoute route) {
        // 中心点坐标信息
        String wkt = route.getCenterPointWkt();
        if (!StringUtils.isEmpty(wkt)) {
            org.geolatte.geom.Point baidu = (org.geolatte.geom.Point) Wkt.fromWkt(wkt);
            org.geolatte.geom.Point wgs = GeoConverter.pointBd2wgs(wkt);
            route.setCenterPoint(baidu);
            route.setCenterPointWgs(wgs);
        }
    }

    protected void bufferPolygon(LsStationRoute stationRoute) {
        String wkt = stationRoute.getBufferPolygonWkt();
        if (!StringUtils.isEmpty(wkt)) {
            stationRoute.setBufferPolygon((Polygon) Wkt.fromWkt(wkt));
            stationRoute.setBufferPolygonWgs(GeoConverter.polygonBd2wgs(wkt));
        }
    }

    protected void remark(LsStationRoute stationRoute) {
        lsStationRouteRepository.updateStartZ(stationRoute);
        lsStationRouteRepository.updateStartB(stationRoute);
        lsStationRouteRepository.updateStartE(stationRoute);
    }

    protected void refreshCurrent(int lineId, int version) {
        stationRouteRepository.deleteByLine(lineId);
        stationRouteRepository.updateFromHistory(lineId, version);
    }
}