郑永安
2023-09-19 69185134fcfaf913ea45f1255677225a2cc311a4
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
package com.gk.hotwork.doublePrevention.service.impl;//package com.gk.hotwork.doublePrevention.service.impl;
 
import com.gk.hotwork.Domain.DepartmentInfo;
import com.gk.hotwork.Domain.Enum.ResultCodes;
import com.gk.hotwork.Domain.RiskControlClassify;
import com.gk.hotwork.Domain.UserInfo;
import com.gk.hotwork.Domain.Utils.ExcelProperty;
import com.gk.hotwork.Domain.Utils.FileOptUtils;
import com.gk.hotwork.Domain.Utils.StringUtils;
import com.gk.hotwork.Domain.co.ContextCacheUser;
import com.gk.hotwork.Domain.Exception.E;
import com.gk.hotwork.Domain.Exception.BusinessException;
import com.gk.hotwork.Domain.Vo.ResultVO;
import com.gk.hotwork.Service.DepartmentService;
import com.gk.hotwork.Service.RiskControlClassifyService;
import com.gk.hotwork.Service.UserService;
import com.gk.hotwork.doublePrevention.entity.*;
import com.gk.hotwork.doublePrevention.enums.DeviceStatusEnum;
import com.gk.hotwork.doublePrevention.enums.StatusEnum;
import com.gk.hotwork.doublePrevention.enums.SyncEnum;
import com.gk.hotwork.doublePrevention.service.FileHandlerService;
import com.gk.hotwork.doublePrevention.service.baseService.*;
import com.gk.hotwork.doublePrevention.utils.SnowFlow;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;
 
import static com.gk.hotwork.Domain.Utils.Properties.filePath;
 
@Service
public class FileHandlerServiceImpl implements FileHandlerService {
 
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UserService userService;
 
    @Autowired
    private PreventDangerCheckTaskUnitService preventDangerCheckTaskUnitService;
    @Autowired
    private PreventRiskControlMeasureService preventRiskControlMeasureService;
    @Autowired
    private PreventDangerCheckWorkService preventDangerCheckWorkService;
    @Autowired
    private PreventDangerCheckTaskService preventDangerCheckTaskService;
    @Autowired
    private PreventDangerCheckContentService preventDangerCheckContentService;
    @Autowired
    private PreventReportConfigService preventReportConfigService;
    @Autowired
    private PreventProduceDeviceService preventProduceDeviceService;
    @Autowired
    private PreventRiskMapService preventRiskMapService;
    @Autowired
    private PreventRiskAnaUnitService preventRiskUnitService;
    @Autowired
    private PreventRiskEventService preventRiskEventService;
    @Autowired
    private PreventRiskControlTemplateService preventRiskControlTemplateService;
 
    @Autowired
    RiskControlClassifyService riskControlClassifyService;
 
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //正整数
    String pattern = "^[0-9]*[1-9][0-9]*$";
 
    Pattern pattern2 = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$");
 
    String[] deviceTitle = {"生产装置", "风险等级", "所属部门", "区域位置"};
 
    String[] riskUnitTitle = {"单元名称", "责任部门", "责任人", "安全风险分析对象编码", "生产装置"};
 
    String[] eventTitle = {"事件名称", "单元名称", "可能造成的后果"};
 
    String[] measureTitle = {"风险事件", "管控措施编号", "管控方式", "管控措施分类1", "管控措施分类2", "管控措施分类3", "管控措施描述", "隐患排查内容"};
 
 
 
