刘光辉
3 小时以前 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
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
package jnpf.elnService.template.impl;
 
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.audit.model.AuditEventDTO;
import jnpf.audit.sdk.AuditClient;
import jnpf.base.ActionResult;
import jnpf.base.ActionResultCode;
import jnpf.base.UserInfo;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.elnEntity.ElnDocumentFileVo;
import jnpf.elnEntity.template.ElnTemplateBindingEntity;
import jnpf.elnEntity.template.ElnTemplateCurrentVersionEntity;
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.ElnTemplateBindingMapper;
import jnpf.elnMapper.ElnTemplateCurrentVersionMapper;
import jnpf.elnService.template.ElnTemplateCatalogService;
import jnpf.elnService.template.ElnTemplateFileService;
import jnpf.elnService.template.ElnTemplateHealthService;
import jnpf.elnService.template.ElnTemplatePublishValidator;
import jnpf.elnService.template.ElnTemplateRepeatGroupService;
import jnpf.elnService.template.ElnTemplateStepService;
import jnpf.exception.DataException;
import jnpf.model.tenant.TenantVO;
import jnpf.onlyoffice.TemplatePublishFenceApi;
import jnpf.permission.UserApi;
import jnpf.permission.entity.UserEntity;
import jnpf.util.JsonUtil;
import jnpf.util.UserProvider;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StringUtils;
 
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
 
@Service
public class ElnTemplateCatalogServiceImpl implements ElnTemplateCatalogService {
 
    private static final String ENABLED = "enabled";
    private static final int MAX_SOURCE_CHAIN_DEPTH = 32;
 
    private final TemplateCatalogStore store;
    private final Supplier<UserContext> userContextSupplier;
    private final TargetIdFactory targetIdFactory;
    private final Supplier<String> bindingIdSupplier;
    private final TemplateFileCopier fileCopier;
    private final Consumer<AuditEventDTO> auditRecorder;
    private final TransactionRunner transactionRunner;
    private final List<ElnTemplatePublishValidator> publishValidators;
    private final TemplatePublishFence publishFence;
    private final UserNameResolver userNameResolver;
    private final VersionGroupCopier versionGroupCopier;
 
    @Autowired
    public ElnTemplateCatalogServiceImpl(ElnTemplateMapper templateMapper,
                                         ElnTemplateBindingMapper bindingMapper,
                                         ElnTemplateCurrentVersionMapper currentMapper,
                                         ElnTemplateFileService fileService,
                                         ElnTemplateHealthService healthService,
                                         ElnTemplateRepeatGroupService repeatGroupService,
                                         ElnTemplateStepService stepService,
                                         List<ElnTemplatePublishValidator> publishValidators,
                                         ObjectProvider<AuditClient> auditClientProvider,
                                         PlatformTransactionManager transactionManager,
                                         TemplatePublishFenceApi publishFenceApi,
                                         UserApi userApi) {
        this(new MyBatisTemplateCatalogStore(templateMapper, bindingMapper, currentMapper),
                ElnTemplateCatalogServiceImpl::currentUserContext,
                ElnTemplateCatalogServiceImpl::deterministicTargetId,
                IdUtil::getSnowflakeNextIdStr,
                fileService::copyDocx,
                event -> {
                    AuditClient client = auditClientProvider.getIfAvailable();
                    if (client != null) {
                        client.record(event);
                    }
                }, new SpringTransactionRunner(transactionManager),
                withHealthValidator(healthService, publishValidators),
                remotePublishFence(publishFenceApi), remoteUserNameResolver(userApi),
                (tenantId, sourceTemplateId, targetTemplateId) -> {
                    repeatGroupService.copyForVersion(
                            tenantId, sourceTemplateId, targetTemplateId);
                    stepService.copyForVersion(tenantId, sourceTemplateId, targetTemplateId);
                });
    }
 
    ElnTemplateCatalogServiceImpl(TemplateCatalogStore store,
                                  Supplier<UserContext> userContextSupplier,
                                  TargetIdFactory targetIdFactory,
                                  Supplier<String> bindingIdSupplier,
                                  TemplateFileCopier fileCopier,
                                  Consumer<AuditEventDTO> auditRecorder) {
        this(store, userContextSupplier, targetIdFactory, bindingIdSupplier,
                fileCopier, auditRecorder, callback -> callback.get(), Collections.emptyList(),
                TemplatePublishFence.noop(), userId -> userId);
    }
 
    ElnTemplateCatalogServiceImpl(TemplateCatalogStore store,
                                  Supplier<UserContext> userContextSupplier,
                                  TargetIdFactory targetIdFactory,
                                  Supplier<String> bindingIdSupplier,
                                  TemplateFileCopier fileCopier,
                                  Consumer<AuditEventDTO> auditRecorder,
                                  TransactionRunner transactionRunner) {
        this(store, userContextSupplier, targetIdFactory, bindingIdSupplier, fileCopier,
                auditRecorder, transactionRunner, Collections.emptyList(),
                TemplatePublishFence.noop(), userId -> userId);
    }
 
    ElnTemplateCatalogServiceImpl(TemplateCatalogStore store,
                                  Supplier<UserContext> userContextSupplier,
                                  TargetIdFactory targetIdFactory,
                                  Supplier<String> bindingIdSupplier,
                                  TemplateFileCopier fileCopier,
                                  Consumer<AuditEventDTO> auditRecorder,
                                  TransactionRunner transactionRunner,
                                  List<ElnTemplatePublishValidator> publishValidators) {
        this(store, userContextSupplier, targetIdFactory, bindingIdSupplier, fileCopier,
                auditRecorder, transactionRunner, publishValidators,
                TemplatePublishFence.noop(), userId -> userId);
    }
 
    ElnTemplateCatalogServiceImpl(TemplateCatalogStore store,
                                  Supplier<UserContext> userContextSupplier,
                                  TargetIdFactory targetIdFactory,
                                  Supplier<String> bindingIdSupplier,
                                  TemplateFileCopier fileCopier,
                                  Consumer<AuditEventDTO> auditRecorder,
                                  TransactionRunner transactionRunner,
                                  List<ElnTemplatePublishValidator> publishValidators,
                                  TemplatePublishFence publishFence) {
        this(store, userContextSupplier, targetIdFactory, bindingIdSupplier, fileCopier,
                auditRecorder, transactionRunner, publishValidators, publishFence,
                userId -> userId);
    }
 
    ElnTemplateCatalogServiceImpl(TemplateCatalogStore store,
                                  Supplier<UserContext> userContextSupplier,
                                  TargetIdFactory targetIdFactory,
                                  Supplier<String> bindingIdSupplier,
                                  TemplateFileCopier fileCopier,
                                  Consumer<AuditEventDTO> auditRecorder,
                                  TransactionRunner transactionRunner,
                                  List<ElnTemplatePublishValidator> publishValidators,
                                  TemplatePublishFence publishFence,
                                  UserNameResolver userNameResolver) {
        this(store, userContextSupplier, targetIdFactory, bindingIdSupplier, fileCopier,
                auditRecorder, transactionRunner, publishValidators, publishFence,
                userNameResolver, (tenantId, sourceTemplateId, targetTemplateId) -> { });
    }
 
    ElnTemplateCatalogServiceImpl(TemplateCatalogStore store,
                                  Supplier<UserContext> userContextSupplier,
                                  TargetIdFactory targetIdFactory,
                                  Supplier<String> bindingIdSupplier,
                                  TemplateFileCopier fileCopier,
                                  Consumer<AuditEventDTO> auditRecorder,
                                  TransactionRunner transactionRunner,
                                  List<ElnTemplatePublishValidator> publishValidators,
                                  TemplatePublishFence publishFence,
                                  UserNameResolver userNameResolver,
                                  VersionGroupCopier versionGroupCopier) {
        this.store = store;
        this.userContextSupplier = userContextSupplier;
        this.targetIdFactory = targetIdFactory;
        this.bindingIdSupplier = bindingIdSupplier;
        this.fileCopier = fileCopier;
        this.auditRecorder = auditRecorder;
        this.transactionRunner = transactionRunner;
        this.publishValidators = publishValidators == null
                ? Collections.emptyList() : new ArrayList<>(publishValidators);
        this.publishFence = publishFence;
        this.userNameResolver = userNameResolver;
        this.versionGroupCopier = versionGroupCopier;
    }
 
