“djh”
2024-12-04 d1549b8445c65a6775cf1ba093f5040ace0f87e7
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
package com.gkhy.huataiFourierSpecialGasMonitor.service.impl;
 
import com.gkhy.huataiFourierSpecialGasMonitor.commons.domain.Result;
import com.gkhy.huataiFourierSpecialGasMonitor.commons.domain.SearchResult;
import com.gkhy.huataiFourierSpecialGasMonitor.commons.enums.ResultCode;
import com.gkhy.huataiFourierSpecialGasMonitor.commons.exception.BusinessException;
import com.gkhy.huataiFourierSpecialGasMonitor.commons.model.PageQuery;
import com.gkhy.huataiFourierSpecialGasMonitor.domain.account.entity.User;
import com.gkhy.huataiFourierSpecialGasMonitor.domain.account.enums.UserStatusEnum;
import com.gkhy.huataiFourierSpecialGasMonitor.domain.account.repository.jpa.UserRepository;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.GasConcentration;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.GasWarnLog;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.query.FindGasWarnLogPageQuery;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.query.GasWarnTimesCountTimeSlotQuery;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.query.WindRoseTimeSlotQuery;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.req.GasWarnLogCountByTimeReqDTO;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.req.GasWarnLogInfoReqDTO;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.req.HandleGasWarnLogReqDTO;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.req.WindRoseByTimeReqDTO;
import com.gkhy.huataiFourierSpecialGasMonitor.entity.resp.*;
import com.gkhy.huataiFourierSpecialGasMonitor.enums.GasWarnTimesCountEnum;
import com.gkhy.huataiFourierSpecialGasMonitor.enums.WarnHandleStatusEnum;
import com.gkhy.huataiFourierSpecialGasMonitor.enums.WindRoseEnum;
import com.gkhy.huataiFourierSpecialGasMonitor.repository.GasConcentrationRepository;
import com.gkhy.huataiFourierSpecialGasMonitor.repository.GasWarnLogRepository;
import com.gkhy.huataiFourierSpecialGasMonitor.service.GasWarnLogService;
import com.gkhy.huataiFourierSpecialGasMonitor.utils.ThreadLocalUtil;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
 
import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author Mr.huang
 * @decription
 * @date 2023/8/9 16:47
 */
@Service
public class GasWarnLogServiceImpl implements GasWarnLogService {
 
    @Autowired
    private GasWarnLogRepository gasWarnLogRepository;
 
    @Resource
    private GasConcentrationRepository gasConcentrationRepository;
 
    @Autowired
    private UserRepository userRepository;
 
    private User getCurrentUser(){
        Long userId = ThreadLocalUtil.get().getId();
        User user = userRepository.findUserByIdAndStatus(userId, UserStatusEnum.STATUS_ACTIVE.getStatus());
        if (user == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL.getCode(),"未成功获取用户信息");
        return user;
    }
 
