ny
23 小时以前 b6f169fe43a2b13f351aefc152374fc7f0bc8cb7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
package jnpf.flowable.service.impl;
 
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
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.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import jnpf.base.UserInfo;
import jnpf.base.entity.DictionaryDataEntity;
import jnpf.base.entity.SystemEntity;
import jnpf.base.entity.VisualdevEntity;
import jnpf.base.model.base.SystemBaeModel;
import jnpf.base.service.SuperServiceImpl;
import jnpf.constant.AuthorizeConst;
import jnpf.constant.MsgCode;
import jnpf.exception.WorkFlowException;
import jnpf.flowable.entity.*;
import jnpf.flowable.enums.NodeEnum;
import jnpf.flowable.enums.TemplateStatueEnum;
import jnpf.flowable.mapper.*;
import jnpf.flowable.model.template.*;
import jnpf.flowable.model.templatejson.FlowFormModel;
import jnpf.flowable.model.templatejson.TemplateJsonExportModel;
import jnpf.flowable.model.templatenode.TemplateNodeUpFrom;
import jnpf.flowable.model.util.FlowNature;
import jnpf.flowable.service.TemplateService;
import jnpf.flowable.util.FlowUtil;
import jnpf.flowable.util.ServiceUtil;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.model.authorize.AuthorizeVO;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import jnpf.util.context.RequestContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.util.*;
import java.util.stream.Collectors;
 
@Service
public class TemplateServiceImpl extends SuperServiceImpl<TemplateMapper, TemplateEntity> implements TemplateService {
 
 
    @Autowired
    private FlowUtil flowUtil;
    @Autowired
    private ServiceUtil serviceUtil;
 
    @Autowired
    private TemplateJsonMapper templateJsonMapper;
    @Autowired
    private TemplateNodeMapper templateNodeMapper;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private TriggerTaskMapper triggerTaskMapper;
    @Autowired
    private TemplateUseNumMapper templateUseNumMapper;
 
    @Override
    public List<TemplateEntity> getList(TemplatePagination pagination) {
        return this.baseMapper.getList(pagination);
    }
 
