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.dao.business.vo.WarningTypeStatVO; 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 findPage(PageWrap pageWrap) { IPage page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity()); MPJLambdaWrapper queryWrapper = buildPageQuery(pageWrap); queryWrapper.orderByDesc(YwElectricalWarning::getStartTime); IPage result = ywElectricalWarningMapper.selectJoinPage(page, YwElectricalWarning.class, queryWrapper); PageData pageData = PageData.from(result); enrichDisplayFields(pageData.getRecords()); return pageData; } @Override public long count(YwElectricalWarning model) { MPJLambdaWrapper 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> response = ElectronicToolUtil.warningList(request); if (response == null || !StringUtils.equals(response.getStatus(), "1")) { throw new BusinessException(ResponseStatus.SERVER_ERROR.getCode(), "同步报警数据异常"); } List dataList = response.getData(); if (CollectionUtils.isEmpty(dataList)) { return "同步完成:第三方无报警数据"; } Map addressMap = buildElectricalAddressMap(); Map didMap = buildElectricalDidMap(); Set 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 listWarningDefOptions() { List list = new ArrayList<>(); for (ElectronicConstant.warningDefId item : ElectronicConstant.warningDefId.listByDeviceType(ELECTRICAL_DEVICE_TYPE)) { list.add(new WarningDefOptionDTO(item.getKey(), item.getName())); } return list; } @Override public List warningTypeStats() { QueryWrapper wrapper = new QueryWrapper<>(); wrapper.select("warning_def_id", "count(1) as cnt") .eq("isdeleted", Constants.ZERO) .eq("device_type", ELECTRICAL_DEVICE_TYPE) .isNotNull("warning_def_id") .groupBy("warning_def_id") .orderByDesc("cnt"); List> rows = ywElectricalWarningMapper.selectMaps(wrapper); List list = new ArrayList<>(); if (CollectionUtils.isEmpty(rows)) { return list; } for (Map row : rows) { Object defIdObj = row.get("warning_def_id"); if (defIdObj == null) { continue; } Integer warningDefId = Integer.parseInt(String.valueOf(defIdObj)); Object cntObj = row.get("cnt"); long count = cntObj == null ? 0L : Long.parseLong(String.valueOf(cntObj)); WarningTypeStatVO stat = new WarningTypeStatVO(); stat.setWarningDefId(warningDefId); stat.setCount(count); ElectronicConstant.warningDefId def = ElectronicConstant.warningDefId.getByKey(warningDefId); stat.setWarningName(def != null ? def.getName() : "未知报警"); list.add(stat); } return list; } private MPJLambdaWrapper buildPageQuery(PageWrap pageWrap) { MPJLambdaWrapper 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 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 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 list) { List electricalIds = list.stream() .map(YwElectricalWarning::getElectricalId) .filter(Objects::nonNull) .distinct() .collect(Collectors.toList()); if (electricalIds.isEmpty()) { return; } MPJLambdaWrapper 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 roomList = ywElectricalRoomMapper.selectJoinList(YwElectricalRoom.class, roomWrapper); if (CollectionUtils.isEmpty(roomList)) { return; } Map> 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 names = roomNameMap.get(warning.getElectricalId()); if (!CollectionUtils.isEmpty(names)) { warning.setRoomNames(String.join(",", names)); } } } private Map buildElectricalAddressMap() { List list = ywElectricalMapper.selectList(new QueryWrapper().lambda() .eq(YwElectrical::getIsdeleted, Constants.ZERO)); Map 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 buildElectricalDidMap() { List list = ywElectricalMapper.selectList(new QueryWrapper().lambda() .eq(YwElectrical::getIsdeleted, Constants.ZERO)); Map 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 addressMap, Map 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 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 warnings = ywElectricalWarningMapper.selectList(new QueryWrapper().lambda() .eq(YwElectricalWarning::getElectricalId, electricalId) .eq(YwElectricalWarning::getIsdeleted, Constants.ZERO)); LinkedHashSet 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().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; } } }