    @Override
    public Result findGasWarnLogPage(PageQuery<FindGasWarnLogPageQuery> pageQuery) {
        if (pageQuery == null || pageQuery.getPageIndex() == null || pageQuery.getPageSize() == null){
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL,"分页参数不能为空");
        }
        Pageable pageable = PageRequest.of(pageQuery.getPageIndex()-1, pageQuery.getPageSize(), Sort.Direction.DESC, "warnTime");
        Specification<GasWarnLog> specification = new Specification<GasWarnLog>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                Set<Predicate> predicateList = new HashSet<>();
                FindGasWarnLogPageQuery searchParams = pageQuery.getSearchParams();
                if (searchParams != null && searchParams.getStartTime() != null && searchParams.getEndTime() != null){
                    predicateList.add(criteriaBuilder.between(root.get("warnTime").as(LocalDateTime.class),searchParams.getStartTime(),searchParams.getEndTime()));
                }
                if (searchParams != null && searchParams.getStatus() != null){
                    predicateList.add(criteriaBuilder.equal(root.get("status").as(Byte.class), searchParams.getStatus()));
                }
                if (searchParams != null && searchParams.getGasCategoryId() != null){
                    predicateList.add(criteriaBuilder.equal(root.get("gasCategoryId").as(Integer.class), searchParams.getGasCategoryId()));
                }
                if (searchParams != null && searchParams.getGasThresholdId() != null){
                    predicateList.add(criteriaBuilder.equal(root.get("gasThresholdId").as(Long.class), searchParams.getGasThresholdId()));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        SearchResult<List<FindGasWarnLogPageRespDTO>> searchResult = new SearchResult<>();
        searchResult.setPageIndex(pageQuery.getPageIndex());
        searchResult.setPageSize(pageQuery.getPageSize());
        searchResult.setSuccess();
        Page<GasWarnLog> pageResult = gasWarnLogRepository.findAll(specification,pageable);
        searchResult.setTotal(pageResult.getTotalElements());
        searchResult.setPages(pageResult.getTotalPages());
        if (!CollectionUtils.isEmpty(pageResult.getContent())){
            List<FindGasWarnLogPageRespDTO> respDTOS = pageResult.getContent().stream().map(gasWarnLog -> {
                FindGasWarnLogPageRespDTO dto = new FindGasWarnLogPageRespDTO();
                BeanUtils.copyProperties(gasWarnLog, dto);
                if (!CollectionUtils.isEmpty(gasWarnLog.getGasWarnLogSmsUsers())) {
                    List<FindGasWarnLogSmsUserPageRespDTO> gasWarnLogSmsUsers = new ArrayList<>();
                    BeanUtils.copyProperties(gasWarnLog.getGasWarnLogSmsUsers(), gasWarnLogSmsUsers);
                    dto.setGasWarnLogSmsUsers(gasWarnLogSmsUsers);
                }
                return dto;
            }).collect(Collectors.toList());
            searchResult.setData(respDTOS);
        }
        return searchResult;
    }
 