    @Override
    public List<TemplatePageVo> getSelector(TemplatePagination pagination) {
        // 流程权限
        Set<String> flowId = new HashSet<>();
        String userId = UserProvider.getLoginUserId();
        if (StringUtil.isNotBlank(pagination.getDelegateUser())) {
            userId = pagination.getDelegateUser();
        }
 
        boolean isDelegate = ObjectUtil.equals(pagination.getIsDelegate(), 1);
        boolean isAuthority = ObjectUtil.equals(pagination.getIsAuthority(), 1);
        boolean isLaunch = ObjectUtil.equals(pagination.getIsLaunch(), 1);
        boolean isSystemFrom = ObjectUtil.equals(pagination.getIsSystemFrom(), 1);
 
        //委托流程的数据
        boolean isEntrust = StringUtils.equals("-1", pagination.getSystemId());
        //当前用户
        AuthorizeVO authorizeByUser = serviceUtil.getAuthorizeByUser();
        // 权限
        boolean commonUser = serviceUtil.isCommonUser(userId);
        if (commonUser) {
            if (isDelegate || isAuthority) {
                flowId.addAll(authorizeByUser.getFlowIdList());
            }
        }
 
        List<String> flowList = new ArrayList<>();
        List<DelegateEntity> delegateEntityList = flowUtil.getByToUserId(userId, 0);
        //获取委托
        for (DelegateEntity delegate : delegateEntityList) {
            List<String> launchPermission = serviceUtil.getPermission(delegate.getUserId());
            if (StringUtil.isNotEmpty(delegate.getFlowId())) {
                QueryWrapper<TemplateEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().in(TemplateEntity::getId, Arrays.asList(delegate.getFlowId().split(",")));
                List<TemplateEntity> list = this.list(queryWrapper);
                //用户拥有权限
                List<String> authoirtyList = list.stream().filter(e -> ObjectUtil.equals(e.getVisibleType(), FlowNature.Authority)).map(TemplateEntity::getId).collect(Collectors.toList());
                launchPermission.retainAll(authoirtyList);
                flowList.addAll(launchPermission);
                //发起列表显示,委托列表不显示
                if (!isDelegate) {
                    flowId.addAll(launchPermission);
                }
                //公开授权
                List<String> flowIdList = list.stream().map(TemplateEntity::getId).collect(Collectors.toList());
                flowIdList.removeAll(authoirtyList);
                flowList.addAll(flowIdList);
            } else {
                List<String> system = serviceUtil.getPermission(delegate.getUserId(), AuthorizeConst.SYSTEM);
                if (system.isEmpty()) {
                    continue;
                }
                QueryWrapper<TemplateEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().in(TemplateEntity::getSystemId, system)
                        .eq(TemplateEntity::getVisibleType, FlowNature.All);
                List<TemplateEntity> list = this.list(queryWrapper);
                List<String> flowIdList = list.stream().map(TemplateEntity::getId).collect(Collectors.toList());
                flowList.addAll(flowIdList);
                //发起列表显示,委托列表不显示
                if (!isDelegate) {
                    flowId.addAll(launchPermission);
                }
            }
        }
 
        MPJLambdaWrapper<TemplateEntity> wrapper = JoinWrappers.lambda(TemplateEntity.class)
                .selectAll(TemplateEntity.class)
                .eq(TemplateEntity::getEnabledMark, 1).ne(TemplateEntity::getType, FlowNature.Quest)
                .eq(TemplateEntity::getStatus, TemplateStatueEnum.up.getCode());
 
        //关键字(流程名称、流程编码)
        String keyWord = pagination.getKeyword();
        if (ObjectUtil.isNotEmpty(keyWord)) {
            wrapper.and(t -> t.like(TemplateEntity::getEnCode, keyWord).or().like(TemplateEntity::getFullName, keyWord));
        }
        //流程显示类型
        if (isLaunch) {
            List<Integer> typeList = ImmutableList.of(FlowNature.AllShowType, FlowNature.FlowShowType);
            wrapper.in(TemplateEntity::getShowType, typeList);
        }
 
        List<String> systemIdList = authorizeByUser.getSystemList().stream().filter(t -> !Objects.equals(t.getIsMain(), 1)).map(SystemBaeModel::getId).collect(Collectors.toList());
        if (isEntrust) {
            if (flowList.isEmpty()) {
                return new ArrayList<>();
            }
 
            List<List<String>> lists = Lists.partition(flowList, 1000);
            wrapper.and(t -> {
                for (List<String> list : lists) {
                    t.in(TemplateEntity::getId, list).or();
                }
            });
 
            wrapper.notIn(!systemIdList.isEmpty(), TemplateEntity::getSystemId, systemIdList);
        } else {
            //应用主建
            String systemId = pagination.getSystemId();
            if (ObjectUtil.isNotEmpty(systemId)) {
                systemIdList.retainAll(Arrays.asList(systemId.split(",")));
            }
 
            if (systemIdList.isEmpty()) {
                return new ArrayList<>();
            }
 
            if (isAuthority) {
                if (commonUser) {
                    wrapper.and(t -> t.eq(TemplateEntity::getVisibleType, FlowNature.All)
                            .or().in(!flowId.isEmpty(), TemplateEntity::getId, flowId)
                    );
                }
            }
 
            wrapper.in(TemplateEntity::getSystemId, systemIdList);
            //所属分类
            String category = pagination.getCategory();
            if (ObjectUtil.isNotEmpty(category)) {
                if (StringUtil.equals(category, "commonFlow")) {
                    wrapper.leftJoin(CommonEntity.class, CommonEntity::getFlowId, TemplateJsonEntity::getId)
                            .eq(CommonEntity::getCreatorUserId, userId).isNotNull(CommonEntity::getFlowId);
                } else {
                    wrapper.in(TemplateEntity::getCategory, Arrays.asList(category.split(",")));
                }
            }
        }
        wrapper.orderByAsc(TemplateEntity::getSortCode).orderByDesc(TemplateEntity::getCreatorTime);
        Page<TemplatePageVo> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<TemplatePageVo> userPage = this.selectJoinListPage(page, TemplatePageVo.class, wrapper);
 
        List<TemplatePageVo> records = userPage.getRecords();
        // 设置常用流程标识
        List<CommonEntity> commonList = commonMapper.getCommonByUserId(userId);
        if (CollectionUtil.isNotEmpty(commonList)) {
            List<String> flowIds = commonList.stream().map(CommonEntity::getFlowId).distinct().collect(Collectors.toList());
            for (TemplatePageVo record : records) {
                if (flowIds.contains(record.getId())) {
                    record.setIsCommonFlow(true);
                }
            }
        }
 
        //判断流程的表单类型
        if (isSystemFrom) {
            List<String> flowIdList = records.stream().map(TemplatePageVo::getFlowId).collect(Collectors.toList());
            List<TemplateNodeEntity> list = templateNodeMapper.getList(flowIdList, NodeEnum.start.getType());
            Map<String, String> formMap = new HashMap<>();
            for (TemplateNodeEntity entity : list) {
                formMap.put(entity.getFlowId(), entity.getFormId());
            }
            List<String> formList = serviceUtil.getFormList(new ArrayList<>(formMap.values())).stream().filter(e -> Objects.equals(e.getType(), 2)).map(VisualdevEntity::getId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(formList)) {
                for (TemplatePageVo record : records) {
                    String formId = formMap.get(record.getFlowId());
                    if (formList.contains(formId)) {
                        record.setIsQuote(1);
                    }
                }
            }
        }
        return pagination.setData(records, page.getTotal());
    }
 