    @Override
    @Transactional(readOnly = true)
    public IPage<ElnTemplateVos.ListItem> page(ElnTemplateForms.Query query) {
        UserContext context = requireContext();
        ElnTemplateForms.Query actual = query == null ? new ElnTemplateForms.Query() : query;
        if (actual.getCurrentPage() < 1 || actual.getPageSize() < 1) {
            throw new DataException("分页参数无效");
        }
        IPage<ElnTemplateVersionEntity> entities = store.page(context.getTenantId(), actual);
        Page<ElnTemplateVos.ListItem> result = new Page<>(entities.getCurrent(), entities.getSize());
        result.setTotal(entities.getTotal());
        List<String> templateCodes = entities.getRecords().stream()
                .map(ElnTemplateVersionEntity::getMubanBianhao)
                .filter(StringUtils::hasText).distinct().collect(Collectors.toList());
        Map<String, String> currentTemplateIds = store.listCurrentVersions(
                        context.getTenantId(), templateCodes).stream()
                .collect(Collectors.toMap(ElnTemplateCurrentVersionEntity::getMubanBianhao,
                        ElnTemplateCurrentVersionEntity::getDangqianMubanId,
                        (first, second) -> first, LinkedHashMap::new));
        List<String> templateIds = entities.getRecords().stream()
                .map(ElnTemplateVersionEntity::getId).collect(Collectors.toList());
        Map<String, Set<String>> fieldsByTemplate = new LinkedHashMap<>();
        for (ElnTemplateBindingEntity binding : store.listActiveBindingsByTemplateIds(
                context.getTenantId(), templateIds)) {
            if (StringUtils.hasText(binding.getZiduanDingyiId())) {
                fieldsByTemplate.computeIfAbsent(
                        binding.getMubanId(), key -> new LinkedHashSet<>())
                        .add(binding.getZiduanDingyiId());
            }
        }
        List<ElnTemplateVos.ListItem> records = new ArrayList<>();
        for (ElnTemplateVersionEntity entity : entities.getRecords()) {
            ElnTemplateVos.ListItem item = toListItem(entity);
            item.setShifouDangqian(Objects.equals(entity.getId(),
                    currentTemplateIds.get(entity.getMubanBianhao())));
            item.setZiduanShu((long) fieldsByTemplate
                    .getOrDefault(entity.getId(), Collections.emptySet()).size());
            records.add(item);
        }
        result.setRecords(records);
        return result;
    }
 
    @Override
    @Transactional(readOnly = true)
    public IPage<ElnTemplateVos.CatalogItem> directory(ElnTemplateForms.Query query) {
        UserContext context = requireContext();
        ElnTemplateForms.Query actual = query == null ? new ElnTemplateForms.Query() : query;
        if (actual.getCurrentPage() < 1 || actual.getPageSize() < 1) {
            throw new DataException("分页参数无效");
        }
        IPage<ElnTemplateVos.CatalogItem> result = store.pageDirectory(
                context.getTenantId(), actual);
        List<String> effectiveTemplateIds = result.getRecords().stream()
                .map(ElnTemplateVos.CatalogItem::getShengxiaoMubanId)
                .filter(StringUtils::hasText).collect(Collectors.toList());
        Map<String, Set<String>> fieldsByTemplate = new LinkedHashMap<>();
        for (ElnTemplateBindingEntity binding : store.listActiveBindingsByTemplateIds(
                context.getTenantId(), effectiveTemplateIds)) {
            if (StringUtils.hasText(binding.getZiduanDingyiId())) {
                fieldsByTemplate.computeIfAbsent(
                        binding.getMubanId(), key -> new LinkedHashSet<>())
                        .add(binding.getZiduanDingyiId());
            }
        }
        for (ElnTemplateVos.CatalogItem item : result.getRecords()) {
            if (StringUtils.hasText(item.getShengxiaoMubanId())) {
                item.setZiduanShu((long) fieldsByTemplate.getOrDefault(
                        item.getShengxiaoMubanId(), Collections.emptySet()).size());
            }
        }
        return result;
    }
 
    @Override
    @Transactional(readOnly = true)
    public ElnTemplateVos.Detail detail(String templateId) {
        UserContext context = requireContext();
        ElnTemplateVersionEntity current = requireTemplate(context.getTenantId(), templateId);
        ElnTemplateVos.Detail result = toDetail(current);
        mergeSourceChain(context.getTenantId(), current, result);
        enrichDetailNames(result);
        return result;
    }
 
    @Override
    public ElnTemplateVos.Detail createVersion(String sourceTemplateId,
                                               ElnTemplateForms.CreateVersion form) {
        UserContext context = requireContext();
        validateCreateVersion(sourceTemplateId, form);
        String sourceId = sourceTemplateId.trim();
        String operation = form.getShengbanCaozuoBianma().trim();
        String businessVersion = form.getMubanBanben().trim();
        Date effectiveDate = form.getShengxiaoRiqi();
        try {
            return transactionRunner.execute(() -> createVersionInTransaction(
                    context, sourceId, businessVersion, operation, effectiveDate));
        } catch (DuplicateKeyException e) {
            return transactionRunner.execute(() -> resolveConcurrentConflict(
                    context, sourceId, businessVersion, operation, effectiveDate));
        }
    }
 
    private ElnTemplateVos.Detail createVersionInTransaction(
            UserContext context, String sourceId, String businessVersion,
            String operation, Date effectiveDate) {
        String tenantId = context.getTenantId();
        ElnTemplateVersionEntity existing = store.findByOperation(tenantId, operation);
        if (existing != null) {
            return completeIdempotentRetry(
                    context, sourceId, businessVersion, operation, effectiveDate, existing);
        }
 
        ElnTemplateVersionEntity source = requireTemplateForUpdate(tenantId, sourceId);
        if (store.findByCodeAndVersion(tenantId, source.getMubanBianhao(), businessVersion) != null) {
            throw new DataException("同名模板业务版本已存在");
        }
 
        String targetId = targetIdFactory.create(tenantId, sourceId, operation);
        ElnTemplateVersionEntity target = new ElnTemplateVersionEntity();
        target.setId(targetId);
        target.setFTenantId(tenantId);
        target.setMubanBianhao(source.getMubanBianhao());
        target.setMubanBanben(businessVersion);
        target.setMubanMingcheng(source.getMubanMingcheng());
        target.setShiyanBuzhou(source.getShiyanBuzhou());
        target.setJianyanXiangmu(source.getJianyanXiangmu());
        target.setJianyanXiangmuBianma(source.getJianyanXiangmuBianma());
        target.setJianyanXiangmuMingcheng(source.getJianyanXiangmuMingcheng());
        target.setMubanFenlei(source.getMubanFenlei());
        target.setMubanFenleiMingcheng(source.getMubanFenleiMingcheng());
        target.setShengxiaoRiqi(effectiveDate);
        target.setBizStatus(ElnTemplateEnums.TemplateStatus.DRAFT.name());
        target.setBizEnabled(ENABLED);
        target.setLaiyuanMubanId(sourceId);
        target.setShengbanCaozuoBianma(operation);
        Date createdAt = new Date();
        target.setChuangjianRenyuan(context.getUserId());
        target.setChuangjianShijian(createdAt);
        target.setFCreatorUserId(context.getUserId());
        target.setFCreatorTime(createdAt);
        target.setFVersion(0);
        target.setFDeleteMark(0);
        store.insertTemplate(target);
 
        String attachmentJson = fileCopier.copy(source.getMubanFile(), targetId);
        target.setMubanFile(attachmentJson);
        store.updateTemplateFile(target);
 
        List<ElnTemplateBindingEntity> sourceBindings =
                store.listActiveBindings(tenantId, sourceId);
        Map<String, ElnTemplateBindingEntity> sourceBindingsById = new LinkedHashMap<>();
        Map<String, String> targetBindingIds = new LinkedHashMap<>();
        for (ElnTemplateBindingEntity sourceBinding : sourceBindings) {
            if (!StringUtils.hasText(sourceBinding.getId())
                    || sourceBindingsById.put(sourceBinding.getId(), sourceBinding) != null) {
                throw new DataException("源模板绑定集合无效");
            }
            String targetBindingId = bindingIdSupplier.get();
            if (!StringUtils.hasText(targetBindingId)
                    || targetBindingIds.containsValue(targetBindingId)) {
                throw new DataException("目标模板绑定 ID 生成失败");
            }
            targetBindingIds.put(sourceBinding.getId(), targetBindingId);
        }
        for (ElnTemplateBindingEntity sourceBinding : sourceBindings) {
            store.insertBinding(copyBinding(sourceBinding, target, operation,
                    sourceBindingsById, targetBindingIds));
        }
        versionGroupCopier.copy(tenantId, sourceId, targetId);
        auditVersionCreate(context, operation, sourceId, targetId, "SUCCESS");
        return toDetail(target);
    }
 
