zhangherong
8 天以前 2d3ded65b3c30b4f5cba6080d9c28e16a0b296cc
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
package org.jeecg.modules.eam.service.impl;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeecg.weibo.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.eam.constant.BusinessCodeConst;
import org.jeecg.modules.eam.constant.EamMaintenanceStandardDetailCategory;
import org.jeecg.modules.eam.constant.MaintenanceStandardStatusEnum;
import org.jeecg.modules.eam.entity.EamEquipment;
import org.jeecg.modules.eam.entity.EamEquipmentExtend;
import org.jeecg.modules.eam.entity.EamMaintenanceStandard;
import org.jeecg.modules.eam.entity.EamMaintenanceStandardDetail;
import org.jeecg.modules.eam.mapper.EamMaintenanceStandardMapper;
import org.jeecg.modules.eam.request.EamMaintenanceStandardRequest;
import org.jeecg.modules.eam.request.ImportException;
import org.jeecg.modules.eam.service.IEamEquipmentExtendService;
import org.jeecg.modules.eam.service.IEamEquipmentService;
import org.jeecg.modules.eam.service.IEamMaintenanceStandardDetailService;
import org.jeecg.modules.eam.service.IEamMaintenanceStandardService;
import org.jeecg.modules.eam.vo.EamMaintenanceStandardVo;
import org.jeecg.modules.flowable.apithird.business.entity.FlowMyBusiness;
import org.jeecg.modules.flowable.apithird.business.service.IFlowMyBusinessService;
import org.jeecg.modules.flowable.apithird.service.FlowCallBackServiceI;
import org.jeecg.modules.flowable.apithird.service.FlowCommonService;
import org.jeecg.modules.flowable.service.IFlowDefinitionService;
import org.jeecg.modules.flowable.service.IFlowTaskService;
import org.jeecg.modules.system.entity.BaseFactory;
import org.jeecg.modules.system.entity.BaseFactoryUser;
import org.jeecg.modules.system.entity.SysParams;
import org.jeecg.modules.system.service.*;
import org.jeecg.modules.system.vo.UserSelector;
import org.springframework.beans.BeanUtils;
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 javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
 
/**
 * @Description: 保养标准
 * @Author: jeecg-boot
 * @Date: 2025-03-26
 * @Version: V1.0
 */
@Service("IEamMaintenanceStandardService")
public class EamMaintenanceStandardServiceImpl extends ServiceImpl<EamMaintenanceStandardMapper, EamMaintenanceStandard> implements IEamMaintenanceStandardService, FlowCallBackServiceI {
 
    @Resource
    private EamMaintenanceStandardMapper eamMaintenanceStandardMapper;
    @Autowired
    private IEamMaintenanceStandardDetailService eamMaintenanceStandardDetailService;
    @Autowired
    private IBaseFactoryUserService baseFactoryUserService;
    @Autowired
    private IBaseFactoryService baseFactoryService;
    @Resource
    private FlowCommonService flowCommonService;
    @Resource
    private IFlowDefinitionService flowDefinitionService;
    @Autowired
    private IFlowTaskService flowTaskService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IFlowMyBusinessService flowMyBusinessService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IEamEquipmentService eamEquipmentService;
    @Autowired
    private IEamEquipmentExtendService eamEquipmentExtendService;
    @Autowired
    private ISysBusinessCodeRuleService businessCodeRuleService;
    @Autowired
    private ISysParamsService sysParamsService;
 
    // 常量定义
    private static final String REPAIR_TITLE = "维修人员保养内容";
    private static final String OPERATOR_TITLE = "操作人员保养内容";
    private static final Map<String, EamMaintenanceStandardDetailCategory> SECOND_CATEGORY_MAPPING = new HashMap<>();
 
    // 枚举映射初始化
    static {
        SECOND_CATEGORY_MAPPING.put(REPAIR_TITLE, EamMaintenanceStandardDetailCategory.REPAIRER_MAINTENANCE);
        SECOND_CATEGORY_MAPPING.put(OPERATOR_TITLE, EamMaintenanceStandardDetailCategory.OPERATOR_MAINTENANCE);
    }
 