    @Override
    public List<TemplateTreeListVo> getTreeCommon() {
        String userId = UserProvider.getLoginUserId();
        List<TemplateTreeListVo> vos = new ArrayList<>();
        List<CommonEntity> commonList = commonMapper.getCommonByUserId(userId);
        if (CollectionUtil.isEmpty(commonList)) {
            return vos;
        }
        String systemCodeById = serviceUtil.getSystemCodeById(RequestContext.getAppCode());
        List<String> flowIds = commonList.stream().map(CommonEntity::getFlowId).collect(Collectors.toList());
        List<TemplateEntity> templateList = this.getList(flowIds);
        if (StringUtil.isNotEmpty(systemCodeById)) {
            templateList = templateList.stream().filter(e -> Objects.equals(e.getSystemId(), systemCodeById)).collect(Collectors.toList());
        }
        if (CollectionUtil.isNotEmpty(templateList)) {
            TemplateTreeListVo allVo = new TemplateTreeListVo();
            allVo.setId(RandomUtil.uuId());
            allVo.setFullName("全部流程");
            List<TemplateTreeListVo> childrenList = new ArrayList<>();
            for (TemplateEntity template : templateList) {
                TemplateTreeListVo vo = JsonUtil.getJsonToBean(template, TemplateTreeListVo.class);
                childrenList.add(vo);
            }
            allVo.setChildren(childrenList);
            vos.add(allVo);
 
            Map<String, List<TemplateTreeListVo>> map = childrenList.stream().collect(Collectors.groupingBy(TemplateTreeListVo::getCategory));
            List<String> categoryIds = new ArrayList<>(map.keySet());
 
            List<DictionaryDataEntity> dictionNameList = serviceUtil.getDictionName(categoryIds);
            for (DictionaryDataEntity dict : dictionNameList) {
                TemplateTreeListVo vo = new TemplateTreeListVo();
                vo.setId(dict.getId());
                vo.setFullName(dict.getFullName());
                vo.setChildren(map.get(dict.getId()));
                vos.add(vo);
            }
        }
        return vos;
    }
 
