DeviceSearchService.java
3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.iot.scheduler.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import jakarta.annotation.Resource;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class DeviceSearchService {
@Value("${device.db.corpCode}")
private String deviceCorpCode;
@Value("${device.db.tableName}")
private String deviceTableName;
@Resource
private JdbcTemplate jdbcTemplate;
public Map<String, Object> queryDeviceList(String deviceName, String lampState, Integer pageNo, Integer pageSize) {
StringBuilder countSql = new StringBuilder("SELECT COUNT(*) FROM " + deviceTableName + " WHERE corp_code = ?");
StringBuilder querySql = new StringBuilder("SELECT id, deviceName, projectType, projectState, dtuSn, dtuId, deviceId, " +
"lampState, startTime, duration, utilizationRate FROM " + deviceTableName + " WHERE corp_code = ?");
List<Object> params = new java.util.ArrayList<>();
params.add(deviceCorpCode);
if (StringUtils.hasText(deviceName)) {
countSql.append(" AND deviceName LIKE ?");
querySql.append(" AND deviceName LIKE ?");
params.add("%" + deviceName + "%");
}
if (StringUtils.hasText(lampState)) {
countSql.append(" AND lampState = ?");
querySql.append(" AND lampState = ?");
params.add(lampState);
}
Long total = jdbcTemplate.queryForObject(countSql.toString(), Long.class, params.toArray());
int offset = (pageNo - 1) * pageSize;
querySql.append(" ORDER BY created_at DESC LIMIT ?, ?");
params.add(offset);
params.add(pageSize);
List<Map<String, Object>> list = jdbcTemplate.queryForList(querySql.toString(), params.toArray());
return Map.of(
"total", total != null ? total : 0,
"pageNo", pageNo,
"pageSize", pageSize,
"list", list
);
}
public Map<String, Object> queryDeviceStats() {
String sql = "SELECT lampState, COUNT(*) as cnt FROM " + deviceTableName +
" WHERE corp_code = ? GROUP BY lampState";
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, deviceCorpCode);
long all = 0;
long red = 0, yellow = 0, green = 0, blue = 0, off = 0;
for (Map<String, Object> row : rows) {
String state = (String) row.get("lampState");
long cnt = ((Number) row.get("cnt")).longValue();
all += cnt;
switch (state) {
case "0" -> off = cnt;
case "1" -> red = cnt;
case "2" -> yellow = cnt;
case "3" -> green = cnt;
case "4" -> blue = cnt;
}
}
return Map.of(
"all", all,
"red", red,
"yellow", yellow,
"green", green,
"blue", blue,
"off", off
);
}
}