lyh
2 天以前 d61b21c50e62298f185ecafa8e0b22f7ee8c4973
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
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 liquibase.pro.packaged.Q;
import org.apache.commons.lang3.StringUtils;
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.constant.DataBaseConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.eam.aspect.annotation.EquipmentHistoryLog;
import org.jeecg.modules.eam.constant.*;
import org.jeecg.modules.eam.dto.EamSecondMaintenanceOrderExport;
import org.jeecg.modules.eam.entity.*;
import org.jeecg.modules.eam.mapper.EamEquipmentMapper;
import org.jeecg.modules.eam.mapper.EamMaintenanceStandardMapper;
import org.jeecg.modules.eam.mapper.EamSecondMaintenanceOrderMapper;
import org.jeecg.modules.eam.request.EamSecondMaintenanceQuery;
import org.jeecg.modules.eam.request.EamSecondMaintenanceRequest;
import org.jeecg.modules.eam.service.*;
import org.jeecg.modules.eam.tree.FindsEquipmentEamCenterUtil;
import org.jeecg.modules.eam.vo.EamEquipmentTree;
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.mapper.BaseFactoryMapper;
import org.jeecg.modules.system.service.IBaseFactoryService;
import org.jeecg.modules.system.service.IBaseFactoryUserService;
import org.jeecg.modules.system.service.ISysUserService;
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 javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
 
/**
 * @Description: 设备二级保养
 * @Author: jeecg-boot
 * @Date:   2025-04-29
 * @Version: V1.0
 */
@Service("IEamSecondMaintenanceOrderService")
public class EamSecondMaintenanceOrderServiceImpl extends ServiceImpl<EamSecondMaintenanceOrderMapper, EamSecondMaintenanceOrder> implements IEamSecondMaintenanceOrderService, FlowCallBackServiceI {
    @Resource
    private EamSecondMaintenanceOrderMapper eamSecondMaintenanceOrderMapper;
    @Autowired
    private IEamSecondMaintenanceOrderDetailService secondMaintenanceOrderDetailService;
 
    @Autowired
    private FlowCommonService flowCommonService;
    @Autowired
    private IFlowDefinitionService flowDefinitionService;
    @Autowired
    private IFlowMyBusinessService flowMyBusinessService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IFlowTaskService flowTaskService;
    @Autowired
    private IBaseFactoryUserService baseFactoryUserService;
    @Autowired
    private IBaseFactoryService baseFactoryService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IEamEquipmentService eamEquipmentService;
    @Autowired
    private IEamEquipmentExtendService eamEquipmentExtendService;
    @Autowired
    private IEamBaseHFCodeService hfCodeService;
    @Autowired
    private IEamMaintenanceStandardDetailService eamMaintenanceStandardDetailService;
    @Autowired
    private EamMaintenanceStandardMapper eamMaintenanceStandardMapper;
    @Resource
    private BaseFactoryMapper baseFactoryMapper;
    @Autowired
    private IEamSecondMaintenanceOrderDetailService eamSecondMaintenanceOrderDetailService;
 
    @Override
    public IPage<EamSecondMaintenanceOrder> queryPageList(Page<EamSecondMaintenanceOrder> page, EamSecondMaintenanceQuery query) {
        QueryWrapper<EamSecondMaintenanceOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wmo.del_flag",CommonConstant.DEL_FLAG_0.toString());
        //用户数据权限
        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 (query != null) {
            if (StringUtils.isNotBlank(query.getId())){
                queryWrapper.eq("wmo.id", query.getId());
            }
            if (StringUtils.isNotBlank(query.getEquipmentId())) {
                queryWrapper.eq("wmo.equipment_id", query.getEquipmentId());
            }
            if (StringUtils.isNotBlank(query.getOrderNum())) {
                queryWrapper.like("wmo.order_num", query.getOrderNum());
            }
            if (StringUtils.isNotBlank(query.getMaintenanceStatus())) {
                queryWrapper.eq("wmo.maintenance_status", query.getMaintenanceStatus());
            }
            if (query.getMaintenanceDateBegin() != null && query.getMaintenanceDateEnd() != null) {
                queryWrapper.between("wmo.maintenance_date", query.getMaintenanceDateBegin(), query.getMaintenanceDateEnd());
            }
            //排序
            if (StringUtils.isNotBlank(query.getColumn()) && StringUtils.isNotBlank(query.getOrder())) {
                String column = query.getColumn();
                if (column.endsWith(CommonConstant.DICT_TEXT_SUFFIX)) {
                    column = column.substring(0, column.lastIndexOf(CommonConstant.DICT_TEXT_SUFFIX));
                }
                if (DataBaseConstant.SQL_ASC.equalsIgnoreCase(query.getOrder())) {
                    queryWrapper.orderByAsc("wmo." + oConvertUtils.camelToUnderline(column));
                } else {
                    queryWrapper.orderByDesc("wmo." + oConvertUtils.camelToUnderline(column));
                }
            } else {
                queryWrapper.orderByDesc("wmo.create_time");
            }
        } else {
            queryWrapper.orderByDesc("wmo.create_time");
        }
 
        return eamSecondMaintenanceOrderMapper.queryPageList(page, queryWrapper);
    }
 
