刘光辉
118 分钟以前 06f314545ac3514d7ce28939920866ae8188d31c
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
package jnpf.elnService.template.impl;
 
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.base.UserInfo;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.elnEntity.template.ElnTemplateStageEntity;
import jnpf.elnEntity.template.ElnTemplateStepEntity;
import jnpf.elnEntity.template.ElnTemplateBindingEntity;
import jnpf.elnEntity.template.ElnTemplateRepeatGroupEntity;
import jnpf.elnEntity.template.ElnTemplateEnums;
import jnpf.elnEntity.template.ElnTemplateForms;
import jnpf.elnEntity.template.ElnTemplateVersionEntity;
import jnpf.elnEntity.template.ElnTemplateVos;
import jnpf.elnMapper.ElnTemplateMapper;
import jnpf.elnMapper.ElnTemplateStageMapper;
import jnpf.elnMapper.ElnTemplateStepMapper;
import jnpf.elnMapper.ElnTemplateBindingMapper;
import jnpf.elnMapper.ElnTemplateRepeatGroupMapper;
import jnpf.elnService.template.ElnTemplateStepService;
import jnpf.exception.DataException;
import jnpf.model.tenant.TenantVO;
import jnpf.util.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
 
@Service
public class ElnTemplateStepServiceImpl implements ElnTemplateStepService {
 
    private final Store store;
    private final Supplier<UserContext> userContextSupplier;
    private final Supplier<String> idSupplier;
 
    @Autowired
    public ElnTemplateStepServiceImpl(ElnTemplateMapper templateMapper,
            ElnTemplateStageMapper stageMapper, ElnTemplateStepMapper stepMapper,
            ElnTemplateBindingMapper bindingMapper,
            ElnTemplateRepeatGroupMapper repeatGroupMapper) {
        this(new MyBatisStore(templateMapper, stageMapper, stepMapper,
                        bindingMapper, repeatGroupMapper),
                ElnTemplateStepServiceImpl::currentUserContext, IdUtil::getSnowflakeNextIdStr);
    }
 
    ElnTemplateStepServiceImpl(Store store, Supplier<UserContext> userContextSupplier) {
        this(store, userContextSupplier, IdUtil::getSnowflakeNextIdStr);
    }
 
    ElnTemplateStepServiceImpl(Store store, Supplier<UserContext> userContextSupplier,
            Supplier<String> idSupplier) {
        this.store = store;
        this.userContextSupplier = userContextSupplier;
        this.idSupplier = idSupplier;
    }
 
    @Override
    @Transactional(readOnly = true)
    public ElnTemplateVos.StepConfiguration configuration(String templateId) {
        UserContext context = requireContext();
        String actualTemplateId = requireText(templateId, "模板不存在");
        return configuration(context.getTenantId(), actualTemplateId);
    }
 
    @Override
    @Transactional(readOnly = true)
    public ElnTemplateVos.StepFillStructure fillStructure(
            String tenantId, String templateId) {
        String actualTenantId = requireText(tenantId, "租户标识无效");
        String actualTemplateId = requireText(templateId, "模板不存在");
        ElnTemplateVos.StepFillStructure result = new ElnTemplateVos.StepFillStructure();
        result.setConfiguration(configuration(actualTenantId, actualTemplateId));
 
        Map<String, String> primarySteps = new LinkedHashMap<>();
        List<ElnTemplateBindingEntity> bindings = store.listBindings(
                actualTenantId, actualTemplateId);
        for (ElnTemplateBindingEntity binding : bindings) {
            if (!isActiveBinding(binding) || !"PRIMARY".equals(binding.getKongjianJuese())) {
                continue;
            }
            String stepId = requireText(binding.getStepId(), "模板普通字段步骤归属无效");
            primarySteps.put(binding.getId(), stepId);
            putControlStep(result, binding.getKongjianBiaoqian(), stepId);
        }
 
        Map<String, String> groupSteps = result.getRepeatGroupSteps();
        for (ElnTemplateRepeatGroupEntity group
                : store.listRepeatGroups(actualTenantId, actualTemplateId)) {
            String code = requireText(group.getRepeatGroupCode(), "模板重复组配置无效");
            String stepId = requireText(group.getStepId(), "模板重复组步骤归属无效");
            if (groupSteps.put(code, stepId) != null) {
                throw new DataException("模板重复组配置重复");
            }
        }
 
        for (ElnTemplateBindingEntity binding : bindings) {
            if (!isActiveBinding(binding)) continue;
            if ("REFERENCE".equals(binding.getKongjianJuese())) {
                String stepId = primarySteps.get(binding.getYinyongShiliId());
                if (!StringUtils.hasText(stepId)) {
                    throw new DataException("模板引用控件步骤归属无效");
                }
                putControlStep(result, binding.getKongjianBiaoqian(), stepId);
            } else if ("REPEAT".equals(binding.getKongjianJuese())) {
                String stepId = groupSteps.get(binding.getRepeatGroupCode());
                if (!StringUtils.hasText(stepId)) {
                    throw new DataException("模板重复列步骤归属无效");
                }
                putControlStep(result, binding.getKongjianBiaoqian(), stepId);
            }
        }
        return result;
    }
 
