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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
package com.ycl.platform.service.impl;
 
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycl.dataListener.CurrencyDataListener;
import com.ycl.platform.domain.entity.WorkOrder;
import com.ycl.platform.domain.entity.WorkOrderWhite;
import com.ycl.platform.domain.entity.YwPoint;
import com.ycl.platform.domain.entity.YwThreshold;
import com.ycl.platform.domain.excel.ErrorExport;
import com.ycl.platform.domain.excel.PointExport;
import com.ycl.platform.domain.excel.WorkOrderWhiteExport;
import com.ycl.platform.domain.query.WorkOrderWhiteQuery;
import com.ycl.platform.domain.result.HK.FaceDeviceInspectionResult;
import com.ycl.platform.domain.result.HK.VehicleDeviceInspectionResult;
import com.ycl.platform.domain.vo.DynamicColumnVO;
import com.ycl.platform.mapper.WorkOrderWhiteMapper;
import com.ycl.platform.mapper.YwThresholdMapper;
import com.ycl.platform.service.IYwThresholdService;
import com.ycl.platform.service.WorkOrderService;
import com.ycl.system.Result;
import com.ycl.system.page.PageUtil;
import com.ycl.utils.SecurityUtils;
import com.ycl.utils.StringUtils;
import com.ycl.utils.ip.PingUtil;
import com.ycl.utils.poi.EasyExcelImportUtils;
import com.ycl.utils.uuid.IdUtils;
import constant.PointHeaderConstant;
import constant.YwThreadConstants;
import enumeration.CompareType;
import enumeration.ErrorType;
import enumeration.general.BusinessTypeEnum;
import enumeration.general.WorkOrderStatusEnum;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import utils.DateUtils;
 
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
 
/**
 * 运维阈值Service业务层处理
 *
 * @author gonghl
 * @date 2024-07-19
 */
@Service
@Slf4j
public class YwThresholdServiceImpl extends ServiceImpl<YwThresholdMapper, YwThreshold> implements IYwThresholdService {
    @Autowired
    private YwThresholdMapper ywThresholdMapper;
 
    @Autowired
    private WorkOrderService workOrderService;
 
    @Autowired
    private WorkOrderWhiteMapper workOrderWhiteMapper;
 
    /**
     * 查询运维阈值
     *
     * @param id 运维阈值主键
     * @return 运维阈值
     */
    @Override
    public YwThreshold selectYwThresholdById(Long id) {
        return ywThresholdMapper.selectYwThresholdById(id);
    }
 
    /**
     * 查询运维阈值列表
     *
     * @param ywThreshold 运维阈值
     * @return 运维阈值
     */
    @Override
    public Map<String, List<YwThreshold>> selectYwThresholdList(YwThreshold ywThreshold) {
        List<YwThreshold> ywThresholds = ywThresholdMapper.selectYwThresholdList(ywThreshold);
        Map<String, List<YwThreshold>> map = ywThresholds.stream().collect(Collectors.groupingBy(YwThreshold::getMonitorType));
        return map;
    }
 
    /**
     * 新增运维阈值
     *
     * @param ywThreshold 运维阈值
     * @return 结果
     */
    @Override
    public int insertYwThreshold(YwThreshold ywThreshold) {
        ywThreshold.setCreateTime(DateUtils.getNowDate());
        return ywThresholdMapper.insertYwThreshold(ywThreshold);
    }
 
    /**
     * 修改运维阈值
     *
     * @param list 运维阈值
     * @return 结果
     */
    @Override
    public Boolean updateYwThreshold(List<YwThreshold> list) {
        list.forEach(item -> item.setCreateTime(new Date()));
        return updateBatchById(list);
    }
 
    /**
     * 批量删除运维阈值
     *
     * @param ids 需要删除的运维阈值主键
     * @return 结果
     */
    @Override
    public int deleteYwThresholdByIds(Long[] ids) {
        return ywThresholdMapper.deleteYwThresholdByIds(ids);
    }
 