    /**
     * 生产装置-导入
     */
    @Transactional
    @Override
    public ResultVO<PreventProduceDevice> deviceImport(ContextCacheUser currentUser, MultipartFile file) {
 
        ResultVO resultVO = new ResultVO<>();
        resultVO.setCode("200");
        resultVO.setMsg("生产设施设备导入成功");
 
        if (file == null){
            throw new BusinessException(E.DATA_PARAM_NULL, "找不到上传文件");
        }
        if (file.getSize() == 0){
            throw new BusinessException(E.DATA_PARAM_NULL, "文件内容为空");
        }
        if (!FileOptUtils.isDirExists(filePath)) {
            throw new BusinessException(E.DATA_PARAM_NULL, "发生错误或不为目录");
        }
        String fileSave = filePath + currentUser.getRealName() + "_"  + ".xlsx";
        int sum = 0;
        //获取list
        List<PreventProduceDevice> deviceLists = new ArrayList<>();
 
        try {
            file.transferTo(new File(fileSave));
            String name = file.getOriginalFilename();
            Boolean isExcel2007 = name.substring(name.lastIndexOf(".") + 1).endsWith("xlsx") ? true : false;
            InputStream in = new FileInputStream(fileSave);
 
            Workbook workbook = null;
            if (isExcel2007) {
                workbook = new XSSFWorkbook(in);
            } else {
                workbook = new HSSFWorkbook(in);
            }
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "excel 第1页不能为空");
            }
            Row row = sheet.getRow(0);
            // 标题总列数
            int colNum = row.getPhysicalNumberOfCells();
            String[] title = new String[colNum];
 