    private ElnTemplateVos.StepConfiguration configuration(
            String tenantId, String templateId) {
        ElnTemplateVersionEntity template = store.findTemplate(
                tenantId, templateId);
        if (template == null) throw new DataException("模板不存在");
 
        List<ElnTemplateStepEntity> steps = orderedSteps(tenantId, templateId);
        if (steps.isEmpty()) throw new DataException("模板版本未配置步骤");
 
        ElnTemplateVos.StepConfiguration result = new ElnTemplateVos.StepConfiguration();
        int order = 0;
        for (ElnTemplateStepEntity step : steps) result.getSteps().add(toStep(step, ++order));
        result.setSingleStep(result.getSteps().size() == 1);
        return result;
    }
 
    private List<ElnTemplateStepEntity> orderedSteps(String tenantId, String templateId) {
        List<ElnTemplateStageEntity> stages = store.listStages(tenantId, templateId);
        stages.sort(Comparator.comparing(ElnTemplateStageEntity::getPaixu,
                        Comparator.nullsLast(Integer::compareTo))
                .thenComparing(ElnTemplateStageEntity::getId));
        Map<String, Integer> stageOrder = new LinkedHashMap<>();
        int order = 0;
        for (ElnTemplateStageEntity stage : stages) stageOrder.put(stage.getId(), ++order);
 
        List<ElnTemplateStepEntity> steps = store.listSteps(tenantId, templateId);
        steps.sort(Comparator.comparing((ElnTemplateStepEntity step) ->
                        stageOrder.getOrDefault(step.getJieduanId(), Integer.MAX_VALUE))
                .thenComparing(ElnTemplateStepEntity::getPaixu,
                        Comparator.nullsLast(Integer::compareTo))
                .thenComparing(ElnTemplateStepEntity::getId));
        return steps;
    }
 
    private static void putControlStep(ElnTemplateVos.StepFillStructure result,
            String controlTag, String stepId) {
        String tag = requireText(controlTag, "模板控件标签无效");
        if (result.getControlSteps().put(tag, stepId) != null) {
            throw new DataException("模板控件标签重复");
        }
    }
 
    private static boolean isActiveBinding(ElnTemplateBindingEntity binding) {
        return binding != null && "ACTIVE".equals(binding.getBangdingZhuangtai())
                && !Integer.valueOf(1).equals(binding.getFDeleteMark());
    }
 