    /**
     * 删除运维阈值信息
     *
     * @param id 运维阈值主键
     * @return 结果
     */
    @Override
    public int deleteYwThresholdById(Long id) {
        return ywThresholdMapper.deleteYwThresholdById(id);
    }
 
    /**
     * 判断视频阈值是否满足下发条件
     *
     * @param list
     */
    @Override
    public void videoCheck(List list) {
    }
 
    @Override
    public void errorTypeCheckUY(List list) {
        // 平台离线故障检测
        if (CollectionUtils.isEmpty(list)) {
            Boolean ping = PingUtil.ping("", 5);
            if (!ping) {
 
            }
        }
        // 设备离线故障检测
 
        // 信号缺失故障检测
 
        // 画面偏色故障检测
 
        // 雪花干扰故障检测
 
        // 条纹干扰故障检测
 
        // 画面遮挡故障检测
 
        // 清晰度异常检测
 
        // 亮度异常故障检测
    }
 
    /**
     * 判断人脸阈值是否满足下发条件
     *
     * @param list
     */
    @Override
    public void faceCheck(List<FaceDeviceInspectionResult> list) {
        Map<String, YwThreshold> thresholdMap = getYwThresholdMap(BusinessTypeEnum.FACE.name());
        //准备待下发工单集合
        List<WorkOrder> distributeList = new ArrayList<>();
        //准备直接下发工单集合
        List<WorkOrder> workOrderList = new ArrayList<>();
        //处理接口数据
        for (FaceDeviceInspectionResult result : list) {
            if (result == null) {
                log.error("人脸对象数据为空");
                continue;
            }
            WorkOrder workOrder = new WorkOrder();
            //检查时钟准确率
            if (result.getSnapClock() != null) {
                Float clockPercent = result.getSnapClock().getClockPercent();
                check(YwThreadConstants.Face_ClockPercent, clockPercent, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.LESS_THAN_EQ, ErrorType.CLOCK_RIGHT.getValue());
            }
            //检查数据及时率
            if (result.getSnapTimely() != null) {
                Float timelyPercent = result.getSnapTimely().getTimelyPercent();
                check(YwThreadConstants.Face_TimelyPercent, timelyPercent, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.LESS_THAN_EQ, ErrorType.DATA_TIMELY_ERROR.getValue());
            }
            //检查持续无数据天数
            if (result.getContinueNoDataCount() != null) {
                Integer continueNoDataCount = result.getContinueNoDataCount();
                check(YwThreadConstants.Face_ContinueNoDataCount, continueNoDataCount, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.MORE_THAN_EQ, ErrorType.LONG_DAY_NO_DATA.getValue());
            }
            //检查不唯一数据量
            if (result.getSnapUnique() != null) {
                Integer nouniqueCount = result.getSnapUnique().getNouniqueCount();
                check(YwThreadConstants.Face_NouniqueCount, nouniqueCount, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.MORE_THAN_EQ, ErrorType.NOT_UNIQUE_DATA_VOLUME.getValue());
            }
            //检查人脸低评分率
            if (result.getSnapValidity() != null) {
                Float lowScorePercent = result.getSnapValidity().getLowScorePercent();
                check(YwThreadConstants.Face_LowScorePercent, lowScorePercent, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.MORE_THAN_EQ, ErrorType.FACE_LOW.getValue());
            }
            //检查建模失败率
            if (result.getSnapValidity() != null) {
                Float failPercent = result.getSnapValidity().getFailPercent();
                check(YwThreadConstants.Face_FailPercent, failPercent, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.MORE_THAN_EQ, ErrorType.MODELING_FAIL.getValue());
            }
            // 点位在线率
//            if (2 == result.getSnapResult()) {
//                workOrder.setSerialNumber(result.getExternalIndexCode());
//                workOrder.setStatus(WorkOrderStatusEnum.DISTRIBUTED);
//                if (CollectionUtils.isEmpty(workOrder.getErrorTypeList())) {
//                    workOrder.setErrorTypeList(new ArrayList<>());
//                    workOrder.getErrorTypeList().add(ErrorType.DEVICE_OFFLINE.getValue());
//                } else {
//                    workOrder.getErrorTypeList().add(ErrorType.DEVICE_OFFLINE.getValue());
//                }
//            }
            if (WorkOrderStatusEnum.WAIT_DISTRIBUTE.equals(workOrder.getStatus())) {
                workOrderList.add(workOrder);
            } else if (WorkOrderStatusEnum.DISTRIBUTED.equals(workOrder.getStatus())) {
                distributeList.add(workOrder);
            }
        }
        /** 添加工单 */
        workOrderService.innerAddWorkOrder(workOrderList);
        workOrderService.innerAddWorkOrder(distributeList);
    }
 
