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
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.TaskService;
import org.flowable.task.api.Task;
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.*;
import org.jeecg.modules.eam.entity.EamEquipment;
import org.jeecg.modules.eam.entity.EamWeekMaintenanceOrder;
import org.jeecg.modules.eam.entity.EamWeekMaintenanceOrderDetail;
import org.jeecg.modules.eam.mapper.EamWeekMaintenanceOrderMapper;
import org.jeecg.modules.eam.request.EamWeekMaintenanceQuery;
import org.jeecg.modules.eam.request.EamWeekMaintenanceRequest;
import org.jeecg.modules.eam.service.*;
import org.jeecg.modules.eam.vo.EquipmentInspectionStatistics;
import org.jeecg.modules.eam.vo.EquipmentMaintenanceStatistics;
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.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.ISysUserService;
import org.jeecg.modules.system.service.impl.ThirdAppWechatEnterpriseServiceImpl;
import org.jeecg.modules.system.vo.UserSelector;
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("IEamWeekMaintenanceOrderService")
public class EamWeekMaintenanceOrderServiceImpl extends ServiceImpl<EamWeekMaintenanceOrderMapper, EamWeekMaintenanceOrder> implements IEamWeekMaintenanceOrderService, FlowCallBackServiceI {
 
    @Resource
    private EamWeekMaintenanceOrderMapper eamWeekMaintenanceOrderMapper;
 
    @Autowired
    private IEamWeekMaintenanceOrderDetailService eamWeekMaintenanceOrderDetailService;
 
    @Autowired
    private FlowCommonService flowCommonService;
    @Autowired
    private IFlowDefinitionService flowDefinitionService;
    @Autowired
    private IFlowMyBusinessService flowMyBusinessService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IFlowTaskService flowTaskService;
 
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IEamEquipmentService eamEquipmentService;
    @Autowired
    private IEamReportRepairService eamReportRepairService;
    @Autowired
    private IEamEquipmentExtendService eamEquipmentExtendService;
    @Autowired
    private IMdcProductionService mdcProductionService;
    @Autowired
    private ThirdAppWechatEnterpriseServiceImpl wechatEnterpriseService;
 
    @Value("${wechatEnterprise.cardActionUrl}")
    private String cardActionUrl;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addWeekMaintenance(EamWeekMaintenanceRequest request) {
        EamEquipment equipment = eamEquipmentService.getById(request.getEquipmentId());
        if (equipment == null) {
            throw new JeecgBootException("设备不存在,添加失败!");
        }
        EamWeekMaintenanceOrder order = new EamWeekMaintenanceOrder();
        order.setOrderNum(request.getOrderNum());
        order.setEquipmentId(request.getEquipmentId());
        order.setStandardId(request.getStandardId());
        order.setMaintenanceDate(request.getMaintenanceDate());
        order.setOperator(request.getOperator());
        order.setRemark(request.getRemark());
        //状态初始化
        order.setMaintenanceStatus(WeekMaintenanceStatusEnum.WAIT_MAINTENANCE.name());
        order.setCreationMethod(request.getCreationMethod());
        //删除标记
        order.setDelFlag(CommonConstant.DEL_FLAG_0);
        eamWeekMaintenanceOrderMapper.insert(order);
        //处理明细数据
        if (CollectionUtil.isNotEmpty(request.getTableDetailList())) {
            request.getTableDetailList().forEach(tableDetail -> {
                tableDetail.setId(null);
                tableDetail.setOrderId(order.getId());
            });
            eamWeekMaintenanceOrderDetailService.saveBatch(request.getTableDetailList());
        }
        //判断是否存在保养人 如果存在则启动流程
        if (StringUtils.isNotBlank(order.getOperator())) {
            //启动流程
            flowCommonService.initActBusiness("工单号: " + order.getOrderNum() + ";设备编号: " + equipment.getEquipmentCode() + ";安装位置: " + equipment.getInstallationPosition(),
                    order.getId(), "IEamWeekMaintenanceOrderService", "week_maintenance_process", null);
            Map<String, Object> variables = new HashMap<>();
            variables.put("dataId", order.getId());
            if (StrUtil.isEmpty(order.getRemark())) {
                variables.put("organization", "新增周保工单默认启动流程");
                variables.put("comment", "新增周保工单默认启动流程");
            } else {
                variables.put("organization", order.getRemark());
                variables.put("comment", order.getRemark());
            }
            variables.put("proofreading", true);
            List<String> usernames = new ArrayList<>();
            usernames.add(order.getOperator());
            variables.put("NextAssignee", usernames);
            Result result = flowDefinitionService.startProcessInstanceByKey("week_maintenance_process", variables);
            if (result != null) {
                //更新周保状态
                order.setMaintenanceStatus(WeekMaintenanceStatusEnum.UNDER_MAINTENANCE.name());
                order.setActualStartTime(new Date());
                eamWeekMaintenanceOrderMapper.updateById(order);
                //更新设备保养状态
                eamEquipmentExtendService.updateEquipmentMaintenanceStatus(order.getEquipmentId(), EquipmentMaintenanceStatus.UNDER_MAINTENANCE.name());
                //推送企业微信消息
                sendQywxTemplateCardMessage(order, null);
                return result.isSuccess();
            }
        }
 
        return true;
    }
 
