GpsServiceImpl.java 26.2 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 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
package com.bsth.service.gps;

import com.bsth.common.ResponseCode;
import com.bsth.data.BasicData;
import com.bsth.data.arrival.ArrivalEntity;
import com.bsth.data.gpsdata.GpsEntity;
import com.bsth.data.gpsdata.GpsRealData;
import com.bsth.data.gpsdata.arrival.utils.GeoUtils;
import com.bsth.data.safe_driv.SafeDriv;
import com.bsth.data.safe_driv.SafeDrivCenter;
import com.bsth.data.schedule.DayOfSchedule;
import com.bsth.entity.realcontrol.ScheduleRealInfo;
import com.bsth.repository.CarParkRepository;
import com.bsth.repository.StationRepository;
import com.bsth.repository.realcontrol.ScheduleRealInfoRepository;
import com.bsth.service.gps.entity.GpsOutbound_DTO;
import com.bsth.service.gps.entity.GpsSpeed_DTO;
import com.bsth.service.gps.entity.HistoryGps_DTO;
import com.bsth.service.gps.entity.Road_DTO;
import com.bsth.util.DateUtils;
import com.bsth.util.TransGPS;
import com.bsth.util.TransGPS.Location;
import com.bsth.util.db.DBUtils_MS;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DecimalFormat;
import java.util.*;

@Service
public class GpsServiceImpl implements GpsService {
    /**
     * 历史gps查询最大范围 24小时
     */
    final static Long GPS_RANGE = 60 * 60 * 24L;

    /**
     * jdbc
     */
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    GpsRealData gpsRealData;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    DayOfSchedule dayOfSchedule;

    @Autowired
    ScheduleRealInfoRepository scheduleRealInfoRepository;

    // 历史gps查询
    @Override
    public List<Map<String, Object>> history(String device, Long startTime, Long endTime, int directions) {
        Calendar sCal = Calendar.getInstance();
        sCal.setTime(new Date(startTime));

        Calendar eCal = Calendar.getInstance();
        eCal.setTime(new Date(endTime));

        int dayOfYear = sCal.get(Calendar.DAY_OF_YEAR);
        /*
         * if(dayOfYear != eCal.get(Calendar.DAY_OF_YEAR)){
		 * System.out.println("暂时不支持跨天查询..."); return null; }
		 */

        String sql = "select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,STOP_NO from bsth_c_gps_info where days_year=? and device_id=? and ts > ? and ts < ?";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = null;
        try {
            conn = DBUtils_MS.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, dayOfYear);
            ps.setString(2, device);
            ps.setLong(3, startTime);
            ps.setLong(4, endTime);

            rs = ps.executeQuery();
            Float lon, lat;
            Location location;
            int upDown;
            while (rs.next()) {
                upDown = getUpOrDown(rs.getLong("SERVICE_STATE"));
                if (upDown != directions)
                    continue;

                // to 百度坐标
                lon = rs.getFloat("LON");
                lat = rs.getFloat("LAT");
                location = TransGPS.LocationMake(lon, lat);
                location = TransGPS.bd_encrypt(TransGPS.transformFromWGSToGCJ(location));

                map = new HashMap<>();
                map.put("device", rs.getString("DEVICE_ID"));
                map.put("lon", location.getLng());
                map.put("lat", location.getLat());
                map.put("ts", rs.getLong("TS"));
                map.put("stopNo", rs.getString("STOP_NO"));
                map.put("inout_stop", rs.getInt("INOUT_STOP"));
                // 上下行
                map.put("upDown", upDown);
                list.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils_MS.close(rs, ps, conn);
        }
        return list;
    }