    @Override
    public List<TemplateTreeListVo> treeList(Integer formType) {
        List<DictionaryDataEntity> dictionList = serviceUtil.getDiList();
 
        TemplatePagination pagination = new TemplatePagination();
        pagination.setSystemId(serviceUtil.getSystemCodeById(RequestContext.getAppCode()));
        List<TemplateEntity> list = getListAll(pagination, false);
 
        List<TemplateNodeEntity> startNodeList;
        // formType 1.系统表单  2.在线开发表单
        if (null != formType) {
            // 版本主键
            List<String> flowIds = list.stream().map(TemplateEntity::getFlowId).collect(Collectors.toList());
            startNodeList = templateNodeMapper.getList(flowIds, NodeEnum.start.getType());
        } else {
            startNodeList = new ArrayList<>();
        }
        List<String> formIds = startNodeList.stream().map(TemplateNodeEntity::getFormId).collect(Collectors.toList());
        List<VisualdevEntity> formList = serviceUtil.getFormList(formIds);
 
        List<TemplateTreeListVo> vos = new ArrayList<>();
 
        for (DictionaryDataEntity dict : dictionList) {
            TemplateTreeListVo vo = new TemplateTreeListVo();
            vo.setFullName(dict.getFullName());
            vo.setId(dict.getId());
            vo.setDisabled(true);
            if (CollectionUtil.isNotEmpty(list)) {
                List<TemplateEntity> childList = list.stream()
                        .filter(e -> dict.getId().equals(e.getCategory())).collect(Collectors.toList());
 
                if (null != formType) {
                    childList = childList.stream().filter(e -> {
                        // 是流程显示类型
                        if (ObjectUtil.equals(e.getShowType(), FlowNature.FlowShowType)) {
                            return false;
                        }
                        TemplateNodeEntity node = startNodeList.stream().filter(a -> a.getFlowId().equals(e.getFlowId())).findFirst().orElse(null);
                        if (null != node) {
                            VisualdevEntity form = formList.stream().filter(b -> b.getId().equals(node.getFormId())).findFirst().orElse(null);
                            if (null != form) {
                                return form.getType().equals(1);
                            }
                        }
                        return false;
                    }).collect(Collectors.toList());
                }
 
                if (CollectionUtil.isNotEmpty(childList)) {
                    childList = childList.stream()
                            .sorted(Comparator.comparing(TemplateEntity::getSortCode, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(TemplateEntity::getCreatorTime).reversed())
                            .collect(Collectors.toList());
                    vo.setNum(childList.size());
                    vo.setChildren(JsonUtil.getJsonToList(childList, TemplateTreeListVo.class));
                    vos.add(vo);
                }
            }
        }
        return vos;
    }
 
    @Override
    public List<TemplateTreeListVo> treeListWithPower() {
        List<TemplateTreeListVo> vos = new ArrayList<>();
 
        MPJLambdaWrapper<TemplateEntity> wrapper = JoinWrappers.lambda(TemplateEntity.class)
                .selectAll(TemplateEntity.class)
                .eq(TemplateEntity::getVisibleType, FlowNature.Authority)
                .isNotNull(TemplateEntity::getFlowId);
 
        List<TemplateEntity> list = this.selectJoinList(TemplateEntity.class, wrapper);
        List<String> systemIdList = list.stream().map(TemplateEntity::getSystemId).collect(Collectors.toList());
        List<SystemEntity> systemList = serviceUtil.getSystemList(systemIdList);
        for (SystemEntity system : systemList) {
            TemplateTreeListVo vo = new TemplateTreeListVo();
            vo.setFullName(system.getFullName());
            vo.setId(system.getId());
            vo.setDisabled(true);
            if (CollectionUtil.isNotEmpty(list)) {
                List<TemplateEntity> childList = list.stream()
                        .filter(e -> system.getId().equals(e.getSystemId()))
                        .sorted(Comparator.comparing(TemplateEntity::getSortCode, Comparator.nullsLast(Comparator.naturalOrder())).thenComparing(TemplateEntity::getCreatorTime, Comparator.reverseOrder()))
                        .collect(Collectors.toList());
 
                if (CollectionUtil.isNotEmpty(childList)) {
                    vo.setNum(childList.size());
                    vo.setChildren(JsonUtil.getJsonToList(childList, TemplateTreeListVo.class));
                    vos.add(vo);
                }
            }
        }
 
        return vos;
    }
 
    @Override
    public List<TemplateEntity> getListAll(TemplatePagination pagination, boolean isPage) {
        // 定义变量判断是否需要使用修改时间倒序
        boolean flag = false;
        QueryWrapper<TemplateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TemplateEntity::getEnabledMark, 1).eq(TemplateEntity::getStatus, TemplateStatueEnum.up.getCode());
        if (ObjectUtil.isNotEmpty(pagination.getType())) {
            flag = true;
            queryWrapper.lambda().eq(TemplateEntity::getType, pagination.getType());
        }
        if (ObjectUtil.isNotEmpty(pagination.getKeyword())) {
            flag = true;
            queryWrapper.lambda().like(TemplateEntity::getFullName, pagination.getKeyword());
        }
        if (ObjectUtil.isNotEmpty(pagination.getCategory())) {
            flag = true;
            queryWrapper.lambda().eq(TemplateEntity::getCategory, pagination.getCategory());
        }
        if (ObjectUtil.isNotEmpty(pagination.getTemplateIdList())) {
            queryWrapper.lambda().in(TemplateEntity::getId, pagination.getTemplateIdList());
        }
        if (ObjectUtil.isNotEmpty(pagination.getSystemId())) {
            queryWrapper.lambda().eq(TemplateEntity::getSystemId, pagination.getSystemId());
        }
        queryWrapper.lambda().orderByAsc(TemplateEntity::getSortCode).orderByDesc(TemplateEntity::getCreatorTime);
        if (flag) {
            queryWrapper.lambda().orderByDesc(TemplateEntity::getLastModifyTime);
        }
        queryWrapper.lambda().select(
                TemplateEntity::getId, TemplateEntity::getEnCode,
                TemplateEntity::getFullName, TemplateEntity::getFlowId,
                TemplateEntity::getStatus, TemplateEntity::getShowType,
                TemplateEntity::getType, TemplateEntity::getIcon,
                TemplateEntity::getCategory, TemplateEntity::getIconBackground,
                TemplateEntity::getCreatorUserId, TemplateEntity::getSortCode,
                TemplateEntity::getEnabledMark, TemplateEntity::getCreatorTime
        );
        if (isPage) {
            Page<TemplateEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
            IPage<TemplateEntity> userPage = this.page(page, queryWrapper);
            return pagination.setData(userPage.getRecords(), page.getTotal());
        } else {
            return this.list(queryWrapper);
        }
    }
 
