123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612 |
- 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<Map<String,Object>> list =new ArrayList<>();
- Map<String,Object> 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<Map<String, Object>> 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<Map<String,Object>> list =new ArrayList<>();
- Map<String,Object> 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<Map<String, Object>> 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<InPumpModel> defaultModels = new ArrayList<>();
- InPumpModel entity = new InPumpModel();
- entity.setOrgId(null);
- entity.setPumpId(null);
- entity.setSubType(subType);
- List<Map<String, Object>> defaultRes = new ArrayList<>();
- Map<String,Object> 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<Map<String, Object>> resList = getWaterTapWaterApi().getTbMHourwaterWaterwithdrawals(jpTbMHourWater.getIsPage(),
- jpTbMHourWater.getLimit(), jpTbMHourWater.getOffset(), jpTbMHourWater.getForDateStr());
- //TODO 按水厂分组
- Map<Object, List<Map<String, Object>>> groupedData =
- resList.stream().collect(Collectors.groupingBy(item -> item.get("orgId")));
- //TODO 查询水厂的取水泵,然后将数据拼接
- List<InPumpModel> inPumpModels = new ArrayList<>();
- for (Object key:groupedData.keySet()) {
- InPumpModel model = new InPumpModel();
- List<Map<String,Object>> 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<Map<String, Object>> dataList = groupedData.get(key);
- //TODO 将年月日时作为分组条件
- Map<String, List<Map<String, Object>>> dataMap = dataList.stream()
- .collect(Collectors.groupingBy(emp ->
- emp.get("Date") + " " + emp.get("Hour") // 创建复合键
- ));
- model.setDataList(dataMap);
- //TODO 查询相应方案数据
- List<Map<String,Object>> 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<InPumpModel> defaultModels = new ArrayList<>();
- InPumpModel entity = new InPumpModel();
- entity.setOrgId(null);
- entity.setPumpId(null);
- entity.setSubType(subType);
- List<Map<String, Object>> defaultRes = new ArrayList<>();
- Map<String,Object> 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<Map<String, Object>> resList = getWaterTapWaterApi().getTbMHourwaterWatersupply(jpTbMHourWater.getIsPage(),
- jpTbMHourWater.getLimit(), jpTbMHourWater.getOffset(), jpTbMHourWater.getForDateStr());
- //TODO 按水厂分组
- Map<Object, List<Map<String, Object>>> groupedData =
- resList.stream().collect(Collectors.groupingBy(item -> item.get("orgId")));
- //TODO 查询水厂的取水泵,然后将数据拼接
- List<InPumpModel> inPumpModels = new ArrayList<>();
- for (Object key:groupedData.keySet()) {
- InPumpModel model = new InPumpModel();
- List<Map<String,Object>> 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<Map<String, Object>> dataList = groupedData.get(key);
- //TODO 将年月日时作为分组条件
- Map<String, List<Map<String, Object>>> dataMap = dataList.stream()
- .collect(Collectors.groupingBy(emp ->
- emp.get("Date") + " " + emp.get("Hour") // 创建复合键
- ));
- model.setDataList(dataMap);
- //TODO 查询相应方案数据
- List<Map<String,Object>> 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<Map<String, Object>> configRes = getWaterTapWaterApi().getWaterYuceConfig(false, 0, 0, "");
- if(!CollectionUtils.isEmpty(configRes)){
- Map<String,Object> 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<Map<String, Object>> configList = getWaterTapApi().getWaterCollectionConfigList(null);
- List<Map<String,Object>> orgConfig = getWaterTapWaterApi().getOrgConfig(false,0,0,"");
- if (!CollectionUtils.isEmpty(configList)&&!CollectionUtils.isEmpty(orgConfig)) {
- //TODO 按照组织机构分组
- Map<Object, List<Map<String, Object>>> 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<Map<String,Object>> 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<Map<String,Object>> daysRecord = recordAllRes.stream().filter(item ->
- LocalDateTime.parse(item.get("time").toString(),formatter).toLocalDate().equals(dateNow.toLocalDate()))
- .collect(Collectors.toList());
- for (Map<String,Object> 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<String> 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<Map<String,Object>> daysRecord = recordAllRes.stream().filter(item ->
- LocalDateTime.parse(item.get("time").toString(),formatter).toLocalDate().equals(dateNow.toLocalDate()))
- .collect(Collectors.toList());
- for (Map<String,Object> mapEntity : daysRecord){
- //TODO 筛选与当前天一样的数据在计算平均值,数据相加除以24小时 (recordAllRes内容为这天每小时的数据)
- if(numAll == null){
- numAll = 0.0;
- }
- numAll += Double.valueOf(mapEntity.get("value").toString());
- }
- //TODO 数据库操作
- Map<String, Object> 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<Map<String,Object>> 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<Map<String, Object>> configRes = getWaterTapWaterApi().getWaterYuceConfig(false, 0, 0, "");
- if(!CollectionUtils.isEmpty(configRes)){
- Map<String,Object> 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<Map<String, Object>> configList = getWaterTapApi().getWaterCollectionConfigList(null);
- List<Map<String,Object>> orgConfig = getWaterTapWaterApi().getOrgConfig(false,0,0,"");
- if (!CollectionUtils.isEmpty(configList)&&!CollectionUtils.isEmpty(orgConfig)) {
- //TODO 按照组织机构分组
- Map<Object, List<Map<String, Object>>> 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<Map<String,Object>> 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<Map<String,Object>> daysRecord = recordAllRes.stream().filter(item ->
- LocalDateTime.parse(item.get("time").toString(),formatter).toLocalDate().equals(dateNow.toLocalDate()))
- .collect(Collectors.toList());
- for (Map<String,Object> 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<String> 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<String, Object> 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<Map<String,Object>> 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();
- }
- }
- }
|