    /**
     * 批量新增树结构
     */
    @Override
    public List<EamEquipmentTree> getTree(){
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser == null) return Collections.emptyList();
 
        // 构建通用查询条件
        QueryWrapper<EamMaintenanceStandard> baseQuery = new QueryWrapper<EamMaintenanceStandard>()
                .eq("ems.maintenance_category", "SECOND_MAINTENANCE")
                .eq("ems.standard_status", MaintenanceStandardStatusEnum.START.name())
                .eq("ems.del_flag", CommonConstant.DEL_FLAG_0.toString());
 
        // 应用数据权限过滤
        applyDataPermissionFilter(sysUser, baseQuery);
 
        // 单次查询设备列表
        List<EamEquipment> equipmentList = eamMaintenanceStandardMapper.queryList(baseQuery);
        if (CollectionUtils.isEmpty(equipmentList)) {
            return Collections.emptyList();
        }
 
        // 获取关联的工厂代码
        Set<String> factoryOrgCodes = equipmentList.stream()
                .map(EamEquipment::getFactoryOrgCode)
                .collect(Collectors.toSet());
 
        // 单次查询所有工厂数据(包含完整树结构)
        List<BaseFactory> allFactories = baseFactoryService.list(
                new LambdaQueryWrapper<BaseFactory>()
                        .eq(BaseFactory::getDelFlag, CommonConstant.DEL_FLAG_0.toString())
                        .orderByAsc(BaseFactory::getSorter));
 
        // 提取权限关联的工厂节点ID(包含所有父节点)
        Set<String> authorizedFactoryIds = extractAuthorizedFactoryIds(
                allFactories, factoryOrgCodes);
 
        // 过滤出有效工厂结构
        List<BaseFactory> validFactories = allFactories.stream()
                .filter(f -> authorizedFactoryIds.contains(f.getId()))
                .collect(Collectors.toList());
 
        // ===构建设备树 ===
        Map<String, List<EamEquipment>> equipmentMap = equipmentList.stream()
                .collect(Collectors.groupingBy(EamEquipment::getFactoryOrgCode));
 
        // 构建基础树
        List<EamEquipmentTree> treeList = FindsEquipmentEamCenterUtil.wrapEquipmentBaseFactoryTreeList(validFactories);
 