    @Override
    public List<TemplateEntity> getListByFlowIds(List<String> flowIds) {
        return flowUtil.getListByFlowIds(flowIds);
    }
 
    @Override
    public TemplateEntity getInfo(String id) throws WorkFlowException {
        return this.baseMapper.getInfo(id);
    }
 
    @Override
    public boolean isExistByFullName(String fullName, String id, String systemId) {
        return this.baseMapper.isExistByFullName(fullName, id, systemId);
    }
 
    @Override
    public boolean isExistByEnCode(String enCode, String id, String systemId) {
        return this.baseMapper.isExistByEnCode(enCode, id, systemId);
    }
 
    @Override
    public void create(TemplateEntity entity, String flowXml, Map<String, Map<String, Object>> flowNodes) throws WorkFlowException {
        entity.setSystemId(serviceUtil.getSystemCodeById(RequestContext.getAppCode()));
        if (StringUtil.isEmpty(entity.getEnCode())) {
            entity.setEnCode(getEnCode(entity));
        }
        if (isExistByFullName(entity.getFullName(), entity.getId(), entity.getSystemId())) {
            throw new WorkFlowException(MsgCode.EXIST001.get());
        }
        if (isExistByEnCode(entity.getEnCode(), entity.getId(), null)) {
            throw new WorkFlowException(MsgCode.EXIST002.get());
        }
        UserInfo userInfo = UserProvider.getUser();
        entity.setId(StringUtil.isNotEmpty(entity.getId()) ? entity.getId() : RandomUtil.uuId());
        entity.setCreatorUserId(userInfo.getUserId());
        entity.setCreatorTime(new Date());
        entity.setFlowId(null);
        entity.setEnabledMark(0);
        entity.setStatus(TemplateStatueEnum.none.getCode());
        entity.setLastModifyUserId(null);
        entity.setLastModifyTime(null);
        this.setIgnoreLogicDelete().removeById(entity.getId());
        this.setIgnoreLogicDelete().saveOrUpdate(entity);
        this.clearIgnoreLogicDelete();
        TemplateNodeUpFrom from = new TemplateNodeUpFrom();
        from.setId(entity.getId());
        from.setFlowXml(flowXml);
        from.setFlowNodes(flowNodes);
        flowUtil.create(from);
    }
 
    @Override
    public boolean update(String id, TemplateEntity entity) throws WorkFlowException {
        if (StringUtil.isEmpty(entity.getEnCode())) {
            entity.setEnCode(getEnCode(entity));
        }
        return this.baseMapper.update(id, entity);
    }
 
    @Override
    public void delete(TemplateEntity entity) throws WorkFlowException {
        if (entity != null) {
            if (ObjectUtil.equals(entity.getType(), FlowNature.Quest)) {
                List<TemplateJsonEntity> list = templateJsonMapper.getList(entity.getId());
                List<String> flowIds = list.stream().map(TemplateJsonEntity::getId).collect(Collectors.toList());
                if (triggerTaskMapper.checkByFlowIds(flowIds)) {
                    throw new WorkFlowException(MsgCode.WF139.get());
                }
            } else {
                List<TaskEntity> taskList = taskMapper.getTaskByTemplate(entity.getId());
                if (CollectionUtil.isNotEmpty(taskList)) {
                    throw new WorkFlowException(MsgCode.WF124.get());
                }
            }
            commonMapper.deleteFlow(entity.getId());
            templateUseNumMapper.deleteUseNum(entity.getId(), null);
            this.removeById(entity.getId());
            List<String> idList = templateJsonMapper.getList(entity.getId()).stream().map(TemplateJsonEntity::getId).collect(Collectors.toList());
            flowUtil.delete(idList);
        }
    }
 