    private ElnTemplateVos.Detail resolveConcurrentConflict(
            UserContext context, String sourceId, String businessVersion,
            String operation, Date effectiveDate) {
        String tenantId = context.getTenantId();
        ElnTemplateVersionEntity existing = store.findByOperation(tenantId, operation);
        if (existing != null) {
            return completeIdempotentRetry(
                    context, sourceId, businessVersion, operation, effectiveDate, existing);
        }
        ElnTemplateVersionEntity source = requireTemplate(tenantId, sourceId);
        if (store.findByCodeAndVersion(tenantId, source.getMubanBianhao(), businessVersion) != null) {
            throw new DataException("同名模板业务版本已存在");
        }
        throw new DataException("模板升版并发冲突,请重试");
    }
 
    private ElnTemplateVos.Detail completeIdempotentRetry(
            UserContext context, String sourceId, String businessVersion,
            String operation, Date effectiveDate, ElnTemplateVersionEntity existing) {
        if (!sourceId.equals(existing.getLaiyuanMubanId())
                || !businessVersion.equals(existing.getMubanBanben())
                || !sameInstant(effectiveDate, existing.getShengxiaoRiqi())) {
            throw new DataException("升版操作码已用于其他模板版本");
        }
        ElnTemplateVersionEntity source = requireTemplate(context.getTenantId(), sourceId);
        String attachmentJson = fileCopier.copy(source.getMubanFile(), existing.getId());
        existing.setMubanFile(attachmentJson);
        store.updateTemplateFile(existing);
        versionGroupCopier.copy(context.getTenantId(), sourceId, existing.getId());
        auditVersionCreate(context, operation, sourceId, existing.getId(), "IDEMPOTENT");
        return toDetail(existing);
    }
 
    private static boolean sameInstant(Date left, Date right) {
        return left == null ? right == null
                : right != null && left.getTime() == right.getTime();
    }
 
    @Override
    public void publish(String templateId, String reason) {
        UserContext context = requireContext();
        ElnTemplateVersionEntity snapshot = requireTemplate(context.getTenantId(), templateId);
        if (!ElnTemplateEnums.TemplateStatus.DRAFT.name().equals(snapshot.getBizStatus())) {
            throw new DataException("只有草稿模板可以发布");
        }
        String fileId = uniqueDocxFileId(snapshot.getMubanFile());
        String fileType = "annex";
        String token = publishFence.acquire(
                context.getTenantId(), snapshot.getId(), fileId, fileType);
        try {
            transactionRunner.execute(() -> {
                publishInTransaction(context, snapshot.getId(), fileId, reason);
                return null;
            });
        } catch (RuntimeException publishError) {
            try {
                publishFence.release(context.getTenantId(), snapshot.getId(),
                        fileId, fileType, token);
            } catch (RuntimeException releaseError) {
                publishError.addSuppressed(releaseError);
            }
            throw publishError;
        }
        try {
            publishFence.release(context.getTenantId(), snapshot.getId(), fileId, fileType, token);
        } catch (RuntimeException releaseError) {
            DataException result = new DataException(
                    "模板已发布成功,但 OnlyOffice 发布锁释放失败,需人工恢复并刷新页面");
            result.addSuppressed(releaseError);
            throw result;
        }
    }
 
    private void publishInTransaction(UserContext context, String templateId,
                                      String fencedFileId, String reason) {
        ElnTemplateVersionEntity template = requireTemplateForUpdate(
                context.getTenantId(), templateId);
        if (!ElnTemplateEnums.TemplateStatus.DRAFT.name().equals(template.getBizStatus())) {
            throw new DataException("只有草稿模板可以发布");
        }
        if (!fencedFileId.equals(uniqueDocxFileId(template.getMubanFile()))) {
            throw new DataException("模板附件已变化,请刷新后重试");
        }
        ElnTemplateVersionEntity changed = copyTemplate(template);
        changed.setMubanFile(fileCopier.copy(template.getMubanFile(),
                template.getId() + "-published"));
        validateForPublish(changed);
        changed.setBizStatus(ElnTemplateEnums.TemplateStatus.PUBLISHED.name());
        touch(changed, context);
        store.updateTemplateLifecycle(changed);
        makeFirstRunnableVersionCurrent(context, changed);
        auditLifecycle("ELN_TEMPLATE_PUBLISH", "发布 ELN 模板版本", changed.getId(),
                context, template, changed, trimToNull(reason));
    }
 
    private void makeFirstRunnableVersionCurrent(UserContext context,
                                                 ElnTemplateVersionEntity published) {
        ElnTemplateCurrentVersionEntity current = store.findCurrent(
                context.getTenantId(), published.getMubanBianhao());
        if (current != null
                || !ENABLED.equals(published.getBizEnabled())
                || published.getShengxiaoRiqi() == null
                || published.getShengxiaoRiqi().after(new Date())) {
            return;
        }
        insertCurrent(context, published);
    }
 
    private static String uniqueDocxFileId(String attachments) {
        try {
            List<ElnDocumentFileVo> files = JsonUtil.getJsonToList(attachments, ElnDocumentFileVo.class);
            List<String> docxFileIds = files == null ? Collections.emptyList() : files.stream()
                    .filter(Objects::nonNull)
                    .filter(file -> "docx".equalsIgnoreCase(file.getFileExtension())
                            || StringUtils.hasText(file.getFileId())
                            && file.getFileId().toLowerCase().endsWith(".docx"))
                    .map(ElnDocumentFileVo::getFileId)
                    .filter(StringUtils::hasText)
                    .collect(Collectors.toList());
            if (docxFileIds.size() != 1) {
                throw new DataException("模板必须且只能包含一个 DOCX 附件");
            }
            return docxFileIds.get(0);
        } catch (DataException e) {
            throw e;
        } catch (RuntimeException e) {
            throw new DataException("模板附件无效");
        }
    }
 
    @Override
    @Transactional
    public void enable(String templateId, String reason) {
        changeEnabled(templateId, ENABLED, requireReason(reason),
                "ELN_TEMPLATE_ENABLE", "启用 ELN 模板版本");
    }
 
    @Override
    @Transactional
    public void disable(String templateId, String reason) {
        changeEnabled(templateId, "disabled", requireReason(reason),
                "ELN_TEMPLATE_DISABLE", "停用 ELN 模板版本");
    }
 
    @Override
    @Transactional
    public void switchCurrent(String templateCode, String templateId, String reason) {
        UserContext context = requireContext();
        String actualReason = requireReason(reason);
        if (!StringUtils.hasText(templateCode)) {
            throw new DataException("模板编号不能为空");
        }
        String actualCode = templateCode.trim();
        ElnTemplateVersionEntity target = requireTemplateForUpdate(
                context.getTenantId(), templateId);
        if (!actualCode.equals(target.getMubanBianhao())) {
            throw new DataException("模板编号与目标版本不一致");
        }
        if (!ElnTemplateEnums.TemplateStatus.PUBLISHED.name().equals(target.getBizStatus())
                || !ENABLED.equals(target.getBizEnabled())
                || target.getShengxiaoRiqi() == null
                || target.getShengxiaoRiqi().after(new Date())) {
            throw new DataException("目标模板不具备设为当前版本的资格");
        }
        validateForPublish(target);
 
        ElnTemplateCurrentVersionEntity current =
                store.findCurrent(context.getTenantId(), actualCode);
        String beforeTemplateId = current == null ? null : current.getDangqianMubanId();
        if (current == null) {
            insertCurrent(context, target);
        } else {
            ElnTemplateCurrentVersionEntity changed = copyCurrent(current);
            changed.setDangqianMubanId(target.getId());
            changed.setJianyanXiangmuBianma(target.getJianyanXiangmuBianma());
            touch(changed, context);
            store.updateCurrent(changed);
        }
        auditSwitch(context, actualReason, beforeTemplateId, target.getId());
    }
 