    @Override
    @Transactional
    public ElnTemplateVos.StepConfiguration save(
            String templateId, ElnTemplateForms.SaveStepConfiguration form) {
        UserContext context = requireContext();
        String actualTemplateId = requireText(templateId, "模板不存在");
        ElnTemplateVersionEntity template = store.findTemplateForUpdate(
                context.getTenantId(), actualTemplateId);
        if (template == null) throw new DataException("模板不存在");
        if (!ElnTemplateEnums.TemplateStatus.DRAFT.name().equals(template.getBizStatus())) {
            throw new DataException("只有草稿模板可以修改步骤");
        }
        List<ElnTemplateForms.Step> requested = form == null ? null : form.getSteps();
        if (requested == null || requested.isEmpty() || requested.size() > 20) {
            throw new DataException("模板步骤数量必须为 1 至 20 个");
        }
 
        Map<String, ElnTemplateStepEntity> existing = new LinkedHashMap<>();
        for (ElnTemplateStepEntity step : store.listSteps(context.getTenantId(), actualTemplateId)) {
            existing.put(step.getId(), step);
        }
        Set<String> seenIds = new LinkedHashSet<>();
        Set<String> seenNames = new LinkedHashSet<>();
        Set<String> targetStepIds = new LinkedHashSet<>();
        store.releaseStepUniqueness(context.getTenantId(), actualTemplateId);
        int order = 0;
        for (ElnTemplateForms.Step input : requested) {
            if (input == null) throw new DataException("模板步骤无效");
            String name = requireText(input.getName(), "步骤名称不能为空");
            if (name.length() > 100) throw new DataException("步骤名称不能超过 100 个字符");
            if (!seenNames.add(name.toLowerCase(Locale.ROOT))) {
                throw new DataException("步骤名称不能重复");
            }
            String requestedId = StringUtils.hasText(input.getId()) ? input.getId().trim() : null;
            ElnTemplateStepEntity target;
            if (requestedId == null) {
                target = new ElnTemplateStepEntity();
                target.setId(requireText(idSupplier.get(), "步骤标识生成失败"));
                target.setFTenantId(context.getTenantId());
                target.setMubanId(actualTemplateId);
                target.setFVersion(0);
                target.setFCreatorUserId(context.getUserId());
                target.setFCreatorTime(new Date());
                target.setFDeleteMark(0);
            } else {
                if (!seenIds.add(requestedId)) throw new DataException("步骤标识不能重复");
                ElnTemplateStepEntity current = existing.get(requestedId);
                if (current == null) throw new DataException("步骤不属于当前模板版本");
                target = copyStep(current);
            }
            targetStepIds.add(target.getId());
            target.setJieduanId(null);
            target.setBuzhouMingcheng(name);
            target.setPaixu(++order);
            reactivate(target);
            target.setFLastModifyUserId(context.getUserId());
            target.setFLastModifyTime(new Date());
            if (requestedId == null) store.insertStep(target);
            else store.updateStep(target);
        }
        migrateAndDeleteSteps(context, actualTemplateId, existing, targetStepIds,
                form.getStepMigrations());
        return configuration(actualTemplateId);
    }
 
    @Override
    @Transactional
    public void copyForVersion(String tenantId, String sourceTemplateId, String targetTemplateId) {
        String actualTenantId = requireText(tenantId, "租户标识无效");
        String sourceId = requireText(sourceTemplateId, "源模板版本无效");
        String targetId = requireText(targetTemplateId, "目标模板版本无效");
        if (sourceId.equals(targetId)) throw new DataException("源模板与目标模板不能相同");
 
        List<ElnTemplateStepEntity> sourceSteps = orderedSteps(actualTenantId, sourceId);
        if (sourceSteps.isEmpty()) throw new DataException("源模板版本未配置步骤");
        List<ElnTemplateStepEntity> targetSteps = store.listSteps(actualTenantId, targetId);
        Map<String, ElnTemplateStepEntity> copiedSteps = new LinkedHashMap<>();
        for (ElnTemplateStepEntity target : targetSteps) {
            if (StringUtils.hasText(target.getLaiyuanBuzhouId())) {
                copiedSteps.put(target.getLaiyuanBuzhouId(), target);
            }
        }
        ElnTemplateStepEntity reusableDefault = targetSteps.size() == 1
                && !StringUtils.hasText(targetSteps.get(0).getLaiyuanBuzhouId())
                ? targetSteps.get(0) : null;
        store.releaseStepUniqueness(actualTenantId, targetId);
        Map<String, String> stepIds = new LinkedHashMap<>();
        int order = 0;
        for (ElnTemplateStepEntity source : sourceSteps) {
            ElnTemplateStepEntity target = copiedSteps.get(source.getId());
            boolean created = target == null && reusableDefault == null;
            if (target == null) {
                target = reusableDefault;
                reusableDefault = null;
            }
            if (target == null) {
                target = new ElnTemplateStepEntity();
                target.setId(requireText(idSupplier.get(), "目标步骤标识生成失败"));
                target.setFTenantId(actualTenantId);
                target.setMubanId(targetId);
                target.setFVersion(0);
                target.setFCreatorTime(new Date());
                target.setFDeleteMark(0);
                created = true;
            }
            target.setJieduanId(null);
            target.setBuzhouMingcheng(source.getBuzhouMingcheng());
            target.setPaixu(++order);
            target.setLaiyuanBuzhouId(source.getId());
            reactivate(target);
            if (created) store.insertStep(target);
            else store.updateStep(target);
            stepIds.put(source.getId(), target.getId());
        }
        remapCopiedOwnership(actualTenantId, sourceId, targetId, stepIds);
    }
 
