From 0541c0791acea41b584f71fc59e22d4d21ba0883 Mon Sep 17 00:00:00 2001
From: 云 <2163098428@qq.com>
Date: 星期三, 15 四月 2026 11:10:46 +0800
Subject: [PATCH] ``` refactor(energy): 优化实时能耗数据服务实现

---
 src/main/java/com/ruoyi/inspectiontask/service/impl/TimingTaskJob.java |  230 ++++++++++++++++++++++++++++++---------------------------
 1 files changed, 121 insertions(+), 109 deletions(-)

diff --git a/src/main/java/com/ruoyi/inspectiontask/service/impl/TimingTaskJob.java b/src/main/java/com/ruoyi/inspectiontask/service/impl/TimingTaskJob.java
index 44ad63d..5a0e6ab 100644
--- a/src/main/java/com/ruoyi/inspectiontask/service/impl/TimingTaskJob.java
+++ b/src/main/java/com/ruoyi/inspectiontask/service/impl/TimingTaskJob.java
@@ -1,31 +1,41 @@
 package com.ruoyi.inspectiontask.service.impl;
 
+import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.device.mapper.DeviceLedgerMapper;
+import com.ruoyi.device.pojo.DeviceLedger;
 import com.ruoyi.inspectiontask.mapper.InspectionTaskMapper;
 import com.ruoyi.inspectiontask.mapper.TimingTaskMapper;
 import com.ruoyi.inspectiontask.pojo.InspectionTask;
 import com.ruoyi.inspectiontask.pojo.TimingTask;
 import com.ruoyi.inspectiontask.service.TimingTaskService;
-import org.quartz.*;
+import org.quartz.DisallowConcurrentExecution;
+import org.quartz.Job;
+import org.quartz.JobDataMap;
+import org.quartz.JobExecutionContext;
+import org.quartz.JobExecutionException;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.stereotype.Component;
 
-import javax.annotation.Resource;
-import javax.sql.DataSource;
 import java.io.Serializable;
+import java.math.BigDecimal;
 import java.time.DayOfWeek;
 import java.time.LocalDateTime;
 import java.time.LocalTime;
 import java.time.YearMonth;
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Objects;
 import java.util.Set;
+import java.util.stream.Collectors;
 
 @Component
-@DisallowConcurrentExecution // 绂佹骞跺彂鎵ц鍚屼竴涓狫ob
+@DisallowConcurrentExecution
 public class TimingTaskJob implements Job, Serializable {
-    private static final long serialVersionUID = 1L; // 蹇呴』瀹氫箟搴忓垪鍖朓D
+    private static final long serialVersionUID = 1L;
 
     @Autowired
     private TimingTaskMapper timingTaskMapper;
@@ -39,93 +49,96 @@
     @Autowired
     private JdbcTemplate jdbcTemplate;
 
+    @Autowired
+    private DeviceLedgerMapper deviceLedgerMapper;
+
     @Override
     public void execute(JobExecutionContext context) throws JobExecutionException {
         JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
-        // 淇绫诲瀷杞崲閿欒锛屾纭幏鍙杢askId
         Long taskId = jobDataMap.getLong("taskId");
 
         try {
-            // 3. 灏濊瘯鏌ヨ浣犵殑涓氬姟鏁版嵁
-            // 閫氳繃JDBC妯℃澘鏌ヨ瀹氭椂浠诲姟淇℃伅锛屼娇鐢ㄥ弬鏁板寲鏌ヨ闃叉SQL娉ㄥ叆
-            String yourSql = "SELECT * FROM timing_task where id = ?";
+            String sql = "SELECT * FROM timing_task WHERE id = ?";
             List<TimingTask> tasks = jdbcTemplate.query(
-                    yourSql,
+                    sql,
                     new BeanPropertyRowMapper<>(TimingTask.class),
                     taskId
             );
             TimingTask timingTask = tasks.isEmpty() ? null : tasks.get(0);
             if (timingTask == null) {
-                throw new JobExecutionException("鎵句笉鍒板畾鏃朵换鍔�: " + taskId);
+                throw new RuntimeException("瀹氭椂浠诲姟涓嶅瓨鍦細 " + taskId);
             }
-            
-//            if (!timingTask.isActive()) {
-//                throw new JobExecutionException("瀹氭椂浠诲姟宸茬鐢�: " + taskId);
-//            }
 
-            // 2. 鍒涘缓骞朵繚瀛樺贰妫�浠诲姟璁板綍 - 杩欏氨鏄偍鎻愪緵鐨勪唬鐮佸簲璇ユ斁鐨勪綅缃�
-            InspectionTask inspectionTask = createInspectionTask(timingTask);
-            inspectionTaskMapper.insert(inspectionTask);
+            List<Long> deviceIds = resolveTaskIds(timingTask);
+            if (deviceIds.isEmpty()) {
+                throw new RuntimeException("璁惧涓嶅瓨鍦細 " + taskId);
+            }
 
-            // 3. 鏇存柊瀹氭椂浠诲姟鐨勬墽琛屾椂闂�
+            for (Long deviceId : deviceIds) {
+                DeviceLedger deviceLedger = deviceLedgerMapper.selectById(deviceId);
+                if (deviceLedger == null) {
+                    continue;
+                }
+                int count = getDeviceCount(deviceLedger.getNumber());
+                for (int i = 0; i < count; i++) {
+                    inspectionTaskMapper.insert(createInspectionTask(timingTask, deviceLedger));
+                }
+            }
+
             if (!tasks.isEmpty()) {
-                TimingTask task = tasks.get(0);
-
-                // 鏇存柊鏈�鍚庢墽琛屾椂闂翠负褰撳墠鏃堕棿
                 LocalDateTime lastExecutionTime = LocalDateTime.now();
-
-                // 璁$畻涓嬫鎵ц鏃堕棿
                 LocalDateTime nextExecutionTime = calculateNextExecutionTime(
-                        task.getFrequencyType(),
-                        task.getFrequencyDetail(),
+                        timingTask.getFrequencyType(),
+                        timingTask.getFrequencyDetail(),
                         lastExecutionTime
                 );
-
-                // 鎵ц鏇存柊鎿嶄綔
-                String updateSql = "UPDATE timing_task " +
-                        "SET last_execution_time = ?, next_execution_time = ? " +
-                        "WHERE id = ?";
-
-                jdbcTemplate.update(
-                        updateSql,
-                        lastExecutionTime,
-                        nextExecutionTime,
-                        taskId
-                );
+                String updateSql = "UPDATE timing_task SET last_execution_time = ?, next_execution_time = ? WHERE id = ?";
+                jdbcTemplate.update(updateSql, lastExecutionTime, nextExecutionTime, taskId);
             }
-//            timingTaskService.updateTaskExecutionTime(taskId);
-
-            // 4. 璁板綍鎵ц鏃ュ織
-//            timingTaskService.recordExecutionLog(taskId, true, "浠诲姟鎵ц鎴愬姛锛岀敓鎴愬贰妫�浠诲姟ID: " + inspectionTask.getId());
-
         } catch (Exception e) {
-//            timingTaskService.recordExecutionLog(taskId, false, "浠诲姟鎵ц澶辫触: " + e.getMessage());
             throw new JobExecutionException(e);
         }
     }
 
-    // 杩欏氨鏄偍鎻愪緵鐨勪唬鐮佸皝瑁呮垚鐨勬柟娉�
-    private InspectionTask createInspectionTask(TimingTask timingTask) {
-        InspectionTask inspectionTask = new InspectionTask();
+    private List<Long> resolveTaskIds(TimingTask timingTask) {
+        if (StringUtils.isNotBlank(timingTask.getTaskIdsStr())) {
+            return Arrays.stream(timingTask.getTaskIdsStr().split(","))
+                    .filter(StringUtils::isNotBlank)
+                    .map(String::trim)
+                    .map(Long::valueOf)
+                    .distinct()
+                    .collect(Collectors.toList());
+        }
+        if (timingTask.getTaskId() != null) {
+            return new ArrayList<>(Arrays.asList(timingTask.getTaskId().longValue()));
+        }
+        return new ArrayList<>();
+    }
 
-        // 澶嶅埗鍩烘湰灞炴��
-        inspectionTask.setTaskName(timingTask.getTaskName());
-        inspectionTask.setTaskId(timingTask.getTaskId());
+    private int getDeviceCount(BigDecimal number) {
+        if (number == null) {
+            return 1;
+        }
+        int count = number.intValue();
+        return count > 0 ? count : 1;
+    }
+
+    private InspectionTask createInspectionTask(TimingTask timingTask, DeviceLedger deviceLedger) {
+        InspectionTask inspectionTask = new InspectionTask();
+        inspectionTask.setTaskName(deviceLedger.getDeviceName());
+        inspectionTask.setTaskId(deviceLedger.getId().intValue());
+        inspectionTask.setAreaId(deviceLedger.getAreaId());
         inspectionTask.setInspectorId(timingTask.getInspectorIds());
         inspectionTask.setInspectionLocation(timingTask.getInspectionLocation());
-        inspectionTask.setRemarks("鑷姩鐢熸垚鑷畾鏃朵换鍔D: " + timingTask.getId());
+        inspectionTask.setRemarks("瀹氭椂鐢熸垚璁惧宸℃浠诲姟 ID: " + timingTask.getId());
         inspectionTask.setRegistrantId(timingTask.getRegistrantId());
+        inspectionTask.setRegistrant(timingTask.getRegistrant());
         inspectionTask.setFrequencyType(timingTask.getFrequencyType());
         inspectionTask.setFrequencyDetail(timingTask.getFrequencyDetail());
         inspectionTask.setTenantId(timingTask.getTenantId());
-
         return inspectionTask;
     }
 
-
-    /**
-     * 璁$畻涓嬫鎵ц鏃堕棿
-     */
     private LocalDateTime calculateNextExecutionTime(String frequencyType,
                                                      String frequencyDetail,
                                                      LocalDateTime currentTime) {
@@ -139,94 +152,64 @@
                     return calculateMonthlyNextTime(frequencyDetail, currentTime);
                 case "QUARTERLY":
                     return calculateQuarterlyNextTime(frequencyDetail, currentTime);
+                case "YEARLY":
+                    return calculateYearlyNextTime(frequencyDetail, currentTime);
                 default:
-                    throw new IllegalArgumentException("涓嶆敮鎸佺殑棰戠巼绫诲瀷: " + frequencyType);
+                    throw new IllegalArgumentException("娑撳秵鏁幐浣烘畱妫版垹宸肩猾璇茬��: " + frequencyType);
             }
         } catch (Exception e) {
-            throw new RuntimeException("璁$畻涓嬫鎵ц鏃堕棿澶辫触: " + e.getMessage(), e);
+            throw new RuntimeException("鐠侊紕鐣绘稉瀣偧閹笛嗩攽閺冨爼妫挎径杈Е: " + e.getMessage(), e);
         }
     }
 
-    /**
-     * 璁$畻姣忔棩浠诲姟鐨勪笅娆℃墽琛屾椂闂�
-     */
     private LocalDateTime calculateDailyNextTime(String timeStr, LocalDateTime current) {
-        LocalTime executionTime = LocalTime.parse(timeStr); // 瑙f瀽鏍煎紡 "HH:mm"
+        LocalTime executionTime = LocalTime.parse(timeStr);
         LocalDateTime nextTime = LocalDateTime.of(current.toLocalDate(), executionTime);
-
-        // 濡傛灉浠婂ぉ鐨勬椂闂村凡杩囷紝鍒欏畨鎺掓槑澶�
         return current.isBefore(nextTime) ? nextTime : nextTime.plusDays(1);
     }
 
-    /**
-     * 璁$畻姣忓懆浠诲姟鐨勪笅娆℃墽琛屾椂闂�
-     */
     private LocalDateTime calculateWeeklyNextTime(String detail, LocalDateTime current) {
         String[] parts = detail.split(",");
-        String dayOfWeekStr = parts[0];  // 濡� "MON" 鎴� "MON|WED|FRI"
-        LocalTime time = LocalTime.parse(parts[1]); // 鏃堕棿閮ㄥ垎
-
-        // 瑙f瀽鏄熸湡鍑�(鏀寔澶氫釜鏄熸湡)
+        String dayOfWeekStr = parts[0];
+        LocalTime time = LocalTime.parse(parts[1]);
         Set<DayOfWeek> targetDays = parseDayOfWeeks(dayOfWeekStr);
 
-        // 浠庡綋鍓嶆椂闂村紑濮嬫壘涓嬩竴涓鍚堟潯浠剁殑鏄熸湡鍑�
         LocalDateTime nextTime = current;
         while (true) {
             nextTime = nextTime.plusDays(1);
             if (targetDays.contains(nextTime.getDayOfWeek())) {
                 return LocalDateTime.of(nextTime.toLocalDate(), time);
             }
-
-            // 闃叉鏃犻檺寰幆(鐞嗚涓婁笉浼氬彂鐢�)
             if (nextTime.isAfter(current.plusYears(1))) {
-                throw new RuntimeException("鏃犳硶鎵惧埌涓嬫鎵ц鏃堕棿");
+                throw new RuntimeException("閺冪姵纭堕幍鎯у煂娑撳顐奸幍褑顢戦弮鍫曟?");
             }
         }
     }
 
-    /**
-     * 璁$畻姣忔湀浠诲姟鐨勪笅娆℃墽琛屾椂闂�
-     */
     private LocalDateTime calculateMonthlyNextTime(String detail, LocalDateTime current) {
         String[] parts = detail.split(",");
         int dayOfMonth = Integer.parseInt(parts[0]);
         LocalTime time = LocalTime.parse(parts[1]);
-
-        // 浠庝笅涓湀寮�濮嬭绠�
-        LocalDateTime nextTime = current.plusMonths(1)
+        return current.plusMonths(1)
                 .withDayOfMonth(Math.min(dayOfMonth, current.plusMonths(1).toLocalDate().lengthOfMonth()))
                 .with(time);
-
-        return nextTime;
     }
 
-    /**
-     * 璁$畻姣忓搴︿换鍔$殑涓嬫鎵ц鏃堕棿
-     */
     private LocalDateTime calculateQuarterlyNextTime(String detail, LocalDateTime current) {
         String[] parts = detail.split(",");
-        int quarterMonth = Integer.parseInt(parts[0]); // 1=绗�1涓湀锛�2=绗�2涓湀锛�3=绗�3涓湀
+        int quarterMonth = Integer.parseInt(parts[0]);
         int dayOfMonth = Integer.parseInt(parts[1]);
         LocalTime time = LocalTime.parse(parts[2]);
 
-        // 璁$畻褰撳墠瀛e害
-        int currentQuarter = (current.getMonthValue() - 1) / 3 + 1;
         int currentMonthInQuarter = (current.getMonthValue() - 1) % 3 + 1;
-
         YearMonth targetYearMonth;
         if (currentMonthInQuarter < quarterMonth) {
-            // 鏈搴﹀唴杩樻湁鎵ц鏈轰細
-            targetYearMonth = YearMonth.from(current)
-                    .plusMonths(quarterMonth - currentMonthInQuarter);
+            targetYearMonth = YearMonth.from(current).plusMonths(quarterMonth - currentMonthInQuarter);
         } else {
-            // 闇�瑕佸埌涓嬩釜瀛e害
-            targetYearMonth = YearMonth.from(current)
-                    .plusMonths(3 - currentMonthInQuarter + quarterMonth);
+            targetYearMonth = YearMonth.from(current).plusMonths(3 - currentMonthInQuarter + quarterMonth);
         }
 
-        // 澶勭悊鏈堟湯鏃ユ湡
         int adjustedDay = Math.min(dayOfMonth, targetYearMonth.lengthOfMonth());
-
         return LocalDateTime.of(
                 targetYearMonth.getYear(),
                 targetYearMonth.getMonthValue(),
@@ -236,23 +219,52 @@
         );
     }
 
-    /**
-     * 瑙f瀽鏄熸湡鍑犲瓧绗︿覆
-     */
+    private LocalDateTime calculateYearlyNextTime(String detail, LocalDateTime current) {
+        String[] parts = detail.split(",");
+        int month = Integer.parseInt(parts[0]);
+        int dayOfMonth = Integer.parseInt(parts[1]);
+        LocalTime time = LocalTime.parse(parts[2]);
+
+        YearMonth targetYearMonth = YearMonth.of(current.getYear(), month);
+        int adjustedDay = Math.min(dayOfMonth, targetYearMonth.lengthOfMonth());
+        LocalDateTime target = LocalDateTime.of(current.getYear(), month, adjustedDay, time.getHour(), time.getMinute());
+        if (!target.isAfter(current)) {
+            targetYearMonth = YearMonth.of(current.getYear() + 1, month);
+            adjustedDay = Math.min(dayOfMonth, targetYearMonth.lengthOfMonth());
+            target = LocalDateTime.of(current.getYear() + 1, month, adjustedDay, time.getHour(), time.getMinute());
+        }
+        return target;
+    }
+
     private Set<DayOfWeek> parseDayOfWeeks(String dayOfWeekStr) {
         Set<DayOfWeek> days = new HashSet<>();
         String[] dayStrs = dayOfWeekStr.split("\\|");
 
         for (String dayStr : dayStrs) {
             switch (dayStr) {
-                case "MON": days.add(DayOfWeek.MONDAY); break;
-                case "TUE": days.add(DayOfWeek.TUESDAY); break;
-                case "WED": days.add(DayOfWeek.WEDNESDAY); break;
-                case "THU": days.add(DayOfWeek.THURSDAY); break;
-                case "FRI": days.add(DayOfWeek.FRIDAY); break;
-                case "SAT": days.add(DayOfWeek.SATURDAY); break;
-                case "SUN": days.add(DayOfWeek.SUNDAY); break;
-                default: throw new IllegalArgumentException("鏃犳晥鐨勬槦鏈熷嚑: " + dayStr);
+                case "MON":
+                    days.add(DayOfWeek.MONDAY);
+                    break;
+                case "TUE":
+                    days.add(DayOfWeek.TUESDAY);
+                    break;
+                case "WED":
+                    days.add(DayOfWeek.WEDNESDAY);
+                    break;
+                case "THU":
+                    days.add(DayOfWeek.THURSDAY);
+                    break;
+                case "FRI":
+                    days.add(DayOfWeek.FRIDAY);
+                    break;
+                case "SAT":
+                    days.add(DayOfWeek.SATURDAY);
+                    break;
+                case "SUN":
+                    days.add(DayOfWeek.SUNDAY);
+                    break;
+                default:
+                    throw new IllegalArgumentException("閺冪姵鏅ラ惃鍕Е閺�? " + dayStr);
             }
         }
 

--
Gitblit v1.9.3