    private void insertCurrent(UserContext context, ElnTemplateVersionEntity target) {
        ElnTemplateCurrentVersionEntity current = new ElnTemplateCurrentVersionEntity();
        current.setId(IdUtil.getSnowflakeNextIdStr());
        current.setFTenantId(context.getTenantId());
        current.setMubanBianhao(target.getMubanBianhao());
        current.setDangqianMubanId(target.getId());
        current.setJianyanXiangmuBianma(target.getJianyanXiangmuBianma());
        current.setFVersion(0);
        current.setFDeleteMark(0);
        current.setFCreatorUserId(context.getUserId());
        touch(current, context);
        try {
            if (!store.insertCurrent(current)) {
                throw new DataException("当前模板设置失败,请重试");
            }
        } catch (DuplicateKeyException e) {
            throw new DataException("当前模板已被其他操作设置,请刷新后重试");
        }
    }
 
    private void changeEnabled(String templateId, String targetEnabled, String reason,
                               String actionCode, String actionLabel) {
        UserContext context = requireContext();
        ElnTemplateVersionEntity template = requireTemplateForUpdate(
                context.getTenantId(), templateId);
        if (targetEnabled.equals(template.getBizEnabled())) {
            throw new DataException(ENABLED.equals(targetEnabled) ? "模板已启用" : "模板已停用");
        }
        ElnTemplateVersionEntity changed = copyTemplate(template);
        changed.setBizEnabled(targetEnabled);
        touch(changed, context);
        store.updateTemplateLifecycle(changed);
        auditLifecycle(actionCode, actionLabel, changed.getId(), context,
                template, changed, reason);
    }
 
    private void validateForPublish(ElnTemplateVersionEntity template) {
        List<ElnTemplateVos.Diagnostic> diagnostics = new ArrayList<>();
        ElnTemplateVos.Diagnostic attachment = attachmentDiagnostic(template.getMubanFile());
        if (attachment != null) {
            diagnostics.add(attachment);
        }
        for (ElnTemplatePublishValidator validator : publishValidators) {
            if (validator == null) {
                continue;
            }
            try {
                List<ElnTemplateVos.Diagnostic> items = validator.validate(
                        template.getFTenantId(), template.getId(), template.getMubanFile());
                if (items != null) {
                    diagnostics.addAll(items);
                }
            } catch (DataException e) {
                diagnostics.add(diagnostic("ERROR", "TEMPLATE_VALIDATION_FAILED", e.getMessage()));
            }
        }
        List<ElnTemplateVos.Diagnostic> errors = diagnostics.stream()
                .filter(item -> item != null && "ERROR".equalsIgnoreCase(item.getSeverity()))
                .collect(Collectors.toList());
        if (!errors.isEmpty()) {
            String message = errors.stream()
                    .map(item -> StringUtils.hasText(item.getMessage())
                            ? item.getMessage() : "模板存在未说明的校验错误")
                    .collect(Collectors.joining(";"));
            throw new DataException("模板发布校验失败:" + message);
        }
    }
 
    private static ElnTemplateVos.Diagnostic attachmentDiagnostic(String attachments) {
        try {
            List<ElnDocumentFileVo> files = JsonUtil.getJsonToList(attachments, ElnDocumentFileVo.class);
            long docxCount = files == null ? 0 : files.stream()
                    .filter(item -> item != null && StringUtils.hasText(item.getFileId()))
                    .filter(item -> "docx".equalsIgnoreCase(item.getFileExtension())
                            || item.getFileId().toLowerCase().endsWith(".docx"))
                    .count();
            return docxCount == 1 ? null : diagnostic("ERROR", "INVALID_DOCX_ATTACHMENT",
                    "模板必须且只能包含一个 DOCX 附件");
        } catch (RuntimeException e) {
            return diagnostic("ERROR", "INVALID_DOCX_ATTACHMENT", "模板附件无效");
        }
    }
 
    static ElnTemplatePublishValidator healthValidator(ElnTemplateHealthService healthService) {
        return new ElnTemplatePublishValidator() {
            @Override
            public List<ElnTemplateVos.Diagnostic> validate(String tenantId, String templateId) {
                return validate(tenantId, templateId, null);
            }
 
            @Override
            public List<ElnTemplateVos.Diagnostic> validate(
                    String tenantId, String templateId, String attachments) {
                ElnTemplateHealthService.HealthReport report = healthService.inspect(templateId, attachments);
                List<ElnTemplateVos.Diagnostic> result = new ArrayList<>();
                if (report == null || report.getDiagnostics() == null) {
                    return result;
                }
                for (ElnTemplateHealthService.HealthDiagnostic source : report.getDiagnostics()) {
                    if (source == null) {
                        continue;
                    }
                    String severity = source.getSeverity();
                    if ("PENDING_BINDING".equals(source.getCode())
                            || "PENDING_CONFIRMATION_REQUIRED".equals(source.getCode())
                            || "FIELD_VERSION_NOT_PUBLISHED".equals(source.getCode())
                            || "CHECKBOX_GROUP_SINGLE_MEMBER".equals(source.getCode())) {
                        severity = "ERROR";
                    }
                    ElnTemplateVos.Diagnostic target = diagnostic(
                            severity, source.getCode(), source.getMessage());
                    target.setBindingId(source.getBindingId());
                    target.setControlTag(source.getControlTag());
                    result.add(target);
                }
                return result;
            }
        };
    }
 
    private static List<ElnTemplatePublishValidator> withHealthValidator(
            ElnTemplateHealthService healthService,
            List<ElnTemplatePublishValidator> injectedValidators) {
        List<ElnTemplatePublishValidator> result = new ArrayList<>();
        result.add(healthValidator(healthService));
        if (injectedValidators != null) {
            result.addAll(injectedValidators);
        }
        return result;
    }
 
    private static ElnTemplateVos.Diagnostic diagnostic(
            String severity, String code, String message) {
        ElnTemplateVos.Diagnostic result = new ElnTemplateVos.Diagnostic();
        result.setSeverity(severity);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }
 
    private ElnTemplateBindingEntity copyBinding(ElnTemplateBindingEntity source,
                                                  ElnTemplateVersionEntity target,
                                                  String operation,
                                                  Map<String, ElnTemplateBindingEntity> sourceBindings,
                                                  Map<String, String> targetBindingIds) {
        ElnTemplateBindingEntity copy = new ElnTemplateBindingEntity();
        copy.setId(targetBindingIds.get(source.getId()));
        copy.setMubanId(target.getId());
        copy.setMubanBianhao(target.getMubanBianhao());
        copy.setZiduanDingyiId(source.getZiduanDingyiId());
        copy.setZiduanBianma(source.getZiduanBianma());
        copy.setZiduanBanbenId(source.getZiduanBanbenId());
        copy.setKongjianBiaoqian(source.getKongjianBiaoqian());
        copy.setKongjianBieming(source.getKongjianBieming());
        copy.setKongjianLeixing(source.getKongjianLeixing());
        copy.setKongjianJuese(source.getKongjianJuese());
        copy.setYinyongShiliId(remapPrimaryBindingId(
                source, sourceBindings, targetBindingIds));
        copy.setRepeatGroupCode(source.getRepeatGroupCode());
        copy.setRepeatPrototypeRowId(source.getRepeatPrototypeRowId());
        copy.setCheckboxGroupCode(source.getCheckboxGroupCode());
        copy.setBangdingZhuangtai(ElnTemplateEnums.BindingStatus.PENDING.name());
        copy.setCaozuoBianma(operation + ":" + source.getId());
        copy.setLaiyuanBangdingId(source.getId());
        copy.setDaoqiShijian(null);
        copy.setZhuangtaiYuanyin(null);
        copy.setFTenantId(target.getFTenantId());
        copy.setFVersion(0);
        copy.setFDeleteMark(0);
        return copy;
    }
 