    @Override
    public void copy(TemplateEntity entity) throws WorkFlowException {
        try {
            TemplateJsonEntity jsonEntity = StringUtil.isNotEmpty(entity.getFlowId()) ? templateJsonMapper.getInfo(entity.getFlowId()) : null;
            String formXml = jsonEntity != null ? jsonEntity.getFlowXml() : null;
            List<TemplateNodeEntity> list = jsonEntity != null ? templateNodeMapper.getList(jsonEntity.getId()) : new ArrayList<>();
            String copyNum = UUID.randomUUID().toString().substring(0, 5);
            entity.setFullName(entity.getFullName() + ".副本" + copyNum);
            entity.setEnCode(entity.getEnCode() + copyNum);
            entity.setId(null);
            Map<String, Map<String, Object>> flowNodes = new HashMap<>();
            for (TemplateNodeEntity nodeEntity : list) {
                flowNodes.put(nodeEntity.getNodeCode(), JsonUtil.stringToMap(nodeEntity.getNodeJson()));
            }
            this.create(entity, formXml, flowNodes);
        } catch (Exception e) {
            throw new WorkFlowException(MsgCode.PRI006.get());
        }
    }
 
    @Override
    public TemplateExportModel export(String id) throws WorkFlowException {
        TemplateEntity entity = getInfo(id);
        TemplateExportModel exportModel = new TemplateExportModel();
        exportModel.setTemplate(entity);
        // 版本
        TemplateJsonEntity jsonEntity = templateJsonMapper.getInfo(entity.getFlowId());
        TemplateJsonExportModel versionModel = JsonUtil.getJsonToBean(jsonEntity, TemplateJsonExportModel.class);
        // 节点
        List<TemplateNodeEntity> list = templateNodeMapper.getList(entity.getFlowId());
        exportModel.setNodeList(list);
        exportModel.setFlowVersion(versionModel);
        return exportModel;
    }
 
    @Override
    public void importData(TemplateExportModel model, String type) throws WorkFlowException {
        TemplateEntity entity = model.getTemplate();
        TemplateJsonExportModel versionModel = model.getFlowVersion();
        String systemId = serviceUtil.getSystemCodeById(RequestContext.getAppCode());
        if (null != entity) {
            entity.setFlowId(null);
            entity.setVersion(null);
            entity.setCreatorUserId(UserProvider.getLoginUserId());
            entity.setCreatorTime(new Date());
            entity.setLastModifyTime(null);
            entity.setLastModifyUserId(null);
            entity.setEnabledMark(0);
            if (!Objects.equals(systemId, entity.getSystemId())) {
                entity.setId(RandomUtil.uuId());
                entity.setSystemId(systemId);
                entity.setEnCode(getEnCode(entity));
            }
            List<String> errList = new ArrayList<>();
            // type: 0.当导入数据不存在,作为新数据导入;数据已存在,不做处理  1.当导入数据已存在,增加相同记录新数据,名称和编码自动增加随机码
            TemplateEntity templateEntity = checkImportEntity(entity, type, errList);
 
            if (!errList.isEmpty()) {
                StringJoiner joiner = new StringJoiner(";");
                joiner.add(String.join("、", errList) + MsgCode.IMP007.get());
                if (StringUtil.isNotEmpty(joiner.toString())) {
                    throw new WorkFlowException(joiner.toString());
                }
            }
            Map<String, Map<String, Object>> flowNodes = new HashMap<>();
            for (TemplateNodeEntity nodeEntity : model.getNodeList()) {
                flowNodes.put(nodeEntity.getNodeCode(), JsonUtil.stringToMap(nodeEntity.getNodeJson()));
            }
            this.create(templateEntity, versionModel.getFlowXml(), flowNodes);
        }
    }
 
    @Override
    public List<TemplateEntity> getList(List<String> ids) {
        return this.baseMapper.getList(ids);
    }
 
    @Override
    public List<TemplateEntity> getListByIds(List<String> ids) {
        return this.baseMapper.getListByIds(ids);
    }
 
    @Override
    public List<TemplateEntity> getListOfHidden(List<String> ids) {
        return this.baseMapper.getListOfHidden(ids);
    }
 
