cuilei
7 天以前 58020f3d711d4baa16ef092c2ea826071c7d23b9
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
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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.flowable.engine.HistoryService;
import org.flowable.engine.TaskService;
import org.flowable.engine.impl.el.DateUtil;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.variable.api.persistence.entity.VariableInstance;
import org.jeecg.common.api.vo.FileUploadResult;
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.BusinessCodeConst;
import org.jeecg.modules.eam.constant.EquipmentMaintenanceStatus;
import org.jeecg.modules.eam.constant.EquipmentOperationTagEnum;
import org.jeecg.modules.eam.constant.InspectionStatus;
import org.jeecg.modules.eam.entity.EamEquipment;
import org.jeecg.modules.eam.entity.EamInspectionOrder;
import org.jeecg.modules.eam.entity.EamInspectionOrderDetail;
import org.jeecg.modules.eam.mapper.EamInspectionOrderMapper;
import org.jeecg.modules.eam.request.EamInspectionOrderQuery;
import org.jeecg.modules.eam.request.EamInspectionOrderRequest;
import org.jeecg.modules.eam.service.*;
import org.jeecg.modules.eam.vo.EquipmentInspectionStatistics;
import org.jeecg.modules.flowable.apithird.business.entity.FlowMyBusiness;
import org.jeecg.modules.flowable.apithird.business.service.impl.FlowMyBusinessServiceImpl;
import org.jeecg.modules.flowable.apithird.service.FlowCallBackServiceI;
import org.jeecg.modules.flowable.apithird.service.FlowCommonService;
import org.jeecg.modules.flowable.domain.vo.FlowTaskVo;
import org.jeecg.modules.flowable.domain.vo.WorkTaskDataVo;
import org.jeecg.modules.flowable.service.IFlowDefinitionService;
import org.jeecg.modules.flowable.service.IFlowTaskService;
import org.jeecg.modules.qywx.message.vo.TemplateCard;
import org.jeecg.modules.qywx.message.vo.TemplateCardEntity;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.IMdcProductionService;
import org.jeecg.modules.system.service.IMdcUserProductionService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.IThirdAppService;
import org.jeecg.modules.system.service.impl.ThirdAppWechatEnterpriseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @Description: 点检工单
 * @Author: jeecg-boot
 * @Date: 2025-04-02
 * @Version: V1.0
 */
@Service("IEamInspectionOrderService")
public class EamInspectionOrderServiceImpl extends ServiceImpl<EamInspectionOrderMapper, EamInspectionOrder> implements IEamInspectionOrderService, FlowCallBackServiceI {
 
    @Resource
    private EamInspectionOrderMapper eamInspectionOrderMapper;
    @Autowired
    private IEamInspectionOrderDetailService eamInspectionOrderDetailService;
    @Resource
    private FlowCommonService flowCommonService;
    @Resource
    private IFlowDefinitionService flowDefinitionService;
    @Autowired
    private IFlowTaskService flowTaskService;
    @Autowired
    private IEamEquipmentService eamEquipmentService;
    @Autowired
    private FlowMyBusinessServiceImpl flowMyBusinessService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IEamEquipmentService iEamEquipmentService;
    @Autowired
    private IMdcUserProductionService mdcUserProductionService;
    @Autowired
    private IEamReportRepairService eamReportRepairService;
    @Autowired
    private IEamEquipmentExtendService eamEquipmentExtendService;
    @Autowired
    private IMdcProductionService mdcProductionService;
    @Autowired
    private ThirdAppWechatEnterpriseServiceImpl wechatEnterpriseService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private HistoryService historyService;
 
    @Value("${wechatEnterprise.cardActionUrl}")
    private String cardActionUrl;
 