        // 填充设备数据
        populateEquipmentNodes(treeList, equipmentMap);
        return treeList;
    }
 
    // 应用数据权限条件(共用方法)
    private void applyDataPermissionFilter(LoginUser user, QueryWrapper<EamMaintenanceStandard> query) {
        if (StringUtils.isNotBlank(user.getEamEquipmentIds())) {
            List<String> equipmentIds = Arrays.asList(user.getEamEquipmentIds().split(","));
            query.in("e.equipment_code", equipmentIds);
        } else {
            List<BaseFactoryUser> factoryUsers = baseFactoryUserService.list(
                    new LambdaQueryWrapper<BaseFactoryUser>()
                            .eq(BaseFactoryUser::getUserId, user.getId()));
 
            if (CollectionUtils.isNotEmpty(factoryUsers)) {
                Set<String> factoryIds = factoryUsers.stream()
                        .map(BaseFactoryUser::getFactoryId)
                        .collect(Collectors.toSet());
 
                Set<String> factoryCodes = baseFactoryService.listByIds(factoryIds).stream()
                        .map(BaseFactory::getOrgCode)
                        .collect(Collectors.toSet());
 
                query.in("e.factory_org_code", factoryCodes);
            }
        }
    }
 
    // 提取授权工厂ID
    private Set<String> extractAuthorizedFactoryIds(List<BaseFactory> allFactories, Set<String> authOrgCodes) {
        Set<String> result = new HashSet<>();
        // 构建ID->工厂的映射
        Map<String, BaseFactory> factoryMap = allFactories.stream()
                .collect(Collectors.toMap(BaseFactory::getId, Function.identity()));
 
        // 逆向查找父节点链
        for (BaseFactory factory : allFactories) {
            if (authOrgCodes.contains(factory.getOrgCode())) {
                collectParentIds(factoryMap, factory.getId(), result);
            }
        }
        return result;
    }
 
    // 递归收集父节点ID
    private void collectParentIds(Map<String, BaseFactory> factoryMap, String currentId, Set<String> idSet) {
        if (StringUtils.isEmpty(currentId) || idSet.contains(currentId)) return;
 
        idSet.add(currentId);
        BaseFactory factory = factoryMap.get(currentId);
        if (factory != null && StringUtils.isNotBlank(factory.getParentId())) {
            collectParentIds(factoryMap, factory.getParentId(), idSet);
        }
    }
 
    // 填充设备节点(非递归)
    private void populateEquipmentNodes(List<EamEquipmentTree> treeList,
                                        Map<String, List<EamEquipment>> equipmentMap) {
        for (EamEquipmentTree node : treeList) {
 
            String orgCode = resolveOrgCodeFromTree(node); // 需实现该逻辑
 
            // 关联设备数据
            List<EamEquipment> devices = equipmentMap.getOrDefault(orgCode, Collections.emptyList());
            if (!CollectionUtils.isEmpty(devices)) {
                for (EamEquipment device : devices) {
                    EamEquipmentTree deviceNode = new EamEquipmentTree().convert(device);
                    deviceNode.setParentId(node.getKey());
                    deviceNode.setType(2);
                    deviceNode.setLeaf(true);  // 明确标记为叶子节点
                    node.getChildren().add(deviceNode);
                }
                // 只有当存在设备时才标记为非叶子
                node.setLeaf(false);
            }
 
            // 继续处理子节点(工厂层级)
            if (!CollectionUtils.isEmpty(node.getChildren())) {
                populateEquipmentNodes(node.getChildren(), equipmentMap);
            }
        }
    }
 
    // 解析方法
    private String resolveOrgCodeFromTree(EamEquipmentTree node) {
        BaseFactory factory =baseFactoryMapper.selectById(node.getKey());
        return factory != null ? factory.getOrgCode() : null;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addMaintenance(EamSecondMaintenanceRequest request) {
        EamEquipment equipment = eamEquipmentService.getById(request.getEquipmentId());
        if (equipment == null) {
            throw new JeecgBootException("设备不存在,添加失败!");
        }
        EamSecondMaintenanceOrder order = new EamSecondMaintenanceOrder();
        order.setOrderNum(request.getOrderNum());
        order.setEquipmentId(request.getEquipmentId());
        order.setStandardId(request.getStandardId());
        order.setMaintenanceDate(request.getMaintenanceDate());
        order.setOperator(request.getOperator());
        //技术状态鉴定表
        EamBaseHFCode eamBaseHFCode = hfCodeService.selectByCategory(HfTemplateCategoryEnum.SECOND_MAINTENANCE.name());
        if(eamBaseHFCode == null) {
            throw new JeecgBootException("未配置技术状态鉴定表的HF编码,添加失败!");
        }
        order.setHfCode(eamBaseHFCode.getHfCode());
        order.setRemark(request.getRemark());
        //状态初始化
        order.setMaintenanceStatus(SecondMaintenanceStatusEnum.WAIT_MAINTENANCE.name());
        order.setCreationMethod(request.getCreationMethod());
        //删除标记
        order.setDelFlag(CommonConstant.DEL_FLAG_0);
        eamSecondMaintenanceOrderMapper.insert(order);
        //处理明细数据
        List<EamMaintenanceStandardDetail> eamMaintenanceStandardDetailList= eamMaintenanceStandardDetailService.selectByStandardId(order.getStandardId());
        List<EamSecondMaintenanceOrderDetail> requestTableDetailList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(eamMaintenanceStandardDetailList)) {
            eamMaintenanceStandardDetailList.forEach(item -> {
                EamSecondMaintenanceOrderDetail detail = new EamSecondMaintenanceOrderDetail();
                BeanUtils.copyProperties(item, detail);
                detail.setId(null);
                detail.setOrderId(order.getId());
                requestTableDetailList.add(detail);
            });
            secondMaintenanceOrderDetailService.saveBatch(requestTableDetailList);
        }
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editMaintenance(EamSecondMaintenanceRequest request) {
        EamEquipment equipment = eamEquipmentService.getById(request.getEquipmentId());
        if (equipment == null) {
            throw new JeecgBootException("设备不存在,添加失败!");
        }
        EamSecondMaintenanceOrder entity = eamSecondMaintenanceOrderMapper.selectById(request.getId());
        if (entity == null) {
            throw new JeecgBootException("编辑的数据已删除,请刷新重试!");
        }
        if (!SecondMaintenanceStatusEnum.WAIT_MAINTENANCE.name().equals(entity.getMaintenanceStatus())) {
            throw new JeecgBootException("只有待保养状态的数据才可编辑!");
        }
        entity.setMaintenanceDate(request.getMaintenanceDate());
        entity.setRemark(request.getRemark());
 
        eamSecondMaintenanceOrderMapper.updateById(entity);
        //判断是否存在保养人 如果存在则启动流程
        if (StringUtils.isNotBlank(entity.getOperator())) {
            //启动流程
            flowCommonService.initActBusiness("工单号: " + entity.getOrderNum() + ";设备编号: " + equipment.getEquipmentCode() + ";安装位置" + equipment.getInstallationPosition(),
                    entity.getId(), "IEamSecondMaintenanceOrderService", "second_maintenance_process", null);
            Map<String, Object> variables = new HashMap<>();
            variables.put("dataId", entity.getId());
            if (StrUtil.isEmpty(entity.getRemark())) {
                variables.put("organization", "新增二保工单默认启动流程");
                variables.put("comment", "新增二保工单默认启动流程");
            } else {
                variables.put("organization", entity.getRemark());
                variables.put("comment", entity.getRemark());
            }
            variables.put("proofreading", true);
            List<String> usernames = new ArrayList<>();
            usernames.add(entity.getOperator());
            variables.put("NextAssignee", usernames);
            Result result = flowDefinitionService.startProcessInstanceByKey("second_maintenance_process", variables);
            if (result != null) {
                //更新周保状态
                entity.setMaintenanceStatus(SecondMaintenanceStatusEnum.UNDER_MAINTENANCE.name());
                entity.setActualStartTime(new Date());
                eamSecondMaintenanceOrderMapper.updateById(entity);
                //更新设备保养状态
                eamEquipmentExtendService.updateEquipmentMaintenanceStatus(entity.getEquipmentId(), EquipmentMaintenanceStatus.UNDER_SECOND_MAINTENANCE.name());
                return result.isSuccess();
            }
 
        }
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean collect(String id) {
        EamSecondMaintenanceOrder entity = eamSecondMaintenanceOrderMapper.selectById(id);
        if (entity == null) {
            throw new JeecgBootException("要领取的工单不存在,请刷新重试!");
        }
        if (!SecondMaintenanceStatusEnum.WAIT_MAINTENANCE.name().equals(entity.getMaintenanceStatus())) {
            throw new JeecgBootException("该工单已进行过领取!");
        }
        EamEquipment equipment = eamEquipmentService.getById(entity.getEquipmentId());
        if (equipment == null) {
            throw new JeecgBootException("设备不存在,添加失败!");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(sysUser != null) {
            if (!BusinessCodeConst.PCR0001.equals(sysUser.getPost()) && !BusinessCodeConst.PCR0002.equals(sysUser.getPost())){
                throw new JeecgBootException("不是操作工,无法领取此工单!");
            }
        }
        List<String> usernames = new ArrayList<>();
        if (sysUser != null) {
            if (BusinessCodeConst.PCR0001.equals(sysUser.getPost())) {
                entity.setOperator(sysUser.getUsername());
                usernames.add(entity.getOperator());
            }
            if (BusinessCodeConst.PCR0002.equals(sysUser.getPost())) {
                entity.setRepairman(sysUser.getUsername());
                usernames.add(entity.getRepairman());
            }
        }
        entity.setMaintenanceStatus(SecondMaintenanceStatusEnum.UNDER_MAINTENANCE.name());
        entity.setActualStartTime(new Date());
        eamSecondMaintenanceOrderMapper.updateById(entity);
        //启动流程
        flowCommonService.initActBusiness("工单号: " + entity.getOrderNum() + ";设备编号: " + equipment.getEquipmentCode() + "进行设备二级保养",
                entity.getId(), "IEamSecondMaintenanceOrderService", "SecondMaintenance_Process", null);
        Map<String, Object> variables = new HashMap<>();
        variables.put("dataId", entity.getId());
        if (StrUtil.isEmpty(entity.getRemark())) {
            variables.put("organization", "新增二保工单默认启动流程");
            variables.put("comment", "新增二保工单默认启动流程");
        } else {
            variables.put("organization", entity.getRemark());
            variables.put("comment", entity.getRemark());
        }
        variables.put("proofreading", true);
        if (sysUser != null) {
            if (BusinessCodeConst.PCR0001.equals(sysUser.getPost())) {
                variables.put("operator_task", usernames);
                List<UserSelector> userSelectorList = sysUserService.selectOperatorList(equipment.getEquipmentCode(), equipment.getFactoryOrgCode(), BusinessCodeConst.PCR0002);
                if (!CollectionUtils.isEmpty(userSelectorList)) {
                    List<String> usernameList = userSelectorList.stream().map(UserSelector::getUsername).collect(Collectors.toList());
                    variables.put("maintenance_task",usernameList);
                }
            }else if (BusinessCodeConst.PCR0002.equals(sysUser.getPost())) {
                variables.put("maintenance_task", usernames);
                List<UserSelector> userSelectorList = sysUserService.selectOperatorList(equipment.getEquipmentCode(), equipment.getFactoryOrgCode(), BusinessCodeConst.PCR0001);
                if (!CollectionUtils.isEmpty(userSelectorList)) {
                    List<String> usernameList = userSelectorList.stream().map(UserSelector::getUsername).collect(Collectors.toList());
                    variables.put("operator_task",usernameList);
                }
            }
        }
        Result result = flowDefinitionService.startProcessInstanceByKey("SecondMaintenance_Process", variables);
        if (result != null) {
            //更新设备保养状态
            eamEquipmentExtendService.updateEquipmentMaintenanceStatus(entity.getEquipmentId(), EquipmentMaintenanceStatus.UNDER_SECOND_MAINTENANCE.name());
            return result.isSuccess();
        }
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    @EquipmentHistoryLog(operationTag = EquipmentOperationTagEnum.SECOND_MAINTENANCE, businessTable = "eam_second_maintenance_order")
    public EamSecondMaintenanceOrder approval(EamSecondMaintenanceRequest request) {
        EamSecondMaintenanceOrder entity = eamSecondMaintenanceOrderMapper.selectById(request.getId());
        if (entity == null) {
            throw new JeecgBootException("审批的数据已删除,请刷新重试!");
        }
        // 获取当前登录用户
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null || StrUtil.isBlank(user.getId())) {
            throw new JeecgBootException("未获取到登录用户,请重新登录后再试!");
        }
        request.setAssignee(user.getUsername());
        // 获取流程业务记录
        FlowMyBusiness flowMyBusiness = flowMyBusinessService.getFlowMyBusiness(request.getInstanceId(), request.getTaskId());
        if (flowMyBusiness == null) {
            throw new JeecgBootException("流程实例不存在,请刷新后重试!");
        }
 
        boolean userAuthorized = isUserAuthorized(flowMyBusiness, user);
        if (!userAuthorized) {
            throw new JeecgBootException("用户无权操作此任务,请刷新后重试!");
        }
        // 认领任务
        if (!claimTask(flowMyBusiness.getTaskId(), user)) {
            throw new JeecgBootException("任务不存在、已完成或已被他人认领!");
        }
 
        EamEquipment equipment = eamEquipmentService.getById(entity.getEquipmentId());
        if (equipment == null) {
            throw new JeecgBootException("设备不存在,请检查!");
        }
 
        SecondMaintenanceStatusEnum status = SecondMaintenanceStatusEnum.getInstance(entity.getMaintenanceStatus());
        if (status == null) {
            return null;
        }
        //流程变量
        Map<String, Object> values = new HashMap<>();
        List<String> userApprovalList;
        List<UserSelector> userSelectors;
        switch (status) {
            case UNDER_MAINTENANCE:
                //保养中
                boolean parallelCompletion = flowTaskService.checkParallelCompletion(flowMyBusiness.getTaskId());
                //执行完成
                 userSelectors = sysUserService.selectOperatorList(equipment.getEquipmentCode(), equipment.getFactoryOrgCode(), BusinessCodeConst.PCR0004);
                if (CollectionUtil.isEmpty(userSelectors)) {
                    throw new JeecgBootException("设备未存在管理员,无法进入下级审批!");
                }else{
                    userApprovalList = userSelectors.stream().map(UserSelector::getUsername).collect(Collectors.toList());
                    if (parallelCompletion) {
                        values.put("NextAssignee", userApprovalList);
                        entity.setMaintenanceStatus(SecondMaintenanceStatusEnum.WAIT_ADMIN_CONFIRM.name());
                        entity.setActualEndTime(new Date());
                    }
                }
                if (BusinessCodeConst.PCR0001.equals(user.getPost())) {
                    entity.setOperator(user.getUsername());
                    values.put("organization", "二保操作工执行结束");
                    values.put("comment", "二保操作工执行结束");
                    request.setComment("二保操作工执行结束");
                    //处理对应详情
                    if (CollectionUtils.isNotEmpty(request.getTableDetailList())){
                        //删除原有数据
                        List<EamSecondMaintenanceOrderDetail> addList = new ArrayList<>();
                        //先删除原有
                        LambdaQueryWrapper<EamSecondMaintenanceOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(EamSecondMaintenanceOrderDetail::getOrderId, entity.getId());
                        queryWrapper.eq(EamSecondMaintenanceOrderDetail::getItemCategory,EamMaintenanceStandardDetailCategory.OPERATOR_MAINTENANCE.name());
                        secondMaintenanceOrderDetailService.remove(queryWrapper);
                        request.getTableDetailList().forEach(tableDetail -> {
                            EamSecondMaintenanceOrderDetail eamMaintenanceStandardDetail=new EamSecondMaintenanceOrderDetail();
                            BeanUtils.copyProperties(tableDetail, eamMaintenanceStandardDetail);
                            eamMaintenanceStandardDetail.setOrderId(entity.getId());
                            eamMaintenanceStandardDetail.setCreateBy(user.getUsername());
                            addList.add(eamMaintenanceStandardDetail);
                        });
                        secondMaintenanceOrderDetailService.saveBatch(addList);
                    }
                }else if (BusinessCodeConst.PCR0002.equals(user.getPost())) {
                    entity.setRepairman(user.getUsername());
                    values.put("organization", "二保维修工执行结束");
                    values.put("comment", "二保维修工执行结束");
                    request.setComment("二保维修工执行结束");
                    //处理对应详情
                    if (CollectionUtils.isNotEmpty(request.getTableDetailList())){
                        //删除原有数据
                        List<EamSecondMaintenanceOrderDetail> addList = new ArrayList<>();
                        //先删除原有
                        LambdaQueryWrapper<EamSecondMaintenanceOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(EamSecondMaintenanceOrderDetail::getOrderId, entity.getId());
                        queryWrapper.eq(EamSecondMaintenanceOrderDetail::getItemCategory,EamMaintenanceStandardDetailCategory.REPAIRER_MAINTENANCE.name());
                        secondMaintenanceOrderDetailService.remove(queryWrapper);
                        request.getTableDetailList().forEach(tableDetail -> {
                            EamSecondMaintenanceOrderDetail eamMaintenanceStandardDetail=new EamSecondMaintenanceOrderDetail();
                            BeanUtils.copyProperties(tableDetail, eamMaintenanceStandardDetail);
                            eamMaintenanceStandardDetail.setOrderId(entity.getId());
                            eamMaintenanceStandardDetail.setCreateBy(user.getUsername());
                            addList.add(eamMaintenanceStandardDetail);
                        });
                        secondMaintenanceOrderDetailService.saveBatch(addList);
                    }
                }
                values.put("dataId", entity.getId());
                break;
            case WAIT_ADMIN_CONFIRM:
                //管理员确认
                userSelectors = sysUserService.selectOperatorList(equipment.getEquipmentCode(), equipment.getFactoryOrgCode(), BusinessCodeConst.PCR0006);
                if (CollectionUtil.isEmpty(userSelectors)) {
                    throw new JeecgBootException("设备未存在检查人,无法进入下级审批!");
                }else{
                    userApprovalList= userSelectors.stream().map(UserSelector::getUsername).collect(Collectors.toList());
                    values.put("dataId", entity.getId());
                    if (StrUtil.isEmpty(request.getDealDescription())){
                        request.setDealDescription("");
                    }
                    values.put("organization",request.getDealDescription());
                    values.put("comment", request.getDealDescription());
                    values.put("manageUserResult",request.getManageUserResult());
                    request.setComment(request.getDealDescription());
                    if (request.getManageUserResult().equals("2")){
                        entity.setMaintenanceStatus(SecondMaintenanceStatusEnum.UNDER_MAINTENANCE.name());
                    }else {
                        values.put("NextAssignee", userApprovalList);
                        entity.setMaintenanceStatus(SecondMaintenanceStatusEnum.WAIT_INSPECTOR_CONFIRM.name());
                        entity.setConfirmTime(new Date());
                        entity.setManageUser(user.getUsername());
                        entity.setProblemDescription(request.getProblemDescription());
                        entity.setManageUserResult(request.getManageUserResult());
                        entity.setDealDescription(request.getDealDescription());
                    }
                }
                break;
            case WAIT_INSPECTOR_CONFIRM:
                //检查人确认
                if (StrUtil.isEmpty(request.getInspectConfirmComment())){
                    request.setInspectConfirmComment("");
                }
                values.put("dataId", entity.getId());
                values.put("organization",request.getInspectConfirmComment());
                values.put("comment", request.getInspectConfirmComment());
                values.put("inspectorResult",request.getInspectorResult());
                request.setComment(request.getInspectConfirmComment());
                if (request.getInspectorResult().equals("2")){
                    entity.setMaintenanceStatus(SecondMaintenanceStatusEnum.WAIT_ADMIN_CONFIRM.name());
                    userSelectors = sysUserService.selectOperatorList(equipment.getEquipmentCode(), equipment.getFactoryOrgCode(), BusinessCodeConst.PCR0004);
                    if (CollectionUtil.isEmpty(userSelectors)) {
                        throw new JeecgBootException("设备未存在车间设备管理员,无法进入驳回审批!");
                    }else{
                        userApprovalList = userSelectors.stream().map(UserSelector::getUsername).collect(Collectors.toList());
                        values.put("NextAssignee", userApprovalList);
                    }
                }else {
                    entity.setMaintenanceStatus(SecondMaintenanceStatusEnum.COMPLETE.name());
                    entity.setInspector(user.getUsername());
                    entity.setInspectorResult(request.getInspectorResult());
                    entity.setInspectConfirmComment(request.getInspectConfirmComment());
                    entity.setInspectConfirmTime(new Date());
                }
                break;
            default:
                throw  new JeecgBootException("审批失败");
        }
        request.setValues(values);
        // 完成流程任务
        Result result = flowTaskService.complete(request);
        if (!result.isSuccess()) {
            throw new JeecgBootException("审批失败,请刷新查看!");
        }
        if (user.getPost().equals(BusinessCodeConst.PCR0004)&&request.getManageUserResult().equals("2")){
            //管理员拒绝,会签节点修改对应关系
            List<FlowMyBusiness> list = flowMyBusinessService.list(new LambdaQueryWrapper<FlowMyBusiness>().eq(FlowMyBusiness::getProcessInstanceId, request.getInstanceId()));
            if (CollectionUtils.isNotEmpty(list)) {
                list.forEach(item -> {
                    if (item.getTaskNameId().equals("maintenance_task")) {
                        //获取维修工岗位用户
                        List<UserSelector> userSelectorList = sysUserService.selectOperatorList(equipment.getEquipmentCode(), equipment.getFactoryOrgCode(), BusinessCodeConst.PCR0002);
                        if (!CollectionUtils.isEmpty(userSelectorList)) {
                            List<String> usernameList = userSelectorList.stream().map(UserSelector::getUsername).collect(Collectors.toList());
                            item.setTodoUsers(JSON.toJSONString(usernameList));
                        }
                    }
                    if (item.getTaskNameId().equals("operator_task")) {
                        //获取操作人岗位用户
                        List<UserSelector> userSelectorList = sysUserService.selectOperatorList(equipment.getEquipmentCode(), equipment.getFactoryOrgCode(), BusinessCodeConst.PCR0001);
                        if (!CollectionUtils.isEmpty(userSelectorList)) {
                            List<String> usernameList = userSelectorList.stream().map(UserSelector::getUsername).collect(Collectors.toList());
                            item.setTodoUsers(JSON.toJSONString(usernameList));
                        }
                    }
                });
                flowMyBusinessService.updateBatchById(list);
            }
        }
        //保存工单
        eamSecondMaintenanceOrderMapper.updateById(entity);
        return entity;
    }
 
    /**
     * 批量打印二保工单
     * @param ids
     * @return
     */
    @Override
    public List<EamSecondMaintenanceOrderExport> export(String ids){
        QueryWrapper<EamSecondMaintenanceOrderExport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wmo.del_flag",CommonConstant.DEL_FLAG_0.toString());
        queryWrapper.eq("wmo.maintenance_status",SecondMaintenanceStatusEnum.COMPLETE.name());
        //用户数据权限
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser == null) {
            return new ArrayList<>();
        }
        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 new ArrayList<>();
            }
        }
        //查询条件过滤
        if (StrUtil.isNotEmpty(ids)) {
            List<String> idList = Arrays.asList(ids.split(","));
            queryWrapper.in("wmo.id", idList);
        } else {
            queryWrapper.orderByDesc("wmo.create_time");
        }
        List<EamSecondMaintenanceOrderExport> eamSecondMaintenanceOrderExports=eamSecondMaintenanceOrderMapper.queryList(queryWrapper);
        //填充对应二保明细
        if (!eamSecondMaintenanceOrderExports.isEmpty()){
            eamSecondMaintenanceOrderExports.forEach(item->{
               //维修人员保养内容
               List<EamSecondMaintenanceOrderDetail> maintenanceOrderDetails=eamSecondMaintenanceOrderDetailService.
                       list(new QueryWrapper<EamSecondMaintenanceOrderDetail>().eq("order_id",item.getId()).
                               eq("item_category",EamMaintenanceStandardDetailCategory.REPAIRER_MAINTENANCE.name())
                               .orderByAsc("item_code"));
               if (!maintenanceOrderDetails.isEmpty()){
                   item.setMaintenanceOrderDetails(maintenanceOrderDetails);
               }
               //操作人员保养内容
                List<EamSecondMaintenanceOrderDetail> operationOrderDetails=eamSecondMaintenanceOrderDetailService.
                        list(new QueryWrapper<EamSecondMaintenanceOrderDetail>().eq("order_id",item.getId()).
                                eq("item_category",EamMaintenanceStandardDetailCategory.OPERATOR_MAINTENANCE.name())
                                .orderByAsc("item_code"));
                if (!operationOrderDetails.isEmpty()) {
                    item.setOperationOrderDetails(operationOrderDetails);
                }
            });
        }
        return eamSecondMaintenanceOrderExports;
    }
 
    private boolean isUserAuthorized(FlowMyBusiness flowMyBusiness, LoginUser user) {
        List<String> todoUsers = JSON.parseArray(flowMyBusiness.getTodoUsers(), String.class);
        return todoUsers != null && todoUsers.contains(user.getUsername());
    }
 
    private boolean claimTask(String taskId, LoginUser user) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            return false;
        }
        if (task.getAssignee() != null && !task.getAssignee().equals(user.getUsername())) {
            return false;
        }
        taskService.claim(taskId, user.getUsername());
        return true;
    }
 
    @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) {
        //业务是否干预流程,业务干预,流程干预,指定人员进行处理
        //获取下一步处理人
        Object object = values.get("NextAssignee");
        return (List<String>) object;
    }
}