Commit f72cc8a76c8c8dff511fa58575032143134547db

Authored by 王通
1 parent 881fcb60

1.

src/main/java/com/bsth/service/gps/GpsServiceImpl.java
1   -package com.bsth.service.gps;
2   -
3   -import java.io.IOException;
4   -import java.io.OutputStream;
5   -import java.io.UnsupportedEncodingException;
6   -import java.lang.reflect.Field;
7   -import java.net.URLEncoder;
8   -import java.sql.Connection;
9   -import java.sql.PreparedStatement;
10   -import java.sql.ResultSet;
11   -import java.sql.SQLException;
12   -import java.text.DecimalFormat;
13   -import java.text.ParseException;
14   -import java.text.SimpleDateFormat;
15   -import java.util.ArrayList;
16   -import java.util.Arrays;
17   -import java.util.Calendar;
18   -import java.util.Collections;
19   -import java.util.Comparator;
20   -import java.util.Date;
21   -import java.util.HashMap;
22   -import java.util.HashSet;
23   -import java.util.Iterator;
24   -import java.util.LinkedList;
25   -import java.util.List;
26   -import java.util.Map;
27   -import java.util.Set;
28   -
29   -import javax.servlet.http.HttpServletResponse;
30   -
31   -import org.apache.commons.lang3.StringUtils;
32   -import org.apache.poi.hssf.usermodel.HSSFCellStyle;
33   -import org.apache.poi.hssf.usermodel.HSSFWorkbook;
34   -import org.apache.poi.ss.usermodel.CellStyle;
35   -import org.apache.poi.ss.usermodel.Row;
36   -import org.apache.poi.ss.usermodel.Sheet;
37   -import org.apache.poi.ss.usermodel.Workbook;
38   -import org.joda.time.format.DateTimeFormat;
39   -import org.joda.time.format.DateTimeFormatter;
40   -import org.slf4j.Logger;
41   -import org.slf4j.LoggerFactory;
42   -import org.springframework.beans.factory.annotation.Autowired;
43   -import org.springframework.dao.DataAccessException;
44   -import org.springframework.jdbc.core.BeanPropertyRowMapper;
45   -import org.springframework.jdbc.core.JdbcTemplate;
46   -import org.springframework.stereotype.Service;
47   -
48   -import com.bsth.common.ResponseCode;
49   -import com.bsth.data.BasicData;
50   -import com.bsth.data.forecast.entity.ArrivalEntity;
51   -import com.bsth.data.gpsdata_v2.GpsRealData;
52   -import com.bsth.data.gpsdata_v2.cache.GeoCacheData;
53   -import com.bsth.data.gpsdata_v2.cache.GpsCacheData;
54   -import com.bsth.data.gpsdata_v2.entity.GpsEntity;
55   -import com.bsth.data.gpsdata_v2.utils.GeoUtils;
56   -import com.bsth.data.pilot80.PilotReport;
57   -import com.bsth.data.safe_driv.SafeDriv;
58   -import com.bsth.data.safe_driv.SafeDrivCenter;
59   -import com.bsth.data.schedule.DayOfSchedule;
60   -import com.bsth.entity.LineVersions;
61   -import com.bsth.entity.LsSectionRoute;
62   -import com.bsth.entity.LsStationRoute;
63   -import com.bsth.entity.directive.D80;
64   -import com.bsth.entity.realcontrol.ScheduleRealInfo;
65   -import com.bsth.repository.CarParkRepository;
66   -import com.bsth.repository.LineRepository;
67   -import com.bsth.repository.LineVersionsRepository;
68   -import com.bsth.repository.LsSectionRouteRepository;
69   -import com.bsth.repository.LsStationRouteRepository;
70   -import com.bsth.repository.StationRepository;
71   -import com.bsth.repository.realcontrol.ScheduleRealInfoRepository;
72   -import com.bsth.service.gps.entity.DeviceChange;
73   -import com.bsth.service.gps.entity.GpsOutbound_DTO;
74   -import com.bsth.service.gps.entity.GpsSpeed;
75   -import com.bsth.service.gps.entity.GpsSpeed_DTO;
76   -import com.bsth.service.gps.entity.HistoryGps_DTO;
77   -import com.bsth.service.gps.entity.HistoryGps_DTOV3;
78   -import com.bsth.service.gps.entity.Road_DTO;
79   -import com.bsth.util.CoordinateConverter;
80   -import com.bsth.util.CoordinateConverter.Location;
81   -import com.bsth.util.db.DBUtils_MS;
82   -
83   -@Service
84   -public class GpsServiceImpl implements GpsService {
85   - /**
86   - * 历史gps查询最大范围 24小时
87   - */
88   - final static Long GPS_RANGE = 60 * 60 * 24L;
89   -
90   - /**
91   - * jdbc
92   - */
93   - Connection conn = null;
94   - PreparedStatement ps = null;
95   - ResultSet rs = null;
96   -
97   - Logger logger = LoggerFactory.getLogger(this.getClass());
98   -
99   - @Autowired
100   - GpsRealData gpsRealData;
101   -
102   - @Autowired
103   - JdbcTemplate jdbcTemplate;
104   -
105   - @Autowired
106   - DayOfSchedule dayOfSchedule;
107   -
108   - @Autowired
109   - ScheduleRealInfoRepository scheduleRealInfoRepository;
110   -
111   -
112   - @Autowired
113   - LineVersionsRepository lineVersionsRepository;
114   -
115   - @Autowired
116   - LineRepository lineRepository;
117   -
118   - @Autowired
119   - LsStationRouteRepository lsStationRouteRepository;
120   -
121   - @Autowired
122   - LsSectionRouteRepository lsSectionRouteRepository;
123   -
124   - // 历史gps查询
125   - @Override
126   - public List<Map<String, Object>> history(String device, Long startTime, Long endTime, int directions) {
127   - Calendar sCal = Calendar.getInstance();
128   - sCal.setTime(new Date(startTime));
129   -
130   - Calendar eCal = Calendar.getInstance();
131   - eCal.setTime(new Date(endTime));
132   -
133   - int dayOfYear = sCal.get(Calendar.DAY_OF_YEAR);
134   - /*
135   - * if(dayOfYear != eCal.get(Calendar.DAY_OF_YEAR)){
136   - * System.out.println("暂时不支持跨天查询..."); return null; }
137   - */
138   -
139   - 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 < ?";
140   - Connection conn = null;
141   - PreparedStatement ps = null;
142   - ResultSet rs = null;
143   - List<Map<String, Object>> list = new ArrayList<>();
144   - Map<String, Object> map = null;
145   - try {
146   - conn = DBUtils_MS.getConnection();
147   - ps = conn.prepareStatement(sql);
148   - ps.setInt(1, dayOfYear);
149   - ps.setString(2, device);
150   - ps.setLong(3, startTime);
151   - ps.setLong(4, endTime);
152   -
153   - rs = ps.executeQuery();
154   - Float lon, lat;
155   - Location location;
156   - int upDown;
157   - while (rs.next()) {
158   - upDown = getUpOrDown(rs.getLong("SERVICE_STATE"));
159   - if (upDown != directions)
160   - continue;
161   -
162   - // to 百度坐标
163   - lon = rs.getFloat("LON");
164   - lat = rs.getFloat("LAT");
165   - location = CoordinateConverter.LocationMake(lon, lat);
166   - location = CoordinateConverter.bd_encrypt(CoordinateConverter.transformFromWGSToGCJ(location));
167   -
168   - map = new HashMap<>();
169   - map.put("device", rs.getString("DEVICE_ID"));
170   - map.put("lon", location.getLng());
171   - map.put("lat", location.getLat());
172   - map.put("ts", rs.getLong("TS"));
173   - map.put("stopNo", rs.getString("STOP_NO"));
174   - map.put("inout_stop", rs.getInt("INOUT_STOP"));
175   - // 上下行
176   - map.put("upDown", upDown);
177   - list.add(map);
178   - }
179   - } catch (Exception e) {
180   - e.printStackTrace();
181   - } finally {
182   - DBUtils_MS.close(rs, ps, conn);
183   - }
184   - return list;
185   - }
186   -
187   - /**
188   - * 王通 2016/6/29 9:23:24 获取车辆线路上下行
189   - *
190   - * @return -1无效 0上行 1下行
191   - */
192   - public static byte getUpOrDown(long serviceState) {
193   - /*if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000
194   - || (serviceState & 0x01000000) == 0x01000000 || (serviceState & 0x08000000) == 0x08000000)
195   - return -1;*/
196   - return (byte) (((serviceState & 0x10000000) == 0x10000000) ? 1 : 0);
197   - }
198   -
199   - /**
200   - * 获取运营状态
201   - *
202   - * @return -1无效 0运营 1未运营
203   - */
204   - public static byte getService(long serviceState) {
205   - /*if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000)
206   - return -1;*/
207   - return (byte) (((serviceState & 0x02000000) == 0x02000000) ? 1 : 0);
208   - }
209   -
210   - private static DateTimeFormatter fmtyyyy = DateTimeFormat.forPattern("yyyy");
211   - @Override
212   - public Map<String, Object> history(String[] nbbmArray, Long st, Long et) {
213   - Map<String, Object> rsMap = new HashMap<>();
214   - List<Map<String, Object>> list = new ArrayList<>();
215   - rsMap.put("list", list);
216   - if (et - st > GPS_RANGE)
217   - return rsMap;
218   -
219   - st = st * 1000;
220   - et = et * 1000;
221   - // day_of_year 分区字段
222   - Calendar sCal = Calendar.getInstance();
223   - sCal.setTime(new Date(st));
224   - int sDayOfYear = sCal.get(Calendar.DAY_OF_YEAR);
225   - Calendar eCal = Calendar.getInstance();
226   - eCal.setTime(new Date(et));
227   - int eDayOfYear = eCal.get(Calendar.DAY_OF_YEAR);
228   -
229   - String nbbm = nbbmArray[0];
230   -
231   - List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);
232   -
233   - //按年分表
234   - String tableName = "bsth_c_gps_info_" + fmtyyyy.print(st);
235   -
236   - StringBuilder sql = new StringBuilder("");
237   - long t1,t2;
238   - DeviceChange dc;
239   - for(int i = 0,len=dcs.size(); i < len; i++){
240   - t1 = st;
241   - t2 = et;
242   - dc = dcs.get(i);
243   - if(dc.getSt() > st)
244   - t1 = dc.getSt();
245   - if(dc.getEt() < et && dc.getEt()!=0)
246   - t2 = dc.getEt();
247   -
248   - sql.append("select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,STOP_NO,DIRECTION,LINE_ID,SPEED_GPS,SECTION_CODE from "+tableName+" where days_year in ("+sDayOfYear+","+eDayOfYear+") " +
249   - " and device_id='"+dc.getDevice()+"' and ts >= "+t1+" and ts <= "+t2+" ");
250   -
251   - if(i == len - 1)
252   - sql.append(" ORDER BY device_id,ts,stop_no");
253   - else
254   - sql.append(" UNION ");
255   - }
256   -
257   - logger.info("轨迹回放 nbbm: " + nbbm + " -st: " + st + " -et: " + et + " -sql: " + sql.toString());
258   -
259   - // 查询到离站数据
260   - Map<String, ArrivalEntity> arrivalMap = findArrivalByTs(st, et, dcs);
261   -
262   - //查询GPS数据
263   - JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
264   - List<Map<String, Object>> dataList = jdbcTemplate_ms.queryForList(sql.toString());
265   -
266   - Float lon, lat;
267   - Location bdLoc, gdLoc;
268   - int inOutStop;
269   - long serviceState;
270   - ArrivalEntity arrival;
271   - Set<Integer> lineSet=new HashSet<Integer>();
272   - List<Map<String,Object>> lineSwitch=new ArrayList<>();
273   -
274   - List<Map<String, Object>> gpsNotValidList=new ArrayList<>();
275   - List<Map<String, Object>> gpsEqualsZeroList=new ArrayList<>();
276   - Map<String, Object> map = null;
277   - int oldLineId = -1, oldGpsValid = -1, oldLonlat = -1;
278   -
279   - // 默认加入一个线路切换信息
280   - Map<String, Object> fls = new HashMap<String, Object>();
281   - fls.put("abnormalType", "normal");
282   - fls.put("st", "-1");
283   - lineSwitch.add(fls);
284   -
285   - // 默认加入一个GPS无效异常信息
286   - Map<String, Object> fgv = new HashMap<String, Object>();
287   - fgv.put("abnormalType", "normal");
288   - fgv.put("st", "-1");
289   - gpsNotValidList.add(fgv);
290   -
291   - // 默认加入一个经纬度为零异常信息
292   - Map<String, Object> fgez = new HashMap<String, Object>();
293   - fgez.put("abnormalType", "normal");
294   - fgez.put("st", "-1");
295   - gpsEqualsZeroList.add(fgez);
296   -
297   - Map<String, Integer> lineCode2IdMap = BasicData.lineId2CodeMap.inverse();
298   - for(Map<String, Object> rs : dataList) {
299   - Object lineCode = rs.get("LINE_ID");
300   - // 线路ID发生变化时补全线路切换信息 并新加入一个
301   - if (oldLineId != (Integer)lineCode) {
302   - String lineName = BasicData.lineCode2NameMap.get(lineCode.toString());
303   - Integer lineId = lineCode2IdMap.get(lineCode.toString());
304   - lineSwitch.get(lineSwitch.size() - 1).put("line2", lineName);
305   - lineSwitch.get(lineSwitch.size() - 1).put("et", rs.get("TS"));
306   -
307   - Map<String, Object> ls = new HashMap<String, Object>();
308   - ls.put("abnormalType", "lineSwitch");
309   - ls.put("line1", lineName);
310   - lineSwitch.add(ls);
311   -
312   - lineSet.add((Integer)lineId);
313   - oldLineId = (Integer)lineId;
314   - }
315   - serviceState = map_get_long(rs, "SERVICE_STATE");
316   - // GPS状态发生变化时补全信息 并新加入一个
317   - if (getGpsValid(serviceState) != oldGpsValid) {
318   - gpsNotValidList.get(gpsNotValidList.size() - 1).put("et", rs.get("TS"));
319   -
320   - Map<String, Object> gv = new HashMap<String, Object>();
321   - gv.put("abnormalType", getGpsValid(serviceState) == 0 ? "normal" : "gpsNotValid");
322   - gv.put("st", rs.get("TS"));
323   - gpsNotValidList.add(gv);
324   -
325   - oldGpsValid = getGpsValid(serviceState);
326   - }
327   -
328   - map = new HashMap<>();
329   - lon = map_get_float(rs, "LON");
330   - lat = map_get_float(rs, "LAT");
331   - // 经纬度为零
332   - if ((lon == 0 || lat == 0 ? 1 : 0) != oldLonlat){
333   - gpsEqualsZeroList.get(gpsEqualsZeroList.size() - 1).put("et", rs.get("TS"));
334   -
335   - Map<String, Object> gez = new HashMap<String, Object>();
336   - gez.put("abnormalType", (lon == 0 || lat == 0 ? 1 : 0) == 0 ? "normal" : "gpsZero");
337   - gez.put("st", rs.get("TS"));
338   - gpsEqualsZeroList.add(gez);
339   -
340   - oldLonlat = (lon == 0 || lat == 0 ? 1 : 0);
341   - }
342   -
343   - // 高德坐标
344   - gdLoc = CoordinateConverter.transformFromWGSToGCJ(CoordinateConverter.LocationMake(lon, lat));
345   - map.put("gcj_lon", gdLoc.getLng());
346   - map.put("gcj_lat", gdLoc.getLat());
347   - // 百度坐标
348   - bdLoc = CoordinateConverter.bd_encrypt(gdLoc);
349   - map.put("bd_lon", bdLoc.getLng());
350   - map.put("bd_lat", bdLoc.getLat());
351   - //原始坐标
352   - map.put("lon", lon);
353   - map.put("lat", lat);
354   -
355   - map.put("deviceId", map_get_str(rs, "DEVICE_ID"));
356   - map.put("ts", map_get_long(rs, "TS"));
357   - map.put("timestamp", map_get_long(rs, "TS"));
358   - map.put("stopNo", map_get_str(rs, "STOP_NO"));
359   - map.put("direction", map_get_float(rs,"DIRECTION"));
360   -
361   - map.put("lineId", map_get_str(rs, "LINE_ID"));
362   - map.put("speed", map_get_float(rs,"SPEED_GPS"));
363   -
364   - inOutStop = Integer.parseInt(rs.get("INOUT_STOP").toString());
365   - map.put("inout_stop", inOutStop);
366   -
367   - arrival = arrivalMap.get(map_get_str(rs, "DEVICE_ID") + "_" + map_get_long(rs, "TS"));
368   - if (arrival != null) {
369   - map.put("inout_stop_info", arrival);
370   - map.put("inout_stop", arrival.getInOut());
371   - }
372   -
373   - //map.put("nbbm", nbbm);
374   - map.put("state", getService(serviceState));
375   - // 上下行
376   - map.put("upDown", getUpOrDown(serviceState));
377   - //路段编码
378   - map.put("section_code", map_get_str(rs,"SECTION_CODE"));
379   - list.add(map);
380   - }
381   - if (dataList.size() > 0) {
382   - Map<String, Object> rs = dataList.get(dataList.size() - 1);
383   - gpsNotValidList.get(gpsNotValidList.size() - 1).put("et", rs.get("TS"));
384   - gpsEqualsZeroList.get(gpsEqualsZeroList.size() - 1).put("et", rs.get("TS"));
385   - }
386   -
387   - for (int i = lineSwitch.size() - 1;i > -1;i--) {
388   - Map<String, Object> ls = lineSwitch.get(i);
389   - if ("normal".equals(ls.get("abnormalType")) || ls.get("et") == null) {
390   - lineSwitch.remove(i);
391   - }
392   - }
393   -
394   - for (int i = gpsNotValidList.size() - 1;i > -1;i--) {
395   - Map<String, Object> gnv = gpsNotValidList.get(i);
396   - if ("normal".equals(gnv.get("abnormalType"))) {
397   - gpsNotValidList.remove(i);
398   - }
399   - }
400   -
401   - for (int i = gpsEqualsZeroList.size() - 1;i > -1;i--) {
402   - Map<String, Object> gez = gpsEqualsZeroList.get(i);
403   - if ("normal".equals(gez.get("abnormalType"))) {
404   - gpsEqualsZeroList.remove(i);
405   - }
406   - }
407   -
408   - if (lineSet.size() > 0){
409   - List<Map<String,Object>> vlist=new ArrayList<>();
410   - Map<String, Map<String, Object>> vmap = new HashMap<>();
411   - Map<String, Map<String, String>> lv2station = new HashMap<String, Map<String, String>>();//lv2section = new HashMap<String, Map<String, String>>();
412   - for (Integer lineId : lineSet) {
413   - String lineCode = BasicData.lineId2CodeMap.get(lineId);
414   - List<LineVersions> lvs = lineVersionsRepository.findBylineId(lineId);
415   - for (LineVersions lv : lvs) {
416   - long vst = lv.getStartDate().getTime(), vet = lv.getEndDate().getTime();
417   - if (st >= vst && st <= vet || et >= vst && et <= vet) {
418   - List<LsStationRoute> stations = lsStationRouteRepository.findupdated(lineId, lineId.toString(), lv.getVersions());
419   - //List<LsSectionRoute> sections = lsSectionRouteRepository.findupdated(lineId, lineId.toString(), lv.getVersions());
420   - Map<String, Object> vm = new HashMap<String, Object>();
421   - vm.put("lineId", lineCode);
422   - vm.put("version", lv.getVersions());
423   - vm.put("startTime", vst);
424   - vm.put("endTime", vet);
425   - vm.put("stations", stations);
426   - //vm.put("sections", sections);
427   -
428   - Map<String, String> stationcode2name = new HashMap<String, String>();//sectioncode2name = new HashMap<String, String>();
429   - for (LsStationRoute lsr : stations) {
430   - stationcode2name.put(lsr.getStationCode(), lsr.getStationName());
431   - }
432   - //for (LsSectionRoute lsr : sections) {
433   - // sectioncode2name.put(lsr.getSectionCode(), lsr.getSection().getSectionName());
434   - //}
435   - lv2station.put(lineCode + "_" + lv.getVersions(), stationcode2name);
436   - // 路段因为可能漂到其它线路路段 因此需要使用最新的全量路段
437   - //lv2section.put(lineId + "_" + lv.getVersions(), sectioncode2name);
438   -
439   - vlist.add(vm);
440   - vmap.put(lineCode + "_" + lv.getVersions(), vm);
441   - }
442   - }
443   - }
444   - rsMap.put("lineVerson",vlist);
445   -
446   - for (Map<String, Object> gps : list) {
447   - long ts = (long)gps.get("timestamp");
448   - for (Map<String, Object> vm : vlist) {
449   - long vst = (long)vm.get("startTime"), vet = (long)vm.get("endTime");
450   - if (gps.get("lineId").equals(vm.get("lineId")) && ts >= vst && ts <= vet) {
451   - gps.put("version", vm.get("version"));
452   - String key = vm.get("lineId") + "_" + vm.get("version");
453   - /*if (StringUtils.isEmpty(sectionCode)) {
454   - gps.put("section_code", "-00404");
455   - gps.put("section_name", "未知路段");
456   - }
457   - gps.put("section_name", lv2section.get(key).get(sectionCode));*/
458   - ArrivalEntity ae = (ArrivalEntity)gps.get("inout_stop_info");
459   - if (ae != null) {
460   - ae.setStopName(lv2station.get(key).get(ae.getStopNo()));
461   - if (StringUtils.isEmpty(lv2station.get(key).get(ae.getStopNo()))) {
462   - ae.setStopName(BasicData.stationCode2NameMap.get(ae.getStopNo()));
463   - }
464   - }
465   - }
466   - }
467   - }
468   - }
469   - // 按时间排序
470   - Collections.sort(list, new Comparator<Map<String, Object>>() {
471   -
472   - @Override
473   - public int compare(Map<String, Object> o1, Map<String, Object> o2) {
474   - return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));
475   - }
476   - });
477   -
478   - rsMap.put("list", list);
479   - rsMap.put("dcs", dcs);
480   - rsMap.put("gpsNotValid",gpsNotValidList);
481   - rsMap.put("lineSwitch",lineSwitch);
482   - rsMap.put("lonlatZero",gpsEqualsZeroList);
483   - return rsMap;
484   - }
485   -
486   - private String map_get_str(Map<String, Object> map, String key){
487   - return map.containsKey(key)?map.get(key).toString():"";
488   - }
489   -
490   - private Long map_get_long(Map<String, Object> map, String key){
491   - return map.containsKey(key)?Long.parseLong(map.get(key).toString()):-1;
492   - }
493   -
494   - private Float map_get_float(Map<String, Object> map, String key){
495   - return map.containsKey(key)?Float.parseFloat(map.get(key).toString()):-1;
496   - }
497   -
498   - private List<DeviceChange> findDeviceChangeLogs(String nbbm, long et, long st){
499   - List<DeviceChange> dcs = null;
500   - List<DeviceChange> rs = new ArrayList<>();
501   - try{
502   -
503   - //JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
504   - dcs = jdbcTemplate.query("select cl_zbh as nbbm,new_device_no as device,old_device_no as old_device,UNIX_TIMESTAMP(qyrq) * 1000 as st from bsth_c_car_device where is_cancel=0 and cl_zbh='"+nbbm+"' order by qyrq"
505   - , BeanPropertyRowMapper.newInstance(DeviceChange.class));
506   -
507   -
508   - //生成一条初始记录
509   - if(dcs.size() > 0){
510   - DeviceChange first = dcs.get(0);
511   -
512   - DeviceChange initDv = new DeviceChange();
513   - initDv.setDevice(first.getOldDevice());
514   - if(StringUtils.isNotEmpty(initDv.getDevice())){
515   - initDv.setNbbm(first.getNbbm());
516   - initDv.setSt(0);
517   - initDv.setEt(first.getSt());
518   - dcs.add(0, initDv);
519   - }
520   - }
521   - for(int i = 0,len=dcs.size(); i < len - 1; i++){
522   - dcs.get(i).setEt(dcs.get(i + 1).getSt());
523   - }
524   -
525   - for(DeviceChange dc : dcs){
526   - if(dc.getEt() < st && dc.getEt() != 0)
527   - continue;
528   - if(dc.getSt() > et)
529   - continue;
530   -
531   - rs.add(dc);
532   - }
533   -
534   - //没有设备变更记录,则参考车辆信息上的设备号
535   - if(null == rs || rs.size() == 0){
536   - DeviceChange dc = new DeviceChange();
537   - dc.setNbbm(nbbm);
538   - dc.setDevice(BasicData.deviceId2NbbmMap.inverse().get(nbbm));
539   - dc.setSt(st);
540   - dc.setEt(et);
541   - dc.setType(1);
542   -
543   - rs.add(dc);
544   - }
545   - }catch (Exception e){
546   - logger.error("", e);
547   - }
548   - return rs;
549   - }
550   -
551   - public static byte getGpsValid(long serviceState) {
552   - return (byte)(((serviceState & 0x80000000) == 0x80000000) ? 1 : 0);
553   - }
554   -
555   - public static void main(String[] args){
556   - System.out.println(getGpsValid(-2147483648));
557   - }
558   -
559   - public Map<String, ArrivalEntity> findArrivalByTs(Long st, Long et, List<DeviceChange> dcs) {
560   - Map<String, ArrivalEntity> map = new HashMap<>();
561   -
562   - // weeks_year 分区字段
563   - Calendar sCal = Calendar.getInstance();
564   - sCal.setTime(new Date(st));
565   - int sWeekOfYear = sCal.get(Calendar.WEEK_OF_YEAR);
566   - Calendar eCal = Calendar.getInstance();
567   - eCal.setTime(new Date(et));
568   - int eWeekOfYear = eCal.get(Calendar.WEEK_OF_YEAR);
569   -
570   - //按年分表
571   - String tableName = "bsth_c_arrival_info_" + fmtyyyy.print(st);
572   -
573   - StringBuilder sql = new StringBuilder("");
574   - long t1,t2;
575   - DeviceChange dc;
576   - for(int i = 0,len=dcs.size(); i < len; i++){
577   - t1 = st;
578   - t2 = et;
579   - dc = dcs.get(i);
580   - if(dc.getSt() > st)
581   - t1 = dc.getSt();
582   - if(dc.getEt() < et && dc.getEt() != 0)
583   - t2 = dc.getEt();
584   -
585   - sql.append("SELECT DEVICE_ID,LINE_ID as LINE_CODE,STOP_NO,TS,UP_DOWN,IN_OUT,WEEKS_YEAR,CREATE_DATE FROM " + tableName +
586   - " where weeks_year in ("+sWeekOfYear+", "+eWeekOfYear+") and device_id='"+dc.getDevice()+"' and ts > "+t1+" and ts < " + t2);
587   -
588   - if(i == len - 1)
589   - sql.append(" ORDER BY device_id,ts,stop_no ");
590   - else
591   - sql.append(" UNION ");
592   - }
593   -
594   - logger.info("arrivl sql : " + sql.toString());
595   - JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
596   - List<ArrivalEntity> list = jdbcTemplate_ms.query(sql.toString(), BeanPropertyRowMapper.newInstance(ArrivalEntity.class));
597   -
598   - String stationName, prefix;
599   - for(ArrivalEntity arr : list){
600   - prefix = arr.getLineCode() + "_" + arr.getUpDown() + "_";
601   - stationName = BasicData.getStationNameByCode(arr.getStopNo(), prefix);
602   -
603   - arr.setStopName(stationName);
604   -
605   - // 反转进出状态
606   - map.put(arr.getDeviceId() + "_" + arr.getTs(), arr);
607   - }
608   - return map;
609   - }
610   -
611   -
612   - @Autowired
613   - StationRepository stationRepository;
614   -
615   - @Autowired
616   - CarParkRepository carParkRepository;
617   -
618   - @Override
619   - public Map<String, Object> findBuffAeraByCode(String lineCode, String code, String type) {
620   - Object[][] obj = null;
621   - if (type.equals("station"))
622   - obj = stationRepository.findBufferArea(lineCode, code);
623   - else if (type.equals("park"))
624   - obj = carParkRepository.findBufferArea(code);
625   -
626   - Map<String, Object> rs = new HashMap<>();
627   -
628   - Object[] subObj = obj[0];
629   - if (subObj != null && subObj.length == 6) {
630   - rs.put("polygon", subObj[0]);
631   - rs.put("type", subObj[1]);
632   - rs.put("cPoint", subObj[2]);
633   - rs.put("radius", subObj[3]);
634   - rs.put("code", subObj[4]);
635   - rs.put("text", subObj[5]);
636   - }
637   -
638   - return rs;
639   - }
640   -
641   - @Override
642   - public Map<String, Object> search(Map<String, Object> map, int page, int size, String order, String direction) {
643   - Map<String, Object> rsMap = new HashMap<>();
644   - try {
645   - //全量
646   - List<GpsEntity> list = new ArrayList<>(gpsRealData.all());
647   - //过滤后的
648   - List<GpsEntity> rs = new ArrayList<>();
649   - Field[] fields = GpsEntity.class.getDeclaredFields();
650   - //参与过滤的字段
651   - List<Field> fs = new ArrayList<>();
652   - for (Field f : fields) {
653   - f.setAccessible(true);
654   - if (map.containsKey(f.getName()))
655   - fs.add(f);
656   - }
657   - //过滤数据
658   - for (GpsEntity gps : list) {
659   - if (fieldEquals(fs, gps, map))
660   - rs.add(gps);
661   - }
662   -
663   - //时间戳排序
664   - Collections.sort(rs, new Comparator<GpsEntity>() {
665   - @Override
666   - public int compare(GpsEntity o1, GpsEntity o2) {
667   - return (int)(o2.getTimestamp().longValue() - o1.getTimestamp().longValue());
668   - }
669   - });
670   -
671   - //分页
672   - int count = rs.size(), s = page * size, e = s + size;
673   - if (e > count)
674   - e = count;
675   -
676   - rsMap.put("list", rs.subList(s, e));
677   - rsMap.put("totalPages", count % size == 0 ? count / size - 1 : count / size);
678   - rsMap.put("page", page);
679   - rsMap.put("status", ResponseCode.SUCCESS);
680   - } catch (Exception e) {
681   - logger.error("", e);
682   - rsMap.put("status", ResponseCode.ERROR);
683   - }
684   - return rsMap;
685   - }
686   -
687   - @Override
688   - public Map<String, Object> removeRealGps(String device) {
689   - Map<String, Object> rs = new HashMap<>();
690   - try {
691   -
692   - gpsRealData.remove(device);
693   - GpsCacheData.remove(BasicData.deviceId2NbbmMap.get(device));
694   - rs.put("status", ResponseCode.SUCCESS);
695   - } catch (Exception e) {
696   - rs.put("status", ResponseCode.ERROR);
697   - }
698   - return rs;
699   - }
700   -
701   - @Override
702   - public Map<String, Object> findRoadSpeed(String lineCode) {
703   - Map<String, Object> rs = new HashMap<>();
704   -
705   - try {
706   - 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)";
707   - List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, lineCode);
708   - rs.put("status", ResponseCode.SUCCESS);
709   - rs.put("roads", list);
710   - } catch (DataAccessException e) {
711   - logger.error("", e);
712   - rs.put("status", ResponseCode.ERROR);
713   - }
714   - return rs;
715   - }
716   -
717   - /**
718   - * gps补全
719   - *
720   - * @param schId
721   - * @return
722   - */
723   - @Override
724   - public Map<String, Object> gpsCompletion(long schId, int type) {
725   - Map<String, Object> rs = new HashMap<>();
726   -
727   - try {
728   - ScheduleRealInfo sch = dayOfSchedule.get(schId);
729   - if (sch == null) {
730   - rs.put("status", ResponseCode.ERROR);
731   - rs.put("msg", "找不到对应班次!!!");
732   - return rs;
733   - }
734   -
735   - if (sch.isReissue()) {
736   - rs.put("status", ResponseCode.ERROR);
737   - rs.put("msg", "你不能重复这个操作");
738   - return rs;
739   - }
740   -
741   - String sql = "select * from bsth_gps_template where line_id='" + sch.getXlBm() + "' and up_down=" + sch.getXlDir();
742   - List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
743   -
744   - if (list.size() == 0) {
745   - rs.put("status", ResponseCode.ERROR);
746   - rs.put("msg", "缺少模板数据,请联系系统管理员!!");
747   - return rs;
748   - }
749   - //排序
750   - Collections.sort(list, new Comparator<Map<String, Object>>() {
751   - @Override
752   - public int compare(Map<String, Object> o1, Map<String, Object> o2) {
753   - return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));
754   - }
755   - });
756   - Map<String, Object> fs = list.get(0);
757   - //替换设备号和时间
758   - long diff = ((sch.getDfsjT() - Long.parseLong(fs.get("ts").toString())) - 1000 * 70);
759   -
760   - String deviceId = BasicData.deviceId2NbbmMap.inverse().get(sch.getClZbh());
761   - int serviceState;
762   - for (Map<String, Object> map : list) {
763   - map.put("device_id", deviceId);
764   - map.put("ts", Long.parseLong(map.get("ts").toString()) + diff);
765   - if(type==1){
766   - //走补传协议
767   - serviceState = Integer.parseInt(map.get("service_state").toString());
768   - map.put("service_state", serviceState |= 0x00100000);
769   - }
770   - }
771   -
772   - String sqlBefore = "insert into bsth_c_template(", sqlValues = " values(";
773   -
774   - Set<String> ks = fs.keySet();
775   - for (String k : ks) {
776   - sqlBefore += (k + ",");
777   - sqlValues += "?,";
778   - }
779   - sqlBefore = sqlBefore.substring(0, sqlBefore.length() - 1) + ", create_ts)";
780   - sqlValues = sqlValues.substring(0, sqlValues.length() - 1) + ", " + System.currentTimeMillis() + ")";
781   - sql = sqlBefore + " " + sqlValues;
782   -
783   - Connection conn = DBUtils_MS.getConnection();
784   - conn.setAutoCommit(false);
785   - ps = conn.prepareStatement(sql);
786   - int fsize = ks.size();
787   - List<Object> vs;
788   - for (Map<String, Object> map : list) {
789   - vs = new ArrayList<>(map.values());
790   - for (int i = 0; i < fsize; i++) {
791   - ps.setObject(i + 1, vs.get(i));
792   - }
793   - ps.addBatch();
794   - }
795   - ps.executeBatch();
796   - conn.commit();
797   -
798   - rs.put("status", ResponseCode.SUCCESS);
799   -
800   - //标记班次
801   - sch.setReissue(true);
802   - scheduleRealInfoRepository.save(sch);
803   -
804   - rs.put("status", ResponseCode.SUCCESS);
805   - } catch (Exception e) {
806   - logger.error("", e);
807   - rs.put("status", ResponseCode.ERROR);
808   - }
809   - return rs;
810   - }
811   -
812   - @Override
813   - public Map<String, Object> history_v2(String nbbm, long st, long et) {
814   - Map<String, Object> rs = new HashMap<>();
815   -
816   - try {
817   - //获取历史gps 数据
818   - List<HistoryGps_DTO> list = HistoryGps_DTO.craete((List<Map<String, Object>>) history(new String[]{nbbm}, st, et).get("list"));
819   - if (list != null && list.size() > 0) {
820   - //获取路段信息
821   - 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)";
822   - List<Road_DTO> roads = Road_DTO.craete(jdbcTemplate.queryForList(sql, list.get(0).getLineId()));
823   -
824   - //为GPS数据关联路段信息
825   - for (HistoryGps_DTO gps : list) {
826   - matchRoadToGps(gps, roads);
827   - }
828   - }
829   -
830   - //超速数据
831   - List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);
832   - //越界数据
833   - List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);
834   - //计算里程
835   - List<HistoryGps_DTO> effList = new ArrayList<>();
836   - for(HistoryGps_DTO gps : list){
837   - if(gps.getLat() != 0 && gps.getLon() != 0)
838   - effList.add(gps);
839   - }
840   - double sum = 0, dist;
841   - for (int i = 0; i < effList.size() - 1; i++) {
842   - dist = GeoUtils.getDistance(effList.get(i).getPoint(), effList.get(i + 1).getPoint());
843   - //点位相同时,dist会NaN
844   - if(String.valueOf(dist).matches("^[0.0-9.0]+$"))
845   - sum += dist;
846   - }
847   -
848   - rs.put("status", ResponseCode.SUCCESS);
849   - rs.put("list", removeDuplicate(effList));
850   - rs.put("speedList", speedList);
851   - rs.put("outboundList", outboundList);
852   - rs.put("sumMileage", new DecimalFormat(".##").format(sum / 1000));
853   - } catch (Exception e) {
854   - logger.error("", e);
855   - rs.put("status", ResponseCode.ERROR);
856   - }
857   - return rs;
858   - }
859   -
860   -
861   - @Override
862   - public Map<String, Object> history_v3(String nbbm, long st, long et) {
863   - Map<String, Object> rs = new HashMap<>();
864   -
865   - try {
866   - //获取历史gps 数据
867   - Map<String, Object> gpsMap = history(new String[]{nbbm}, st, et);
868   - List<HistoryGps_DTOV3> list = HistoryGps_DTOV3.craete((List<Map<String, Object>>) gpsMap.get("list"));
869   - if (list != null && list.size() > 0) {
870   - //关联路段名称
871   - Map<String, String> sectionCode2Name = GeoCacheData.sectionCode2NameMap();
872   - for(HistoryGps_DTOV3 gps : list){
873   - if(StringUtils.isNotEmpty(gps.getSection_code()))
874   - gps.setSection_name(sectionCode2Name.get(gps.getSection_code()));
875   - else{
876   - gps.setSection_code("-00404");
877   - gps.setSection_name("未知路段");
878   - }
879   - }
880   - }
881   -
882   - //超速数据
883   - List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);
884   -
885   - //越界数据
886   - List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);
887   -
888   - //计算里程
889   - List<HistoryGps_DTOV3> effList = new ArrayList<>();
890   - for(HistoryGps_DTOV3 gps : list){
891   - if(gps.getLat() != 0 && gps.getLon() != 0 && !"0".equals(gps.getLineId()))
892   - effList.add(gps);
893   - }
894   - double sum = 0, dist;
895   - for (int i = 0; i < effList.size() - 1; i++) {
896   - dist = GeoUtils.getDistance(effList.get(i).getPoint(), effList.get(i + 1).getPoint());
897   - //点位相同时,dist会NaN
898   - if(String.valueOf(dist).matches("^[0.0-9.0]+$")){
899   - if(dist > 0.8)
900   - sum += dist;
901   - }
902   - }
903   -
904   - rs.put("status", ResponseCode.SUCCESS);
905   - rs.put("list", removeDuplicateV3(effList));
906   - rs.put("speedList", speedList);
907   - rs.put("outboundList", outboundList);
908   - rs.put("sumMileage", new DecimalFormat(".##").format(sum / 1000));
909   - rs.put("dcs", gpsMap.get("dcs"));
910   - rs.put("lineVerson",gpsMap.get("lineVerson"));
911   - rs.put("gpsInvalid",gpsMap.get("gpsNotValid"));
912   - rs.put("gpslineSwitch",gpsMap.get("lineSwitch"));
913   - rs.put("gpslonlatex",gpsMap.get("lonlatZero"));
914   - } catch (Exception e) {
915   - logger.error("", e);
916   - rs.put("status", ResponseCode.ERROR);
917   - rs.put("msg", e.getMessage());
918   - }
919   - return rs;
920   - }
921   -
922   - @Override
923   - public void trailExcel(String nbbm, long st, long et, HttpServletResponse resp) {
924   - //获取历史gps 数据
925   - List<HistoryGps_DTOV3> list = HistoryGps_DTOV3.craete((List<Map<String, Object>>) history(new String[]{nbbm}, st, et).get("list"));
926   - if (list != null && list.size() > 0) {
927   - //关联路段名称
928   - Map<String, String> sectionCode2Name = GeoCacheData.sectionCode2NameMap();
929   - for(HistoryGps_DTOV3 gps : list){
930   - if(StringUtils.isNotEmpty(gps.getSection_code()))
931   - gps.setSection_name(sectionCode2Name.get(gps.getSection_code()));
932   - else{
933   - gps.setSection_code("-00404");
934   - gps.setSection_name("未知路段");
935   - }
936   - }
937   - }
938   -
939   - //创建excel工作簿
940   - Workbook wb = new HSSFWorkbook();
941   - Sheet sheet = wb.createSheet("行车轨迹");
942   - //表头
943   - Row row = sheet.createRow(0);
944   - row.setHeight((short) (1.5 * 256));
945   - row.createCell(0).setCellValue("序号");
946   - row.createCell(1).setCellValue("车辆");
947   - row.createCell(2).setCellValue("牌照号");
948   - row.createCell(3).setCellValue("所在道路");
949   - row.createCell(4).setCellValue("经度");
950   - row.createCell(5).setCellValue("纬度");
951   - row.createCell(6).setCellValue("时间");
952   - row.createCell(7).setCellValue("速度");
953   - //数据
954   - DateTimeFormatter fmtHHmmss = DateTimeFormat.forPattern("HH:mm.ss"),
955   - fmt = DateTimeFormat.forPattern("yyyyMMddHHmm");
956   - HistoryGps_DTOV3 gps;
957   - for(int i = 0; i < list.size(); i ++){
958   - gps = list.get(i);
959   - row = sheet.createRow(i + 1);
960   - row.createCell(0).setCellValue(i + 1);
961   - row.createCell(1).setCellValue(nbbm);
962   - row.createCell(2).setCellValue(BasicData.nbbmCompanyPlateMap.get(nbbm));
963   - row.createCell(3).setCellValue(gps.getSection_name());
964   - row.createCell(4).setCellValue(gps.getLon());
965   - row.createCell(5).setCellValue(gps.getLat());
966   - row.createCell(6).setCellValue(fmtHHmmss.print(gps.getTimestamp()));
967   - row.createCell(7).setCellValue(gps.getSpeed());
968   - }
969   -
970   - st = st * 1000;
971   - et = et * 1000;
972   - String filename = nbbm + "轨迹数据" + fmt.print(st) + "至" + fmt.print(et) + ".xls";
973   - try {
974   - resp.setContentType("application/x-msdownload");
975   - resp.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
976   -
977   - OutputStream out=resp.getOutputStream();
978   - wb.write(out);
979   - out.flush();
980   - out.close();
981   - } catch (UnsupportedEncodingException e) {
982   - logger.error("", e);
983   - } catch (IOException e) {
984   - logger.error("", e);
985   - }
986   - }
987   -
988   - @Override
989   - public void abnormalExcel(String nbbm, long st, long et, HttpServletResponse resp) {
990   - //超速数据
991   - List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);
992   - //越界数据
993   - List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);
994   -
995   - //创建excel工作簿
996   - Workbook wb = new HSSFWorkbook();
997   -
998   - DateTimeFormatter fmtHHmmss = DateTimeFormat.forPattern("HH:mm.ss"),
999   - fmt = DateTimeFormat.forPattern("yyyyMMddHHmm");
1000   - if(speedList.size() > 0){
1001   - Sheet sheet = wb.createSheet("超速");
1002   - //表头
1003   - Row row = sheet.createRow(0);
1004   - row.setHeight((short) (1.5 * 256));
1005   - row.createCell(0).setCellValue("异常信息");
1006   - row.createCell(1).setCellValue("最大速度");
1007   - row.createCell(2).setCellValue("开始时间");
1008   - row.createCell(3).setCellValue("结束时间");
1009   - row.createCell(4).setCellValue("持续(秒)");
1010   - row.createCell(5).setCellValue("所在路段");
1011   -
1012   - GpsSpeed_DTO speed;
1013   - for(int i = 0; i < speedList.size(); i++){
1014   - speed = speedList.get(i);
1015   - row = sheet.createRow(i + 1);
1016   - row.createCell(0).setCellValue("超速");
1017   - row.createCell(1).setCellValue(speed.getSpeed());
1018   - row.createCell(2).setCellValue(fmtHHmmss.print(speed.getSt()));
1019   - row.createCell(3).setCellValue(fmtHHmmss.print(speed.getEt()));
1020   - if(speed.getEt() != 0)
1021   - row.createCell(4).setCellValue((speed.getEt() - speed.getSt()) / 1000);
1022   - row.createCell(5).setCellValue("");
1023   - }
1024   - }
1025   -
1026   - if(outboundList.size() > 0){
1027   - Sheet sheet = wb.createSheet("越界");
1028   - //表头
1029   - Row row = sheet.createRow(0);
1030   - row.setHeight((short) (1.5 * 256));
1031   - row.createCell(0).setCellValue("异常信息");
1032   - row.createCell(1).setCellValue("开始时间");
1033   - row.createCell(2).setCellValue("结束时间");
1034   - row.createCell(3).setCellValue("持续(秒)");
1035   - row.createCell(4).setCellValue("所在路段");
1036   - row.createCell(5).setCellValue("路径");
1037   -
1038   - GpsOutbound_DTO outbound;
1039   - //设置路径单元格 水平对齐 填充
1040   - CellStyle cs = wb.createCellStyle();
1041   - cs.setAlignment(HSSFCellStyle.ALIGN_FILL);
1042   - for(int i = 0; i < outboundList.size(); i++){
1043   - outbound = outboundList.get(i);
1044   - row = sheet.createRow(i + 1);
1045   - row.createCell(0).setCellValue("超速");
1046   - row.createCell(1).setCellValue(fmtHHmmss.print(outbound.getSt()));
1047   - row.createCell(2).setCellValue(fmtHHmmss.print(outbound.getEt()));
1048   - if(outbound.getEt() != 0)
1049   - row.createCell(3).setCellValue((outbound.getEt() - outbound.getSt()) / 1000);
1050   - row.createCell(4).setCellValue("");
1051   - row.createCell(5).setCellValue(outbound.getLocations());
1052   -
1053   - row.getCell(5).setCellStyle(cs);
1054   - }
1055   - }
1056   -
1057   - st = st * 1000;
1058   - et = et * 1000;
1059   - String filename = nbbm + "异常信息" + fmt.print(st) + "至" + fmt.print(et) + ".xls";
1060   - try {
1061   - resp.setContentType("application/x-msdownload");
1062   - resp.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
1063   -
1064   - OutputStream out=resp.getOutputStream();
1065   - wb.write(out);
1066   - out.flush();
1067   - out.close();
1068   - } catch (UnsupportedEncodingException e) {
1069   - logger.error("", e);
1070   - } catch (IOException e) {
1071   - logger.error("", e);
1072   - }
1073   - }
1074   -
1075   - @Override
1076   - public void arrivalExcel(String nbbm, long st, long et, HttpServletResponse resp) {
1077   -
1078   - }
1079   -
1080   - @Override
1081   - public List<GpsSpeed_DTO> speeds(String nbbm, long st, long et) {
1082   - st = st * 1000;
1083   - et = et * 1000;
1084   - //按周分区
1085   - Calendar sCal = Calendar.getInstance();
1086   - sCal.setTime(new Date(st));
1087   - int sWeekYear = sCal.get(Calendar.WEEK_OF_YEAR);
1088   - Calendar eCal = Calendar.getInstance();
1089   - eCal.setTime(new Date(et));
1090   - int eWeekYear = eCal.get(Calendar.WEEK_OF_YEAR);
1091   -
1092   - //按年分表
1093   - String tableName = "bsth_c_speeding_" + fmtyyyy.print(st);
1094   -
1095   - List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);
1096   - StringBuilder sql = new StringBuilder("");
1097   - long t1,t2;
1098   - DeviceChange dc;
1099   - for(int i = 0,len=dcs.size(); i < len; i++){
1100   - t1 = st;
1101   - t2 = et;
1102   - dc = dcs.get(i);
1103   - if(dc.getSt() > st)
1104   - t1 = dc.getSt();
1105   - if(dc.getEt() < et && dc.getEt()!=0)
1106   - t2 = dc.getEt();
1107   -
1108   - sql.append(" select vehicle, line, up_down, lon, lat, speed,timestamp from "+tableName+" where " +
1109   - " weeks_year in ("+sWeekYear+", "+eWeekYear+") and vehicle='"+dc.getDevice()+"' and timestamp>="+t1+" and timestamp<= " + t2);
1110   -
1111   - if(i == len - 1)
1112   - sql.append(" ORDER BY vehicle,timestamp");
1113   - else
1114   - sql.append(" UNION ");
1115   - }
1116   -
1117   - logger.info("speed sql : " + sql.toString());
1118   - return GpsSpeed_DTO.create(new JdbcTemplate(DBUtils_MS.getDataSource()).queryForList(sql.toString()));
1119   - }
1120   -
1121   - @Override
1122   - public List<GpsOutbound_DTO> outbounds(String nbbm, long st, long et) {
1123   - st = st * 1000;
1124   - et = et * 1000;
1125   - //按周分区
1126   - Calendar sCal = Calendar.getInstance();
1127   - sCal.setTime(new Date(st));
1128   - int sWeekYear = sCal.get(Calendar.WEEK_OF_YEAR);
1129   - Calendar eCal = Calendar.getInstance();
1130   - eCal.setTime(new Date(et));
1131   - int eWeekYear = eCal.get(Calendar.WEEK_OF_YEAR);
1132   -
1133   - //按年分表
1134   - String tableName = "bsth_c_outbound_" + fmtyyyy.print(st);
1135   -
1136   - List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);
1137   - StringBuilder sql = new StringBuilder("");
1138   - long t1,t2;
1139   - DeviceChange dc;
1140   - for(int i = 0,len=dcs.size(); i < len; i++){
1141   - t1 = st;
1142   - t2 = et;
1143   - dc = dcs.get(i);
1144   - if(dc.getSt() > st)
1145   - t1 = dc.getSt();
1146   - if(dc.getEt() < et && dc.getEt()!=0)
1147   - t2 = dc.getEt();
1148   -
1149   - sql.append("select vehicle,line,up_down,lon,lat,timestamp from "+tableName+" where " +
1150   - " weeks_year in ("+sWeekYear+", "+eWeekYear+") and vehicle='"+dc.getDevice()+"' and timestamp>="+t1+" and timestamp<=" + t2);
1151   -
1152   - if(i == len - 1)
1153   - sql.append(" ORDER BY vehicle,timestamp");
1154   - else
1155   - sql.append(" UNION ");
1156   - }
1157   -
1158   - logger.info("outbounds sql : " + sql.toString());
1159   - return GpsOutbound_DTO.create(new JdbcTemplate(DBUtils_MS.getDataSource()).queryForList(sql.toString()));
1160   - }
1161   -
1162   - @Override
1163   - public Map<String, Object> safeDrivList(Map<String, Object> map, int page, int size, String order, String direction) {
1164   - Map<String, Object> rsMap = new HashMap<>();
1165   - try {
1166   - //全量
1167   - List<SafeDriv> list = new ArrayList<>(SafeDrivCenter.findAll());
1168   - //过滤后的
1169   - List<SafeDriv> rs = new ArrayList<>();
1170   - Field[] fields = SafeDriv.class.getDeclaredFields();
1171   - //参与过滤的字段
1172   - List<Field> fs = new ArrayList<>();
1173   - for (Field f : fields) {
1174   - f.setAccessible(true);
1175   - if (map.containsKey(f.getName()))
1176   - fs.add(f);
1177   - }
1178   - //过滤数据
1179   - for (SafeDriv sd : list) {
1180   - if (isSpecialLines(sd, map) && fieldEqualstow(fs, sd, map))
1181   - rs.add(sd);
1182   - }
1183   -
1184   - //时间戳排序
1185   - Collections.sort(rs, new Comparator<SafeDriv>() {
1186   - @Override
1187   - public int compare(SafeDriv o1, SafeDriv o2) {
1188   - return (int)(o2.getTs().longValue() - o1.getTs().longValue());
1189   - }
1190   - });
1191   -
1192   - //分页
1193   - int count = rs.size(), s = page * size, e = s + size;
1194   - if (e > count)
1195   - e = count;
1196   -
1197   - rsMap.put("list", rs.subList(s, e));
1198   - rsMap.put("totalPages", count % size == 0 ? count / size - 1 : count / size);
1199   - rsMap.put("page", page);
1200   - rsMap.put("status", ResponseCode.SUCCESS);
1201   - } catch (Exception e) {
1202   - logger.error("", e);
1203   - rsMap.put("status", ResponseCode.ERROR);
1204   - }
1205   - return rsMap;
1206   - }
1207   -
1208   - private void matchRoadToGps(HistoryGps_DTO gps, List<Road_DTO> roads) {
1209   - double min = -1, distance;
1210   - Road_DTO nearRoad = null;
1211   - for (Road_DTO road : roads) {
1212   - distance = GeoUtils.getDistanceFromLine(road.getLineStr(), gps.getPoint());
1213   -
1214   - if (min > distance || min == -1) {
1215   - min = distance;
1216   - nearRoad = road;
1217   - }
1218   - }
1219   -
1220   - gps.setRoad(nearRoad);
1221   - gps.setRoadMinDistance(min);
1222   - }
1223   -
1224   -
1225   - private void matchRoadToGps(HistoryGps_DTOV3 gps, List<Road_DTO> roads) {
1226   - double min = -1, distance;
1227   - Road_DTO nearRoad = null;
1228   - for (Road_DTO road : roads) {
1229   - distance = GeoUtils.getDistanceFromLine(road.getLineStr(), gps.getPoint());
1230   -
1231   - if (min > distance || min == -1) {
1232   - min = distance;
1233   - nearRoad = road;
1234   - }
1235   - }
1236   -
1237   - if(min < 200){
1238   - gps.setSection_code(nearRoad.getROAD_CODE());
1239   - gps.setSection_name(nearRoad.getROAD_NAME());
1240   - }
1241   - else {
1242   - gps.setSection_code("-00404");
1243   - gps.setSection_name("未知路段");
1244   - }
1245   - //gps.setRoad(nearRoad);
1246   - //gps.setRoadMinDistance(min);
1247   - }
1248   -
1249   - /**
1250   - * 去重复
1251   - *
1252   - * @param list
1253   - * @return
1254   - */
1255   - private Set<HistoryGps_DTO> removeDuplicate(List<HistoryGps_DTO> list) {
1256   - Set<HistoryGps_DTO> set = new HashSet<>();
1257   - for (HistoryGps_DTO gps : list) {
1258   - set.add(gps);
1259   - }
1260   - return set;
1261   - }
1262   -
1263   - /**
1264   - * 去重复
1265   - *
1266   - * @param list
1267   - * @return
1268   - */
1269   - private Set<HistoryGps_DTOV3> removeDuplicateV3(List<HistoryGps_DTOV3> list) {
1270   - Set<HistoryGps_DTOV3> set = new HashSet<>();
1271   - for (HistoryGps_DTOV3 gps : list) {
1272   - set.add(gps);
1273   - }
1274   - return set;
1275   - }
1276   -
1277   -
1278   - private void sortGpsList(final Field f, List<GpsEntity> rs) {
1279   - Collections.sort(rs, new Comparator<GpsEntity>() {
1280   -
1281   - @Override
1282   - public int compare(GpsEntity o1, GpsEntity o2) {
1283   - try {
1284   - if (f.get(o1) == f.get(o2))
1285   - return 0;
1286   -
1287   - if (null == f.get(o1))
1288   - return 1;
1289   -
1290   - if (null == f.get(o2))
1291   - return -1;
1292   -
1293   - return f.get(o1).toString().compareTo(f.get(o2).toString());
1294   - } catch (Exception e) {
1295   - logger.error("", e);
1296   - return -1;
1297   - }
1298   - }
1299   - });
1300   - }
1301   -
1302   - /**
1303   - *
1304   - * @param sd
1305   - * @param map
1306   - * @return
1307   - */
1308   - public boolean isSpecialLines(SafeDriv sd, Map<String, Object> map) {
1309   - String lines = (String)map.get("lines");
1310   - if (lines == null) lines = "";
1311   -
1312   - if (Arrays.asList(lines.split(",")).contains(sd.getXlbm())) return true;
1313   - return false;
1314   - }
1315   -
1316   - public boolean fieldEquals(List<Field> fs, Object obj, Map<String, Object> map) {
1317   - try {
1318   - String fv, v;
1319   - for (Field f : fs) {
1320   - if (StringUtils.isEmpty(map.get(f.getName()).toString()))
1321   - continue;
1322   -
1323   - if(f.get(obj) == null)
1324   - return false;
1325   -
1326   - fv = f.get(obj).toString();
1327   - v = map.get(f.getName()).toString();
1328   -
1329   - if(!fv.startsWith(v)/* && !fv.endsWith(v)*/)
1330   - return false;
1331   - }
1332   - } catch (Exception e) {
1333   - logger.error("", e);
1334   - return false;
1335   - }
1336   - return true;
1337   - }
1338   -
1339   - public boolean fieldEqualstow(List<Field> fs, Object obj, Map<String, Object> map) {
1340   - try {
1341   - String fv, v;
1342   - for (Field f : fs) {
1343   - if (StringUtils.isEmpty(map.get(f.getName()).toString()))
1344   - continue;
1345   -
1346   - if(f.get(obj) == null)
1347   - return false;
1348   -
1349   - fv = f.get(obj).toString();
1350   - v = map.get(f.getName()).toString();
1351   - SafeDriv sd = (SafeDriv) obj;
1352   - if(v.equals(sd.getJctype()))
1353   - return true;
1354   - else if(!fv.startsWith(v)/* && !fv.endsWith(v)*/)
1355   - return false;
1356   - }
1357   - } catch (Exception e) {
1358   - logger.error("", e);
1359   - return false;
1360   - }
1361   - return true;
1362   - }
1363   -
1364   -
1365   - @Override
1366   - public List<GpsSpeed> findPosition(String deviceid, String startdate,
1367   - String enddate) throws ParseException{
1368   - SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1369   - Calendar c = Calendar.getInstance();
1370   - Date date = sdf.parse(startdate);
1371   - c.setTime(date);
1372   - int daysYear = c.get(Calendar.DAY_OF_YEAR);//获取当前是今年的第几天。
1373   -
1374   - long startTime = sdf.parse(startdate).getTime();
1375   - long endTime = sdf.parse(enddate).getTime();
1376   -
1377   - String sql = "select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,speed_gps from bsth_c_gps_info where days_year=? and device_id=? and ts >= ? and ts <= ?" +
1378   - " ORDER BY TS ";
1379   - Connection conn = null;
1380   - PreparedStatement ps = null;
1381   - ResultSet rs = null;
1382   - List<GpsSpeed> listResult = new ArrayList<GpsSpeed>();
1383   - GpsSpeed gpsSpeed = null;
1384   - try {
1385   - conn = DBUtils_MS.getConnection();
1386   - ps = conn.prepareStatement(sql);
1387   - ps.setInt(1, daysYear);
1388   - ps.setString(2, deviceid);
1389   - ps.setLong(3,startTime);
1390   - ps.setLong(4,endTime);
1391   - rs = ps.executeQuery();
1392   - Float lon, lat;
1393   - Location location;
1394   - while (rs.next()) {
1395   - gpsSpeed = new GpsSpeed();
1396   - // to 百度坐标
1397   - lon = rs.getFloat("LON");
1398   - lat = rs.getFloat("LAT");
1399   - location = CoordinateConverter.LocationMake(lon, lat);
1400   - location = CoordinateConverter.bd_encrypt(CoordinateConverter.transformFromWGSToGCJ(location));
1401   - gpsSpeed.setVehicle(rs.getString("device_id"));
1402   - gpsSpeed.setLon((float)location.getLng());
1403   - gpsSpeed.setLat((float)location.getLat());
1404   - gpsSpeed.setSpeed(rs.getFloat("speed_gps"));
1405   - gpsSpeed.setTimestamp(rs.getLong("TS"));
1406   - // 上下行
1407   - listResult.add(gpsSpeed);
1408   - }
1409   - } catch (Exception e) {
1410   - e.printStackTrace();
1411   - } finally {
1412   - DBUtils_MS.close(rs, ps, conn);
1413   - }
1414   - return listResult;
1415   -
1416   - }
1417   -
1418   - @Override
1419   - public Map<String, Object> Pagequery(Map<String, Object> map) {
1420   - SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1421   - Integer totalDays = 0;//数据跨越天数
1422   - try {
1423   - totalDays = (int) ((sdf.parse(map.get("endDate").toString()+" 23:59:59").getTime()-sdf.parse(map.get("startDate").toString()+" 00:00:00").getTime()+1)/(3600*24*1000))+1;
1424   - } catch (ParseException e) {
1425   - e.printStackTrace();
1426   - }//总页数
1427   - map.put("totalDays",totalDays);
1428   - List<GpsSpeed> list=findAll(map);
1429   - List<GpsSpeed> listResult = new ArrayList<GpsSpeed>();
1430   - int curPage = 0;//页码
1431   - int pageData = 0;//每页的记录条数
1432   - if(list.size()>1){
1433   - GpsSpeed GpsSpeedNow;//下标为i的车辆行驶记录
1434   - GpsSpeed GpsSpeedLast;//下标为i-1的车辆行驶记录
1435   - GpsSpeed spped = null;//整合后的车辆行驶记录
1436   - String strNow;
1437   - String strLast;
1438   - boolean Flag = false;//判断是否有连续超速记录,默认没有
1439   - for(int i = 1;i<list.size();i++){
1440   - GpsSpeedNow = list.get(i);
1441   - GpsSpeedLast = list.get(i-1);
1442   - strNow = GpsSpeedNow.getVehicle()+GpsSpeedNow.getLine()+GpsSpeedNow.getUp_down();
1443   - strLast = GpsSpeedLast.getVehicle()+GpsSpeedLast.getLine()+GpsSpeedLast.getUp_down();
1444   - if(GpsSpeedNow.getSpeed()>60 && GpsSpeedLast.getSpeed()>60 && strNow.equals(strLast)){//如果两条连续的记录都是超速且属于同一辆车。
1445   - if(Flag==false){//
1446   - spped = new GpsSpeed();
1447   - spped.setLine(GpsSpeedLast.getLine());//设置连续超速记录线路
1448   - spped.setLineName(GpsSpeedLast.getLineName());//设置连续超速记录线路名称
1449   - spped.setVehicle(GpsSpeedLast.getVehicle());//设置连续超速记录的车辆编号
1450   - spped.setUp_down(GpsSpeedLast.getUp_down());//设置上下行
1451   - spped.setLon(GpsSpeedLast.getLon());//设置开始时经度
1452   - spped.setLat(GpsSpeedLast.getLat());//设置开始时纬度
1453   - spped.setTimestamp(GpsSpeedLast.getTimestamp());//设置连续超速记录的开始时间
1454   - spped.setTimestampDate(GpsSpeedLast.getTimestampDate());//设置连续超速记录的开始时间戳
1455   - }
1456   - spped.setEndtimestamp(GpsSpeedNow.getTimestamp());//设置结束时间戳
1457   - spped.setEndtimestampDate(sdf.format(new Date(GpsSpeedNow.getTimestamp())));//设置结束时间
1458   - spped.setEndlon(GpsSpeedNow.getLon());//设置结束时的经度
1459   - spped.setEndlat(GpsSpeedNow.getLat());//设置结束时的纬度
1460   - Flag = true;
1461   - }else{
1462   - if(Flag){//如果上一条记录超速。
1463   - listResult.add(spped);
1464   - Flag = false;
1465   - }
1466   - }
1467   - }
1468   - if(listResult.size()>0){
1469   - Iterator<GpsSpeed> speedIt = listResult.iterator();
1470   - while(speedIt.hasNext()){
1471   - GpsSpeed GpsSpeed = speedIt.next();
1472   - if(GpsSpeed.getEndtimestamp()-GpsSpeed.getTimestamp()<=1000){
1473   - speedIt.remove();
1474   - }
1475   - }
1476   - }
1477   - }
1478   - if(map.get("curPage") == null || map.get("curPage").equals("0")){
1479   - curPage = 0;
1480   - }else{
1481   - curPage = Integer.parseInt((String) map.get("curPage"));
1482   - }
1483   - Integer totalPage = totalDays;
1484   - pageData = listResult.size();//每页的记录条数就是当前页查出的全部数据。
1485   - Map<String,Object> paramMap = new HashMap<String,Object>();
1486   - paramMap.put("totalPage", totalPage);
1487   - paramMap.put("page", curPage);
1488   - paramMap.put("pageData", pageData);
1489   - paramMap.put("list", listResult);
1490   - return paramMap;
1491   - }
1492   -
1493   - @Override
1494   - public Map<String, Object> allCarsByLine(String lineCode) {
1495   - Map<String, Object> map = new HashMap();
1496   - try{
1497   - List<Map<String, Object>> list = new ArrayList<>();
1498   - Map<String, Object> item;
1499   - GpsEntity gps;
1500   - //当天线路下营运的车辆
1501   - Set<String> cars = dayOfSchedule.findCarByLineCode(lineCode);
1502   - ScheduleRealInfo sch;
1503   - String device;
1504   -
1505   - Map<String, Integer> allDevices = new HashMap<>();
1506   - String execStr = "";
1507   - D80 d80;
1508   - for(String nbbm : cars){
1509   - item = new HashMap<>();
1510   - device = BasicData.deviceId2NbbmMap.inverse().get(nbbm);
1511   - allDevices.put(device, 1);
1512   - item.put("nbbm", nbbm);
1513   - item.put("device", device);
1514   -
1515   - sch = dayOfSchedule.executeCurr(nbbm);
1516   - if(null != sch){
1517   - execStr = (sch.getXlDir().equals("0")?"上行":"下行") + "("+sch.getDfsj()+")";
1518   - if(!sch.getXlBm().equals(lineCode))
1519   - execStr = sch.getXlName()+execStr;
1520   - else
1521   - item.put("schId", sch.getId());
1522   - item.put("exec", execStr);
1523   - }
1524   -
1525   - gps = gpsRealData.get(device);
1526   - if(null != gps){
1527   - item.put("loc", gps.getStationName());
1528   - item.put("lineCodeReal", gps.getLineId());
1529   - item.put("status", gps.isOffline()?"离线":"在线");
1530   - item.put("gpsTs", gps.getTimestamp());
1531   - }
1532   - //请求出场时间
1533   - d80 = PilotReport.qqccMap.get(device);
1534   - if(null != d80)
1535   - item.put("qqcc", d80.getTimestamp());
1536   -
1537   - list.add(item);
1538   - }
1539   -
1540   - //车载编码落在该线路的设备
1541   - Set<String> devices = gpsRealData.findDevices(lineCode);
1542   - for(String d : devices){
1543   - if(allDevices.containsKey(d))
1544   - continue;
1545   -
1546   - gps = gpsRealData.get(d);
1547   - if(null == gps)
1548   - continue;
1549   -
1550   - item = new HashMap<>();
1551   - item.put("nbbm", gps.getNbbm());
1552   - item.put("device", d);
1553   - item.put("loc", gps.getStationName());
1554   - item.put("lineCodeReal", gps.getLineId());
1555   - item.put("status", gps.isOffline()?"离线":"在线");
1556   - item.put("gpsTs", gps.getTimestamp());
1557   -
1558   - //请求出场时间
1559   - d80 = PilotReport.qqccMap.get(d);
1560   - if(null != d80)
1561   - item.put("qqcc", d80.getTimestamp());
1562   -
1563   - list.add(item);
1564   - }
1565   -
1566   - map.put("list", list);
1567   - map.put("status", ResponseCode.SUCCESS);
1568   - }catch (Exception e){
1569   - logger.error("", e);
1570   - map.put("status", ResponseCode.ERROR);
1571   - map.put("msg", e.getMessage());
1572   - }
1573   - return map;
1574   - }
1575   -
1576   - static List<GpsSpeed> findAll(Map<String, Object> map) {
1577   - Connection conn = null;
1578   - PreparedStatement ps = null;
1579   - ResultSet rs = null;
1580   - List<GpsSpeed> list=new ArrayList<GpsSpeed>();
1581   - String sql="select * from bsth_c_gps_info where 1=1 ";
1582   - Object line=map.get("line");
1583   - Object nbbm=map.get("nbbm");
1584   - Object updown=map.get("updown");
1585   - Object startDate=map.get("startDate");
1586   - Object endDate=map.get("endDate");
1587   - Integer totalDays = Integer.valueOf(map.get("totalDays").toString());
1588   - Integer curPage = 0;//页码
1589   - if(map.get("curPage") == null || map.get("curPage").equals("0")){
1590   - curPage = 0;
1591   - }else{
1592   - curPage = Integer.parseInt((String) map.get("curPage"));
1593   - }
1594   -
1595   - SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1596   - if(line!=null){
1597   - sql +=" and line_id like'%"+line.toString().trim()+"%'";
1598   - }
1599   -
1600   - if(nbbm!=null){
1601   - nbbm=BasicData.deviceId2NbbmMap.inverse().get(nbbm);
1602   - if(nbbm!=null)
1603   - sql +=" and vehicle like '%"+nbbm.toString()+"%'";
1604   - }
1605   -
1606   - if(updown!=null){
1607   - sql +="and industry_code like '%"+updown.toString()+"%'";
1608   - }
1609   - if(startDate!=null){
1610   - if (startDate.toString().length()>0) {
1611   - try {
1612   - Long t1=sdf.parse(startDate.toString()+" 00:00:00").getTime()+curPage*3600*24*1000;
1613   - sql += " and ts >="+t1;
1614   - } catch (ParseException e) {
1615   - e.printStackTrace();
1616   - }
1617   - }
1618   -
1619   - }
1620   - if(endDate!=null){
1621   - if (endDate.toString().length()>0) {
1622   - try {
1623   - Long t2=sdf.parse(endDate.toString()+" 23:59:59").getTime()-(totalDays-1-curPage)*3600*24*1000;
1624   - sql += " and ts <="+t2;
1625   - } catch (ParseException e) {
1626   - e.printStackTrace();
1627   - }
1628   - }
1629   -
1630   - }
1631   -
1632   - try {
1633   - conn = DBUtils_MS.getConnection();
1634   - ps = conn.prepareStatement(sql);
1635   - rs = ps.executeQuery();
1636   - list = resultSet2Set(rs);
1637   - } catch (SQLException e) {
1638   - e.printStackTrace();
1639   - }finally {
1640   - DBUtils_MS.close(rs, ps, conn);
1641   - }
1642   -
1643   - return list;
1644   - }
1645   -
1646   - static List<GpsSpeed> resultSet2Set(ResultSet rs) throws SQLException{
1647   - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1648   - List<GpsSpeed> list=new ArrayList<GpsSpeed>();
1649   - GpsSpeed GpsSpeed;
1650   - Float lon, lat;
1651   - Location location;
1652   - while(rs.next()){
1653   - lon = rs.getFloat("lon");
1654   - lat = rs.getFloat("lat");
1655   - location = CoordinateConverter.LocationMake(lon, lat);
1656   - location = CoordinateConverter.bd_encrypt(CoordinateConverter.transformFromWGSToGCJ(location));
1657   - GpsSpeed=new GpsSpeed();
1658   - GpsSpeed.setLon((float)location.getLng());
1659   - GpsSpeed.setLat((float)location.getLat());
1660   - GpsSpeed.setLine(rs.getObject("line_id").toString());
1661   - //run 时注解
1662   - GpsSpeed.setLineName(BasicData.lineCode2NameMap.get(GpsSpeed.getLine().toString()));
1663   - GpsSpeed.setSpeed(Float.valueOf(rs.getObject("speed_gps").toString()));
1664   - GpsSpeed.setTimestamp((Long.valueOf(rs.getObject("ts").toString())));
1665   - GpsSpeed.setTimestampDate(sdf.format(new Date(GpsSpeed.getTimestamp())));
1666   - GpsSpeed.setUp_down(((Integer.valueOf(rs.getObject("service_state").toString())) & 0x10000000)==0?0:1);
1667   - GpsSpeed.setVehicle(BasicData.deviceId2NbbmMap.get(rs.getObject("device_id").toString()));
1668   - list.add(GpsSpeed);
1669   - }
1670   - return list;
1671   - }
1672   -
1673   -}
1674   -
  1 +package com.bsth.service.gps;
  2 +
  3 +import java.io.IOException;
  4 +import java.io.OutputStream;
  5 +import java.io.UnsupportedEncodingException;
  6 +import java.lang.reflect.Field;
  7 +import java.net.URLEncoder;
  8 +import java.sql.Connection;
  9 +import java.sql.PreparedStatement;
  10 +import java.sql.ResultSet;
  11 +import java.sql.SQLException;
  12 +import java.text.DecimalFormat;
  13 +import java.text.ParseException;
  14 +import java.text.SimpleDateFormat;
  15 +import java.util.ArrayList;
  16 +import java.util.Arrays;
  17 +import java.util.Calendar;
  18 +import java.util.Collections;
  19 +import java.util.Comparator;
  20 +import java.util.Date;
  21 +import java.util.HashMap;
  22 +import java.util.HashSet;
  23 +import java.util.Iterator;
  24 +import java.util.LinkedList;
  25 +import java.util.List;
  26 +import java.util.Map;
  27 +import java.util.Set;
  28 +
  29 +import javax.servlet.http.HttpServletResponse;
  30 +
  31 +import org.apache.commons.lang3.StringUtils;
  32 +import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  33 +import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  34 +import org.apache.poi.ss.usermodel.CellStyle;
  35 +import org.apache.poi.ss.usermodel.Row;
  36 +import org.apache.poi.ss.usermodel.Sheet;
  37 +import org.apache.poi.ss.usermodel.Workbook;
  38 +import org.joda.time.format.DateTimeFormat;
  39 +import org.joda.time.format.DateTimeFormatter;
  40 +import org.slf4j.Logger;
  41 +import org.slf4j.LoggerFactory;
  42 +import org.springframework.beans.factory.annotation.Autowired;
  43 +import org.springframework.dao.DataAccessException;
  44 +import org.springframework.jdbc.core.BeanPropertyRowMapper;
  45 +import org.springframework.jdbc.core.JdbcTemplate;
  46 +import org.springframework.stereotype.Service;
  47 +
  48 +import com.bsth.common.ResponseCode;
  49 +import com.bsth.data.BasicData;
  50 +import com.bsth.data.forecast.entity.ArrivalEntity;
  51 +import com.bsth.data.gpsdata_v2.GpsRealData;
  52 +import com.bsth.data.gpsdata_v2.cache.GeoCacheData;
  53 +import com.bsth.data.gpsdata_v2.cache.GpsCacheData;
  54 +import com.bsth.data.gpsdata_v2.entity.GpsEntity;
  55 +import com.bsth.data.gpsdata_v2.utils.GeoUtils;
  56 +import com.bsth.data.pilot80.PilotReport;
  57 +import com.bsth.data.safe_driv.SafeDriv;
  58 +import com.bsth.data.safe_driv.SafeDrivCenter;
  59 +import com.bsth.data.schedule.DayOfSchedule;
  60 +import com.bsth.entity.LineVersions;
  61 +import com.bsth.entity.LsSectionRoute;
  62 +import com.bsth.entity.LsStationRoute;
  63 +import com.bsth.entity.directive.D80;
  64 +import com.bsth.entity.realcontrol.ScheduleRealInfo;
  65 +import com.bsth.repository.CarParkRepository;
  66 +import com.bsth.repository.LineRepository;
  67 +import com.bsth.repository.LineVersionsRepository;
  68 +import com.bsth.repository.LsSectionRouteRepository;
  69 +import com.bsth.repository.LsStationRouteRepository;
  70 +import com.bsth.repository.StationRepository;
  71 +import com.bsth.repository.realcontrol.ScheduleRealInfoRepository;
  72 +import com.bsth.service.gps.entity.DeviceChange;
  73 +import com.bsth.service.gps.entity.GpsOutbound_DTO;
  74 +import com.bsth.service.gps.entity.GpsSpeed;
  75 +import com.bsth.service.gps.entity.GpsSpeed_DTO;
  76 +import com.bsth.service.gps.entity.HistoryGps_DTO;
  77 +import com.bsth.service.gps.entity.HistoryGps_DTOV3;
  78 +import com.bsth.service.gps.entity.Road_DTO;
  79 +import com.bsth.util.CoordinateConverter;
  80 +import com.bsth.util.CoordinateConverter.Location;
  81 +import com.bsth.util.db.DBUtils_MS;
  82 +
  83 +@Service
  84 +public class GpsServiceImpl implements GpsService {
  85 + /**
  86 + * 历史gps查询最大范围 24小时
  87 + */
  88 + final static Long GPS_RANGE = 60 * 60 * 24L;
  89 +
  90 + /**
  91 + * jdbc
  92 + */
  93 + Connection conn = null;
  94 + PreparedStatement ps = null;
  95 + ResultSet rs = null;
  96 +
  97 + Logger logger = LoggerFactory.getLogger(this.getClass());
  98 +
  99 + @Autowired
  100 + GpsRealData gpsRealData;
  101 +
  102 + @Autowired
  103 + JdbcTemplate jdbcTemplate;
  104 +
  105 + @Autowired
  106 + DayOfSchedule dayOfSchedule;
  107 +
  108 + @Autowired
  109 + ScheduleRealInfoRepository scheduleRealInfoRepository;
  110 +
  111 +
  112 + @Autowired
  113 + LineVersionsRepository lineVersionsRepository;
  114 +
  115 + @Autowired
  116 + LineRepository lineRepository;
  117 +
  118 + @Autowired
  119 + LsStationRouteRepository lsStationRouteRepository;
  120 +
  121 + @Autowired
  122 + LsSectionRouteRepository lsSectionRouteRepository;
  123 +
  124 + // 历史gps查询
  125 + @Override
  126 + public List<Map<String, Object>> history(String device, Long startTime, Long endTime, int directions) {
  127 + Calendar sCal = Calendar.getInstance();
  128 + sCal.setTime(new Date(startTime));
  129 +
  130 + Calendar eCal = Calendar.getInstance();
  131 + eCal.setTime(new Date(endTime));
  132 +
  133 + int dayOfYear = sCal.get(Calendar.DAY_OF_YEAR);
  134 + /*
  135 + * if(dayOfYear != eCal.get(Calendar.DAY_OF_YEAR)){
  136 + * System.out.println("暂时不支持跨天查询..."); return null; }
  137 + */
  138 +
  139 + 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 < ?";
  140 + Connection conn = null;
  141 + PreparedStatement ps = null;
  142 + ResultSet rs = null;
  143 + List<Map<String, Object>> list = new ArrayList<>();
  144 + Map<String, Object> map = null;
  145 + try {
  146 + conn = DBUtils_MS.getConnection();
  147 + ps = conn.prepareStatement(sql);
  148 + ps.setInt(1, dayOfYear);
  149 + ps.setString(2, device);
  150 + ps.setLong(3, startTime);
  151 + ps.setLong(4, endTime);
  152 +
  153 + rs = ps.executeQuery();
  154 + Float lon, lat;
  155 + Location location;
  156 + int upDown;
  157 + while (rs.next()) {
  158 + upDown = getUpOrDown(rs.getLong("SERVICE_STATE"));
  159 + if (upDown != directions)
  160 + continue;
  161 +
  162 + // to 百度坐标
  163 + lon = rs.getFloat("LON");
  164 + lat = rs.getFloat("LAT");
  165 + location = CoordinateConverter.LocationMake(lon, lat);
  166 + location = CoordinateConverter.bd_encrypt(CoordinateConverter.transformFromWGSToGCJ(location));
  167 +
  168 + map = new HashMap<>();
  169 + map.put("device", rs.getString("DEVICE_ID"));
  170 + map.put("lon", location.getLng());
  171 + map.put("lat", location.getLat());
  172 + map.put("ts", rs.getLong("TS"));
  173 + map.put("stopNo", rs.getString("STOP_NO"));
  174 + map.put("inout_stop", rs.getInt("INOUT_STOP"));
  175 + // 上下行
  176 + map.put("upDown", upDown);
  177 + list.add(map);
  178 + }
  179 + } catch (Exception e) {
  180 + e.printStackTrace();
  181 + } finally {
  182 + DBUtils_MS.close(rs, ps, conn);
  183 + }
  184 + return list;
  185 + }
  186 +
  187 + /**
  188 + * 王通 2016/6/29 9:23:24 获取车辆线路上下行
  189 + *
  190 + * @return -1无效 0上行 1下行
  191 + */
  192 + public static byte getUpOrDown(long serviceState) {
  193 + /*if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000
  194 + || (serviceState & 0x01000000) == 0x01000000 || (serviceState & 0x08000000) == 0x08000000)
  195 + return -1;*/
  196 + return (byte) (((serviceState & 0x10000000) == 0x10000000) ? 1 : 0);
  197 + }
  198 +
  199 + /**
  200 + * 获取运营状态
  201 + *
  202 + * @return -1无效 0运营 1未运营
  203 + */
  204 + public static byte getService(long serviceState) {
  205 + /*if ((serviceState & 0x00020000) == 0x00020000 || (serviceState & 0x80000000) == 0x80000000)
  206 + return -1;*/
  207 + return (byte) (((serviceState & 0x02000000) == 0x02000000) ? 1 : 0);
  208 + }
  209 +
  210 + private static DateTimeFormatter fmtyyyy = DateTimeFormat.forPattern("yyyy");
  211 + @Override
  212 + public Map<String, Object> history(String[] nbbmArray, Long st, Long et) {
  213 + Map<String, Object> rsMap = new HashMap<>();
  214 + List<Map<String, Object>> list = new ArrayList<>();
  215 + rsMap.put("list", list);
  216 + if (et - st > GPS_RANGE)
  217 + return rsMap;
  218 +
  219 + st = st * 1000;
  220 + et = et * 1000;
  221 + // day_of_year 分区字段
  222 + Calendar sCal = Calendar.getInstance();
  223 + sCal.setTime(new Date(st));
  224 + int sDayOfYear = sCal.get(Calendar.DAY_OF_YEAR);
  225 + Calendar eCal = Calendar.getInstance();
  226 + eCal.setTime(new Date(et));
  227 + int eDayOfYear = eCal.get(Calendar.DAY_OF_YEAR);
  228 +
  229 + String nbbm = nbbmArray[0];
  230 +
  231 + List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);
  232 +
  233 + //按年分表
  234 + String tableName = "bsth_c_gps_info_" + fmtyyyy.print(st);
  235 +
  236 + StringBuilder sql = new StringBuilder("");
  237 + long t1,t2;
  238 + DeviceChange dc;
  239 + for(int i = 0,len=dcs.size(); i < len; i++){
  240 + t1 = st;
  241 + t2 = et;
  242 + dc = dcs.get(i);
  243 + if(dc.getSt() > st)
  244 + t1 = dc.getSt();
  245 + if(dc.getEt() < et && dc.getEt()!=0)
  246 + t2 = dc.getEt();
  247 +
  248 + sql.append("select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,STOP_NO,DIRECTION,LINE_ID,SPEED_GPS,SECTION_CODE from "+tableName+" where days_year in ("+sDayOfYear+","+eDayOfYear+") " +
  249 + " and device_id='"+dc.getDevice()+"' and ts >= "+t1+" and ts <= "+t2+" ");
  250 +
  251 + if(i == len - 1)
  252 + sql.append(" ORDER BY device_id,ts,stop_no");
  253 + else
  254 + sql.append(" UNION ");
  255 + }
  256 +
  257 + logger.info("轨迹回放 nbbm: " + nbbm + " -st: " + st + " -et: " + et + " -sql: " + sql.toString());
  258 +
  259 + // 查询到离站数据
  260 + Map<String, ArrivalEntity> arrivalMap = findArrivalByTs(st, et, dcs);
  261 +
  262 + //查询GPS数据
  263 + JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
  264 + List<Map<String, Object>> dataList = jdbcTemplate_ms.queryForList(sql.toString());
  265 +
  266 + Float lon, lat;
  267 + Location bdLoc, gdLoc;
  268 + int inOutStop;
  269 + long serviceState;
  270 + ArrivalEntity arrival;
  271 + Set<Integer> lineSet=new HashSet<Integer>();
  272 + List<Map<String,Object>> lineSwitch=new ArrayList<>();
  273 +
  274 + List<Map<String, Object>> gpsNotValidList=new ArrayList<>();
  275 + List<Map<String, Object>> gpsEqualsZeroList=new ArrayList<>();
  276 + Map<String, Object> map = null;
  277 + int oldLineId = -1, oldGpsValid = -1, oldLonlat = -1;
  278 +
  279 + // 默认加入一个线路切换信息
  280 + Map<String, Object> fls = new HashMap<String, Object>();
  281 + fls.put("abnormalType", "normal");
  282 + fls.put("st", "-1");
  283 + lineSwitch.add(fls);
  284 +
  285 + // 默认加入一个GPS无效异常信息
  286 + Map<String, Object> fgv = new HashMap<String, Object>();
  287 + fgv.put("abnormalType", "normal");
  288 + fgv.put("st", "-1");
  289 + gpsNotValidList.add(fgv);
  290 +
  291 + // 默认加入一个经纬度为零异常信息
  292 + Map<String, Object> fgez = new HashMap<String, Object>();
  293 + fgez.put("abnormalType", "normal");
  294 + fgez.put("st", "-1");
  295 + gpsEqualsZeroList.add(fgez);
  296 +
  297 + Map<String, Integer> lineCode2IdMap = BasicData.lineId2CodeMap.inverse();
  298 + for(Map<String, Object> rs : dataList) {
  299 + Object lineCode = rs.get("LINE_ID");
  300 + // 线路ID发生变化时补全线路切换信息 并新加入一个
  301 + if (oldLineId != (Integer)lineCode) {
  302 + String lineName = BasicData.lineCode2NameMap.get(lineCode.toString());
  303 + Integer lineId = lineCode2IdMap.get(lineCode.toString());
  304 + lineSwitch.get(lineSwitch.size() - 1).put("line2", lineName);
  305 + lineSwitch.get(lineSwitch.size() - 1).put("et", rs.get("TS"));
  306 +
  307 + Map<String, Object> ls = new HashMap<String, Object>();
  308 + ls.put("abnormalType", "lineSwitch");
  309 + ls.put("line1", lineName);
  310 + lineSwitch.add(ls);
  311 +
  312 + lineSet.add((Integer)lineId);
  313 + oldLineId = (Integer)lineId;
  314 + }
  315 + serviceState = map_get_long(rs, "SERVICE_STATE");
  316 + // GPS状态发生变化时补全信息 并新加入一个
  317 + if (getGpsValid(serviceState) != oldGpsValid) {
  318 + gpsNotValidList.get(gpsNotValidList.size() - 1).put("et", rs.get("TS"));
  319 +
  320 + Map<String, Object> gv = new HashMap<String, Object>();
  321 + gv.put("abnormalType", getGpsValid(serviceState) == 0 ? "normal" : "gpsNotValid");
  322 + gv.put("st", rs.get("TS"));
  323 + gpsNotValidList.add(gv);
  324 +
  325 + oldGpsValid = getGpsValid(serviceState);
  326 + }
  327 +
  328 + map = new HashMap<>();
  329 + lon = map_get_float(rs, "LON");
  330 + lat = map_get_float(rs, "LAT");
  331 + // 经纬度为零
  332 + if ((lon == 0 || lat == 0 ? 1 : 0) != oldLonlat){
  333 + gpsEqualsZeroList.get(gpsEqualsZeroList.size() - 1).put("et", rs.get("TS"));
  334 +
  335 + Map<String, Object> gez = new HashMap<String, Object>();
  336 + gez.put("abnormalType", (lon == 0 || lat == 0 ? 1 : 0) == 0 ? "normal" : "gpsZero");
  337 + gez.put("st", rs.get("TS"));
  338 + gpsEqualsZeroList.add(gez);
  339 +
  340 + oldLonlat = (lon == 0 || lat == 0 ? 1 : 0);
  341 + }
  342 +
  343 + // 高德坐标
  344 + gdLoc = CoordinateConverter.transformFromWGSToGCJ(CoordinateConverter.LocationMake(lon, lat));
  345 + map.put("gcj_lon", gdLoc.getLng());
  346 + map.put("gcj_lat", gdLoc.getLat());
  347 + // 百度坐标
  348 + bdLoc = CoordinateConverter.bd_encrypt(gdLoc);
  349 + map.put("bd_lon", bdLoc.getLng());
  350 + map.put("bd_lat", bdLoc.getLat());
  351 + //原始坐标
  352 + map.put("lon", lon);
  353 + map.put("lat", lat);
  354 +
  355 + map.put("deviceId", map_get_str(rs, "DEVICE_ID"));
  356 + map.put("ts", map_get_long(rs, "TS"));
  357 + map.put("timestamp", map_get_long(rs, "TS"));
  358 + map.put("stopNo", map_get_str(rs, "STOP_NO"));
  359 + map.put("direction", map_get_float(rs,"DIRECTION"));
  360 +
  361 + map.put("lineId", map_get_str(rs, "LINE_ID"));
  362 + map.put("speed", map_get_float(rs,"SPEED_GPS"));
  363 +
  364 + inOutStop = Integer.parseInt(rs.get("INOUT_STOP").toString());
  365 + map.put("inout_stop", inOutStop);
  366 +
  367 + arrival = arrivalMap.get(map_get_str(rs, "DEVICE_ID") + "_" + map_get_long(rs, "TS"));
  368 + if (arrival != null) {
  369 + map.put("inout_stop_info", arrival);
  370 + map.put("inout_stop", arrival.getInOut());
  371 + }
  372 +
  373 + //map.put("nbbm", nbbm);
  374 + map.put("state", getService(serviceState));
  375 + // 上下行
  376 + map.put("upDown", getUpOrDown(serviceState));
  377 + //路段编码
  378 + map.put("section_code", map_get_str(rs,"SECTION_CODE"));
  379 + list.add(map);
  380 + }
  381 + if (dataList.size() > 0) {
  382 + Map<String, Object> rs = dataList.get(dataList.size() - 1);
  383 + gpsNotValidList.get(gpsNotValidList.size() - 1).put("et", rs.get("TS"));
  384 + gpsEqualsZeroList.get(gpsEqualsZeroList.size() - 1).put("et", rs.get("TS"));
  385 + }
  386 +
  387 + for (int i = lineSwitch.size() - 1;i > -1;i--) {
  388 + Map<String, Object> ls = lineSwitch.get(i);
  389 + if ("normal".equals(ls.get("abnormalType")) || ls.get("et") == null) {
  390 + lineSwitch.remove(i);
  391 + }
  392 + }
  393 +
  394 + for (int i = gpsNotValidList.size() - 1;i > -1;i--) {
  395 + Map<String, Object> gnv = gpsNotValidList.get(i);
  396 + if ("normal".equals(gnv.get("abnormalType"))) {
  397 + gpsNotValidList.remove(i);
  398 + }
  399 + }
  400 +
  401 + for (int i = gpsEqualsZeroList.size() - 1;i > -1;i--) {
  402 + Map<String, Object> gez = gpsEqualsZeroList.get(i);
  403 + if ("normal".equals(gez.get("abnormalType"))) {
  404 + gpsEqualsZeroList.remove(i);
  405 + }
  406 + }
  407 +
  408 + if (lineSet.size() > 0){
  409 + List<Map<String,Object>> vlist=new ArrayList<>();
  410 + Map<String, Map<String, Object>> vmap = new HashMap<>();
  411 + Map<String, Map<String, String>> lv2station = new HashMap<String, Map<String, String>>();//lv2section = new HashMap<String, Map<String, String>>();
  412 + for (Integer lineId : lineSet) {
  413 + String lineCode = BasicData.lineId2CodeMap.get(lineId);
  414 + List<LineVersions> lvs = lineVersionsRepository.findBylineId(lineId);
  415 + for (LineVersions lv : lvs) {
  416 + long vst = lv.getStartDate().getTime(), vet = lv.getEndDate().getTime();
  417 + if (st >= vst && st <= vet || et >= vst && et <= vet) {
  418 + List<LsStationRoute> stations = lsStationRouteRepository.findupdated(lineId, lineId.toString(), lv.getVersions());
  419 + //List<LsSectionRoute> sections = lsSectionRouteRepository.findupdated(lineId, lineId.toString(), lv.getVersions());
  420 + Map<String, Object> vm = new HashMap<String, Object>();
  421 + vm.put("lineId", lineCode);
  422 + vm.put("version", lv.getVersions());
  423 + vm.put("startTime", vst);
  424 + vm.put("endTime", vet);
  425 + vm.put("stations", stations);
  426 + //vm.put("sections", sections);
  427 +
  428 + Map<String, String> stationcode2name = new HashMap<String, String>();//sectioncode2name = new HashMap<String, String>();
  429 + for (LsStationRoute lsr : stations) {
  430 + stationcode2name.put(lsr.getStationCode(), lsr.getStationName());
  431 + }
  432 + //for (LsSectionRoute lsr : sections) {
  433 + // sectioncode2name.put(lsr.getSectionCode(), lsr.getSection().getSectionName());
  434 + //}
  435 + lv2station.put(lineCode + "_" + lv.getVersions(), stationcode2name);
  436 + // 路段因为可能漂到其它线路路段 因此需要使用最新的全量路段
  437 + //lv2section.put(lineId + "_" + lv.getVersions(), sectioncode2name);
  438 +
  439 + vlist.add(vm);
  440 + vmap.put(lineCode + "_" + lv.getVersions(), vm);
  441 + }
  442 + }
  443 + }
  444 + rsMap.put("lineVerson",vlist);
  445 +
  446 + for (Map<String, Object> gps : list) {
  447 + long ts = (long)gps.get("timestamp");
  448 + for (Map<String, Object> vm : vlist) {
  449 + long vst = (long)vm.get("startTime"), vet = (long)vm.get("endTime");
  450 + if (gps.get("lineId").equals(vm.get("lineId")) && ts >= vst && ts <= vet) {
  451 + gps.put("version", vm.get("version"));
  452 + String key = vm.get("lineId") + "_" + vm.get("version");
  453 + /*if (StringUtils.isEmpty(sectionCode)) {
  454 + gps.put("section_code", "-00404");
  455 + gps.put("section_name", "未知路段");
  456 + }
  457 + gps.put("section_name", lv2section.get(key).get(sectionCode));*/
  458 + ArrivalEntity ae = (ArrivalEntity)gps.get("inout_stop_info");
  459 + if (ae != null) {
  460 + ae.setStopName(lv2station.get(key).get(ae.getStopNo()));
  461 + if (StringUtils.isEmpty(lv2station.get(key).get(ae.getStopNo()))) {
  462 + ae.setStopName(BasicData.stationCode2NameMap.get(ae.getStopNo()));
  463 + }
  464 + }
  465 + }
  466 + }
  467 + }
  468 + }
  469 + // 按时间排序
  470 + Collections.sort(list, new Comparator<Map<String, Object>>() {
  471 +
  472 + @Override
  473 + public int compare(Map<String, Object> o1, Map<String, Object> o2) {
  474 + return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));
  475 + }
  476 + });
  477 +
  478 + rsMap.put("list", list);
  479 + rsMap.put("dcs", dcs);
  480 + rsMap.put("gpsNotValid",gpsNotValidList);
  481 + rsMap.put("lineSwitch",lineSwitch);
  482 + rsMap.put("lonlatZero",gpsEqualsZeroList);
  483 + return rsMap;
  484 + }
  485 +
  486 + private String map_get_str(Map<String, Object> map, String key){
  487 + return map.containsKey(key)?map.get(key).toString():"";
  488 + }
  489 +
  490 + private Long map_get_long(Map<String, Object> map, String key){
  491 + return map.containsKey(key)?Long.parseLong(map.get(key).toString()):-1;
  492 + }
  493 +
  494 + private Float map_get_float(Map<String, Object> map, String key){
  495 + return map.containsKey(key)?Float.parseFloat(map.get(key).toString()):-1;
  496 + }
  497 +
  498 + private List<DeviceChange> findDeviceChangeLogs(String nbbm, long et, long st){
  499 + List<DeviceChange> dcs = null;
  500 + List<DeviceChange> rs = new ArrayList<>();
  501 + try{
  502 +
  503 + //JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
  504 + dcs = jdbcTemplate.query("select cl_zbh as nbbm,new_device_no as device,old_device_no as old_device,UNIX_TIMESTAMP(qyrq) * 1000 as st from bsth_c_car_device where cl_zbh='"+nbbm+"' order by qyrq"
  505 + , BeanPropertyRowMapper.newInstance(DeviceChange.class));
  506 +
  507 +
  508 + //生成一条初始记录
  509 + if(dcs.size() > 0){
  510 + DeviceChange first = dcs.get(0);
  511 +
  512 + DeviceChange initDv = new DeviceChange();
  513 + initDv.setDevice(first.getOldDevice());
  514 + if(StringUtils.isNotEmpty(initDv.getDevice())){
  515 + initDv.setNbbm(first.getNbbm());
  516 + initDv.setSt(0);
  517 + initDv.setEt(first.getSt());
  518 + dcs.add(0, initDv);
  519 + }
  520 + }
  521 + for(int i = 0,len=dcs.size(); i < len - 1; i++){
  522 + dcs.get(i).setEt(dcs.get(i + 1).getSt());
  523 + }
  524 +
  525 + for(DeviceChange dc : dcs){
  526 + if(dc.getEt() < st && dc.getEt() != 0)
  527 + continue;
  528 + if(dc.getSt() > et)
  529 + continue;
  530 +
  531 + rs.add(dc);
  532 + }
  533 +
  534 + //没有设备变更记录,则参考车辆信息上的设备号
  535 + if(null == rs || rs.size() == 0){
  536 + DeviceChange dc = new DeviceChange();
  537 + dc.setNbbm(nbbm);
  538 + dc.setDevice(BasicData.deviceId2NbbmMap.inverse().get(nbbm));
  539 + dc.setSt(st);
  540 + dc.setEt(et);
  541 + dc.setType(1);
  542 +
  543 + rs.add(dc);
  544 + }
  545 + }catch (Exception e){
  546 + logger.error("", e);
  547 + }
  548 + return rs;
  549 + }
  550 +
  551 + public static byte getGpsValid(long serviceState) {
  552 + return (byte)(((serviceState & 0x80000000) == 0x80000000) ? 1 : 0);
  553 + }
  554 +
  555 + public static void main(String[] args){
  556 + System.out.println(getGpsValid(-2147483648));
  557 + }
  558 +
  559 + public Map<String, ArrivalEntity> findArrivalByTs(Long st, Long et, List<DeviceChange> dcs) {
  560 + Map<String, ArrivalEntity> map = new HashMap<>();
  561 +
  562 + // weeks_year 分区字段
  563 + Calendar sCal = Calendar.getInstance();
  564 + sCal.setTime(new Date(st));
  565 + int sWeekOfYear = sCal.get(Calendar.WEEK_OF_YEAR);
  566 + Calendar eCal = Calendar.getInstance();
  567 + eCal.setTime(new Date(et));
  568 + int eWeekOfYear = eCal.get(Calendar.WEEK_OF_YEAR);
  569 +
  570 + //按年分表
  571 + String tableName = "bsth_c_arrival_info_" + fmtyyyy.print(st);
  572 +
  573 + StringBuilder sql = new StringBuilder("");
  574 + long t1,t2;
  575 + DeviceChange dc;
  576 + for(int i = 0,len=dcs.size(); i < len; i++){
  577 + t1 = st;
  578 + t2 = et;
  579 + dc = dcs.get(i);
  580 + if(dc.getSt() > st)
  581 + t1 = dc.getSt();
  582 + if(dc.getEt() < et && dc.getEt() != 0)
  583 + t2 = dc.getEt();
  584 +
  585 + sql.append("SELECT DEVICE_ID,LINE_ID as LINE_CODE,STOP_NO,TS,UP_DOWN,IN_OUT,WEEKS_YEAR,CREATE_DATE FROM " + tableName +
  586 + " where weeks_year in ("+sWeekOfYear+", "+eWeekOfYear+") and device_id='"+dc.getDevice()+"' and ts > "+t1+" and ts < " + t2);
  587 +
  588 + if(i == len - 1)
  589 + sql.append(" ORDER BY device_id,ts,stop_no ");
  590 + else
  591 + sql.append(" UNION ");
  592 + }
  593 +
  594 + logger.info("arrivl sql : " + sql.toString());
  595 + JdbcTemplate jdbcTemplate_ms = new JdbcTemplate(DBUtils_MS.getDataSource());
  596 + List<ArrivalEntity> list = jdbcTemplate_ms.query(sql.toString(), BeanPropertyRowMapper.newInstance(ArrivalEntity.class));
  597 +
  598 + String stationName, prefix;
  599 + for(ArrivalEntity arr : list){
  600 + prefix = arr.getLineCode() + "_" + arr.getUpDown() + "_";
  601 + stationName = BasicData.getStationNameByCode(arr.getStopNo(), prefix);
  602 +
  603 + arr.setStopName(stationName);
  604 +
  605 + // 反转进出状态
  606 + map.put(arr.getDeviceId() + "_" + arr.getTs(), arr);
  607 + }
  608 + return map;
  609 + }
  610 +
  611 +
  612 + @Autowired
  613 + StationRepository stationRepository;
  614 +
  615 + @Autowired
  616 + CarParkRepository carParkRepository;
  617 +
  618 + @Override
  619 + public Map<String, Object> findBuffAeraByCode(String lineCode, String code, String type) {
  620 + Object[][] obj = null;
  621 + if (type.equals("station"))
  622 + obj = stationRepository.findBufferArea(lineCode, code);
  623 + else if (type.equals("park"))
  624 + obj = carParkRepository.findBufferArea(code);
  625 +
  626 + Map<String, Object> rs = new HashMap<>();
  627 +
  628 + Object[] subObj = obj[0];
  629 + if (subObj != null && subObj.length == 6) {
  630 + rs.put("polygon", subObj[0]);
  631 + rs.put("type", subObj[1]);
  632 + rs.put("cPoint", subObj[2]);
  633 + rs.put("radius", subObj[3]);
  634 + rs.put("code", subObj[4]);
  635 + rs.put("text", subObj[5]);
  636 + }
  637 +
  638 + return rs;
  639 + }
  640 +
  641 + @Override
  642 + public Map<String, Object> search(Map<String, Object> map, int page, int size, String order, String direction) {
  643 + Map<String, Object> rsMap = new HashMap<>();
  644 + try {
  645 + //全量
  646 + List<GpsEntity> list = new ArrayList<>(gpsRealData.all());
  647 + //过滤后的
  648 + List<GpsEntity> rs = new ArrayList<>();
  649 + Field[] fields = GpsEntity.class.getDeclaredFields();
  650 + //参与过滤的字段
  651 + List<Field> fs = new ArrayList<>();
  652 + for (Field f : fields) {
  653 + f.setAccessible(true);
  654 + if (map.containsKey(f.getName()))
  655 + fs.add(f);
  656 + }
  657 + //过滤数据
  658 + for (GpsEntity gps : list) {
  659 + if (fieldEquals(fs, gps, map))
  660 + rs.add(gps);
  661 + }
  662 +
  663 + //时间戳排序
  664 + Collections.sort(rs, new Comparator<GpsEntity>() {
  665 + @Override
  666 + public int compare(GpsEntity o1, GpsEntity o2) {
  667 + return (int)(o2.getTimestamp().longValue() - o1.getTimestamp().longValue());
  668 + }
  669 + });
  670 +
  671 + //分页
  672 + int count = rs.size(), s = page * size, e = s + size;
  673 + if (e > count)
  674 + e = count;
  675 +
  676 + rsMap.put("list", rs.subList(s, e));
  677 + rsMap.put("totalPages", count % size == 0 ? count / size - 1 : count / size);
  678 + rsMap.put("page", page);
  679 + rsMap.put("status", ResponseCode.SUCCESS);
  680 + } catch (Exception e) {
  681 + logger.error("", e);
  682 + rsMap.put("status", ResponseCode.ERROR);
  683 + }
  684 + return rsMap;
  685 + }
  686 +
  687 + @Override
  688 + public Map<String, Object> removeRealGps(String device) {
  689 + Map<String, Object> rs = new HashMap<>();
  690 + try {
  691 +
  692 + gpsRealData.remove(device);
  693 + GpsCacheData.remove(BasicData.deviceId2NbbmMap.get(device));
  694 + rs.put("status", ResponseCode.SUCCESS);
  695 + } catch (Exception e) {
  696 + rs.put("status", ResponseCode.ERROR);
  697 + }
  698 + return rs;
  699 + }
  700 +
  701 + @Override
  702 + public Map<String, Object> findRoadSpeed(String lineCode) {
  703 + Map<String, Object> rs = new HashMap<>();
  704 +
  705 + try {
  706 + 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)";
  707 + List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, lineCode);
  708 + rs.put("status", ResponseCode.SUCCESS);
  709 + rs.put("roads", list);
  710 + } catch (DataAccessException e) {
  711 + logger.error("", e);
  712 + rs.put("status", ResponseCode.ERROR);
  713 + }
  714 + return rs;
  715 + }
  716 +
  717 + /**
  718 + * gps补全
  719 + *
  720 + * @param schId
  721 + * @return
  722 + */
  723 + @Override
  724 + public Map<String, Object> gpsCompletion(long schId, int type) {
  725 + Map<String, Object> rs = new HashMap<>();
  726 +
  727 + try {
  728 + ScheduleRealInfo sch = dayOfSchedule.get(schId);
  729 + if (sch == null) {
  730 + rs.put("status", ResponseCode.ERROR);
  731 + rs.put("msg", "找不到对应班次!!!");
  732 + return rs;
  733 + }
  734 +
  735 + if (sch.isReissue()) {
  736 + rs.put("status", ResponseCode.ERROR);
  737 + rs.put("msg", "你不能重复这个操作");
  738 + return rs;
  739 + }
  740 +
  741 + String sql = "select * from bsth_gps_template where line_id='" + sch.getXlBm() + "' and up_down=" + sch.getXlDir();
  742 + List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
  743 +
  744 + if (list.size() == 0) {
  745 + rs.put("status", ResponseCode.ERROR);
  746 + rs.put("msg", "缺少模板数据,请联系系统管理员!!");
  747 + return rs;
  748 + }
  749 + //排序
  750 + Collections.sort(list, new Comparator<Map<String, Object>>() {
  751 + @Override
  752 + public int compare(Map<String, Object> o1, Map<String, Object> o2) {
  753 + return (int) (Long.parseLong(o1.get("ts").toString()) - Long.parseLong(o2.get("ts").toString()));
  754 + }
  755 + });
  756 + Map<String, Object> fs = list.get(0);
  757 + //替换设备号和时间
  758 + long diff = ((sch.getDfsjT() - Long.parseLong(fs.get("ts").toString())) - 1000 * 70);
  759 +
  760 + String deviceId = BasicData.deviceId2NbbmMap.inverse().get(sch.getClZbh());
  761 + int serviceState;
  762 + for (Map<String, Object> map : list) {
  763 + map.put("device_id", deviceId);
  764 + map.put("ts", Long.parseLong(map.get("ts").toString()) + diff);
  765 + if(type==1){
  766 + //走补传协议
  767 + serviceState = Integer.parseInt(map.get("service_state").toString());
  768 + map.put("service_state", serviceState |= 0x00100000);
  769 + }
  770 + }
  771 +
  772 + String sqlBefore = "insert into bsth_c_template(", sqlValues = " values(";
  773 +
  774 + Set<String> ks = fs.keySet();
  775 + for (String k : ks) {
  776 + sqlBefore += (k + ",");
  777 + sqlValues += "?,";
  778 + }
  779 + sqlBefore = sqlBefore.substring(0, sqlBefore.length() - 1) + ", create_ts)";
  780 + sqlValues = sqlValues.substring(0, sqlValues.length() - 1) + ", " + System.currentTimeMillis() + ")";
  781 + sql = sqlBefore + " " + sqlValues;
  782 +
  783 + Connection conn = DBUtils_MS.getConnection();
  784 + conn.setAutoCommit(false);
  785 + ps = conn.prepareStatement(sql);
  786 + int fsize = ks.size();
  787 + List<Object> vs;
  788 + for (Map<String, Object> map : list) {
  789 + vs = new ArrayList<>(map.values());
  790 + for (int i = 0; i < fsize; i++) {
  791 + ps.setObject(i + 1, vs.get(i));
  792 + }
  793 + ps.addBatch();
  794 + }
  795 + ps.executeBatch();
  796 + conn.commit();
  797 +
  798 + rs.put("status", ResponseCode.SUCCESS);
  799 +
  800 + //标记班次
  801 + sch.setReissue(true);
  802 + scheduleRealInfoRepository.save(sch);
  803 +
  804 + rs.put("status", ResponseCode.SUCCESS);
  805 + } catch (Exception e) {
  806 + logger.error("", e);
  807 + rs.put("status", ResponseCode.ERROR);
  808 + }
  809 + return rs;
  810 + }
  811 +
  812 + @Override
  813 + public Map<String, Object> history_v2(String nbbm, long st, long et) {
  814 + Map<String, Object> rs = new HashMap<>();
  815 +
  816 + try {
  817 + //获取历史gps 数据
  818 + List<HistoryGps_DTO> list = HistoryGps_DTO.craete((List<Map<String, Object>>) history(new String[]{nbbm}, st, et).get("list"));
  819 + if (list != null && list.size() > 0) {
  820 + //获取路段信息
  821 + 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)";
  822 + List<Road_DTO> roads = Road_DTO.craete(jdbcTemplate.queryForList(sql, list.get(0).getLineId()));
  823 +
  824 + //为GPS数据关联路段信息
  825 + for (HistoryGps_DTO gps : list) {
  826 + matchRoadToGps(gps, roads);
  827 + }
  828 + }
  829 +
  830 + //超速数据
  831 + List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);
  832 + //越界数据
  833 + List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);
  834 + //计算里程
  835 + List<HistoryGps_DTO> effList = new ArrayList<>();
  836 + for(HistoryGps_DTO gps : list){
  837 + if(gps.getLat() != 0 && gps.getLon() != 0)
  838 + effList.add(gps);
  839 + }
  840 + double sum = 0, dist;
  841 + for (int i = 0; i < effList.size() - 1; i++) {
  842 + dist = GeoUtils.getDistance(effList.get(i).getPoint(), effList.get(i + 1).getPoint());
  843 + //点位相同时,dist会NaN
  844 + if(String.valueOf(dist).matches("^[0.0-9.0]+$"))
  845 + sum += dist;
  846 + }
  847 +
  848 + rs.put("status", ResponseCode.SUCCESS);
  849 + rs.put("list", removeDuplicate(effList));
  850 + rs.put("speedList", speedList);
  851 + rs.put("outboundList", outboundList);
  852 + rs.put("sumMileage", new DecimalFormat(".##").format(sum / 1000));
  853 + } catch (Exception e) {
  854 + logger.error("", e);
  855 + rs.put("status", ResponseCode.ERROR);
  856 + }
  857 + return rs;
  858 + }
  859 +
  860 +
  861 + @Override
  862 + public Map<String, Object> history_v3(String nbbm, long st, long et) {
  863 + Map<String, Object> rs = new HashMap<>();
  864 +
  865 + try {
  866 + //获取历史gps 数据
  867 + Map<String, Object> gpsMap = history(new String[]{nbbm}, st, et);
  868 + List<HistoryGps_DTOV3> list = HistoryGps_DTOV3.craete((List<Map<String, Object>>) gpsMap.get("list"));
  869 + if (list != null && list.size() > 0) {
  870 + //关联路段名称
  871 + Map<String, String> sectionCode2Name = GeoCacheData.sectionCode2NameMap();
  872 + for(HistoryGps_DTOV3 gps : list){
  873 + if(StringUtils.isNotEmpty(gps.getSection_code()))
  874 + gps.setSection_name(sectionCode2Name.get(gps.getSection_code()));
  875 + else{
  876 + gps.setSection_code("-00404");
  877 + gps.setSection_name("未知路段");
  878 + }
  879 + }
  880 + }
  881 +
  882 + //超速数据
  883 + List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);
  884 +
  885 + //越界数据
  886 + List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);
  887 +
  888 + //计算里程
  889 + List<HistoryGps_DTOV3> effList = new ArrayList<>();
  890 + for(HistoryGps_DTOV3 gps : list){
  891 + if(gps.getLat() != 0 && gps.getLon() != 0 && !"0".equals(gps.getLineId()))
  892 + effList.add(gps);
  893 + }
  894 + double sum = 0, dist;
  895 + for (int i = 0; i < effList.size() - 1; i++) {
  896 + dist = GeoUtils.getDistance(effList.get(i).getPoint(), effList.get(i + 1).getPoint());
  897 + //点位相同时,dist会NaN
  898 + if(String.valueOf(dist).matches("^[0.0-9.0]+$")){
  899 + if(dist > 0.8)
  900 + sum += dist;
  901 + }
  902 + }
  903 +
  904 + rs.put("status", ResponseCode.SUCCESS);
  905 + rs.put("list", removeDuplicateV3(effList));
  906 + rs.put("speedList", speedList);
  907 + rs.put("outboundList", outboundList);
  908 + rs.put("sumMileage", new DecimalFormat(".##").format(sum / 1000));
  909 + rs.put("dcs", gpsMap.get("dcs"));
  910 + rs.put("lineVerson",gpsMap.get("lineVerson"));
  911 + rs.put("gpsInvalid",gpsMap.get("gpsNotValid"));
  912 + rs.put("gpslineSwitch",gpsMap.get("lineSwitch"));
  913 + rs.put("gpslonlatex",gpsMap.get("lonlatZero"));
  914 + } catch (Exception e) {
  915 + logger.error("", e);
  916 + rs.put("status", ResponseCode.ERROR);
  917 + rs.put("msg", e.getMessage());
  918 + }
  919 + return rs;
  920 + }
  921 +
  922 + @Override
  923 + public void trailExcel(String nbbm, long st, long et, HttpServletResponse resp) {
  924 + //获取历史gps 数据
  925 + List<HistoryGps_DTOV3> list = HistoryGps_DTOV3.craete((List<Map<String, Object>>) history(new String[]{nbbm}, st, et).get("list"));
  926 + if (list != null && list.size() > 0) {
  927 + //关联路段名称
  928 + Map<String, String> sectionCode2Name = GeoCacheData.sectionCode2NameMap();
  929 + for(HistoryGps_DTOV3 gps : list){
  930 + if(StringUtils.isNotEmpty(gps.getSection_code()))
  931 + gps.setSection_name(sectionCode2Name.get(gps.getSection_code()));
  932 + else{
  933 + gps.setSection_code("-00404");
  934 + gps.setSection_name("未知路段");
  935 + }
  936 + }
  937 + }
  938 +
  939 + //创建excel工作簿
  940 + Workbook wb = new HSSFWorkbook();
  941 + Sheet sheet = wb.createSheet("行车轨迹");
  942 + //表头
  943 + Row row = sheet.createRow(0);
  944 + row.setHeight((short) (1.5 * 256));
  945 + row.createCell(0).setCellValue("序号");
  946 + row.createCell(1).setCellValue("车辆");
  947 + row.createCell(2).setCellValue("牌照号");
  948 + row.createCell(3).setCellValue("所在道路");
  949 + row.createCell(4).setCellValue("经度");
  950 + row.createCell(5).setCellValue("纬度");
  951 + row.createCell(6).setCellValue("时间");
  952 + row.createCell(7).setCellValue("速度");
  953 + //数据
  954 + DateTimeFormatter fmtHHmmss = DateTimeFormat.forPattern("HH:mm.ss"),
  955 + fmt = DateTimeFormat.forPattern("yyyyMMddHHmm");
  956 + HistoryGps_DTOV3 gps;
  957 + for(int i = 0; i < list.size(); i ++){
  958 + gps = list.get(i);
  959 + row = sheet.createRow(i + 1);
  960 + row.createCell(0).setCellValue(i + 1);
  961 + row.createCell(1).setCellValue(nbbm);
  962 + row.createCell(2).setCellValue(BasicData.nbbmCompanyPlateMap.get(nbbm));
  963 + row.createCell(3).setCellValue(gps.getSection_name());
  964 + row.createCell(4).setCellValue(gps.getLon());
  965 + row.createCell(5).setCellValue(gps.getLat());
  966 + row.createCell(6).setCellValue(fmtHHmmss.print(gps.getTimestamp()));
  967 + row.createCell(7).setCellValue(gps.getSpeed());
  968 + }
  969 +
  970 + st = st * 1000;
  971 + et = et * 1000;
  972 + String filename = nbbm + "轨迹数据" + fmt.print(st) + "至" + fmt.print(et) + ".xls";
  973 + try {
  974 + resp.setContentType("application/x-msdownload");
  975 + resp.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
  976 +
  977 + OutputStream out=resp.getOutputStream();
  978 + wb.write(out);
  979 + out.flush();
  980 + out.close();
  981 + } catch (UnsupportedEncodingException e) {
  982 + logger.error("", e);
  983 + } catch (IOException e) {
  984 + logger.error("", e);
  985 + }
  986 + }
  987 +
  988 + @Override
  989 + public void abnormalExcel(String nbbm, long st, long et, HttpServletResponse resp) {
  990 + //超速数据
  991 + List<GpsSpeed_DTO> speedList = speeds(nbbm, st, et);
  992 + //越界数据
  993 + List<GpsOutbound_DTO> outboundList = outbounds(nbbm, st, et);
  994 +
  995 + //创建excel工作簿
  996 + Workbook wb = new HSSFWorkbook();
  997 +
  998 + DateTimeFormatter fmtHHmmss = DateTimeFormat.forPattern("HH:mm.ss"),
  999 + fmt = DateTimeFormat.forPattern("yyyyMMddHHmm");
  1000 + if(speedList.size() > 0){
  1001 + Sheet sheet = wb.createSheet("超速");
  1002 + //表头
  1003 + Row row = sheet.createRow(0);
  1004 + row.setHeight((short) (1.5 * 256));
  1005 + row.createCell(0).setCellValue("异常信息");
  1006 + row.createCell(1).setCellValue("最大速度");
  1007 + row.createCell(2).setCellValue("开始时间");
  1008 + row.createCell(3).setCellValue("结束时间");
  1009 + row.createCell(4).setCellValue("持续(秒)");
  1010 + row.createCell(5).setCellValue("所在路段");
  1011 +
  1012 + GpsSpeed_DTO speed;
  1013 + for(int i = 0; i < speedList.size(); i++){
  1014 + speed = speedList.get(i);
  1015 + row = sheet.createRow(i + 1);
  1016 + row.createCell(0).setCellValue("超速");
  1017 + row.createCell(1).setCellValue(speed.getSpeed());
  1018 + row.createCell(2).setCellValue(fmtHHmmss.print(speed.getSt()));
  1019 + row.createCell(3).setCellValue(fmtHHmmss.print(speed.getEt()));
  1020 + if(speed.getEt() != 0)
  1021 + row.createCell(4).setCellValue((speed.getEt() - speed.getSt()) / 1000);
  1022 + row.createCell(5).setCellValue("");
  1023 + }
  1024 + }
  1025 +
  1026 + if(outboundList.size() > 0){
  1027 + Sheet sheet = wb.createSheet("越界");
  1028 + //表头
  1029 + Row row = sheet.createRow(0);
  1030 + row.setHeight((short) (1.5 * 256));
  1031 + row.createCell(0).setCellValue("异常信息");
  1032 + row.createCell(1).setCellValue("开始时间");
  1033 + row.createCell(2).setCellValue("结束时间");
  1034 + row.createCell(3).setCellValue("持续(秒)");
  1035 + row.createCell(4).setCellValue("所在路段");
  1036 + row.createCell(5).setCellValue("路径");
  1037 +
  1038 + GpsOutbound_DTO outbound;
  1039 + //设置路径单元格 水平对齐 填充
  1040 + CellStyle cs = wb.createCellStyle();
  1041 + cs.setAlignment(HSSFCellStyle.ALIGN_FILL);
  1042 + for(int i = 0; i < outboundList.size(); i++){
  1043 + outbound = outboundList.get(i);
  1044 + row = sheet.createRow(i + 1);
  1045 + row.createCell(0).setCellValue("超速");
  1046 + row.createCell(1).setCellValue(fmtHHmmss.print(outbound.getSt()));
  1047 + row.createCell(2).setCellValue(fmtHHmmss.print(outbound.getEt()));
  1048 + if(outbound.getEt() != 0)
  1049 + row.createCell(3).setCellValue((outbound.getEt() - outbound.getSt()) / 1000);
  1050 + row.createCell(4).setCellValue("");
  1051 + row.createCell(5).setCellValue(outbound.getLocations());
  1052 +
  1053 + row.getCell(5).setCellStyle(cs);
  1054 + }
  1055 + }
  1056 +
  1057 + st = st * 1000;
  1058 + et = et * 1000;
  1059 + String filename = nbbm + "异常信息" + fmt.print(st) + "至" + fmt.print(et) + ".xls";
  1060 + try {
  1061 + resp.setContentType("application/x-msdownload");
  1062 + resp.addHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
  1063 +
  1064 + OutputStream out=resp.getOutputStream();
  1065 + wb.write(out);
  1066 + out.flush();
  1067 + out.close();
  1068 + } catch (UnsupportedEncodingException e) {
  1069 + logger.error("", e);
  1070 + } catch (IOException e) {
  1071 + logger.error("", e);
  1072 + }
  1073 + }
  1074 +
  1075 + @Override
  1076 + public void arrivalExcel(String nbbm, long st, long et, HttpServletResponse resp) {
  1077 +
  1078 + }
  1079 +
  1080 + @Override
  1081 + public List<GpsSpeed_DTO> speeds(String nbbm, long st, long et) {
  1082 + st = st * 1000;
  1083 + et = et * 1000;
  1084 + //按周分区
  1085 + Calendar sCal = Calendar.getInstance();
  1086 + sCal.setTime(new Date(st));
  1087 + int sWeekYear = sCal.get(Calendar.WEEK_OF_YEAR);
  1088 + Calendar eCal = Calendar.getInstance();
  1089 + eCal.setTime(new Date(et));
  1090 + int eWeekYear = eCal.get(Calendar.WEEK_OF_YEAR);
  1091 +
  1092 + //按年分表
  1093 + String tableName = "bsth_c_speeding_" + fmtyyyy.print(st);
  1094 +
  1095 + List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);
  1096 + StringBuilder sql = new StringBuilder("");
  1097 + long t1,t2;
  1098 + DeviceChange dc;
  1099 + for(int i = 0,len=dcs.size(); i < len; i++){
  1100 + t1 = st;
  1101 + t2 = et;
  1102 + dc = dcs.get(i);
  1103 + if(dc.getSt() > st)
  1104 + t1 = dc.getSt();
  1105 + if(dc.getEt() < et && dc.getEt()!=0)
  1106 + t2 = dc.getEt();
  1107 +
  1108 + sql.append(" select vehicle, line, up_down, lon, lat, speed,timestamp from "+tableName+" where " +
  1109 + " weeks_year in ("+sWeekYear+", "+eWeekYear+") and vehicle='"+dc.getDevice()+"' and timestamp>="+t1+" and timestamp<= " + t2);
  1110 +
  1111 + if(i == len - 1)
  1112 + sql.append(" ORDER BY vehicle,timestamp");
  1113 + else
  1114 + sql.append(" UNION ");
  1115 + }
  1116 +
  1117 + logger.info("speed sql : " + sql.toString());
  1118 + return GpsSpeed_DTO.create(new JdbcTemplate(DBUtils_MS.getDataSource()).queryForList(sql.toString()));
  1119 + }
  1120 +
  1121 + @Override
  1122 + public List<GpsOutbound_DTO> outbounds(String nbbm, long st, long et) {
  1123 + st = st * 1000;
  1124 + et = et * 1000;
  1125 + //按周分区
  1126 + Calendar sCal = Calendar.getInstance();
  1127 + sCal.setTime(new Date(st));
  1128 + int sWeekYear = sCal.get(Calendar.WEEK_OF_YEAR);
  1129 + Calendar eCal = Calendar.getInstance();
  1130 + eCal.setTime(new Date(et));
  1131 + int eWeekYear = eCal.get(Calendar.WEEK_OF_YEAR);
  1132 +
  1133 + //按年分表
  1134 + String tableName = "bsth_c_outbound_" + fmtyyyy.print(st);
  1135 +
  1136 + List<DeviceChange> dcs = findDeviceChangeLogs(nbbm, et, st);
  1137 + StringBuilder sql = new StringBuilder("");
  1138 + long t1,t2;
  1139 + DeviceChange dc;
  1140 + for(int i = 0,len=dcs.size(); i < len; i++){
  1141 + t1 = st;
  1142 + t2 = et;
  1143 + dc = dcs.get(i);
  1144 + if(dc.getSt() > st)
  1145 + t1 = dc.getSt();
  1146 + if(dc.getEt() < et && dc.getEt()!=0)
  1147 + t2 = dc.getEt();
  1148 +
  1149 + sql.append("select vehicle,line,up_down,lon,lat,timestamp from "+tableName+" where " +
  1150 + " weeks_year in ("+sWeekYear+", "+eWeekYear+") and vehicle='"+dc.getDevice()+"' and timestamp>="+t1+" and timestamp<=" + t2);
  1151 +
  1152 + if(i == len - 1)
  1153 + sql.append(" ORDER BY vehicle,timestamp");
  1154 + else
  1155 + sql.append(" UNION ");
  1156 + }
  1157 +
  1158 + logger.info("outbounds sql : " + sql.toString());
  1159 + return GpsOutbound_DTO.create(new JdbcTemplate(DBUtils_MS.getDataSource()).queryForList(sql.toString()));
  1160 + }
  1161 +
  1162 + @Override
  1163 + public Map<String, Object> safeDrivList(Map<String, Object> map, int page, int size, String order, String direction) {
  1164 + Map<String, Object> rsMap = new HashMap<>();
  1165 + try {
  1166 + //全量
  1167 + List<SafeDriv> list = new ArrayList<>(SafeDrivCenter.findAll());
  1168 + //过滤后的
  1169 + List<SafeDriv> rs = new ArrayList<>();
  1170 + Field[] fields = SafeDriv.class.getDeclaredFields();
  1171 + //参与过滤的字段
  1172 + List<Field> fs = new ArrayList<>();
  1173 + for (Field f : fields) {
  1174 + f.setAccessible(true);
  1175 + if (map.containsKey(f.getName()))
  1176 + fs.add(f);
  1177 + }
  1178 + //过滤数据
  1179 + for (SafeDriv sd : list) {
  1180 + if (isSpecialLines(sd, map) && fieldEqualstow(fs, sd, map))
  1181 + rs.add(sd);
  1182 + }
  1183 +
  1184 + //时间戳排序
  1185 + Collections.sort(rs, new Comparator<SafeDriv>() {
  1186 + @Override
  1187 + public int compare(SafeDriv o1, SafeDriv o2) {
  1188 + return (int)(o2.getTs().longValue() - o1.getTs().longValue());
  1189 + }
  1190 + });
  1191 +
  1192 + //分页
  1193 + int count = rs.size(), s = page * size, e = s + size;
  1194 + if (e > count)
  1195 + e = count;
  1196 +
  1197 + rsMap.put("list", rs.subList(s, e));
  1198 + rsMap.put("totalPages", count % size == 0 ? count / size - 1 : count / size);
  1199 + rsMap.put("page", page);
  1200 + rsMap.put("status", ResponseCode.SUCCESS);
  1201 + } catch (Exception e) {
  1202 + logger.error("", e);
  1203 + rsMap.put("status", ResponseCode.ERROR);
  1204 + }
  1205 + return rsMap;
  1206 + }
  1207 +
  1208 + private void matchRoadToGps(HistoryGps_DTO gps, List<Road_DTO> roads) {
  1209 + double min = -1, distance;
  1210 + Road_DTO nearRoad = null;
  1211 + for (Road_DTO road : roads) {
  1212 + distance = GeoUtils.getDistanceFromLine(road.getLineStr(), gps.getPoint());
  1213 +
  1214 + if (min > distance || min == -1) {
  1215 + min = distance;
  1216 + nearRoad = road;
  1217 + }
  1218 + }
  1219 +
  1220 + gps.setRoad(nearRoad);
  1221 + gps.setRoadMinDistance(min);
  1222 + }
  1223 +
  1224 +
  1225 + private void matchRoadToGps(HistoryGps_DTOV3 gps, List<Road_DTO> roads) {
  1226 + double min = -1, distance;
  1227 + Road_DTO nearRoad = null;
  1228 + for (Road_DTO road : roads) {
  1229 + distance = GeoUtils.getDistanceFromLine(road.getLineStr(), gps.getPoint());
  1230 +
  1231 + if (min > distance || min == -1) {
  1232 + min = distance;
  1233 + nearRoad = road;
  1234 + }
  1235 + }
  1236 +
  1237 + if(min < 200){
  1238 + gps.setSection_code(nearRoad.getROAD_CODE());
  1239 + gps.setSection_name(nearRoad.getROAD_NAME());
  1240 + }
  1241 + else {
  1242 + gps.setSection_code("-00404");
  1243 + gps.setSection_name("未知路段");
  1244 + }
  1245 + //gps.setRoad(nearRoad);
  1246 + //gps.setRoadMinDistance(min);
  1247 + }
  1248 +
  1249 + /**
  1250 + * 去重复
  1251 + *
  1252 + * @param list
  1253 + * @return
  1254 + */
  1255 + private Set<HistoryGps_DTO> removeDuplicate(List<HistoryGps_DTO> list) {
  1256 + Set<HistoryGps_DTO> set = new HashSet<>();
  1257 + for (HistoryGps_DTO gps : list) {
  1258 + set.add(gps);
  1259 + }
  1260 + return set;
  1261 + }
  1262 +
  1263 + /**
  1264 + * 去重复
  1265 + *
  1266 + * @param list
  1267 + * @return
  1268 + */
  1269 + private Set<HistoryGps_DTOV3> removeDuplicateV3(List<HistoryGps_DTOV3> list) {
  1270 + Set<HistoryGps_DTOV3> set = new HashSet<>();
  1271 + for (HistoryGps_DTOV3 gps : list) {
  1272 + set.add(gps);
  1273 + }
  1274 + return set;
  1275 + }
  1276 +
  1277 +
  1278 + private void sortGpsList(final Field f, List<GpsEntity> rs) {
  1279 + Collections.sort(rs, new Comparator<GpsEntity>() {
  1280 +
  1281 + @Override
  1282 + public int compare(GpsEntity o1, GpsEntity o2) {
  1283 + try {
  1284 + if (f.get(o1) == f.get(o2))
  1285 + return 0;
  1286 +
  1287 + if (null == f.get(o1))
  1288 + return 1;
  1289 +
  1290 + if (null == f.get(o2))
  1291 + return -1;
  1292 +
  1293 + return f.get(o1).toString().compareTo(f.get(o2).toString());
  1294 + } catch (Exception e) {
  1295 + logger.error("", e);
  1296 + return -1;
  1297 + }
  1298 + }
  1299 + });
  1300 + }
  1301 +
  1302 + /**
  1303 + *
  1304 + * @param sd
  1305 + * @param map
  1306 + * @return
  1307 + */
  1308 + public boolean isSpecialLines(SafeDriv sd, Map<String, Object> map) {
  1309 + String lines = (String)map.get("lines");
  1310 + if (lines == null) lines = "";
  1311 +
  1312 + if (Arrays.asList(lines.split(",")).contains(sd.getXlbm())) return true;
  1313 + return false;
  1314 + }
  1315 +
  1316 + public boolean fieldEquals(List<Field> fs, Object obj, Map<String, Object> map) {
  1317 + try {
  1318 + String fv, v;
  1319 + for (Field f : fs) {
  1320 + if (StringUtils.isEmpty(map.get(f.getName()).toString()))
  1321 + continue;
  1322 +
  1323 + if(f.get(obj) == null)
  1324 + return false;
  1325 +
  1326 + fv = f.get(obj).toString();
  1327 + v = map.get(f.getName()).toString();
  1328 +
  1329 + if(!fv.startsWith(v)/* && !fv.endsWith(v)*/)
  1330 + return false;
  1331 + }
  1332 + } catch (Exception e) {
  1333 + logger.error("", e);
  1334 + return false;
  1335 + }
  1336 + return true;
  1337 + }
  1338 +
  1339 + public boolean fieldEqualstow(List<Field> fs, Object obj, Map<String, Object> map) {
  1340 + try {
  1341 + String fv, v;
  1342 + for (Field f : fs) {
  1343 + if (StringUtils.isEmpty(map.get(f.getName()).toString()))
  1344 + continue;
  1345 +
  1346 + if(f.get(obj) == null)
  1347 + return false;
  1348 +
  1349 + fv = f.get(obj).toString();
  1350 + v = map.get(f.getName()).toString();
  1351 + SafeDriv sd = (SafeDriv) obj;
  1352 + if(v.equals(sd.getJctype()))
  1353 + return true;
  1354 + else if(!fv.startsWith(v)/* && !fv.endsWith(v)*/)
  1355 + return false;
  1356 + }
  1357 + } catch (Exception e) {
  1358 + logger.error("", e);
  1359 + return false;
  1360 + }
  1361 + return true;
  1362 + }
  1363 +
  1364 +
  1365 + @Override
  1366 + public List<GpsSpeed> findPosition(String deviceid, String startdate,
  1367 + String enddate) throws ParseException{
  1368 + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1369 + Calendar c = Calendar.getInstance();
  1370 + Date date = sdf.parse(startdate);
  1371 + c.setTime(date);
  1372 + int daysYear = c.get(Calendar.DAY_OF_YEAR);//获取当前是今年的第几天。
  1373 +
  1374 + long startTime = sdf.parse(startdate).getTime();
  1375 + long endTime = sdf.parse(enddate).getTime();
  1376 +
  1377 + String sql = "select DEVICE_ID,LON,LAT,TS,INOUT_STOP,SERVICE_STATE ,speed_gps from bsth_c_gps_info where days_year=? and device_id=? and ts >= ? and ts <= ?" +
  1378 + " ORDER BY TS ";
  1379 + Connection conn = null;
  1380 + PreparedStatement ps = null;
  1381 + ResultSet rs = null;
  1382 + List<GpsSpeed> listResult = new ArrayList<GpsSpeed>();
  1383 + GpsSpeed gpsSpeed = null;
  1384 + try {
  1385 + conn = DBUtils_MS.getConnection();
  1386 + ps = conn.prepareStatement(sql);
  1387 + ps.setInt(1, daysYear);
  1388 + ps.setString(2, deviceid);
  1389 + ps.setLong(3,startTime);
  1390 + ps.setLong(4,endTime);
  1391 + rs = ps.executeQuery();
  1392 + Float lon, lat;
  1393 + Location location;
  1394 + while (rs.next()) {
  1395 + gpsSpeed = new GpsSpeed();
  1396 + // to 百度坐标
  1397 + lon = rs.getFloat("LON");
  1398 + lat = rs.getFloat("LAT");
  1399 + location = CoordinateConverter.LocationMake(lon, lat);
  1400 + location = CoordinateConverter.bd_encrypt(CoordinateConverter.transformFromWGSToGCJ(location));
  1401 + gpsSpeed.setVehicle(rs.getString("device_id"));
  1402 + gpsSpeed.setLon((float)location.getLng());
  1403 + gpsSpeed.setLat((float)location.getLat());
  1404 + gpsSpeed.setSpeed(rs.getFloat("speed_gps"));
  1405 + gpsSpeed.setTimestamp(rs.getLong("TS"));
  1406 + // 上下行
  1407 + listResult.add(gpsSpeed);
  1408 + }
  1409 + } catch (Exception e) {
  1410 + e.printStackTrace();
  1411 + } finally {
  1412 + DBUtils_MS.close(rs, ps, conn);
  1413 + }
  1414 + return listResult;
  1415 +
  1416 + }
  1417 +
  1418 + @Override
  1419 + public Map<String, Object> Pagequery(Map<String, Object> map) {
  1420 + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1421 + Integer totalDays = 0;//数据跨越天数
  1422 + try {
  1423 + totalDays = (int) ((sdf.parse(map.get("endDate").toString()+" 23:59:59").getTime()-sdf.parse(map.get("startDate").toString()+" 00:00:00").getTime()+1)/(3600*24*1000))+1;
  1424 + } catch (ParseException e) {
  1425 + e.printStackTrace();
  1426 + }//总页数
  1427 + map.put("totalDays",totalDays);
  1428 + List<GpsSpeed> list=findAll(map);
  1429 + List<GpsSpeed> listResult = new ArrayList<GpsSpeed>();
  1430 + int curPage = 0;//页码
  1431 + int pageData = 0;//每页的记录条数
  1432 + if(list.size()>1){
  1433 + GpsSpeed GpsSpeedNow;//下标为i的车辆行驶记录
  1434 + GpsSpeed GpsSpeedLast;//下标为i-1的车辆行驶记录
  1435 + GpsSpeed spped = null;//整合后的车辆行驶记录
  1436 + String strNow;
  1437 + String strLast;
  1438 + boolean Flag = false;//判断是否有连续超速记录,默认没有
  1439 + for(int i = 1;i<list.size();i++){
  1440 + GpsSpeedNow = list.get(i);
  1441 + GpsSpeedLast = list.get(i-1);
  1442 + strNow = GpsSpeedNow.getVehicle()+GpsSpeedNow.getLine()+GpsSpeedNow.getUp_down();
  1443 + strLast = GpsSpeedLast.getVehicle()+GpsSpeedLast.getLine()+GpsSpeedLast.getUp_down();
  1444 + if(GpsSpeedNow.getSpeed()>60 && GpsSpeedLast.getSpeed()>60 && strNow.equals(strLast)){//如果两条连续的记录都是超速且属于同一辆车。
  1445 + if(Flag==false){//
  1446 + spped = new GpsSpeed();
  1447 + spped.setLine(GpsSpeedLast.getLine());//设置连续超速记录线路
  1448 + spped.setLineName(GpsSpeedLast.getLineName());//设置连续超速记录线路名称
  1449 + spped.setVehicle(GpsSpeedLast.getVehicle());//设置连续超速记录的车辆编号
  1450 + spped.setUp_down(GpsSpeedLast.getUp_down());//设置上下行
  1451 + spped.setLon(GpsSpeedLast.getLon());//设置开始时经度
  1452 + spped.setLat(GpsSpeedLast.getLat());//设置开始时纬度
  1453 + spped.setTimestamp(GpsSpeedLast.getTimestamp());//设置连续超速记录的开始时间
  1454 + spped.setTimestampDate(GpsSpeedLast.getTimestampDate());//设置连续超速记录的开始时间戳
  1455 + }
  1456 + spped.setEndtimestamp(GpsSpeedNow.getTimestamp());//设置结束时间戳
  1457 + spped.setEndtimestampDate(sdf.format(new Date(GpsSpeedNow.getTimestamp())));//设置结束时间
  1458 + spped.setEndlon(GpsSpeedNow.getLon());//设置结束时的经度
  1459 + spped.setEndlat(GpsSpeedNow.getLat());//设置结束时的纬度
  1460 + Flag = true;
  1461 + }else{
  1462 + if(Flag){//如果上一条记录超速。
  1463 + listResult.add(spped);
  1464 + Flag = false;
  1465 + }
  1466 + }
  1467 + }
  1468 + if(listResult.size()>0){
  1469 + Iterator<GpsSpeed> speedIt = listResult.iterator();
  1470 + while(speedIt.hasNext()){
  1471 + GpsSpeed GpsSpeed = speedIt.next();
  1472 + if(GpsSpeed.getEndtimestamp()-GpsSpeed.getTimestamp()<=1000){
  1473 + speedIt.remove();
  1474 + }
  1475 + }
  1476 + }
  1477 + }
  1478 + if(map.get("curPage") == null || map.get("curPage").equals("0")){
  1479 + curPage = 0;
  1480 + }else{
  1481 + curPage = Integer.parseInt((String) map.get("curPage"));
  1482 + }
  1483 + Integer totalPage = totalDays;
  1484 + pageData = listResult.size();//每页的记录条数就是当前页查出的全部数据。
  1485 + Map<String,Object> paramMap = new HashMap<String,Object>();
  1486 + paramMap.put("totalPage", totalPage);
  1487 + paramMap.put("page", curPage);
  1488 + paramMap.put("pageData", pageData);
  1489 + paramMap.put("list", listResult);
  1490 + return paramMap;
  1491 + }
  1492 +
  1493 + @Override
  1494 + public Map<String, Object> allCarsByLine(String lineCode) {
  1495 + Map<String, Object> map = new HashMap();
  1496 + try{
  1497 + List<Map<String, Object>> list = new ArrayList<>();
  1498 + Map<String, Object> item;
  1499 + GpsEntity gps;
  1500 + //当天线路下营运的车辆
  1501 + Set<String> cars = dayOfSchedule.findCarByLineCode(lineCode);
  1502 + ScheduleRealInfo sch;
  1503 + String device;
  1504 +
  1505 + Map<String, Integer> allDevices = new HashMap<>();
  1506 + String execStr = "";
  1507 + D80 d80;
  1508 + for(String nbbm : cars){
  1509 + item = new HashMap<>();
  1510 + device = BasicData.deviceId2NbbmMap.inverse().get(nbbm);
  1511 + allDevices.put(device, 1);
  1512 + item.put("nbbm", nbbm);
  1513 + item.put("device", device);
  1514 +
  1515 + sch = dayOfSchedule.executeCurr(nbbm);
  1516 + if(null != sch){
  1517 + execStr = (sch.getXlDir().equals("0")?"上行":"下行") + "("+sch.getDfsj()+")";
  1518 + if(!sch.getXlBm().equals(lineCode))
  1519 + execStr = sch.getXlName()+execStr;
  1520 + else
  1521 + item.put("schId", sch.getId());
  1522 + item.put("exec", execStr);
  1523 + }
  1524 +
  1525 + gps = gpsRealData.get(device);
  1526 + if(null != gps){
  1527 + item.put("loc", gps.getStationName());
  1528 + item.put("lineCodeReal", gps.getLineId());
  1529 + item.put("status", gps.isOffline()?"离线":"在线");
  1530 + item.put("gpsTs", gps.getTimestamp());
  1531 + }
  1532 + //请求出场时间
  1533 + d80 = PilotReport.qqccMap.get(device);
  1534 + if(null != d80)
  1535 + item.put("qqcc", d80.getTimestamp());
  1536 +
  1537 + list.add(item);
  1538 + }
  1539 +
  1540 + //车载编码落在该线路的设备
  1541 + Set<String> devices = gpsRealData.findDevices(lineCode);
  1542 + for(String d : devices){
  1543 + if(allDevices.containsKey(d))
  1544 + continue;
  1545 +
  1546 + gps = gpsRealData.get(d);
  1547 + if(null == gps)
  1548 + continue;
  1549 +
  1550 + item = new HashMap<>();
  1551 + item.put("nbbm", gps.getNbbm());
  1552 + item.put("device", d);
  1553 + item.put("loc", gps.getStationName());
  1554 + item.put("lineCodeReal", gps.getLineId());
  1555 + item.put("status", gps.isOffline()?"离线":"在线");
  1556 + item.put("gpsTs", gps.getTimestamp());
  1557 +
  1558 + //请求出场时间
  1559 + d80 = PilotReport.qqccMap.get(d);
  1560 + if(null != d80)
  1561 + item.put("qqcc", d80.getTimestamp());
  1562 +
  1563 + list.add(item);
  1564 + }
  1565 +
  1566 + map.put("list", list);
  1567 + map.put("status", ResponseCode.SUCCESS);
  1568 + }catch (Exception e){
  1569 + logger.error("", e);
  1570 + map.put("status", ResponseCode.ERROR);
  1571 + map.put("msg", e.getMessage());
  1572 + }
  1573 + return map;
  1574 + }
  1575 +
  1576 + static List<GpsSpeed> findAll(Map<String, Object> map) {
  1577 + Connection conn = null;
  1578 + PreparedStatement ps = null;
  1579 + ResultSet rs = null;
  1580 + List<GpsSpeed> list=new ArrayList<GpsSpeed>();
  1581 + String sql="select * from bsth_c_gps_info where 1=1 ";
  1582 + Object line=map.get("line");
  1583 + Object nbbm=map.get("nbbm");
  1584 + Object updown=map.get("updown");
  1585 + Object startDate=map.get("startDate");
  1586 + Object endDate=map.get("endDate");
  1587 + Integer totalDays = Integer.valueOf(map.get("totalDays").toString());
  1588 + Integer curPage = 0;//页码
  1589 + if(map.get("curPage") == null || map.get("curPage").equals("0")){
  1590 + curPage = 0;
  1591 + }else{
  1592 + curPage = Integer.parseInt((String) map.get("curPage"));
  1593 + }
  1594 +
  1595 + SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1596 + if(line!=null){
  1597 + sql +=" and line_id like'%"+line.toString().trim()+"%'";
  1598 + }
  1599 +
  1600 + if(nbbm!=null){
  1601 + nbbm=BasicData.deviceId2NbbmMap.inverse().get(nbbm);
  1602 + if(nbbm!=null)
  1603 + sql +=" and vehicle like '%"+nbbm.toString()+"%'";
  1604 + }
  1605 +
  1606 + if(updown!=null){
  1607 + sql +="and industry_code like '%"+updown.toString()+"%'";
  1608 + }
  1609 + if(startDate!=null){
  1610 + if (startDate.toString().length()>0) {
  1611 + try {
  1612 + Long t1=sdf.parse(startDate.toString()+" 00:00:00").getTime()+curPage*3600*24*1000;
  1613 + sql += " and ts >="+t1;
  1614 + } catch (ParseException e) {
  1615 + e.printStackTrace();
  1616 + }
  1617 + }
  1618 +
  1619 + }
  1620 + if(endDate!=null){
  1621 + if (endDate.toString().length()>0) {
  1622 + try {
  1623 + Long t2=sdf.parse(endDate.toString()+" 23:59:59").getTime()-(totalDays-1-curPage)*3600*24*1000;
  1624 + sql += " and ts <="+t2;
  1625 + } catch (ParseException e) {
  1626 + e.printStackTrace();
  1627 + }
  1628 + }
  1629 +
  1630 + }
  1631 +
  1632 + try {
  1633 + conn = DBUtils_MS.getConnection();
  1634 + ps = conn.prepareStatement(sql);
  1635 + rs = ps.executeQuery();
  1636 + list = resultSet2Set(rs);
  1637 + } catch (SQLException e) {
  1638 + e.printStackTrace();
  1639 + }finally {
  1640 + DBUtils_MS.close(rs, ps, conn);
  1641 + }
  1642 +
  1643 + return list;
  1644 + }
  1645 +
  1646 + static List<GpsSpeed> resultSet2Set(ResultSet rs) throws SQLException{
  1647 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  1648 + List<GpsSpeed> list=new ArrayList<GpsSpeed>();
  1649 + GpsSpeed GpsSpeed;
  1650 + Float lon, lat;
  1651 + Location location;
  1652 + while(rs.next()){
  1653 + lon = rs.getFloat("lon");
  1654 + lat = rs.getFloat("lat");
  1655 + location = CoordinateConverter.LocationMake(lon, lat);
  1656 + location = CoordinateConverter.bd_encrypt(CoordinateConverter.transformFromWGSToGCJ(location));
  1657 + GpsSpeed=new GpsSpeed();
  1658 + GpsSpeed.setLon((float)location.getLng());
  1659 + GpsSpeed.setLat((float)location.getLat());
  1660 + GpsSpeed.setLine(rs.getObject("line_id").toString());
  1661 + //run 时注解
  1662 + GpsSpeed.setLineName(BasicData.lineCode2NameMap.get(GpsSpeed.getLine().toString()));
  1663 + GpsSpeed.setSpeed(Float.valueOf(rs.getObject("speed_gps").toString()));
  1664 + GpsSpeed.setTimestamp((Long.valueOf(rs.getObject("ts").toString())));
  1665 + GpsSpeed.setTimestampDate(sdf.format(new Date(GpsSpeed.getTimestamp())));
  1666 + GpsSpeed.setUp_down(((Integer.valueOf(rs.getObject("service_state").toString())) & 0x10000000)==0?0:1);
  1667 + GpsSpeed.setVehicle(BasicData.deviceId2NbbmMap.get(rs.getObject("device_id").toString()));
  1668 + list.add(GpsSpeed);
  1669 + }
  1670 + return list;
  1671 + }
  1672 +
  1673 +}
  1674 +
... ...