    @Override
    public IPage<EamInspectionOrder> queryPageList(Page<EamInspectionOrder> page, EamInspectionOrderQuery query) {
        QueryWrapper<EamInspectionOrder> queryWrapper = new QueryWrapper<>();
        //用户数据权限
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (sysUser == null) {
            return page;
        }
        if (StringUtils.isNotBlank(sysUser.getEquipmentIds())) {
            //选择了设备,根据设备id过滤设备
            List<String> equipArr = Arrays.asList(sysUser.getEquipmentIds().split(","));
            queryWrapper.in("e.equipment_code", equipArr);
        } else {
            //没有选择设备,根据车间过滤设备
            queryWrapper.exists("select 1 from mdc_user_production t where t.user_id={0} and t.pro_id=e.org_id ", sysUser.getId());
        }
        //查询条件过滤
        if (query != null) {
            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.getInspectionStatus())) {
                queryWrapper.eq("wmo.inspection_status", query.getInspectionStatus());
            }
            if (query.getInspectionDateBegin() != null && query.getInspectionDateEnd() != null) {
                queryWrapper.between("wmo.inspection_date", query.getInspectionDateBegin(), query.getInspectionDateEnd());
            }
            //排序
            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 eamInspectionOrderMapper.queryPageList(page, queryWrapper);
    }
 
    @Override
    public List<EamInspectionOrder> selectUnCompleteOrder(String expiredDate) {
        LambdaQueryWrapper<EamInspectionOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.lt(EamInspectionOrder::getInspectionDate, expiredDate);
        List<String> unCompleteStatus = new ArrayList<>();
        unCompleteStatus.add(InspectionStatus.WAIT_INSPECTION.name());
        unCompleteStatus.add(InspectionStatus.UNDER_INSPECTION.name());
        queryWrapper.in(EamInspectionOrder::getInspectionStatus, unCompleteStatus);
        queryWrapper.orderByAsc(EamInspectionOrder::getInspectionDate);
        return eamInspectionOrderMapper.selectList(queryWrapper);
    }
 
    @Override
    public List<EquipmentInspectionStatistics> equipmentInspectionStatistics(String productionId, LocalDate firstOfMonth, LocalDate today) {
        if (StringUtils.isNotBlank(productionId)) {
            //车间编码不为空
            List<String> productIds = mdcProductionService.recursionChildren(productionId);
            if (CollectionUtil.isEmpty(productIds)) {
                return Collections.emptyList();
            }
            List<EquipmentInspectionStatistics> list = this.baseMapper.equipmentInspectionStatistics(productIds, firstOfMonth.toString(), today.plusDays(1).toString());
            if (CollectionUtil.isEmpty(list)) {
                return Collections.emptyList();
            }
            return list;
        }
        List<EquipmentInspectionStatistics> list = this.baseMapper.equipmentInspectionStatistics(null, firstOfMonth.toString(), today.plusDays(1).toString());
        if (CollectionUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list;
    }
 
    @Override
    public List<EamInspectionOrder> selectUnReceivedInspectionOrder() {
        return this.baseMapper.selectUnReceivedInspectionOrder();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addInspectionOrder(EamInspectionOrderRequest eamInspectionOrderRequest) {
        EamInspectionOrder eamInspectionOrder = new EamInspectionOrder();
        BeanUtils.copyProperties(eamInspectionOrderRequest, eamInspectionOrder);
        //修改状态
        if (StrUtil.isNotBlank(eamInspectionOrderRequest.getOperator())) {
            eamInspectionOrder.setInspectionStatus(InspectionStatus.UNDER_INSPECTION.name());
        } else {
            eamInspectionOrder.setInspectionStatus(InspectionStatus.WAIT_INSPECTION.name());
        }
        save(eamInspectionOrder);
        //处理明细数据
        if (CollectionUtil.isNotEmpty(eamInspectionOrderRequest.getTableDetailList())) {
            eamInspectionOrderRequest.getTableDetailList().forEach(tableDetail -> {
                tableDetail.setOrderId(eamInspectionOrder.getId());
                tableDetail.setId(null);
            });
            eamInspectionOrderDetailService.saveBatch(eamInspectionOrderRequest.getTableDetailList());
        }
        //处理附件
        if (CollectionUtil.isNotEmpty(eamInspectionOrderRequest.getFileList())) {
            FileUploadResult fileUploadResult = eamInspectionOrderRequest.getFileList().get(0);
            ObjectMapper mapper = new ObjectMapper();
            try {
                String referenceFile = mapper.writeValueAsString(fileUploadResult);
                eamInspectionOrder.setImageFiles(referenceFile);
            } catch (JsonProcessingException e) {
                log.error("JSON转换失败:" + e.getMessage(), e);
            }
        }
        if (StrUtil.isNotBlank(eamInspectionOrderRequest.getOperator())) {
            triggerProcess(eamInspectionOrder);
            //更新设备保养状态
            eamEquipmentExtendService.updateEquipmentInspectionStatus(eamInspectionOrder.getEquipmentId(), EquipmentMaintenanceStatus.UNDER_INSPECTION.name());
            //推送企业微信消息
            sendQywxTemplateCardMessage(eamInspectionOrder, null);
        }
 
        return true;
    }
 
    private void sendQywxTemplateCardMessage(EamInspectionOrder eamInspectionOrder, EamInspectionOrderRequest request) {
        TemplateCard templateCard = new TemplateCard();
        String inspectionStatus = eamInspectionOrder.getInspectionStatus();
        EamEquipment equipment = eamEquipmentService.getById(eamInspectionOrder.getEquipmentId());
        eamInspectionOrder.setEquipmentCode(equipment.getEquipmentCode());
        //todo 目前确认,待领取工单不推送
        //if (InspectionStatus.WAIT_INSPECTION.name().equals(inspectionStatus)) {
        //    //工单待领取,推送消息给所有操作工
        //    String orgId = Optional.ofNullable(eamEquipmentService.getById(eamInspectionOrder.getEquipmentId()))
        //            .map(EamEquipment::getOrgId)
        //            .orElse(null);
        //    if (orgId == null) {
        //        throw new IllegalArgumentException("未找到设备的组织 ID");
        //    }
        //    //查询该设备所属产线的所有操作工
        //    List<SysUser> sysUserList = mdcUserProductionService.queryByPostAndProId("PCR0001", orgId);
        //    List<String> usernameList = sysUserList.stream().map(SysUser::getUsername).collect(Collectors.toList());
        //    if (usernameList.isEmpty()) {
        //        throw new IllegalArgumentException("未找到该设备所属产线的操作工,请联系管理员处理");
        //    }
        //    String nextAssigneeStr = usernameList.stream()
        //            .filter(Objects::nonNull) // 可选:过滤 null 值
        //            .collect(Collectors.joining(","));
        //    String touser = wechatEnterpriseService.getTouser(nextAssigneeStr, false);
        //    templateCard.setTouser(touser);
        //}
        if (InspectionStatus.UNDER_INSPECTION.name().equals(inspectionStatus)) {
            //工单已开始点检,推送消息给具体操作工(新增工单时指定、领取工单的操作工)
            String operator = eamInspectionOrder.getOperator();
            if (StrUtil.isNotBlank(operator)) {
                //新增工单时、工单领取时已指定点检人
                String touser = wechatEnterpriseService.getTouser(operator, false);
                templateCard.setTouser(touser);
            }
        }
        if (InspectionStatus.WAIT_CONFIRM.name().equals(inspectionStatus)) {
            //工单已点检完成,推送消息给班组长确认
            List<String> nextAssignee = (List<String>) request.getValues().get("NextAssignee");
            String nextAssigneeStr = nextAssignee.stream()
                    .filter(Objects::nonNull) // 可选:过滤 null 值
                    .collect(Collectors.joining(","));
            String touser = wechatEnterpriseService.getTouser(nextAssigneeStr, false);
            templateCard.setTouser(touser);
        }
        //todo 工单完成,不推送消息
        //if (InspectionStatus.COMPLETE.name().equals(inspectionStatus)) {
        //    //工单已确认完成,推送消息给点检人
        //    String touser = wechatEnterpriseService.getTouser(eamInspectionOrder.getOperator(), false);
        //    templateCard.setTouser(touser);
        //}
 
        TemplateCardEntity templateCardEntity = new TemplateCardEntity();
        templateCard.setTemplate_card(templateCardEntity);
        templateCardEntity.setTask_id(eamInspectionOrder.getId());
        TemplateCardEntity.MainTitle mainTitle = new TemplateCardEntity.MainTitle();
        mainTitle.setTitle("设备点检");
        templateCardEntity.setMain_title(mainTitle);
 
        //if (InspectionStatus.WAIT_INSPECTION.name().equals(inspectionStatus)) {
        //    templateCardEntity.setSub_title_text("新增设备点检工单: " + eamInspectionOrder.getOrderNum() + " ,请进入系统领取");
        //}
        if (InspectionStatus.UNDER_INSPECTION.name().equals(inspectionStatus)) {
            if (Objects.nonNull(request) && StrUtil.isNotBlank(request.getConfirmDealType())) {
                //是驳回的单子
                templateCardEntity.setSub_title_text("工单: " + eamInspectionOrder.getOrderNum() + " 被驳回,请重新进行设备点检");
            } else {
                templateCardEntity.setSub_title_text("已领取工单: " + eamInspectionOrder.getOrderNum() + ",开始进行设备点检");
            }
        }
        if (InspectionStatus.WAIT_CONFIRM.name().equals(inspectionStatus)) {
            templateCardEntity.setSub_title_text("工单: " + eamInspectionOrder.getOrderNum() + " 已完成设备点检,请进入系统确认");
        }
        //if (InspectionStatus.COMPLETE.name().equals(inspectionStatus)) {
        //    templateCardEntity.setSub_title_text("工单: " + eamInspectionOrder.getOrderNum() + " 已完成点检后确认");
        //}
 
        List<TemplateCardEntity.HorizontalContent> horizontalContentList = CollectionUtil.newArrayList();
        TemplateCardEntity.HorizontalContent content1 = new TemplateCardEntity.HorizontalContent();
        content1.setKeyname("工单号");
        content1.setValue(eamInspectionOrder.getOrderNum());
        horizontalContentList.add(content1);
        TemplateCardEntity.HorizontalContent content2 = new TemplateCardEntity.HorizontalContent();
        content2.setKeyname("设备编号");
        content2.setValue(eamInspectionOrder.getEquipmentCode());
        horizontalContentList.add(content2);
 
        //如果工单状态为待点检(没指定点检人的未领取状态),流程是没有启动的,无法获取节点信息
        if (!InspectionStatus.WAIT_INSPECTION.name().equals(inspectionStatus)) {
            WorkTaskDataVo previousFlowInfo = flowTaskService.getPreviousFlowInfo(eamInspectionOrder.getId());
            TemplateCardEntity.HorizontalContent content3 = new TemplateCardEntity.HorizontalContent();
            content3.setKeyname("前驱节点");
            content3.setValue(previousFlowInfo.getPreNode());
            horizontalContentList.add(content3);
            TemplateCardEntity.HorizontalContent content4 = new TemplateCardEntity.HorizontalContent();
            content4.setKeyname("当前节点");
            if (InspectionStatus.COMPLETE.name().equals(inspectionStatus)) {
                content4.setValue("已完成");
            } else {
                content4.setValue(previousFlowInfo.getName());
            }
            horizontalContentList.add(content4);
        }
 
        //if (InspectionStatus.WAIT_INSPECTION.name().equals(inspectionStatus)) {
        //    TemplateCardEntity.HorizontalContent content3 = new TemplateCardEntity.HorizontalContent();
        //    content3.setKeyname("发起人");
        //    SysUser sysUser = sysUserService.getUserByName(eamInspectionOrder.getCreateBy());
        //    content3.setValue(sysUser.getRealname());
        //    horizontalContentList.add(content3);
        //}
        if (InspectionStatus.UNDER_INSPECTION.name().equals(inspectionStatus)) {
            if (Objects.isNull(request)) {
                TemplateCardEntity.HorizontalContent content = new TemplateCardEntity.HorizontalContent();
                content.setKeyname("领取人");
                SysUser sysUser = sysUserService.getUserByName(eamInspectionOrder.getOperator());
                content.setValue(sysUser.getRealname());
                horizontalContentList.add(content);
            } else {
                TemplateCardEntity.HorizontalContent content3 = new TemplateCardEntity.HorizontalContent();
                TemplateCardEntity.HorizontalContent content4 = new TemplateCardEntity.HorizontalContent();
                content3.setKeyname("确认人");
                String confirmAssignee = request.getAssignee();
                SysUser confirmUser = sysUserService.getUserByName(confirmAssignee);
                content3.setValue(confirmUser.getRealname());
                horizontalContentList.add(content3);
                content4.setKeyname("确认意见");
                content4.setValue("驳回");
                horizontalContentList.add(content4);
            }
        }
        if (InspectionStatus.WAIT_CONFIRM.name().equals(inspectionStatus)) {
            TemplateCardEntity.HorizontalContent content3 = new TemplateCardEntity.HorizontalContent();
            content3.setKeyname("点检人");
            SysUser sysUser = sysUserService.getUserByName(eamInspectionOrder.getOperator());
            content3.setValue(sysUser.getRealname());
            horizontalContentList.add(content3);
        }
        //if ((InspectionStatus.COMPLETE.name().equals(inspectionStatus))) {
        //    TemplateCardEntity.HorizontalContent content3 = new TemplateCardEntity.HorizontalContent();
        //    TemplateCardEntity.HorizontalContent content4 = new TemplateCardEntity.HorizontalContent();
        //    content3.setKeyname("确认人");
        //    SysUser sysUser = sysUserService.getUserByName(eamInspectionOrder.getCreateBy());
        //    content3.setValue(sysUser.getRealname());
        //    horizontalContentList.add(content3);
        //    content4.setKeyname("确认意见");
        //    content4.setValue("通过");
        //    horizontalContentList.add(content4);
        //}
 
        templateCardEntity.setHorizontal_content_list(horizontalContentList);
 
        TemplateCardEntity.CardAction cardAction = new TemplateCardEntity.CardAction();
        cardAction.setType(1);
        cardAction.setUrl(cardActionUrl);
        templateCardEntity.setCard_action(cardAction);
 
        wechatEnterpriseService.sendTemplateCardMsg(templateCard, true);
    }
 
    /**
     * 触发流程
     *
     * @param eamInspectionOrder
     * @return
     */
    public boolean triggerProcess(EamInspectionOrder eamInspectionOrder) {
        EamEquipment equipment = eamEquipmentService.getById(eamInspectionOrder.getEquipmentId());
        if (equipment == null) {
            return false;
        } else {
            eamInspectionOrder.setEquipmentCode(equipment.getEquipmentCode());
        }
        System.out.println("设备点检:" + eamInspectionOrder.getId());
        flowCommonService.initActBusiness("工单号: " + eamInspectionOrder.getOrderNum() + ";设备编号: " + eamInspectionOrder.getEquipmentCode() + ";安装位置: " + equipment.getInstallationPosition(),
                eamInspectionOrder.getId(), "IEamInspectionOrderService", "eam_inspection", null);
        Map<String, Object> variables = new HashMap<>();
        variables.put("dataId", eamInspectionOrder.getId());
        if (StrUtil.isEmpty(eamInspectionOrder.getRemark())) {
            variables.put("organization", "新增点检工单默认启动流程");
            variables.put("comment", "新增点检工单默认启动流程");
        } else {
            variables.put("organization", eamInspectionOrder.getRemark());
            variables.put("comment", eamInspectionOrder.getRemark());
        }
        variables.put("proofreading", true);
        List<String> usernames = new ArrayList<>();
        usernames.add(eamInspectionOrder.getOperator());
        variables.put("NextAssignee", usernames);
        Result result = flowDefinitionService.startProcessInstanceByKey("eam_inspection", variables);
        return result.isSuccess();
    }
 
 
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean editInspectionOrder(EamInspectionOrderRequest eamInspectionOrderRequest) {
        EamInspectionOrder eamInspectionOrder = new EamInspectionOrder();
        BeanUtils.copyProperties(eamInspectionOrderRequest, eamInspectionOrder);
        if (StrUtil.isNotEmpty(eamInspectionOrder.getOperator())) {
            eamInspectionOrder.setInspectionStatus(InspectionStatus.UNDER_INSPECTION.name());
            triggerProcess(eamInspectionOrder);
            //更新设备保养状态
            eamEquipmentExtendService.updateEquipmentInspectionStatus(eamInspectionOrder.getEquipmentId(), EquipmentMaintenanceStatus.UNDER_INSPECTION.name());
        }
        super.updateById(eamInspectionOrder);
        //处理明细数据
        if (CollectionUtil.isNotEmpty(eamInspectionOrderRequest.getTableDetailList())) {
            eamInspectionOrderRequest.getTableDetailList().forEach(tableDetail -> {
                tableDetail.setOrderId(eamInspectionOrder.getId());
                tableDetail.setCreateTime(new Date());
            });
            //删除明细
            eamInspectionOrderDetailService.remove(new QueryWrapper<EamInspectionOrderDetail>().eq("order_id", eamInspectionOrder.getId()));
            eamInspectionOrderDetailService.saveBatch(eamInspectionOrderRequest.getTableDetailList());
        }
        return true;
    }
 
    /**
     * 领取点检工单
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean takeInspectionOrder(String id) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(user == null || !BusinessCodeConst.PCR0001.equals(user.getPost())) {
            throw new JeecgBootException("不是操作工,无法领取此工单!");
        }
        EamInspectionOrder eamInspectionOrder = this.getById(id);
        if (eamInspectionOrder == null) {
            return false;
        } else {
            eamInspectionOrder.setOperator(user.getUsername());
            //修改状态
            eamInspectionOrder.setInspectionStatus(InspectionStatus.UNDER_INSPECTION.name());
            this.triggerProcess(eamInspectionOrder);
            this.updateById(eamInspectionOrder);
            //更新设备保养状态
            eamEquipmentExtendService.updateEquipmentInspectionStatus(eamInspectionOrder.getEquipmentId(), EquipmentMaintenanceStatus.UNDER_INSPECTION.name());
            //推送企业微信消息
            sendQywxTemplateCardMessage(eamInspectionOrder, null);
            return true;
        }
    }
 
    /**
     * 作废点检工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean cancelInspectionOrder(String id) {
        EamInspectionOrder eamInspectionOrder = this.getById(id);
        if (eamInspectionOrder == null) {
            return false;
        } else {
            eamInspectionOrder.setInspectionStatus(InspectionStatus.ABOLISH.name());
            return updateById(eamInspectionOrder);
        }
    }
 
    /**
     * 点检流程
     *
     * @param eamInspectionOrderRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @EquipmentHistoryLog(operationTag = EquipmentOperationTagEnum.POINT_INSPECTION, businessTable = "eam_inspection_order")
    public EamInspectionOrder inspectionProcess(EamInspectionOrderRequest eamInspectionOrderRequest) {
        try {
            // 检查请求参数
            if (!isValidRequest(eamInspectionOrderRequest)) {
                throw new JeecgBootException("非法参数");
            }
 
            // 获取当前登录用户
            LoginUser user = getCurrentUser();
            if (user == null || StrUtil.isBlank(user.getId())) {
                throw new JeecgBootException("账号不存在");
            }
            eamInspectionOrderRequest.setAssignee(user.getUsername());
 
            // 获取点检工单信息
            EamInspectionOrder eamInspectionOrder = getEamInspectionOrder(eamInspectionOrderRequest.getDataId());
            if (eamInspectionOrder == null) {
                throw new JeecgBootException("未找到对应数据");
            }
 
            // 获取流程业务记录
            FlowMyBusiness flowMyBusiness = getFlowMyBusiness(eamInspectionOrderRequest.getInstanceId());
            if (flowMyBusiness == null) {
                throw new JeecgBootException("流程记录不存在");
            }
 
            // 检查用户是否有权限操作任务
            if (!isUserAuthorized(flowMyBusiness, user)) {
                throw new JeecgBootException("用户无权操作此任务");
            }
 
            // 认领任务
            if (!claimTask(flowMyBusiness.getTaskId(), user)) {
                throw new JeecgBootException("任务不存在、已完成或已被他人认领");
            }
 
            // 设置流程变量
            setupProcessVariables(eamInspectionOrderRequest, eamInspectionOrder, user);
 
            // 完成流程任务
            Result result = flowTaskService.complete(eamInspectionOrderRequest);
 
            // 根据任务完成结果更新工单状态
            updateOrderStatus(result, eamInspectionOrderRequest, eamInspectionOrder, user);
 
            // 更新工单信息
            updateEamInspectionOrder(eamInspectionOrder);
 
            //微信消息推送(工单完成不推送)
            if (!InspectionStatus.COMPLETE.name().equals(eamInspectionOrder.getInspectionStatus())) {
                sendQywxTemplateCardMessage(eamInspectionOrder, eamInspectionOrderRequest);
            }
 
            //查询数据,进行设备维修处理
            if (eamInspectionOrder.getInspectionStatus().equals(InspectionStatus.WAIT_CONFIRM.name())) {
                updateEamInspectionOrderDetail(eamInspectionOrder);
            }
 
            return eamInspectionOrder;
        } catch (Exception e) {
            throw new JeecgBootException("操作失败:" + e.getMessage());
        }
    }
 
 
    private boolean isValidRequest(EamInspectionOrderRequest request) {
        return StrUtil.isNotBlank(request.getTaskId()) && StrUtil.isNotBlank(request.getDataId());
    }
 
    private LoginUser getCurrentUser() {
        try {
            return (LoginUser) SecurityUtils.getSubject().getPrincipal();
        } catch (Exception e) {
            return null;
        }
    }
 
    private EamInspectionOrder getEamInspectionOrder(String dataId) {
        return this.getById(dataId);
    }
 
    private FlowMyBusiness getFlowMyBusiness(String instanceId) {
        List<FlowMyBusiness> businessList = flowMyBusinessService.list(
                new QueryWrapper<FlowMyBusiness>().eq("process_instance_id", instanceId));
        return businessList.isEmpty() ? null : businessList.get(0);
    }
 
    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;
    }
 
    private void setupProcessVariables(EamInspectionOrderRequest request, EamInspectionOrder order, LoginUser user) {
        Map<String, Object> values = new HashMap<>();
        if (InspectionStatus.UNDER_INSPECTION.name().equals(order.getInspectionStatus()) && user.getUsername().equals(order.getOperator())) {
            // 点检人点检结束
            String orgId = Optional.ofNullable(iEamEquipmentService.getById(order.getEquipmentId()))
                    .map(equipment -> equipment.getOrgId())
                    .orElse(null);
            if (orgId == null) {
                throw new IllegalArgumentException("未找到设备的组织 ID");
            }
            List<SysUser> sysUserList = mdcUserProductionService.queryByPostAndProId("PCR0003", orgId);
            List<String> usernameList = sysUserList.stream().map(SysUser::getUsername).collect(Collectors.toList());
            if (usernameList.isEmpty()) {
                throw new IllegalArgumentException("未找到该设备对应车间的班组长,请联系管理员处理");
            }
            values.put("dataId", order.getId());
            values.put("organization", "点检人点检结束");
            values.put("comment", "点检人点检结束");
            values.put("NextAssignee", usernameList);
            request.setComment("点检人点检结束");
        } else {
            // 班组长确认
            values.put("dataId", order.getId());
            values.put("organization", request.getConfirmComment());
            values.put("comment", request.getConfirmComment());
            values.put("confirmation", request.getConfirmDealType());
            request.setComment(request.getConfirmComment());
            if ("2".equals(request.getConfirmDealType())) {
                // 班组长驳回
                List<String> usernames = new ArrayList<>();
                usernames.add(order.getOperator());
                order.setInspectionStatus(InspectionStatus.UNDER_INSPECTION.name());
                values.put("NextAssignee", usernames);
            }
        }
        request.setValues(values);
    }
 
    private void updateOrderStatus(Result result, EamInspectionOrderRequest request, EamInspectionOrder order, LoginUser user) {
        if (result.isSuccess()) {
            if (InspectionStatus.UNDER_INSPECTION.name().equals(order.getInspectionStatus()) && StrUtil.isEmpty(request.getConfirmDealType())) {
                // 点检完成
                order.setInspectionStatus(InspectionStatus.WAIT_CONFIRM.name());
                order.setOperateTime(new Date());
                if (CollectionUtil.isNotEmpty(request.getFileList())) {
                    List<FileUploadResult> fileUploadResultList = request.getFileList();
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        String referenceFile = mapper.writeValueAsString(fileUploadResultList);
                        order.setImageFiles(referenceFile);
                    } catch (JsonProcessingException e) {
                        log.error("JSON转换失败:" + e.getMessage(), e);
                    }
                }
                eamInspectionOrderDetailService.remove(new QueryWrapper<EamInspectionOrderDetail>().eq("order_id", order.getId()));
                eamInspectionOrderDetailService.saveBatch(request.getTableDetailList());
                //更新设备保养状态
                eamEquipmentExtendService.updateEquipmentInspectionStatus(order.getEquipmentId(), EquipmentMaintenanceStatus.INSPECTION_CONFIRM.name());
            } else if (InspectionStatus.WAIT_CONFIRM.name().equals(order.getInspectionStatus()) && StrUtil.isNotEmpty(request.getConfirmDealType())) {
                // 班组长确认任务
                order.setInspectionStatus(InspectionStatus.COMPLETE.name());
                order.setConfirmUser(user.getUsername());
                order.setConfirmComment(request.getConfirmComment());
                order.setConfirmDealType(request.getConfirmDealType());
                order.setConfirmTime(new Date());
                //更新设备保养状态
                eamEquipmentExtendService.updateEquipmentInspectionStatus(order.getEquipmentId(), EquipmentMaintenanceStatus.NORMAL.name());
            }
        }
    }
 
    private void updateEamInspectionOrder(EamInspectionOrder eamInspectionOrder) {
        this.updateById(eamInspectionOrder);
    }
 
    /**
     * 设备是否存在异常,并进行设备维修
     *
     * @param eamInspectionOrder
     */
    private void updateEamInspectionOrderDetail(EamInspectionOrder eamInspectionOrder) {
        List<EamInspectionOrderDetail> eamInspectionOrderDetails = eamInspectionOrderDetailService
                .list(new QueryWrapper<EamInspectionOrderDetail>()
                        .eq("order_id", eamInspectionOrder.getId()).eq("report_flag", "1").eq("inspection_result", "2"));
        eamReportRepairService.reportRepairFromInspection(eamInspectionOrder.getEquipmentId(), eamInspectionOrder.getOperator(), eamInspectionOrderDetails);
    }
 
    /**
     * 批量作废与领取
     *
     * @param ids
     * @param type
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> batchCancelOrTakeInspectionOrder(String ids, String type) {
        if (type == null) {
            return Result.error("请选择操作类型");
        }
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> list = Arrays.asList(ids.split(","));
        QueryWrapper<EamInspectionOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", list);
        queryWrapper.eq("inspection_status", InspectionStatus.WAIT_INSPECTION.name());
        List<EamInspectionOrder> eamInspectionOrderList = this.list(queryWrapper);
        if (!eamInspectionOrderList.isEmpty()) {
            eamInspectionOrderList.forEach(eamInspectionOrder -> {
                eamInspectionOrder.setInspectionStatus(type);
                if (InspectionStatus.UNDER_INSPECTION.name().equals(type)) {
                    eamInspectionOrder.setOperator(loginUser.getUsername());
                    this.triggerProcess(eamInspectionOrder);
                    //更新设备保养状态
                    eamEquipmentExtendService.updateEquipmentInspectionStatus(eamInspectionOrder.getEquipmentId(), EquipmentMaintenanceStatus.UNDER_INSPECTION.name());
                } else {
                    eamInspectionOrder.setOperator(null);
                }
            });
            this.updateBatchById(eamInspectionOrderList);
        }
        return Result.OK("操作成功");
    }
 
 
    @Override
    public Result<?> selectVoById(String id) {
        List<EamInspectionOrder> eamInspectionOrders = this.list(new QueryWrapper<EamInspectionOrder>().eq("id", id));
        List<EamInspectionOrderRequest> eamInspectionOrderRequestList = new ArrayList<>();
        eamInspectionOrders.forEach(eamInspectionOrder -> {
            EamInspectionOrderRequest eamInspectionOrderRequest = new EamInspectionOrderRequest();
            BeanUtils.copyProperties(eamInspectionOrder, eamInspectionOrderRequest);
            List<EamInspectionOrderDetail> eamInspectionOrderDetails = eamInspectionOrderDetailService
                    .list(new QueryWrapper<EamInspectionOrderDetail>().eq("order_id", eamInspectionOrder.getId()));
            eamInspectionOrderRequest.setTableDetailList(eamInspectionOrderDetails);
            eamInspectionOrderRequestList.add(eamInspectionOrderRequest);
        });
        return Result.ok(eamInspectionOrderRequestList);
    }
 
    @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;
    }
}