    @Override
    @Transactional(readOnly = true)
    public String resolveAssignment(
            String tenantId, String templateId, String requestedStepId) {
        String actualTenantId = requireText(tenantId, "租户标识无效");
        String actualTemplateId = requireText(templateId, "模板版本无效");
        List<ElnTemplateStepEntity> steps = store.listSteps(actualTenantId, actualTemplateId);
        if (steps.isEmpty()) throw new DataException("模板版本未配置步骤");
        if (StringUtils.hasText(requestedStepId)) {
            String actualStepId = requestedStepId.trim();
            for (ElnTemplateStepEntity step : steps) {
                if (actualStepId.equals(step.getId())) return actualStepId;
            }
            throw new DataException("所选步骤不属于当前模板版本");
        }
        if (steps.size() != 1) throw new DataException("多步骤模板必须选择当前步骤");
        return steps.get(0).getId();
    }
 
    @Override
    @Transactional(readOnly = true)
    public List<ElnTemplateVos.Diagnostic> validate(String tenantId, String templateId) {
        return validate(tenantId, templateId, null);
    }
 
    @Override
    @Transactional(readOnly = true)
    public List<ElnTemplateVos.Diagnostic> validate(
            String tenantId, String templateId, String templateAttachments) {
        List<ElnTemplateVos.Diagnostic> diagnostics = new ArrayList<>();
        List<ElnTemplateStepEntity> steps = store.listSteps(tenantId, templateId);
        if (steps.isEmpty() || steps.size() > 20) {
            diagnostics.add(diagnostic("INVALID_STEP_COUNT", "模板必须配置 1 至 20 个步骤", null));
            return diagnostics;
        }
        Set<String> stepIds = new LinkedHashSet<>();
        Set<String> stepNames = new LinkedHashSet<>();
        for (ElnTemplateStepEntity step : steps) {
            if (!StringUtils.hasText(step.getId()) || !StringUtils.hasText(step.getBuzhouMingcheng())
                    || !stepIds.add(step.getId())
                    || !stepNames.add(step.getBuzhouMingcheng().trim().toLowerCase(Locale.ROOT))) {
                diagnostics.add(diagnostic("INVALID_STEP", "模板步骤名称为空或重复", null));
            }
        }
 
        Set<String> occupiedSteps = new LinkedHashSet<>();
        Map<String, Set<String>> primaryStepsByField = new LinkedHashMap<>();
        List<ElnTemplateBindingEntity> bindings = store.listBindings(tenantId, templateId);
        for (ElnTemplateBindingEntity binding : bindings) {
            if (!isLiveBinding(binding)) continue;
            if ("PRIMARY".equals(binding.getKongjianJuese())) {
                if (!StringUtils.hasText(binding.getStepId())
                        || !stepIds.contains(binding.getStepId())) {
                    diagnostics.add(diagnostic("UNASSIGNED_PRIMARY_BINDING",
                            "普通主绑定未归属有效步骤", binding.getId()));
                    continue;
                }
                occupiedSteps.add(binding.getStepId());
                String fieldIdentity = StringUtils.hasText(binding.getZiduanDingyiId())
                        ? binding.getZiduanDingyiId() : binding.getZiduanBianma();
                primaryStepsByField.computeIfAbsent(fieldIdentity,
                        ignored -> new LinkedHashSet<>()).add(binding.getStepId());
            } else if (StringUtils.hasText(binding.getStepId())) {
                diagnostics.add(diagnostic("INHERITED_BINDING_HAS_STEP",
                        "引用控件或重复列不能保存独立步骤归属", binding.getId()));
            }
        }
        for (Set<String> assigned : primaryStepsByField.values()) {
            if (assigned.size() > 1) {
                diagnostics.add(diagnostic("MULTIPLE_STEP_ASSIGNMENT",
                        "同一普通字段被分配到多个步骤", null));
            }
        }
        for (ElnTemplateRepeatGroupEntity group : store.listRepeatGroups(tenantId, templateId)) {
            if (!StringUtils.hasText(group.getStepId()) || !stepIds.contains(group.getStepId())) {
                diagnostics.add(diagnostic("UNASSIGNED_REPEAT_GROUP",
                        "重复组未整体归属有效步骤", group.getId()));
            } else {
                occupiedSteps.add(group.getStepId());
            }
        }
        for (ElnTemplateStepEntity step : steps) {
            if (!occupiedSteps.contains(step.getId())) {
                diagnostics.add(diagnostic("EMPTY_STEP",
                        "步骤未包含普通字段或重复组:" + step.getBuzhouMingcheng(), null));
            }
        }
        return diagnostics;
    }
 
