doum
2026-05-26 f4d592f3626f94117d8a4eb22176a28290931980
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
package com.doumee.service.business.impl;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.device.ElectronicToolUtil;
import com.doumee.core.device.model.ElectronicConstant;
import com.doumee.core.device.model.request.WarningListRequest;
import com.doumee.core.device.model.response.ElectronicDataResponse;
import com.doumee.core.device.model.response.WarningInfoResponse;
import com.doumee.core.exception.BusinessException;
import com.doumee.core.model.PageData;
import com.doumee.core.model.PageWrap;
import com.doumee.core.utils.Constants;
import com.doumee.core.utils.Utils;
import com.doumee.dao.business.YwElectricalMapper;
import com.doumee.dao.business.YwElectricalRoomMapper;
import com.doumee.dao.business.YwElectricalWarningMapper;
import com.doumee.dao.business.dto.WarningDefOptionDTO;
import com.doumee.dao.business.model.YwElectrical;
import com.doumee.dao.business.model.YwElectricalRoom;
import com.doumee.dao.business.model.YwElectricalWarning;
import com.doumee.dao.business.model.YwRoom;
import com.doumee.service.business.YwElectricalWarningService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
 
/**
 * 智能电表报警记录Service实现
 */
@Service
public class YwElectricalWarningServiceImpl implements YwElectricalWarningService {
 
    private static final int ELECTRICAL_DEVICE_TYPE = 0;
    private static final int ELECTRICAL_ROOM_TYPE = 0;
    private static final String START_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
 
    @Autowired
    private YwElectricalWarningMapper ywElectricalWarningMapper;
 
    @Autowired
    private YwElectricalMapper ywElectricalMapper;
 
    @Autowired
    private YwElectricalRoomMapper ywElectricalRoomMapper;
 
    @Override
    public PageData<YwElectricalWarning> findPage(PageWrap<YwElectricalWarning> pageWrap) {
        IPage<YwElectricalWarning> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        MPJLambdaWrapper<YwElectricalWarning> queryWrapper = buildPageQuery(pageWrap);
        queryWrapper.orderByDesc(YwElectricalWarning::getStartTime);
        IPage<YwElectricalWarning> result = ywElectricalWarningMapper.selectJoinPage(page, YwElectricalWarning.class, queryWrapper);
        PageData<YwElectricalWarning> pageData = PageData.from(result);
        enrichDisplayFields(pageData.getRecords());
        return pageData;
    }
 
    @Override
    public long count(YwElectricalWarning model) {
        MPJLambdaWrapper<YwElectricalWarning> queryWrapper = new MPJLambdaWrapper<>();
        YwElectricalWarning query = model == null ? new YwElectricalWarning() : model;
        applyBaseFilters(queryWrapper, query);
        return ywElectricalWarningMapper.selectJoinCount(queryWrapper);
    }
 