    /**
     * 王通 2016/6/29 9:23:24 获取车辆线路上下行
     *
     * @return -1无效 0上行 1下行
     */
    public static byte getUpOrDown(long serviceState) {
        if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000
                || (serviceState & 0x01000000) == 0x01000000 || (serviceState & 0x08000000) == 0x08000000)
            return -1;
        return (byte) (((serviceState & 0x10000000) == 0x10000000) ? 1 : 0);
    }

    @Override
    public List<Map<String, Object>> history(String[] nbbmArray, Long st, Long et) {
        List<Map<String, Object>> list = new ArrayList<>();
        // 超过最大查询范围,直接忽略
        if (et - st > GPS_RANGE)
            return list;

        // 车辆编码转换成设备号
        String[] devices = new String[nbbmArray.length];
        for (int i = 0; i < nbbmArray.length; i++) {
            devices[i] = BasicData.deviceId2NbbmMap.inverse().get(nbbmArray[i]);
        }
        // day_of_year
        Calendar sCal = Calendar.getInstance();
        sCal.setTime(new Date(st * 1000));
        int sDayOfYear = sCal.get(Calendar.DAY_OF_YEAR)/* 200 */;

        Calendar eCal = Calendar.getInstance();
        eCal.setTime(new Date(et * 1000));
        int eDayOfYear = eCal.get(Calendar.DAY_OF_YEAR)/* 200 */;

        Calendar weekCal = Calendar.getInstance();

        // 如果是同一天
        if (sDayOfYear == eDayOfYear) {
            weekCal.setTimeInMillis(st * 1000);
            list = findByTs(weekCal.get(Calendar.WEEK_OF_YEAR), sDayOfYear, st, et, devices);
        } else {
            // 跨天
            Long tempSt = 0L, tempEt = 0L;
            for (int i = sDayOfYear; i <= eDayOfYear; i++) {

                if (i == sDayOfYear) {
                    tempSt = st;
                    tempEt = DateUtils.getTimesnight(sCal);
                } else if (i == eDayOfYear) {
                    tempSt = DateUtils.getTimesmorning(sCal);
                    tempEt = et;
                } else {
                    tempSt = DateUtils.getTimesmorning(sCal);
                    tempEt = DateUtils.getTimesnight(sCal);
                }

                weekCal.setTimeInMillis(tempSt * 1000);
                list.addAll(findByTs(weekCal.get(Calendar.WEEK_OF_YEAR), i, tempSt, tempEt, devices));
                // 加一天
                sCal.add(Calendar.DATE, 1);
            }
        }

        // 按时间排序
        Collections.sort(list, new Comparator<Map<String, Object>>() {

            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));
            }
        });
        return list;
    }

    public List<Map<String, Object>> findByTs(int weekOfYear, int dayOfYear, Long st, Long et, String[] devices) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = null;

        // 直接拼 in 语句
        String inv = "";
        for (String device : devices)
            inv += ("'" + device + "',");
        inv = inv.substring(0, inv.length() - 1);

        // 查询到离站数据
        Map<String, ArrivalEntity> arrivalMap = findArrivalByTs(weekOfYear, st, et, inv);

        String sql = "select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,STOP_NO,DIRECTION,LINE_ID,SPEED_GPS from bsth_c_gps_info where days_year=? and device_id in ("
                + inv + ") and ts > ? and ts < ? ORDER BY device_id,ts,stop_no";
        try {
            conn = DBUtils_MS.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, dayOfYear);
            /* ps.setArray(2, conn.createArrayOf("VARCHAR", devices)); */
            ps.setLong(2, st * 1000);
            ps.setLong(3, et * 1000);

            rs = ps.executeQuery();
            Float lon, lat;
            Location bdLoc, gdLoc;
            int upDown, inOutStop;
            ArrivalEntity arrival;
            while (rs.next()) {
                upDown = getUpOrDown(rs.getLong("SERVICE_STATE"));
                map = new HashMap<>();

                lon = rs.getFloat("LON");
                lat = rs.getFloat("LAT");
                // 高德坐标
                gdLoc = TransGPS.transformFromWGSToGCJ(TransGPS.LocationMake(lon, lat));
                map.put("gcj_lon", gdLoc.getLng());
                map.put("gcj_lat", gdLoc.getLat());
                // 百度坐标
                bdLoc = TransGPS.bd_encrypt(gdLoc);
                map.put("bd_lon", bdLoc.getLng());
                map.put("bd_lat", bdLoc.getLat());
                //原始坐标
                map.put("lon", lon);
                map.put("lat", lat);

                map.put("deviceId", rs.getString("DEVICE_ID"));
                map.put("ts", rs.getLong("TS"));
                map.put("timestamp", rs.getLong("TS"));
                map.put("stopNo", rs.getString("STOP_NO"));
                map.put("direction", rs.getFloat("DIRECTION"));

                map.put("lineId", rs.getString("LINE_ID"));
                map.put("speed", rs.getFloat("SPEED_GPS"));

                inOutStop = rs.getInt("INOUT_STOP");
                map.put("inout_stop", inOutStop);

                arrival = arrivalMap.get(rs.getString("DEVICE_ID") + "_" + rs.getLong("TS"));
                if (arrival != null) {
                    map.put("inout_stop_info", arrival);
                    map.put("inout_stop", arrival.getInOut());
                }

                map.put("nbbm", BasicData.deviceId2NbbmMap.get(rs.getString("DEVICE_ID")));
                map.put("state", 0);
                // 上下行
                map.put("upDown", upDown);
                list.add(map);
            }
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            DBUtils_MS.close(rs, ps, conn);
        }
        return list;
    }

    public Map<String, ArrivalEntity> findArrivalByTs(int weekOfYear, Long st, Long et, String devicesInSql) {
        Map<String, ArrivalEntity> map = new HashMap<>();

        String sql = "SELECT DEVICE_ID,LINE_ID,STOP_NO,TS,UP_DOWN,IN_OUT,WEEKS_YEAR,CREATE_DATE FROM bsth_c_arrival_info where weeks_year=? and device_id in ("
                + devicesInSql + ") and ts > ? and ts < ?";
        try {
            conn = DBUtils_MS.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, weekOfYear);
            ps.setLong(2, st * 1000);
            ps.setLong(3, et * 1000);

            rs = ps.executeQuery();
            ArrivalEntity arr;
            int inOut, updown;
            String prefix, stationName, lineId;
            while (rs.next()) {
                lineId = rs.getString("LINE_ID");
                updown = rs.getInt("UP_DOWN");
                prefix = lineId + "_" + updown + "_";
                stationName = BasicData.getStationNameByCode(rs.getString("STOP_NO"), prefix);

                if (StringUtils.isEmpty(stationName))
                    continue;

                arr = new ArrivalEntity(rs.getString("DEVICE_ID"), rs.getLong("TS"), lineId,
                        updown, rs.getString("STOP_NO"), rs.getInt("IN_OUT"), rs.getLong("CREATE_DATE"),
                        rs.getInt("WEEKS_YEAR"), stationName);

                // 设备号_时间戳_进出状态 为key
                // 反转进出状态
                inOut = arr.getInOut() == 0 ? 1 : 0;
                map.put(arr.getDeviceId() + "_" + arr.getTs(), arr);
            }
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            DBUtils_MS.close(rs, ps, conn);
        }
        return map;
    }


    @Autowired
    StationRepository stationRepository;

    @Autowired
    CarParkRepository carParkRepository;

    @Override
    public Map<String, Object> findBuffAeraByCode(String code, String type) {
        Object[][] obj = null;
        if (type.equals("station"))
            obj = stationRepository.bufferAera(code);
        else if (type.equals("park"))
            obj = carParkRepository.bufferAera(code);

        Map<String, Object> rs = new HashMap<>();

        Object[] subObj = obj[0];
        if (subObj != null && subObj.length == 6) {
            rs.put("polygon", subObj[0]);
            rs.put("type", subObj[1]);
            rs.put("cPoint", subObj[2]);
            rs.put("radius", subObj[3]);
            rs.put("code", subObj[4]);
            rs.put("text", subObj[5]);
        }

        return rs;
    }

    @Override
    public Map<String, Object> search(Map<String, Object> map, int page, int size, String order, String direction) {
        Map<String, Object> rsMap = new HashMap<>();
        try {
            //全量
            List<GpsEntity> list = new ArrayList<>(gpsRealData.all());
            //过滤后的
            List<GpsEntity> rs = new ArrayList<>();
            Field[] fields = GpsEntity.class.getDeclaredFields();
            //参与过滤的字段
            List<Field> fs = new ArrayList<>();
            for (Field f : fields) {
                f.setAccessible(true);
                if (map.containsKey(f.getName()))
                    fs.add(f);
            }
            //过滤数据
            for (GpsEntity gps : list) {
                if (fieldEquals(fs, gps, map))
                    rs.add(gps);
            }

            //时间戳排序
            Collections.sort(rs, new Comparator<GpsEntity>() {
                @Override
                public int compare(GpsEntity o1, GpsEntity o2) {
                    return o2.getTimestamp().intValue() - o1.getTimestamp().intValue();
                }
            });

            //分页
            int count = rs.size(), s = page * size, e = s + size;
            if (e > count)
                e = count;

            rsMap.put("list", rs.subList(s, e));
            rsMap.put("totalPages", count % size == 0 ? count / size - 1 : count / size);
            rsMap.put("page", page);
            rsMap.put("status", ResponseCode.SUCCESS);
        } catch (Exception e) {
            logger.error("", e);
            rsMap.put("status", ResponseCode.ERROR);
        }
        return rsMap;
    }

    @Override
    public Map<String, Object> removeRealGps(String device) {
        Map<String, Object> rs = new HashMap<>();
        try {

            gpsRealData.remove(device);
            rs.put("status", ResponseCode.SUCCESS);
        } catch (Exception e) {
            rs.put("status", ResponseCode.ERROR);
        }
        return rs;
    }

    @Override
    public Map<String, Object> findRoadSpeed(String lineCode) {
        Map<String, Object> rs = new HashMap<>();

        try {
            String sql = "select ID, ST_AsText(GROAD_VECTOR) as GROAD_VECTOR,ROAD_CODE,ROAD_NAME,SPEED from bsth_c_road where road_code in(select section_code from bsth_c_sectionroute where line_code=? and destroy=0)";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, lineCode);
            rs.put("status", ResponseCode.SUCCESS);
            rs.put("roads", list);
        } catch (DataAccessException e) {
            logger.error("", e);
            rs.put("status", ResponseCode.ERROR);
        }
        return rs;
    }

    /**
     * gps补全
     *
     * @param schId
     * @return
     */
    @Override
    public Map<String, Object> gpsCompletion(long schId) {
        Map<String, Object> rs = new HashMap<>();

        try {
            ScheduleRealInfo sch = dayOfSchedule.get(schId);
            if (sch == null) {
                rs.put("status", ResponseCode.ERROR);
                rs.put("msg", "找不到对应班次!!!");
                return rs;
            }

            if (sch.isReissue()) {
                rs.put("status", ResponseCode.ERROR);
                rs.put("msg", "你不能重复这个操作");
                return rs;
            }

            String sql = "select * from bsth_gps_template where line_id='" + sch.getXlBm() + "' and up_down=" + sch.getXlDir();
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

            if (list.size() == 0) {
                rs.put("status", ResponseCode.ERROR);
                rs.put("msg", "缺少模板数据,请联系系统管理员!!");
                return rs;
            }
            //排序
            Collections.sort(list, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));
                }
            });
            Map<String, Object> fs = list.get(0);
            //替换设备号和时间
            int diff = (int) (sch.getDfsjT() - Long.parseLong(fs.get("ts").toString()) - 1000 * 70);

            String deviceId = BasicData.deviceId2NbbmMap.inverse().get(sch.getClZbh());
            for (Map<String, Object> map : list) {
                map.put("device_id", deviceId);
                map.put("ts", Long.parseLong(map.get("ts").toString()) + diff);
            }

            String sqlBefore = "insert into bsth_c_template(", sqlValues = " values(";

            Set<String> ks = fs.keySet();
            for (String k : ks) {
                sqlBefore += (k + ",");
                sqlValues += "?,";
            }
            sqlBefore = sqlBefore.substring(0, sqlBefore.length() - 1) + ", create_ts)";
            sqlValues = sqlValues.substring(0, sqlValues.length() - 1) + ", " + System.currentTimeMillis() + ")";
            sql = sqlBefore + " " + sqlValues;

            Connection conn = DBUtils_MS.getConnection();
            conn.setAutoCommit(false);
            ps = conn.prepareStatement(sql);
            int fsize = ks.size();
            List<Object> vs;
            for (Map<String, Object> map : list) {
                vs = new ArrayList<>(map.values());
                for (int i = 0; i < fsize; i++) {
                    ps.setObject(i + 1, vs.get(i));
                }
                ps.addBatch();
            }
            ps.executeBatch();
            conn.commit();

            rs.put("status", ResponseCode.SUCCESS);

            //标记班次
            sch.setReissue(true);
            scheduleRealInfoRepository.save(sch);

            rs.put("status", ResponseCode.SUCCESS);
        } catch (Exception e) {
            logger.error("", e);
            rs.put("status", ResponseCode.ERROR);
        }
        return rs;
    }

    @Override
    public Map<String, Object> history_v2(String nbbm, long st, long et) {
        Map<String, Object> rs = new HashMap<>();

        try {
            //获取历史gps 数据
            List<HistoryGps_DTO> list = HistoryGps_DTO.craete(history(new String[]{nbbm}, st, et));
            if (list != null && list.size() > 0) {
                //获取路段信息
                String sql = "select ID, ST_AsText(GROAD_VECTOR) as GROAD_VECTOR,ROAD_CODE,ROAD_NAME,SPEED from bsth_c_road where road_code in(select section_code from bsth_c_sectionroute where line_code=? and destroy=0)";
                List<Road_DTO> roads = Road_DTO.craete(jdbcTemplate.queryForList(sql, list.get(0).getLineId()));

                //为GPS数据关联路段信息
                for (HistoryGps_DTO gps : list) {
                    matchRoadToGps(gps, roads);
                }
            }

            //超速数据
            List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);
            //越界数据
            List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);
            //计算里程
            List<HistoryGps_DTO> effList = new ArrayList<>();
            for(HistoryGps_DTO gps : list){
                if(gps.getLat() != 0 && gps.getLon() != 0)
                    effList.add(gps);
            }
            double sum = 0, dist;
            for (int i = 0; i < effList.size() - 1; i++) {
                dist = GeoUtils.getDistance(effList.get(i).getPoint(), effList.get(i + 1).getPoint());
                //点位相同时,dist会NaN
                if(String.valueOf(dist).matches("^[0.0-9.0]+$"))
                    sum += dist;
            }

            rs.put("status", ResponseCode.SUCCESS);
            rs.put("list", removeDuplicate(effList));
            rs.put("speedList", speedList);
            rs.put("outboundList", outboundList);
            rs.put("sumMileage", new DecimalFormat(".##").format(sum / 1000));
        } catch (Exception e) {
            logger.error("", e);
            rs.put("status", ResponseCode.ERROR);
        }
        return rs;
    }

    @Override
    public List<GpsSpeed_DTO> speeds(String nbbm, long st, long et) {
        String deviceId = BasicData.deviceId2NbbmMap.inverse().get(nbbm);
        String sql = "select vehicle, line, up_down, lon, lat, speed,timestamp from bsth_c_speeding where vehicle=? and timestamp>? and timestamp<?";

        return GpsSpeed_DTO.create(new JdbcTemplate(DBUtils_MS.getDataSource()).queryForList(sql, deviceId, st * 1000, et * 1000));
    }

    @Override
    public List<GpsOutbound_DTO> outbounds(String nbbm, long st, long et) {
        /**
         * 如果 st 和 et 跨了周分区,也只查询st 分区的数据。
         */
        st = st * 1000;
        et = et * 1000;
        //按周分区
        Calendar weekCal = Calendar.getInstance();
        weekCal.setTimeInMillis(st);
        int weekYear = weekCal.get(Calendar.WEEK_OF_YEAR);
        //设备号
        String deviceId = BasicData.deviceId2NbbmMap.inverse().get(nbbm);
        String sql = "select vehicle,line,up_down,lon,lat,timestamp from bsth_c_outbound where weeks_year=" + weekYear + " and vehicle=? and timestamp>? and timestamp<?";
        return GpsOutbound_DTO.create(new JdbcTemplate(DBUtils_MS.getDataSource()).queryForList(sql, deviceId, st, et));
    }

    @Override
    public Map<String, Object> safeDrivList(Map<String, Object> map, int page, int size, String order, String direction) {
        Map<String, Object> rsMap = new HashMap<>();
        try {
            //全量
            List<SafeDriv> list = new ArrayList<>(SafeDrivCenter.findAll());
            //过滤后的
            List<SafeDriv> rs = new ArrayList<>();
            Field[] fields = SafeDriv.class.getDeclaredFields();
            //参与过滤的字段
            List<Field> fs = new ArrayList<>();
            for (Field f : fields) {
                f.setAccessible(true);
                if (map.containsKey(f.getName()))
                    fs.add(f);
            }
            //过滤数据
            for (SafeDriv sd : list) {
                if (fieldEquals(fs, sd, map))
                    rs.add(sd);
            }

            //时间戳排序
            Collections.sort(rs, new Comparator<SafeDriv>() {
                @Override
                public int compare(SafeDriv o1, SafeDriv o2) {
                    return o2.getTs().intValue() - o1.getTs().intValue();
                }
            });

            //分页
            int count = rs.size(), s = page * size, e = s + size;
            if (e > count)
                e = count;

            rsMap.put("list", rs.subList(s, e));
            rsMap.put("totalPages", count % size == 0 ? count / size - 1 : count / size);
            rsMap.put("page", page);
            rsMap.put("status", ResponseCode.SUCCESS);
        } catch (Exception e) {
            logger.error("", e);
            rsMap.put("status", ResponseCode.ERROR);
        }
        return rsMap;
    }

    private void matchRoadToGps(HistoryGps_DTO gps, List<Road_DTO> roads) {
        double min = -1, distance;
        Road_DTO nearRoad = null;
        for (Road_DTO road : roads) {
            distance = GeoUtils.getDistanceFromLine(road.getLineStr(), gps.getPoint());

            if (min > distance || min == -1) {
                min = distance;
                nearRoad = road;
            }
        }

        gps.setRoad(nearRoad);
        gps.setRoadMinDistance(min);
    }

    /**
     * 去重复
     *
     * @param list
     * @return
     */
    private Set<HistoryGps_DTO> removeDuplicate(List<HistoryGps_DTO> list) {
        Set<HistoryGps_DTO> set = new HashSet<>();
        for (HistoryGps_DTO gps : list) {
            set.add(gps);
        }
        return set;
    }

    private void sortGpsList(final Field f, List<GpsEntity> rs) {
        Collections.sort(rs, new Comparator<GpsEntity>() {

            @Override
            public int compare(GpsEntity o1, GpsEntity o2) {
                try {
                    if (f.get(o1) == f.get(o2))
                        return 0;

                    if (null == f.get(o1))
                        return 1;

                    if (null == f.get(o2))
                        return -1;

                    return f.get(o1).toString().compareTo(f.get(o2).toString());
                } catch (Exception e) {
                    logger.error("", e);
                    return -1;
                }
            }
        });
    }

    public boolean fieldEquals(List<Field> fs, Object obj, Map<String, Object> map) {
        try {
            for (Field f : fs) {
                if (StringUtils.isEmpty(map.get(f.getName()).toString()))
                    continue;

                if (f.get(obj) == null || f.get(obj).toString().indexOf(map.get(f.getName()).toString()) == -1)
                    return false;
            }
        } catch (Exception e) {
            logger.error("", e);
            return false;
        }
        return true;
    }
}