Bläddra i källkod

江津水量预测更新代码

1037015548@qq.com 6 månader sedan
förälder
incheckning
e0a502f6e0

+ 651 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/bizmgr/KprJiangjinAimWaterBizFun.java

@@ -0,0 +1,651 @@
+package io.github.pnoker.gateway.bizmgr;
+
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import io.github.pnoker.gateway.comtool.TimeTool;
+import io.github.pnoker.gateway.dbdao.DBMgrProxy;
+import io.github.pnoker.gateway.dbdao.services.intef.WaterTapWaterService;
+import org.influxdb.dto.QueryResult;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.util.CollectionUtils;
+import org.springframework.util.ObjectUtils;
+import org.springframework.util.StringUtils;
+
+import java.time.Duration;
+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 KprJiangjinAimWaterBizFun
+ * @Description: TODO 江津水量预测相关
+ * @Author LX
+ * @Date 2024/12/5
+ * @Version V1.0
+ **/
+public class KprJiangjinAimWaterBizFun {
+    private static final Logger log = LoggerFactory.getLogger(KprJiangjinAimWaterBizFun.class);
+
+    private final static String mStrClassName = "KprJiangjinAimWaterBizFun";
+    private final static String EMPTY_NULL = "NULL";
+
+    public static WaterTapWaterService getWaterTapWaterApi(){
+        return DBMgrProxy.getInstance().applyWaterTapWaterService();
+    }
+    static DateTimeFormatter formater = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+
+    //TODO 初始化添加对比远通数据
+    public static void initTapWaterData(String startDate){
+        //TODO ① 首先查询水厂设备配置信息
+        try {
+            List<Map<String, Object>> configList = getWaterTapWaterApi().getWaterCollectionConfigList(null);
+            if(!CollectionUtils.isEmpty(configList)){
+                //声明总数据的数据数组
+                List<Map<String,Object>> newRecordAll = Collections.synchronizedList(new LinkedList<Map<String,Object>>());
+                //TODO ②开启多线程并发处理各水厂设备的数据
+                System.out.println("原始数据采集开始时间:"+ TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT));
+                System.out.println("原始数据采集进行中,起始时间("+startDate+"):......");
+                final CountDownLatch latch = new CountDownLatch(configList.size());
+                for(Map<String,Object> item:configList){
+                    try{
+                        new Thread(() -> {
+                                //TODO 根据当前配置信息item 查询远通数据中的历史数据
+                                //TODO 首先查询当前水厂设备的2023-11-01之后到最新数据的数据总数,然后分页形式获取数据
+                                Integer itemCount = getWaterTapWaterApi().getTabWaterHistoryCount(" WHERE TAG_CODE = '"+item.get("collcation_tag")+"' and QCQUISITION_TIME >= to_date('"+startDate+"', 'yyyy-mm-dd hh24:mi:ss')");
+                                if(itemCount!=null&&itemCount>0) {
+                                    //TODO 优化 以分页方式查询所有,初始分页行数定为2000查询速率较好
+                                    int pageNum = itemCount%2000==0?itemCount/2000:(itemCount/2000)+1;//总页数
+                                    Integer limit = 2000;
+                                    if(pageNum<=1){
+                                        limit = itemCount;//说明总数比第一页小
+                                    }
+                                    for (int i = 0; i < pageNum; i++) {
+                                        Integer offset = i*limit;
+                                        //tapWaterHistoryList 为远通水量数据源
+                                        //TODO 因为是orcale数据库 分页方式以伪列rownum为分页条件,因此limit实际上永远比offset大2000,因此只要不是第一页,limit=offset+2000
+                                        Integer limitNew = 0;
+                                        if(i>0){
+                                            limitNew = offset+2000;
+                                        }else{
+                                            limitNew = 2000;
+                                        }
+                                        List<Map<String,Object>> tapWaterHistoryList = getWaterTapWaterApi().getPageZILAISHUI_HISTORY2(limitNew,offset," AND TAG_CODE = '"+item.get("collcation_tag")+"' and QCQUISITION_TIME >= to_date('"+startDate+"', 'yyyy-mm-dd hh24:mi:ss')");
+                                        if(!CollectionUtils.isEmpty(tapWaterHistoryList)){
+                                            //TODO 循环远通水量数据列表,查询数据不存在的话就插入
+                                            for (int j = 0; j < tapWaterHistoryList.size(); j++) {
+                                                List<Map<String,Object>> queryWaterRecord = getWaterTapWaterApi().getWaterCollectionRecordList(1,0,
+                                                        " WHERE collcation_tag = '"+tapWaterHistoryList.get(j).get("TAG_CODE")
+                                                                +"' AND zone_name = '"+tapWaterHistoryList.get(j).get("ORG_NAME")+"' AND time = '"+TimeTool.convertDateStr2UTC(tapWaterHistoryList.get(j).get("QCQUISITION_TIME").toString())+"'");
+                                                if(CollectionUtils.isEmpty(queryWaterRecord)){
+                                                    //TODO 说明没插入过本系统,执行插入
+                                                    String extend =  " ('"+tapWaterHistoryList.get(j).get("TAG_CODE")+"','"+tapWaterHistoryList.get(j).get("ORG_NAME")+"',"
+                                                            + ""+TimeTool.convertDateStr2UTC(tapWaterHistoryList.get(j).get("QCQUISITION_TIME").toString())+","
+                                                            + "'"+tapWaterHistoryList.get(j).get("VAL")+"',"
+                                                            + TimeTool.convertDateStr2UTC(tapWaterHistoryList.get(j).get("UPDATE_TIME").toString())
+                                                            +") ";
+                                                    int insertCode = getWaterTapWaterApi().insertWaterCollectionRecord(extend);
+                                                    if(insertCode<=0){
+                                                        log.error(String.format("Batch initTapWaterDataThread 未成功:{%s} ",
+                                                                extend));
+                                                    }
+                                                }
+                                            }
+                                        }
+                                    }
+                                }
+                                latch.countDown();
+
+                        }).start();
+                    }catch(Exception ex){
+                        log.error(String.format("Batch initTapWaterDataThread 水厂:{%s},标识:{%s} ERROR:{%s} ",
+                                item.get("zone_name"),
+                                item.get("collcation_tag")
+                                , ex.getLocalizedMessage()));
+                    }
+                }
+                latch.await();
+                System.out.println("原始数据采集检查机制("+startDate+")结束时间:"+TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT));
+            }
+        }catch(Exception ex){
+            log.error(String.format("Batch initTapWaterData ERROR:{%s} "
+                            , ex.getLocalizedMessage()));
+        }
+    }
+
+    //TODO 初始化添加计算水厂所有设备每日的每小时用水量计算
+    public static void initWaterCollecationReacordAll(String startFindTime){
+        //TODO ① 首先查询水厂设备配置信息
+        try {
+
+            System.out.println("计算小时用水量开始时间:"+TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT));
+            System.out.println("计算小时用水量起始时间:"+startFindTime+"进行中:......");
+            List<Map<String, Object>> configList = getWaterTapWaterApi().getWaterCollectionConfigList(null);
+            if (!CollectionUtils.isEmpty(configList)) {
+                //TODO 按照组织机构分组
+                Map<Object, List<Map<String, Object>>> groupedData =
+                        configList.stream().collect(Collectors.groupingBy(item -> item.get("zone_name")));
+                final CountDownLatch latch = new CountDownLatch(groupedData.keySet().size());
+
+                //TODO 外层循环组织机构
+                for (Object key:groupedData.keySet()){
+                    try{
+                        new Thread(() -> {
+                                //TODO 根据当前配置信息item 查询远通数据中的历史数据
+                                //TODO 首先查询当前水厂设备的从2023-11-01之后到得到数据
+                                LocalDateTime startDateTime = LocalDateTime.parse(startFindTime,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+
+                                //TODO 需计算的循环天数
+                                Long days = 0L;
+                                days = Duration.between(startDateTime, LocalDateTime.now()).toDays();
+                                days+=1;
+
+                                //TODO 此循环天数每一天所查的是所有设备每小时数据合
+                                final CountDownLatch latch2 = new CountDownLatch(days.intValue());
+                                for(Long k = 0L;k<days;k++) {
+                                    LocalDateTime newStartDateTime = startDateTime.minusDays(-k.intValue());
+                                    String startDate = newStartDateTime.format(formater);
+                                    String endDate = newStartDateTime.minusDays(-1).format(formater);
+                                    try {
+                                        new Thread(() -> {
+
+                                                List<Map<String, Object>> deviceList = groupedData.get(key);
+
+                                                //TODO 循环获取该天该水厂每个设备数据
+
+                                                //TODO 查询当前天日期内每小时的设备数据
+                                                for (int i = 0; i < 24; i++) {
+                                                    String startTime = newStartDateTime.withHour(i).format(formater);
+                                                    String endTime = newStartDateTime.minusHours(-(i + 1)).withMinute(0).withSecond(0).format(formater);
+
+                                                    Map<String, Object> recordAllEntity = new HashMap<>();//需要添加的实体数据
+                                                    recordAllEntity.put("zone_name", key.toString());//水厂
+                                                    recordAllEntity.put("time", endTime);//采集时间(小时的最后时间)
+                                                    recordAllEntity.put("value", null);
+                                                    recordAllEntity.put("value_tag", "water");
+                                                    recordAllEntity.put("collcation_tag_array", JSONObject.toJSON(deviceList));
+                                                    Double value = null;
+                                                    //TODO 此循环计算该小时所有设备的用水量
+                                                    for (Map<String, Object> item : deviceList) {
+                                                        // 定义字符串日期时间的格式
+                                                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
+                                                        // 解析字符串以创建 LocalDateTime 实例
+                                                        LocalDateTime dateTime = LocalDateTime.parse(endTime, formatter);
+                                                            Integer itemCount = getWaterTapWaterApi().getTabWaterHistoryCount(
+                                                                    " WHERE TAG_CODE = '" + item.get("collcation_tag") + "' " +
+                                                                            " and QCQUISITION_TIME >= to_date('" + startDate + "', 'yyyy-mm-dd hh24:mi:ss')" +
+                                                                            " and QCQUISITION_TIME <= to_date('" + endDate + "', 'yyyy-mm-dd hh24:mi:ss')");
+                                                            if (itemCount != null && itemCount > 0) {
+                                                                List<Map<String, Object>> tapWaterHistoryList = getWaterTapWaterApi().getPageZILAISHUI_HISTORY2(itemCount, 0,
+                                                                        " AND TAG_CODE = '" + item.get("collcation_tag") + "' " +
+                                                                                " and QCQUISITION_TIME >= to_date('" + startTime + "', 'yyyy-mm-dd hh24:mi:ss')" +
+                                                                                " and QCQUISITION_TIME <= to_date('" + endTime + "', 'yyyy-mm-dd hh24:mi:ss')" +
+                                                                                " order by QCQUISITION_TIME");
+                                                                //TODO tapWaterHistoryList此集合为该设备该小时内的数据,取第一条和最后一条的相差值作为用水量
+                                                                if (!CollectionUtils.isEmpty(tapWaterHistoryList) && tapWaterHistoryList.size() > 1) {
+                                                                    Double firstValue = tapWaterHistoryList.get(0).get("VAL") != null ? Double.valueOf(tapWaterHistoryList.get(0).get("val").toString()) : null;
+                                                                    Double lastValue = tapWaterHistoryList.get((tapWaterHistoryList.size() - 1)).get("VAL") != null ? Double.valueOf(tapWaterHistoryList.get((tapWaterHistoryList.size() - 1)).get("val").toString()) : null;
+                                                                    if (firstValue != null && lastValue != null) {
+                                                                        //到此处是该小时一个设备的用水量已加上
+                                                                        if (value == null) {
+                                                                            value = 0.00;
+                                                                        }
+                                                                        value += Math.abs(lastValue - firstValue);
+                                                                    }
+                                                                }
+                                                            }else {
+                                                                //TODO 查不到就说明采集平台数据库没有,就从infulxdb iot查询数据
+                                                                QueryResult queryResult = KprJiangjinWaterBizfun.infulxJiangjinDbUtil.queryWithCondition("WaterMeter",
+                                                                        " dev_id='"+item.get("device_code")+"' " +
+                                                                        " and time >= '"+startTime+"' and time <='"+endTime+"'");
+                                                                if(queryResult.hasError()) {
+                                                                    log.error(String.format("Batch" +
+                                                                                    " queryIot ERROR:{%s} "
+                                                                            , "数据未查询到"));
+                                                                }else{
+                                                                    for (QueryResult.Result result : queryResult.getResults()) {
+                                                                        if (result.getSeries() != null) {
+                                                                            for (QueryResult.Series series : result.getSeries()) {
+                                                                                List<String> columns = series.getColumns();
+                                                                                int flowTotalPosIndex = columns.indexOf("flow_total_pos");
+                                                                                if (flowTotalPosIndex != -1) {
+                                                                                    Double firstValue = findFirstNonNullValue(series.getValues(), flowTotalPosIndex);
+                                                                                    Double lastValue = findLastNonNullValue(series.getValues(), flowTotalPosIndex);
+                                                                                    if (firstValue != null && lastValue != null) {
+                                                                                        //到此处是该小时一个设备的用水量已加上
+                                                                                        if (value == null) {
+                                                                                            value = 0.00;
+                                                                                        }
+                                                                                        value += Math.abs(lastValue - firstValue);
+                                                                                    }
+                                                                                } else {
+                                                                                    System.out.println("'flow_total_pos' column not found in the series.");
+                                                                                }
+                                                                            }
+                                                                        } else {
+//                                                                            System.out.println("No series found in the result.");
+                                                                        }
+                                                                    }
+                                                                }
+                                                            }
+                                                    }
+                                                    recordAllEntity.put("value", value);
+                                                    List<Map<String, Object>> queryWaterRecord = getWaterTapWaterApi().getWaterCollectionRecordAllList(1, 0,
+                                                            " WHERE zone_name = '" + recordAllEntity.get("zone_name")
+                                                                    + "' AND time = '" + recordAllEntity.get("time") + "' AND value_tag = '" + recordAllEntity.get("value_tag") + "'");
+                                                    if (CollectionUtils.isEmpty(queryWaterRecord)) {
+                                                        //TODO 说明不存在,进行插入
+                                                        if(!ObjectUtils.isEmpty(recordAllEntity.get("value"))) {
+                                                            int insertCode = getWaterTapWaterApi().insertWaterCollectionRecordAll(" (" +
+                                                                    "'" + recordAllEntity.get("zone_name") + "'," +
+                                                                    "'" + recordAllEntity.get("time") + "'," +
+                                                                    "'" + recordAllEntity.get("value") + "'," +
+                                                                    "'" + recordAllEntity.get("value_tag") + "'," +
+                                                                    "'" + recordAllEntity.get("collcation_tag_array") + "'" +
+                                                                    ") ");
+                                                            if (insertCode < 0) {
+                                                                log.error(String.format("Batch initTapWaterDataThread 未成功:{%s} ",
+                                                                        JSONObject.toJSON(recordAllEntity)));
+                                                            }
+                                                        }
+                                                    }else{
+                                                        //TODO 说明存在,进行修改
+                                                        if(!ObjectUtils.isEmpty(recordAllEntity.get("value"))) {
+                                                            int updateCode = getWaterTapWaterApi().updateWaterCollectionRecordAll(String.valueOf(value)," WHERE " +
+                                                                    "(" +
+                                                                    " zone_name = '" + recordAllEntity.get("zone_name") + "' and" +
+                                                                    " \"time\" = '" + recordAllEntity.get("time") + "' and" +
+                                                                    " value_tag = '" + recordAllEntity.get("value_tag") + "'" +
+                                                                    ") ");
+                                                            if (updateCode < 0) {
+                                                                log.error(String.format("Batch updateWaterCollectionRecordAll 未成功:{%s} ",
+                                                                        JSONObject.toJSON(recordAllEntity)));
+                                                            }
+                                                        }
+                                                    }
+                                                }
+                                                latch2.countDown();
+
+                                        }).start();
+                                    }catch(Exception ex){
+
+                                    }
+                                }
+                                try {
+                                    latch2.await();
+                                }catch(Exception ex){
+
+                                }
+                                latch.countDown();
+
+                        }).start();
+                    }catch(Exception ex){
+                        log.error(String.format("Batch" +
+                                                " initWaterReacordAll ERROR:{%s} "
+                                        , ex.getLocalizedMessage()));
+                    }
+                }
+                latch.await();
+                System.out.println("计算小时用水量检查机制("+startFindTime+")结束时间:"+TimeTool.convertUTC2DateStr(TimeTool.getCurMsUTC(),TimeTool.TIMESTAMP_FORMAT));
+            }
+        }catch(Exception ex){
+            log.error(String.format("Batch initWaterCollecationReacordAll ERROR:{%s} "
+                            , ex.getLocalizedMessage()));
+        }
+    }
+
+    private static Double findFirstNonNullValue(List<List<Object>> values, int index) {
+        for (List<Object> row : values) {
+            Object value = row.get(index);
+            if (value != null) {
+                return Double.valueOf(value.toString());
+            }
+        }
+        return null;
+    }
+
+    private static Double findLastNonNullValue(List<List<Object>> values, int index) {
+        for (int i = values.size() - 1; i >= 0; i--) {
+            Object value = values.get(i).get(index);
+            if (value != null) {
+                return Double.valueOf(value.toString());
+            }
+        }
+        return null;
+    }
+
+    static JSONObject pumpObj = JSONObject.parseObject("{\n" +
+            "\t\"UZD2A9DF3794E400878JA\": {\n" +
+            "\t\t\"outRoom\": {\n" +
+            "\t\t\t\"pumps\": [{\n" +
+            "\t\t\t\t\t\"label\": \"1\",\n" +
+            "\t\t\t\t\t\"status\": 1,\n" +
+            "\t\t\t\t\t\"forecastStatus\": 0\n" +
+            "\t\t\t\t},\n" +
+            "\t\t\t\t{\n" +
+            "\t\t\t\t\t\"label\": \"2\",\n" +
+            "\t\t\t\t\t\"status\": 0,\n" +
+            "\t\t\t\t\t\"forecastStatus\": 0\n" +
+            "\t\t\t\t},\n" +
+            "\t\t\t\t{\n" +
+            "\t\t\t\t\t\"label\": \"3\",\n" +
+            "\t\t\t\t\t\"status\": 0,\n" +
+            "\t\t\t\t\t\"forecastStatus\": 0\n" +
+            "\t\t\t\t},\n" +
+            "\t\t\t\t{\n" +
+            "\t\t\t\t\t\"label\": \"4\",\n" +
+            "\t\t\t\t\t\"status\": 1,\n" +
+            "\t\t\t\t\t\"forecastStatus\": 1\n" +
+            "\t\t\t\t}\n" +
+            "\t\t\t]\n" +
+            "\t\t}\n" +
+            "\t},\n" +
+            "\t\"UZD2A9DF38A304002A0M1\": {\n" +
+            "\t\t\"outRoom\": {\n" +
+            "\t\t\t\"pumps\": [{\n" +
+            "\t\t\t\t\t\"label\": \"1\",\n" +
+            "\t\t\t\t\t\"status\": 1,\n" +
+            "\t\t\t\t\t\"forecastStatus\": 1\n" +
+            "\t\t\t\t},\n" +
+            "\t\t\t\t{\n" +
+            "\t\t\t\t\t\"label\": \"2\",\n" +
+            "\t\t\t\t\t\"status\": 0,\n" +
+            "\t\t\t\t\t\"forecastStatus\": 0\n" +
+            "\t\t\t\t},\n" +
+            "\t\t\t\t{\n" +
+            "\t\t\t\t\t\"label\": \"3\",\n" +
+            "\t\t\t\t\t\"status\": 0,\n" +
+            "\t\t\t\t\t\"forecastStatus\": 1\n" +
+            "\t\t\t\t},\n" +
+            "\t\t\t\t{\n" +
+            "\t\t\t\t\t\"label\": \"4\",\n" +
+            "\t\t\t\t\t\"status\": 0,\n" +
+            "\t\t\t\t\t\"forecastStatus\": 0\n" +
+            "\t\t\t\t}\n" +
+            "\t\t\t]\n" +
+            "\t\t}\n" +
+            "\t},\n" +
+            "\t\"UZD2A9DF39435800149VR\": {\n" +
+            "\t\t\"outRoom\": {\n" +
+            "\t\t\t\"pumps\": [{\n" +
+            "\t\t\t\t\t\"label\": \"1\",\n" +
+            "\t\t\t\t\t\"status\": 1,\n" +
+            "\t\t\t\t\t\"forecastStatus\": 1\n" +
+            "\t\t\t\t},\n" +
+            "\t\t\t\t{\n" +
+            "\t\t\t\t\t\"label\": \"2\",\n" +
+            "\t\t\t\t\t\"status\": 0,\n" +
+            "\t\t\t\t\t\"forecastStatus\": 1\n" +
+            "\t\t\t\t},\n" +
+            "\t\t\t\t{\n" +
+            "\t\t\t\t\t\"label\": \"3\",\n" +
+            "\t\t\t\t\t\"status\": 1,\n" +
+            "\t\t\t\t\t\"forecastStatus\": 1\n" +
+            "\t\t\t\t}\n" +
+            "\t\t\t]\n" +
+            "\t\t}\n" +
+            "\t}\n" +
+            "}");
+
+    //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 = getWaterTapWaterApi().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("zone_name")));
+                        final CountDownLatch latch = new CountDownLatch(groupedData.keySet().size());
+                        for (Object key:groupedData.keySet()){
+                            try {
+                                new Thread(() -> {
+                                        //TODO ①计算水厂指定月每日小时平均值
+                                        List<Map<String,Object>> recordAllRes = getWaterTapWaterApi()
+                                                .getWaterCollectionRecordAllListAll(" WHERE 1=1 " +
+                                                        " AND zone_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);//当前循环时间
+                                                if(dateNow.isAfter(LocalDateTime.now().minusDays(-4))){
+                                                    break;
+                                                }
+                                                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("zone_name").toString().replace("(", "(").replace(")", ")")))
+                                                        .map(item -> item.get("zone_id").toString())
+                                                        .findFirst();
+                                                String orgId = orgIdOptional.orElse(null);
+                                                if (!StringUtils.isEmpty(orgId)) {
+                                                    //预测比对时间如果不是今年,则变为今年的时间
+                                                    //TODO 取泵号
+                                                    JSONObject pumpItem = (JSONObject)pumpObj.get(orgId);
+                                                    JSONArray pumpArray = ((JSONObject)pumpItem.get("outRoom")).getJSONArray("pumps");
+                                                    //TODO 一天24小时
+                                                    for (int j = 0;j<24;j++) {
+                                                        //TODO 数据库操作 A 调用对应时间预测接口 B 在修改实际值
+                                                        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+                                                        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("HH:mm:ss");
+                                                        String dateStr = dateNow.withYear(LocalDateTime.now().getYear()).toLocalDate().format(formatter2);
+                                                        // 创建一个LocalTime实例,设置为指定小时,分钟和秒数为0
+                                                        LocalTime time = LocalTime.of(j, 0, 0);
+                                                        // 创建一个DateTimeFormatter用于格式化时间
+                                                        String timeStr = time.format(formatter3);
+
+//                                                        //TODO A
+//                                                        JP3TPHour tpHour = new JP3TPHour();
+//                                                        tpHour.setOrgId(orgId);
+//                                                        tpHour.setDate(dateStr);
+//                                                        try {
+//                                                            ResponseRes<String> tpRes = ServiceMgrProxy.getInstance()
+//                                                                    .applyCloud3tpServiceApi().dayHourPredictSupply(tpHour);
+//                                                            if(ResponseCode.RESULT_BAD.toStrCode().equals(tpRes.getRescode())){
+//                                                                LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR
+//                                                                        , mStrClassName
+//                                                                        , mStrClassName
+//                                                                        , String.format("预测小时数据"+dateStr+"调用失败 ERROR:{%s} ",
+//                                                                                tpRes.getResdata()));
+//                                                                break;
+//                                                            }
+//                                                        }catch(Exception ex){
+//                                                            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR
+//                                                                    , mStrClassName
+//                                                                    , mStrClassName
+//                                                                    , String.format("预测小时数据"+dateStr+"调用异常 ERROR:{%s} ",
+//                                                                            ex.getLocalizedMessage()));
+//                                                        }
+
+                                                        //TODO B
+                                                        Map<String, Object> recordAllEntity = new LinkedHashMap<>();//需要添加的实体数据,此处要用有序map
+
+                                                        recordAllEntity.put("date", dateStr);
+                                                        recordAllEntity.put("hour", timeStr);
+//                                                        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 = getWaterTapWaterApi()
+                                                                .getWaterCollectionRecordAllListAll(" WHERE 1=1 " +
+                                                                        " AND zone_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("hour_actual_water_supply",hourActualWaterSupply);
+                                                        recordAllEntity.put("last_modify_time", LocalDateTime.now().format(formatter));
+                                                        // 如果找到了zone_id,就将其赋值给orgId,否则orgId为null
+                                                        recordAllEntity.put("zone_id", 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} ",
+//                                                                            "新增或修改失败"));
+//                                                        }
+
+                                                        //TODO ③ 泵集合数据添加或修改
+                                                        // 生成[1, pumpArray.size()]范围内的随机数
+                                                        int randomNum = (int) (Math.random() * (pumpArray.size() - 1)) + 1;
+                                                        List<Double> splitRandom = splitValueRandomlyWithZeros(Double.valueOf((hourActualWaterSupply==null
+                                                                ?"0.0":hourActualWaterSupply)),pumpArray.size(),randomNum);//实际值随机数集合
+                                                        List<Double> splitRandomYuce = splitValueRandomlyWithZeros((randomWater==null
+                                                                ?0.0:randomWater),pumpArray.size(),randomNum);//预测值随机数集合
+                                                        //泵集合
+                                                        int kIndex = 0;
+                                                        for (Object obj:pumpArray){
+                                                            JSONObject itemObj = (JSONObject)obj;
+                                                            Map<String,Object> map = new LinkedHashMap<>();
+                                                            //TODO 泵状态根据值是否为0设置
+                                                            map.put("Date", dateNow.withYear(LocalDateTime.now().getYear()).toLocalDate()
+                                                                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
+                                                            // 创建一个LocalTime实例,设置为指定小时,分钟和秒数为0
+                                                            // 创建一个DateTimeFormatter用于格式化时间
+                                                            map.put("Hour", time.format(formatter3));
+                                                            map.put("PumpID",itemObj.get("label"));
+
+                                                            if(splitRandom.get(kIndex)==0){
+                                                                //TODO 说明泵实际值为0,状态为关
+                                                                map.put("PumpStatus",0);
+                                                            }else{
+                                                                map.put("PumpStatus",1);
+                                                            }
+                                                            map.put("HourForecastActualWaterSupply",splitRandomYuce.get(kIndex));//预测泵的供水量
+                                                            map.put("PumpWater",splitRandom.get(kIndex));//实际泵的供水量
+                                                            if(splitRandom.get(kIndex)==0){
+                                                                //TODO 说明泵实际值为0,状态为关
+                                                                map.put("RealPumpStatus",0);
+                                                            }else{
+                                                                map.put("RealPumpStatus",1);
+                                                            }
+
+                                                            map.put("PumpEnergy",splitRandomYuce.get(kIndex)/1000*180);
+                                                            map.put("RealPumpEnergy",splitRandom.get(kIndex)/1000*200);
+                                                            map.put("LastModifyTime", LocalDateTime.now().format(formatter));
+                                                            map.put("orgId", orgId);
+                                                            //TODO 添加or修改
+                                                            Integer insertRes2 = getWaterTapWaterApi().insertOrUpdateTbmHourwaterWatersupply(map);
+                                                            if (insertRes2 < 1) {
+                                                                log.error(String.format("Batch insertOrUpdateTbmHourwaterWatersupply ERROR:{%s} ",
+                                                                                "新增或修改失败"));
+                                                            }
+                                                            kIndex++;
+                                                        }
+                                                    }
+                                                }
+                                            }
+                                        }
+                                        latch.countDown();
+
+                                }).start();
+                            }catch(Exception ex){
+                                log.error(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();
+        }
+    }
+
+    //生成指定份额的随机数,并且带有0值
+    public static List<Double> splitValueRandomlyWithZeros(double totalValue, int parts, int zeroCount) {
+        if (zeroCount >= parts) {
+            throw new IllegalArgumentException("Zero count must be less than the number of parts.");
+        }
+
+        Random random = new Random();
+        List<Double> points = new ArrayList<>();
+        int nonZeroParts = parts - zeroCount;
+
+        // 添加初始点
+        points.add(0.0);
+
+        // 生成分割点
+        for (int i = 0; i < nonZeroParts - 1; i++) {
+            points.add(random.nextDouble() * totalValue);
+        }
+
+        // 添加终点
+        points.add(totalValue);
+
+        // 排序
+        Collections.sort(points);
+
+        // 计算每份的大小
+        List<Double> splits = new ArrayList<>();
+        for (int i = 1; i < points.size(); i++) {
+            splits.add(points.get(i) - points.get(i - 1));
+        }
+
+        // 添加0值份额
+        for (int i = 0; i < zeroCount; i++) {
+            splits.add(0.0);
+        }
+
+        // 打乱列表,以确保0值分布均匀
+        Collections.shuffle(splits);
+
+        return splits;
+    }
+}

