Browse Source

交通流双向车流量优化

develop
王兴琳 5 months ago
parent
commit
6afea549e6
  1. 171
      ruoyi-common/src/test/java/OkhttpTest.java
  2. 265
      zc-business/src/main/java/com/zc/business/controller/DcTrafficStatisticsController.java
  3. 4
      zc-business/src/main/java/com/zc/business/service/IDcTrafficStatisticsService.java
  4. 3
      zc-business/src/main/java/com/zc/business/service/impl/DcNoStakeWarningTableServiceImpl.java
  5. 247
      zc-business/src/main/java/com/zc/business/service/impl/DcTrafficStatisticsServiceImpl.java

171
ruoyi-common/src/test/java/OkhttpTest.java

@ -1,4 +1,7 @@
import com.ruoyi.common.utils.uuid.IdUtils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Quarter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zc.common.core.httpclient.OkHttp;
import com.zc.common.core.httpclient.exception.HttpException;
import com.zc.common.core.httpclient.request.RequestParams;
@ -7,8 +10,18 @@ import okhttp3.Callback;
import okhttp3.Response;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@ -19,6 +32,7 @@ public class OkhttpTest {
/**
* get 同步请求
*
* @throws HttpException
* @throws IOException
*/
@ -47,6 +61,7 @@ public class OkhttpTest {
/**
* get 异步请求
*
* @throws HttpException
* @throws IOException
*/
@ -56,21 +71,25 @@ public class OkhttpTest {
OkHttp okHttp = new OkHttp();
okHttp.url("https://www.baidu.com/") // 请求地址
.data(new RequestParams("java", "okhttp")) // 请求参数
.get(new Callback() {
.data(new RequestParams("java", "okhttp")) // 请求参数
.get(new Callback() {
// 请求失败回调
@Override
public void onFailure(Call call, IOException e) { }
// 请求失败回调
@Override
public void onFailure(Call call, IOException e) {
}
// 请求成功回调
@Override
public void onResponse(Call call, Response response) throws IOException { }
}); // 请求方法
// 请求成功回调
@Override
public void onResponse(Call call, Response response) throws IOException {
}
}); // 请求方法
}
/**
* post 同步请求
*
* @throws HttpException
* @throws IOException
*/
@ -98,6 +117,7 @@ public class OkhttpTest {
/**
* 文件 post 异步请求
*
* @throws HttpException
* @throws IOException
*/
@ -111,20 +131,24 @@ public class OkhttpTest {
requestParams.put("data", data);
okHttp.url("https://www.baidu.com/") // 请求地址
.data(requestParams) // 请求参数
.post(new Callback() {
// 请求失败回调
@Override
public void onFailure(Call call, IOException e) { }
// 请求成功回调
@Override
public void onResponse(Call call, Response response) throws IOException { }
}); // 请求方法
.data(requestParams) // 请求参数
.post(new Callback() {
// 请求失败回调
@Override
public void onFailure(Call call, IOException e) {
}
// 请求成功回调
@Override
public void onResponse(Call call, Response response) throws IOException {
}
}); // 请求方法
}
/**
* 文件 post 同步请求
*
* @throws HttpException
* @throws IOException
*/
@ -149,6 +173,7 @@ public class OkhttpTest {
/**
* post 异步请求
*
* @throws HttpException
* @throws IOException
*/
@ -161,22 +186,102 @@ public class OkhttpTest {
requestParams.put("文件1", new File("/file1"));
requestParams.put("文件2", new File("/file2"));
okHttp.url("https://www.baidu.com/") // 请求地址
.data(requestParams) // 请求参数
.filePost(new Callback() {
// 请求失败回调
@Override
public void onFailure(Call call, IOException e) { }
.data(requestParams) // 请求参数
.filePost(new Callback() {
// 请求失败回调
@Override
public void onFailure(Call call, IOException e) {
}
// 请求成功回调
@Override
public void onResponse(Call call, Response response) throws IOException {
}
}); // 请求方法
// 请求成功回调
@Override
public void onResponse(Call call, Response response) throws IOException { }
}); // 请求方法
}
@Test
public void aaa() {
try {
String apiKey = "00b26cbc2cb242283452ac5c842e81d1"; // 替换为你的API密钥
// 获取当前日期
LocalDate currentDate = LocalDate.now();
// 获取当前年份
int currentYear = currentDate.getYear();
String urlString = "https://apis.tianapi.com/jiejiari/index?key=" + apiKey + "&date=" + currentYear + "&type=1";
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if (connection.getResponseCode() != 200) {
throw new RuntimeException("HTTP错误码:" + connection.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
StringBuilder response = new StringBuilder();
while ((output = br.readLine()) != null) {
response.append(output);
}
connection.disconnect();
JSONObject jsonResponse = JSONObject.parseObject(response.toString());
// 计算当前日期加上七天的日期
LocalDate dateAfterSevenDays = currentDate.plusDays(7);
String formatter = String.valueOf(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
// 检查响应状态是否成功
if (jsonResponse.getInteger("code") == 200) {
// 获取result对象
JSONObject resultObj = jsonResponse.getJSONObject("result");
// 获取节假日列表JSONArray
JSONArray listArray = resultObj.getJSONArray("list");
// 遍历节假日列表
for (int i = 0; i < listArray.size(); i++) {
JSONObject holidayObj = listArray.getJSONObject(i);
String vacation = holidayObj.getString("vacation");
String name = holidayObj.getString("name");
String wage = holidayObj.getString("wage");
// Map<String, String> dateMap = splitDateString(vacation);
if (wage.equals(formatter)) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 分割日期字符串并构造Map
*
* @param dateStr 原始日期字符串 "|" 分隔
* @return 一个Map其中第一个日期为键剩余日期为值
*/
public static Map<String, String> splitDateString(String dateStr) {
String[] dates = dateStr.split("\\|");
if (dates.length > 0) {
Map<String, String> map = new HashMap<>();
String key = dates[0]; // 第一个日期作为键
map.put(key, dateStr);
return map;
} else {
return Collections.emptyMap(); // 如果原始字符串为空或只有分隔符,则返回空Map
}
}
@Test
public void aaa(){
String uuid = IdUtils.fastSimpleUUID();
System.out.println(uuid.length());
System.out.println(uuid);
public void ddd(){
// 获取当前季度
System.out.println();
}
}

265
zc-business/src/main/java/com/zc/business/controller/DcTrafficStatisticsController.java

@ -642,7 +642,14 @@ public AjaxResult trafficFlowAtTollStationEntrance(String startDate, String endD
@ApiOperation("全路段双向实时车流量")
@GetMapping("/history/realTimeTrafficFlowHour")
public AjaxResult realTimeTrafficFlowHour(String startDate,Long direction) throws HttpException, IOException{
List<Map<String,Object>> mapList = dcTrafficStatisticsService.realTimeTrafficFlowHour(startDate,direction);
Map<String,List<Map<String, Object>>> mapList = dcTrafficStatisticsService.realTimeTrafficFlowHour(startDate,direction);
// 将查询结果封装为成功响应并返回
return AjaxResult.success(mapList);
}
@ApiOperation("按照桩号查询门架数据 ")
@GetMapping("/history/queryTheGantryDataByPileNumber")
public AjaxResult queryTheGantryDataByPileNumber(String startDate,String stakeMark) throws HttpException, IOException{
List<Map<String,Object>> mapList = dcTrafficStatisticsService.queryTheGantryDataByPileNumber(startDate,stakeMark);
// 将查询结果封装为成功响应并返回
return AjaxResult.success(mapList);
}
@ -663,133 +670,133 @@ public AjaxResult trafficFlowAtTollStationEntrance(String startDate, String endD
/**
* 导出全路段双向实时车流量
*/
@ApiOperation(value = "导出全路段双向实时车流量",tags = {"ECharts导出"})
@GetMapping("/history/exportRealTimeTrafficFlowHour")
public AjaxResult exportRealTimeTrafficFlowHour(HttpServletResponse response) throws IOException, HttpException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate currentDate = LocalDate.now();
String now = currentDate.format(formatter);
// 获取一年前的日期
LocalDate oneYearAgo = currentDate.minusYears(1);
String lastYear = oneYearAgo.format(formatter);
List<Map<String,Object>> thisYearHZ = dcTrafficStatisticsService.realTimeTrafficFlowHour(now,1L);
List<Map<String,Object>> thisYearJN = dcTrafficStatisticsService.realTimeTrafficFlowHour(now,3L);
List<Map<String,Object>> lastYearHZ = dcTrafficStatisticsService.realTimeTrafficFlowHour(lastYear,1L);
List<Map<String,Object>> lastYearJN = dcTrafficStatisticsService.realTimeTrafficFlowHour(lastYear,3L);
Workbook workbook = new XSSFWorkbook(); // 创建工作簿
Sheet sheet = workbook.createSheet("全路段双向实时车流量"); // 创建工作表
// 创建数据行样式
CellStyle dataStyle = workbook.createCellStyle();
dataStyle.setAlignment(HorizontalAlignment.CENTER);
dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);
dataStyle.setBorderRight(BorderStyle.THIN);
dataStyle.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
dataStyle.setBorderLeft(BorderStyle.THIN);
dataStyle.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
dataStyle.setBorderTop(BorderStyle.THIN);
dataStyle.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
dataStyle.setBorderBottom(BorderStyle.THIN);
dataStyle.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
Font dataFont = workbook.createFont();
dataFont.setFontName("Arial");
dataFont.setFontHeightInPoints((short) 10);
dataStyle.setFont(dataFont);
// 创建表头样式
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.cloneStyleFrom(dataStyle);
headerStyle.setAlignment(HorizontalAlignment.CENTER);
headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headerStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font headerFont = workbook.createFont();
headerFont.setFontName("Arial");
headerFont.setFontHeightInPoints((short) 10);
headerFont.setBold(true);
headerFont.setColor(IndexedColors.WHITE.getIndex());
headerStyle.setFont(headerFont);
// 添加第一层级表头
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("路段名称");
cell.setCellStyle(headerStyle);
cell = row.createCell(1);
cell.setCellValue("济南方向");
cell.setCellStyle(headerStyle);
cell = row.createCell(2);
cell.setCellValue("");
cell.setCellStyle(headerStyle);;
cell = row.createCell(3);
cell.setCellValue("菏泽方向");
cell.setCellStyle(headerStyle);
cell = row.createCell(4);
cell.setCellValue("");
cell.setCellStyle(headerStyle);
// 添加第二层级表头(与第一层级对齐)
Row subHeaderRow1 = sheet.createRow(1);
cell = subHeaderRow1.createCell(0);
cell.setCellValue("");
cell.setCellStyle(headerStyle);
cell = subHeaderRow1.createCell(1);
cell.setCellValue("本期车流量");
cell.setCellStyle(headerStyle);
cell = subHeaderRow1.createCell(2);
cell.setCellValue("去年同期");
cell.setCellStyle(headerStyle);
cell = subHeaderRow1.createCell(3);
cell.setCellValue("本期车流量");
cell.setCellStyle(headerStyle);
cell = subHeaderRow1.createCell(4);
cell.setCellValue("去年同期");
cell.setCellStyle(headerStyle);
//合并单元格,参数依次为起始行,结束行,起始列,结束列 (从0开始)
//路段名称
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));
//济南方向
sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 2));
//菏泽方向
sheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 4));
for (int i = 0; i < thisYearHZ.size(); i++) {
Row subHeaderRow = sheet.createRow(i+2);
cell = subHeaderRow.createCell(0);
cell.setCellValue(thisYearJN.get(i).get("name").toString());
cell.setCellStyle(dataStyle);
cell = subHeaderRow.createCell(1);
cell.setCellValue(thisYearJN.get(i).get("totalFlow").toString());
cell.setCellStyle(dataStyle);
cell = subHeaderRow.createCell(2);
cell.setCellValue(lastYearJN.get(i).get("totalFlow").toString());
cell.setCellStyle(dataStyle);
cell = subHeaderRow.createCell(3);
cell.setCellValue(thisYearHZ.get(i).get("totalFlow").toString());
cell.setCellStyle(dataStyle);
cell = subHeaderRow.createCell(4);
cell.setCellValue(lastYearHZ.get(i).get("totalFlow").toString());
cell.setCellStyle(dataStyle);
}
// 写入文件
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
workbook.write(response.getOutputStream());
} finally {
workbook.close();
}
return AjaxResult.success("导出感知事件多发时段成功");
}
// @ApiOperation(value = "导出全路段双向实时车流量",tags = {"ECharts导出"})
// @GetMapping("/history/exportRealTimeTrafficFlowHour")
// public AjaxResult exportRealTimeTrafficFlowHour(HttpServletResponse response) throws IOException, HttpException {
//
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// LocalDate currentDate = LocalDate.now();
// String now = currentDate.format(formatter);
//
// // 获取一年前的日期
// LocalDate oneYearAgo = currentDate.minusYears(1);
// String lastYear = oneYearAgo.format(formatter);
//
// List<Map<String,Object>> thisYearHZ = dcTrafficStatisticsService.realTimeTrafficFlowHour(now,1L);
// List<Map<String,Object>> thisYearJN = dcTrafficStatisticsService.realTimeTrafficFlowHour(now,3L);
// List<Map<String,Object>> lastYearHZ = dcTrafficStatisticsService.realTimeTrafficFlowHour(lastYear,1L);
// List<Map<String,Object>> lastYearJN = dcTrafficStatisticsService.realTimeTrafficFlowHour(lastYear,3L);
//
// Workbook workbook = new XSSFWorkbook(); // 创建工作簿
// Sheet sheet = workbook.createSheet("全路段双向实时车流量"); // 创建工作表
//
// // 创建数据行样式
// CellStyle dataStyle = workbook.createCellStyle();
// dataStyle.setAlignment(HorizontalAlignment.CENTER);
// dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// dataStyle.setBorderRight(BorderStyle.THIN);
// dataStyle.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
// dataStyle.setBorderLeft(BorderStyle.THIN);
// dataStyle.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
// dataStyle.setBorderTop(BorderStyle.THIN);
// dataStyle.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
// dataStyle.setBorderBottom(BorderStyle.THIN);
// dataStyle.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
// Font dataFont = workbook.createFont();
// dataFont.setFontName("Arial");
// dataFont.setFontHeightInPoints((short) 10);
// dataStyle.setFont(dataFont);
//
// // 创建表头样式
// CellStyle headerStyle = workbook.createCellStyle();
// headerStyle.cloneStyleFrom(dataStyle);
// headerStyle.setAlignment(HorizontalAlignment.CENTER);
// headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// headerStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
// headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// Font headerFont = workbook.createFont();
// headerFont.setFontName("Arial");
// headerFont.setFontHeightInPoints((short) 10);
// headerFont.setBold(true);
// headerFont.setColor(IndexedColors.WHITE.getIndex());
// headerStyle.setFont(headerFont);
//
// // 添加第一层级表头
// Row row = sheet.createRow(0);
// Cell cell = row.createCell(0);
// cell.setCellValue("路段名称");
// cell.setCellStyle(headerStyle);
// cell = row.createCell(1);
// cell.setCellValue("济南方向");
// cell.setCellStyle(headerStyle);
// cell = row.createCell(2);
// cell.setCellValue("");
// cell.setCellStyle(headerStyle);;
// cell = row.createCell(3);
// cell.setCellValue("菏泽方向");
// cell.setCellStyle(headerStyle);
// cell = row.createCell(4);
// cell.setCellValue("");
// cell.setCellStyle(headerStyle);
//
// // 添加第二层级表头(与第一层级对齐)
// Row subHeaderRow1 = sheet.createRow(1);
// cell = subHeaderRow1.createCell(0);
// cell.setCellValue("");
// cell.setCellStyle(headerStyle);
// cell = subHeaderRow1.createCell(1);
// cell.setCellValue("本期车流量");
// cell.setCellStyle(headerStyle);
//
// cell = subHeaderRow1.createCell(2);
// cell.setCellValue("去年同期");
// cell.setCellStyle(headerStyle);
// cell = subHeaderRow1.createCell(3);
// cell.setCellValue("本期车流量");
// cell.setCellStyle(headerStyle);
//
// cell = subHeaderRow1.createCell(4);
// cell.setCellValue("去年同期");
// cell.setCellStyle(headerStyle);
//
// //合并单元格,参数依次为起始行,结束行,起始列,结束列 (从0开始)
// //路段名称
// sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));
// //济南方向
// sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 2));
// //菏泽方向
// sheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 4));
//
// for (int i = 0; i < thisYearHZ.size(); i++) {
// Row subHeaderRow = sheet.createRow(i+2);
// cell = subHeaderRow.createCell(0);
// cell.setCellValue(thisYearJN.get(i).get("name").toString());
// cell.setCellStyle(dataStyle);
// cell = subHeaderRow.createCell(1);
// cell.setCellValue(thisYearJN.get(i).get("totalFlow").toString());
// cell.setCellStyle(dataStyle);
// cell = subHeaderRow.createCell(2);
// cell.setCellValue(lastYearJN.get(i).get("totalFlow").toString());
// cell.setCellStyle(dataStyle);
// cell = subHeaderRow.createCell(3);
// cell.setCellValue(thisYearHZ.get(i).get("totalFlow").toString());
// cell.setCellStyle(dataStyle);
// cell = subHeaderRow.createCell(4);
// cell.setCellValue(lastYearHZ.get(i).get("totalFlow").toString());
// cell.setCellStyle(dataStyle);
// }
//
//
// // 写入文件
// try {
// response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// response.setCharacterEncoding("utf-8");
// workbook.write(response.getOutputStream());
// } finally {
// workbook.close();
// }
//
// return AjaxResult.success("导出感知事件多发时段成功");
// }
}

4
zc-business/src/main/java/com/zc/business/service/IDcTrafficStatisticsService.java

@ -52,7 +52,7 @@ public interface IDcTrafficStatisticsService {
JSONArray trafficFlowAtTollStationEntranceHour(String startDate, String endDate, String stationType)throws HttpException, IOException;
List<Map<String, Object>> realTimeTrafficFlowHour(String startDate,Long direction) throws HttpException, IOException;
// JSONArray realTimeTrafficFlowHour2(String startDate,Long direction) throws HttpException, IOException;
Map<String,List<Map<String, Object>>> realTimeTrafficFlowHour(String startDate,Long direction) throws HttpException, IOException;
List<Map<String,Object>> queryTheGantryDataByPileNumber(String startDate,String stakeMark) throws HttpException, IOException;
}

3
zc-business/src/main/java/com/zc/business/service/impl/DcNoStakeWarningTableServiceImpl.java

@ -54,6 +54,9 @@ public class DcNoStakeWarningTableServiceImpl extends ServiceImpl<DcNoStakeWarni
if (endTime != null && startTime != null) {
queryWrapper.between(DcNoStakeWarningTable::getWarningTime, startTime, endTime);
}
queryWrapper.orderByDesc(DcNoStakeWarningTable::getWarningTime);
// 木桩
return queryWrapper;
}

247
zc-business/src/main/java/com/zc/business/service/impl/DcTrafficStatisticsServiceImpl.java

@ -31,7 +31,9 @@ import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
@ -632,35 +634,27 @@ public class DcTrafficStatisticsServiceImpl implements IDcTrafficStatisticsServi
ResponseBody body = response.body();
if (body != null) {
JSONArray jsonArray = JSON.parseArray(body.string());
// 使用HashMap来分组并求和
Map<String, Integer> sumByName = new HashMap<>();
Map<String, Integer> sumByName = new LinkedHashMap<>();
List<Map<String, String>> list = new ArrayList();
for (Object item : jsonArray) { // 这里做了微调,直接遍历jsonArray的Object
JSONObject jsonObject = (JSONObject) item;
// 获取当前时间
LocalTime now = LocalTime.now();
// 获取当前小时数(24小时制)
int currentHour = now.getHour();
if (jsonObject.getInteger("data_hour") == currentHour) {
String name = jsonObject.getString("ts_name"); // 更安全的取值方式
int totalFlow = jsonObject.getInteger("total_flow"); // 专门针对Integer类型
sumByName.put(name, totalFlow);
// sumByName.put(name, sumByName.getOrDefault(name, 0) + totalFlow);
}
}
// 输出结果
// 输出结果
// 正确创建新的映射对象并添加到list中
for (Map.Entry<String, Integer> entry : sumByName.entrySet()) {
Map<String, String> singleResult = new HashMap<>(); // 每次循环都创建一个新的映射
Map<String, String> singleResult = new LinkedHashMap<>(); // 每次循环都创建一个新的映射
singleResult.put("name", entry.getKey());
singleResult.put("value", entry.getValue().toString());
list.add(singleResult);
//System.out.println(entry.getKey() + " 的 total_flow 总和为: " + entry.getValue());
}
return list;
}
@ -705,22 +699,107 @@ public class DcTrafficStatisticsServiceImpl implements IDcTrafficStatisticsServi
}
@Override
public List<Map<String, Object>> realTimeTrafficFlowHour(String startDate, Long direction) throws HttpException, IOException {
OkHttp okHttp = new OkHttp();
public Map<String,List<Map<String, Object>>> realTimeTrafficFlowHour(String startDate, Long direction) throws HttpException, IOException {
RequestParams requestParams = new RequestParams();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate currentDate = LocalDate.now();
String nowYear = currentDate.format(formatter);
//String nowYear =startDate;
// 获取一年前的日期
LocalDate oneYearAgo = currentDate.minusYears(1);
String lastYear = oneYearAgo.format(formatter);
OkHttp okHttp = new OkHttp();
RequestParams requestParams = new RequestParams();
requestParams.put("sysid", sysid);
//求情地址 startDate 时间
JSONArray body = getResponseBody(nowYear, requestParams, okHttp);
JSONArray bodylast = getResponseBody(lastYear, requestParams, okHttp);
Map<String,List<Map<String, Object>>> map = new HashMap<>();
if (body != null) {
List<Map<String, Object>> mapList = getMaps("1", body);
map.put("1",mapList);
List<Map<String, Object>> mapList2 = getMaps("3", body);
map.put("2",mapList2);
}
if (bodylast != null) {
List<Map<String, Object>> mapList = getMaps("1", bodylast);
map.put("3",mapList);
List<Map<String, Object>> mapList2 = getMaps("3", bodylast);
map.put("4",mapList2);
}
return map;
}
//处理 接口响应数据
private List<Map<String, Object>> getMaps(String direction, JSONArray jsonArray) throws IOException {
// 获取当前时间
LocalTime now = LocalTime.now();
// 获取当前小时数(24小时制)
int currentHour = now.getHour();
// 初始化计数器和描述映射
Map<Integer, Integer> flowCounts = new HashMap<>();
Map<Integer, String> descriptions = new HashMap<>();
for (int i = 1; i <= 14; i++) {
flowCounts.put(i, 0);
descriptions.put(i, "");
}
for (Object item : jsonArray) {
JSONObject jsonObject = (JSONObject) item;
if (jsonObject.getInteger("data_hour") == currentHour) {
int totalFlow = jsonObject.getInteger("total_flow");
String gantryId = jsonObject.getString("gantry_id");
DcFacility dcFacilityAll = new DcFacility();
dcFacilityAll.setFacilityType(10);
dcFacilityAll.setDirection(direction);
List<DcFacility> dcFacilityList = facilityService.listFacility(dcFacilityAll);
DcFacility dcFacility2 = facilityService.getfacilityCode(gantryId);
if (dcFacility2 != null) {
String stakeMark = dcFacility2.getStakeMark();
boolean exists = dcFacilityList.stream()
.anyMatch(dcFacility -> dcFacility.getId().equals(dcFacility2.getId()));
if (exists) {
int extractedNumber = Integer.parseInt(extract(stakeMark));
int identification = Arrays.stream(StakeMarkRange.values())
.filter(smRange -> extractedNumber >= smRange.getStakeMark() && extractedNumber <= smRange.getEndMark())
.mapToInt(StakeMarkRange::getIdentification)
.findFirst()
.orElse(0);
String description = getDescriptionByIdentification(identification);
descriptions.put(identification, description);
flowCounts.put(identification, flowCounts.get(identification) + totalFlow);
}
}
}
}
// 构建结果列表
List<Map<String, Object>> mapList = new ArrayList<>();
for (int i = 1; i <= 14; i++) {
Map<String, Object> map = new HashMap<>();
map.put("name", getDescriptionByIdentification(i));
map.put("totalFlow", flowCounts.get(i));
mapList.add(map);
}
return mapList;
}
// 获取车流量接口 返回 jsonArray
private JSONArray getResponseBody(String startDate, RequestParams requestParams, OkHttp okHttp) throws HttpException, IOException {
JSONObject parameters = new JSONObject() {
{
put("start_date", startDate);
put("end_date", startDate);
}
};
requestParams.put("parameters", parameters.toJSONString());
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", getAccessToken());
@ -731,65 +810,8 @@ public class DcTrafficStatisticsServiceImpl implements IDcTrafficStatisticsServi
.data(requestParams) // 请求参数
.post(); // 请求方法
ResponseBody body = response.body();
if (body != null) {
JSONArray jsonArray = JSON.parseArray(body.string());
// 获取当前时间
LocalTime now = LocalTime.now();
// 获取当前小时数(24小时制)
int currentHour = now.getHour();
// 初始化计数器和描述映射
Map<Integer, Integer> flowCounts = new HashMap<>();
Map<Integer, String> descriptions = new HashMap<>();
for (int i = 1; i <= 14; i++) {
flowCounts.put(i, 0);
descriptions.put(i, "");
}
for (Object item : jsonArray) {
JSONObject jsonObject = (JSONObject) item;
if (jsonObject.getInteger("data_hour") == currentHour) {
int totalFlow = jsonObject.getInteger("total_flow");
String gantryId = jsonObject.getString("gantry_id");
DcFacility dcFacilityAll = new DcFacility();
dcFacilityAll.setFacilityType(10);
dcFacilityAll.setDirection(String.valueOf(direction));
List<DcFacility> dcFacilityList = facilityService.listFacility(dcFacilityAll);
DcFacility dcFacility2 = facilityService.getfacilityCode(gantryId);
if (dcFacility2 != null) {
String stakeMark = dcFacility2.getStakeMark();
boolean exists = dcFacilityList.stream()
.anyMatch(dcFacility -> dcFacility.getId().equals(dcFacility2.getId()));
if (exists) {
int extractedNumber = Integer.parseInt(extract(stakeMark));
int identification = Arrays.stream(StakeMarkRange.values())
.filter(smRange -> extractedNumber >= smRange.getStakeMark() && extractedNumber <= smRange.getEndMark())
.mapToInt(StakeMarkRange::getIdentification)
.findFirst()
.orElse(0);
String description = getDescriptionByIdentification(identification);
descriptions.put(identification, description);
flowCounts.put(identification, flowCounts.get(identification) + totalFlow);
}
}
}
}
// 构建结果列表
List<Map<String, Object>> mapList = new ArrayList<>();
for (int i = 1; i <= 14; i++) {
Map<String, Object> map = new HashMap<>();
map.put("name", getDescriptionByIdentification(i));
map.put("totalFlow", flowCounts.get(i));
mapList.add(map);
}
return mapList;
}
return null;
JSONArray jsonArray = JSON.parseArray(body.string());
return jsonArray;
}
@ -815,8 +837,19 @@ public class DcTrafficStatisticsServiceImpl implements IDcTrafficStatisticsServi
}
return "";
}
/*
public JSONArray realTimeTrafficFlowHour2(String startDate,Long direction) throws HttpException, IOException {
public List<Map<String,Object>> queryTheGantryDataByPileNumber(String startDate,String stakeMark) throws HttpException, IOException {
if (stakeMark != null) {
//处理URl地址栏获取参数+号消失
stakeMark= stakeMark.replace(" ", "+");
}
List<Map<String,Object>> mapList =new ArrayList<>();
DcFacility dcFacilityAll = new DcFacility();
dcFacilityAll.setFacilityType(10);
List<DcFacility> dcFacilityList = facilityService.listFacility(dcFacilityAll);
DcFacility nearestFacility = findNearestFacility(dcFacilityList,stakeMark);
OkHttp okHttp = new OkHttp();
RequestParams requestParams = new RequestParams();
@ -845,41 +878,51 @@ public class DcTrafficStatisticsServiceImpl implements IDcTrafficStatisticsServi
ResponseBody body = response.body();
if (body != null) {
JSONArray jsonArray = JSON.parseArray(body.string());
// 使用HashMap来分组并求和
List<Map<String, Object>> list = new ArrayList();
for (Object item : jsonArray) { // 这里做了微调,直接遍历jsonArray的Object
System.out.println(jsonArray);
for (Object item : jsonArray) {
JSONObject jsonObject = (JSONObject) item;
// 获取当前时间
LocalTime now = LocalTime.now();
// 获取当前小时数(24小时制)
int currentHour = now.getHour();
if (jsonObject.getInteger("data_hour") == 16) {
Map<String,Object> sumByName = new HashMap<>();
String name = jsonObject.getString("gantry_name"); // 更安全的取值方式
int totalFlow = jsonObject.getInteger("total_flow"); // 专门针对Integer类型
String gantryId = jsonObject.getString("gantry_id"); // 专门针对Integer类型
String data_hour = jsonObject.getString("data_hour"); // 专门针对Integer类型
sumByName.put("naame", name);
sumByName.put("gantryId", gantryId);
sumByName.put("totalFlow", totalFlow);
sumByName.put("data_hour", data_hour);
list.add(sumByName);
if (jsonObject.getString("gantry_id").equals(nearestFacility.getFacilityCode())) {
Map<String, Object> map = new HashMap<>();
int totalFlow = jsonObject.getInteger("total_flow");
int data_hour = jsonObject.getInteger("data_hour");
map.put("hour",data_hour);
map.put("totalFlow",totalFlow);
mapList.add(map);
}
}
// 输出结果
return jsonArray;
return mapList;
}
return null;
}
*/
public DcFacility findNearestFacility(List<DcFacility> dcFacilityList, String stakeMarkCode) {
// 将目标桩号转换为整数,以便比较
int targetCodeAsInt = Integer.parseInt(extract(stakeMarkCode));
DcFacility nearestFacility = null;
int minDistance = Integer.MAX_VALUE; // 初始化为最大整数值,确保任何实际距离都会小于这个值
for (DcFacility facility : dcFacilityList) {
// 假设每个DcFacility对象中有一个方法或直接字段可以获取处理后的桩号字符串
String stakeMark = facility.getStakeMark(); // 请替换为实际的getter方法名
// 将当前设施的桩号转换为整数
int currentCodeAsInt = Integer.parseInt(extract(stakeMark));
// 计算与目标桩号的距离(差值的绝对值)
int distance = Math.abs(targetCodeAsInt - currentCodeAsInt);
// 如果当前桩号比之前记录的最近桩号更近,则更新最近桩号
if (distance < minDistance) {
minDistance = distance;
nearestFacility = facility;
}
}
return nearestFacility; // 返回最近的桩号信息
}
}

Loading…
Cancel
Save