    /**
     * 判断车辆阈值是否满足下发条件
     *
     * @param list
     */
    @Override
    public void carCheck(List<VehicleDeviceInspectionResult> list) {
        Map<String, YwThreshold> thresholdMap = getYwThresholdMap(BusinessTypeEnum.CAR.name());
        //准备下发工单集合
        List<WorkOrder> distributeList = new ArrayList<>();
        //准备自动生成工单集合
        List<WorkOrder> workOrderList = new ArrayList<>();
        //处理接口数据
        for (VehicleDeviceInspectionResult result : list) {
            if (result == null) {
                log.error("车辆对象数据为空");
                continue;
            }
            WorkOrder workOrder = new WorkOrder();
            //检查持续无数据天数
            Integer continueNoDataCount = result.getContinueNoDataCount();
            check(YwThreadConstants.Car_ContinueNoDataCount, continueNoDataCount, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.MORE_THAN_EQ, ErrorType.LONG_DAY_NO_DATA.getValue());
            //检查时钟准确率
            if (result.getSnapClock() != null) {
                Float clockPercent = result.getSnapClock().getClockPercent();
                check(YwThreadConstants.Car_ClockPercent, clockPercent, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.LESS_THAN_EQ, ErrorType.CLOCK_RIGHT.getValue());
            }
            //检查数据及时率
            if (result.getSnapTimely() != null) {
                Float timelyPercentResult = result.getSnapTimely().getTimelyPercent();
                check(YwThreadConstants.Car_TimelyPercent, timelyPercentResult, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.LESS_THAN_EQ, ErrorType.DATA_TIMELY_ERROR.getValue());
            }
            //检查不唯一数据量
            if (result.getSnapUnique() != null) {
                Integer nouniqueCountResult = result.getSnapUnique().getNouniqueCount();
                check(YwThreadConstants.Car_NouniqueCount, nouniqueCountResult, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.MORE_THAN_EQ, ErrorType.NOT_UNIQUE_DATA_VOLUME.getValue());
            }
            //检查白天未识别量
            if (result.getSnapPlate() != null) {
                Integer dayNoNumberCountResult = result.getSnapPlate().getDayNoNumberCount();
                check(YwThreadConstants.Car_DayNoNumberCount, dayNoNumberCountResult, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.MORE_THAN_EQ, ErrorType.UNRECOGNIZED_DAY_VOLUME.getValue());
            }
            //车辆主要属性一致率
            if (result.getIntegrity() != null) {
                Integer noIntegrityCountResult = result.getIntegrity().getMainNoIntegrityCount();
                Integer dataCount = result.getDataCount();
                Double integrityRate = ((double) dataCount - noIntegrityCountResult) / dataCount;
                check(YwThreadConstants.Car_NoIntegrityCount, integrityRate, result.getExternalIndexCode(), thresholdMap, workOrder, CompareType.LESS_THAN_EQ, ErrorType.CAR_SIX.getValue());
            }
            // 点位在线率
//            if (2 == result.getSnapResult()) {
//                workOrder.setSerialNumber(result.getExternalIndexCode());
//                workOrder.setStatus(WorkOrderStatusEnum.DISTRIBUTED);
//                if (CollectionUtils.isEmpty(workOrder.getErrorTypeList())) {
//                    workOrder.setErrorTypeList(new ArrayList<>());
//                    workOrder.getErrorTypeList().add(ErrorType.DEVICE_OFFLINE.getValue());
//                } else {
//                    workOrder.getErrorTypeList().add(ErrorType.DEVICE_OFFLINE.getValue());
//                }
//            }
            if (WorkOrderStatusEnum.WAIT_DISTRIBUTE.equals(workOrder.getStatus())) {
                workOrderList.add(workOrder);
            } else if (WorkOrderStatusEnum.DISTRIBUTED.equals(workOrder.getStatus())) {
                distributeList.add(workOrder);
            }
        }
        /** 添加工单 */
        workOrderService.innerAddWorkOrder(workOrderList);
        workOrderService.innerAddWorkOrder(distributeList);
 
    }
 