    // 校验导入的实体
    public TemplateEntity checkImportEntity(TemplateEntity templateEntity, String type, List<String> errList) {
        TemplateEntity entity = JsonUtil.getJsonToBean(templateEntity, TemplateEntity.class);
        boolean skip = Objects.equals("0", type);
        int num = 0;
        QueryWrapper<TemplateEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TemplateEntity::getId, entity.getId());
        if (this.count(queryWrapper) > 0) {
            num++;
            if (skip) {
                errList.add("ID");
            }
        }
        if (isExistByEnCode(entity.getEnCode(), null, entity.getSystemId())) {
            num++;
            if (skip) {
                errList.add(MsgCode.IMP009.get());
            }
        }
        if (isExistByFullName(entity.getFullName(), null, entity.getSystemId())) {
            num++;
            if (skip) {
                errList.add(MsgCode.IMP008.get());
            }
        }
        if (num > 0 && !skip) {
            String copyNum = UUID.randomUUID().toString().substring(0, 5);
            entity.setFullName(entity.getFullName() + ".副本" + copyNum);
            entity.setEnCode(entity.getEnCode() + copyNum);
        }
        entity.setId(RandomUtil.uuId());
        return entity;
    }
 
    @Override
    public FlowByFormModel getFlowByFormId(String formId, Boolean start) {
        FlowByFormModel res = new FlowByFormModel();
        List<TemplateByFormModel> resList = new ArrayList<>();
 
        QueryWrapper<TemplateNodeEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TemplateNodeEntity::getFormId, formId);
        // start 传true 仅发起节点   false 全部节点
        start = null == start || start;
        if (start) {
            wrapper.lambda().eq(TemplateNodeEntity::getNodeType, NodeEnum.start.getType());
        }
        List<TemplateNodeEntity> nodeList = templateNodeMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(nodeList)) {
            return res;
        }
        List<String> flowIds = nodeList.stream().map(TemplateNodeEntity::getFlowId).distinct().collect(Collectors.toList());
        if (CollectionUtil.isEmpty(flowIds)) {
            return res;
        }
        List<TemplateJsonEntity> versionList = templateJsonMapper.selectByIds(flowIds);
        if (CollectionUtil.isEmpty(versionList)) {
            return res;
        }
        // 获取启用版本
        versionList = versionList.stream().filter(e -> e.getState().equals(1))
                .sorted(Comparator.comparing(TemplateJsonEntity::getCreatorTime).reversed()).collect(Collectors.toList());
        // 获取流程
        List<String> templateIds = versionList.stream().map(TemplateJsonEntity::getTemplateId).distinct().collect(Collectors.toList());
        List<TemplateEntity> templateList = CollectionUtil.isNotEmpty(templateIds) ? this.listByIds(templateIds) : new ArrayList<>();
        // 获取权限流程
        String loginUserId = UserProvider.getLoginUserId();
        //是否普通用户
        boolean commonUser = serviceUtil.isCommonUser(loginUserId);
        List<String> templatePermissionIds = new ArrayList<>();
        if (commonUser) {
            templatePermissionIds.addAll(serviceUtil.getLaunchPermission());
        }
        for (TemplateJsonEntity jsonEntity : versionList) {
            TemplateByFormModel model = new TemplateByFormModel();
            model.setId(jsonEntity.getId());
 
            TemplateEntity template = templateList.stream()
                    .filter(e -> ObjectUtil.equals(e.getId(), jsonEntity.getTemplateId())).findFirst().orElse(null);
            if (null == template || !ObjectUtil.equals(template.getStatus(), TemplateStatueEnum.up.getCode())) {
                continue;
            }
            if (commonUser && ObjectUtil.equals(template.getVisibleType(), FlowNature.Authority)) {
                // 带权限
                if (templatePermissionIds.contains(jsonEntity.getId())) {
                    model.setFullName(template.getFullName());
                    resList.add(model);
                }
            } else {
                model.setFullName(template.getFullName());
                resList.add(model);
            }
        }
        res.setList(resList);
        res.setIsConfig(true);
        return res;
    }
 
    @Override
    public List<UserEntity> getSubFlowUserList(String flowId, TemplatePagination pagination) throws WorkFlowException {
        TemplateEntity template = this.getInfo(flowId);
        return serviceUtil.getLaunchUserByTemplateId(template, pagination);
    }
 
    @Override
    public VisualdevEntity getFormByTemplateId(String templateId) throws WorkFlowException {
        TemplateEntity template = this.getInfo(templateId);
        List<TemplateNodeEntity> nodeEntityList = templateNodeMapper.getList(template.getFlowId());
 
        TemplateNodeEntity nodeEntity = nodeEntityList.stream()
                .filter(e -> ObjectUtil.equals(e.getNodeType(), NodeEnum.start.getType())).findFirst().orElse(null);
        if (null == nodeEntity) {
            throw new WorkFlowException(MsgCode.FA001.get());
        }
        return serviceUtil.getFormInfo(nodeEntity.getFormId());
    }
 
    @Override
    public FlowFormModel getFormIdAndFlowId(List<String> userIdAll, String templateId) throws WorkFlowException {
        return flowUtil.getFormIdAndFlowId(userIdAll, templateId);
    }
 
    @Override
    public List<String> getFormList() {
        List<String> resList = new ArrayList<>();
        List<TemplateJsonEntity> list = templateJsonMapper.getListOfEnable();
        if (CollectionUtil.isNotEmpty(list)) {
            List<String> flowIds = list.stream().map(TemplateJsonEntity::getId).distinct().collect(Collectors.toList());
            List<TemplateNodeEntity> startNodeList = templateNodeMapper.getList(flowIds, NodeEnum.start.getType());
            resList = startNodeList.stream().map(TemplateNodeEntity::getFormId).distinct().collect(Collectors.toList());
        }
        return resList;
    }
 
    @Override
    public Map<String, String> getFlowFormMap() {
        Map<String, String> map = new HashMap<>();
        List<TemplateJsonEntity> listOfEnable = templateJsonMapper.getListOfEnable();
        List<TemplateNodeEntity> listStart = templateNodeMapper.getListStart(listOfEnable);
        List<String> collect = listStart.stream().map(TemplateNodeEntity::getFlowId).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(collect)) {
            QueryWrapper<TemplateEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(TemplateEntity::getId, TemplateEntity::getFlowId);
            queryWrapper.lambda().in(TemplateEntity::getFlowId, collect);
            Map<String, String> flowTempMap = this.list(queryWrapper).stream().collect(Collectors.toMap(TemplateEntity::getFlowId, TemplateEntity::getId));
            for (TemplateNodeEntity templateNodeEntity : listStart) {
                if (ObjectUtil.isNotEmpty(flowTempMap.get(templateNodeEntity.getFlowId()))) {
                    map.put(flowTempMap.get(templateNodeEntity.getFlowId()), templateNodeEntity.getFormId());
                }
            }
        }
        return map;
    }
 
    @Override
    public List<TemplatePageVo> getCommonList(TemplatePagination pagination) {
        AuthorizeVO authorize = pagination.getAuthorize();
        if (authorize == null) {
            authorize = serviceUtil.getAuthorizeByUser();
        }
        List<String> systemIdList = authorize.getSystemList().stream().filter(t -> !Objects.equals(t.getIsMain(), 1)).map(SystemBaeModel::getId).collect(Collectors.toList());
        List<String> flowId = authorize.getFlowIdList();
        String userId = UserProvider.getLoginUserId();
        MPJLambdaWrapper<TemplateEntity> wrapper = JoinWrappers.lambda(TemplateEntity.class)
                .selectAll(TemplateEntity.class)
                .leftJoin(CommonEntity.class, CommonEntity::getFlowId, TemplateEntity::getId)
                .eq(TemplateEntity::getEnabledMark, 1).ne(TemplateEntity::getType, FlowNature.Quest)
                .eq(TemplateEntity::getStatus, TemplateStatueEnum.up.getCode());
        //应用主建
        String systemId = pagination.getSystemId();
        if (ObjectUtil.isNotEmpty(systemId)) {
            systemIdList.retainAll(Arrays.asList(systemId.split(",")));
        }
 
        if (systemIdList.isEmpty()) {
            return new ArrayList<>();
        }
 
        wrapper.and(t -> t.eq(TemplateEntity::getVisibleType, FlowNature.All)
                .or().in(!flowId.isEmpty(), TemplateEntity::getId, flowId)
        );
 
        wrapper.in(TemplateEntity::getSystemId, systemIdList);
 
        //关键字(流程名称、流程编码)
        String keyWord = pagination.getKeyword();
        if (ObjectUtil.isNotEmpty(keyWord)) {
            wrapper.and(t -> t.like(TemplateEntity::getEnCode, keyWord).or().like(TemplateEntity::getFullName, keyWord));
        }
        wrapper.eq(CommonEntity::getCreatorUserId, userId);
        wrapper.orderByAsc(TemplateEntity::getSortCode).orderByDesc(TemplateEntity::getCreatorTime);
        List<TemplatePageVo> list = this.selectJoinList(TemplatePageVo.class, wrapper);
 
        //添加应用信息
        List<String> sysIds = list.stream().map(TemplatePageVo::getSystemId).collect(Collectors.toList());
        Map<String, SystemEntity> sysMap = serviceUtil.getSystemList(sysIds).stream().collect(Collectors.toMap(SystemEntity::getId, t -> t));
        list.stream().forEach(t -> t.setSystemName(sysMap.get(t.getSystemId()) != null ? sysMap.get(t.getSystemId()).getFullName() : ""));
        return list;
    }
 
    private String getEnCode(TemplateEntity entity) {
        String code = serviceUtil.getCode();
        boolean existByEnCode = isExistByEnCode(code, entity.getId(), null);
        if (existByEnCode) {
            return getEnCode(entity);
        }
        return code;
    }
 
    @Override
    public List<TemplateEntity> getListByCreUser(String creUser) {
        return this.baseMapper.getListByCreUser(creUser);
    }
}