            if (colNum != deviceTitle.length) {
                throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "上传文件的列的个数错误");
            }
            for (int i = 0; i < colNum; i++) {
 
                title[i] = row.getCell(i).getStringCellValue();
                if (StringUtils.isNotBlank(title[i])) {
                    title[i] = title[i].trim();
                }
                if (!title[i].equals((deviceTitle[i]))) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "上传文件的第" + (i + 1) + "列的标题为:" + title[i] + ",不为:" + deviceTitle[i]);
                }
            }
            //遍历封装数据
            for (int irow = 1; irow <= sheet.getLastRowNum(); irow++) {
                int realRow = irow + 1;
                PreventProduceDevice device = new PreventProduceDevice();
                Object value = null;
                row = sheet.getRow(irow);
 
                //字段1-生产装置
                value = ExcelProperty.getCellValue(row.getCell(0), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + (realRow + 1) + "行,生产装置不能为空.<br/>");
                } else {
                    //无重名,设置属性
                    PreventProduceDevice deviceByName = preventProduceDeviceService.getDeviceByName(value.toString().trim());
                    if (ObjectUtils.isEmpty(deviceByName)){
                        device.setProduceDeviceName(value.toString().trim());
                    }else {
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + (realRow + 1) + "行,生产装置名称已被使用,请在生产装置名称后添加编号或所属部门.<br/>");
                    }
                }
 
                //字段2-风险等级
                //String level1="";
                value = ExcelProperty.getCellValue(row.getCell(1), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + (realRow + 1) + "行,风险等级不能为空.<br/>");
                }
                /*1-低风险,2-一般风险,3-较大风险,4-重大风险*/
                if(value.toString().trim().equals("低风险")){
                    device.setRiskLevel((byte) 1);
                } else if(value.toString().trim().equals("一般风险")){
                    device.setRiskLevel((byte) 2);
                } else if(value.toString().trim().equals("较大风险")){
                    device.setRiskLevel((byte) 3);
                } else if(value.toString().trim().equals("重大风险")){
                    device.setRiskLevel((byte) 4);
                } else {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + (realRow + 1) + "行,风险等级不符合规范.<br/>");
                }
 
                //参数属性3-所属部门
                value = ExcelProperty.getCellValue(row.getCell(2), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + (realRow + 1) + "行,所属部门不能为空.<br/>");
                } else {
                    //通过部门名称查部门
                    DepartmentInfo departmentInfo = departmentService.getInfoByName(value.toString().trim());
                    if (ObjectUtils.isEmpty(departmentInfo)){
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + (realRow + 1) + "行,部门名称有误,或未录入系统.<br/>");
                    }else {
                        device.setDepName(value.toString().trim());
                        device.setDepId(departmentInfo.getId());
                    }
                }
 
                //参数属性4-区域位置
                value = ExcelProperty.getCellValue(row.getCell(3), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + (realRow + 1) + "行的区域位置不能为空.<br/>");
                } else {
                    device.setLocation(value.toString().trim());
                }
                //获取填充信息
                Date date = new Date();
                SnowFlow snowFlow = new SnowFlow();//雪花算法生成器
                String uuid = UUID.randomUUID().toString();
                //封装参数
                device.setId( snowFlow.nextId());
                device.setUuid(uuid);
                device.setStatus(DeviceStatusEnum.DEVICE_USE.getCode());
                device.setEnterpriseId((long) 1);
                device.setEnterpriseUuid("111");
                device.setDepUuid(null);
                //TODO 此处未获取到真实姓名
                device.setCreateByUserName(currentUser.getRealName());//todo 暂时不知道是否能拿到属性
                device.setGmtCreate(date);
                device.setLastEditUserName(currentUser.getRealName());
                device.setGmtModitify(date);
                device.setDeleteStatus(StatusEnum.DELETE_STATUS_USE.getCode());
                deviceLists.add(device);
            }
        } catch (IOException e) {
            throw new RuntimeException("读取上传文件发生错误{}"+e);
        }
 
        for (PreventProduceDevice device : deviceLists) {
            //插入
            int result = preventProduceDeviceService.saveDevice(device);
            sum = sum + result;
        }
        resultVO.setCount(sum);
 
        return resultVO;
    }
 
 
    /**
     * 风险分析单元-导入
     */
    @Transactional
    @Override
    public ResultVO<PreventRiskAnaUnit> riskUnitImport(ContextCacheUser currentUser, MultipartFile file) {
 
        ResultVO resultVO = new ResultVO<>();
        resultVO.setCode("200");
        resultVO.setMsg(" 风险分析单元数据导入成功");
 
        if (file == null){
            throw new BusinessException(E.DATA_PARAM_NULL, "找不到上传文件");
        }
        if (file.getSize() == 0){
            throw new BusinessException(E.DATA_PARAM_NULL, "文件内容为空");
        }
        if (!FileOptUtils.isDirExists(filePath)) {
            throw new BusinessException(E.DATA_PARAM_NULL, "发生错误或不为目录");
        }
        String fileSave = filePath + currentUser.getRealName() + "_"  + ".xlsx";
        int sum = 0;
        //获取list
        List<PreventRiskAnaUnit> riskUnitLists = new ArrayList<>();
 
        try {
            file.transferTo(new File(fileSave));
            String name = file.getOriginalFilename();
            Boolean isExcel2007 = name.substring(name.lastIndexOf(".") + 1).endsWith("xlsx") ? true : false;
            InputStream in = new FileInputStream(fileSave);
 
            Workbook workbook = null;
            if (isExcel2007) {
                workbook = new XSSFWorkbook(in);
            } else {
                workbook = new HSSFWorkbook(in);
            }
 
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "excel 第1页不能为空");
            }
            Row row = sheet.getRow(0);
            // 标题总列数
            int colNum = row.getPhysicalNumberOfCells();
            String[] title = new String[colNum];
 
            if (colNum != riskUnitTitle.length) {
                throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "上传文件的列的个数错误");
            }
            for (int i = 0; i < colNum; i++) {
 
                title[i] = row.getCell(i).getStringCellValue();
                if (StringUtils.isNotBlank(title[i])) {
                    title[i] = title[i].trim();
                }
                if (!title[i].equals((riskUnitTitle[i]))) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "上传文件的第" + (i + 1) + "列的标题为" + title[i] + "不为" + riskUnitTitle[i]);
                }
            }
            //遍历封装数据
            for (int irow = 1; irow <= sheet.getLastRowNum(); irow++) {
                int realRow = irow + 1;
                PreventRiskAnaUnit riskAnaUnit = new PreventRiskAnaUnit();
                Object value = null;
                Object value1 = null;
                row = sheet.getRow(irow);
 
                //字段1-安全风险分析单元
                value = ExcelProperty.getCellValue(row.getCell(0), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,安全风险分析单元名称不能为空.<br/>");
                } else {
                    PreventRiskAnaUnit riskUnitByName = preventRiskUnitService.getRiskUnitByName(value.toString().trim());
                    //无重名,设置属性
                    if (ObjectUtils.isEmpty(riskUnitByName)){
                        riskAnaUnit.setRiskUnitName(value.toString().trim());
                       }else {
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,安全风险分析单元名称已被使用,请在安全风险分析单元名称后添加编号或所属部门.<br/>");
                    }
                }
 
                //字段2-责任部门
                value1 = ExcelProperty.getCellValue(row.getCell(1), evaluator);
                if (null == value1 || StringUtils.isBlank(value1.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,责任部门不能为空.<br/>");
                } else {
                    //通过部门名称查部门
                    DepartmentInfo departmentInfo = departmentService.getInfoByName(value1.toString().trim());
                    if (ObjectUtils.isEmpty(departmentInfo)){
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,责任部门名称有误,或未录入系统.<br/>");
                    }else {
                        riskAnaUnit.setLiableDep(value1.toString().trim());
                        riskAnaUnit.setLiableDepId(departmentInfo.getId());
                        riskAnaUnit.setLiableDepUuid(null);
                    }
                }
 
                //字段3-责任人
                value = ExcelProperty.getCellValue(row.getCell(2), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行的责任人不能为空.<br/>");
                } else {
                    //UserInfo userInfo = userService.selectByUser(value.toString().trim());
                    DepartmentInfo departmentInfo = departmentService.getInfoByName(value1.toString().trim());
                    UserInfo userByRealName = userService.getUserByRealNameAndDep(value.toString().trim(), departmentInfo.getId());
                    if (ObjectUtils.isEmpty(userByRealName)){
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行的责任人名称有误,或未录入系统.<br/>");
                    }else {
                        riskAnaUnit.setLiablePerson(userByRealName.getRealname());
                        riskAnaUnit.setLiablePersonId(userByRealName.getId());
                        riskAnaUnit.setLiablePersonUuid(null);
                    }
                }
 
                //参数属性4-安全风险分析对象编码
                value = ExcelProperty.getCellValue(row.getCell(3), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,安全风险分析对象编码不能为空.<br/>");
                } else {
                    //查询是否有重复编码
                    PreventRiskAnaUnit riskUnitByCode = preventRiskUnitService.getRiskUnitByCode(value.toString().trim());
                    if (ObjectUtils.isEmpty(riskUnitByCode)){
                        riskAnaUnit.setRiskCode(value.toString().trim());
                    }else {
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,安全风险分析对象编码已经被使用.<br/>");
                    }
                }
 
                //参数属性5-所属生产装置
                value = ExcelProperty.getCellValue(row.getCell(4), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,生产装置不能为空.<br/>");
                } else {
                    PreventProduceDevice deviceByName = preventProduceDeviceService.getDeviceByNameAndDep(value.toString().trim(), value1.toString().trim());
                    if (ObjectUtils.isEmpty(deviceByName)){
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,生产装置不存在或未录入系统.<br/>");
                    }else {
                        riskAnaUnit.setProduceDeviceId(deviceByName.getId());
                        riskAnaUnit.setProduceDeviceUuid(deviceByName.getUuid());
                    }
                }
 
                //获取填充信息
                Date date = new Date();
                SnowFlow snowFlow = new SnowFlow();//雪花算法生成器
                String uuid = UUID.randomUUID().toString();
                //封装参数
                riskAnaUnit.setId(snowFlow.nextId());
                riskAnaUnit.setUuid(uuid);
                riskAnaUnit.setDeleteStatus(StatusEnum.DELETE_STATUS_USE.getCode());
                riskAnaUnit.setEnterpriseId((long) 1);
                riskAnaUnit.setEnterpriseUuid("111");
                riskAnaUnit.setGmtModitify(date);
                riskAnaUnit.setGmtCreate(date);
                riskAnaUnit.setCreateByUserName(currentUser.getRealName());
                riskAnaUnit.setLastEditUserName(currentUser.getRealName());
                //读取上报主配置,设置上报属性
                PreventReportConfig reportConfigById = preventReportConfigService.getReportConfigById(SyncEnum.REPORT_CONFIG_RISK_ANA_UNIT.getCode());
                //设置上报时间为空
                riskAnaUnit.setReportTime(null);
                //设置本条数据上报更新时间
                riskAnaUnit.setUpdateReportDataTime(date);
                //读取上报主配置,进行任务记录上报配置,如果开启上报功能,且设置为自动上报,开启上报相关配置
                if (reportConfigById.getReportState() == SyncEnum.REPORT_ON.getCode()
                        && reportConfigById.getReportType() == SyncEnum.REPORT_HAND_EXEC_CONFIG.getCode()){
                    //设置上报状态为-等待上报
                    riskAnaUnit.setReportStatus(SyncEnum.SYNC_WAIT_EXEC.getCode());
                    //设置本条数据上报开关为-开启
                    riskAnaUnit.setReportSwitch(SyncEnum.REPORT_ON.getCode());
                    //其他情况默认不开启上报数据,如果是手动上报,可对单条数据进行操作
                }else {
                    //设置上报状态为-不上报
                    riskAnaUnit.setReportStatus(SyncEnum.SYNC_NOT_EXEC.getCode());
                    //设置本条数据上报开关为-关闭
                    riskAnaUnit.setReportSwitch(SyncEnum.REPORT_OFF.getCode());
                }
                //封装数据
                riskUnitLists.add(riskAnaUnit);
            }
        } catch (IOException e) {
            throw new RuntimeException("读取上传文件发生错误{}"+e);
        }
 
        //插入
        for (PreventRiskAnaUnit riskUnit : riskUnitLists) {
            int result = preventRiskUnitService.saveRiskAnaUnit(riskUnit);
            sum = sum + result;
        }
        resultVO.setCount(sum);
 
        return resultVO;
    }
 
    /**
     * 安全风险事件-导入
     */
    @Transactional
    @Override
    public ResultVO<PreventRiskEvent> eventImport(ContextCacheUser currentUser, MultipartFile file) {
 
        ResultVO resultVO = new ResultVO<>();
        resultVO.setCode("200");
        resultVO.setMsg(" 安全风险事件数据导入成功");
 
        if (file == null){
            throw new BusinessException(E.DATA_PARAM_NULL, "找不到上传文件");
        }
        if (file.getSize() == 0){
            throw new BusinessException(E.DATA_PARAM_NULL, "文件内容为空");
        }
        if (!FileOptUtils.isDirExists(filePath)) {
            throw new BusinessException(E.DATA_PARAM_NULL, "发生错误或不为目录");
        }
        String fileSave = filePath + currentUser.getRealName() + "_"  + ".xlsx";
        int sum = 0;
        //获取list
        List<PreventRiskEvent> eventList = new ArrayList<>();
 
        try {
            file.transferTo(new File(fileSave));
            String name = file.getOriginalFilename();
            Boolean isExcel2007 = name.substring(name.lastIndexOf(".") + 1).endsWith("xlsx") ? true : false;
            InputStream in = new FileInputStream(fileSave);
 
            Workbook workbook = null;
            if (isExcel2007) {
                workbook = new XSSFWorkbook(in);
            } else {
                workbook = new HSSFWorkbook(in);
            }
 
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "excel 第1页不能为空");
            }
            Row row = sheet.getRow(0);
            // 标题总列数
            int colNum = row.getPhysicalNumberOfCells();
            String[] title = new String[colNum];
 
            if (colNum != eventTitle.length) {
                throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "上传文件的列的个数错误");
            }
            for (int i = 0; i < colNum; i++) {
 
                title[i] = row.getCell(i).getStringCellValue();
                if (StringUtils.isNotBlank(title[i])) {
                    title[i] = title[i].trim();
                }
                if (!title[i].equals((eventTitle[i]))) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "上传文件的第" + (i + 1) + "列的标题为:" + title[i] + ",不为:" + eventTitle[i]);
                }
            }
            //遍历封装数据
            for (int irow = 1; irow <= sheet.getLastRowNum(); irow++) {
                int realRow = irow + 1;
                PreventRiskEvent event = new PreventRiskEvent();
                Object value = null;
                row = sheet.getRow(irow);
 
                //字段1-风险事件名称
                value = ExcelProperty.getCellValue(row.getCell(0), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,风险事件名称不能为空.<br/>");
                } else {
                    //通过部门名称查部门
                    PreventRiskEvent riskEventByName = preventRiskEventService.getRiskEventByName(value.toString().trim());
                    if (ObjectUtils.isEmpty(riskEventByName)){
                        event.setRiskEventName(value.toString().trim());
                    }else {
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,风险事件名称已经被使用,请为新事件添加编号、部门、设施.<br/>");
                    }
                }
 
                //字段2-安全风险分析单元
                value = ExcelProperty.getCellValue(row.getCell(1), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,安全风险分析单元名称不能为空.<br/>");
                } else {
                    PreventRiskAnaUnit riskUnitByName = preventRiskUnitService.getRiskUnitByName(value.toString().trim());
                    if (ObjectUtils.isEmpty(riskUnitByName)){
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,安全风险分析单元不存在或未录入系统.<br/>");
                    }else {
                        event.setRiskUnitId(riskUnitByName.getId());
                        event.setRiskUnitUuid(riskUnitByName.getUuid());
                    }
                }
 
                //字段3-可能造成的后果
                value = ExcelProperty.getCellValue(row.getCell(2), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    event.setEventResult(null);
                } else {
                   event.setEventResult(value.toString().trim());
                }
 
                //获取填充信息
                Date date = new Date();
                SnowFlow snowFlow = new SnowFlow();//雪花算法生成器
                String uuid = UUID.randomUUID().toString();
                //封装参数
                event.setId(snowFlow.nextId());
                event.setUuid(uuid);
                event.setDeleteStatus(StatusEnum.DELETE_STATUS_USE.getCode());
                event.setEnterpriseId((long) 1);
                event.setEnterpriseUuid("111");
                event.setGmtModitify(date);
                event.setGmtCreate(date);
                event.setCreateByUserName(currentUser.getRealName());
                event.setLastEditUserName(currentUser.getRealName());
                //读取上报主配置,设置属性
                PreventReportConfig reportConfigById = preventReportConfigService.getReportConfigById(SyncEnum.REPORT_CONFIG_RISK_EVENT.getCode());
                //设置上报时间为空
                event.setReportTime(null);
                //设置本条数据上报更新时间
                event.setUpdateReportDataTime(date);
                //读取上报主配置,进行任务记录上报配置,如果开启上报功能,且设置为自动上报,开启上报相关配置
                if (reportConfigById.getReportState() == SyncEnum.REPORT_ON.getCode()
                        && reportConfigById.getReportType() == SyncEnum.REPORT_HAND_EXEC_CONFIG.getCode()){
                    //设置上报状态为-等待上报
                    event.setReportStatus(SyncEnum.SYNC_WAIT_EXEC.getCode());
                    //设置本条数据上报开关为-开启
                    event.setReportSwitch(SyncEnum.REPORT_ON.getCode());
                    //其他情况默认不开启上报数据,如果是手动上报,可对单条数据进行操作
                }else {
                    //设置上报状态为-不上报
                    event.setReportStatus(SyncEnum.SYNC_NOT_EXEC.getCode());
                    //设置本条数据上报开关为-关闭
                    event.setReportSwitch(SyncEnum.REPORT_OFF.getCode());
                }
 
                eventList.add(event);
            }
        } catch (IOException e) {
            throw new RuntimeException("读取上传文件发生错误{}"+e);
        }
 
        //插入
        for (PreventRiskEvent event : eventList) {
            int result = preventRiskEventService.saveRiskEvent(event);
            sum = sum + result;
        }
        resultVO.setCount(sum);
 
        return resultVO;
    }
 
 
 
    /**
     * 管控措施-导入
     */
    @Transactional
    @Override
    public ResultVO<PreventRiskEvent> measureImport(ContextCacheUser currentUser, MultipartFile file) {
 
        ResultVO resultVO = new ResultVO<>();
        resultVO.setCode("200");
        resultVO.setMsg(" 安全风险管控措施导入成功");
 
        if (file == null){
            throw new BusinessException(E.DATA_PARAM_NULL, "找不到上传文件");
        }
        if (file.getSize() == 0){
            throw new BusinessException(E.DATA_PARAM_NULL, "文件内容为空");
        }
        if (!FileOptUtils.isDirExists(filePath)) {
            throw new BusinessException(E.DATA_PARAM_NULL, "发生错误或不为目录");
        }
        String fileSave = filePath + currentUser.getRealName() + "_"  + ".xlsx";
        int sum = 0;
        //获取list
        List<PreventRiskControlMeasure> measureList = new ArrayList<>();
        List<PreventDangerCheckContent> checkContentList = new ArrayList<>();
 
        try {
            file.transferTo(new File(fileSave));
            String name = file.getOriginalFilename();
            Boolean isExcel2007 = name.substring(name.lastIndexOf(".") + 1).endsWith("xlsx") ? true : false;
            InputStream in = new FileInputStream(fileSave);
 
            Workbook workbook = null;
            if (isExcel2007) {
                workbook = new XSSFWorkbook(in);
            } else {
                workbook = new HSSFWorkbook(in);
            }
 
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "excel 第1页不能为空");
            }
            Row row = sheet.getRow(0);
            // 标题总列数
            int colNum = row.getPhysicalNumberOfCells();
            String[] title = new String[colNum];
 
            if (colNum != measureTitle.length) {
                throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "上传文件的列的个数错误");
            }
            for (int i = 0; i < colNum; i++) {
 
                title[i] = row.getCell(i).getStringCellValue();
                if (StringUtils.isNotBlank(title[i])) {
                    title[i] = title[i].trim();
                }
                if (!title[i].equals((measureTitle[i]))) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "上传文件的第" + (i+1) + "列的标题为:" + title[i] + ",不为:" + measureTitle[i]);
                }
            }
            //遍历封装数据
            for (int irow = 1; irow <= sheet.getLastRowNum(); irow++) {
                int realRow = irow + 1;
                PreventRiskControlMeasure measure = new PreventRiskControlMeasure();
                PreventDangerCheckContent checkContent = new PreventDangerCheckContent();
                Object value = null;
                Object value1 = null;
                row = sheet.getRow(irow);
 
                //字段1-风险事件名称 封装eventId 与 eventUuid
                value = ExcelProperty.getCellValue(row.getCell(0), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,风险事件名称不能为空.<br/>");
                } else {
                    //通过名称查事件
                    PreventRiskEvent riskEventByName = preventRiskEventService.getRiskEventByName(value.toString().trim());
                    if (ObjectUtils.isEmpty(riskEventByName)){
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,风险事件不存在或未录入系统.<br/>");
                    }else {
                        measure.setRiskEventId(riskEventByName.getId());
                        measure.setRiskEventUuid(riskEventByName.getUuid());
                    }
                }
 
                //字段2-管控措施编号
                value = ExcelProperty.getCellValue(row.getCell(1), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,管控措施编号不能为空.<br/>");
                } else {
                    PreventRiskControlMeasure controlMeasureByCode = preventRiskControlMeasureService.getControlMeasureByCode(value.toString().trim());
                    if (ObjectUtils.isEmpty(controlMeasureByCode)){
                        measure.setControlMeasureCode(value.toString().trim());
                    }else {
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,管控措施编号已经被使用.<br/>");
                    }
                }
 
                //字段3-管控方式
                value = ExcelProperty.getCellValue(row.getCell(2), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,管控方式不能为空.<br/>");
                } else {
                    if (value.toString().trim().equals("自动化监控")){
                        measure.setControlType((byte) 1);
                    }else if (value.toString().trim().equals("隐患排查")){
                        measure.setControlType((byte) 2);
                    }else {
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,管控方式不符合要求.<br/>");
                    }
                }
 
 
                //字段4、5-管控措施分类1、管控措施分类2
                value = ExcelProperty.getCellValue(row.getCell(3), evaluator);
                value1 = ExcelProperty.getCellValue(row.getCell(4), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,管控措施分类1不能为空.<br/>");
                } else if (null == value1 || StringUtils.isBlank(value.toString())){
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,管控措施分类2不能为空.<br/>");
                }else {
                    RiskControlClassify getByClassify1AndClassify2 = riskControlClassifyService.getByClassify1AndClassify2(value.toString().trim(), value1.toString().trim());
                    if (ObjectUtils.isEmpty(getByClassify1AndClassify2)){
                        throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow + "行,管控措施分类1与管控措施分类2不符合规范或者不是父子层级.<br/>");
                    }else {
                        RiskControlClassify Classify1 = riskControlClassifyService.getByClassify(value.toString().trim());
                        measure.setClassify1(Classify1.getId().byteValue());
                        RiskControlClassify Classify2 = riskControlClassifyService.getByClassify2(Classify1.getId(), value1.toString().trim());
                        measure.setClassify2(Classify2.getId().byteValue());
                    }
                }
 
                //字段6-管控措施分类3
                value = ExcelProperty.getCellValue(row.getCell(5), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    measure.setClassify3(null);
                } else {
                    measure.setClassify3(value.toString().trim());
                }
 
                //字段7-管控措施描述
                value = ExcelProperty.getCellValue(row.getCell(6), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    measure.setMeasureDesc(null);
                } else {
                    measure.setMeasureDesc(value.toString().trim());
                }
 
                //字段7-隐患排查内容
                value = ExcelProperty.getCellValue(row.getCell(7), evaluator);
                if (null == value || StringUtils.isBlank(value.toString())) {
                    throw new BusinessException(E.DATA_PARAM_CHECK_INVALID, "文件不符合要求,第" + realRow  + "行,隐患排查内容不能为空.<br/>");
                } else {
                    checkContent.setCheckContent(value.toString().trim());
                }