    private static String remapPrimaryBindingId(ElnTemplateBindingEntity source,
            Map<String, ElnTemplateBindingEntity> sourceBindings,
            Map<String, String> targetBindingIds) {
        if (ElnTemplateEnums.ControlRole.PRIMARY.name().equals(source.getKongjianJuese())) {
            if (StringUtils.hasText(source.getYinyongShiliId())) {
                throw new DataException("源模板主控件引用关系无效");
            }
            return null;
        }
        if (ElnTemplateEnums.ControlRole.REPEAT.name().equals(source.getKongjianJuese())) {
            if (StringUtils.hasText(source.getYinyongShiliId())
                    || !StringUtils.hasText(source.getRepeatGroupCode())
                    || !StringUtils.hasText(source.getRepeatPrototypeRowId())) {
                throw new DataException("源模板重复绑定关系无效");
            }
            return null;
        }
        if (!ElnTemplateEnums.ControlRole.REFERENCE.name().equals(source.getKongjianJuese())
                || !StringUtils.hasText(source.getYinyongShiliId())) {
            throw new DataException("源模板绑定角色无效");
        }
        ElnTemplateBindingEntity primary = sourceBindings.get(source.getYinyongShiliId());
        if (primary == null
                || !ElnTemplateEnums.ControlRole.PRIMARY.name().equals(primary.getKongjianJuese())
                || !source.getZiduanDingyiId().equals(primary.getZiduanDingyiId())
                || !source.getZiduanBanbenId().equals(primary.getZiduanBanbenId())) {
            throw new DataException("源模板引用控件未指向本次复制的有效主控件");
        }
        String targetPrimaryId = targetBindingIds.get(primary.getId());
        if (!StringUtils.hasText(targetPrimaryId)) {
            throw new DataException("目标模板主控件 ID 映射缺失");
        }
        return targetPrimaryId;
    }
 
    private void validateCreateVersion(String sourceTemplateId, ElnTemplateForms.CreateVersion form) {
        if (!StringUtils.hasText(sourceTemplateId) || form == null
                || !StringUtils.hasText(form.getMubanBanben())
                || !StringUtils.hasText(form.getShengbanCaozuoBianma())) {
            throw new DataException("源模板、业务版本和升版操作码不能为空");
        }
    }
 
    private ElnTemplateVersionEntity requireTemplate(String tenantId, String templateId) {
        if (!StringUtils.hasText(templateId)) {
            throw new DataException("模板不存在");
        }
        ElnTemplateVersionEntity template = store.findTemplate(tenantId, templateId.trim());
        if (template == null || !tenantId.equals(template.getFTenantId())) {
            throw new DataException("模板不存在或不属于当前租户");
        }
        return template;
    }
 
    private ElnTemplateVersionEntity requireTemplateForUpdate(
            String tenantId, String templateId) {
        if (!StringUtils.hasText(templateId)) {
            throw new DataException("模板不存在");
        }
        ElnTemplateVersionEntity template = store.findTemplateForUpdate(
                tenantId, templateId.trim());
        if (template == null || !tenantId.equals(template.getFTenantId())) {
            throw new DataException("模板不存在或不属于当前租户");
        }
        return template;
    }
 
    private UserContext requireContext() {
        UserContext context = userContextSupplier.get();
        if (context == null || !StringUtils.hasText(context.getTenantId())) {
            throw new DataException("当前租户无效");
        }
        return context;
    }
 
    private static String requireReason(String reason) {
        if (!StringUtils.hasText(reason)) {
            throw new DataException("操作原因不能为空");
        }
        return reason.trim();
    }
 
    private static String trimToNull(String value) {
        return StringUtils.hasText(value) ? value.trim() : null;
    }
 
    private static String value(String source) {
        return source == null ? "" : source;
    }
 
    private static ElnTemplateVersionEntity copyTemplate(ElnTemplateVersionEntity source) {
        return JsonUtil.getJsonToBean(source, ElnTemplateVersionEntity.class);
    }
 
    private static ElnTemplateCurrentVersionEntity copyCurrent(
            ElnTemplateCurrentVersionEntity source) {
        return JsonUtil.getJsonToBean(source, ElnTemplateCurrentVersionEntity.class);
    }
 
    private static void touch(ElnTemplateVersionEntity target, UserContext context) {
        target.setFLastModifyUserId(context.getUserId());
        target.setFLastModifyTime(new Date());
    }
 
    private static void touch(ElnTemplateCurrentVersionEntity target, UserContext context) {
        target.setFLastModifyUserId(context.getUserId());
        target.setFLastModifyTime(new Date());
    }
 
    private void auditVersionCreate(UserContext context, String operation, String sourceId,
                                    String targetId, String result) {
        Map<String, Object> snapshot = new LinkedHashMap<>();
        snapshot.put("operation", operation);
        snapshot.put("sourceTemplateId", sourceId);
        snapshot.put("targetTemplateId", targetId);
        snapshot.put("result", result);
        auditRecorder.accept(AuditEventDTO.builder()
                .operationId(operation)
                .tenantId(context.getTenantId())
                .operatorId(context.getUserId())
                .eventTime(new Date())
                .eventType("DATA_CHANGE")
                .actionCode("ELN_TEMPLATE_VERSION_CREATE")
                .actionLabel("ELN_TEMPLATE_VERSION_CREATE")
                .bizModule("eln")
                .bizType("eln_template_version")
                .targetTable("eln_template")
                .targetId(targetId)
                .dataSnapshot(JsonUtil.getObjectToString(snapshot))
                .build());
    }
 
    private void auditLifecycle(String actionCode, String actionLabel, String targetId,
                                UserContext context, Object before, Object after, String reason) {
        Map<String, Object> snapshot = new LinkedHashMap<>();
        snapshot.put("before", before);
        snapshot.put("after", after);
        auditRecorder.accept(AuditEventDTO.builder()
                .tenantId(context.getTenantId())
                .operatorId(context.getUserId())
                .eventTime(new Date())
                .eventType("BIZ_ACTION")
                .actionCode(actionCode)
                .actionLabel(actionLabel)
                .bizModule("eln")
                .bizType("eln_template")
                .targetTable("eln_template")
                .targetId(targetId)
                .reason(reason)
                .dataSnapshot(JsonUtil.getObjectToString(snapshot))
                .build());
    }
 
    private void auditSwitch(UserContext context, String reason,
                             String beforeTemplateId, String afterTemplateId) {
        Map<String, Object> snapshot = new LinkedHashMap<>();
        snapshot.put("beforeTemplateId", beforeTemplateId);
        snapshot.put("afterTemplateId", afterTemplateId);
        auditRecorder.accept(AuditEventDTO.builder()
                .tenantId(context.getTenantId())
                .operatorId(context.getUserId())
                .eventTime(new Date())
                .eventType("BIZ_ACTION")
                .actionCode("ELN_TEMPLATE_SWITCH_CURRENT")
                .actionLabel("切换 ELN 当前模板版本")
                .bizModule("eln")
                .bizType("eln_template")
                .targetTable("eln_template_current_version")
                .targetId(afterTemplateId)
                .reason(reason)
                .dataSnapshot(JsonUtil.getObjectToString(snapshot))
                .build());
    }
 
    private static ElnTemplateVos.ListItem toListItem(ElnTemplateVersionEntity source) {
        ElnTemplateVos.ListItem result = new ElnTemplateVos.ListItem();
        result.setId(source.getId());
        result.setMubanBianhao(source.getMubanBianhao());
        result.setMubanBanben(source.getMubanBanben());
        result.setJianyanXiangmu(source.getJianyanXiangmu());
        result.setJianyanXiangmuBianma(source.getJianyanXiangmuBianma());
        result.setJianyanXiangmuMingcheng(source.getJianyanXiangmuMingcheng());
        result.setMubanFenlei(source.getMubanFenlei());
        result.setMubanFenleiMingcheng(source.getMubanFenleiMingcheng());
        result.setBizStatus(source.getBizStatus());
        result.setBizEnabled(source.getBizEnabled());
        result.setShengxiaoRiqi(source.getShengxiaoRiqi());
        result.setGengxinShijian(source.getFLastModifyTime() == null
                ? source.getFCreatorTime() : source.getFLastModifyTime());
        result.setChuangjianShijian(source.getChuangjianShijian() == null
                ? source.getFCreatorTime() : source.getChuangjianShijian());
        return result;
    }
 
    private static ElnTemplateVos.Detail toDetail(ElnTemplateVersionEntity source) {
        ElnTemplateVos.Detail result = new ElnTemplateVos.Detail();
        ElnTemplateVos.ListItem base = toListItem(source);
        result.setId(base.getId());
        result.setMubanBianhao(base.getMubanBianhao());
        result.setMubanBanben(base.getMubanBanben());
        result.setJianyanXiangmu(base.getJianyanXiangmu());
        result.setJianyanXiangmuBianma(base.getJianyanXiangmuBianma());
        result.setJianyanXiangmuMingcheng(base.getJianyanXiangmuMingcheng());
        result.setMubanFenlei(base.getMubanFenlei());
        result.setMubanFenleiMingcheng(base.getMubanFenleiMingcheng());
        result.setBizStatus(base.getBizStatus());
        result.setBizEnabled(base.getBizEnabled());
        result.setShengxiaoRiqi(base.getShengxiaoRiqi());
        result.setGengxinShijian(base.getGengxinShijian());
        result.setChuangjianShijian(base.getChuangjianShijian());
        result.setMubanMingcheng(source.getMubanMingcheng());
        result.setShiyanBuzhou(source.getShiyanBuzhou());
        result.setChuangjianRenyuan(firstText(
                source.getChuangjianRenyuan(), source.getFCreatorUserId()));
        result.setMubanFile(source.getMubanFile());
        result.setLaiyuanMubanId(source.getLaiyuanMubanId());
        result.setShengbanCaozuoBianma(source.getShengbanCaozuoBianma());
        return result;
    }
 