    private static boolean isLiveBinding(ElnTemplateBindingEntity binding) {
        if (binding == null || Integer.valueOf(1).equals(binding.getFDeleteMark())) return false;
        return "PENDING".equals(binding.getBangdingZhuangtai())
                || "ACTIVE".equals(binding.getBangdingZhuangtai());
    }
 
    private static ElnTemplateVos.Diagnostic diagnostic(
            String code, String message, String bindingId) {
        ElnTemplateVos.Diagnostic result = new ElnTemplateVos.Diagnostic();
        result.setSeverity("ERROR");
        result.setCode(code);
        result.setMessage(message);
        result.setBindingId(bindingId);
        return result;
    }
 
    private void remapCopiedOwnership(String tenantId, String sourceTemplateId,
            String targetTemplateId, Map<String, String> stepIds) {
        Map<String, ElnTemplateBindingEntity> sourceBindings = new LinkedHashMap<>();
        for (ElnTemplateBindingEntity source : store.listBindings(tenantId, sourceTemplateId)) {
            sourceBindings.put(source.getId(), source);
        }
        for (ElnTemplateBindingEntity target : store.listBindings(tenantId, targetTemplateId)) {
            if (!StringUtils.hasText(target.getLaiyuanBangdingId())) continue;
            ElnTemplateBindingEntity source = sourceBindings.get(target.getLaiyuanBangdingId());
            if (source == null || !"PRIMARY".equals(source.getKongjianJuese())) continue;
            String targetStepId = stepIds.get(source.getStepId());
            if (!StringUtils.hasText(targetStepId)) {
                throw new DataException("源模板普通字段步骤归属无效");
            }
            target.setStepId(targetStepId);
            store.updateBindingStep(target);
        }
        Map<String, ElnTemplateRepeatGroupEntity> sourceGroups = new LinkedHashMap<>();
        for (ElnTemplateRepeatGroupEntity source
                : store.listRepeatGroups(tenantId, sourceTemplateId)) {
            sourceGroups.put(source.getRepeatGroupCode(), source);
        }
        for (ElnTemplateRepeatGroupEntity target
                : store.listRepeatGroups(tenantId, targetTemplateId)) {
            ElnTemplateRepeatGroupEntity source = sourceGroups.get(target.getRepeatGroupCode());
            if (source == null) continue;
            String targetStepId = stepIds.get(source.getStepId());
            if (!StringUtils.hasText(targetStepId)) {
                throw new DataException("源模板重复组步骤归属无效");
            }
            target.setStepId(targetStepId);
            store.updateRepeatGroupStep(target);
        }
    }
 