//    String[] measureTitle = {"风险事件", "管控措施编号", "管控方式", "管控措施分类1", "管控措施分类2", "管控措施分类3", "管控措施描述", "隐患排查内容"}; todo
                //获取填充信息
                Date date = new Date();
                SnowFlow snowFlow = new SnowFlow();//雪花算法生成器
                String uuid = UUID.randomUUID().toString();
                long measureId = snowFlow.nextId();
                //封装管控措施参数
                measure.setId(measureId);
                measure.setUuid(uuid);
                measure.setEnterpriseId((long) 1);
                measure.setEnterpriseUuid("123");
                measure.setDeleteStatus(StatusEnum.DELETE_STATUS_USE.getCode());
                measure.setGmtModitify(date);
                measure.setGmtCreate(date);
                measure.setCreateByUserName(currentUser.getRealName());
                measure.setLastEditUserName(currentUser.getRealName());
                measure.setCheckTaskUnitId(null);
                measure.setCheckTaskUnitUuid(null);
                measure.setCheckWorkId(null);
                measure.setCheckWorkUuid(null);
                measure.setCheckTaskId(null);
                measure.setCheckTaskUuid(null);
 
                //封装隐患检查内容的参数
                checkContent.setControlMeasureId(measureId);
                checkContent.setControlMeasureUuid(uuid);
 
                PreventReportConfig reportConfigById = preventReportConfigService.getReportConfigById(SyncEnum.REPORT_CONFIG_RISK_MEASURE.getCode());
                //设置上报时间为空
                measure.setReportTime(null);
                //设置本条数据上报更新时间
                measure.setUpdateReportDataTime(date);
                //读取上报主配置,进行任务记录上报配置,如果开启上报功能,且设置为自动上报,开启上报相关配置
                if (reportConfigById.getReportState() == SyncEnum.REPORT_ON.getCode()
                        && reportConfigById.getReportType() == SyncEnum.REPORT_HAND_EXEC_CONFIG.getCode()){
                    //设置上报状态为-等待上报
                    measure.setReportStatus(SyncEnum.SYNC_WAIT_EXEC.getCode());
                    //设置本条数据上报开关为-开启
                    measure.setReportSwitch(SyncEnum.REPORT_ON.getCode());
                    //其他情况默认不开启上报数据,如果是手动上报,可对单条数据进行操作
                }else {
                    //设置上报状态为-不上报
                    measure.setReportStatus(SyncEnum.SYNC_NOT_EXEC.getCode());
                    //设置本条数据上报开关为-关闭
                    measure.setReportSwitch(SyncEnum.REPORT_OFF.getCode());
                }
 
                measureList.add(measure);
                checkContentList.add(checkContent);
            }
        } catch (IOException e) {
            throw new RuntimeException("读取上传文件发生错误{}"+e);
        }
 
        //插入
//        for (PreventRiskControlMeasure measure : measureList) {
//            int result = preventRiskControlMeasureService.saveRiskControlMeasure(measure);
//            if (result == 0 ){
//                throw new BusinessException(E.ADD_FAIL, "新增失败");
//            }
//            sum = sum + result;
//        }
        //todo
        boolean b = preventRiskControlMeasureService.saveBatch(measureList);
 
        //保存排查内容
        for (PreventDangerCheckContent checkContent : checkContentList) {
            int result = preventDangerCheckContentService.saveDangerCheckContent(checkContent);
            if (result == 0){
                throw new BusinessException(ResultCodes.SERVER_ADD_ERROR);
            }
        }
        resultVO.setCount(sum);
 
        return resultVO;
    }
}