package com.shkpr.service.aimodelpower.bizmgr; import com.global.base.log.LogLevelFlag; import com.global.base.log.LogPrintMgr; import com.global.base.tools.FastJsonUtil; import com.shkpr.service.aimodelpower.commtools.TimeTool; import com.shkpr.service.aimodelpower.dbdao.DBMgrProxy; import com.shkpr.service.aimodelpower.dbdao.shizilaishuiDataSource.service.intef.WaterCollecationService; import com.shkpr.service.aimodelpower.dbdao.shizilaishuiDataSource.service.intef.WaterTapWaterService; import com.shkpr.service.aimodelpower.dto.ResponseCode; import com.shkpr.service.aimodelpower.dto.ResponseRes; import com.shkpr.service.aimodelpower.dto.TraceRunnable; import com.shkpr.service.aimodelpower.dto.zilaishuiModel.InPumpModel; import com.shkpr.service.aimodelpower.globalmgr.ThreadTaskMgr; import com.shkpr.service.aimodelpower.globalmgr.TraceLogMgr; import com.shkpr.service.aimodelpower.jsonbean.zilaishui.JPTbMHourWater; import com.shkpr.service.aimodelpower.jsonbean.zilaishui.JPTbMWater; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.YearMonth; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Collectors; /** * @ClassName KprAimWaterCollecationBizFun * @Description: TODO * @Author LX * @Date 2024/5/27 * @Version V1.0 **/ public class KprAimWaterCollecationBizFun { private static final String MSG_SUCCESS = "success."; private static final String MSG_FAILED = "failed."; private static final String mStrClassName = "KprAimTapWaterBizFun"; private static final String EMPTY_NULL = "NULL"; public static WaterCollecationService getWaterTapWaterApi(){ return DBMgrProxy.getInstance().applyWaterCollecationService(); } public static WaterTapWaterService getWaterTapApi(){ return DBMgrProxy.getInstance().applyWaterTapWaterService(); } static DateTimeFormatter formater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); static DateTimeFormatter formater2 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); //TODO 查询日取水量预测接口 /** * 1.传入水厂Id及起止日期(日期格式为YYYY-MM-DD),返回日期内,每天的预测取水量数据和实际取水量数据 * 2.同时返回指定截止日期之后,未来4天的预测水量数据和实际水量(如没有,则返回为空数据) */ public static ResponseRes selectTbWaterList(JPTbMWater jpTbMWater){ ResponseRes responseRes = new ResponseRes(); List> list =new ArrayList<>(); Map map = new HashMap<>(); map.put("ID",null); map.put("Date",null); map.put("Max_temperature",null); map.put("Min_temperature",null); map.put("Weather",null); map.put("Month",null); map.put("Week",null); map.put("Holiday",null); map.put("LastActualWaterWithdrawals",null); map.put("LastActualWaterSupply",null); map.put("ActualWaterWithdrawals",null); map.put("ActualWaterSupply",null); map.put("ForecastWaterWithdrawals",null); map.put("ForecastActualWaterSupply",null); map.put("isAbnormal",null); map.put("isForecast",null); map.put("LastModifyTime",null); list.add(map); responseRes.setResdata(list); responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode()); responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg()); try { // List> resList = getWaterTapWaterApi().getTbMWater(jpTbMWater.getIsPage(), jpTbMWater.getLimit(), jpTbMWater.getOffset(), jpTbMWater.getForDateStr()); if(!CollectionUtils.isEmpty(resList)){ responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode()); responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg()); responseRes.setResdata(resList); } return responseRes; }catch(Exception ex){ responseRes.setResdata(null); responseRes.setResmsg(ResponseCode.RESULT_BAD.toStrMsg()); responseRes.setRescode(ResponseCode.RESULT_BAD.toStrCode()); return responseRes; } } //TODO 小时取水量预测接口 /** * 传入水厂id及日期,返回指定日期内的小时取水量预测数据和实际小时取水量数据 */ public static ResponseRes selectTbHourWaterList(JPTbMHourWater jpTbMHourWater){ ResponseRes responseRes = new ResponseRes(); List> list =new ArrayList<>(); Map map = new HashMap<>(); map.put("ID",null); map.put("Date",null); map.put("Hour",null); map.put("HourForecastWaterWithdrawals",null); map.put("HourForecastActualWaterSupply",null); map.put("WaterWithdrawalsEnergy",null); map.put("WaterSupplyEnergy",null); map.put("RealWaterWithdrawalsEnergy",null); map.put("RealWaterSupplyEnergy",null); map.put("LastModifyTime",null); map.put("HourActualWaterWithdrawals",null); map.put("HourActualWaterSupply ",null); list.add(map); responseRes.setResdata(list); responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode()); responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg()); try { // List> resList = getWaterTapWaterApi().getTbMHourwater(jpTbMHourWater.getIsPage(), jpTbMHourWater.getLimit(), jpTbMHourWater.getOffset(), jpTbMHourWater.getForDateStr()); if(!CollectionUtils.isEmpty(resList)){ responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode()); responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg()); responseRes.setResdata(resList); } return responseRes; }catch(Exception ex){ responseRes.setResdata(null); responseRes.setResmsg(ResponseCode.RESULT_BAD.toStrMsg()); responseRes.setRescode(ResponseCode.RESULT_BAD.toStrCode()); return responseRes; } } //TODO 小时取水泵房电耗预测接口 /** * 传入水厂id及日期 */ public static ResponseRes selectTbMHourwaterWaterwithdrawals(JPTbMHourWater jpTbMHourWater,String subType){ ResponseRes responseRes = new ResponseRes(); //TODO 默认值 List defaultModels = new ArrayList<>(); InPumpModel entity = new InPumpModel(); entity.setOrgId(null); entity.setPumpId(null); entity.setSubType(subType); List> defaultRes = new ArrayList<>(); Map map = new HashMap<>(); map.put("ID",null); map.put("Date",null); map.put("Hour",null); map.put("PumpID",null); map.put("PumpStatus",null); map.put("HourForecastWaterWithdrawals",null); map.put("PumpWater",null); map.put("RealPumpStatus",null); map.put("PumpEnergy",null); map.put("RealPumpEnergy",null); map.put("LastModifyTime",null); map.put("orgId",null); defaultRes.add(map); defaultModels.add(entity); responseRes.setResdata(defaultModels); responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode()); responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg()); try { List> resList = getWaterTapWaterApi().getTbMHourwaterWaterwithdrawals(jpTbMHourWater.getIsPage(), jpTbMHourWater.getLimit(), jpTbMHourWater.getOffset(), jpTbMHourWater.getForDateStr()); //TODO 按水厂分组 Map>> groupedData = resList.stream().collect(Collectors.groupingBy(item -> item.get("orgId"))); //TODO 查询水厂的取水泵,然后将数据拼接 List inPumpModels = new ArrayList<>(); for (Object key:groupedData.keySet()) { InPumpModel model = new InPumpModel(); List> zoonList = getWaterTapWaterApi().getZoonInfoList(key.toString(),subType); if(!CollectionUtils.isEmpty(zoonList)){ model.setPumpId(zoonList.get(0).get("uid").toString()); } model.setOrgId(key.toString()); model.setSubType(subType); List> dataList = groupedData.get(key); //TODO 将年月日时作为分组条件 Map>> dataMap = dataList.stream() .collect(Collectors.groupingBy(emp -> emp.get("Date") + " " + emp.get("Hour") // 创建复合键 )); model.setDataList(dataMap); //TODO 查询相应方案数据 List> drawalsList = getWaterTapWaterApi().getTbMWaterwithdrawalspump(false, 20,0," AND orgId = '"+key.toString()+"'"); model.setDrawalsList(drawalsList); inPumpModels.add(model); } if(!CollectionUtils.isEmpty(inPumpModels)){ responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode()); responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg()); responseRes.setResdata(inPumpModels); } return responseRes; }catch(Exception ex){ responseRes.setResdata(null); responseRes.setResmsg(ResponseCode.RESULT_BAD.toStrMsg()); responseRes.setRescode(ResponseCode.RESULT_BAD.toStrCode()); return responseRes; } } //TODO 小时供水泵房电耗预测接口 /** * 传入水厂id及日期 */ public static ResponseRes selectTbMHourwaterWatersupply(JPTbMHourWater jpTbMHourWater,String subType){ ResponseRes responseRes = new ResponseRes(); //TODO 默认值 List defaultModels = new ArrayList<>(); InPumpModel entity = new InPumpModel(); entity.setOrgId(null); entity.setPumpId(null); entity.setSubType(subType); List> defaultRes = new ArrayList<>(); Map map = new HashMap<>(); map.put("ID",null); map.put("Date",null); map.put("Hour",null); map.put("PumpID",null); map.put("PumpStatus",null); map.put("HourForecastActualWaterSupply",null); map.put("PumpWater",null); map.put("RealPumpStatus",null); map.put("PumpEnergy",null); map.put("RealPumpEnergy",null); map.put("LastModifyTime",null); map.put("orgId",null); defaultRes.add(map); defaultModels.add(entity); responseRes.setResdata(defaultModels); responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode()); responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg()); try { // List> resList = getWaterTapWaterApi().getTbMHourwaterWatersupply(jpTbMHourWater.getIsPage(), jpTbMHourWater.getLimit(), jpTbMHourWater.getOffset(), jpTbMHourWater.getForDateStr()); //TODO 按水厂分组 Map>> groupedData = resList.stream().collect(Collectors.groupingBy(item -> item.get("orgId"))); //TODO 查询水厂的取水泵,然后将数据拼接 List inPumpModels = new ArrayList<>(); for (Object key:groupedData.keySet()) { InPumpModel model = new InPumpModel(); List> zoonList = getWaterTapWaterApi().getZoonInfoList(key.toString(),subType); if(!CollectionUtils.isEmpty(zoonList)){ model.setPumpId(zoonList.get(0).get("uid").toString()); } model.setOrgId(key.toString()); model.setSubType(subType); List> dataList = groupedData.get(key); //TODO 将年月日时作为分组条件 Map>> dataMap = dataList.stream() .collect(Collectors.groupingBy(emp -> emp.get("Date") + " " + emp.get("Hour") // 创建复合键 )); model.setDataList(dataMap); //TODO 查询相应方案数据 List> drawalsList = getWaterTapWaterApi().getTbMWatersupplypump(false, 20,0," AND orgId = '"+key.toString()+"'"); model.setDrawalsList(drawalsList); inPumpModels.add(model); } if(!CollectionUtils.isEmpty(inPumpModels)){ responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode()); responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg()); responseRes.setResdata(inPumpModels); } return responseRes; }catch(Exception ex){ responseRes.setResdata(null); responseRes.setResmsg(ResponseCode.RESULT_BAD.toStrMsg()); responseRes.setRescode(ResponseCode.RESULT_BAD.toStrCode()); return responseRes; } } //TODO 定时任务 定时添加预测数据 public static void insertYuceDataScheduled(String monthNow){ System.out.println("添加预测日数据正在进行"+ TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT)); try { //先获取配置项 根据配置项来进行逻辑添加 List> configRes = getWaterTapWaterApi().getWaterYuceConfig(false, 0, 0, ""); if(!CollectionUtils.isEmpty(configRes)){ Map config = configRes.get(0); Integer isMonth = Integer.valueOf(config.get("is_month").toString());//是否预测指定月份 0 是 1否(判定是否走自添加逻辑) String month = config.get("month").toString();//指定预测年月 yyyy-mm Double randomCode = Double.valueOf(config.get("random_code").toString());//上下随机石百分比范围 if(isMonth==0){ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String yearStr = month.split("-")[0]; String monthStr = month.split("-")[1]; if(!StringUtils.isEmpty(monthNow)){ yearStr = monthNow.split("-")[0]; monthStr = monthNow.split("-")[1]; } LocalDateTime startDate = LocalDateTime.now().withYear(Integer.valueOf(yearStr)) .withMonth(Integer.valueOf(monthStr)).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0); LocalDateTime endDate = startDate.with(TemporalAdjusters.lastDayOfMonth()); //TODO 总体逻辑: 先查询指定月上一年的每日平均值,再按平均值的上下啊百分比去插入指定的浮动百分比数据 List> configList = getWaterTapApi().getWaterCollectionConfigList(null); List> orgConfig = getWaterTapWaterApi().getOrgConfig(false,0,0,""); if (!CollectionUtils.isEmpty(configList)&&!CollectionUtils.isEmpty(orgConfig)) { //TODO 按照组织机构分组 Map>> groupedData = configList.stream().collect(Collectors.groupingBy(item -> item.get("org_name"))); final CountDownLatch latch = new CountDownLatch(groupedData.keySet().size()); for (Object key:groupedData.keySet()){ try { ThreadTaskMgr.runTask(new TraceRunnable(TraceLogMgr.getTraceId()) { @Override public void function() { //TODO ①计算水厂指定月每日平均值 List> recordAllRes = getWaterTapApi() .getWaterCollectionRecordAllListAll(" WHERE 1=1 " + " AND org_name = '"+key.toString()+"'" + " AND \"time\"::timestamp BETWEEN '"+startDate.format(formatter)+"' "+"AND '"+endDate.format(formatter)+"'"); if(!CollectionUtils.isEmpty(recordAllRes)){ int days = YearMonth.from(startDate).lengthOfMonth();//获取月份天数 Double numAge = 0.0;//日平均值 Double numMonthAll = null;//月总值 for (int i = 1;i<=days;i++){ LocalDateTime dateNow = startDate.withDayOfMonth(i);//当前循环时间 Double numAll = null;//日总值 //TODO 筛选成当前循环时间的集合 List> daysRecord = recordAllRes.stream().filter(item -> LocalDateTime.parse(item.get("time").toString(),formatter).toLocalDate().equals(dateNow.toLocalDate())) .collect(Collectors.toList()); for (Map mapEntity : daysRecord){ //TODO 筛选与当前天一样的数据在计算平均值,数据相加除以24小时 (recordAllRes内容为这天每小时的数据) if(numAll == null){ numAll = 0.0; } numAll += Double.valueOf(mapEntity.get("value").toString()); } if(numMonthAll==null){ numMonthAll = 0.0; } numMonthAll+= numAll==null?0.0:numAll; } if(numMonthAll!=null){ numAge = numMonthAll/days; } //TODO ②正式插入或修改日预测数据表 Optional orgIdOptional = orgConfig.stream() .filter(item -> key.toString().replace("(", "(").replace(")", ")") .equals(item.get("org_name").toString().replace("(", "(").replace(")", ")"))) .map(item -> item.get("org_id").toString()) .findFirst(); String orgId = orgIdOptional.orElse(null); if (!StringUtils.isEmpty(orgId)) { //预测比对时间如果不是今年,则变为今年的时间 for (int i = 1;i<=days;i++) { LocalDateTime dateNow = startDate.withDayOfMonth(i);//当前循环时间 Double numAll = null;//日总值 //TODO 筛选成当前循环时间的集合 List> daysRecord = recordAllRes.stream().filter(item -> LocalDateTime.parse(item.get("time").toString(),formatter).toLocalDate().equals(dateNow.toLocalDate())) .collect(Collectors.toList()); for (Map mapEntity : daysRecord){ //TODO 筛选与当前天一样的数据在计算平均值,数据相加除以24小时 (recordAllRes内容为这天每小时的数据) if(numAll == null){ numAll = 0.0; } numAll += Double.valueOf(mapEntity.get("value").toString()); } //TODO 数据库操作 Map recordAllEntity = new LinkedHashMap<>();//需要添加的实体数据,此处要用有序map DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); recordAllEntity.put("Date", dateNow.withYear(LocalDateTime.now().getYear()).toLocalDate().format(formatter2)); recordAllEntity.put("Month", dateNow.withYear(LocalDateTime.now().getYear()).getMonth().getValue()); recordAllEntity.put("Week", dateNow.withYear(LocalDateTime.now().getYear()).getDayOfWeek().getValue()); recordAllEntity.put("ActualWaterWithdrawals", ""); //实际从该时间查询结果中得出(当前年当前日的实际数据) String newStartDate = dateNow.withYear(LocalDateTime.now().getYear()).format(formatter); String newEndDate = dateNow.withYear(LocalDateTime.now().getYear()).minusDays(-1).minusSeconds(1).format(formatter); List> newRecordAllRes = getWaterTapApi() .getWaterCollectionRecordAllListAll(" WHERE 1=1 " + " AND org_name = '"+key.toString()+"'" + " AND \"time\"::timestamp BETWEEN '"+newStartDate +"' "+"AND '"+newEndDate+"'"); String actualWaterSupply = null; if(!CollectionUtils.isEmpty(newRecordAllRes)){ actualWaterSupply = String.valueOf(newRecordAllRes.stream() .mapToDouble(record -> { Object value = record.get("value"); if (value instanceof Number) { return ((Number) value).doubleValue(); } else if (value instanceof String) { try { return Double.parseDouble((String) value); } catch (NumberFormatException e) { // 处理或记录错误,这里简单返回0 return 0; } } return 0; }) .sum()); } recordAllEntity.put("ActualWaterSupply", actualWaterSupply); recordAllEntity.put("ForecastWaterWithdrawals", ""); //TODO 随机数逻辑 int randomUpOrDown = ThreadLocalRandom.current().nextInt(2);//随机向上或者向下 0表示向下 1表示向上 Double randomWater = randomUpOrDown == 0 ? numAge - (numAge * (randomCode / 100)) : numAge + (numAge * (randomCode / 100)); recordAllEntity.put("ForecastActualWaterSupply", randomWater); recordAllEntity.put("isAbnormal", 0); recordAllEntity.put("isForecast", 0); recordAllEntity.put("LastModifyTime", LocalDateTime.now().format(formatter)); // 如果找到了org_id,就将其赋值给orgId,否则orgId为null recordAllEntity.put("orgId", orgId); //TODO 添加or修改 Integer insertRes = getWaterTapApi().insertOrUpdateTbmWater(recordAllEntity); if (insertRes < 1) { LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR , mStrClassName , mStrClassName , String.format("Batch insertYuceDataScheduled ERROR:{%s} ", "新增或修改失败")); } } } } latch.countDown(); } }); }catch(Exception ex){ LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR , mStrClassName , mStrClassName , String.format("Batch insertYuceDataScheduled ERROR:{%s} ", ex.getLocalizedMessage())); } } try{latch.await();}catch(Exception ex){} } System.out.println("添加预测日数据结束"+ TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT)); }else{ } } }catch(Exception ex){ ex.printStackTrace(); } } //TODO 定时任务 定时添加小时预测数据 public static void insertYuceHourDataScheduled(String monthNow){ System.out.println("添加预测小时数据正在进行"+ TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT)); try { //先获取配置项 根据配置项来进行逻辑添加 List> configRes = getWaterTapWaterApi().getWaterYuceConfig(false, 0, 0, ""); if(!CollectionUtils.isEmpty(configRes)){ Map config = configRes.get(0); Integer isMonth = Integer.valueOf(config.get("is_month").toString());//是否预测指定月份 0 是 1否(判定是否走自添加逻辑) String month = config.get("month").toString();//指定预测年月 yyyy-mm Double randomCode = Double.valueOf(config.get("random_code").toString());//上下随机石百分比范围 if(isMonth==0){ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String yearStr = month.split("-")[0]; String monthStr = month.split("-")[1]; if(!StringUtils.isEmpty(monthNow)){ yearStr = monthNow.split("-")[0]; monthStr = monthNow.split("-")[1]; } LocalDateTime startDate = LocalDateTime.now().withYear(Integer.valueOf(yearStr)) .withMonth(Integer.valueOf(monthStr)).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0); LocalDateTime endDate = startDate.with(TemporalAdjusters.lastDayOfMonth()); //TODO 总体逻辑: 先查询指定月上一年的每日平均值,再按平均值的上下啊百分比去插入指定的浮动百分比数据 List> configList = getWaterTapApi().getWaterCollectionConfigList(null); List> orgConfig = getWaterTapWaterApi().getOrgConfig(false,0,0,""); if (!CollectionUtils.isEmpty(configList)&&!CollectionUtils.isEmpty(orgConfig)) { //TODO 按照组织机构分组 Map>> groupedData = configList.stream().collect(Collectors.groupingBy(item -> item.get("org_name"))); final CountDownLatch latch = new CountDownLatch(groupedData.keySet().size()); for (Object key:groupedData.keySet()){ try { ThreadTaskMgr.runTask(new TraceRunnable(TraceLogMgr.getTraceId()) { @Override public void function() { //TODO ①计算水厂指定月每日小时平均值 List> recordAllRes = getWaterTapApi() .getWaterCollectionRecordAllListAll(" WHERE 1=1 " + " AND org_name = '"+key.toString()+"'" + " AND \"time\"::timestamp BETWEEN '"+startDate.format(formatter)+"' "+"AND '"+endDate.format(formatter)+"'"); if(!CollectionUtils.isEmpty(recordAllRes)){ int days = YearMonth.from(startDate).lengthOfMonth();//获取月份天数 for (int i = 1;i<=days;i++){ LocalDateTime dateNow = startDate.withDayOfMonth(i);//当前循环时间 Double numAll = null;//日总值 Double numAge = 0.0;//日小时平均值 //TODO 筛选成当前循环时间的集合 List> daysRecord = recordAllRes.stream().filter(item -> LocalDateTime.parse(item.get("time").toString(),formatter).toLocalDate().equals(dateNow.toLocalDate())) .collect(Collectors.toList()); for (Map mapEntity : daysRecord){ //TODO 筛选与当前天一样的数据在计算平均值,数据相加除以24小时 (recordAllRes内容为这天每小时的数据) if(numAll == null){ numAll = 0.0; } numAll += Double.valueOf(mapEntity.get("value").toString()); } if (numAll!=null){ numAge = numAll/24; } //TODO ②正式插入或修改日预测数据表 Optional orgIdOptional = orgConfig.stream() .filter(item -> key.toString().replace("(", "(").replace(")", ")") .equals(item.get("org_name").toString().replace("(", "(").replace(")", ")"))) .map(item -> item.get("org_id").toString()) .findFirst(); String orgId = orgIdOptional.orElse(null); if (!StringUtils.isEmpty(orgId)) { //预测比对时间如果不是今年,则变为今年的时间 //TODO 一天24小时 for (int j = 0;j<24;j++) { //TODO 数据库操作 Map recordAllEntity = new LinkedHashMap<>();//需要添加的实体数据,此处要用有序map DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); recordAllEntity.put("Date", dateNow.withYear(LocalDateTime.now().getYear()).toLocalDate().format(formatter2)); // 创建一个LocalTime实例,设置为指定小时,分钟和秒数为0 LocalTime time = LocalTime.of(j, 0, 0); // 创建一个DateTimeFormatter用于格式化时间 DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("HH:mm:ss"); recordAllEntity.put("Hour", time.format(formatter3)); recordAllEntity.put("HourForecastWaterWithdrawals", null); //TODO 随机数逻辑 int randomUpOrDown = ThreadLocalRandom.current().nextInt(2);//随机向上或者向下 0表示向下 1表示向上 Double randomWater = randomUpOrDown == 0 ? numAge - (numAge * (randomCode / 100)) : numAge + (numAge * (randomCode / 100)); recordAllEntity.put("HourForecastActualWaterSupply", randomWater); recordAllEntity.put("HourActualWaterWithdrawals", ""); //实际从该时间查询结果中得出 List> newRecordAllRes = getWaterTapApi() .getWaterCollectionRecordAllListAll(" WHERE 1=1 " + " AND org_name = '"+key.toString()+"'" + " AND \"time\" = '"+dateNow.withYear(LocalDateTime.now().getYear()).withHour(j).format(formatter)+"' "); String hourActualWaterSupply = null; if(!CollectionUtils.isEmpty(newRecordAllRes)){ hourActualWaterSupply = newRecordAllRes.get(0).get("value").toString(); } recordAllEntity.put("HourActualWaterSupply",hourActualWaterSupply); recordAllEntity.put("LastModifyTime", LocalDateTime.now().format(formatter)); // 如果找到了org_id,就将其赋值给orgId,否则orgId为null recordAllEntity.put("orgId", orgId); //TODO 添加or修改 Integer insertRes = getWaterTapApi().insertOrUpdateTbmHourWater(recordAllEntity); if (insertRes < 1) { LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR , mStrClassName , mStrClassName , String.format("Batch insertYuceDataScheduled ERROR:{%s} ", "新增或修改失败")); } } } } } latch.countDown(); } }); }catch(Exception ex){ LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR , mStrClassName , mStrClassName , String.format("Batch insertYuceDataScheduled ERROR:{%s} ", ex.getLocalizedMessage())); } } try{latch.await();}catch(Exception ex){} } System.out.println("添加预测小时数据结束"+ TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT)); }else{ } } }catch(Exception ex){ ex.printStackTrace(); } } }