    @Override
    @Transactional
    public String syncFromPlatform() {
        if (Constants.DEALING_ELECTRICAL_WARNING_SYNC) {
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(), "报警同步任务正在执行,请稍后再试");
        }
        Constants.DEALING_ELECTRICAL_WARNING_SYNC = true;
        try {
            WarningListRequest request = new WarningListRequest();
            request.setDevice_type(String.valueOf(ELECTRICAL_DEVICE_TYPE));
            ElectronicDataResponse<List<WarningInfoResponse>> response = ElectronicToolUtil.warningList(request);
            if (response == null || !StringUtils.equals(response.getStatus(), "1")) {
                throw new BusinessException(ResponseStatus.SERVER_ERROR.getCode(), "同步报警数据异常");
            }
            List<WarningInfoResponse> dataList = response.getData();
            if (CollectionUtils.isEmpty(dataList)) {
                return "同步完成:第三方无报警数据";
            }
            Map<String, YwElectrical> addressMap = buildElectricalAddressMap();
            Map<String, YwElectrical> didMap = buildElectricalDidMap();
            Set<Integer> affectedElectricalIds = new LinkedHashSet<>();
            Date now = new Date();
            int addCount = 0;
            int updateCount = 0;
            for (WarningInfoResponse item : dataList) {
                if (item == null || StringUtils.isBlank(item.getDevice_address())) {
                    continue;
                }
                Integer deviceType = parseDeviceType(item.getDevice_type());
                if (deviceType != null && deviceType != ELECTRICAL_DEVICE_TYPE) {
                    continue;
                }
                Integer warningDefId = parseWarningDefId(item.getWarning_def_id());
                Date startTime = parseStartTime(item.getStart_time());
                if (warningDefId == null || startTime == null) {
                    continue;
                }
                YwElectricalWarning entity = findExisting(item.getDevice_address(), warningDefId, startTime);
                boolean isNew = entity == null;
                if (isNew) {
                    entity = new YwElectricalWarning();
                    entity.setCreateDate(now);
                    entity.setIsdeleted(Constants.ZERO);
                }
                entity.setDeviceType(deviceType == null ? ELECTRICAL_DEVICE_TYPE : deviceType);
                entity.setDeviceId(item.getDevice_id());
                entity.setDeviceAddress(item.getDevice_address());
                entity.setWarningDefId(warningDefId);
                entity.setStartTime(startTime);
                entity.setMsg(item.getMsg());
                entity.setEditDate(now);
                resolveElectricalId(entity, addressMap, didMap);
                if (entity.getElectricalId() != null) {
                    affectedElectricalIds.add(entity.getElectricalId());
                }
                if (isNew) {
                    ywElectricalWarningMapper.insert(entity);
                    addCount++;
                } else {
                    ywElectricalWarningMapper.updateById(entity);
                    updateCount++;
                }
            }
            int electricalUpdateCount = updateElectricalWarnTypes(affectedElectricalIds, now);
            return "同步完成:新增【" + addCount + "】条,更新【" + updateCount + "】条,回写电表预警【" + electricalUpdateCount + "】台";
        } finally {
            Constants.DEALING_ELECTRICAL_WARNING_SYNC = false;
        }
    }
 
    @Override
    public List<WarningDefOptionDTO> listWarningDefOptions() {
        List<WarningDefOptionDTO> list = new ArrayList<>();
        for (ElectronicConstant.warningDefId item : ElectronicConstant.warningDefId.listByDeviceType(ELECTRICAL_DEVICE_TYPE)) {
            list.add(new WarningDefOptionDTO(item.getKey(), item.getName()));
        }
        return list;
    }
 
    private MPJLambdaWrapper<YwElectricalWarning> buildPageQuery(PageWrap<YwElectricalWarning> pageWrap) {
        MPJLambdaWrapper<YwElectricalWarning> queryWrapper = new MPJLambdaWrapper<>();
        YwElectricalWarning model = pageWrap.getModel() == null ? new YwElectricalWarning() : pageWrap.getModel();
        Utils.MP.blankToNull(model);
        queryWrapper.selectAll(YwElectricalWarning.class)
                .selectAs(YwElectrical::getName, YwElectricalWarning::getElectricalName)
                .leftJoin(YwElectrical.class, YwElectrical::getId, YwElectricalWarning::getElectricalId);
        applyBaseFilters(queryWrapper, model);
        if (StringUtils.isNotBlank(model.getMeterKeyword())) {
            String keyword = model.getMeterKeyword();
            queryWrapper.and(w -> w.like(YwElectricalWarning::getDeviceAddress, keyword)
                    .or()
                    .like(YwElectrical::getName, keyword)
                    .or()
                    .like(YwElectrical::getAddress, keyword));
        }
        return queryWrapper;
    }
 
    private void applyBaseFilters(MPJLambdaWrapper<YwElectricalWarning> queryWrapper, YwElectricalWarning model) {
        queryWrapper.eq(YwElectricalWarning::getIsdeleted, Constants.ZERO);
        queryWrapper.eq(YwElectricalWarning::getDeviceType, ELECTRICAL_DEVICE_TYPE);
        queryWrapper.eq(model.getWarningDefId() != null, YwElectricalWarning::getWarningDefId, model.getWarningDefId());
        if (model.getStartTimeBegin() != null) {
            queryWrapper.ge(YwElectricalWarning::getStartTime, Utils.Date.getStart(model.getStartTimeBegin()));
        }
        if (model.getStartTimeEnd() != null) {
            queryWrapper.le(YwElectricalWarning::getStartTime, Utils.Date.getEnd(model.getStartTimeEnd()));
        }
    }
 
    private void enrichDisplayFields(List<YwElectricalWarning> list) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        fillRoomNames(list);
        for (YwElectricalWarning row : list) {
            ElectronicConstant.warningDefId def = ElectronicConstant.warningDefId.getByKey(row.getWarningDefId());
            if (def != null) {
                row.setWarningName(def.getName());
                row.setWarningInfo(def.getInfo());
            }
        }
    }
 
    private void fillRoomNames(List<YwElectricalWarning> list) {
        List<Integer> electricalIds = list.stream()
                .map(YwElectricalWarning::getElectricalId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        if (electricalIds.isEmpty()) {
            return;
        }
        MPJLambdaWrapper<YwElectricalRoom> roomWrapper = new MPJLambdaWrapper<>();
        roomWrapper.select(YwElectricalRoom::getObjId, YwElectricalRoom::getSortnum)
                .selectAs(YwRoom::getName, YwElectricalRoom::getRoomName)
                .selectAs(YwRoom::getRoomNum, YwElectricalRoom::getRoomNum)
                .leftJoin(YwRoom.class, YwRoom::getId, YwElectricalRoom::getRoomId)
                .in(YwElectricalRoom::getObjId, electricalIds)
                .eq(YwElectricalRoom::getType, ELECTRICAL_ROOM_TYPE)
                .eq(YwElectricalRoom::getIsdeleted, Constants.ZERO)
                .orderByAsc(YwElectricalRoom::getSortnum)
                .orderByAsc(YwElectricalRoom::getId);
        List<YwElectricalRoom> roomList = ywElectricalRoomMapper.selectJoinList(YwElectricalRoom.class, roomWrapper);
        if (CollectionUtils.isEmpty(roomList)) {
            return;
        }
        Map<Integer, List<String>> roomNameMap = new HashMap<>();
        for (YwElectricalRoom room : roomList) {
            if (room.getObjId() == null) {
                continue;
            }
            String display = StringUtils.isNotBlank(room.getRoomName()) ? room.getRoomName() : room.getRoomNum();
            if (StringUtils.isBlank(display)) {
                continue;
            }
            roomNameMap.computeIfAbsent(room.getObjId(), k -> new ArrayList<>()).add(display);
        }
        for (YwElectricalWarning warning : list) {
            List<String> names = roomNameMap.get(warning.getElectricalId());
            if (!CollectionUtils.isEmpty(names)) {
                warning.setRoomNames(String.join(",", names));
            }
        }
    }
 
    private Map<String, YwElectrical> buildElectricalAddressMap() {
        List<YwElectrical> list = ywElectricalMapper.selectList(new QueryWrapper<YwElectrical>().lambda()
                .eq(YwElectrical::getIsdeleted, Constants.ZERO));
        Map<String, YwElectrical> map = new HashMap<>();
        if (CollectionUtils.isEmpty(list)) {
            return map;
        }
        for (YwElectrical electrical : list) {
            if (StringUtils.isNotBlank(electrical.getAddress())) {
                map.put(electrical.getAddress(), electrical);
            }
            if (StringUtils.isNotBlank(electrical.getCode())) {
                map.putIfAbsent(electrical.getCode(), electrical);
            }
        }
        return map;
    }
 
    private Map<String, YwElectrical> buildElectricalDidMap() {
        List<YwElectrical> list = ywElectricalMapper.selectList(new QueryWrapper<YwElectrical>().lambda()
                .eq(YwElectrical::getIsdeleted, Constants.ZERO));
        Map<String, YwElectrical> map = new HashMap<>();
        if (CollectionUtils.isEmpty(list)) {
            return map;
        }
        for (YwElectrical electrical : list) {
            if (StringUtils.isNotBlank(electrical.getDId())) {
                map.put(electrical.getDId(), electrical);
            }
        }
        return map;
    }
 
    private void resolveElectricalId(YwElectricalWarning entity, Map<String, YwElectrical> addressMap, Map<String, YwElectrical> didMap) {
        YwElectrical electrical = null;
        if (StringUtils.isNotBlank(entity.getDeviceAddress())) {
            electrical = addressMap.get(entity.getDeviceAddress());
        }
        if (electrical == null && StringUtils.isNotBlank(entity.getDeviceId())) {
            electrical = didMap.get(entity.getDeviceId());
        }
        if (electrical != null) {
            entity.setElectricalId(electrical.getId());
        }
    }
 
    /** 按电表汇总全部报警类型,逗号分隔回写 warn_type */
    private int updateElectricalWarnTypes(Set<Integer> affectedElectricalIds, Date editDate) {
        if (CollectionUtils.isEmpty(affectedElectricalIds)) {
            return 0;
        }
        for (Integer electricalId : affectedElectricalIds) {
            refreshElectricalWarnType(electricalId, editDate);
        }
        return affectedElectricalIds.size();
    }
 
    private void refreshElectricalWarnType(Integer electricalId, Date editDate) {
        List<YwElectricalWarning> warnings = ywElectricalWarningMapper.selectList(new QueryWrapper<YwElectricalWarning>().lambda()
                .eq(YwElectricalWarning::getElectricalId, electricalId)
                .eq(YwElectricalWarning::getIsdeleted, Constants.ZERO));
        LinkedHashSet<Integer> defIds = new LinkedHashSet<>();
        if (!CollectionUtils.isEmpty(warnings)) {
            for (YwElectricalWarning warning : warnings) {
                if (warning.getWarningDefId() != null) {
                    defIds.add(warning.getWarningDefId());
                }
            }
        }
        String warnType = defIds.stream().map(String::valueOf).collect(Collectors.joining(","));
        YwElectrical upd = new YwElectrical();
        upd.setId(electricalId);
        upd.setWarnType(StringUtils.isBlank(warnType) ? null : warnType);
        upd.setEditDate(editDate);
        ywElectricalMapper.updateById(upd);
    }
 
    private YwElectricalWarning findExisting(String deviceAddress, Integer warningDefId, Date startTime) {
        return ywElectricalWarningMapper.selectOne(new QueryWrapper<YwElectricalWarning>().lambda()
                .eq(YwElectricalWarning::getDeviceAddress, deviceAddress)
                .eq(YwElectricalWarning::getWarningDefId, warningDefId)
                .eq(YwElectricalWarning::getStartTime, startTime)
                .eq(YwElectricalWarning::getIsdeleted, Constants.ZERO)
                .last("limit 1"));
    }
 
    private Integer parseDeviceType(String deviceType) {
        if (StringUtils.isBlank(deviceType)) {
            return ELECTRICAL_DEVICE_TYPE;
        }
        try {
            return Integer.parseInt(deviceType.trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }
 
    private Integer parseWarningDefId(String warningDefId) {
        if (StringUtils.isBlank(warningDefId)) {
            return null;
        }
        try {
            return Integer.parseInt(warningDefId.trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }
 
    private Date parseStartTime(String startTime) {
        if (StringUtils.isBlank(startTime)) {
            return null;
        }
        try {
            return new SimpleDateFormat(START_TIME_PATTERN).parse(startTime.trim());
        } catch (ParseException e) {
            return null;
        }
    }
}