zxl
4 天以前 c83101eb62f5d4906b9c01ceea6b21a37f9e84d8
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
package com.ycl.platform.service.impl;
 
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycl.platform.domain.dto.ReportImportDTO;
import com.ycl.platform.domain.entity.*;
import com.ycl.platform.domain.form.ReportAuditingForm;
import com.ycl.platform.domain.form.ReportForm;
import com.ycl.platform.domain.query.ReportQuery;
import com.ycl.platform.domain.vo.ReportVO;
import com.ycl.platform.domain.vo.YwPointVO;
import com.ycl.platform.mapper.ReportMapper;
import com.ycl.platform.mapper.YwPeopleMapper;
import com.ycl.platform.mapper.YwPointMapper;
import com.ycl.platform.mapper.YwUnitMapper;
import com.ycl.platform.service.ReportAuditingRecordService;
import com.ycl.platform.service.ReportErrorTypeService;
import com.ycl.platform.service.ReportService;
import com.ycl.system.Result;
import com.ycl.system.entity.SysDictData;
import com.ycl.system.page.PageUtil;
import com.ycl.system.service.ISysDictTypeService;
import com.ycl.utils.DateUtils;
import com.ycl.utils.SecurityUtils;
import com.ycl.utils.StringUtils;
import com.ycl.utils.html.EscapeUtil;
import com.ycl.utils.poi.ExcelUtil;
import com.ycl.utils.uuid.IdUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
 
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 报备 服务实现类
 *
 * @author xp
 * @since 2024-03-19
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Report> implements ReportService {
 
    private final YwUnitMapper unitMapper;
    private final YwPointMapper ywpointMapper;
    private final YwPeopleMapper peopleMapper;
    private final ReportErrorTypeService reportErrorTypeService;
    private final ISysDictTypeService dictTypeService;
    private final ReportAuditingRecordService reportAuditingRecordService;
 
    /**
     * 添加
     * @param form
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(ReportForm form) {
        if (Objects.isNull(form.getPointId())) {
            throw new RuntimeException("点位不能为空");
        }
        Integer unitId = SecurityUtils.getUnitId();
        if (Objects.isNull(unitId)) {
            throw new RuntimeException("非运维单位暂时无法报备");
        }
        form.setUnitId(unitId);
        Long userId = SecurityUtils.getLoginUser().getUserId();
        form.setPeopleId(Integer.parseInt(userId+""));
        if ("事前报备".equals(form.getReportType())) {
            // 如果是事前报备需要检验是否已经生成下发工单
            YwPointVO point = ywpointMapper.countNotFinishedWorkOrderByGb(form.getPointId());
            if (Objects.nonNull(point)) {
                throw new RuntimeException(String.format("点位【%s】已经存在下发工单,无法事前报备", point.getPointName()));
            }
        }
        YwPoint point = new LambdaQueryChainWrapper<>(ywpointMapper)
                .eq(YwPoint::getSerialNumber, form.getPointId())
                .one();
        if (Objects.isNull(point)) {
            throw new RuntimeException("点位不存在");
        }
        Report entity = ReportForm.getEntityByForm(form, null);
        entity.setSerialNumber(point.getSerialNumber());
        entity.setStatus(0);
        Date now = new Date();
        entity.setCreateTime(now);
        entity.setUpdateTime(now);
        entity.setIdentify(IdUtils.randomNO(now));
        baseMapper.insert(entity);
        List<ReportErrorType> errorTypeList = form.getErrorTypeList().stream().map(item -> {
            ReportErrorType reportErrorType = new ReportErrorType();
            reportErrorType.setErrorType(item);
            reportErrorType.setDeleted(0);
            reportErrorType.setCreateTime(now);
            reportErrorType.setReportId(entity.getId());
            return reportErrorType;
        }).collect(Collectors.toList());
        reportErrorTypeService.saveBatch(errorTypeList);
        return Result.ok("报备成功");
    }
 
    @Override
    @SneakyThrows
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<ReportImportDTO> excelUtil = new ExcelUtil<>(ReportImportDTO.class);
        excelUtil.exportExcel(response, null, "报备导入模板");
    }
 
    @Override
    @SneakyThrows
    @Transactional
    public Result importData(ReportForm form) {
        Integer unitId = SecurityUtils.getUnitId();
        if (Objects.isNull(unitId)) {
            throw new RuntimeException("非运维单位暂时无法报备");
        }
        form.setUnitId(unitId);
        form.setBeginCreateTime(DateUtils.parseDate(form.getBeginCreateTimeStr()));
        form.setEndCreateTime(DateUtils.parseDate(form.getEndCreateTimeStr()));
        // 读取excel数据
        ExcelUtil<ReportImportDTO> excelUtil = new ExcelUtil<>(ReportImportDTO.class);
        List<ReportImportDTO> list = excelUtil.importExcel(form.getImportPointId().getInputStream());
        Date now = DateUtils.getNowDate();
        // 批量插入
        String pid = IdUtils.randomNO(now);
        Integer success = 0;
        for (ReportImportDTO item : list) {
            if ("事前报备".equals(form.getReportType())) {
                // 如果是事前报备需要检验是否已经生成下发工单
                YwPointVO point = ywpointMapper.countNotFinishedWorkOrderByGb(item.getSerialNumber());
                if (Objects.nonNull(point)) {
                    throw new RuntimeException(String.format("点位【%s】已经存在下发工单,无法事前报备", point.getPointName()));
                }
            }
            YwPoint point = new LambdaQueryChainWrapper<>(ywpointMapper)
                    .eq(YwPoint::getSerialNumber, item.getSerialNumber())
                    .one();
            if (Objects.isNull(point)) {
                continue;
            }
            Report entity = ReportForm.getEntityByForm(form, null);
            entity.setImportBatchNumber(pid);
            entity.setSerialNumber(item.getSerialNumber());
            entity.setStatus(0);
            entity.setIdentify(IdUtils.randomNO(now));
            entity.setCreateTime(now);
            entity.setUpdateTime(now);
            baseMapper.insert(entity);
            List<ReportErrorType> errorTypeList = form.getErrorTypeList().stream().map(err -> {
                ReportErrorType reportErrorType = new ReportErrorType();
                reportErrorType.setErrorType(err);
                reportErrorType.setDeleted(0);
                reportErrorType.setCreateTime(now);
                reportErrorType.setReportId(entity.getId());
                return reportErrorType;
            }).collect(Collectors.toList());
            reportErrorTypeService.saveBatch(errorTypeList);
            success++;
        }
        return Result.ok("报备点位数:" + list.size() + ",导入成功数:" + success);
    }
 
    @Override
    public Result getTogether(String pid) {
        List<Report> list = baseMapper.getTogether(pid);
        return Result.ok().data(list);
    }
 
    /**
     * 修改
     * @param form
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result update(ReportForm form) {
 
        Report entity = baseMapper.selectById(form.getId());
        // 为空抛IllegalArgumentException,做全局异常处理
        Assert.notNull(entity, "记录不存在");
        Date now = new Date();
        entity.setUpdateTime(now);
        if ("事前报备".equals(form.getReportType())) {
            // 如果是事前报备需要检验是否已经生成下发工单
            YwPointVO point = ywpointMapper.countNotFinishedWorkOrderByGb(form.getPointId());
            if (Objects.nonNull(point)) {
                throw new RuntimeException(String.format("点位【%s】已经存在下发工单,无法事前报备", point.getPointName()));
            }
        }
        YwPoint point = new LambdaQueryChainWrapper<>(ywpointMapper)
                .eq(YwPoint::getSerialNumber, form.getPointId())
                .one();
        if (Objects.isNull(point)) {
            throw new RuntimeException("点位不存在");
        }
        BeanUtils.copyProperties(form, entity);
        entity.setSerialNumber(form.getPointId());
        // 重置为待审核
        entity.setStatus(0);
        baseMapper.updateById(entity);
        new LambdaUpdateChainWrapper<>(reportErrorTypeService.getBaseMapper())
                .eq(ReportErrorType::getReportId, form.getId())
                .remove();
        List<ReportErrorType> errorTypeList = form.getErrorTypeList().stream().map(err -> {
            ReportErrorType reportErrorType = new ReportErrorType();
            reportErrorType.setErrorType(err);
            reportErrorType.setDeleted(0);
            reportErrorType.setCreateTime(now);
            reportErrorType.setReportId(entity.getId());
            return reportErrorType;
        }).collect(Collectors.toList());
        reportErrorTypeService.saveBatch(errorTypeList);
        return Result.ok("修改成功");
    }
 
    /**
     * 批量删除
     * @param ids
     * @return
     */
    @Override
    public Result remove(List<String> ids) {
        if(baseMapper.deleteBatchIds(ids) > 0) {
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }
 
    /**
     * id删除
     * @param id
     * @return
     */
    @Override
    public Result removeById(String id) {
        if(baseMapper.deleteById(id) > 0) {
            return Result.ok("删除成功");
        }
        return Result.error("删除失败");
    }
 
    /**
     * 分页查询
     * @param query
     * @return
     */
    @Override
    public Result page(ReportQuery query) {
        IPage<ReportVO> page = PageUtil.getPage(query, ReportVO.class);
        query.setUnitId(SecurityUtils.getUnitId());
        if (query.getReportTimeEnd() != null) {
            query.setReportTimeEnd(DateUtils.getDayEnd(query.getReportTimeEnd()));
        }
 
        if (query.getEffectTimeEnd() != null) {
            query.setEffectTimeEnd(DateUtils.getDayEnd(query.getEffectTimeEnd()));
        }
        long dbStartTime = System.currentTimeMillis();
        baseMapper.page(page, query);
        long dbCostTime = System.currentTimeMillis() - dbStartTime;
        // 5. 打印耗时日志(含请求参数,方便后续排查慢查询)
        log.info("报表数据库查询耗时:{}ms,查询参数:{}", dbCostTime, JSON.toJSONString(query));
 
        long dictStartTime = System.currentTimeMillis();
        List<SysDictData> errorTypeList = dictTypeService.selectDictDataByType("report_error_type");
        long dictEndTime = System.currentTimeMillis() - dictStartTime;
        Map<String, String> dictMap = errorTypeList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        page.getRecords().stream().forEach(item -> {
            if (StringUtils.hasText(item.getErrorType())) {
                item.setErrorTypeList(List.of(item.getErrorType().split(",")));
                StringBuilder sb = new StringBuilder();
                item.getErrorTypeList().stream().forEach(err -> {
                    String s = dictMap.get(err);
                    if (org.springframework.util.StringUtils.hasText(s)) {
                        sb.append(s).append("、");
                    }
                });
                if (sb.length() > 0) {
                    item.setErrorType(sb.substring(0, sb.length() - 1));
                } else {
                    // 无匹配标签时,可设为空字符串或保留原始 errorType
                    item.setErrorType("");
                    // 或 item.setErrorType(item.getErrorType()); // 保留原始编码
                }
            }
        });
        log.info("组装信息耗时:{}ms", dictEndTime);
        return Result.ok().data(page).total(page.getTotal());
    }
 
    /**
     * 根据id查找
     * @param id
     * @return
     */
    @Override
    public Result detail(String id) {
        Report entity = baseMapper.selectById(id);
        Assert.notNull(entity, "记录不存在");
        ReportVO vo = ReportVO.getVoByEntity(entity, null);
        vo.setPointId(vo.getSerialNumber());
        List<ReportErrorType> errList = new LambdaQueryChainWrapper<>(reportErrorTypeService.getBaseMapper())
                .select(ReportErrorType::getErrorType)
                .eq(ReportErrorType::getReportId, id)
                .list();
        List<String> list = errList.stream().map(ReportErrorType::getErrorType).collect(Collectors.toList());
        vo.setErrorTypeList(list);
        return Result.ok().data(vo);
    }
 
    /**
     * 列表
     * @return
     */
    @Override
    public Result all() {
        List<Report> entities = baseMapper.selectList(null);
        List<ReportVO> vos = entities.stream()
                .map(
                        entity -> ReportVO.getVoByEntity(entity, null)
                )
                .collect(Collectors.toList());
        return Result.ok().data(vos);
    }
 
    @Override
    public List<ReportVO> export(ReportQuery query) {
        // 1. 分页查询主数据(不变)
        IPage<ReportVO> page = PageUtil.getPage(query, ReportVO.class);
        page.setSize(-1);
        query.setUnitId(SecurityUtils.getUnitId());
        baseMapper.page(page, query);
        List<ReportVO> records = page.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return Collections.emptyList();
        }
 
        // 2. 批量查询字典数据(不变,建议加缓存)
        List<SysDictData> errorTypeList = dictTypeService.selectDictDataByType("report_error_type");
        Map<String, String> errorDictMap = errorTypeList.stream()
                .collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel, (k1, k2) -> k2));
 
        // 3. 批量查询审核记录(核心修改:用子查询替代窗口函数,兼容低版本MySQL)
        List<Integer> reportIds = records.stream().map(ReportVO::getId).collect(Collectors.toList());
        // 子查询:获取每个reportId的最新创建时间
        LambdaQueryWrapper<ReportAuditingRecord> maxTimeQuery = new LambdaQueryWrapper<ReportAuditingRecord>()
                .in(ReportAuditingRecord::getReportId, reportIds)
                .groupBy(ReportAuditingRecord::getReportId)
                .select(ReportAuditingRecord::getReportId, ReportAuditingRecord::getCreateTime); // 分组查reportId和最大时间
 
        // 主查询:关联子查询,拿到每个reportId最新的审核记录
        List<ReportAuditingRecord> allAuditRecords = reportAuditingRecordService.getBaseMapper().selectList(
                new LambdaQueryWrapper<ReportAuditingRecord>()
                        .in(ReportAuditingRecord::getReportId, reportIds)
                        // 关联子查询,匹配reportId和最新创建时间
                        .inSql(ReportAuditingRecord::getCreateTime,
                                "SELECT MAX(create_time) FROM t_report_auditing_record WHERE report_id IN (" +
                                        reportIds.stream().map(String::valueOf).collect(Collectors.joining(",")) +
                                        ") GROUP BY report_id")
        );
 
        // 构建reportId -> 最新审核记录的Map(不变)
        Map<Integer, ReportAuditingRecord> auditRecordMap = allAuditRecords.stream()
                .collect(Collectors.toMap(ReportAuditingRecord::getReportId, record -> record, (k1, k2) -> {
                    // 极端情况:同一reportId有相同创建时间的记录,取任意一个(按创建时间倒序取第一个)
                    return k1.getCreateTime().after(k2.getCreateTime()) ? k1 : k2;
                }));
 
        // 4. 循环处理数据(不变,保留之前的字符串优化和空值处理)
        records.forEach(item -> {
            // 处理故障类型(不变)
            String errorType = item.getErrorType();
            if (StringUtils.hasText(errorType)) {
                String[] errorTypeArr = StringUtils.split(errorType, ",");
                StringJoiner sj = new StringJoiner("、");
                for (String err : errorTypeArr) {
                    String dictLabel = errorDictMap.get(err);
                    if (StringUtils.hasText(dictLabel)) {
                        sj.add(dictLabel);
                    }
                }
                item.setErrorTypeList(Arrays.asList(errorTypeArr));
                item.setErrorType(sj.toString());
            }
 
            // 处理审核结果(不变,从Map获取)
            ReportAuditingRecord auditRecord = auditRecordMap.get(item.getId());
            if (auditRecord != null) {
                item.setResultStr(auditRecord.getResult() ? "通过" : "未通过");
                item.setResultRemark(auditRecord.getResultRemark());
                item.setAuditingTime(auditRecord.getCreateTime());
            } else {
                item.setResultStr("审核中");
            }
 
            item.setReportContent(EscapeUtil.clean(StringUtils.defaultString(item.getReportContent())));
        });
 
        return records;
    }
 
    @Override
    public Result auditingRecord(Integer id) {
        List<ReportVO> reportList = baseMapper.examineRecord(id);
        return Result.ok().data(reportList);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result auditing(ReportAuditingForm form) {
        if (CollectionUtils.isEmpty(form.getTogetherList())) {
            form.setTogetherList(new ArrayList<>(2));
        }
        form.getTogetherList().add(form.getId());
        for (Integer id : form.getTogetherList()) {
            Report report = baseMapper.selectById(id);
            if (Objects.isNull(report)) {
                continue;
            }
            if (form.getAuditingResult()) {
                report.setStatus(1);
            } else {
                report.setStatus(2);
            }
            Date now = new Date();
            report.setUpdateTime(now);
            baseMapper.updateById(report);
 
            // 添加一条审核记录
            ReportAuditingRecord reportAuditingRecord = new ReportAuditingRecord();
            reportAuditingRecord.setReportId(id);
            reportAuditingRecord.setDeleted(0);
            reportAuditingRecord.setCreateTime(now);
            reportAuditingRecord.setResultRemark(form.getAuditOpinion());
            reportAuditingRecord.setResult(form.getAuditingResult());
            reportAuditingRecordService.save(reportAuditingRecord);
        }
        return Result.ok("操作成功");
    }
 
    @Override
    public Result getListByGb(String gb) {
        List<ReportVO> list = baseMapper.getListByGb(gb);
        for (ReportVO report : list) {
            List<ReportErrorType> errors = new LambdaQueryChainWrapper<>(reportErrorTypeService.getBaseMapper())
                    .eq(ReportErrorType::getReportId, report.getId())
                    .orderByDesc(ReportErrorType::getCreateTime)
                    .list();
            String err = errors.stream().map(ReportErrorType::getErrorType).collect(Collectors.joining(","));
            report.setErrorType(err);
        }
        return Result.ok().data(list);
    }
}