    @Override
    public IPage<EamWeekMaintenanceOrder> queryPageList(Page<EamWeekMaintenanceOrder> page, EamWeekMaintenanceQuery query) {
        QueryWrapper<EamWeekMaintenanceOrder> 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.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.getRandomInspectionFlag())) {
                if(CommonConstant.DEFAULT_1.equals(query.getRandomInspectionFlag())) {
                    queryWrapper.eq("wmo.random_inspection_flag", CommonConstant.DEFAULT_1);
                }else {
                    queryWrapper.and(q -> q.eq("wmo.random_inspection_flag", CommonConstant.DEFAULT_0).or().isNull("wmo.random_inspection_flag"));
                }
            }
            if(StringUtils.isNotBlank(query.getFinalRandomInspectionFlag())) {
                if(CommonConstant.DEFAULT_1.equals(query.getFinalRandomInspectionFlag())) {
                    queryWrapper.eq("wmo.final_random_inspection_flag", CommonConstant.DEFAULT_1);
                }else {
                    queryWrapper.and(q -> q.eq("wmo.final_random_inspection_flag", CommonConstant.DEFAULT_0).or().isNull("wmo.final_random_inspection_flag"));
                }
            }
            //排序
            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 eamWeekMaintenanceOrderMapper.queryPageList(page, queryWrapper);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editWeekMaintenance(EamWeekMaintenanceRequest request) {
        EamEquipment equipment = eamEquipmentService.getById(request.getEquipmentId());
        if (equipment == null) {
            throw new JeecgBootException("设备不存在,添加失败!");
        }
        EamWeekMaintenanceOrder entity = eamWeekMaintenanceOrderMapper.selectById(request.getId());
        if (entity == null) {
            throw new JeecgBootException("编辑的数据已删除,请刷新重试!");
        }
        if (!WeekMaintenanceStatusEnum.WAIT_MAINTENANCE.name().equals(entity.getMaintenanceStatus())) {
            throw new JeecgBootException("只有待保养状态的数据才可编辑!");
        }
        entity.setMaintenanceDate(request.getMaintenanceDate());
        entity.setOperator(request.getOperator());
        entity.setRemark(request.getRemark());
 
        eamWeekMaintenanceOrderMapper.updateById(entity);
        //处理详情
        if (CollectionUtil.isNotEmpty(request.getTableDetailList())) {
            List<EamWeekMaintenanceOrderDetail> addList = new ArrayList<>();
            List<EamWeekMaintenanceOrderDetail> updateList = new ArrayList<>();
            request.getTableDetailList().forEach(tableDetail -> {
                tableDetail.setOrderId(entity.getId());
                if (tableDetail.getId() == null) {
                    addList.add(tableDetail);
                } else {
                    updateList.add(tableDetail);
                }
            });
            if (CollectionUtil.isNotEmpty(addList)) {
                eamWeekMaintenanceOrderDetailService.saveBatch(addList);
            }
            if (CollectionUtil.isNotEmpty(updateList)) {
                eamWeekMaintenanceOrderDetailService.updateBatchById(updateList);
            }
        }
        if (CollectionUtil.isNotEmpty(request.getRemoveDetailList())) {
            List<String> ids = request.getRemoveDetailList().stream().map(EamWeekMaintenanceOrderDetail::getId).collect(Collectors.toList());
            eamWeekMaintenanceOrderDetailService.removeBatchByIds(ids);
        }
        //判断是否存在保养人 如果存在则启动流程
        if (StringUtils.isNotBlank(entity.getOperator())) {
            //启动流程
            flowCommonService.initActBusiness("工单号: " + entity.getOrderNum() + ";设备编号: " + equipment.getEquipmentCode() + ";安装位置: " + equipment.getInstallationPosition(),
                    entity.getId(), "IEamWeekMaintenanceOrderService", "week_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("week_maintenance_process", variables);
            if (result != null) {
                //更新周保状态
                entity.setMaintenanceStatus(WeekMaintenanceStatusEnum.UNDER_MAINTENANCE.name());
                entity.setActualStartTime(new Date());
                eamWeekMaintenanceOrderMapper.updateById(entity);
                //更新设备保养状态
                eamEquipmentExtendService.updateEquipmentMaintenanceStatus(entity.getEquipmentId(), EquipmentMaintenanceStatus.UNDER_MAINTENANCE.name());
                return result.isSuccess();
            }
 
        }
        return true;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean collect(String id) {
        EamWeekMaintenanceOrder entity = eamWeekMaintenanceOrderMapper.selectById(id);
        if (entity == null) {
            throw new JeecgBootException("要领取的工单不存在,请刷新重试!");
        }
        if (!WeekMaintenanceStatusEnum.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 || !BusinessCodeConst.PCR0001.equals(sysUser.getPost())) {
            throw new JeecgBootException("不是操作工,无法领取此工单!");
        }
        entity.setOperator(sysUser.getUsername());
        entity.setMaintenanceStatus(WeekMaintenanceStatusEnum.UNDER_MAINTENANCE.name());
        entity.setActualStartTime(new Date());
        eamWeekMaintenanceOrderMapper.updateById(entity);
 
        //启动流程
        flowCommonService.initActBusiness("工单号: " + entity.getOrderNum() + ";设备编号: " + equipment.getEquipmentCode() + ";安装位置: " + equipment.getInstallationPosition(),
                entity.getId(), "IEamWeekMaintenanceOrderService", "week_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("week_maintenance_process", variables);
        if (result != null) {
            //更新设备保养状态
            eamEquipmentExtendService.updateEquipmentMaintenanceStatus(entity.getEquipmentId(), EquipmentMaintenanceStatus.UNDER_MAINTENANCE.name());
            //推送企业微信消息
            sendQywxTemplateCardMessage(entity, null);
            return result.isSuccess();
        }
        return true;
    }
 
    private void sendQywxTemplateCardMessage(EamWeekMaintenanceOrder order, EamWeekMaintenanceRequest request) {
        TemplateCard templateCard = new TemplateCard();
        EamEquipment equipment = eamEquipmentService.getById(order.getEquipmentId());
        order.setEquipmentCode(equipment.getEquipmentCode());
        String maintenanceStatus = order.getMaintenanceStatus();
        if (WeekMaintenanceStatusEnum.UNDER_MAINTENANCE.name().equals(maintenanceStatus)) {
            //工单保养中,推送消息给保养人(新增工单时指定、保养人领取)
            String operator = order.getOperator();
            String touser = wechatEnterpriseService.getTouser(operator, false);
            templateCard.setTouser(touser);
        }
        if (WeekMaintenanceStatusEnum.WAIT_CONFIRM.name().equals(maintenanceStatus)
                || WeekMaintenanceStatusEnum.WAIT_INITIAL_ACCEPTANCE.name().equals(maintenanceStatus)
                || WeekMaintenanceStatusEnum.WAIT_FINAL_ACCEPTANCE.name().equals(maintenanceStatus)) {
            //工单已保养完成待确认,推送消息给班组长
            //班组长已确认,推送消息给设备管理员确认
            //设备管理员已确认,推送给设能部管理员确认
            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);
        }
 
        TemplateCardEntity templateCardEntity = new TemplateCardEntity();
        templateCard.setTemplate_card(templateCardEntity);
        templateCardEntity.setTask_id(order.getId());
        TemplateCardEntity.MainTitle mainTitle = new TemplateCardEntity.MainTitle();
        mainTitle.setTitle("设备周保");
        templateCardEntity.setMain_title(mainTitle);
 
        if (WeekMaintenanceStatusEnum.UNDER_MAINTENANCE.name().equals(maintenanceStatus)) {
            if (Objects.nonNull(request) && StrUtil.isNotBlank(request.getConfirmDealType())) {
                templateCardEntity.setSub_title_text("工单: " + order.getOrderNum() + " 被驳回,请重新执行保养后提交");
            } else {
                templateCardEntity.setSub_title_text("已领取周保工单: " + order.getOrderNum() + ",开始进行保养");
            }
        }
        if (WeekMaintenanceStatusEnum.WAIT_CONFIRM.name().equals(maintenanceStatus)) {
            templateCardEntity.setSub_title_text("工单: " + order.getOrderNum() + " 已保养完成,请进入系统确认");
        }
        if (WeekMaintenanceStatusEnum.WAIT_INITIAL_ACCEPTANCE.name().equals(maintenanceStatus)) {
            templateCardEntity.setSub_title_text("工单: " + order.getOrderNum() + " 已保养完成,请进入系统进行初验收");
        }
        if (WeekMaintenanceStatusEnum.WAIT_FINAL_ACCEPTANCE.name().equals(maintenanceStatus)) {
            templateCardEntity.setSub_title_text("工单: " + order.getOrderNum() + " 已完成初验收,请进入系统进行终验收");
        }
 
        List<TemplateCardEntity.HorizontalContent> horizontalContentList = CollectionUtil.newArrayList();
        TemplateCardEntity.HorizontalContent content1 = new TemplateCardEntity.HorizontalContent();
        content1.setKeyname("工单号");
        content1.setValue(order.getOrderNum());
        horizontalContentList.add(content1);
        TemplateCardEntity.HorizontalContent content2 = new TemplateCardEntity.HorizontalContent();
        content2.setKeyname("设备编号");
        content2.setValue(order.getEquipmentCode());
        horizontalContentList.add(content2);
 
        //如果工单状态为待保养(没指定保养人的未领取状态),流程是没有启动的,无法获取节点信息
        if (!WeekMaintenanceStatusEnum.WAIT_MAINTENANCE.name().equals(maintenanceStatus)) {
            WorkTaskDataVo previousFlowInfo = flowTaskService.getPreviousFlowInfo(order.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 (WeekMaintenanceStatusEnum.COMPLETE.name().equals(maintenanceStatus)) {
                content4.setValue("已完成");
            } else {
                content4.setValue(previousFlowInfo.getName());
            }
            horizontalContentList.add(content4);
        }
 
        if (WeekMaintenanceStatusEnum.UNDER_MAINTENANCE.name().equals(maintenanceStatus)) {
            if (Objects.isNull(request)) {
                //新增的工单(指定了保养人)、新领取的工单
                TemplateCardEntity.HorizontalContent content = new TemplateCardEntity.HorizontalContent();
                content.setKeyname("发起人");
                SysUser sysUser = sysUserService.getUserByName(order.getCreateBy());
                content.setValue(sysUser.getRealname());
                horizontalContentList.add(content);
            } else {
                //被驳回的工单
                TemplateCardEntity.HorizontalContent content3 = new TemplateCardEntity.HorizontalContent();
                TemplateCardEntity.HorizontalContent content4 = new TemplateCardEntity.HorizontalContent();
                String confirmAssign = request.getAssignee();
                SysUser confirmUser = sysUserService.getUserByName(confirmAssign);
                content3.setKeyname("确认人");
                content3.setValue(confirmUser.getRealname());
                horizontalContentList.add(content3);
                content4.setKeyname("确认意见");
                content4.setValue("驳回");
                horizontalContentList.add(content4);
            }
        }
        if (WeekMaintenanceStatusEnum.WAIT_CONFIRM.name().equals(maintenanceStatus)) {
            TemplateCardEntity.HorizontalContent content = new TemplateCardEntity.HorizontalContent();
            content.setKeyname("保养人");
            SysUser sysUser = sysUserService.getUserByName(order.getOperator());
            content.setValue(sysUser.getRealname());
            horizontalContentList.add(content);
            //TemplateCardEntity.HorizontalContent content = new TemplateCardEntity.HorizontalContent();
            //List<String> nextAssignee = (List<String>) request.getValues().get("NextAssignee");
            //String realNameStr = sysUserService.getRealNameStrByUserNameList(nextAssignee);
            //content.setKeyname("确认人");
            //content.setValue(realNameStr);
            //horizontalContentList.add(content);
        }
        if (WeekMaintenanceStatusEnum.WAIT_INITIAL_ACCEPTANCE.name().equals(maintenanceStatus)) {
            TemplateCardEntity.HorizontalContent content3 = new TemplateCardEntity.HorizontalContent();
            //TemplateCardEntity.HorizontalContent content4 = new TemplateCardEntity.HorizontalContent();
            String confirmAssignee = request.getAssignee();
            SysUser confirmUser = sysUserService.getUserByName(confirmAssignee);
            content3.setKeyname("确认人");
            content3.setValue(confirmUser.getRealname());
            horizontalContentList.add(content3);
            //List<String> nextAssignee = (List<String>) request.getValues().get("NextAssignee");
            //String realNameStr = sysUserService.getRealNameStrByUserNameList(nextAssignee);
            //content4.setKeyname("初验人");
            //content4.setValue(realNameStr);
            //horizontalContentList.add(content4);
        }
        if (WeekMaintenanceStatusEnum.WAIT_FINAL_ACCEPTANCE.name().equals(maintenanceStatus)) {
            TemplateCardEntity.HorizontalContent content3 = new TemplateCardEntity.HorizontalContent();
            //TemplateCardEntity.HorizontalContent content4 = new TemplateCardEntity.HorizontalContent();
            String initialAssignee = request.getAssignee();
            SysUser initialUser = sysUserService.getUserByName(initialAssignee);
            content3.setKeyname("初验人");
            content3.setValue(initialUser.getRealname());
            horizontalContentList.add(content3);
            //List<String> nextAssignee = (List<String>) request.getValues().get("NextAssignee");
            //String realNameStr = sysUserService.getRealNameStrByUserNameList(nextAssignee);
            //content4.setKeyname("终验人");
            //content4.setValue(realNameStr);
            //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);
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    @EquipmentHistoryLog(operationTag = EquipmentOperationTagEnum.WEEK_MAINTENANCE, businessTable = "eam_week_maintenance_order")
    public EamWeekMaintenanceOrder approval(EamWeekMaintenanceRequest request) {
        EamWeekMaintenanceOrder entity = eamWeekMaintenanceOrderMapper.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());
        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("设备不存在,请检查!");
        }
 
        WeekMaintenanceStatusEnum status = WeekMaintenanceStatusEnum.getInstance(entity.getMaintenanceStatus());
        if (status == null) {
            return null;
        }
        //流程变量
        Map<String, Object> values = new HashMap<>();
        switch (status) {
            case UNDER_MAINTENANCE:
                //执行完成
                List<UserSelector> userSelectors = sysUserService.selectOperatorList(equipment.getEquipmentCode(), equipment.getOrgId(), BusinessCodeConst.PCR0003);
                if (CollectionUtil.isEmpty(userSelectors)) {
                    throw new JeecgBootException("设备未分配给班组长,无法进入下级审批!");
                }
                List<String> userApprovalList = userSelectors.stream().map(UserSelector::getUsername).collect(Collectors.toList());
                values.put("dataId", entity.getId());
                values.put("organization", "周保执行结束");
                values.put("comment", "周保执行结束");
                values.put("NextAssignee", userApprovalList);
                request.setComment("周保执行结束");
                //设置entity
                entity.setMaintenanceStatus(WeekMaintenanceStatusEnum.WAIT_CONFIRM.name());
                entity.setActualEndTime(new Date());
                //处理附件
                if (CollectionUtil.isNotEmpty(request.getImageFilesResult())) {
                    List<FileUploadResult> fileUploadResultList = request.getImageFilesResult();
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        String referenceFile = mapper.writeValueAsString(fileUploadResultList);
                        entity.setImageFiles(referenceFile);
                    } catch (JsonProcessingException e) {
                        log.error("JSON转换失败:" + e.getMessage(), e);
                    }
                }
                //处理详情
                if (CollectionUtil.isNotEmpty(request.getTableDetailList())) {
                    eamWeekMaintenanceOrderDetailService.updateBatchById(request.getTableDetailList());
                }
                //更新设备保养状态
                eamEquipmentExtendService.updateEquipmentMaintenanceStatus(entity.getEquipmentId(), EquipmentMaintenanceStatus.WAIT_CONFIRM.name());
                break;
            case WAIT_CONFIRM:
                if (StringUtils.isBlank(equipment.getEquipmentManager())) {
                    throw new JeecgBootException("设备未分配设备管理员,无法进入下级审批!");
                }
                //班组长确认
                userApprovalList = new ArrayList<>();
                userApprovalList.add(equipment.getEquipmentManager());
                values.put("dataId", entity.getId());
                values.put("organization", request.getConfirmComment());
                values.put("comment", request.getConfirmComment());
                values.put("NextAssignee", userApprovalList);
                values.put("confirmation", request.getConfirmDealType());
                request.setComment(request.getConfirmComment());
                //设置entity
                entity.setMaintenanceStatus(WeekMaintenanceStatusEnum.WAIT_INITIAL_ACCEPTANCE.name());
                entity.setConfirmUser(user.getUsername());
                entity.setConfirmComment(request.getConfirmComment());
                entity.setConfirmTime(new Date());
                entity.setConfirmDealType(request.getConfirmDealType());
                if (CommonConstant.HAS_CANCLE.equals(request.getConfirmDealType())) {
                    //驳回
                    userApprovalList = new ArrayList<>();
                    userApprovalList.add(entity.getOperator());
                    values.put("NextAssignee", userApprovalList);
                    entity.setMaintenanceStatus(WeekMaintenanceStatusEnum.UNDER_MAINTENANCE.name());
                }
                //处理报修
                List<EamWeekMaintenanceOrderDetail> collect = request.getTableDetailList().stream().filter((detail) -> CommonConstant.DEFAULT_1.equals(detail.getReportFlag())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collect)) {
                    eamReportRepairService.reportRepairFromMaintenance(equipment.getId(), entity.getOperator(), collect);
                }
                break;
            case WAIT_INITIAL_ACCEPTANCE:
                userSelectors = sysUserService.selectOperatorList(equipment.getEquipmentCode(), equipment.getOrgId(), BusinessCodeConst.PCR0005);
                if (CollectionUtil.isEmpty(userSelectors)) {
                    throw new JeecgBootException("设备未分配给设能部管理员,无法进入下级审批!");
                }
                userApprovalList = userSelectors.stream().map(UserSelector::getUsername).collect(Collectors.toList());
                values.put("dataId", entity.getId());
                values.put("organization", request.getInitialAcceptanceComment());
                values.put("comment", request.getInitialAcceptanceComment());
                values.put("NextAssignee", userApprovalList);
                request.setComment(request.getInitialAcceptanceComment());
                //设置entity
                entity.setMaintenanceStatus(WeekMaintenanceStatusEnum.WAIT_FINAL_ACCEPTANCE.name());
                entity.setInitialAcceptanceUser(user.getUsername());
                entity.setInitialAcceptanceComment(request.getInitialAcceptanceComment());
                entity.setInitialAcceptanceTime(new Date());
                entity.setRandomInspectionFlag(request.getRandomInspectionFlag());
                //处理附件
                if (CollectionUtil.isNotEmpty(request.getInitialAcceptanceFilesResult())) {
                    List<FileUploadResult> fileUploadResultList = request.getInitialAcceptanceFilesResult();
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        String referenceFile = mapper.writeValueAsString(fileUploadResultList);
                        entity.setInitialAcceptanceFiles(referenceFile);
                    } catch (JsonProcessingException e) {
                        log.error("JSON转换失败:" + e.getMessage(), e);
                    }
                }
                break;
            case WAIT_FINAL_ACCEPTANCE:
                values.put("dataId", entity.getId());
                values.put("organization", request.getFinalAcceptanceComment());
                values.put("comment", request.getFinalAcceptanceComment());
                request.setComment(request.getFinalAcceptanceComment());
                //设置entity
                entity.setMaintenanceStatus(WeekMaintenanceStatusEnum.COMPLETE.name());
                entity.setFinalAcceptanceUser(user.getUsername());
                entity.setFinalAcceptanceComment(request.getFinalAcceptanceComment());
                entity.setFinalAcceptanceTime(new Date());
                entity.setFinalRandomInspectionFlag(request.getFinalRandomInspectionFlag());
                //处理附件
                if (CollectionUtil.isNotEmpty(request.getFinalAcceptanceFilesResult())) {
                    List<FileUploadResult> fileUploadResultList = request.getFinalAcceptanceFilesResult();
                    ObjectMapper mapper = new ObjectMapper();
                    try {
                        String referenceFile = mapper.writeValueAsString(fileUploadResultList);
                        entity.setFinalAcceptanceFiles(referenceFile);
                    } catch (JsonProcessingException e) {
                        log.error("JSON转换失败:" + e.getMessage(), e);
                    }
                }
                //更新设备保养状态
                eamEquipmentExtendService.updateEquipmentMaintenanceStatus(entity.getEquipmentId(), EquipmentMaintenanceStatus.NORMAL.name());
                break;
        }
        request.setValues(values);
 
        // 完成流程任务
        Result result = flowTaskService.complete(request);
        if (!result.isSuccess()) {
            throw new JeecgBootException("审批失败,请刷新查看!");
        }
        //保存工单
        eamWeekMaintenanceOrderMapper.updateById(entity);
        //推送企业微信消息,工单完结不发送
        if (!WeekMaintenanceStatusEnum.COMPLETE.name().equals(entity.getMaintenanceStatus())) {
            sendQywxTemplateCardMessage(entity, request);
        }
        return entity;
    }
 
    @Override
    public List<EamWeekMaintenanceOrder> selectUnCompleteOrder(String expiredDate) {
        LambdaQueryWrapper<EamWeekMaintenanceOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.lt(EamWeekMaintenanceOrder::getMaintenanceDate, expiredDate);
        List<String> unCompleteStatus = new ArrayList<>();
        unCompleteStatus.add(WeekMaintenanceStatusEnum.WAIT_MAINTENANCE.name());
        unCompleteStatus.add(WeekMaintenanceStatusEnum.UNDER_MAINTENANCE.name());
        queryWrapper.in(EamWeekMaintenanceOrder::getMaintenanceStatus, unCompleteStatus);
        queryWrapper.orderByAsc(EamWeekMaintenanceOrder::getMaintenanceDate);
        return eamWeekMaintenanceOrderMapper.selectList(queryWrapper);
    }
 
    @Override
    public List<EquipmentMaintenanceStatistics> equipmentMaintenanceStatistics(String productionId, LocalDate firstOfMonth, LocalDate today) {
        if (StringUtils.isNotBlank(productionId)) {
            //车间编码不为空
            List<String> productIds = mdcProductionService.recursionChildren(productionId);
            if (CollectionUtil.isEmpty(productIds)) {
                return Collections.emptyList();
            }
            List<EquipmentMaintenanceStatistics> list = this.baseMapper.equipmentMaintenanceStatistics(productIds, firstOfMonth.toString(), today.plusDays(1).toString());
            if (CollectionUtil.isEmpty(list)) {
                return Collections.emptyList();
            }
            return list;
        }
        List<EquipmentMaintenanceStatistics> list = this.baseMapper.equipmentMaintenanceStatistics(null, firstOfMonth.toString(), today.plusDays(1).toString());
        if (CollectionUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list;
    }
 
    @Override
    public List<EamWeekMaintenanceOrder> selectUnReceivedMaintenanceOrder() {
        return this.baseMapper.selectUnReceivedMaintenanceOrder();
    }
 
    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;
    }
}