    private void mergeSourceChain(String tenantId, ElnTemplateVersionEntity current,
                                  ElnTemplateVos.Detail result) {
        Set<String> visited = new LinkedHashSet<>();
        visited.add(current.getId());
        String sourceId = current.getLaiyuanMubanId();
        int depth = 0;
        while (StringUtils.hasText(sourceId)
                && depth++ < MAX_SOURCE_CHAIN_DEPTH
                && visited.add(sourceId)) {
            ElnTemplateVersionEntity source = store.findTemplate(tenantId, sourceId);
            if (source == null) {
                break;
            }
            fillMissingDetailFields(result, source);
            sourceId = source.getLaiyuanMubanId();
        }
    }
 
    private static void fillMissingDetailFields(ElnTemplateVos.Detail target,
                                                ElnTemplateVersionEntity source) {
        if (!StringUtils.hasText(target.getMubanMingcheng())) {
            target.setMubanMingcheng(source.getMubanMingcheng());
        }
        if (!StringUtils.hasText(target.getShiyanBuzhou())) {
            target.setShiyanBuzhou(source.getShiyanBuzhou());
        }
        if (!StringUtils.hasText(target.getJianyanXiangmu())) {
            target.setJianyanXiangmu(source.getJianyanXiangmu());
        }
        if (!StringUtils.hasText(target.getJianyanXiangmuBianma())) {
            target.setJianyanXiangmuBianma(source.getJianyanXiangmuBianma());
        }
        if (!StringUtils.hasText(target.getJianyanXiangmuMingcheng())) {
            target.setJianyanXiangmuMingcheng(source.getJianyanXiangmuMingcheng());
        }
        if (!StringUtils.hasText(target.getMubanFenlei())) {
            target.setMubanFenlei(source.getMubanFenlei());
        }
        if (!StringUtils.hasText(target.getMubanFenleiMingcheng())) {
            target.setMubanFenleiMingcheng(source.getMubanFenleiMingcheng());
        }
        if (!StringUtils.hasText(target.getChuangjianRenyuan())) {
            target.setChuangjianRenyuan(firstText(
                    source.getChuangjianRenyuan(), source.getFCreatorUserId()));
        }
        if (target.getChuangjianShijian() == null) {
            target.setChuangjianShijian(source.getChuangjianShijian() == null
                    ? source.getFCreatorTime() : source.getChuangjianShijian());
        }
    }
 
    private void enrichDetailNames(ElnTemplateVos.Detail result) {
        result.setChuangjianRenyuanMingcheng(resolveUserName(
                result.getChuangjianRenyuan()));
    }
 
    private String resolveUserName(String userId) {
        if (!StringUtils.hasText(userId)) {
            return userId;
        }
        try {
            String name = userNameResolver.resolve(userId);
            return StringUtils.hasText(name) ? name : userId;
        } catch (RuntimeException ignored) {
            return userId;
        }
    }
 
    private static String firstText(String first, String second) {
        return StringUtils.hasText(first) ? first : second;
    }
 
    private static UserNameResolver remoteUserNameResolver(UserApi userApi) {
        return userId -> {
            List<UserEntity> users = userApi.getUserName(Collections.singletonList(userId));
            if (users == null) {
                return null;
            }
            return users.stream()
                    .filter(user -> userId.equals(user.getId()))
                    .map(user -> firstText(user.getRealName(), user.getAccount()))
                    .filter(StringUtils::hasText)
                    .findFirst().orElse(null);
        };
    }
 