    private void migrateAndDeleteSteps(UserContext context, String templateId,
            Map<String, ElnTemplateStepEntity> existing, Set<String> targetStepIds,
            Map<String, String> requestedMigrations) {
        Map<String, String> migrations = requestedMigrations == null
                ? new LinkedHashMap<>() : requestedMigrations;
        List<ElnTemplateBindingEntity> bindings = store.listBindings(
                context.getTenantId(), templateId);
        List<ElnTemplateRepeatGroupEntity> groups = store.listRepeatGroups(
                context.getTenantId(), templateId);
        for (ElnTemplateStepEntity removed : existing.values()) {
            if (targetStepIds.contains(removed.getId())) continue;
            String targetId = StringUtils.hasText(migrations.get(removed.getId()))
                    ? migrations.get(removed.getId()).trim() : null;
            boolean ownsBindings = false;
            for (ElnTemplateBindingEntity binding : bindings) {
                if (isLivePrimary(binding) && removed.getId().equals(binding.getStepId())) {
                    ownsBindings = true;
                }
            }
            boolean ownsGroups = false;
            for (ElnTemplateRepeatGroupEntity group : groups) {
                if (removed.getId().equals(group.getStepId())) ownsGroups = true;
            }
            if ((ownsBindings || ownsGroups) && targetId == null) {
                throw new DataException("有字段归属的步骤必须先显式迁移");
            }
            if (targetId != null && (!targetStepIds.contains(targetId)
                    || removed.getId().equals(targetId))) {
                throw new DataException("步骤迁移目标无效");
            }
            if (targetId != null) {
                for (ElnTemplateBindingEntity binding : bindings) {
                    if (isLivePrimary(binding) && removed.getId().equals(binding.getStepId())) {
                        binding.setStepId(targetId);
                        binding.setFLastModifyUserId(context.getUserId());
                        binding.setFLastModifyTime(new Date());
                        store.updateBindingStep(binding);
                    }
                }
                for (ElnTemplateRepeatGroupEntity group : groups) {
                    if (removed.getId().equals(group.getStepId())) {
                        group.setStepId(targetId);
                        group.setFLastModifyUserId(context.getUserId());
                        group.setFLastModifyTime(new Date());
                        store.updateRepeatGroupStep(group);
                    }
                }
            }
            ElnTemplateStepEntity deleted = copyStep(removed);
            deleted.setFDeleteMark(1);
            deleted.setFDeleteUserId(context.getUserId());
            deleted.setFDeleteTime(new Date());
            deleted.setFLastModifyUserId(context.getUserId());
            deleted.setFLastModifyTime(new Date());
            store.updateStep(deleted);
        }
    }
 
    private static boolean isLivePrimary(ElnTemplateBindingEntity binding) {
        if (binding == null || !"PRIMARY".equals(binding.getKongjianJuese())) {
            return false;
        }
        String status = binding.getBangdingZhuangtai();
        return ("PENDING".equals(status) || "ACTIVE".equals(status))
                && !Integer.valueOf(1).equals(binding.getFDeleteMark());
    }
 
    private static ElnTemplateStepEntity copyStep(ElnTemplateStepEntity source) {
        ElnTemplateStepEntity result = new ElnTemplateStepEntity();
        result.setId(source.getId());
        result.setMubanId(source.getMubanId());
        result.setJieduanId(source.getJieduanId());
        result.setBuzhouMingcheng(source.getBuzhouMingcheng());
        result.setPaixu(source.getPaixu());
        result.setLaiyuanBuzhouId(source.getLaiyuanBuzhouId());
        result.setFTenantId(source.getFTenantId());
        result.setFVersion(source.getFVersion());
        result.setFCreatorUserId(source.getFCreatorUserId());
        result.setFCreatorTime(source.getFCreatorTime());
        result.setFLastModifyUserId(source.getFLastModifyUserId());
        result.setFLastModifyTime(source.getFLastModifyTime());
        result.setFDeleteUserId(source.getFDeleteUserId());
        result.setFDeleteTime(source.getFDeleteTime());
        result.setFDeleteMark(source.getFDeleteMark());
        return result;
    }
 