    @Override
    public IPage<EamMaintenanceStandard> queryPageList(Page<EamMaintenanceStandard> page, EamMaintenanceStandard eamMaintenanceStandard) {
        QueryWrapper<EamMaintenanceStandard> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ems.del_flag", CommonConstant.DEL_FLAG_0);
        //用户数据权限
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser == null) {
            return page;
        }
        if (StringUtils.isNotBlank(sysUser.getEamEquipmentIds())) {
            //选择了设备,根据设备id过滤设备
            List<String> equipArr = Arrays.asList(sysUser.getEamEquipmentIds().split(","));
            queryWrapper.in("e.equipment_code", equipArr);
        } else {
            //没有选择设备,根据中心过滤设备
            List<BaseFactoryUser> baseFactoryUserList = baseFactoryUserService.
                    list(new LambdaQueryWrapper<BaseFactoryUser>().eq(BaseFactoryUser::getUserId, sysUser.getId()));
            if (!CollectionUtils.isEmpty(baseFactoryUserList)) {
                Set<String> factoryIds = baseFactoryUserList.stream().map(BaseFactoryUser::getFactoryId).collect(Collectors.toSet());
                Set<String> factoryCode = baseFactoryService.listByIds(factoryIds).stream().map(BaseFactory::getOrgCode).collect(Collectors.toSet());
                queryWrapper.in("e.factory_org_code", factoryCode);
            } else {
                return page;
            }
        }
        if (eamMaintenanceStandard != null) {
            //编码 模糊查询
            if (StringUtils.isNotBlank(eamMaintenanceStandard.getStandardCode())) {
                queryWrapper.like("ems.standard_code", eamMaintenanceStandard.getStandardCode());
            }
            //名称 模糊查询
            if (StringUtils.isNotBlank(eamMaintenanceStandard.getStandardName())) {
                queryWrapper.like("ems.standard_name", eamMaintenanceStandard.getStandardName());
            }
            //设备
            if (StringUtils.isNotBlank(eamMaintenanceStandard.getEquipmentId())) {
                queryWrapper.eq("ems.equipment_id", eamMaintenanceStandard.getEquipmentId());
            }
            //保养分类
            if (StringUtils.isNotBlank(eamMaintenanceStandard.getMaintenanceCategory())) {
                queryWrapper.eq("ems.maintenance_category", eamMaintenanceStandard.getMaintenanceCategory());
            }
            //保养分类
            if (StringUtils.isNotBlank(eamMaintenanceStandard.getStandardStatus())) {
                queryWrapper.eq("ems.standard_status", eamMaintenanceStandard.getStandardStatus());
            }
            //设备编码
            if (StringUtils.isNotBlank(eamMaintenanceStandard.getKeyword())) {
                queryWrapper.and(wrapper -> wrapper.like("e.equipment_name", eamMaintenanceStandard.getKeyword())
                        .or()
                        .like("e.equipment_code", eamMaintenanceStandard.getKeyword()));
            }
            //id
            if (StringUtils.isNotBlank(eamMaintenanceStandard.getId())) {
                queryWrapper.eq("ems.id", eamMaintenanceStandard.getId());
            }
        }
        queryWrapper.orderByDesc("ems.create_time");
        return eamMaintenanceStandardMapper.queryPageList(page, queryWrapper);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addMaintenanceStandard(EamMaintenanceStandardRequest standardRequest) {
        EamMaintenanceStandard entity = new EamMaintenanceStandard();
        BeanUtils.copyProperties(standardRequest, entity);
        entity.setStandardStatus(MaintenanceStandardStatusEnum.WAIT_SUBMIT.name());
        //版本递增
        entity.setStandardVersion("v" + CommonConstant.OPERATE_TYPE_1);
        //设备处理
        entity.setEquipmentId(standardRequest.getEquipmentId());
        //删除标记
        entity.setDelFlag(CommonConstant.DEL_FLAG_0);
        //重复性校验
        EamMaintenanceStandard exist = checkDuplicate(entity.getEquipmentId(), entity.getMaintenanceCategory(), MaintenanceStandardStatusEnum.WAIT_SUBMIT.name());
        if (exist != null) {
            throw new JeecgBootException("设备标准已存在,不能重复添加!");
        }
        eamMaintenanceStandardMapper.insert(entity);
        //处理明细数据
        if (CollectionUtil.isNotEmpty(standardRequest.getTableDetailList())) {
            standardRequest.getTableDetailList().forEach(tableDetail -> {
                tableDetail.setStandardId(entity.getId());
            });
            eamMaintenanceStandardDetailService.saveBatch(standardRequest.getTableDetailList());
        }
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editMaintenanceStandard(EamMaintenanceStandardRequest standardRequest) {
        EamMaintenanceStandard entity = eamMaintenanceStandardMapper.selectById(standardRequest.getId());
        if (entity == null) {
            throw new JeecgBootException("编辑的数据已删除,请刷新重试!");
        }
        entity.setStandardName(standardRequest.getStandardName());
        entity.setMaintenancePeriod(standardRequest.getMaintenancePeriod());
        eamMaintenanceStandardMapper.updateById(entity);
        //处理详情
        if(CollectionUtil.isNotEmpty(standardRequest.getTableDetailList())) {
            List<EamMaintenanceStandardDetail> addList = new ArrayList<>();
            //先删除原有
            LambdaQueryWrapper<EamMaintenanceStandardDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(EamMaintenanceStandardDetail::getStandardId, standardRequest.getId());
            eamMaintenanceStandardDetailService.remove(queryWrapper);
            standardRequest.getTableDetailList().forEach(tableDetail -> {
                EamMaintenanceStandardDetail eamMaintenanceStandardDetail=new EamMaintenanceStandardDetail();
                BeanUtils.copyProperties(tableDetail, eamMaintenanceStandardDetail);
                eamMaintenanceStandardDetail.setStandardId(entity.getId());
                addList.add(eamMaintenanceStandardDetail);
            });
            eamMaintenanceStandardDetailService.saveBatch(addList);
        }
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean upgradeMaintenanceStandard(EamMaintenanceStandardRequest standardRequest) {
        EamMaintenanceStandard entity = eamMaintenanceStandardMapper.selectById(standardRequest.getId());
        if (entity == null) {
            throw new JeecgBootException("编辑的数据已删除,请刷新重试!");
        }
 
        //新增一个版本
        EamMaintenanceStandard newEntity = new EamMaintenanceStandard();
        newEntity.setStandardCode(standardRequest.getStandardCode());
        newEntity.setStandardName(standardRequest.getStandardName());
        newEntity.setMaintenanceCategory(standardRequest.getMaintenanceCategory());
        newEntity.setMaintenancePeriod(standardRequest.getMaintenancePeriod());
        newEntity.setInitialDate(standardRequest.getInitialDate());
        newEntity.setPeriodUnit(standardRequest.getPeriodUnit());
        newEntity.setStandardStatus(MaintenanceStandardStatusEnum.WAIT_SUBMIT.name());
        //版本递增
        //获取数字
        Pattern pattern = Pattern.compile("(\\d+)(?:\\.\\d+)*$");
        Matcher matcher = pattern.matcher(entity.getStandardVersion());
        if (matcher.find()) {
            try {
                int mainVersion = Integer.parseInt(matcher.group(1));
                newEntity.setStandardVersion("v" + (mainVersion + 1));
            } catch (NumberFormatException ignored) {
            }
        }
        //设备处理
        newEntity.setEquipmentId(standardRequest.getEquipmentId());
        //删除标记
        newEntity.setDelFlag(CommonConstant.DEL_FLAG_0);
        //重复性校验
        EamMaintenanceStandard exist = checkDuplicate(newEntity.getEquipmentId(), newEntity.getMaintenanceCategory(), MaintenanceStandardStatusEnum.WAIT_SUBMIT.name());
        if (exist != null) {
            throw new JeecgBootException("设备标准已存在,不能重复添加!");
        }
        eamMaintenanceStandardMapper.insert(newEntity);
        //处理明细数据
        if (CollectionUtil.isNotEmpty(standardRequest.getTableDetailList())) {
            standardRequest.getTableDetailList().forEach(tableDetail -> {
                tableDetail.setId(null);
                tableDetail.setCreateBy(null);
                tableDetail.setUpdateBy(null);
                tableDetail.setCreateTime(null);
                tableDetail.setUpdateTime(null);
                tableDetail.setStandardId(newEntity.getId());
            });
            eamMaintenanceStandardDetailService.saveBatch(standardRequest.getTableDetailList());
        }
        return true;
    }
 
    @Override
    public EamMaintenanceStandard checkDuplicate(String equipmentId, String maintenanceCategory, String standardStatus) {
        LambdaQueryWrapper<EamMaintenanceStandard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EamMaintenanceStandard::getEquipmentId, equipmentId);
        queryWrapper.eq(EamMaintenanceStandard::getMaintenanceCategory, maintenanceCategory);
        queryWrapper.eq(EamMaintenanceStandard::getDelFlag, CommonConstant.DEL_FLAG_0);
        queryWrapper.eq(EamMaintenanceStandard::getStandardStatus, standardStatus);
        queryWrapper.orderByDesc(EamMaintenanceStandard::getStandardVersion);
 
        List<EamMaintenanceStandard> list = eamMaintenanceStandardMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }
 
    /**
     * 查询标准列表-前端展示该用户拥有的标准
     *
     * @param keyword             设备编号
     * @param maintenanceCategory 保养类型
     * @return
     */
    @Override
    public List<EamMaintenanceStandard> queryListByKeywordAndCategory(String keyword, String equipmentId, Integer pageSize, String maintenanceCategory) {
        Page<EamMaintenanceStandard> page = new Page<EamMaintenanceStandard>(1, pageSize);
        EamMaintenanceStandard query = new EamMaintenanceStandard();
        query.setEquipmentId(equipmentId);
        query.setKeyword(keyword);
        query.setMaintenanceCategory(maintenanceCategory);
        query.setStandardStatus(MaintenanceStandardStatusEnum.START.name());
        IPage<EamMaintenanceStandard> pageData = this.queryPageList(page, query);
        return pageData.getRecords();
    }
 
    @Override
    public List<EamMaintenanceStandard> queryListByCategory(String maintenanceCategory) {
        LambdaQueryWrapper<EamMaintenanceStandard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EamMaintenanceStandard::getDelFlag, CommonConstant.DEL_FLAG_0);
        queryWrapper.eq(EamMaintenanceStandard::getMaintenanceCategory, maintenanceCategory);
        queryWrapper.eq(EamMaintenanceStandard::getStandardStatus, MaintenanceStandardStatusEnum.START.name());
        return eamMaintenanceStandardMapper.selectList(queryWrapper);
    }
 
 
    /*流程业务代码--------------------------开始*/
 