    /**
     * 把阈值条件查出来,转成map
     *
     * @param name
     * @return
     */
    @Override
    public Map<String, YwThreshold> getYwThresholdMap(String name) {
        return ywThresholdMapper.selectList(
                new QueryWrapper<YwThreshold>().eq("monitor_type", name)
        ).stream().collect(Collectors.toMap(
                YwThreshold::getKey,
                Function.identity()
        ));
    }
 
    /**
     * 白名单详情
     *
     * @param id
     * @return
     */
    @Override
    public Result selectWorkOrderWhiteDetail(Integer id) {
        WorkOrderWhite workOrderWhite = workOrderWhiteMapper.getById(id);
        List<String> errorTypeList = Arrays.asList(workOrderWhite.getErrorType().split(","));
        workOrderWhite.setErrorTypeList(errorTypeList);
        return Result.ok().data(workOrderWhite);
    }
 
    /**
     * 工单白名单列表
     *
     * @param query 查询
     * @return {@link List }<{@link WorkOrderWhite }>
     * @author
     */
    @Override
    public Result selectWorkOrderWhiteList(WorkOrderWhiteQuery query) {
        IPage<WorkOrderWhite> page = PageUtil.getPage(query, WorkOrderWhite.class);
        workOrderWhiteMapper.page(page, query);
        List<WorkOrderWhite> records = page.getRecords();
        records.forEach(white -> {
            List<String> errorTextList = new ArrayList<>();
            List<String> errorTypeList = Arrays.asList(white.getErrorType().split(","));
            errorTypeList.forEach(error -> {
                String errorText = ErrorType.getDescriptionByValue(error);
                errorTextList.add(errorText);
            });
            white.setErrorType(String.join(",", errorTextList));
        });
        return Result.ok().data(records).total(page.getTotal());
    }
 
    /**
     * 添加工单白名单
     *
     * @param workOrderWhite 白色工单
     * @return {@link Result }
     * @author
     */
    @Override
    public Result addWorkOrderWhite(WorkOrderWhite workOrderWhite) {
        // 检查是否已经存在该白名单
        WorkOrderWhite flag = workOrderWhiteMapper.selectBySerialNumber(workOrderWhite.getSerialNumber());
        if (flag != null) {
            return Result.error("该设备已存在白名单");
        } else {
            List<String> errorTypeList = workOrderWhite.getErrorTypeList();
            workOrderWhite.setErrorType(String.join(",", errorTypeList));
            workOrderWhite.setCreateBy(SecurityUtils.getUsername());
            workOrderWhiteMapper.insert(workOrderWhite);
            return Result.ok();
        }
    }
 