    private static void reactivate(ElnTemplateStepEntity entity) {
        entity.setFDeleteMark(0);
        entity.setFDeleteUserId(null);
        entity.setFDeleteTime(null);
    }
 
    private static ElnTemplateVos.Step toStep(ElnTemplateStepEntity entity, int order) {
        ElnTemplateVos.Step result = new ElnTemplateVos.Step();
        result.setId(entity.getId());
        result.setName(entity.getBuzhouMingcheng());
        result.setOrder(order);
        return result;
    }
 
    private UserContext requireContext() {
        UserContext context = userContextSupplier.get();
        if (context == null || !StringUtils.hasText(context.getTenantId())) {
            throw new DataException("当前租户无效");
        }
        return context;
    }
 
    private static String requireText(String value, String message) {
        if (!StringUtils.hasText(value)) throw new DataException(message);
        return value.trim();
    }
 
    private static UserContext currentUserContext() {
        UserInfo user = UserProvider.getUser();
        TenantVO routed = TenantDataSourceUtil.getTenantInfo();
        String tenantId = routed != null && StringUtils.hasText(routed.getEnCode())
                ? routed.getEnCode().trim()
                : user != null && StringUtils.hasText(user.getTenantId())
                ? user.getTenantId().trim() : "0";
        String userId = user == null || !StringUtils.hasText(user.getUserId())
                ? null : user.getUserId().trim();
        return new UserContext(tenantId, userId);
    }
 
    static final class UserContext {
        private final String tenantId;
        private final String userId;
 
        UserContext(String tenantId, String userId) {
            this.tenantId = tenantId;
            this.userId = userId;
        }
 
        String getTenantId() { return tenantId; }
        String getUserId() { return userId; }
    }
 
    interface Store {
        ElnTemplateVersionEntity findTemplate(String tenantId, String templateId);
        ElnTemplateVersionEntity findTemplateForUpdate(String tenantId, String templateId);
        List<ElnTemplateStageEntity> listStages(String tenantId, String templateId);
        List<ElnTemplateStepEntity> listSteps(String tenantId, String templateId);
        List<ElnTemplateBindingEntity> listBindings(String tenantId, String templateId);
        List<ElnTemplateRepeatGroupEntity> listRepeatGroups(String tenantId, String templateId);
        void releaseStepUniqueness(String tenantId, String templateId);
        void insertStep(ElnTemplateStepEntity entity);
        void updateStep(ElnTemplateStepEntity entity);
        void updateBindingStep(ElnTemplateBindingEntity entity);
        void updateRepeatGroupStep(ElnTemplateRepeatGroupEntity entity);
    }
 
    private static final class MyBatisStore implements Store {
        private final ElnTemplateMapper templateMapper;
        private final ElnTemplateStageMapper stageMapper;
        private final ElnTemplateStepMapper stepMapper;
        private final ElnTemplateBindingMapper bindingMapper;
        private final ElnTemplateRepeatGroupMapper repeatGroupMapper;
 
        private MyBatisStore(ElnTemplateMapper templateMapper,
                ElnTemplateStageMapper stageMapper, ElnTemplateStepMapper stepMapper,
                ElnTemplateBindingMapper bindingMapper,
                ElnTemplateRepeatGroupMapper repeatGroupMapper) {
            this.templateMapper = templateMapper;
            this.stageMapper = stageMapper;
            this.stepMapper = stepMapper;
            this.bindingMapper = bindingMapper;
            this.repeatGroupMapper = repeatGroupMapper;
        }
 
        @Override
        public ElnTemplateVersionEntity findTemplate(String tenantId, String templateId) {
            return templateMapper.selectOne(Wrappers.<ElnTemplateVersionEntity>lambdaQuery()
                    .eq(ElnTemplateVersionEntity::getFTenantId, tenantId)
                    .eq(ElnTemplateVersionEntity::getId, templateId)
                    .and(q -> q.isNull(ElnTemplateVersionEntity::getFDeleteMark)
                            .or().eq(ElnTemplateVersionEntity::getFDeleteMark, 0)));
        }
 