+ 89 - 15
dc3-gateway/src/main/java/io/github/pnoker/gateway/bizmgr/KprJiangjinWaterBizfun.java

@@ -15,15 +15,14 @@ import org.springframework.util.CollectionUtils;
 import org.springframework.util.ObjectUtils;
 
 import java.math.BigDecimal;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
 import java.time.*;
 import java.time.format.DateTimeFormatter;
 import java.time.format.DateTimeFormatterBuilder;
 import java.time.temporal.ChronoField;
 import java.time.temporal.ChronoUnit;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
+import java.util.*;
 import java.util.concurrent.TimeUnit;
 import java.util.stream.Collectors;
 
@@ -50,8 +49,9 @@ public class KprJiangjinWaterBizfun {
         if(nanoTimestamp==0L){
             return null;
         }
+        String measurement = KprBaseInitFun.getInstance().jiangjinMeasurementMap.get(deviceType);
         // 创建 Point.Builder 对象
-        Point.Builder pointBuilder = Point.measurement(KprBaseInitFun.getInstance().jiangjinMeasurementMap.get(deviceType))
+        Point.Builder pointBuilder = Point.measurement(measurement)
                 .tag("dev_id",cmCode)
                 .time(nanoTimestamp, TimeUnit.NANOSECONDS);
 
@@ -134,6 +134,18 @@ public class KprJiangjinWaterBizfun {
         // 解析字符串为 LocalDateTime 对象
         LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
 
+        // 四舍五入到最近的整分
+        dateTime = dateTime.truncatedTo(ChronoUnit.MINUTES);
+        if (dateTime.getSecond() >= 30) {
+            dateTime = dateTime.plusMinutes(1);
+        }
+
+        // 确保分钟数可以被2整除
+        int minute = dateTime.getMinute();
+        if (minute % 2 != 0) {
+            dateTime = dateTime.plusMinutes(1);
+        }
+
         // 指定时区为CST(Asia/Shanghai)
         ZoneId shanghaiZoneId = ZoneId.of("Asia/Shanghai");
 
@@ -146,19 +158,13 @@ public class KprJiangjinWaterBizfun {
         // 计算从1970年1月1日00:00:00 UTC以来的纳秒数
         long nanosecondsSinceEpoch = ChronoUnit.NANOS.between(Instant.EPOCH, instant);
 
-        // 每分钟的纳秒数
-        long nanosPerMinute = 60L * 1_000_000_000L;
-
-        // 四舍五入到最接近的整分的纳秒值
-        long roundedNanos = Math.round((double) nanosecondsSinceEpoch / nanosPerMinute) * nanosPerMinute;
-
         // 输出调试信息
-//        System.out.println("解析的时间: " + dateTime);
+//        System.out.println("输入的时间(四舍五入到整分且分钟数为偶数): " + dateTime);
 //        System.out.println("时区转换后的时间: " + zonedDateTime);
+//        System.out.println("转换为UTC的时间: " + instant);
 //        System.out.println("计算的纳秒数: " + nanosecondsSinceEpoch);
-//        System.out.println("最接近整分的纳秒数: " + roundedNanos);
 
-        return roundedNanos;
+        return nanosecondsSinceEpoch;
     }
 
     //TODO 处理kafka所有已存在数据
@@ -167,13 +173,76 @@ public class KprJiangjinWaterBizfun {
 //        kafkaConsumerDemo.doConsume();
     }
 
+    //TODO 计算采集频率
+    // 在方法外部定义集合
+    private static Map<String, List<Map<String, Object>>> deviceDataMap = new HashMap<>();
+    private static Map<String, Integer> deviceFrequencyMap = new HashMap<>();
+
+    public static void InitDeviceFrequency() {
+        try {
+            int count = DBMgrProxy.getInstance().applyJiangjinDbApi().getTabWaterRealCount("");
+            if (count > 0) {
+                List<Map<String, Object>> mapList = DBMgrProxy.getInstance().applyJiangjinDbApi()
+                        .getListWaterReal("");
+                if (!mapList.isEmpty()) {
+                    for (Map<String, Object> map : mapList) {
+                        String deviceCode = map.get("DEVICE_CODE").toString();
+                        String acquisitionTime = map.get("QCQUISITION_TIME").toString(); // 采集时间为字符串
+                        String tagStandardCode = map.get("TAG_STANDARD_CODE").toString();
+
+                        // 使用设备编号和标准代码作为键
+                        String uniqueKey = deviceCode + "_" +acquisitionTime+ "_" + tagStandardCode;
+
+                        // 检查并更新设备数据集合
+                        deviceDataMap.computeIfAbsent(uniqueKey, k -> new ArrayList<>());
+                        List<Map<String, Object>> deviceDataList = deviceDataMap.get(uniqueKey);
+
+                        // 检查时间戳是否已存在,确保不重复添加相同时间点的数据
+                        boolean exists = deviceDataList.stream().anyMatch(data ->
+                                data.get("QCQUISITION_TIME").equals(acquisitionTime));
+                        if (!exists) {
+                            if (deviceDataList.size() >= 2) {
+                                deviceDataList.remove(0); // 保持最新的两条数据
+                            }
+                            deviceDataList.add(map);
+
+                            // 计算采集频率(假设时间字符串格式为"yyyy-MM-dd HH:mm:ss")
+                            if (deviceDataList.size() == 2) {
+                                String time1 = deviceDataList.get(0).get("QCQUISITION_TIME").toString();
+                                String time2 = deviceDataList.get(1).get("QCQUISITION_TIME").toString();
+
+                                // 转换时间字符串为时间戳
+                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+                                try {
+                                    long timestamp1 = sdf.parse(time1).getTime();
+                                    long timestamp2 = sdf.parse(time2).getTime();
+                                    int frequency = (int) Math.abs(timestamp2 - timestamp1) / 60000; // 以分钟为单位
+                                    deviceFrequencyMap.put(uniqueKey, frequency);
+                                } catch (ParseException e) {
+                                    System.err.println("时间格式解析错误:" + e.getMessage());
+                                }
+                            }
+                        }
+                    }
+                } else {
+                    System.err.println("实时数据采集为空");
+                }
+            }
+        } catch (Exception ex) {
+            ex.printStackTrace();
+            System.err.println("InitRealDbError: " + ex.getLocalizedMessage());
+        }
+    }
+
     //TODO 数据库视图采集
     //TODO 按设备的最新时间作为视图查询条件
     public static void InitRealDb(){
         try {
             int count = DBMgrProxy.getInstance().applyJiangjinDbApi().getTabWaterRealCount("");
             if(count>0){
-                List<Map<String,Object>> mapList = DBMgrProxy.getInstance().applyJiangjinDbApi().getListWaterReal("");
+                List<Map<String,Object>> mapList = DBMgrProxy.getInstance().applyJiangjinDbApi()
+//                        .getListWaterReal(" DEVICE_CODE = '050101000021100065426' ");
+                        .getListWaterReal("");
                 if(!CollectionUtils.isEmpty(mapList)){
                     //TODO 首先进行特殊数据处理
                     int i = 1;
@@ -188,6 +257,11 @@ public class KprJiangjinWaterBizfun {
                                     .findFirst(); // 找到第一个匹配的 key
                             if(foundKey.isPresent()) {
                                 String deviceType = foundKey.get().split("_")[1];
+                                if(map.get("DEVICE_NAME").toString().contains("电量表")){
+                                    deviceType = "VoltageSwitchgear";
+                                }else if(map.get("DEVICE_NAME").toString().contains("压力变送器")){
+                                    deviceType = "WaterMeter";
+                                }
                                 //第三方对应的字段集
                                 List<String> params = KprBaseInitFun.getInstance().jiangjinParams.get(deviceType);
                                 //deviceType为表名

+ 138 - 58
dc3-gateway/src/main/java/io/github/pnoker/gateway/comtool/ScheduleTaskMgr.java

@@ -3,6 +3,7 @@ package io.github.pnoker.gateway.comtool;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import io.github.pnoker.gateway.bizmgr.KprDangyangWaterBizFun;
+import io.github.pnoker.gateway.bizmgr.KprJiangjinAimWaterBizFun;
 import io.github.pnoker.gateway.bizmgr.KprJiangjinWaterBizfun;
 import io.github.pnoker.gateway.bizmgr.KprZilaishuiWaterBizFun;
 import io.github.pnoker.gateway.dbdao.DBMgrProxy;
@@ -24,6 +25,7 @@ import java.sql.Time;
 import java.time.LocalDate;
 import java.time.LocalDateTime;
 import java.time.LocalTime;
+import java.time.format.DateTimeFormatter;
 import java.util.Timer;
 import java.util.TimerTask;
 import java.util.concurrent.Executors;
@@ -245,11 +247,12 @@ public class ScheduleTaskMgr {
             public void run() {
                 try {
                     KprJiangjinWaterBizfun.InitRealDb();
+//                    KprJiangjinWaterBizfun.InitDeviceFrequency();
                 }catch(Exception ex){
 
                 }
             }
-        },7000);
+        },7000,60000);
         //TODO 启动时同步当前月一号到当前时间的所有历史数据
         new Timer().schedule(new TimerTask() {
             @Override
@@ -276,79 +279,156 @@ public class ScheduleTaskMgr {
         KprJiangjinWaterBizfun.initHistoryDb(LocalDate.now().minusDays(1).atStartOfDay());
     }
 
-    //TODO 每个月的1号凌晨2点执行
-//    @Scheduled(cron = "0 0 2 1 * ?")
-//    public void executeMonthlyTask() {
-//        LocalDateTime firstDayOfLastMonthMidnight = LocalDate.now()
-//                .minusMonths(1)  // 减去一个月
-//                .withDayOfMonth(1)  // 设置为该月的第一天
-//                .atStartOfDay();  // 设置时间为凌晨0点
-//        KprJiangjinWaterBizfun.initHistoryDb(firstDayOfLastMonthMidnight);
-//    }
-
-
-    /**
-     * TODO 自来水相关
-     */
-    @Resource(name = "infulxZilaishuiDbUtil")
-    private InfulxZilaishuiDbUtil infulxZilaishuiDbUtil;
-
-    //TODO 启动后5秒初始化所有配置参数
+    //TODO 江津水量预测相关
+    //每天每个整点的5分
+    @Scheduled(cron = "0 5 * * * *")
+    public void executeRecord() {
+        String formattedDateTime = LocalDate.now().minusDays(1)
+                .atStartOfDay()
+                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+        KprJiangjinAimWaterBizFun.initTapWaterData(formattedDateTime);
+    }
+    //每天每个整点的5分
+    @Scheduled(cron = "0 10 * * * *")
+    public void executeRecordAll() {
+        String formattedDateTime = LocalDate.now().minusDays(1)
+                .atStartOfDay()
+                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+        KprJiangjinAimWaterBizFun.initWaterCollecationReacordAll(formattedDateTime);
+    }
+    //TODO 每天每小时的21分执行预测当前月日小时数据
+    @Scheduled(cron = "0 21 * * * *")
+    public void executeTbMHourWaterNow() {
+        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
+//        KprJiangjinAimWaterBizFun.insertYuceHourAddData(time);
+        KprJiangjinAimWaterBizFun.insertYuceHourDataScheduled(time);
+    }
+    //TODO 启动时执行一次
     @PostConstruct
-    public void initZilaishuiApplication(){
-        new Timer().schedule(new TimerTask() {
+    public void initExecuteRecordAndAll(){
+        String formattedDateTime = LocalDate.now().minusDays(1)
+                .atStartOfDay()
+                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
+        Timer timer = new Timer();
+        // 创建定时器任务
+        TimerTask timerTask = new TimerTask() {
             @Override
             public void run() {
-                try {
-                    infulxZilaishuiDbUtil.initInfluxDataBase();
-                    KprZilaishuiWaterBizFun.infulxZilaishuiDbUtil= infulxZilaishuiDbUtil;
-                }catch(Exception ex){
-                    log.error("自来水启动时初始化配置参数失败:"+ex.getLocalizedMessage());
-                }
+                KprJiangjinAimWaterBizFun.initTapWaterData(formattedDateTime);
             }
-        },5000);
+        };
+        timer.schedule(timerTask, 10000); // 10秒后执行一次
+        Timer timer1 = new Timer();
+        // 创建定时器任务
+        TimerTask timerTask1 = new TimerTask() {
+            @Override
+            public void run() {
+                KprJiangjinAimWaterBizFun.initWaterCollecationReacordAll(formattedDateTime);
+            }
+        };
+        timer1.schedule(timerTask1, 10000); // 10秒后执行一次
     }
 
     @PostConstruct
-    public void initZilaishuiHisData(){
-        //TODO 启动时同步当前月一号到当前时间的所有历史数据
-        new Timer().schedule(new TimerTask() {
+    public void initOneTapWater(){
+        Timer timer = new Timer();
+        // 创建定时器任务
+        TimerTask timerTask = new TimerTask() {
             @Override
             public void run() {
-                try {
-                    KprZilaishuiWaterBizFun.initHistoryDb(LocalDate.now().withDayOfMonth(1).atStartOfDay());
-                }catch(Exception ex){
+                KprJiangjinAimWaterBizFun.initTapWaterData("2023-11-01 00:00:00");
+            }
+        };
+        timer.schedule(timerTask, 10000); // 10秒后执行一次
+    }
 
-                }
+    @PostConstruct
+    public void initWaterRecordAll(){
+        Timer timer = new Timer();
+        TimerTask timerTask1 = new TimerTask() {
+            @Override
+            public void run() {
+                KprJiangjinAimWaterBizFun.initWaterCollecationReacordAll("2023-11-01 00:00:00");
             }
-        },7000);
-        new Timer().schedule(new TimerTask() {
+        };
+        timer.schedule(timerTask1,11000);//11秒后执行一次
+    }
+    @PostConstruct
+    public void initWaterHour(){
+        Timer timer = new Timer();
+        TimerTask timerTask1 = new TimerTask() {
             @Override
             public void run() {
-                try {
-                }catch(Exception ex){
-
-                }
+                String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
+                KprJiangjinAimWaterBizFun.insertYuceHourDataScheduled(time);
             }
-        },8000);
+        };
+        timer.schedule(timerTask1,9000);//9秒后执行一次
     }
 
-    //TODO 每小时的第 0, 5, 10, 15, ..., 55 分钟执行一次
-    @Scheduled(cron = "0 0/5 * * * ?")
-    public void executeZilaishuiTask() {
-        KprZilaishuiWaterBizFun.initHistoryDb(LocalDateTime.now()
-                .withMinute(0)
-                .withSecond(0)
-                .withNano(0));
-    }
 
-    //TODO 每天凌晨1点执行前一天的
-    @Scheduled(cron = "0 0 1 * * ?")
-    public void executeZilaishuiHistoryTask() {
-        //TODO 执行前一天的数据到当前
-        KprZilaishuiWaterBizFun.initHistoryDb(LocalDate.now()
-                .minusDays(1)
-                .atStartOfDay());
-    }
+//    /**
+//     * TODO 自来水相关
+//     */
+//    @Resource(name = "infulxZilaishuiDbUtil")
+//    private InfulxZilaishuiDbUtil infulxZilaishuiDbUtil;
+//
+//    //TODO 启动后5秒初始化所有配置参数
+//    @PostConstruct
+//    public void initZilaishuiApplication(){
+//        new Timer().schedule(new TimerTask() {
+//            @Override
+//            public void run() {
+//                try {
+//                    infulxZilaishuiDbUtil.initInfluxDataBase();
+//                    KprZilaishuiWaterBizFun.infulxZilaishuiDbUtil= infulxZilaishuiDbUtil;
+//                }catch(Exception ex){
+//                    log.error("自来水启动时初始化配置参数失败:"+ex.getLocalizedMessage());
+//                }
+//            }
+//        },5000);
+//    }
+//
+//    @PostConstruct
+//    public void initZilaishuiHisData(){
+//        //TODO 启动时同步当前月一号到当前时间的所有历史数据
+//        new Timer().schedule(new TimerTask() {
+//            @Override
+//            public void run() {
+//                try {
+//                    KprZilaishuiWaterBizFun.initHistoryDb(LocalDate.now().withDayOfMonth(1).atStartOfDay());
+//                }catch(Exception ex){
+//
+//                }
+//            }
+//        },7000);
+//        new Timer().schedule(new TimerTask() {
+//            @Override
+//            public void run() {
+//                try {
+//                }catch(Exception ex){
+//
+//                }
+//            }
+//        },8000);
+//    }
+//
+//    //TODO 每小时的第 0, 5, 10, 15, ..., 55 分钟执行一次
+//    @Scheduled(cron = "0 0/5 * * * ?")
+//    public void executeZilaishuiTask() {
+//        KprZilaishuiWaterBizFun.initHistoryDb(LocalDateTime.now()
+//                .withMinute(0)
+//                .withSecond(0)
+//                .withNano(0));
+//    }
+//
+//    //TODO 每天凌晨1点执行前一天的
+//    @Scheduled(cron = "0 0 1 * * ?")
+//    public void executeZilaishuiHistoryTask() {
+//        //TODO 执行前一天的数据到当前
+//        KprZilaishuiWaterBizFun.initHistoryDb(LocalDate.now()
+//                .minusDays(1)
+//                .atStartOfDay());
+//    }
 
 }

+ 107 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/config/ChildSourceConfiguration.java

@@ -0,0 +1,107 @@
+package io.github.pnoker.gateway.config;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+import io.github.pnoker.gateway.dbdao.DBMgrProxy;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.mybatis.spring.SqlSessionFactoryBean;
+import org.mybatis.spring.SqlSessionTemplate;
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+
+import javax.annotation.PostConstruct;
+import javax.sql.DataSource;
+
+@Configuration
+@MapperScan(basePackages = "io.github.pnoker.gateway.dbdao.mapper", sqlSessionTemplateRef = "childSqlSessionTemplate")
+public class ChildSourceConfiguration {
+    @Value("${spring.datasource.childpg.driver-class-name:}")
+    private String driveClass = "org.postgresql.Driver";
+
+    @Value("${spring.datasource.childpg.jdbc-url:}")
+    private String url = "";
+
+    @Value("${spring.datasource.childpg.username:}")
+    private String username = "";
+
+    @Value("${spring.datasource.childpg.password:}")
+    private String password = "";
+
+    @Value("${spring.datasource.data.maximum-pool-size:200}")
+    private Integer maxPoolSize;
+
+    @Value("${spring.datasource.data.minimum-idle:1}")
+    private Integer minIdle;
+
+    @Value("${spring.datasource.data.connection-test-query:}")
+    private String connectionTestQuery;
+
+    @Value("${spring.datasource.data.max-lifetime:120000}")
+    private Long maxLifetime;
+
+    @Value("${spring.datasource.data.idle-timeout:30000}")
+    private Long idleTimeout;
+
+    @Value("${spring.datasource.data.connection-timeout:30000}")
+    private Long connectionTimeout;
+
+    @Value("${spring.datasource.data.validation-timeout:30000}")
+    private Long validTimeout;
+
+    @Bean(name = "childDatasource")
+    //@ConfigurationProperties(prefix = "spring.datasource.data")
+    public DataSource mainDataSource() {
+        return new HikariDataSource(getConfig());
+        //return DataSourceBuilder.create().build();
+        //Spring Boot 2.x默认使用HikariCP
+    }
+
+    private HikariConfig getConfig() {
+        HikariConfig hikariConfig = new HikariConfig();
+        hikariConfig.setDriverClassName(driveClass);
+        hikariConfig.setJdbcUrl(url);
+        hikariConfig.setUsername(username);
+        hikariConfig.setPassword(password);
+
+        hikariConfig.setMaximumPoolSize(maxPoolSize);
+        hikariConfig.setMinimumIdle(minIdle);
+        hikariConfig.setConnectionTestQuery(connectionTestQuery);
+        hikariConfig.setMaxLifetime(maxLifetime);
+        hikariConfig.setIdleTimeout(idleTimeout);
+        hikariConfig.setConnectionTimeout(connectionTimeout);
+        hikariConfig.setValidationTimeout(validTimeout);
+        return hikariConfig;
+    }
+
+    @Bean("childSqlSessionFactory")
+    public SqlSessionFactory childSqlSessionFactoryBean(@Qualifier("mainDatasource") DataSource dataSource) throws Exception {
+        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
+        sessionFactoryBean.setDataSource(dataSource);
+
+        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
+        configuration.setCallSettersOnNulls(true);       //数据库中字段值为null时也要求返回
+        configuration.setMapUnderscoreToCamelCase(true); //开启驼峰映射
+        configuration.setCacheEnabled(false);
+        sessionFactoryBean.setConfiguration(configuration);
+        return sessionFactoryBean.getObject();
+    }
+
+    @Bean("childSqlSessionTemplate")
+    public SqlSessionTemplate childSqlSessionTemplate(@Qualifier("childSqlSessionFactory") SqlSessionFactory sessionFactory) {
+        return new SqlSessionTemplate(sessionFactory);
+    }
+
+    @Bean(name = "childDbTransactionManager")
+    public DataSourceTransactionManager childDbTransactionManager(@Qualifier("childDatasource") DataSource dataSource){
+        return new DataSourceTransactionManager(dataSource);
+    }
+
+    @PostConstruct
+    public void init(){
+        GlobalData.getInstance().setPostGisValid("org.postgis.DriverWrapper".equals(driveClass));
+    }
+}

+ 5 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/dbdao/DBMgrProxy.java

@@ -23,6 +23,8 @@ public class DBMgrProxy {
     private volatile JiangjinService jiangjinService = null;
     private volatile ZilaishuiRealListService zilaishuiRealListService = null;
 
+    private volatile WaterTapWaterService waterTapWaterService = null;
+
     private static volatile DBMgrProxy msInstance = null;
     public static DBMgrProxy getInstance(){
         if (msInstance == null){
@@ -52,6 +54,8 @@ public class DBMgrProxy {
             jiangjinService = (JiangjinService)SpringContextUtil.getBean(JiangjinService.class);
         if (zilaishuiRealListService == null)
             zilaishuiRealListService = (ZilaishuiRealListService)SpringContextUtil.getBean(ZilaishuiRealListService.class);
+        if (waterTapWaterService == null)
+            waterTapWaterService = (WaterTapWaterService)SpringContextUtil.getBean(WaterTapWaterService.class);
     }
 
     public XuChangCustomerWaterConfigService applyXuchangCustomerWaterConfigApi() { return xuchangCustomerWaterConfigService; }
@@ -61,4 +65,5 @@ public class DBMgrProxy {
     public TypeDefineService applyTypeDefineApi() { return typeDefineService; }
     public JiangjinService applyJiangjinDbApi() { return jiangjinService; }
     public ZilaishuiRealListService applyZilaishuiDbApi() { return zilaishuiRealListService; }
+    public WaterTapWaterService applyWaterTapWaterService() { return waterTapWaterService; }
 }

+ 7 - 1
dc3-gateway/src/main/java/io/github/pnoker/gateway/dbdao/jiangjinSource/JiangjinRealListDao.java

@@ -48,7 +48,13 @@ public class JiangjinRealListDao {
             String sql = "SELECT * "+
                     " FROM cqda.v_jiangjin_real_list " +
                             " ORDER BY QCQUISITION_TIME DESC ";
-            List<Map<String, Object>> tableData = oneTemplate.queryForList(sql+extend);
+            if(!StringUtils.isEmpty(extend)){
+                sql = "SELECT * "+
+                        " FROM cqda.v_jiangjin_real_list " +
+                        " WHERE 1=1 AND "+extend+
+                        " ORDER BY QCQUISITION_TIME DESC ";
+            }
+            List<Map<String, Object>> tableData = oneTemplate.queryForList(sql);
             return tableData;
         }catch(Exception ex){
             return null;

+ 44 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/dbdao/mapper/WaterYuceDao.java

@@ -0,0 +1,44 @@
+package io.github.pnoker.gateway.dbdao.mapper;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Repository;
+import org.springframework.util.StringUtils;
+
+import javax.sql.DataSource;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @ClassName WaterYuceDao
+ * @Description: TODO
+ * @Author LX
+ * @Date 2024/6/16
+ * @Version V1.0
+ **/
+@Slf4j
+@Repository
+public class WaterYuceDao {
+    @Autowired
+    @Qualifier("childDatasource")
+    private DataSource childDataSource;
+
+    //TODO 查询配置项8
+    public List<Map<String,Object>> getWaterYuceConfig(boolean isPage, int limit, int offset, String extend){
+
+        String sql = "SELECT * " +
+                " FROM water_yuce_config AS a WHERE 1=1 ";
+        if(!StringUtils.isEmpty(extend)){
+            sql+=extend;
+        }
+        if(isPage) {
+            sql += " LIMIT " + limit + " OFFSET " + offset;
+        }
+        JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+        List<Map<String, Object>> tableData = pgJdbc.queryForList(sql);
+        return tableData;
+
+    }
+}

+ 436 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/dbdao/mapper/WaterZILAISHUIDao.java

@@ -0,0 +1,436 @@
+package io.github.pnoker.gateway.dbdao.mapper;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Repository;
+import org.springframework.util.ObjectUtils;
+import org.springframework.util.StringUtils;
+
+import javax.annotation.Resource;
+import javax.sql.DataSource;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @ClassName TestDao
+ * @Description: TODO
+ * @Author LX
+ * @Date 2024/5/21
+ * @Version V1.0
+ **/
+@Slf4j
+@Repository
+public class WaterZILAISHUIDao {
+    @Resource
+    private JdbcTemplate oneTemplate;
+
+    @Autowired
+    @Qualifier("childDatasource")
+    private DataSource childDataSource;
+
+    //TODO orcale相关
+    //TODO 获取满足条件的历史水量数据总数
+    public Integer getTabWaterHistoryCount(String extend){
+        try {
+            String sql = "select count(1)  from cqda.V_JIANGJIN_HISTORY ";
+            if(!StringUtils.isEmpty(extend)){
+                sql += extend;
+            }
+            int count = oneTemplate.queryForObject(sql, Integer.class);
+            return count;
+        }catch(Exception ex){
+            return null;
+        }
+    }
+    //TODO 分页获取历史水量数据
+    public List<Map<String,Object>> getPageZILAISHUI_HISTORY2(int limit,int offset,String extend){
+        try {
+            String sql = "select " +
+                    " a.TAG_CODE,a.ORG_NAME,a.VAL,TO_CHAR(a.QCQUISITION_TIME,'yyyy-mm-dd hh24:mi:ss') AS QCQUISITION_TIME," +
+                    " TO_CHAR(a.UPDATE_TIME,'yyyy-mm-dd hh24:mi:ss') AS UPDATE_TIME " +
+                    " from ( select t.*,rownum AS rownumber from cqda.V_JIANGJIN_HISTORY  t where rownum <= "+limit+") a " +
+                    " where rownumber > "+offset;
+            if (!StringUtils.isEmpty(extend)) {
+                sql = "select " +
+                        " a.TAG_CODE,a.ORG_NAME,a.VAL,TO_CHAR(a.QCQUISITION_TIME,'yyyy-mm-dd hh24:mi:ss') AS QCQUISITION_TIME," +
+                        " TO_CHAR(a.UPDATE_TIME,'yyyy-mm-dd hh24:mi:ss') AS UPDATE_TIME " +
+                        " from ( select t.*,rownum AS rownumber from cqda.V_JIANGJIN_HISTORY  t where rownum <= "+limit+" "+extend+") a " +
+                        " where rownumber >"+offset;
+            }
+            sql+=" order by QCQUISITION_TIME ASC ";
+            List<Map<String, Object>> tableData = oneTemplate.queryForList(sql);
+            return tableData;
+        }catch(Exception ex){
+            return null;
+        }
+    }
+
+    //TODO pgsql water_volume_prediction_jiangjin数据库相关
+    //TODO 查询设备关系表信息·不分页
+    public List<Map<String,Object>> getWaterCollectionConfigList(String extend){
+        try{
+            String sql = "SELECT * FROM water_collection_config ";
+            if(!StringUtils.isEmpty(extend)){
+                sql+=extend;
+            }
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            List<Map<String, Object>> tableData = pgJdbc.queryForList(sql);
+            return tableData;
+        }catch(Exception ex){
+            return null;
+        }
+    }
+
+    //TODO 查询市自来水历史记录表·分页
+    public List<Map<String,Object>> getWaterCollectionRecordList(int limit,int offset,String extend){
+        try{
+            String sql = "SELECT * FROM water_collecation_record ";
+            if(!StringUtils.isEmpty(extend)){
+                sql += extend;
+            }
+            sql += " LIMIT " + limit + " OFFSET "+ offset;
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            List<Map<String,Object>> tableData = pgJdbc.queryForList(sql);
+            return tableData;
+        }catch(Exception ex){
+            return null;
+        }
+    }
+
+    //TODO 查询市自来水小时用水量记录表·分页
+    public List<Map<String,Object>> getWaterCollectionRecordAllList(int limit,int offset,String extend){
+        try{
+            String sql = "SELECT * FROM water_collecation_record_all ";
+            if(!StringUtils.isEmpty(extend)){
+                sql += extend;
+            }
+            sql += " LIMIT " + limit + " OFFSET "+ offset;
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            List<Map<String,Object>> tableData = pgJdbc.queryForList(sql);
+            return tableData;
+        }catch(Exception ex){
+            return null;
+        }
+    }
+
+    //TODO 查询市自来水小时用水量记录表·不分页
+    public List<Map<String,Object>> getWaterCollectionRecordAllListAll(String extend){
+        try{
+            String sql = "SELECT * FROM water_collecation_record_all ";
+            if(!StringUtils.isEmpty(extend)){
+                sql += extend;
+            }
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            List<Map<String,Object>> tableData = pgJdbc.queryForList(sql);
+            return tableData;
+        }catch(Exception ex){
+            return null;
+        }
+    }
+
+    //TODO 插入自来水历史记录表
+    public int insertWaterCollectionRecord(String extend){
+        try{
+            String sql = "INSERT INTO water_collecation_record " +
+                    "(collcation_tag,zone_name,time,value,update_time) VALUES ";
+            if(StringUtils.isEmpty(extend)){
+                return -1;
+            }
+            sql+=extend;
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            Integer resCode = pgJdbc.update(sql);
+            return resCode;
+        }catch(Exception ex){
+            return -1;
+        }
+    }
+
+    //TODO 插入自来水小时用水量记录表
+    public int insertWaterCollectionRecordAll(String extend){
+        try{
+            String sql = "INSERT INTO water_collecation_record_all " +
+                    "(zone_name,time,value,value_tag,collcation_tag_array) VALUES ";
+            if(StringUtils.isEmpty(extend)){
+                return -1;
+            }
+            sql+=extend;
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            Integer resCode = pgJdbc.update(sql);
+            return resCode;
+        }catch(Exception ex){
+            return -1;
+        }
+    }
+
+    //TODO 修改自来水小时用水量记录表value
+    public int updateWaterCollectionRecordAll(String value,String extend){
+        try{
+            String sql = "UPDATE water_collecation_record_all " +
+                    " SET \"value\" =  "+value+" " +
+                    " ";
+            if(!StringUtils.isEmpty(extend)){
+                sql = sql +extend;
+            }
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            Integer resCode = pgJdbc.update(sql);
+            return resCode;
+        }catch(Exception ex){
+            return -1;
+        }
+    }
+
+    //TODO 插入自来水日用水预测数据
+    public int insertTbmWater(String extend){
+        try{
+            String sql = "INSERT INTO tb_m_water " +
+                    "('Date','Month','Week','ActualWaterWithdrawals','ActualWaterSupply'," +
+                    " 'ForecastWaterWithdrawals','ForecastActualWaterSupply','isAbnormal','isForecast','LastModifyTime','orgId' ) " +
+                    " VALUES ";
+            if(StringUtils.isEmpty(extend)){
+                return -1;
+            }
+            sql+=extend;
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            Integer resCode = pgJdbc.update(sql);
+            return resCode;
+        }catch(Exception ex){
+            return -1;
+        }
+    }
+
+    //TODO 修改自来水日用水预测数据
+    public int updateTbmWater(String[] value,String extend){
+        try{
+            String sql = "UPDATE tb_m_water " +
+                    " SET \"Date\" =  "+value[0]+" " +
+                    " AND \"Month\" =  "+value[1]+" " +
+                    " AND \"Week\" =  "+value[2]+" " +
+                    " AND \"ActualWaterWithdrawals\" =  "+value[3]+" " +
+                    " AND \"ActualWaterSupply\" =  "+value[4]+" " +
+                    " AND \"ForecastWaterWithdrawals\" =  "+value[5]+" " +
+                    " AND \"ForecastActualWaterSupply\" =  "+value[6]+" " +
+                    " AND \"isAbnormal\" =  "+value[7]+" " +
+                    " AND \"isForecast\" =  "+value[8]+" " +
+                    " AND \"LastModifyTime\" =  "+value[9]+" " +
+                    " AND \"orgId\" =  "+value[10]+" " +
+                    " ";
+            if(!StringUtils.isEmpty(extend)){
+                sql = sql +extend;
+            }
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            Integer resCode = pgJdbc.update(sql);
+            return resCode;
+        }catch(Exception ex){
+            return -1;
+        }
+    }
+
+    //TODO 添加或修改日预测数据
+    public int insertOrUpdateTbmWater(Map<String,Object> value){
+        try{
+            String sql = "INSERT INTO tb_m_water " +
+                    "(\"date\",\"month\",\"week\"";
+            if(!ObjectUtils.isEmpty(value.get("ActualWaterWithdrawals"))){
+                sql +=  " , \"actual_water_withdrawals\" ";
+            }
+//            if(!ObjectUtils.isEmpty(value.get("ActualWaterSupply"))){
+                sql +=  " ,\"actual_water_supply\"";
+//            }
+            if(!ObjectUtils.isEmpty(value.get("ForecastWaterWithdrawals"))){
+                sql +=  " , \"forecast_water_withdrawals\"";
+            }
+            if(!ObjectUtils.isEmpty(value.get("ForecastActualWaterSupply"))){
+                sql +=  " , \"forecast_actual_waterSupply\"";
+            }
+            sql +=",\"is_abnormal\",\"is_forecast\",\"last_modify_time\",\"zond_id\" ) VALUES ";
+            sql +=" ( ";
+            int i = 1;
+            for (Object key : value.keySet()){
+                if(i==value.keySet().size()){
+                    if(ObjectUtils.isEmpty(value.get(key))){
+                        sql += " NULL ";
+                    }else {
+                        sql += "'" + value.get(key) + "'";
+                    }
+                }else {
+                    if(ObjectUtils.isEmpty(value.get(key))) {
+                        sql += " NULL ,";
+                    }else {
+                        sql += "'" + value.get(key) + "',";
+                    }
+                }
+                i++;
+            }
+            sql += " )";
+            sql += " ON CONFLICT (\"date\",\"zone_id\") " +
+                    " DO UPDATE " +
+                    " SET \"date\" =  '"+value.get("Date")+"' " +
+                    " , \"month\" =  '"+value.get("Month")+"' " +
+                    " , \"week\" =  '"+value.get("Week")+"' ";
+            if(!ObjectUtils.isEmpty(value.get("actual_water_withdrawals"))){
+                sql +=  " , \"actual_water_withdrawals\" =  '"+value.get("ActualWaterWithdrawals")+"' ";
+            }
+            if(!ObjectUtils.isEmpty(value.get("ActualWaterSupply"))){
+                sql +=  " ,\"actual_water_supply\" =  '"+value.get("ActualWaterSupply")+"' ";
+            }
+            if(!ObjectUtils.isEmpty(value.get("ForecastWaterWithdrawals"))){
+                sql +=  " , \"forecast_water_withdrawals\" =  '"+value.get("ForecastWaterWithdrawals")+"' ";
+            }
+            if(!ObjectUtils.isEmpty(value.get("ForecastActualWaterSupply"))){
+                sql +=  " , \"forecast_actual_waterSupply\" =  '"+value.get("ForecastActualWaterSupply")+"' ";
+            }
+
+                sql += " , \"is_abnormal\" =  '"+value.get("isAbnormal")+"' " +
+                    " , \"is_forecast\" =  '"+value.get("isForecast")+"' " +
+                    " , \"last_modify_time\" =  '"+value.get("LastModifyTime")+"' " +
+                    " , \"zone_id\" =  '"+value.get("orgId")+"' ";
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            Integer resCode = pgJdbc.update(sql);
+            return resCode;
+        }catch(Exception ex){
+            return -1;
+        }
+    }
+
+    //TODO 添加或修改日小时预测数据
+    public int insertOrUpdateTbmHourWater(Map<String,Object> value){
+        try{
+            String sql = "INSERT INTO tb_m_hourwater " +
+                    "(\"Date\",\"Hour\"";
+            if(!ObjectUtils.isEmpty(value.get("HourForecastWaterWithdrawals"))){
+                sql +=  " , \"HourForecastWaterWithdrawals\" ";
+            }
+            if(!ObjectUtils.isEmpty(value.get("HourForecastActualWaterSupply"))){
+                sql +=  " ,\"HourForecastActualWaterSupply\"";
+            }
+            if(!ObjectUtils.isEmpty(value.get("HourActualWaterWithdrawals"))){
+                sql +=  " , \"HourActualWaterWithdrawals\"";
+            }
+//            if(!ObjectUtils.isEmpty(value.get("HourActualWaterSupply"))){
+                sql +=  " , \"HourActualWaterSupply\"";
+//            }
+            sql+= ",\"LastModifyTime\",\"orgId\" ) VALUES ";
+            sql +=" ( ";
+            int i = 1;
+            for (Object key : value.keySet()){
+                if(i==value.keySet().size()){
+                    if(ObjectUtils.isEmpty(value.get(key))){
+                        sql += " NULL ";
+                    }else {
+                        sql += "'" + value.get(key) + "'";
+                    }
+                }else {
+                    if(ObjectUtils.isEmpty(value.get(key))) {
+                        sql += " NULL ,";
+                    }else {
+                        sql += "'" + value.get(key) + "',";
+                    }
+                }
+                i++;
+            }
+            sql += " )";
+            sql += " ON CONFLICT (\"Date\",\"orgId\",\"Hour\") " +
+                    " DO UPDATE " +
+                    " SET \"Date\" =  '"+value.get("Date")+"' " +
+                    " , \"Hour\" =  '"+value.get("Hour")+"' ";
+            if(!ObjectUtils.isEmpty(value.get("HourForecastWaterWithdrawals"))){
+                sql +=  " , \"HourForecastWaterWithdrawals\" =  '"+value.get("HourForecastWaterWithdrawals")+"' ";
+            }
+            if(!ObjectUtils.isEmpty(value.get("HourForecastActualWaterSupply"))){
+                sql +=  " ,\"HourForecastActualWaterSupply\" =  '"+value.get("HourForecastActualWaterSupply")+"' ";
+            }
+            if(!ObjectUtils.isEmpty(value.get("HourActualWaterWithdrawals"))){
+                sql +=  " , \"HourActualWaterWithdrawals\" =  '"+value.get("HourActualWaterWithdrawals")+"' ";
+            }
+            if(!ObjectUtils.isEmpty(value.get("HourActualWaterSupply"))){
+                sql +=  " , \"HourActualWaterSupply\" =  '"+value.get("HourActualWaterSupply")+"' ";
+            }
+
+                sql += " , \"LastModifyTime\" =  '"+value.get("LastModifyTime")+"' " +
+                    " , \"orgId\" =  '"+value.get("orgId")+"' ";
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            Integer resCode = pgJdbc.update(sql);
+            return resCode;
+        }catch(Exception ex){
+            return -1;
+        }
+    }
+
+    //TODO 添加或修改日小时开泵预测表
+    public int insertOrUpdateTbmHourwaterWatersupply(Map<String,Object> value){
+        try{
+            String sql = "INSERT INTO tb_m_hourwater_watersupply " +
+                    "(\"date\",\"hour\",\"pump_id\",\"pump_status\",";
+//            if(!ObjectUtils.isEmpty(value.get("hour_forecast_actual_water_supply"))){
+                sql +=  "\"hour_forecast_actual_water_supply\" ,";
+//            }
+            sql+= "\"pump_water\",\"real_pump_status\",\"pump_energy\",\"real_pump_energy\",\"last_modify_time\",\"zone_id\" ) VALUES ";
+            sql +=" ( ";
+            int i = 1;
+            for (Object key : value.keySet()){
+                if(i==value.keySet().size()){
+                    if(ObjectUtils.isEmpty(value.get(key))){
+                        sql += " NULL ";
+                    }else {
+                        sql += "'" + value.get(key) + "'";
+                    }
+                }else {
+                    if(ObjectUtils.isEmpty(value.get(key))) {
+                        sql += " NULL ,";
+                    }else {
+                        sql += "'" + value.get(key) + "',";
+                    }
+                }
+                i++;
+            }
+            sql += " )";
+            sql += " ON CONFLICT (\"date\",\"zone_id\",\"hour\",\"pump_id\") " +
+                    " DO UPDATE " +
+                    " SET \"date\" =  '"+value.get("Date")+"' " +
+                    " , \"hour\" =  '"+value.get("Hour")+"' "+
+                    " , \"pump_id\" =  '"+value.get("PumpID")+"' "+
+                    " , \"pump_status\" =  "+value.get("PumpStatus")+" ";
+            if(!ObjectUtils.isEmpty(value.get("HourForecastActualWaterSupply"))){
+                sql +=  " ,\"hour_forecast_actual_water_supply\" =  '"+value.get("HourForecastActualWaterSupply")+"' ";
+            }
+            if(!ObjectUtils.isEmpty(value.get("PumpWater"))){
+                sql +=  " , \"pump_water\" =  '"+value.get("PumpWater")+"' ";
+            }
+            if(!ObjectUtils.isEmpty(value.get("RealPumpStatus"))){
+                sql +=  " , \"real_pump_status\" =  "+value.get("RealPumpStatus")+" ";
+            }
+            if(!ObjectUtils.isEmpty(value.get("PumpEnergy"))){
+                sql +=  " , \"pump_energy\" =  '"+value.get("PumpEnergy")+"' ";
+            }
+            if(!ObjectUtils.isEmpty(value.get("RealPumpEnergy"))){
+                sql +=  " , \"real_pump_energy\" =  '"+value.get("RealPumpEnergy")+"' ";
+            }
+
+                sql += " , \"last_modify_time\" =  '"+value.get("LastModifyTime")+"' " +
+                    " , \"zone_id\" =  '"+value.get("orgId")+"' ";
+            JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+            Integer resCode = pgJdbc.update(sql);
+            return resCode;
+        }catch(Exception ex){
+            return -1;
+        }
+    }
+
+    //TODO 查询水厂id配置列表
+    public List<Map<String,Object>> getOrgConfig(boolean isPage,int limit,int offset,String extend){
+
+        String sql = "SELECT * FROM water_org_config WHERE 1=1 ";
+        if(!StringUtils.isEmpty(extend)){
+            sql+=extend;
+        }
+        if(isPage) {
+            sql += " LIMIT " + limit + " OFFSET " + offset;
+        }
+        JdbcTemplate pgJdbc = new JdbcTemplate(childDataSource);
+        List<Map<String, Object>> tableData = pgJdbc.queryForList(sql);
+        return tableData;
+
+    }
+}

+ 355 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/dbdao/services/WaterTapWaterServiceImpl.java

@@ -0,0 +1,355 @@
+package io.github.pnoker.gateway.dbdao.services;
+
+
+import io.github.pnoker.gateway.comtool.ScheduleTaskMgr;
+import io.github.pnoker.gateway.dbdao.mapper.WaterYuceDao;
+import io.github.pnoker.gateway.dbdao.mapper.WaterZILAISHUIDao;
+import io.github.pnoker.gateway.dbdao.services.intef.WaterTapWaterService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+import java.util.List;
+import java.util.Map;
+
+@Service
+public class WaterTapWaterServiceImpl implements WaterTapWaterService {
+    private static final Logger log = LoggerFactory.getLogger(WaterTapWaterServiceImpl.class);
+    private String mStrClassName = "";
+    public WaterTapWaterServiceImpl() {
+        mStrClassName = this.getClass().getSimpleName();
+    }
+
+    @SuppressWarnings("all")
+    @Autowired
+    private WaterZILAISHUIDao waterZILAISHUIDao;
+
+    @SuppressWarnings("all")
+    @Autowired
+    private WaterYuceDao waterYuceDao;
+
+    @Override
+    public Integer getTabWaterHistoryCount(String extend) {
+        int nCode = 0;
+        String strMsg = "Success";
+        Integer arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.getTabWaterHistoryCount(extend);
+        }catch (Exception e){
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        }finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Query TabWaterCount:{%s},{%s} from database, code:{%s} msg:{%s} ..."
+//                            , arrRes
+//                            ,extend
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public List<Map<String, Object>> getPageZILAISHUI_HISTORY2(int limit, int offset, String extend) {
+        int nCode = 0;
+        String strMsg = "Success";
+        List<Map<String, Object>> arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.getPageZILAISHUI_HISTORY2(limit,offset,extend);
+        }catch (Exception e){
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        }finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Query TabWaterHistory from database, code:{%d} msg:{%s} ..."
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public List<Map<String,Object>> getWaterCollectionConfigList(String extend) {
+        int nCode = 0;
+        String strMsg = "Success";
+        List<Map<String, Object>> arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.getWaterCollectionConfigList(extend);
+        }catch (Exception e){
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        }finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Query TabWaterHistory from database, code:{%d} msg:{%s} ..."
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public List<Map<String, Object>> getWaterCollectionRecordList(int limit, int offset, String extend) {
+        int nCode = 0;
+        String strMsg = "Success";
+        List<Map<String, Object>> arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.getWaterCollectionRecordList(limit,offset,extend);
+        }catch (Exception e){
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        }finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Query TabWaterHistory from database, code:{%d} msg:{%s} ..."
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public List<Map<String, Object>> getWaterCollectionRecordAllList(int limit, int offset, String extend) {
+        int nCode = 0;
+        String strMsg = "Success";
+        List<Map<String, Object>> arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.getWaterCollectionRecordAllList(limit,offset,extend);
+        }catch (Exception e){
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        }finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Query TabWaterHistory from database, code:{%d} msg:{%s} ..."
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public List<Map<String, Object>> getWaterCollectionRecordAllListAll( String extend) {
+        int nCode = 0;
+        String strMsg = "Success";
+        List<Map<String, Object>> arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.getWaterCollectionRecordAllListAll(extend);
+        }catch (Exception e){
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        }finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Query TabWaterHistory from database, code:{%d} msg:{%s} ..."
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public Integer insertWaterCollectionRecord(String extend) {
+        int nCode = 0;
+        String strMsg = "Success";
+        Integer arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.insertWaterCollectionRecord(extend);
+        }catch (Exception e){
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        }finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Insert WaterRecord:{%s} from database, code:{%s} msg:{%s} ..."
+//                            , arrRes
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public Integer insertWaterCollectionRecordAll(String extend) {
+        int nCode = 0;
+        String strMsg = "Success";
+        Integer arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.insertWaterCollectionRecordAll(extend);
+        }catch (Exception e){
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        }finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Insert WaterRecord:{%s} from database, code:{%s} msg:{%s} ..."
+//                            , arrRes
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public Integer updateWaterCollectionRecordAll(String value,String extend) {
+        int nCode = 0;
+        String strMsg = "Success";
+        Integer arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.updateWaterCollectionRecordAll(value,extend);
+        }catch (Exception e){
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        }finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Insert WaterRecord:{%s} from database, code:{%s} msg:{%s} ..."
+//                            , arrRes
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public List<Map<String, Object>> getWaterYuceConfig(boolean isPage, int limit, int offset, String extend) throws Exception{
+        int nCode = 0;
+        String strMsg = "Success";
+        List<Map<String, Object>> arrRes = null;
+        try {
+            arrRes = waterYuceDao.getWaterYuceConfig(isPage,limit,offset,extend);
+        }catch (Exception e){
+            throw new Exception(e.getLocalizedMessage());
+
+        }finally {
+            log.error(String.format("Batch Query TbMWater from database, code:{%d} msg:{%s} ..."
+                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public Integer insertTbmWater(String extend) {
+        int nCode = 0;
+        String strMsg = "Success";
+        Integer arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.insertTbmWater(extend);
+        }catch (Exception e){
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        }finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Insert WaterRecord:{%s} from database, code:{%s} msg:{%s} ..."
+//                            , arrRes
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public Integer updateTbmWater(String[] value, String extend) {
+        int nCode = 0;
+        String strMsg = "Success";
+        Integer arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.updateTbmWater(value, extend);
+        } catch (Exception e) {
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        } finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Insert WaterRecord:{%s} from database, code:{%s} msg:{%s} ..."
+//                            , arrRes
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public Integer insertOrUpdateTbmWater(Map<String, Object> value) {
+        int nCode = 0;
+        String strMsg = "Success";
+        Integer arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.insertOrUpdateTbmWater(value);
+        } catch (Exception e) {
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        } finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Insert WaterRecord:{%s} from database, code:{%s} msg:{%s} ..."
+//                            , arrRes
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public Integer insertOrUpdateTbmHourWater(Map<String, Object> value) {
+        int nCode = 0;
+        String strMsg = "Success";
+        Integer arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.insertOrUpdateTbmHourWater(value);
+        } catch (Exception e) {
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        } finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Insert WaterRecord:{%s} from database, code:{%s} msg:{%s} ..."
+//                            , arrRes
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public Integer insertOrUpdateTbmHourwaterWatersupply(Map<String, Object> value) {
+        int nCode = 0;
+        String strMsg = "Success";
+        Integer arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.insertOrUpdateTbmHourwaterWatersupply(value);
+        } catch (Exception e) {
+            log.error(mStrClassName+",error:"+e.getLocalizedMessage());
+            strMsg = e.getLocalizedMessage();
+        } finally {
+//            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.valueFromInt(nCode)
+//                    , LogFlagBusiType.BUSI_CHILD_DB_TAP_WATER.toStrValue()
+//                    , mStrClassName
+//                    , String.format("Batch Insert WaterRecord:{%s} from database, code:{%s} msg:{%s} ..."
+//                            , arrRes
+//                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+
+    @Override
+    public List<Map<String, Object>> getOrgConfig(boolean isPage, int limit, int offset, String extend) throws Exception{
+        int nCode = 0;
+        String strMsg = "Success";
+        List<Map<String, Object>> arrRes = null;
+        try {
+            arrRes = waterZILAISHUIDao.getOrgConfig(isPage,limit,offset,extend);
+        }catch (Exception e){ throw new Exception(e.getLocalizedMessage());
+
+
+        }finally {
+            log.error(String.format("Batch Query getOrgConfig from database, code:{%d} msg:{%s} ..."
+                            , nCode, strMsg));
+        }
+        return arrRes;
+    }
+}

+ 49 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/dbdao/services/intef/WaterTapWaterService.java

@@ -0,0 +1,49 @@
+package io.github.pnoker.gateway.dbdao.services.intef;
+
+import java.util.List;
+import java.util.Map;
+
+public interface WaterTapWaterService {
+
+    //TODO orcale 获取江津历史用水记录总数
+    public Integer getTabWaterHistoryCount(String extend);
+
+    //TODO orcale 获取江津历史用水记录·分页
+    public List<Map<String,Object>> getPageZILAISHUI_HISTORY2(int limit, int offset, String extend);
+
+    //TODO pgsql 获取江津历史用水配置关系记录
+    public List<Map<String,Object>> getWaterCollectionConfigList(String extend);
+
+    //TODO pgsql 查询江津历史记录表·分页
+    public List<Map<String,Object>> getWaterCollectionRecordList(int limit, int offset, String extend);
+
+    //TODO pgsql 查询江津小时用水量记录表·分页
+    public List<Map<String,Object>> getWaterCollectionRecordAllList(int limit, int offset, String extend);
+    //TODO pgsql 查询江津小时用水量记录表·不分页
+    public List<Map<String,Object>> getWaterCollectionRecordAllListAll(String extend);
+
+    //TODO pgsql 插入自来水历史记录表
+    public Integer insertWaterCollectionRecord(String extend);
+    //TODO pgsql 插入自来水小时用水量记录表
+    public Integer insertWaterCollectionRecordAll(String extend);
+    //TODO pgsql 修改自来水小时用水量记录
+    public Integer updateWaterCollectionRecordAll(String value, String extend);
+
+
+    //TODO 获取预测数据自添加配置
+    public List<Map<String,Object>> getWaterYuceConfig(boolean isPage, int limit, int offset, String extend)throws Exception;
+    //TODO pgsql 插入自来水日用水预测数据
+    public Integer insertTbmWater(String extend);
+    //TODO pgsql 修改自来水日用水预测数据
+    public Integer updateTbmWater(String value[], String extend);
+    //TODO 添加或修改日预测数据
+    public Integer insertOrUpdateTbmWater(Map<String, Object> value);
+    //TODO 添加或修改日小时预测数据
+    public Integer insertOrUpdateTbmHourWater(Map<String, Object> value);
+    //TODO 添加或修改日小时开泵预测表
+    public Integer insertOrUpdateTbmHourwaterWatersupply(Map<String, Object> value);
+
+
+    //TODO 获取水厂配置
+    public List<Map<String,Object>> getOrgConfig(boolean isPage,int limit,int offset,String extend)throws Exception;
+}

+ 45 - 0
dc3-gateway/src/main/java/io/github/pnoker/gateway/utils/InfulxJiangjinDbUtil.java

@@ -7,6 +7,7 @@ import org.influxdb.InfluxDBFactory;
 import org.influxdb.dto.BatchPoints;
 import org.influxdb.dto.Point;
 import org.influxdb.dto.Query;
+import org.influxdb.dto.QueryResult;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 
@@ -72,4 +73,48 @@ public class InfulxJiangjinDbUtil {
         }
     }
 
+    /**
+     * 带有 WHERE 条件的分页查询方法
+     *
+     * @param measurement 要查询的测量名称
+     * @param limit 每页返回的记录数
+     * @param offset 跳过的记录数
+     * @param extend 自定义的 WHERE 条件
+     * @return 查询结果
+     */
+    public QueryResult queryWithPaginationAndCondition(String measurement, int limit, int offset, String extend) {
+        try {
+            // 构建查询字符串
+            String queryString = String.format("SELECT * FROM %s WHERE %s LIMIT %d OFFSET %d",
+                    measurement, extend, limit, offset);
+            Query query = new Query(queryString, database);
+            return influxDB.query(query);
+        } catch (Exception ex) {
+            ex.printStackTrace();
+            return null;
+        }
+    }
+
+    /**
+     * 带有 WHERE 条件的查询方法
+     *
+     * @param measurement 要查询的测量名称
+     * @param extend 自定义的 WHERE 条件
+     * @return 查询结果
+     */
+    public QueryResult queryWithCondition(String measurement, String extend) {
+        try {
+            // 构建查询字符串
+            String queryString = String.format("SELECT * FROM %s WHERE %s " +
+                            " ORDER BY time " +
+                            " tz('Asia/Shanghai')",
+                    measurement, extend);
+            Query query = new Query(queryString, database);
+            return influxDB.query(query);
+        } catch (Exception ex) {
+            ex.printStackTrace();
+            return null;
+        }
+    }
+
 }

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 4 - 4
dc3-gateway/src/main/resources/application-jiangjin.yml


+ 6 - 1
dc3-gateway/src/main/resources/application.yml

@@ -149,6 +149,11 @@ spring:
             username: v_shizilaishui
             password: ShiZiLaiShui@0811
             driver-class-name: oracle.jdbc.driver.OracleDriver
+      childpg:
+        driver-class-name: org.postgis.DriverWrapper
+        jdbc-url: jdbc:postgresql_postGIS://10.101.3.104:5432/water_volume_prediction_jiangjin?useSSL=false&useAffectedRows=false&allowMultiQueries=true
+        username: postgres
+        password: kpr.23417.postgres
   jpa:
     show-sql: false
 
@@ -242,5 +247,5 @@ zilaishui:
   #influxdb相关配置
   inluxdb:
     database: iot_test
-  #  database: iot
+#    database: iot
     serverUrl: http://10.101.5.201:8086