refactor(biz): 优化模板参数过滤逻辑

- 统计每个占位符在模板中出现的次数
- 根据占位符出现次数和实际可用源数量,选择合适的源进行过滤
- 优化日志输出,增加占位符统计信息
This commit is contained in:
2025-09-19 18:48:52 +08:00
parent 9226dfff1d
commit f10ede0d2c

View File

@@ -14,6 +14,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@@ -134,26 +135,42 @@ public class TemplateBiz {
return Map.of(); return Map.of();
} }
// 统计每个 placeholder 在模板中出现的次数
Map<String, Long> placeholderCounts = templatePlaceholders.stream()
.collect(Collectors.groupingBy(
placeholder -> placeholder,
Collectors.counting()
));
Map<String, List<SourceEntity>> filteredParams = new HashMap<>(); Map<String, List<SourceEntity>> filteredParams = new HashMap<>();
for (String placeholder : templatePlaceholders) { for (Map.Entry<String, Long> entry : placeholderCounts.entrySet()) {
String placeholder = entry.getKey();
Long requiredCount = entry.getValue();
if (placeholder.startsWith("P")) { if (placeholder.startsWith("P")) {
// 图片源:占位符格式为 "P{deviceId}" // 图片源:占位符格式为 "P{deviceId}"
String imageKey = placeholder; String imageKey = placeholder;
if (allTaskParams.containsKey(imageKey)) { if (allTaskParams.containsKey(imageKey)) {
filteredParams.put(imageKey, allTaskParams.get(imageKey)); List<SourceEntity> allSources = allTaskParams.get(imageKey);
int actualCount = Math.min(requiredCount.intValue(), allSources.size());
List<SourceEntity> selectedSources = allSources.subList(0, actualCount);
filteredParams.put(imageKey, new ArrayList<>(selectedSources));
} }
} else { } else {
// 视频源:占位符直接对应设备ID // 视频源:占位符直接对应设备ID
String videoKey = placeholder; String videoKey = placeholder;
if (allTaskParams.containsKey(videoKey)) { if (allTaskParams.containsKey(videoKey)) {
filteredParams.put(videoKey, allTaskParams.get(videoKey)); List<SourceEntity> allSources = allTaskParams.get(videoKey);
int actualCount = Math.min(requiredCount.intValue(), allSources.size());
List<SourceEntity> selectedSources = allSources.subList(0, actualCount);
filteredParams.put(videoKey, new ArrayList<>(selectedSources));
} }
} }
} }
log.info("filterTaskParams: templateId:{}, original keys:{}, filtered keys:{}", log.info("filterTaskParams: templateId:{}, original keys:{}, filtered keys:{}, placeholder counts:{}",
templateId, allTaskParams.keySet().size(), filteredParams.keySet().size()); templateId, allTaskParams.keySet().size(), filteredParams.keySet().size(), placeholderCounts);
return filteredParams; return filteredParams;
} }