    static String deterministicTargetId(String tenantId, String sourceTemplateId,
                                        String operationCode) {
        String seed = tenantId + "\u0000" + sourceTemplateId + "\u0000" + operationCode;
        return UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8))
                .toString().replace("-", "");
    }
 
    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 TargetIdFactory {
        String create(String tenantId, String sourceTemplateId, String operationCode);
    }
 
    interface TemplateFileCopier {
        String copy(String sourceAttachments, String targetTemplateId);
    }
 
    interface TemplatePublishFence {
        String acquire(String tenantId, String templateId, String fileId, String fileType);
 
        void release(String tenantId, String templateId, String fileId, String fileType, String token);
 
        static TemplatePublishFence noop() {
            return new TemplatePublishFence() {
                @Override
                public String acquire(String tenantId, String templateId,
                        String fileId, String fileType) {
                    return "noop";
                }
 
                @Override
                public void release(String tenantId, String templateId,
                        String fileId, String fileType, String token) {
                }
            };
        }
    }
 
    private static TemplatePublishFence remotePublishFence(TemplatePublishFenceApi api) {
        return new TemplatePublishFence() {
            @Override
            public String acquire(String tenantId, String templateId,
                    String fileId, String fileType) {
                ActionResult<String> result = api.acquire(
                        tenantId, templateId, fileId, fileType);
                if (result == null
                        || !ActionResultCode.SUCCESS.getCode().equals(result.getCode())
                        || !StringUtils.hasText(result.getData())) {
                    throw new DataException(result == null || !StringUtils.hasText(result.getMsg())
                            ? "无法锁定 OnlyOffice 模板文件,请稍后重试" : result.getMsg());
                }
                return result.getData();
            }
 
            @Override
            public void release(String tenantId, String templateId,
                    String fileId, String fileType, String token) {
                ActionResult<Boolean> result = api.release(
                        tenantId, templateId, fileId, fileType, token);
                if (result == null
                        || !ActionResultCode.SUCCESS.getCode().equals(result.getCode())
                        || !Boolean.TRUE.equals(result.getData())) {
                    throw new DataException(result == null || !StringUtils.hasText(result.getMsg())
                            ? "OnlyOffice 发布锁释放失败,需人工恢复" : result.getMsg());
                }
            }
        };
    }
 
    interface TransactionRunner {
        ElnTemplateVos.Detail execute(Supplier<ElnTemplateVos.Detail> callback);
    }
 
    private static final class SpringTransactionRunner implements TransactionRunner {
        private final TransactionTemplate transactionTemplate;
 
        private SpringTransactionRunner(PlatformTransactionManager transactionManager) {
            this.transactionTemplate = new TransactionTemplate(transactionManager);
            this.transactionTemplate.setPropagationBehavior(
                    TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        }
 
        @Override
        public ElnTemplateVos.Detail execute(Supplier<ElnTemplateVos.Detail> callback) {
            return transactionTemplate.execute(status -> callback.get());
        }
    }
 
    interface TemplateCatalogStore {
        ElnTemplateVersionEntity findTemplate(String tenantId, String templateId);
 
        ElnTemplateVersionEntity findTemplateForUpdate(String tenantId, String templateId);
 
        ElnTemplateVersionEntity findByOperation(String tenantId, String operationCode);
 
        ElnTemplateVersionEntity findByCodeAndVersion(
                String tenantId, String templateCode, String businessVersion);
 
        void insertTemplate(ElnTemplateVersionEntity template);
 
        void updateTemplateFile(ElnTemplateVersionEntity template);
 
        void updateTemplateLifecycle(ElnTemplateVersionEntity template);
 
        ElnTemplateCurrentVersionEntity findCurrent(String tenantId, String templateCode);
 
        List<ElnTemplateCurrentVersionEntity> listCurrentVersions(
                String tenantId, List<String> templateCodes);
 
        boolean insertCurrent(ElnTemplateCurrentVersionEntity current);
 
        void updateCurrent(ElnTemplateCurrentVersionEntity current);
 
        List<ElnTemplateBindingEntity> listActiveBindings(String tenantId, String templateId);
 
        List<ElnTemplateBindingEntity> listActiveBindingsByTemplateIds(
                String tenantId, List<String> templateIds);
 
        default List<ElnTemplateVos.TemplateCategory> listTemplateCategories(
                String tenantId, List<String> templateCategoryIds) {
            return Collections.emptyList();
        }
 
        void insertBinding(ElnTemplateBindingEntity binding);
 
        IPage<ElnTemplateVersionEntity> page(String tenantId, ElnTemplateForms.Query query);
 
        IPage<ElnTemplateVos.CatalogItem> pageDirectory(
                String tenantId, ElnTemplateForms.Query query);
    }
 
    interface UserNameResolver {
        String resolve(String userId);
    }
 
    interface VersionGroupCopier {
        void copy(String tenantId, String sourceTemplateId, String targetTemplateId);
    }
 
    private static final class MyBatisTemplateCatalogStore implements TemplateCatalogStore {
        private final ElnTemplateMapper templateMapper;
        private final ElnTemplateBindingMapper bindingMapper;
        private final ElnTemplateCurrentVersionMapper currentMapper;
 
        private MyBatisTemplateCatalogStore(ElnTemplateMapper templateMapper,
                                            ElnTemplateBindingMapper bindingMapper,
                                            ElnTemplateCurrentVersionMapper currentMapper) {
            this.templateMapper = templateMapper;
            this.bindingMapper = bindingMapper;
            this.currentMapper = currentMapper;
        }
 
        @Override
        public ElnTemplateVersionEntity findTemplate(String tenantId, String templateId) {
            return templateMapper.selectOne(templateQuery(tenantId)
                    .eq(ElnTemplateVersionEntity::getId, templateId));
        }
 
        @Override
        public ElnTemplateVersionEntity findTemplateForUpdate(
                String tenantId, String templateId) {
            return templateMapper.selectOne(templateQuery(tenantId)
                    .eq(ElnTemplateVersionEntity::getId, templateId)
                    .last("FOR UPDATE"));
        }
 
        @Override
        public ElnTemplateVersionEntity findByOperation(String tenantId, String operationCode) {
            return templateMapper.selectOne(templateQuery(tenantId)
                    .eq(ElnTemplateVersionEntity::getShengbanCaozuoBianma, operationCode));
        }
 
        @Override
        public ElnTemplateVersionEntity findByCodeAndVersion(
                String tenantId, String templateCode, String businessVersion) {
            return templateMapper.selectOne(templateQuery(tenantId)
                    .eq(ElnTemplateVersionEntity::getMubanBianhao, templateCode)
                    .eq(ElnTemplateVersionEntity::getMubanBanben, businessVersion));
        }
 
        @Override
        public void insertTemplate(ElnTemplateVersionEntity template) {
            templateMapper.insert(template);
        }
 
        @Override
        public void updateTemplateFile(ElnTemplateVersionEntity template) {
            Integer expectedVersion = template.getFVersion();
            int nextVersion = expectedVersion == null ? 1 : expectedVersion + 1;
            LambdaUpdateWrapper<ElnTemplateVersionEntity> update =
                    Wrappers.<ElnTemplateVersionEntity>lambdaUpdate()
                            .eq(ElnTemplateVersionEntity::getFTenantId, template.getFTenantId())
                            .eq(ElnTemplateVersionEntity::getId, template.getId())
                            .and(item -> item.isNull(ElnTemplateVersionEntity::getFDeleteMark)
                                    .or().eq(ElnTemplateVersionEntity::getFDeleteMark, 0))
                            .set(ElnTemplateVersionEntity::getMubanFile, template.getMubanFile())
                            .set(ElnTemplateVersionEntity::getFLastModifyUserId,
                                    template.getFLastModifyUserId())
                            .set(ElnTemplateVersionEntity::getFLastModifyTime,
                                    template.getFLastModifyTime())
                            .set(ElnTemplateVersionEntity::getFVersion, nextVersion);
            if (expectedVersion == null) {
                update.isNull(ElnTemplateVersionEntity::getFVersion);
            } else {
                update.eq(ElnTemplateVersionEntity::getFVersion, expectedVersion);
            }
            if (templateMapper.update(null, update) != 1) {
                throw new DataException("模板状态已变化,请刷新后重试");
            }
            template.setFVersion(nextVersion);
        }
 
        @Override
        public void updateTemplateLifecycle(ElnTemplateVersionEntity template) {
            Integer expectedVersion = template.getFVersion();
            int nextVersion = expectedVersion == null ? 1 : expectedVersion + 1;
            LambdaUpdateWrapper<ElnTemplateVersionEntity> update =
                    Wrappers.<ElnTemplateVersionEntity>lambdaUpdate()
                            .eq(ElnTemplateVersionEntity::getFTenantId, template.getFTenantId())
                            .eq(ElnTemplateVersionEntity::getId, template.getId())
                            .and(item -> item.isNull(ElnTemplateVersionEntity::getFDeleteMark)
                                    .or().eq(ElnTemplateVersionEntity::getFDeleteMark, 0))
                            .set(ElnTemplateVersionEntity::getMubanFile, template.getMubanFile())
                            .set(ElnTemplateVersionEntity::getBizStatus, template.getBizStatus())
                            .set(ElnTemplateVersionEntity::getBizEnabled, template.getBizEnabled())
                            .set(ElnTemplateVersionEntity::getFLastModifyUserId,
                                    template.getFLastModifyUserId())
                            .set(ElnTemplateVersionEntity::getFLastModifyTime,
                                    template.getFLastModifyTime())
                            .set(ElnTemplateVersionEntity::getFVersion, nextVersion);
            if (expectedVersion == null) {
                update.isNull(ElnTemplateVersionEntity::getFVersion);
            } else {
                update.eq(ElnTemplateVersionEntity::getFVersion, expectedVersion);
            }
            if (templateMapper.update(null, update) != 1) {
                throw new DataException("模板状态已变化,请刷新后重试");
            }
            template.setFVersion(nextVersion);
        }
 
        @Override
        public ElnTemplateCurrentVersionEntity findCurrent(String tenantId, String templateCode) {
            return currentMapper.selectOne(Wrappers.<ElnTemplateCurrentVersionEntity>lambdaQuery()
                    .eq(ElnTemplateCurrentVersionEntity::getFTenantId, tenantId)
                    .eq(ElnTemplateCurrentVersionEntity::getMubanBianhao, templateCode)
                    .and(item -> item.isNull(ElnTemplateCurrentVersionEntity::getFDeleteMark)
                            .or().eq(ElnTemplateCurrentVersionEntity::getFDeleteMark, 0)));
        }
 
        @Override
        public List<ElnTemplateCurrentVersionEntity> listCurrentVersions(
                String tenantId, List<String> templateCodes) {
            if (templateCodes.isEmpty()) {
                return Collections.emptyList();
            }
            return currentMapper.selectList(
                    Wrappers.<ElnTemplateCurrentVersionEntity>lambdaQuery()
                            .eq(ElnTemplateCurrentVersionEntity::getFTenantId, tenantId)
                            .in(ElnTemplateCurrentVersionEntity::getMubanBianhao, templateCodes)
                            .and(item -> item.isNull(ElnTemplateCurrentVersionEntity::getFDeleteMark)
                                    .or().eq(ElnTemplateCurrentVersionEntity::getFDeleteMark, 0)));
        }
 
        @Override
        public boolean insertCurrent(ElnTemplateCurrentVersionEntity current) {
            return currentMapper.insert(current) == 1;
        }
 
        @Override
        public void updateCurrent(ElnTemplateCurrentVersionEntity current) {
            Integer expectedVersion = current.getFVersion();
            int nextVersion = expectedVersion == null ? 1 : expectedVersion + 1;
            LambdaUpdateWrapper<ElnTemplateCurrentVersionEntity> update =
                    Wrappers.<ElnTemplateCurrentVersionEntity>lambdaUpdate()
                            .eq(ElnTemplateCurrentVersionEntity::getFTenantId,
                                    current.getFTenantId())
                            .eq(ElnTemplateCurrentVersionEntity::getMubanBianhao,
                                    current.getMubanBianhao())
                            .eq(ElnTemplateCurrentVersionEntity::getId, current.getId())
                            .and(item -> item.isNull(ElnTemplateCurrentVersionEntity::getFDeleteMark)
                                    .or().eq(ElnTemplateCurrentVersionEntity::getFDeleteMark, 0))
                            .set(ElnTemplateCurrentVersionEntity::getDangqianMubanId,
                                    current.getDangqianMubanId())
                            .set(ElnTemplateCurrentVersionEntity::getFLastModifyUserId,
                                    current.getFLastModifyUserId())
                            .set(ElnTemplateCurrentVersionEntity::getFLastModifyTime,
                                    current.getFLastModifyTime())
                            .set(ElnTemplateCurrentVersionEntity::getFVersion, nextVersion);
            if (expectedVersion == null) {
                update.isNull(ElnTemplateCurrentVersionEntity::getFVersion);
            } else {
                update.eq(ElnTemplateCurrentVersionEntity::getFVersion, expectedVersion);
            }
            if (currentMapper.update(null, update) != 1) {
                throw new DataException("当前模板已变化,请刷新后重试");
            }
            current.setFVersion(nextVersion);
        }
 
        @Override
        public List<ElnTemplateBindingEntity> listActiveBindings(String tenantId, String templateId) {
            return bindingMapper.selectList(Wrappers.<ElnTemplateBindingEntity>lambdaQuery()
                    .eq(ElnTemplateBindingEntity::getFTenantId, tenantId)
                    .eq(ElnTemplateBindingEntity::getMubanId, templateId)
                    .eq(ElnTemplateBindingEntity::getBangdingZhuangtai,
                            ElnTemplateEnums.BindingStatus.ACTIVE.name())
                    .and(item -> item.isNull(ElnTemplateBindingEntity::getFDeleteMark)
                            .or().eq(ElnTemplateBindingEntity::getFDeleteMark, 0)));
        }
 
        @Override
        public List<ElnTemplateBindingEntity> listActiveBindingsByTemplateIds(
                String tenantId, List<String> templateIds) {
            if (templateIds.isEmpty()) {
                return Collections.emptyList();
            }
            return bindingMapper.selectList(Wrappers.<ElnTemplateBindingEntity>lambdaQuery()
                    .eq(ElnTemplateBindingEntity::getFTenantId, tenantId)
                    .in(ElnTemplateBindingEntity::getMubanId, templateIds)
                    .eq(ElnTemplateBindingEntity::getBangdingZhuangtai,
                            ElnTemplateEnums.BindingStatus.ACTIVE.name())
                    .and(item -> item.isNull(ElnTemplateBindingEntity::getFDeleteMark)
                            .or().eq(ElnTemplateBindingEntity::getFDeleteMark, 0)));
        }
 
        @Override
        public List<ElnTemplateVos.TemplateCategory> listTemplateCategories(
                String tenantId, List<String> templateCategoryIds) {
            if (templateCategoryIds.isEmpty()) {
                return Collections.emptyList();
            }
            return templateMapper.selectTemplateCategories(tenantId, templateCategoryIds);
        }
 
        @Override
        public void insertBinding(ElnTemplateBindingEntity binding) {
            bindingMapper.insert(binding);
        }
 
        @Override
        public IPage<ElnTemplateVersionEntity> page(String tenantId, ElnTemplateForms.Query form) {
            if (ElnTemplateForms.VersionScope.LATEST.equals(form.getVersionScope())) {
                return pageLatestVersions(tenantId, form);
            }
            LambdaQueryWrapper<ElnTemplateVersionEntity> query = templateQuery(tenantId);
            applyPageFilters(query, form);
            query.orderByDesc(ElnTemplateVersionEntity::getFLastModifyTime)
                    .orderByDesc(ElnTemplateVersionEntity::getFCreatorTime)
                    .orderByDesc(ElnTemplateVersionEntity::getId);
            return templateMapper.selectPage(new Page<>(form.getCurrentPage(), form.getPageSize()), query);
        }
 
        @Override
        public IPage<ElnTemplateVos.CatalogItem> pageDirectory(
                String tenantId, ElnTemplateForms.Query form) {
            String keyword = trimToNull(form.getKeyword());
            return templateMapper.selectTemplateDirectory(
                    new Page<>(form.getCurrentPage(), form.getPageSize()),
                    tenantId,
                    trimToNull(form.getMubanFenlei()),
                    trimToNull(form.getMubanBianhao()),
                    trimToNull(form.getBizStatus()),
                    trimToNull(form.getBizEnabled()),
                    keyword == null ? null : "%" + keyword + "%");
        }
 
        private IPage<ElnTemplateVersionEntity> pageLatestVersions(
                String tenantId, ElnTemplateForms.Query form) {
            String keyword = trimToNull(form.getKeyword());
            IPage<String> codePage = templateMapper.selectLatestTemplateCodes(
                    new Page<>(form.getCurrentPage(), form.getPageSize()),
                    tenantId,
                    trimToNull(form.getMubanFenlei()),
                    trimToNull(form.getMubanBianhao()),
                    trimToNull(form.getBizStatus()),
                    trimToNull(form.getBizEnabled()),
                    keyword == null ? null : "%" + keyword + "%");
            Page<ElnTemplateVersionEntity> result =
                    new Page<>(codePage.getCurrent(), codePage.getSize());
            result.setTotal(codePage.getTotal());
            if (codePage.getRecords().isEmpty()) {
                return result;
            }
 
            LambdaQueryWrapper<ElnTemplateVersionEntity> query = templateQuery(tenantId)
                    .in(ElnTemplateVersionEntity::getMubanBianhao, codePage.getRecords());
            applyPageFilters(query, form);
            List<ElnTemplateVersionEntity> candidates = templateMapper.selectList(query);
            candidates.sort(MyBatisTemplateCatalogStore::compareLatestFirst);
            Map<String, ElnTemplateVersionEntity> latestByCode = new LinkedHashMap<>();
            for (ElnTemplateVersionEntity candidate : candidates) {
                latestByCode.putIfAbsent(candidate.getMubanBianhao(), candidate);
            }
            List<ElnTemplateVersionEntity> records = codePage.getRecords().stream()
                    .map(latestByCode::get)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            result.setRecords(records);
            return result;
        }
 
        private static void applyPageFilters(
                LambdaQueryWrapper<ElnTemplateVersionEntity> query,
                ElnTemplateForms.Query form) {
            if (StringUtils.hasText(form.getMubanBianhao())) {
                query.eq(ElnTemplateVersionEntity::getMubanBianhao, form.getMubanBianhao().trim());
            }
            if (StringUtils.hasText(form.getMubanFenlei())) {
                query.eq(ElnTemplateVersionEntity::getMubanFenlei, form.getMubanFenlei().trim());
            }
            if (StringUtils.hasText(form.getBizStatus())) {
                query.eq(ElnTemplateVersionEntity::getBizStatus, form.getBizStatus().trim());
            }
            if (StringUtils.hasText(form.getBizEnabled())) {
                query.eq(ElnTemplateVersionEntity::getBizEnabled, form.getBizEnabled().trim());
            }
            if (StringUtils.hasText(form.getKeyword())) {
                String keyword = form.getKeyword().trim();
                query.and(item -> item.like(ElnTemplateVersionEntity::getMubanBianhao, keyword)
                        .or().like(ElnTemplateVersionEntity::getMubanBanben, keyword)
                        .or().like(ElnTemplateVersionEntity::getJianyanXiangmu, keyword)
                        .or().like(ElnTemplateVersionEntity::getJianyanXiangmuMingcheng,
                                keyword));
            }
        }
 
        private static int compareLatestFirst(ElnTemplateVersionEntity left,
                                              ElnTemplateVersionEntity right) {
            int byTime = Comparator.nullsLast(Comparator.<Date>reverseOrder())
                    .compare(versionTimestamp(left), versionTimestamp(right));
            if (byTime != 0) {
                return byTime;
            }
            return Comparator.nullsLast(Comparator.<String>reverseOrder())
                    .compare(left.getId(), right.getId());
        }
 
        private static Date versionTimestamp(ElnTemplateVersionEntity version) {
            if (version.getFLastModifyTime() != null) {
                return version.getFLastModifyTime();
            }
            if (version.getFCreatorTime() != null) {
                return version.getFCreatorTime();
            }
            return version.getChuangjianShijian();
        }
 
        private static String trimToNull(String value) {
            return StringUtils.hasText(value) ? value.trim() : null;
        }
 
        private static LambdaQueryWrapper<ElnTemplateVersionEntity> templateQuery(String tenantId) {
            return Wrappers.<ElnTemplateVersionEntity>lambdaQuery()
                    .eq(ElnTemplateVersionEntity::getFTenantId, tenantId)
                    .and(item -> item.isNull(ElnTemplateVersionEntity::getFDeleteMark)
                            .or().eq(ElnTemplateVersionEntity::getFDeleteMark, 0));
        }
    }
}