        @Override
        public ElnTemplateVersionEntity findTemplateForUpdate(String tenantId, String templateId) {
            return templateMapper.lockTemplateForUpdate(tenantId, templateId);
        }
 
        @Override
        public List<ElnTemplateStageEntity> listStages(String tenantId, String templateId) {
            return new ArrayList<>(stageMapper.selectList(
                    Wrappers.<ElnTemplateStageEntity>lambdaQuery()
                            .eq(ElnTemplateStageEntity::getFTenantId, tenantId)
                            .eq(ElnTemplateStageEntity::getMubanId, templateId)
                            .and(q -> q.isNull(ElnTemplateStageEntity::getFDeleteMark)
                                    .or().eq(ElnTemplateStageEntity::getFDeleteMark, 0))));
        }
 
        @Override
        public List<ElnTemplateStepEntity> listSteps(String tenantId, String templateId) {
            return new ArrayList<>(stepMapper.selectList(
                    Wrappers.<ElnTemplateStepEntity>lambdaQuery()
                            .eq(ElnTemplateStepEntity::getFTenantId, tenantId)
                            .eq(ElnTemplateStepEntity::getMubanId, templateId)
                            .and(q -> q.isNull(ElnTemplateStepEntity::getFDeleteMark)
                                    .or().eq(ElnTemplateStepEntity::getFDeleteMark, 0))));
        }
 
        @Override
        public List<ElnTemplateBindingEntity> listBindings(String tenantId, String templateId) {
            return new ArrayList<>(bindingMapper.selectList(
                    Wrappers.<ElnTemplateBindingEntity>lambdaQuery()
                            .eq(ElnTemplateBindingEntity::getFTenantId, tenantId)
                            .eq(ElnTemplateBindingEntity::getMubanId, templateId)
                            .and(q -> q.isNull(ElnTemplateBindingEntity::getFDeleteMark)
                                    .or().eq(ElnTemplateBindingEntity::getFDeleteMark, 0))));
        }
 
        @Override
        public List<ElnTemplateRepeatGroupEntity> listRepeatGroups(
                String tenantId, String templateId) {
            return new ArrayList<>(repeatGroupMapper.selectList(
                    Wrappers.<ElnTemplateRepeatGroupEntity>lambdaQuery()
                            .eq(ElnTemplateRepeatGroupEntity::getFTenantId, tenantId)
                            .eq(ElnTemplateRepeatGroupEntity::getMubanId, templateId)
                            .and(q -> q.isNull(ElnTemplateRepeatGroupEntity::getFDeleteMark)
                                    .or().eq(ElnTemplateRepeatGroupEntity::getFDeleteMark, 0))));
        }
 
        @Override
        public void releaseStepUniqueness(String tenantId, String templateId) {
            stepMapper.update(null, Wrappers.<ElnTemplateStepEntity>lambdaUpdate()
                    .eq(ElnTemplateStepEntity::getFTenantId, tenantId)
                    .eq(ElnTemplateStepEntity::getMubanId, templateId)
                    .and(q -> q.isNull(ElnTemplateStepEntity::getFDeleteMark)
                            .or().eq(ElnTemplateStepEntity::getFDeleteMark, 0))
                    .set(ElnTemplateStepEntity::getFDeleteMark, 1));
        }
 
 
        @Override
        public void insertStep(ElnTemplateStepEntity entity) {
            stepMapper.insert(entity);
        }
 
        @Override
        public void updateStep(ElnTemplateStepEntity entity) {
            if (stepMapper.updateById(entity) != 1) {
                throw new DataException("步骤已被其他操作修改,请刷新后重试");
            }
        }
 
        @Override
        public void updateBindingStep(ElnTemplateBindingEntity entity) {
            if (bindingMapper.updateById(entity) != 1) {
                throw new DataException("字段归属已被其他操作修改,请刷新后重试");
            }
        }
 
        @Override
        public void updateRepeatGroupStep(ElnTemplateRepeatGroupEntity entity) {
            if (repeatGroupMapper.updateById(entity) != 1) {
                throw new DataException("重复组归属已被其他操作修改,请刷新后重试");
            }
        }
    }
}