    /**
     * 修改工单白名单
     *
     * @param workOrderWhite 白色工单
     * @return {@link Result }
     * @author
     */
    @Override
    public Result updateWorkOrderWhite(WorkOrderWhite workOrderWhite) {
        WorkOrderWhite white = workOrderWhiteMapper.selectBySerialNumber(workOrderWhite.getSerialNumber());
        workOrderWhite.setId(white.getId());
        List<String> errorTypeList = workOrderWhite.getErrorTypeList();
        workOrderWhite.setErrorType(String.join(",", errorTypeList));
        workOrderWhiteMapper.updateById(workOrderWhite);
        return Result.ok();
    }
 
    /**
     * 批量删除工单白名单
     *
     * @param ids ids
     * @author
     */
    @Override
    public Result batchDeleteWorkOrderWhite(List<String> ids) {
        workOrderWhiteMapper.batchDelete(ids);
        return Result.ok();
    }
 
    /**
     * 白名单导出
     *
     * @param response
     * @throws IOException
     */
    @Override
    public void whiteExport(HttpServletResponse response) throws IOException {
        //白名单数据
        List<WorkOrderWhiteExport> data = workOrderWhiteMapper.whiteExport();
        data.forEach(white -> {
            List<String> errorTextList = new ArrayList<>();
            List<String> errorTypeList = Arrays.asList(white.getErrorType().split(","));
            errorTypeList.forEach(error -> {
                String errorText = ErrorType.getDescriptionByValue(error);
                errorTextList.add(errorText);
            });
            white.setErrorType(String.join(",", errorTextList));
        });
        //故障类型数据
        List<String> errorTextList = ErrorType.getDescriptionList();
        List<ErrorExport> errorExports = new ArrayList<>();
        errorTextList.forEach(error -> {
            ErrorExport errorExport = new ErrorExport();
            errorExport.setError(error);
            errorExports.add(errorExport);
        });
        ExcelWriter excelWriter = null;
        try (OutputStream outputStream = response.getOutputStream()) {
            excelWriter = EasyExcel.write(outputStream).build();
 
            WriteSheet whiteSheet = EasyExcel.writerSheet(0, "工单白名单清单").head(WorkOrderWhiteExport.class).build();
            WriteSheet errorSheet = EasyExcel.writerSheet(1, "故障类型").head(ErrorExport.class).build();
 
            excelWriter.write(data, whiteSheet);
            excelWriter.write(errorExports, errorSheet);
            excelWriter.finish();
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                excelWriter.finish();
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }
 
    /**
     * 导入工单白名单
     *
     * @param file
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result importWhite(MultipartFile file) throws IOException {
//        Consumer<List<WorkOrderWhiteExport>> consumer = (dataList) -> {
//            try {
//                this.updateWhite(dataList);
//            } catch (ExecutionException e) {
//                e.printStackTrace();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        };
//        EasyExcel.read(file.getInputStream(), WorkOrderWhiteExport.class, new CurrencyDataListener(consumer))
//                .sheet()
//                .headRowNumber(1)
//                .doRead();
        List<WorkOrderWhiteExport> dataList = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), WorkOrderWhiteExport.class, new AnalysisEventListener<WorkOrderWhiteExport>() {
            @Override
            public void invoke(WorkOrderWhiteExport excel, AnalysisContext analysisContext) {
                // 将读取到的每一行存入reportDetails集合中
                dataList.add(excel);
            }
 
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            }
        }).sheet().doRead();
 
        if (CollectionUtils.isEmpty(dataList)) {
            throw new RuntimeException("导入数据不能为空");
        }
        boolean duplic = checkDuplic(dataList);
        if (duplic) throw new RuntimeException("存在重复国标设备");
        List<WorkOrderWhite> addList = new ArrayList<>();
        dataList.stream().forEach(item -> {
            WorkOrderWhite white = new WorkOrderWhite();
            //国标码
            white.setSerialNumber(item.getSerialNumber());
            //备注
            white.setRemark(item.getRemark());
            String errorType = item.getErrorType();
            if (StringUtils.isEmpty(errorType)) {
                throw new RuntimeException("国标码为" + item.getSerialNumber() + "的设备故障不能为空");
            }
            try {
                List<String> errorDataList = new ArrayList<>();
                List<String> errorExcelList = Arrays.asList(item.getErrorType().split(","));
                errorExcelList.forEach(desc -> {
                    //把中文转换为数据库存储格式
                    String errorText = ErrorType.getValueByDescription(desc);
                    //找不到抛出异常
                    if (errorText == null)
                        throw new RuntimeException("国标码为" + item.getSerialNumber() + "的设备故障类型有误");
                    errorDataList.add(errorText);
                });
                white.setErrorType(String.join(",", errorDataList));
                addList.add(white);
            } catch (Exception e) {
                throw new RuntimeException("国标码为" + item.getSerialNumber() + "的设备故障类型有误");
            }
        });
        if (!CollectionUtils.isEmpty(addList)) {
            workOrderWhiteMapper.deleteAll();
            workOrderWhiteMapper.insertBatch(addList);
        }
        return Result.ok();
    }
 
    /**
     * 修改白名单
     *
     * @param dataList
     * @param unitId
     */
    public void updateWhite(List<WorkOrderWhiteExport> dataList) throws ExecutionException, InterruptedException {
        if (CollectionUtils.isEmpty(dataList)) {
            throw new RuntimeException("导入数据不能为空");
        }
        //已存在的白名单
        List<String> serialNumbers = workOrderWhiteMapper.selectList().stream().map(WorkOrderWhite::getSerialNumber).collect(Collectors.toList());
        List<WorkOrderWhite> addList = new ArrayList<>();
        List<WorkOrderWhite> updateList = new ArrayList<>();
        dataList.stream().forEach(item -> {
            WorkOrderWhite white = new WorkOrderWhite();
            //国标码
            white.setSerialNumber(item.getSerialNumber());
            //备注
            white.setRemark(item.getRemark());
            String errorType = item.getErrorType();
            if (StringUtils.isEmpty(errorType)) {
                throw new RuntimeException("国标码为" + item.getSerialNumber() + "的设备故障不能为空");
            }
            try {
                List<String> errorDataList = new ArrayList<>();
                List<String> errorExcelList = Arrays.asList(item.getErrorType().split(","));
                errorExcelList.forEach(desc -> {
                    //把中文转换为数据库存储格式
                    String errorText = ErrorType.getValueByDescription(desc);
                    //找不到抛出异常
                    if (errorText == null)
                        throw new RuntimeException("国标码为" + item.getSerialNumber() + "的设备故障类型有误");
                    errorDataList.add(errorText);
                });
                white.setErrorType(String.join(",", errorDataList));
                if (!CollectionUtils.isEmpty(serialNumbers) && serialNumbers.contains(white.getSerialNumber())) {
                    updateList.add(white);
                } else {
                    addList.add(white);
                }
            } catch (Exception e) {
                throw new RuntimeException("国标码为" + item.getSerialNumber() + "的设备故障类型有误");
            }
        });
        if (!CollectionUtils.isEmpty(addList)) workOrderWhiteMapper.insertBatch(addList);
        if (!CollectionUtils.isEmpty(updateList)) workOrderWhiteMapper.updateBatch(updateList);
    }
 
    /**
     * 检查阈值
     *
     * @param key          某阈值标识
     * @param value        接口获取到的值
     * @param serialNumber 国标码
     * @param thresholds   阈值条件map
     * @param compareType  比较方式:>=    <=
     * @param errorType    故障类型
     * @param <T>
     */
    @Override
    public <T extends Comparable<T>> void check(String key, T value, String
            serialNumber, Map<String, YwThreshold> thresholds, WorkOrder workOrder, CompareType compareType, String
                                                        errorType) {
        Optional.ofNullable(value).ifPresentOrElse(
                v -> {
                    YwThreshold ywThreshold = thresholds.get(key);
                    //转换类型
                    //待工单阈值
                    T thresholdAutoValue = parseThreshold(ywThreshold.getValueAuto(), value.getClass());
                    //直接下发工单阈值
                    T thresholdValue = parseThreshold(ywThreshold.getValue(), value.getClass());
                    if ("percent".equals(ywThreshold.getCountType())) {
                        if (thresholdAutoValue instanceof Float) {
                            thresholdAutoValue = (T) Float.valueOf(((Float) thresholdAutoValue) / 100f);
                        }
                        if (thresholdValue instanceof Float) {
                            thresholdValue = (T) Float.valueOf(((Float) thresholdValue) / 100f);
                        }
                    }
                    //比较大小,加入到对应待处理集合
                    if (compareType.compare(v, thresholdValue)) {
                        //进入工单直接下发
                        workOrder.setSerialNumber(serialNumber);
                        workOrder.setStatus(WorkOrderStatusEnum.DISTRIBUTED);
                        if (CollectionUtils.isEmpty(workOrder.getErrorTypeList())) {
                            workOrder.setErrorTypeList(new ArrayList<>());
                            workOrder.getErrorTypeList().add(errorType);
                        } else {
                            workOrder.getErrorTypeList().add(errorType);
                        }
                    } else if (compareType.compare(v, thresholdAutoValue)) {
                        //进入工单代下发
                        workOrder.setSerialNumber(serialNumber);
                        workOrder.setStatus(WorkOrderStatusEnum.WAIT_DISTRIBUTE);
                        if (CollectionUtils.isEmpty(workOrder.getErrorTypeList())) {
                            workOrder.setErrorTypeList(new ArrayList<>());
                            workOrder.getErrorTypeList().add(errorType);
                        } else {
                            workOrder.getErrorTypeList().add(errorType);
                        }
                    }
                },
                () -> log.error("{} 为空: {}", thresholds.get(key).getName(), serialNumber)
        );
    }
 
    /**
     * 所有白名单添加故障类型
     *
     * @param workOrderWhite
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addBatch(WorkOrderWhite workOrderWhite) {
        List<String> errorTypeListAdd = workOrderWhite.getErrorTypeList();
        List<WorkOrderWhite> whites = workOrderWhiteMapper.selectList();
        for (WorkOrderWhite white : whites) {
            List<String> errorTypeList = new ArrayList<>(Arrays.asList(white.getErrorType().split(",")));
            for (String newError : errorTypeListAdd) {
                if (errorTypeList.contains(newError)) {
                    continue;
                } else {
                    errorTypeList.add(newError);
                }
            }
            white.setErrorType(String.join(",", errorTypeList));
        }
        if (!CollectionUtils.isEmpty(whites)) {
            workOrderWhiteMapper.deleteAll();
            workOrderWhiteMapper.insertBatch(whites);
        }
        return Result.ok();
    }
 
    private <T extends Comparable<T>> T parseThreshold(String thresholdStr, Class<?> type) {
        if (Integer.class.equals(type)) {
            return (T) Integer.valueOf(thresholdStr);
        } else if (Float.class.equals(type)) {
            return (T) Float.valueOf(thresholdStr);
        } else if (Double.class.equals(type)) {
            return (T) Double.valueOf(thresholdStr);
        } else if (Long.class.equals(type)) {
            return (T) Long.valueOf(thresholdStr);
        } else {
            throw new IllegalArgumentException("不支持转换类型" + type);
        }
    }
 
    public static boolean checkDuplic(List<WorkOrderWhiteExport> dataList) {
        Set<String> serialNumbers = new HashSet<>();
 
        for (WorkOrderWhiteExport white : dataList) {
            String serialNumber = white.getSerialNumber();
            if (!serialNumbers.add(serialNumber)) {
                return true;
            }
        }
        return false;
    }
}