    /**
     * 流程启动,保存对应的数据
     *
     * @param id
     * @return
     */
    @Override
    public Result<?> saveEamMaintenanceStandardProcess(String id) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        EamMaintenanceStandard maintenanceStandard = this.getById(id);
        if (maintenanceStandard == null) {
            return Result.error("未找到对应保养标准");
        }
        System.out.println("保养规范流程:" + maintenanceStandard.getId());
        flowCommonService.initActBusiness(maintenanceStandard.getStandardName() + "规范进行流程审核",
                maintenanceStandard.getId(), "IEamMaintenanceStandardService", "eam_maintenance_standard", null);
        Map<String, Object> variables = new HashMap<>();
        variables.put("dataId", maintenanceStandard.getId());
        variables.put("organization", "保养规范启动流程");
        variables.put("comment", "保养规范启动流程");
        variables.put("proofreading", true);
        Result result = flowDefinitionService.startProcessInstanceByKey("eam_maintenance_standard", variables);
        if (!result.isSuccess()) {
            super.removeById(maintenanceStandard.getId());
        } else {
            maintenanceStandard.setStandardStatus(MaintenanceStandardStatusEnum.WAIT_REPAIR_DIRECTOR.name());
            maintenanceStandard.setDesigner(user.getUsername());
            maintenanceStandard.setDesignTime(new Date());
            eamMaintenanceStandardMapper.updateById(maintenanceStandard);
            //获取flow的流程实例id,设置下一步的处理人员
            List<FlowMyBusiness> businessList = flowMyBusinessService.list(
                    new QueryWrapper<FlowMyBusiness>()
                            .eq("data_id", maintenanceStandard.getId())
            );
            if (businessList.isEmpty()) {
                return Result.error("流程记录不存在");
            }
            FlowMyBusiness flowMyBusiness = businessList.get(0);
            EamEquipment eamEquipment = eamEquipmentService.getById(maintenanceStandard.getEquipmentId());
            List<UserSelector> userSelectorList = sysUserService.selectOperatorList(eamEquipment.getEquipmentCode(), eamEquipment.getFactoryOrgCode(), BusinessCodeConst.PCR0008);
            if (!CollectionUtils.isEmpty(userSelectorList)) {
                List<String> usernameList = userSelectorList.stream().map(UserSelector::getUsername).collect(Collectors.toList());
                flowMyBusiness.setTodoUsers(JSON.toJSONString(usernameList));
                flowMyBusinessService.updateById(flowMyBusiness);
            }
        }
        return result;
    }
 
    /**
     * 审批操作
     *
     * @param eamMaintenanceStandardVo
     * @return
     */
    @Override
    public Result<?> auditEamMaintenanceStandard(EamMaintenanceStandardVo eamMaintenanceStandardVo) {
        try {
            // 参数校验
            if (StrUtil.isEmpty(eamMaintenanceStandardVo.getTaskId()) || StrUtil.isEmpty(eamMaintenanceStandardVo.getDataId())) {
                return Result.error("参数错误");
            }
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String userId = user.getId();
            eamMaintenanceStandardVo.setAssignee(user.getUsername());
            if (StrUtil.isEmpty(userId)) {
                return Result.error("未找到对应用户");
            }
 
            // 数据查询
            EamMaintenanceStandard eamMaintenanceStandard = this.getById(eamMaintenanceStandardVo.getDataId());
            if (eamMaintenanceStandard == null) {
                return Result.error("未找到对应保养标准");
            }
 
            // 2. 查询流程业务记录(处理空结果)
            List<FlowMyBusiness> businessList = flowMyBusinessService.list(
                    new QueryWrapper<FlowMyBusiness>()
                            .eq("process_instance_id", eamMaintenanceStandardVo.getInstanceId())
            );
            if (businessList.isEmpty()) {
                return Result.error("流程记录不存在");
            }
            FlowMyBusiness flowMyBusiness = businessList.get(0);
 
            // 3. 校验用户是否为候选处理人
            List<String> todoUsers = JSON.parseArray(flowMyBusiness.getTodoUsers(), String.class);
            if (todoUsers == null || !todoUsers.contains(user.getUsername())) {
                return Result.error("用户无权操作此任务");
            }
 
            // 4. 认领任务(处理已被认领的情况)
            String taskId = flowMyBusiness.getTaskId();
            Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
            if (task == null) {
                return Result.error("任务不存在或已完成");
            }
            if (task.getAssignee() != null && !task.getAssignee().equals(user.getUsername())) {
                return Result.error("任务已被他人认领");
            }
            taskService.claim(taskId, user.getUsername());
 
            // 设置流程变量
            Map<String, Object> values = setProcessVariables(eamMaintenanceStandard, userId, eamMaintenanceStandardVo);
            eamMaintenanceStandardVo.setValues(values);
            eamMaintenanceStandardVo.setComment(values.get("comment").toString());
            // 完成流程任务
            Result result = flowTaskService.complete(eamMaintenanceStandardVo);
            if (result.isSuccess()) {
                if (eamMaintenanceStandardVo.getRepairManagerApproveResult() != null) {
                    if (eamMaintenanceStandardVo.getRepairManagerApproveResult().equals("1")) {
                        List<FlowMyBusiness> newbusinessList = flowMyBusinessService.list(
                                new QueryWrapper<FlowMyBusiness>()
                                        .eq("process_instance_id", eamMaintenanceStandardVo.getInstanceId()));
                        FlowMyBusiness newflowMyBusiness = newbusinessList.get(0);
                        eamMaintenanceStandard.setStandardStatus(MaintenanceStandardStatusEnum.WAIT_TECHNICAL_DIRECTOR.name());
                        //获取flow的流程实例id,设置下一步的处理人员
                        EamMaintenanceStandard maintenanceStandard = this.getById(eamMaintenanceStandardVo.getDataId());
                        EamEquipment eamEquipment = eamEquipmentService.getById(maintenanceStandard.getEquipmentId());
                        List<UserSelector> userSelectorList = sysUserService.selectOperatorList(eamEquipment.getEquipmentCode(), eamEquipment.getFactoryOrgCode(), BusinessCodeConst.PCR0009);
                        if (!CollectionUtils.isEmpty(userSelectorList)) {
                            List<String> usernameList = userSelectorList.stream().map(UserSelector::getUsername).collect(Collectors.toList());
                            newflowMyBusiness.setTodoUsers(JSON.toJSONString(usernameList));
                            flowMyBusinessService.updateById(newflowMyBusiness);
                        }
                    } else {
                        eamMaintenanceStandard.setStandardStatus(MaintenanceStandardStatusEnum.WAIT_SUBMIT.name());
                    }
                    eamMaintenanceStandard.setRepairManager(user.getUsername());
                    eamMaintenanceStandard.setRepairManagerApproveResult(eamMaintenanceStandardVo.getRepairManagerApproveResult());
                    eamMaintenanceStandard.setRepairManagerApproveTime(new Date());
                    eamMaintenanceStandard.setRepairManagerApproveComment(eamMaintenanceStandardVo.getComment());
                }
                if (eamMaintenanceStandardVo.getTechnicalManagerApproveResult() != null) {
                    if (eamMaintenanceStandardVo.getTechnicalManagerApproveResult().equals("1")) {
                        eamMaintenanceStandard.setStandardStatus(MaintenanceStandardStatusEnum.START.name());
                        //判断是否进行升版,通过设备编号、保养分类、状态进行筛选
                        EamMaintenanceStandard maintenanceStandard = this.getById(eamMaintenanceStandardVo.getDataId());
                        QueryWrapper<EamMaintenanceStandard> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("equipment_id", maintenanceStandard.getEquipmentId());
                        queryWrapper.eq("maintenance_category", maintenanceStandard.getMaintenanceCategory());
                        queryWrapper.eq("standard_status", MaintenanceStandardStatusEnum.START.name());
                        List<EamMaintenanceStandard> list = eamMaintenanceStandardMapper.selectList(queryWrapper);
                        if (!CollectionUtils.isEmpty(list)) {
                            //作废原有
                            for (EamMaintenanceStandard eamMaintenanceStandard1 : list) {
                                eamMaintenanceStandard1.setStandardStatus(MaintenanceStandardStatusEnum.ABOLISH.name());
                                this.updateById(eamMaintenanceStandard1);
                            }
                        }
                    } else {
                        eamMaintenanceStandard.setStandardStatus(MaintenanceStandardStatusEnum.WAIT_SUBMIT.name());
                    }
                    eamMaintenanceStandard.setTechnicalManager(user.getUsername());
                    eamMaintenanceStandard.setTechnicalManagerApproveResult(eamMaintenanceStandardVo.getTechnicalManagerApproveResult());
                    eamMaintenanceStandard.setTechnicalManagerApproveTime(new Date());
                    eamMaintenanceStandard.setTechnicalManagerApproveComment(eamMaintenanceStandardVo.getComment());
                }
                this.updateById(eamMaintenanceStandard);
            } else {
                return result;
            }
            return Result.OK("操作成功");
        } catch (Exception e) {
            return Result.error("操作失败:" + e.getMessage());
        }
    }
 
    private Map<String, Object> setProcessVariables(EamMaintenanceStandard eamMaintenanceStandard, String userId, EamMaintenanceStandardVo eamMaintenanceStandardVo) {
        Map<String, Object> values = new HashMap<>();
        values.put("dataId", eamMaintenanceStandard.getId());
        values.put("assignee", userId);
        if (eamMaintenanceStandardVo.getRepairManagerApproveResult() != null) {
            values.put("repairManagerApproveResult", eamMaintenanceStandardVo.getRepairManagerApproveResult());
            values.put("organization", eamMaintenanceStandardVo.getRepairManagerApproveComment());
            values.put("comment", eamMaintenanceStandardVo.getRepairManagerApproveComment());
        }
        if (eamMaintenanceStandardVo.getTechnicalManagerApproveResult() != null) {
            values.put("technicalManagerApproveResult", eamMaintenanceStandardVo.getTechnicalManagerApproveResult());
            values.put("organization", eamMaintenanceStandardVo.getTechnicalManagerApproveComment());
            values.put("comment", eamMaintenanceStandardVo.getTechnicalManagerApproveComment());
        }
        return values;
    }
 
 
    @Override
    public void afterFlowHandle(FlowMyBusiness business) {
        business.getTaskNameId();//接下来审批的节点
        business.getValues();//前端传进来的参数
        business.getActStatus();
    }
 
    @Override
    public Object getBusinessDataById(String dataId) {
        return this.getById(dataId);
    }
 
    @Override
    public Map<String, Object> flowValuesOfTask(String taskNameId, Map<String, Object> values) {
        return null;
    }
 
    @Override
    public List<String> flowCandidateUsernamesOfTask(String taskNameId, Map<String, Object> values) {
        //业务是否干预流程,业务干预,流程干预,指定人员进行处理
        return null;
    }
 
    /*流程业务代码--------------------------结束*/
 
 
    /*导入点检文件Excel--------------------------开始*/
 
    /**
     * 点检表导入入口
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> importPointInspectionExcel(MultipartFile file) {
        try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
 
            // 提取名称
            String name = extractInspectionTitle(file) + "点检表";
 
            // 1. 提取设备信息
            EamMaintenanceStandard eamMaintenanceStandard = extractDeviceInfo(sheet);
            if (eamMaintenanceStandard == null || eamMaintenanceStandard.getEquipmentId() == null) {
                return Result.error("设备信息提取失败");
            }
 
            eamMaintenanceStandard.setStandardName(name);
 
            // 检查重复
            EamMaintenanceStandard exist = checkDuplicate(eamMaintenanceStandard.getEquipmentId(),
                    eamMaintenanceStandard.getMaintenanceCategory(), MaintenanceStandardStatusEnum.START.name());
            if (exist != null) {
                return Result.error(name + ": 设备标准已存在,不能重复添加");
            }
 
            eamMaintenanceStandardMapper.insert(eamMaintenanceStandard);
 
            Map<Integer, String> rowErrors = new HashMap<>();
 
            // 2. 提取每日点检项目(优化空行和结束标记处理)
            List<EamMaintenanceStandardDetail> dailyDetails = extractDailyItems(sheet, eamMaintenanceStandard, rowErrors);
            if (dailyDetails.isEmpty()) {
                return Result.error("未找到每日点检项目");
            }
 
            // 3. 提取周保养项目
            List<EamMaintenanceStandardDetail> weeklyDetails = extractWeeklyItems(sheet, eamMaintenanceStandard, rowErrors);
            if (weeklyDetails.isEmpty()) {
                return Result.error("未找到周保养项目");
            }
 
            // 合并并保存所有项目
            List<EamMaintenanceStandardDetail> allDetails = new ArrayList<>();
            allDetails.addAll(dailyDetails);
            allDetails.addAll(weeklyDetails);
 
            if (!CollectionUtils.isEmpty(allDetails)) {
                eamMaintenanceStandardDetailService.saveBatch(allDetails);
            }
 
            // 触发保养流程
            SysParams sysParams = sysParamsService.getSysPramBySettingKey("maintenance_import_type");
            if (sysParams != null) {
                if (sysParams.getSettingValue().equals("1")){
                    eamMaintenanceStandard.setStandardStatus(MaintenanceStandardStatusEnum.WAIT_SUBMIT.name());
                    eamMaintenanceStandardMapper.updateById(eamMaintenanceStandard);
                }
            } else {
                return Result.error("未找到保养流程导入相关配置,请联系管理员");
            }
 
            return Result.OK("点检表导入成功");
 
        } catch (Exception e) {
            throw new BusinessException("点检表导入失败: " + e.getMessage());
        }
    }
 
    /**
     * 提取点检表标题
     */
    private String extractInspectionTitle(MultipartFile file) {
        try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            Row firstRow = sheet.getRow(0);
 
            if (firstRow == null) {
                return "未找到标题";
            }
 
            Cell firstCell = firstRow.getCell(0);
            if (firstCell == null) {
                return "";
            }
 
            String title = getCellStringValue(firstCell);
            return extractTextBeforeInspection(title);
 
        } catch (Exception e) {
            return "";
        }
    }
 
    /**
     * 提取点检表之前的文字
     */
    private String extractTextBeforeInspection(String title) {
        if (StringUtils.isBlank(title)) {
            return "";
        }
 
        int index = title.indexOf("点检表");
        return index > 0 ? title.substring(0, index).trim() : title;
    }
 
    /**
     * 提取设备信息
     */
    private EamMaintenanceStandard extractDeviceInfo(Sheet sheet) {
        Row headerRow = sheet.getRow(0);
        if (headerRow == null) {
            return null;
        }
 
        String headerText = getCellStringValue(headerRow.getCell(0));
        if (StringUtils.isBlank(headerText)) {
            return null;
        }
 
        EamMaintenanceStandard standard = new EamMaintenanceStandard();
        standard.setEquipmentName(extractField(headerText, "设备名称[::]\\s*(\\S+)"));
        standard.setEquipmentCode(extractField(headerText, "统一编号[::]\\s*(\\S+)"));
 
 
        // 日期处理
        String dateStr = extractField(headerText, "日期[::]\\s*(\\S+)");
        if (StringUtils.isNotBlank(dateStr)) {
            try {
                // 支持多种日期格式
                Date date = parseDate(dateStr);
                standard.setDesignTime(date);
                standard.setInitialDate(date);
            } catch (ParseException ignored) {
 
            }
        }
 
        // 关联设备ID
        if (StrUtil.isNotEmpty(standard.getEquipmentCode())) {
            EamEquipment equipments = eamEquipmentService.selectByEquipmentCode(standard.getEquipmentCode());
            if (equipments == null) {
                return null;
            } else {
                standard.setEquipmentId(equipments.getId());
            }
        }
        String codeSeq = businessCodeRuleService.generateBusinessCodeSeq(BusinessCodeConst.MAINTENANCE_STANDARD_CODE_RULE);
        standard.setStandardCode(codeSeq);
        standard.setMaintenanceCategory("POINT_INSPECTION");
        standard.setPeriodUnit("天");
        standard.setStandardStatus(MaintenanceStandardStatusEnum.START.name());
        standard.setStandardVersion("v" + CommonConstant.OPERATE_TYPE_1);
        standard.setDelFlag(0);
        standard.setMaintenancePeriod(1);
 
        return standard;
    }
 
    /**
     * 解析日期字符串
     */
    private Date parseDate(String dateStr) throws ParseException {
        // 尝试多种日期格式
        String[] patterns = {
                "yyyy年MM月",
                "yyyy-MM",
                "yyyy/MM",
                "yyyyMM",
                "yyyy年M月"
        };
 
        for (String pattern : patterns) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                sdf.setLenient(false);
                return sdf.parse(dateStr);
            } catch (ParseException e) {
                // 尝试下一个格式
            }
        }
 
        throw new ParseException("无法解析日期: " + dateStr, 0);
    }
 
    /**
     * 使用正则提取字段
     */
    private String extractField(String text, String regex) {
        if (StringUtils.isBlank(text)) return "";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);
        return matcher.find() ? matcher.group(1) : "";
    }
 
    /**
            * 提取每日点检项目
     */
    private List<EamMaintenanceStandardDetail> extractDailyItems(Sheet sheet, EamMaintenanceStandard standard, Map<Integer, String> rowErrors) {
        // 使用多关键词匹配
        String[] primaryHeaders = {"点检项目", "日常点检", "每日检查"};
        String[] secondaryHeaders = {"完成数据/要求", "检查标准", "要求"};
        return extractItems(sheet, standard, primaryHeaders, secondaryHeaders, "DAY_INSPECTION", rowErrors);
    }
 
    /**
            * 提取周保养项目
     */
    private List<EamMaintenanceStandardDetail> extractWeeklyItems(Sheet sheet, EamMaintenanceStandard standard, Map<Integer, String> rowErrors) {
        // 使用多关键词匹配
        String[] primaryHeaders = {"周保养项目", "周保养", "每周保养"};
        String[] secondaryHeaders = {"检查标准", "保养要求", "标准"};
        return extractItems(sheet, standard, primaryHeaders, secondaryHeaders, "WEEK_INSPECTION", rowErrors);
    }
 
    /**
     * 核心改进:优化表格区域识别和数据提取
    */
    private List<EamMaintenanceStandardDetail> extractItems(Sheet sheet,
                                                            EamMaintenanceStandard standard,
                                                            String[] primaryHeaders,
                                                            String[] secondaryHeaders,
                                                            String itemCategory,
                                                            Map<Integer, String> rowErrors) {
 
        // 1. 定位表格区域(精确匹配表头)
        int startRow = findHeaderRow(sheet, primaryHeaders, secondaryHeaders);
        if (startRow == -1) {
            rowErrors.put(-1, "未找到" + Arrays.toString(primaryHeaders) + "表头区域");
            return Collections.emptyList();
        }
 
        int endRow = findDataEnd(sheet, startRow + 1, "周保养项目");
 
        // 提取日志(实际使用时可以去掉)
        System.out.println("提取区域: " + (startRow + 1) + "行到" + (endRow + 1) + "行");
 
        // 2. 提取数据行
        List<EamMaintenanceStandardDetail> details = new ArrayList<>();
        for (int rowIdx = startRow + 1; rowIdx <= endRow; rowIdx++) {
            Row row = sheet.getRow(rowIdx);
            if (row == null) continue;
 
            try {
                // 序号列处理
                Cell seqCell = row.getCell(0);
                if (seqCell == null || seqCell.getCellType() == CellType.BLANK) {
                    continue;
                }
 
                // 获取序号值(支持数字和文本格式)
                int seqValue = 0;
                try {
                    if (seqCell.getCellType() == CellType.NUMERIC) {
                        seqValue = (int) seqCell.getNumericCellValue();
                    } else if (seqCell.getCellType() == CellType.STRING) {
                        seqValue = Integer.parseInt(seqCell.getStringCellValue().trim());
                    }
                } catch (NumberFormatException e) {
                    rowErrors.put(rowIdx + 1, "序号格式错误");
                    continue;
                }
 
                // 项目名称列(第二列)
                Cell nameCell = row.getCell(1);
                if (nameCell == null || nameCell.getCellType() == CellType.BLANK) {
                    continue;
                }
                String itemName = getCellStringValue(nameCell).trim();
 
                // 要求/标准列(第三列)
                String demand = "";
                if (row.getLastCellNum() >= 3) {
                    Cell demandCell = row.getCell(2);
                    if (demandCell != null) {
                        demand = getCellStringValue(demandCell).trim();
                    }
                }
 
                // 创建详情对象
                EamMaintenanceStandardDetail detail = new EamMaintenanceStandardDetail();
                detail.setStandardId(standard.getId());
                detail.setItemCode(seqValue);
                detail.setItemName(itemName);
                detail.setItemDemand(demand);
                detail.setItemCategory(itemCategory);
                details.add(detail);
 
            } catch (Exception e) {
                rowErrors.put(rowIdx + 1, "解析错误: " + e.getMessage());
            }
        }
        return details;
    }
 
    /**
     * 获取行中所有单元格的字符串值
     */
    private List<String> getRowStringValues(Row row) {
        List<String> values = new ArrayList<>();
        if (row == null) return values;
 
        for (int cellIdx = 0; cellIdx < row.getLastCellNum(); cellIdx++) {
            Cell cell = row.getCell(cellIdx);
            if (cell != null) {
                values.add(getCellStringValue(cell));
            } else {
                values.add(""); // 对于空单元格添加空字符串
            }
        }
        return values;
    }
 
    /**
     * 获取单元格字符串值(增强公式处理)
     */
    private String getCellStringValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        // 保持不变,但添加数字类型处理
        if (cell.getCellType() == CellType.NUMERIC) {
            // 整数处理
            double num = cell.getNumericCellValue();
            if (num == (int) num) {
                return String.valueOf((int) num);
            }
            return String.valueOf(num);
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return new SimpleDateFormat("yyyy年MM月").format(cell.getDateCellValue());
                }
                return String.valueOf((int) cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return getFormulaCellValue(cell);
            default:
                return "";
        }
    }
 
    /**
     * 精确查找表头行
    */
    private int findHeaderRow(Sheet sheet, String[] primaryHeaders, String[] secondaryHeaders) {
        for (int rowIdx = 0; rowIdx <= sheet.getLastRowNum(); rowIdx++) {
            Row row = sheet.getRow(rowIdx);
            if (row == null) continue;
 
            String rowText = getRowStringValues(row).stream().collect(Collectors.joining());
 
            // 检查主标题和副标题
            boolean hasPrimary = false;
            boolean hasSecondary = false;
 
            for (String header : primaryHeaders) {
                if (rowText.contains(header)) {
                    hasPrimary = true;
                    break;
                }
            }
 
            for (String header : secondaryHeaders) {
                if (rowText.contains(header)) {
                    hasSecondary = true;
                    break;
                }
            }
 
            if (hasPrimary && hasSecondary) {
                return rowIdx;
            }
        }
        return -1;
    }
 
    /**
     * 查找数据结束位置(根据您的Excel结构优化)
     */
    private int findDataEnd(Sheet sheet, int startRow, String nextSectionKeyword) {
        int consecutiveEmptyRows = 0;
        final int MAX_EMPTY_ROWS = 3;
 
        for (int rowIdx = startRow; rowIdx <= sheet.getLastRowNum(); rowIdx++) {
            Row row = sheet.getRow(rowIdx);
 
            // 关键改进1:空行处理
            if (isEssentiallyEmpty(row)) {
                consecutiveEmptyRows++;
                if (consecutiveEmptyRows >= MAX_EMPTY_ROWS) {
                    return rowIdx - consecutiveEmptyRows;
                }
                continue;
            } else {
                consecutiveEmptyRows = 0;
            }
 
            // 关键改进2:结束标记检测
            String rowText = getRowStringValues(row).stream().collect(Collectors.joining());
 
            // 根据您的Excel结构,签字行有特定格式
            if (rowText.contains("维护责任人签字")) {
                return rowIdx - 1;
            }
 
            // 检测下一个区域的开始(如周保养项目)
            if (StringUtils.isNotBlank(nextSectionKeyword) &&
                    rowText.contains(nextSectionKeyword)) {
                return rowIdx - 1;
            }
        }
        return sheet.getLastRowNum();
    }
 
    /**
     * 判断条件:前两列为空即视为空行
     */
    private boolean isEssentiallyEmpty(Row row) {
        if (row == null) return true;
 
        // 检查序号列
        Cell indexCell = row.getCell(0);
        if (indexCell != null && indexCell.getCellType() != CellType.BLANK) {
            return false;
        }
 
        // 检查项目名称列
        Cell nameCell = row.getCell(1);
        if (nameCell != null && nameCell.getCellType() != CellType.BLANK) {
            return false;
        }
 
        return true;
    }
 
    /**
            * 获取公式单元格值
     */
    private String getFormulaCellValue(Cell cell) {
        try {
            Workbook workbook = cell.getSheet().getWorkbook();
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            CellValue cellValue = evaluator.evaluate(cell);
            if (cellValue == null) {
                return "";
            }
            switch (cellValue.getCellType()) {
                case STRING:
                    return cellValue.getStringValue();
                case NUMERIC:
                    return String.valueOf((int) cellValue.getNumberValue());
                case BOOLEAN:
                    return String.valueOf(cellValue.getBooleanValue());
                default:
                    return "";
            }
        } catch (Exception e) {
            log.warn("解析公式单元格失败");
            return "";
        }
    }
 
 
    private int findDataEnd(Sheet sheet, int startRow) {
        int consecutiveEmptyRows = 0;
        final int MAX_EMPTY_ROWS = 2;
        boolean foundData = false;
 
        for (int rowIdx = startRow; rowIdx <= sheet.getLastRowNum(); rowIdx++) {
            Row row = sheet.getRow(rowIdx);
 
            // 关键优化1:先检查是否为空行
            if (isEmptyRow(row)) {
                consecutiveEmptyRows++;
                if (consecutiveEmptyRows >= MAX_EMPTY_ROWS) {
                    return foundData ? rowIdx - consecutiveEmptyRows : startRow;
                }
                continue;
            } else {
                consecutiveEmptyRows = 0;
            }
 
            // 关键优化2:严格限定结束标记的识别条件
            if (isStrongEndMarker(row)) {
                return foundData ? rowIdx - 1 : startRow;
            }
 
            // 关键优化3:标记已找到有效数据
            foundData = true;
        }
        return sheet.getLastRowNum();
    }
 
    // 增强版结束标记识别
    private boolean isStrongEndMarker(Row row) {
        String rowText = String.join("", getRowStringValues(row)).toLowerCase();
 
        return
                // 精确匹配签字特征(出现在行首)
                (rowText.startsWith("维护责任人签字") ||
                        rowText.startsWith("执行人签字")) ||
                        // 精确匹配新板块标题
                        rowText.matches("^\\s*周保养项目\\s*$") ||
                        rowText.contains("年度保养项目");
    }
 
    // 空行检测优化(允许部分列为空)
    private boolean isEmptyRow(Row row) {
        if (row == null) return true;
        // 只检查前3列(序号列+项目名+要求)
        for (int cellIdx = 0; cellIdx < Math.min(3, row.getLastCellNum()); cellIdx++) {
            Cell cell = row.getCell(cellIdx);
            if (cell != null && cell.getCellType() != CellType.BLANK) {
                return false;
            }
        }
        return true;
    }
    /*导入点检文件Excel--------------------------结束*/
 
    /*导入二保三保文件Excel--------------------------开始*/
 
    /**
     * 统一保养规范导入入口
     *
     * @param file 上传文件
     * @param type 保养类型 (SECOND/THIRD)
     * @return 导入结果(包含成功/失败信息)
     */
    @Override
    @Transactional
    public Result<?> importMaintenanceStandard(MultipartFile file, String type) {
        String fileName = file.getOriginalFilename();
 
        try (XWPFDocument doc = new XWPFDocument(file.getInputStream())) {
            // 基础验证
            if (doc.getTables().isEmpty()) {
                return Result.error(fileName + ": 文档中未找到表格");
            }
 
            List<XWPFTable> tables = doc.getTables();
            EamMaintenanceStandard standard = null;
            List<EamMaintenanceStandardDetail> items = new ArrayList<>();
            String standardId = null;
 
            // 1. 处理所有表格
            for (int i = 0; i < tables.size(); i++) {
                XWPFTable table = tables.get(i);
 
                if (i == 0) { // 第一页表格
                    // 验证设备信息表格
                    if (isWrongDocumentType(table, type)) {
                        return Result.error(fileName + ": 文档类型不匹配 - " +
                                ("SECOND".equals(type) ? "请导入二级保养文档" : "请导入三级保养文档"));
                    }
 
                    // 提取设备信息
                    standard = extractDeviceInfo(table, type);
                    if (standard == null) {
                        return Result.error(fileName + ": 设备信息提取失败");
                    }
 
                    // 配置类型相关参数
                    configureStandard(standard, type, file);
                    EamMaintenanceStandard exist = checkDuplicate(standard.getEquipmentId(), standard.getMaintenanceCategory(), MaintenanceStandardStatusEnum.START.name());
                    if (exist != null) {
                        return Result.error(fileName + ": 设备标准已存在,不能重复添加");
                    }
                    eamMaintenanceStandardMapper.insert(standard);
                    standardId = standard.getId();
 
                    // 提取第一页的保养项目
                    if ("SECOND".equals(type)) {
                        items.addAll(extractSecondMaintenanceItems(table, standardId, true));
                    } else if ("THIRD".equals(type)) {
                        items.addAll(extractThirdMaintenanceItems(table, standardId, true));
                    }
 
                } else { // 后续页面
                    // 提取后续页面的保养项目
                    if ("SECOND".equals(type)) {
                        items.addAll(extractSecondMaintenanceItems(table, standardId, false));
                    } else if ("THIRD".equals(type)) {
                        items.addAll(extractThirdMaintenanceItems(table, standardId, false));
                    }
                }
            }
 
            // 验证设备信息提取
            if (standard == null) {
                return Result.error(fileName + ": 设备信息提取失败");
            }
 
            // 2. 后处理:根据不同类型进行处理
            processItemsAfterExtraction(items, type);
 
            // 3. 项目验证
            if (items.isEmpty()) {
                return Result.error(fileName + ": 未提取到任何保养项目");
            }
 
            // 4. 保存项目
            eamMaintenanceStandardDetailService.saveBatch(items);
 
 
            SysParams sysParams = sysParamsService.getSysPramBySettingKey("maintenance_import_type");
 
            if (sysParams != null) {
                if (sysParams.getSettingValue().equals("1")) {
                    standard.setStandardStatus(MaintenanceStandardStatusEnum.WAIT_SUBMIT.name());
                    eamMaintenanceStandardMapper.updateById(standard);
                }
            } else {
                return Result.error("未找到保养流程导入相关配置,请联系管理员");
            }
 
            return Result.ok(fileName + ": 导入成功, 项目数: " + items.size());
 
        } catch (ImportException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error(fileName + ": 系统错误 - " + e.getClass().getSimpleName());
        }
    }
 
    /**
     * 后处理方法:根据不同类型进行处理
     */
    private void processItemsAfterExtraction(List<EamMaintenanceStandardDetail> items, String type) {
        if ("SECOND".equals(type)) {
            // 二级保养: 删除没有序号的数据
            items.removeIf(item -> item.getItemCode() == null);
        } else {
            // 三级保养:
            // 1. 删除第一条数据(通常是标题行)
            if (!items.isEmpty()) {
                items.remove(0);
            }
            // 2. 为缺失部位的数据填充前一条的保养部位
            String lastPart = "";
            int i = 1;
            for (EamMaintenanceStandardDetail item : items) {
                item.setItemCode(i);
                if (item.getItemPart() != null && !item.getItemPart().isEmpty()) {
                    lastPart = item.getItemPart();
                } else if (!lastPart.isEmpty()) {
                    item.setItemPart(lastPart);
                }
                i++;
            }
        }
    }
 
    /**
     * 提取二级保养项目(区分第一页和后续页面)
     */
    private List<EamMaintenanceStandardDetail> extractSecondMaintenanceItems(
            XWPFTable table, String standardId, boolean isFirstTable) {
 
        List<EamMaintenanceStandardDetail> items = new ArrayList<>();
        String currentCategory = null;
        int startRow = 0;
 
        // 对于第一页表格,跳过前两行(设备信息行)
        if (isFirstTable && table.getNumberOfRows() > 2) {
            startRow = 2; // 从第三行开始是保养内容
        }
 
        for (int i = startRow; i < table.getNumberOfRows(); i++) {
            XWPFTableRow row = table.getRow(i);
            if (row == null) continue;
 
            // 检查是否是标题行(维修人员保养内容或操作人员保养内容)
            String firstCell = getCellText(row.getCell(0));
            // 处理空行后的部位继承
            if (firstCell.contains(REPAIR_TITLE)) {
                currentCategory = "REPAIRER_MAINTENANCE";
            } else if (firstCell.contains(OPERATOR_TITLE)) {
                currentCategory = "OPERATOR_MAINTENANCE";
            }
 
            // 处理普通项目行
            if (currentCategory != null && isValidItemRow(row)) {
                EamMaintenanceStandardDetail item = new EamMaintenanceStandardDetail();
                item.setItemCategory(currentCategory);
                item.setStandardId(standardId);
 
                // 提取序号(第二列)
                if (row.getTableCells().size() > 1) {
                    String seqText = getCellText(row.getCell(1));
                    try {
                        if (!seqText.equals("序号")) {
                            item.setItemCode(Integer.parseInt(seqText.trim()));
                        }
                    } catch (NumberFormatException e) {
                        // 忽略序号解析错误
                    }
                }
 
                // 提取内容(第三列)
                if (row.getTableCells().size() > 2) {
                    String seqText = getCellText(row.getCell(2));
                    item.setItemName(seqText);
                }
 
                items.add(item);
            }
        }
        return items;
    }
 
    /**
     * 提取三级保养项目(解决跨页空行问题)
     */
    private List<EamMaintenanceStandardDetail> extractThirdMaintenanceItems(
            XWPFTable table, String standardId, boolean isFirstTable) {
 
        List<EamMaintenanceStandardDetail> items = new ArrayList<>();
        String currentPart = "";
        int startRow = 0;
 
        // 对于第一页表格,跳过前两行(设备信息行)
        if (isFirstTable && table.getNumberOfRows() > 2) {
            startRow = 2; // 从第三行开始是保养内容
        }
 
        for (int i = startRow; i < table.getNumberOfRows(); i++) {
            XWPFTableRow row = table.getRow(i);
            if (row == null) continue;  // 确保行对象不为空
 
            // 检查是否是空行(包含所有单元格都为空的情况)
            if (isRowEmpty(row)) {
                // 空行处理:保留当前位置但不创建项目
                continue;
            }
 
            // 创建保养项目
            EamMaintenanceStandardDetail item = new EamMaintenanceStandardDetail();
            item.setStandardId(standardId);
            int colCount = row.getTableCells().size();
 
            // 处理部位列(第一列)
            if (colCount > 0) {
                String firstCell = getCellText(row.getCell(0)).trim();
 
                // 关键改进:正确处理空行后的部位继承
                if (!firstCell.isEmpty() && !firstCell.equals("保养部位")) {
                    // 更新当前部位
                    currentPart = firstCell;
                }
                item.setItemPart(currentPart);
            } else {
                // 如果没有单元格,使用当前部位
                item.setItemPart(currentPart);
            }
 
            // 根据列数提取内容(考虑合并单元格情况)
            List<String> cellContents = new ArrayList<>();
            for (int j = 0; j < colCount; j++) {
                XWPFTableCell cell = row.getCell(j);
                String text = getCellText(cell).trim();
 
                // 特殊处理:第二页第一行可能是空行后的内容
                if (j == 0 && !text.isEmpty() && !text.equals(currentPart)) {
                    // 如果不是部位列,则添加为内容
                    cellContents.add(text);
                } else if (j > 0) {
                    // 其他列作为内容
                    cellContents.add(text);
                }
            }
 
            // 智能解析单元格内容
            if (cellContents.size() >= 2) {
                // 默认处理方式:最后两个作为内容和标准
                item.setItemName(cellContents.get(cellContents.size() - 2));
                item.setItemDemand(cellContents.get(cellContents.size() - 1));
            } else if (cellContents.size() == 1) {
                // 单列模式:视为内容
                item.setItemName(cellContents.get(0));
            } else if (!isRowEmpty(row)) {
                // 特殊处理:行非空但没有提取到内容(可能是复杂合并单元格)
                // 尝试提取整行文本作为内容
                StringBuilder content = new StringBuilder();
                for (XWPFTableCell cell : row.getTableCells()) {
                    content.append(getCellText(cell).trim()).append(" ");
                }
                item.setItemName(content.toString().trim());
            }
 
            items.add(item);
        }
        return items;
    }
 
    /**
     * 优化后的空行检测(解决跨页空行问题)
     */
    private boolean isRowEmpty(XWPFTableRow row) {
        if (row == null || row.getTableCells().isEmpty()) {
            return true;
        }
 
        boolean allCellsEmpty = true;
        for (XWPFTableCell cell : row.getTableCells()) {
            String text = getCellText(cell).trim();
            // 保留包含换行符等的单元格作为非空行
            if (!text.isEmpty() && !text.replaceAll("\\s+", "").isEmpty()) {
                allCellsEmpty = false;
                break;
            }
        }
        return allCellsEmpty;
    }
 
    /**
     * 文档类型校验 - 防止二保传入三保或反之
     */
    private boolean isWrongDocumentType(XWPFTable table, String requestedType) {
        boolean hasRepairTitle = false;
        boolean hasOperatorTitle = false;
        boolean hasMaintenancePart = false;
 
        // 只检查前10行(通常标题在前几行)
        int maxRows = Math.min(table.getNumberOfRows(), 10);
 
        for (int i = 0; i < maxRows; i++) {
            XWPFTableRow row = table.getRow(i);
            if (row == null) continue;
 
            // 检查所有单元格内容
            for (int j = 0; j < row.getTableCells().size(); j++) {
                String cellText = getCellText(row.getCell(j));
 
                // 检查二级保养特征
                if (cellText.contains(REPAIR_TITLE)) {
                    hasRepairTitle = true;
                }
                if (cellText.contains(OPERATOR_TITLE)) {
                    hasOperatorTitle = true;
                }
 
                // 检查三级保养特征
                if (cellText.contains("保养部位")) {
                    hasMaintenancePart = true;
                }
            }
        }
 
        // 逻辑判断
        if ("SECOND".equals(requestedType)) {
            // 如果请求导入二级保养,但文档中有三级保养特征
            return !(hasRepairTitle || hasOperatorTitle) || hasMaintenancePart;
        } else if ("THIRD".equals(requestedType)) {
            // 如果请求导入三级保养,但文档中有二级保养特征
            return !hasMaintenancePart || (hasRepairTitle || hasOperatorTitle);
        }
 
        return false;
    }
 
    /**
     * 提取设备基本信息
     */
    private EamMaintenanceStandard extractDeviceInfo(XWPFTable table, String type) {
        if (table.getNumberOfRows() < 2) return null;
 
        // 提取前两行数据
        Map<String, String> row1Data = extractRowData(table.getRow(0));
        Map<String, String> row2Data = extractRowData(table.getRow(1));
 
        // 创建设备标准对象
        EamMaintenanceStandard standard = new EamMaintenanceStandard();
        standard.setEquipmentText(row1Data.get("设备类别"));
        standard.setEquipmentCode(row1Data.get("设备编号"));
        standard.setEquipmentName(row2Data.get("设备名称"));
        standard.setEquipmentModel(row2Data.get("设备型号"));
 
        // 关联设备ID
        if (StrUtil.isNotEmpty(standard.getEquipmentCode())) {
            EamEquipment equipments = eamEquipmentService.selectByEquipmentCode(standard.getEquipmentCode());
            if (equipments == null) {
                return null;
            } else {
                standard.setEquipmentId(equipments.getId());
            }
            if (type.equals("THIRD")) {
                EamEquipmentExtend eamEquipmentExtend = eamEquipmentExtendService.getById(standard.getEquipmentId());
                standard.setMaintenancePeriod(eamEquipmentExtend.getThirdMaintenancePeriod());
            }
        }
 
        return standard;
    }
 
 
    /**
     * 表格行数据解析
     */
    private Map<String, String> extractRowData(XWPFTableRow row) {
        Map<String, String> data = new HashMap<>();
        int cellCount = row.getTableCells().size();
 
        try {
            // 键值对模式 (标签|值|标签|值)
            if (cellCount >= 4 && cellCount % 2 == 0) {
                for (int i = 0; i < cellCount; i += 2) {
                    String key = cleanKey(getCellText(row.getCell(i)));
                    String value = getCellText(row.getCell(i + 1));
                    if (!key.isEmpty()) data.put(key, value);
                }
            }
            // 连续单元格模式
            else {
                for (int i = 0; i < cellCount; i++) {
                    String text = getCellText(row.getCell(i));
                    int colonIndex = text.indexOf(':');
                    if (colonIndex > 0) {
                        String key = cleanKey(text.substring(0, colonIndex));
                        String value = text.substring(colonIndex + 1);
                        data.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
            log.error("行数据解析异常", e);
        }
        return data;
    }
 
    /**
     * 键名标准化处理
     */
    private String cleanKey(String key) {
        if (key == null) return "";
        // 移除空格和中文冒号
        return key.replaceAll("\\s", "").replace(":", "");
    }
 
    /**
     * 配置保养标准参数
     */
    private void configureStandard(EamMaintenanceStandard standard, String type, MultipartFile file) {
        // 基础参数
        String filename = file.getOriginalFilename();
        if (filename != null && filename.contains(".")) {
            filename = filename.substring(0, filename.lastIndexOf('.'));
        }
 
        standard.setStandardName(filename)
                .setInitialDate(new Date())
                .setStandardStatus(MaintenanceStandardStatusEnum.START.name())
                .setStandardVersion("v" + CommonConstant.OPERATE_TYPE_1)
                .setDelFlag(0)
                .setStandardCode(businessCodeRuleService.generateBusinessCodeSeq(
                        BusinessCodeConst.MAINTENANCE_STANDARD_CODE_RULE
                ));
 
        // 类型特定参数
        if ("SECOND".equals(type)) {
            standard.setMaintenanceCategory("SECOND_MAINTENANCE")
                    .setMaintenancePeriod(6)
                    .setPeriodUnit("月");
        } else {
            standard.setMaintenanceCategory("THIRD_MAINTENANCE")
                    .setPeriodUnit("年");
 
            // 获取三级保养周期
            if (standard.getEquipmentId() != null) {
                EamEquipmentExtend extend = eamEquipmentExtendService.getById(standard.getEquipmentId());
                if (extend != null) {
                    standard.setMaintenancePeriod(extend.getThirdMaintenancePeriod());
                }
            }
        }
    }
 
    /**
     * 兼容版单元格文本提取
     */
    private String getCellText(XWPFTableCell cell) {
        if (cell == null) return "";
 
        StringBuilder text = new StringBuilder();
        for (XWPFParagraph para : cell.getParagraphs()) {
            if (para != null) {
                for (XWPFRun run : para.getRuns()) {
                    if (run != null) {
                        String runText = run.getText(0);
                        if (runText != null) {
                            text.append(runText);
                        }
                    }
                }
            }
        }
        return text.toString();
    }
 
    /**
     * 验证有效项目行
     */
    private boolean isValidItemRow(XWPFTableRow row) {
        return row != null &&
                row.getTableCells().size() >= 2 &&
                !getCellText(row.getCell(1)).trim().isEmpty();
    }
 
    /*导入二保三保文件Excel--------------------------结束*/
 
}