    @Override
    public Result handleGasWarnLog(HandleGasWarnLogReqDTO reqDto) {
        User currentUser = getCurrentUser();
        if (reqDto == null){
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL,"参数不能为空");
        }
        if (reqDto.getId() == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL,"参数不能为空");
        if (reqDto.getUserId() == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL,"参数不能为空");
        if (StringUtils.isBlank(reqDto.getHandlerDesc()))
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL,"参数不能为空");
        GasWarnLog gasWarnLog = gasWarnLogRepository.findByIdAndStatus(reqDto.getId(), WarnHandleStatusEnum.HANDLE_NO.getStatus());
        if (gasWarnLog == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL,"预警信息不存在");
        User user = userRepository.findUserByIdAndStatus(reqDto.getUserId(), UserStatusEnum.STATUS_ACTIVE.getStatus());
        if (user == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL,"处理人不存在");
        gasWarnLog.setHandlerId(user.getId());
        gasWarnLog.setHandlerName(user.getName());
        gasWarnLog.setHandlerRealName(user.getRealName());
        gasWarnLog.setHandlerTime(LocalDateTime.now());
        gasWarnLog.setHandlerDesc(reqDto.getHandlerDesc());
        gasWarnLog.setStatus(WarnHandleStatusEnum.HANDLE_YES.getStatus());
        GasWarnLog save = gasWarnLogRepository.save(gasWarnLog);
        if (save == null)
            throw new BusinessException(this.getClass(), ResultCode.SYSTEM_ERROR_DATABASE_FAIL,"预警信息处理失败");
        return Result.success();
    }
 
    @Override
    public GasWarnLog save(GasWarnLog gasWarnLog) {
        return gasWarnLogRepository.save(gasWarnLog);
    }
 
    @Override
    public List<GasWarnLog> listYesterday() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 获取昨天的日期
        LocalDateTime yesterday = now.minusDays(1);
        // 获取昨天的9点时间
        LocalDateTime yesterdayStart = LocalDateTime.of(yesterday.toLocalDate(), LocalTime.of(9,0,0));
        // 获取今天的9点时间
        LocalDateTime yesterdayEnd = LocalDateTime.of(yesterday.toLocalDate(), LocalTime.of(9,0,0));
        Specification<GasWarnLog> specification = new Specification<GasWarnLog>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                Set<Predicate> predicateList = new HashSet<>();
                predicateList.add(criteriaBuilder.between(root.get("warnTime").as(LocalDateTime.class),yesterdayStart,yesterdayEnd));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        List<GasWarnLog> warnLogs = gasWarnLogRepository.findAll(specification);
        return warnLogs;
    }
 
    @Override
    public Result gasWarnLogCountByTime(GasWarnLogCountByTimeReqDTO gasWarnLogCountByTimeReqDTO) {
        if (gasWarnLogCountByTimeReqDTO == null && gasWarnLogCountByTimeReqDTO .getCountTime() == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL,"参数不能为空");
        Integer countTime = gasWarnLogCountByTimeReqDTO.getCountTime();
        GasWarnTimesCountTimeSlotQuery query = GasWarnTimesCountEnum.getQueryObject(countTime).getTimeSlotByStrategy();
        Result result = Result.success();
        List<GasWarnLog> gasWarnLog = gasWarnLogRepository.findAllByWarnTimeBetweenOrderByWarnTimeDesc(query.getStartTime(), query.getEndTime());
        if (CollectionUtils.isEmpty(gasWarnLog))
            return result;
        GasWarnLogCountByTimeRespDTO gasWarnLogCountByTimeRespDTO = new GasWarnLogCountByTimeRespDTO();
        Map<Integer, Long> nameCountMap = gasWarnLog.stream()
                .collect(Collectors.groupingBy(GasWarnLog::getGasThresholdId, Collectors.counting()));
        gasWarnLogCountByTimeRespDTO.setYellowWarnNum(nameCountMap.get(1));
        gasWarnLogCountByTimeRespDTO.setRedWarnNum(nameCountMap.get(2));
        result.setData(gasWarnLogCountByTimeRespDTO);
        return result;
    }
 
    @Override
    public Result gasWindRoseByTime(WindRoseByTimeReqDTO reqDTO) {
        if (reqDTO == null && reqDTO .getCountTime() == null)
            throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL,"参数不能为空");
        Integer countTime = reqDTO.getCountTime();
        List<GasConcentration> gasConcentrations;
        if (reqDTO.getCountTime().equals(WindRoseEnum.CUSTOM_TIME.getState())){
            if (reqDTO.getStartTime() == null && reqDTO.getEndTime() == null)
                throw new BusinessException(this.getClass(), ResultCode.PARAM_ERROR_NULL,"参数不能为空");
            gasConcentrations = gasConcentrationRepository.findAllByDataReceivingTimeBetweenOrderByDataReceivingTimeDesc(reqDTO.getStartTime(), reqDTO.getEndTime());
        }else {
            WindRoseTimeSlotQuery query = WindRoseEnum.getQueryObject(countTime).getTimeSlotByStrategy();
             gasConcentrations = gasConcentrationRepository.findAllByDataReceivingTimeBetweenOrderByDataReceivingTimeDesc(query.getStartTime(), query.getEndTime());
        }
        Result result = Result.success();
        if (CollectionUtils.isEmpty(gasConcentrations))
            return result;
        List<WindRoseByTimeRespDTO> collect = gasConcentrations.stream().map(gasConcentration -> {
            WindRoseByTimeRespDTO dto = new WindRoseByTimeRespDTO();
            BeanUtils.copyProperties(gasConcentration, dto);
            return dto;
        }).collect(Collectors.toList());
        result.setData(collect);
        return result;
    }
 
    @Override
    public Result gasWarnLogInfoByTime(GasWarnLogInfoReqDTO gasWarnLogInfoReqDTO) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = now.with(LocalTime.MIN);
        if (gasWarnLogInfoReqDTO != null && gasWarnLogInfoReqDTO.getStartTime() != null) {
            startTime = gasWarnLogInfoReqDTO.getStartTime();
        }
        if (gasWarnLogInfoReqDTO != null && gasWarnLogInfoReqDTO.getEndTime() != null) {
            now = gasWarnLogInfoReqDTO.getEndTime();
        }
        Result result = Result.success();
        List<GasWarnLog> gasWarnLogs = gasWarnLogRepository.findAllByWarnTimeBetweenOrderByWarnTimeDesc(startTime, now);
        if (CollectionUtils.isEmpty(gasWarnLogs))
            return result;
        List<GasWarnLogInfoByTimeRespDTO> dtos = gasWarnLogs.stream().map(gasWarnLog -> {
            GasWarnLogInfoByTimeRespDTO dto = new GasWarnLogInfoByTimeRespDTO();
            BeanUtils.copyProperties(gasWarnLog, dto);
            return dto;
        }).collect(Collectors.toList());
        result.setData(dtos);
        return result;
    }
}