KprAimWaterCollecationBizFun.java 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. package com.shkpr.service.aimodelpower.bizmgr;
  2. import com.global.base.log.LogLevelFlag;
  3. import com.global.base.log.LogPrintMgr;
  4. import com.global.base.tools.FastJsonUtil;
  5. import com.shkpr.service.aimodelpower.commtools.TimeTool;
  6. import com.shkpr.service.aimodelpower.dbdao.DBMgrProxy;
  7. import com.shkpr.service.aimodelpower.dbdao.shizilaishuiDataSource.service.intef.WaterCollecationService;
  8. import com.shkpr.service.aimodelpower.dbdao.shizilaishuiDataSource.service.intef.WaterTapWaterService;
  9. import com.shkpr.service.aimodelpower.dto.ResponseCode;
  10. import com.shkpr.service.aimodelpower.dto.ResponseRes;
  11. import com.shkpr.service.aimodelpower.dto.TraceRunnable;
  12. import com.shkpr.service.aimodelpower.dto.zilaishuiModel.InPumpModel;
  13. import com.shkpr.service.aimodelpower.globalmgr.ThreadTaskMgr;
  14. import com.shkpr.service.aimodelpower.globalmgr.TraceLogMgr;
  15. import com.shkpr.service.aimodelpower.jsonbean.zilaishui.JPTbMHourWater;
  16. import com.shkpr.service.aimodelpower.jsonbean.zilaishui.JPTbMWater;
  17. import org.springframework.util.CollectionUtils;
  18. import org.springframework.util.StringUtils;
  19. import java.io.File;
  20. import java.io.FileInputStream;
  21. import java.io.FileNotFoundException;
  22. import java.io.InputStream;
  23. import java.time.LocalDateTime;
  24. import java.time.LocalTime;
  25. import java.time.YearMonth;
  26. import java.time.format.DateTimeFormatter;
  27. import java.time.temporal.TemporalAdjusters;
  28. import java.util.*;
  29. import java.util.concurrent.CountDownLatch;
  30. import java.util.concurrent.ThreadLocalRandom;
  31. import java.util.stream.Collectors;
  32. /**
  33. * @ClassName KprAimWaterCollecationBizFun
  34. * @Description: TODO
  35. * @Author LX
  36. * @Date 2024/5/27
  37. * @Version V1.0
  38. **/
  39. public class KprAimWaterCollecationBizFun {
  40. private static final String MSG_SUCCESS = "success.";
  41. private static final String MSG_FAILED = "failed.";
  42. private static final String mStrClassName = "KprAimTapWaterBizFun";
  43. private static final String EMPTY_NULL = "NULL";
  44. public static WaterCollecationService getWaterTapWaterApi(){
  45. return DBMgrProxy.getInstance().applyWaterCollecationService();
  46. }
  47. public static WaterTapWaterService getWaterTapApi(){
  48. return DBMgrProxy.getInstance().applyWaterTapWaterService();
  49. }
  50. static DateTimeFormatter formater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  51. static DateTimeFormatter formater2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  52. //TODO 查询日取水量预测接口
  53. /**
  54. * 1.传入水厂Id及起止日期(日期格式为YYYY-MM-DD),返回日期内,每天的预测取水量数据和实际取水量数据
  55. * 2.同时返回指定截止日期之后,未来4天的预测水量数据和实际水量(如没有,则返回为空数据)
  56. */
  57. public static ResponseRes selectTbWaterList(JPTbMWater jpTbMWater){
  58. ResponseRes responseRes = new ResponseRes();
  59. List<Map<String,Object>> list =new ArrayList<>();
  60. Map<String,Object> map = new HashMap<>();
  61. map.put("ID",null);
  62. map.put("Date",null);
  63. map.put("Max_temperature",null);
  64. map.put("Min_temperature",null);
  65. map.put("Weather",null);
  66. map.put("Month",null);
  67. map.put("Week",null);
  68. map.put("Holiday",null);
  69. map.put("LastActualWaterWithdrawals",null);
  70. map.put("LastActualWaterSupply",null);
  71. map.put("ActualWaterWithdrawals",null);
  72. map.put("ActualWaterSupply",null);
  73. map.put("ForecastWaterWithdrawals",null);
  74. map.put("ForecastActualWaterSupply",null);
  75. map.put("isAbnormal",null);
  76. map.put("isForecast",null);
  77. map.put("LastModifyTime",null);
  78. list.add(map);
  79. responseRes.setResdata(list);
  80. responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode());
  81. responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg());
  82. try {
  83. //
  84. List<Map<String, Object>> resList = getWaterTapWaterApi().getTbMWater(jpTbMWater.getIsPage(),
  85. jpTbMWater.getLimit(), jpTbMWater.getOffset(), jpTbMWater.getForDateStr());
  86. if(!CollectionUtils.isEmpty(resList)){
  87. responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode());
  88. responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg());
  89. responseRes.setResdata(resList);
  90. }
  91. return responseRes;
  92. }catch(Exception ex){
  93. responseRes.setResdata(null);
  94. responseRes.setResmsg(ResponseCode.RESULT_BAD.toStrMsg());
  95. responseRes.setRescode(ResponseCode.RESULT_BAD.toStrCode());
  96. return responseRes;
  97. }
  98. }
  99. //TODO 小时取水量预测接口
  100. /**
  101. * 传入水厂id及日期,返回指定日期内的小时取水量预测数据和实际小时取水量数据
  102. */
  103. public static ResponseRes selectTbHourWaterList(JPTbMHourWater jpTbMHourWater){
  104. ResponseRes responseRes = new ResponseRes();
  105. List<Map<String,Object>> list =new ArrayList<>();
  106. Map<String,Object> map = new HashMap<>();
  107. map.put("ID",null);
  108. map.put("Date",null);
  109. map.put("Hour",null);
  110. map.put("HourForecastWaterWithdrawals",null);
  111. map.put("HourForecastActualWaterSupply",null);
  112. map.put("WaterWithdrawalsEnergy",null);
  113. map.put("WaterSupplyEnergy",null);
  114. map.put("RealWaterWithdrawalsEnergy",null);
  115. map.put("RealWaterSupplyEnergy",null);
  116. map.put("LastModifyTime",null);
  117. map.put("HourActualWaterWithdrawals",null);
  118. map.put("HourActualWaterSupply ",null);
  119. list.add(map);
  120. responseRes.setResdata(list);
  121. responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode());
  122. responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg());
  123. try {
  124. //
  125. List<Map<String, Object>> resList = getWaterTapWaterApi().getTbMHourwater(jpTbMHourWater.getIsPage(),
  126. jpTbMHourWater.getLimit(), jpTbMHourWater.getOffset(), jpTbMHourWater.getForDateStr());
  127. if(!CollectionUtils.isEmpty(resList)){
  128. responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode());
  129. responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg());
  130. responseRes.setResdata(resList);
  131. }
  132. return responseRes;
  133. }catch(Exception ex){
  134. responseRes.setResdata(null);
  135. responseRes.setResmsg(ResponseCode.RESULT_BAD.toStrMsg());
  136. responseRes.setRescode(ResponseCode.RESULT_BAD.toStrCode());
  137. return responseRes;
  138. }
  139. }
  140. //TODO 小时取水泵房电耗预测接口
  141. /**
  142. * 传入水厂id及日期
  143. */
  144. public static ResponseRes selectTbMHourwaterWaterwithdrawals(JPTbMHourWater jpTbMHourWater,String subType){
  145. ResponseRes responseRes = new ResponseRes();
  146. //TODO 默认值
  147. List<InPumpModel> defaultModels = new ArrayList<>();
  148. InPumpModel entity = new InPumpModel();
  149. entity.setOrgId(null);
  150. entity.setPumpId(null);
  151. entity.setSubType(subType);
  152. List<Map<String, Object>> defaultRes = new ArrayList<>();
  153. Map<String,Object> map = new HashMap<>();
  154. map.put("ID",null);
  155. map.put("Date",null);
  156. map.put("Hour",null);
  157. map.put("PumpID",null);
  158. map.put("PumpStatus",null);
  159. map.put("HourForecastWaterWithdrawals",null);
  160. map.put("PumpWater",null);
  161. map.put("RealPumpStatus",null);
  162. map.put("PumpEnergy",null);
  163. map.put("RealPumpEnergy",null);
  164. map.put("LastModifyTime",null);
  165. map.put("orgId",null);
  166. defaultRes.add(map);
  167. defaultModels.add(entity);
  168. responseRes.setResdata(defaultModels);
  169. responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode());
  170. responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg());
  171. try {
  172. List<Map<String, Object>> resList = getWaterTapWaterApi().getTbMHourwaterWaterwithdrawals(jpTbMHourWater.getIsPage(),
  173. jpTbMHourWater.getLimit(), jpTbMHourWater.getOffset(), jpTbMHourWater.getForDateStr());
  174. //TODO 按水厂分组
  175. Map<Object, List<Map<String, Object>>> groupedData =
  176. resList.stream().collect(Collectors.groupingBy(item -> item.get("orgId")));
  177. //TODO 查询水厂的取水泵,然后将数据拼接
  178. List<InPumpModel> inPumpModels = new ArrayList<>();
  179. for (Object key:groupedData.keySet()) {
  180. InPumpModel model = new InPumpModel();
  181. List<Map<String,Object>> zoonList = getWaterTapWaterApi().getZoonInfoList(key.toString(),subType);
  182. if(!CollectionUtils.isEmpty(zoonList)){
  183. model.setPumpId(zoonList.get(0).get("uid").toString());
  184. }
  185. model.setOrgId(key.toString());
  186. model.setSubType(subType);
  187. List<Map<String, Object>> dataList = groupedData.get(key);
  188. //TODO 将年月日时作为分组条件
  189. Map<String, List<Map<String, Object>>> dataMap = dataList.stream()
  190. .collect(Collectors.groupingBy(emp ->
  191. emp.get("Date") + " " + emp.get("Hour") // 创建复合键
  192. ));
  193. model.setDataList(dataMap);
  194. //TODO 查询相应方案数据
  195. List<Map<String,Object>> drawalsList = getWaterTapWaterApi().getTbMWaterwithdrawalspump(false,
  196. 20,0," AND orgId = '"+key.toString()+"'");
  197. model.setDrawalsList(drawalsList);
  198. inPumpModels.add(model);
  199. }
  200. if(!CollectionUtils.isEmpty(inPumpModels)){
  201. responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode());
  202. responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg());
  203. responseRes.setResdata(inPumpModels);
  204. }
  205. return responseRes;
  206. }catch(Exception ex){
  207. responseRes.setResdata(null);
  208. responseRes.setResmsg(ResponseCode.RESULT_BAD.toStrMsg());
  209. responseRes.setRescode(ResponseCode.RESULT_BAD.toStrCode());
  210. return responseRes;
  211. }
  212. }
  213. //TODO 小时供水泵房电耗预测接口
  214. /**
  215. * 传入水厂id及日期
  216. */
  217. public static ResponseRes selectTbMHourwaterWatersupply(JPTbMHourWater jpTbMHourWater,String subType){
  218. ResponseRes responseRes = new ResponseRes();
  219. //TODO 默认值
  220. List<InPumpModel> defaultModels = new ArrayList<>();
  221. InPumpModel entity = new InPumpModel();
  222. entity.setOrgId(null);
  223. entity.setPumpId(null);
  224. entity.setSubType(subType);
  225. List<Map<String, Object>> defaultRes = new ArrayList<>();
  226. Map<String,Object> map = new HashMap<>();
  227. map.put("ID",null);
  228. map.put("Date",null);
  229. map.put("Hour",null);
  230. map.put("PumpID",null);
  231. map.put("PumpStatus",null);
  232. map.put("HourForecastActualWaterSupply",null);
  233. map.put("PumpWater",null);
  234. map.put("RealPumpStatus",null);
  235. map.put("PumpEnergy",null);
  236. map.put("RealPumpEnergy",null);
  237. map.put("LastModifyTime",null);
  238. map.put("orgId",null);
  239. defaultRes.add(map);
  240. defaultModels.add(entity);
  241. responseRes.setResdata(defaultModels);
  242. responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode());
  243. responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg());
  244. try {
  245. //
  246. List<Map<String, Object>> resList = getWaterTapWaterApi().getTbMHourwaterWatersupply(jpTbMHourWater.getIsPage(),
  247. jpTbMHourWater.getLimit(), jpTbMHourWater.getOffset(), jpTbMHourWater.getForDateStr());
  248. //TODO 按水厂分组
  249. Map<Object, List<Map<String, Object>>> groupedData =
  250. resList.stream().collect(Collectors.groupingBy(item -> item.get("orgId")));
  251. //TODO 查询水厂的取水泵,然后将数据拼接
  252. List<InPumpModel> inPumpModels = new ArrayList<>();
  253. for (Object key:groupedData.keySet()) {
  254. InPumpModel model = new InPumpModel();
  255. List<Map<String,Object>> zoonList = getWaterTapWaterApi().getZoonInfoList(key.toString(),subType);
  256. if(!CollectionUtils.isEmpty(zoonList)){
  257. model.setPumpId(zoonList.get(0).get("uid").toString());
  258. }
  259. model.setOrgId(key.toString());
  260. model.setSubType(subType);
  261. List<Map<String, Object>> dataList = groupedData.get(key);
  262. //TODO 将年月日时作为分组条件
  263. Map<String, List<Map<String, Object>>> dataMap = dataList.stream()
  264. .collect(Collectors.groupingBy(emp ->
  265. emp.get("Date") + " " + emp.get("Hour") // 创建复合键
  266. ));
  267. model.setDataList(dataMap);
  268. //TODO 查询相应方案数据
  269. List<Map<String,Object>> drawalsList = getWaterTapWaterApi().getTbMWatersupplypump(false,
  270. 20,0," AND orgId = '"+key.toString()+"'");
  271. model.setDrawalsList(drawalsList);
  272. inPumpModels.add(model);
  273. }
  274. if(!CollectionUtils.isEmpty(inPumpModels)){
  275. responseRes.setRescode(ResponseCode.RESULT_NORMAL.toStrCode());
  276. responseRes.setResmsg(ResponseCode.RESULT_NORMAL.toStrMsg());
  277. responseRes.setResdata(inPumpModels);
  278. }
  279. return responseRes;
  280. }catch(Exception ex){
  281. responseRes.setResdata(null);
  282. responseRes.setResmsg(ResponseCode.RESULT_BAD.toStrMsg());
  283. responseRes.setRescode(ResponseCode.RESULT_BAD.toStrCode());
  284. return responseRes;
  285. }
  286. }
  287. //TODO 定时任务 定时添加预测数据
  288. public static void insertYuceDataScheduled(String monthNow){
  289. System.out.println("添加预测日数据正在进行"+ TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT));
  290. try {
  291. //先获取配置项 根据配置项来进行逻辑添加
  292. List<Map<String, Object>> configRes = getWaterTapWaterApi().getWaterYuceConfig(false, 0, 0, "");
  293. if(!CollectionUtils.isEmpty(configRes)){
  294. Map<String,Object> config = configRes.get(0);
  295. Integer isMonth = Integer.valueOf(config.get("is_month").toString());//是否预测指定月份 0 是 1否(判定是否走自添加逻辑)
  296. String month = config.get("month").toString();//指定预测年月 yyyy-mm
  297. Double randomCode = Double.valueOf(config.get("random_code").toString());//上下随机石百分比范围
  298. if(isMonth==0){
  299. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  300. String yearStr = month.split("-")[0];
  301. String monthStr = month.split("-")[1];
  302. if(!StringUtils.isEmpty(monthNow)){
  303. yearStr = monthNow.split("-")[0];
  304. monthStr = monthNow.split("-")[1];
  305. }
  306. LocalDateTime startDate = LocalDateTime.now().withYear(Integer.valueOf(yearStr))
  307. .withMonth(Integer.valueOf(monthStr)).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
  308. LocalDateTime endDate = startDate.with(TemporalAdjusters.lastDayOfMonth());
  309. //TODO 总体逻辑: 先查询指定月上一年的每日平均值,再按平均值的上下啊百分比去插入指定的浮动百分比数据
  310. List<Map<String, Object>> configList = getWaterTapApi().getWaterCollectionConfigList(null);
  311. List<Map<String,Object>> orgConfig = getWaterTapWaterApi().getOrgConfig(false,0,0,"");
  312. if (!CollectionUtils.isEmpty(configList)&&!CollectionUtils.isEmpty(orgConfig)) {
  313. //TODO 按照组织机构分组
  314. Map<Object, List<Map<String, Object>>> groupedData =
  315. configList.stream().collect(Collectors.groupingBy(item -> item.get("org_name")));
  316. final CountDownLatch latch = new CountDownLatch(groupedData.keySet().size());
  317. for (Object key:groupedData.keySet()){
  318. try {
  319. ThreadTaskMgr.runTask(new TraceRunnable(TraceLogMgr.getTraceId()) {
  320. @Override
  321. public void function() {
  322. //TODO ①计算水厂指定月每日平均值
  323. List<Map<String,Object>> recordAllRes = getWaterTapApi()
  324. .getWaterCollectionRecordAllListAll(" WHERE 1=1 " +
  325. " AND org_name = '"+key.toString()+"'" +
  326. " AND \"time\"::timestamp BETWEEN '"+startDate.format(formatter)+"' "+"AND '"+endDate.format(formatter)+"'");
  327. if(!CollectionUtils.isEmpty(recordAllRes)){
  328. int days = YearMonth.from(startDate).lengthOfMonth();//获取月份天数
  329. Double numAge = 0.0;//日平均值
  330. Double numMonthAll = null;//月总值
  331. for (int i = 1;i<=days;i++){
  332. LocalDateTime dateNow = startDate.withDayOfMonth(i);//当前循环时间
  333. Double numAll = null;//日总值
  334. //TODO 筛选成当前循环时间的集合
  335. List<Map<String,Object>> daysRecord = recordAllRes.stream().filter(item ->
  336. LocalDateTime.parse(item.get("time").toString(),formatter).toLocalDate().equals(dateNow.toLocalDate()))
  337. .collect(Collectors.toList());
  338. for (Map<String,Object> mapEntity : daysRecord){
  339. //TODO 筛选与当前天一样的数据在计算平均值,数据相加除以24小时 (recordAllRes内容为这天每小时的数据)
  340. if(numAll == null){
  341. numAll = 0.0;
  342. }
  343. numAll += Double.valueOf(mapEntity.get("value").toString());
  344. }
  345. if(numMonthAll==null){
  346. numMonthAll = 0.0;
  347. }
  348. numMonthAll+= numAll==null?0.0:numAll;
  349. }
  350. if(numMonthAll!=null){
  351. numAge = numMonthAll/days;
  352. }
  353. //TODO ②正式插入或修改日预测数据表
  354. Optional<String> orgIdOptional = orgConfig.stream()
  355. .filter(item -> key.toString().replace("(", "(").replace(")", ")")
  356. .equals(item.get("org_name").toString().replace("(", "(").replace(")", ")")))
  357. .map(item -> item.get("org_id").toString())
  358. .findFirst();
  359. String orgId = orgIdOptional.orElse(null);
  360. if (!StringUtils.isEmpty(orgId)) {
  361. //预测比对时间如果不是今年,则变为今年的时间
  362. for (int i = 1;i<=days;i++) {
  363. LocalDateTime dateNow = startDate.withDayOfMonth(i);//当前循环时间
  364. Double numAll = null;//日总值
  365. //TODO 筛选成当前循环时间的集合
  366. List<Map<String,Object>> daysRecord = recordAllRes.stream().filter(item ->
  367. LocalDateTime.parse(item.get("time").toString(),formatter).toLocalDate().equals(dateNow.toLocalDate()))
  368. .collect(Collectors.toList());
  369. for (Map<String,Object> mapEntity : daysRecord){
  370. //TODO 筛选与当前天一样的数据在计算平均值,数据相加除以24小时 (recordAllRes内容为这天每小时的数据)
  371. if(numAll == null){
  372. numAll = 0.0;
  373. }
  374. numAll += Double.valueOf(mapEntity.get("value").toString());
  375. }
  376. //TODO 数据库操作
  377. Map<String, Object> recordAllEntity = new LinkedHashMap<>();//需要添加的实体数据,此处要用有序map
  378. DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  379. recordAllEntity.put("Date", dateNow.withYear(LocalDateTime.now().getYear()).toLocalDate().format(formatter2));
  380. recordAllEntity.put("Month", dateNow.withYear(LocalDateTime.now().getYear()).getMonth().getValue());
  381. recordAllEntity.put("Week", dateNow.withYear(LocalDateTime.now().getYear()).getDayOfWeek().getValue());
  382. recordAllEntity.put("ActualWaterWithdrawals", "");
  383. //实际从该时间查询结果中得出(当前年当前日的实际数据)
  384. String newStartDate = dateNow.withYear(LocalDateTime.now().getYear()).format(formatter);
  385. String newEndDate = dateNow.withYear(LocalDateTime.now().getYear()).minusDays(-1).minusSeconds(1).format(formatter);
  386. List<Map<String,Object>> newRecordAllRes = getWaterTapApi()
  387. .getWaterCollectionRecordAllListAll(" WHERE 1=1 " +
  388. " AND org_name = '"+key.toString()+"'" +
  389. " AND \"time\"::timestamp BETWEEN '"+newStartDate
  390. +"' "+"AND '"+newEndDate+"'");
  391. String actualWaterSupply = null;
  392. if(!CollectionUtils.isEmpty(newRecordAllRes)){
  393. actualWaterSupply = String.valueOf(newRecordAllRes.stream()
  394. .mapToDouble(record -> {
  395. Object value = record.get("value");
  396. if (value instanceof Number) {
  397. return ((Number) value).doubleValue();
  398. } else if (value instanceof String) {
  399. try {
  400. return Double.parseDouble((String) value);
  401. } catch (NumberFormatException e) {
  402. // 处理或记录错误,这里简单返回0
  403. return 0;
  404. }
  405. }
  406. return 0;
  407. })
  408. .sum());
  409. }
  410. recordAllEntity.put("ActualWaterSupply", actualWaterSupply);
  411. recordAllEntity.put("ForecastWaterWithdrawals", "");
  412. //TODO 随机数逻辑
  413. int randomUpOrDown = ThreadLocalRandom.current().nextInt(2);//随机向上或者向下 0表示向下 1表示向上
  414. Double randomWater = randomUpOrDown == 0 ?
  415. numAge - (numAge * (randomCode / 100)) :
  416. numAge + (numAge * (randomCode / 100));
  417. recordAllEntity.put("ForecastActualWaterSupply", randomWater);
  418. recordAllEntity.put("isAbnormal", 0);
  419. recordAllEntity.put("isForecast", 0);
  420. recordAllEntity.put("LastModifyTime", LocalDateTime.now().format(formatter));
  421. // 如果找到了org_id,就将其赋值给orgId,否则orgId为null
  422. recordAllEntity.put("orgId", orgId);
  423. //TODO 添加or修改
  424. Integer insertRes = getWaterTapApi().insertOrUpdateTbmWater(recordAllEntity);
  425. if (insertRes < 1) {
  426. LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR
  427. , mStrClassName
  428. , mStrClassName
  429. , String.format("Batch insertYuceDataScheduled ERROR:{%s} ",
  430. "新增或修改失败"));
  431. }
  432. }
  433. }
  434. }
  435. latch.countDown();
  436. }
  437. });
  438. }catch(Exception ex){
  439. LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR
  440. , mStrClassName
  441. , mStrClassName
  442. , String.format("Batch insertYuceDataScheduled ERROR:{%s} ",
  443. ex.getLocalizedMessage()));
  444. }
  445. }
  446. try{latch.await();}catch(Exception ex){}
  447. }
  448. System.out.println("添加预测日数据结束"+ TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT));
  449. }else{
  450. }
  451. }
  452. }catch(Exception ex){
  453. ex.printStackTrace();
  454. }
  455. }
  456. //TODO 定时任务 定时添加小时预测数据
  457. public static void insertYuceHourDataScheduled(String monthNow){
  458. System.out.println("添加预测小时数据正在进行"+ TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT));
  459. try {
  460. //先获取配置项 根据配置项来进行逻辑添加
  461. List<Map<String, Object>> configRes = getWaterTapWaterApi().getWaterYuceConfig(false, 0, 0, "");
  462. if(!CollectionUtils.isEmpty(configRes)){
  463. Map<String,Object> config = configRes.get(0);
  464. Integer isMonth = Integer.valueOf(config.get("is_month").toString());//是否预测指定月份 0 是 1否(判定是否走自添加逻辑)
  465. String month = config.get("month").toString();//指定预测年月 yyyy-mm
  466. Double randomCode = Double.valueOf(config.get("random_code").toString());//上下随机石百分比范围
  467. if(isMonth==0){
  468. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  469. String yearStr = month.split("-")[0];
  470. String monthStr = month.split("-")[1];
  471. if(!StringUtils.isEmpty(monthNow)){
  472. yearStr = monthNow.split("-")[0];
  473. monthStr = monthNow.split("-")[1];
  474. }
  475. LocalDateTime startDate = LocalDateTime.now().withYear(Integer.valueOf(yearStr))
  476. .withMonth(Integer.valueOf(monthStr)).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
  477. LocalDateTime endDate = startDate.with(TemporalAdjusters.lastDayOfMonth());
  478. //TODO 总体逻辑: 先查询指定月上一年的每日平均值,再按平均值的上下啊百分比去插入指定的浮动百分比数据
  479. List<Map<String, Object>> configList = getWaterTapApi().getWaterCollectionConfigList(null);
  480. List<Map<String,Object>> orgConfig = getWaterTapWaterApi().getOrgConfig(false,0,0,"");
  481. if (!CollectionUtils.isEmpty(configList)&&!CollectionUtils.isEmpty(orgConfig)) {
  482. //TODO 按照组织机构分组
  483. Map<Object, List<Map<String, Object>>> groupedData =
  484. configList.stream().collect(Collectors.groupingBy(item -> item.get("org_name")));
  485. final CountDownLatch latch = new CountDownLatch(groupedData.keySet().size());
  486. for (Object key:groupedData.keySet()){
  487. try {
  488. ThreadTaskMgr.runTask(new TraceRunnable(TraceLogMgr.getTraceId()) {
  489. @Override
  490. public void function() {
  491. //TODO ①计算水厂指定月每日小时平均值
  492. List<Map<String,Object>> recordAllRes = getWaterTapApi()
  493. .getWaterCollectionRecordAllListAll(" WHERE 1=1 " +
  494. " AND org_name = '"+key.toString()+"'" +
  495. " AND \"time\"::timestamp BETWEEN '"+startDate.format(formatter)+"' "+"AND '"+endDate.format(formatter)+"'");
  496. if(!CollectionUtils.isEmpty(recordAllRes)){
  497. int days = YearMonth.from(startDate).lengthOfMonth();//获取月份天数
  498. for (int i = 1;i<=days;i++){
  499. LocalDateTime dateNow = startDate.withDayOfMonth(i);//当前循环时间
  500. Double numAll = null;//日总值
  501. Double numAge = 0.0;//日小时平均值
  502. //TODO 筛选成当前循环时间的集合
  503. List<Map<String,Object>> daysRecord = recordAllRes.stream().filter(item ->
  504. LocalDateTime.parse(item.get("time").toString(),formatter).toLocalDate().equals(dateNow.toLocalDate()))
  505. .collect(Collectors.toList());
  506. for (Map<String,Object> mapEntity : daysRecord){
  507. //TODO 筛选与当前天一样的数据在计算平均值,数据相加除以24小时 (recordAllRes内容为这天每小时的数据)
  508. if(numAll == null){
  509. numAll = 0.0;
  510. }
  511. numAll += Double.valueOf(mapEntity.get("value").toString());
  512. }
  513. if (numAll!=null){
  514. numAge = numAll/24;
  515. }
  516. //TODO ②正式插入或修改日预测数据表
  517. Optional<String> orgIdOptional = orgConfig.stream()
  518. .filter(item -> key.toString().replace("(", "(").replace(")", ")")
  519. .equals(item.get("org_name").toString().replace("(", "(").replace(")", ")")))
  520. .map(item -> item.get("org_id").toString())
  521. .findFirst();
  522. String orgId = orgIdOptional.orElse(null);
  523. if (!StringUtils.isEmpty(orgId)) {
  524. //预测比对时间如果不是今年,则变为今年的时间
  525. //TODO 一天24小时
  526. for (int j = 0;j<24;j++) {
  527. //TODO 数据库操作
  528. Map<String, Object> recordAllEntity = new LinkedHashMap<>();//需要添加的实体数据,此处要用有序map
  529. DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  530. recordAllEntity.put("Date", dateNow.withYear(LocalDateTime.now().getYear()).toLocalDate().format(formatter2));
  531. // 创建一个LocalTime实例,设置为指定小时,分钟和秒数为0
  532. LocalTime time = LocalTime.of(j, 0, 0);
  533. // 创建一个DateTimeFormatter用于格式化时间
  534. DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("HH:mm:ss");
  535. recordAllEntity.put("Hour", time.format(formatter3));
  536. recordAllEntity.put("HourForecastWaterWithdrawals", null);
  537. //TODO 随机数逻辑
  538. int randomUpOrDown = ThreadLocalRandom.current().nextInt(2);//随机向上或者向下 0表示向下 1表示向上
  539. Double randomWater = randomUpOrDown == 0 ?
  540. numAge - (numAge * (randomCode / 100)) :
  541. numAge + (numAge * (randomCode / 100));
  542. recordAllEntity.put("HourForecastActualWaterSupply", randomWater);
  543. recordAllEntity.put("HourActualWaterWithdrawals", "");
  544. //实际从该时间查询结果中得出
  545. List<Map<String,Object>> newRecordAllRes = getWaterTapApi()
  546. .getWaterCollectionRecordAllListAll(" WHERE 1=1 " +
  547. " AND org_name = '"+key.toString()+"'" +
  548. " AND \"time\" = '"+dateNow.withYear(LocalDateTime.now().getYear()).withHour(j).format(formatter)+"' ");
  549. String hourActualWaterSupply = null;
  550. if(!CollectionUtils.isEmpty(newRecordAllRes)){
  551. hourActualWaterSupply = newRecordAllRes.get(0).get("value").toString();
  552. }
  553. recordAllEntity.put("HourActualWaterSupply",hourActualWaterSupply);
  554. recordAllEntity.put("LastModifyTime", LocalDateTime.now().format(formatter));
  555. // 如果找到了org_id,就将其赋值给orgId,否则orgId为null
  556. recordAllEntity.put("orgId", orgId);
  557. //TODO 添加or修改
  558. Integer insertRes = getWaterTapApi().insertOrUpdateTbmHourWater(recordAllEntity);
  559. if (insertRes < 1) {
  560. LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR
  561. , mStrClassName
  562. , mStrClassName
  563. , String.format("Batch insertYuceDataScheduled ERROR:{%s} ",
  564. "新增或修改失败"));
  565. }
  566. }
  567. }
  568. }
  569. }
  570. latch.countDown();
  571. }
  572. });
  573. }catch(Exception ex){
  574. LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR
  575. , mStrClassName
  576. , mStrClassName
  577. , String.format("Batch insertYuceDataScheduled ERROR:{%s} ",
  578. ex.getLocalizedMessage()));
  579. }
  580. }
  581. try{latch.await();}catch(Exception ex){}
  582. }
  583. System.out.println("添加预测小时数据结束"+ TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT));
  584. }else{
  585. }
  586. }
  587. }catch(Exception ex){
  588. ex.printStackTrace();
  589. }
  590. }
  591. }