刘光辉
4 小时以前 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
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
package jnpf.elnService.template.impl;
 
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jnpf.audit.model.AuditEventDTO;
import jnpf.audit.sdk.AuditClient;
import jnpf.base.UserInfo;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.elnEntity.ElnDocumentFileVo;
import jnpf.elnEntity.field.ElnFieldDefEntity;
import jnpf.elnEntity.field.ElnFieldEnums;
import jnpf.elnEntity.field.ElnFieldForms;
import jnpf.elnEntity.field.ElnFieldVersionEntity;
import jnpf.elnEntity.field.ElnFieldVos;
import jnpf.elnEntity.template.ElnTemplateBindingEntity;
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.ElnFieldDefMapper;
import jnpf.elnMapper.ElnFieldVersionMapper;
import jnpf.elnMapper.ElnTemplateBindingMapper;
import jnpf.elnService.ElnFieldCatalogService;
import jnpf.elnService.template.ElnTemplateBindingConfirmationFacade;
import jnpf.elnService.template.ElnTemplateBindingDependencyValidator;
import jnpf.elnService.template.ElnTemplateBindingLifecycleParticipant;
import jnpf.elnService.template.ElnTemplateBindingService;
import jnpf.elnService.template.ElnTemplateCheckboxGroupService;
import jnpf.elnService.template.ElnTemplateDocumentEvidence;
import jnpf.elnService.template.ElnTemplateOperationException;
import jnpf.elnService.template.ElnPendingBindingCleanupService;
import jnpf.elnService.template.ElnTemplateRepeatGroupService;
import jnpf.elnService.template.ElnTemplateVersionCopyParticipant;
import jnpf.elnService.template.ElnTemplateStepService;
import jnpf.elnService.template.TemplateAnnotationAuthorization;
import jnpf.elnService.template.docx.DocxControlConfigMatcher;
import jnpf.elnService.template.docx.DocxExpectedControlConfig;
import jnpf.elnService.template.docx.DocxControlSnapshot;
import jnpf.exception.DataException;
import jnpf.model.tenant.TenantVO;
import jnpf.util.JsonUtil;
import jnpf.util.UserProvider;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
 
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
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;
 
@Service
public class ElnTemplateBindingServiceImpl implements ElnTemplateBindingService {
 
    private static final String ENABLED = "enabled";
    private static final String DRAFT = ElnTemplateEnums.TemplateStatus.DRAFT.name();
    private static final String PENDING = ElnTemplateEnums.BindingStatus.PENDING.name();
    private static final String ACTIVE = ElnTemplateEnums.BindingStatus.ACTIVE.name();
    private static final String CANCELLED = ElnTemplateEnums.BindingStatus.CANCELLED.name();
    private static final String REMOVED = ElnTemplateEnums.BindingStatus.REMOVED.name();
    private static final String PRIMARY = ElnTemplateEnums.ControlRole.PRIMARY.name();
    private static final String REFERENCE = ElnTemplateEnums.ControlRole.REFERENCE.name();
    private static final String REPEAT = ElnTemplateEnums.ControlRole.REPEAT.name();
    private static final String REPEAT_PROTOTYPE_ROW_ID = "prototype";
 
    private final BindingStore store;
    private final ElnFieldCatalogService fieldCatalogService;
    private final ElnTemplateRepeatGroupService repeatGroupService;
    private final List<ElnTemplateBindingDependencyValidator> dependencyValidators;
    private final List<ElnTemplateVersionCopyParticipant> copyParticipants;
    private final List<ElnTemplateBindingLifecycleParticipant> lifecycleParticipants;
    private final Supplier<String> bindingIdSupplier;
    private final Supplier<String> referenceInstanceIdSupplier;
    private final Consumer<AuditEventDTO> auditRecorder;
    private final ElnTemplateDocumentEvidence documentEvidence;
    private final ElnPendingBindingCleanupService pendingCleanupService;
    private final Supplier<UserContext> userContextSupplier;
    private final ElnTemplateBindingConfirmationFacade confirmationFacade;
    private final StepAssignmentResolver stepAssignmentResolver;
    private final StepConfigurationReader stepConfigurationReader;
    private ElnTemplateCheckboxGroupService checkboxGroupService;
    private long pendingTimeoutMinutes;
 
    @Autowired
    public ElnTemplateBindingServiceImpl(ElnTemplateMapper templateMapper,
            ElnFieldDefMapper fieldMapper, ElnFieldVersionMapper fieldVersionMapper,
            ElnTemplateBindingMapper bindingMapper, ElnFieldCatalogService fieldCatalogService,
            ElnTemplateRepeatGroupService repeatGroupService,
            ElnTemplateCheckboxGroupService checkboxGroupService,
            ElnTemplateStepService stepService,
            List<ElnTemplateBindingDependencyValidator> dependencyValidators,
            List<ElnTemplateVersionCopyParticipant> copyParticipants,
            List<ElnTemplateBindingLifecycleParticipant> lifecycleParticipants,
            ObjectProvider<AuditClient> auditClientProvider,
            ObjectProvider<ElnTemplateDocumentEvidence> documentEvidenceProvider,
            ElnPendingBindingCleanupService pendingCleanupService,
            @Value("${eln.template-binding.pending-timeout-minutes:30}")
            long pendingTimeoutMinutes,
            ElnTemplateBindingConfirmationFacade confirmationFacade) {
        this(new MyBatisBindingStore(templateMapper, fieldMapper, fieldVersionMapper, bindingMapper),
                fieldCatalogService, repeatGroupService, dependencyValidators, copyParticipants,
                lifecycleParticipants,
                IdUtil::getSnowflakeNextIdStr,
                () -> UUID.randomUUID().toString().replace("-", ""),
                event -> {
                    AuditClient client = auditClientProvider.getIfAvailable();
                    if (client != null) {
                        client.record(event);
                    }
                }, evidence(documentEvidenceProvider), pendingCleanupService,
                ElnTemplateBindingServiceImpl::currentUserContext, confirmationFacade,
                stepService::resolveAssignment, stepService::configuration);
        this.checkboxGroupService = checkboxGroupService;
        this.pendingTimeoutMinutes = pendingTimeoutMinutes;
    }
 
    ElnTemplateBindingServiceImpl(BindingStore store,
            ElnFieldCatalogService fieldCatalogService,
            ElnTemplateRepeatGroupService repeatGroupService,
            List<ElnTemplateBindingDependencyValidator> dependencyValidators,
            List<ElnTemplateVersionCopyParticipant> copyParticipants,
            List<ElnTemplateBindingLifecycleParticipant> lifecycleParticipants,
            Supplier<String> bindingIdSupplier, Supplier<String> referenceInstanceIdSupplier,
            Consumer<AuditEventDTO> auditRecorder, ElnTemplateDocumentEvidence documentEvidence,
            Supplier<UserContext> userContextSupplier,
            ElnTemplateBindingConfirmationFacade confirmationFacade) {
        this(store, fieldCatalogService, repeatGroupService, dependencyValidators, copyParticipants,
                lifecycleParticipants,
                bindingIdSupplier, referenceInstanceIdSupplier, auditRecorder, documentEvidence,
                null, userContextSupplier, confirmationFacade);
    }
 
    ElnTemplateBindingServiceImpl(BindingStore store,
            ElnFieldCatalogService fieldCatalogService,
            ElnTemplateRepeatGroupService repeatGroupService,
            List<ElnTemplateBindingDependencyValidator> dependencyValidators,
            List<ElnTemplateVersionCopyParticipant> copyParticipants,
            List<ElnTemplateBindingLifecycleParticipant> lifecycleParticipants,
            Supplier<String> bindingIdSupplier, Supplier<String> referenceInstanceIdSupplier,
            Consumer<AuditEventDTO> auditRecorder, ElnTemplateDocumentEvidence documentEvidence,
            ElnPendingBindingCleanupService pendingCleanupService,
            Supplier<UserContext> userContextSupplier,
            ElnTemplateBindingConfirmationFacade confirmationFacade) {
        this(store, fieldCatalogService, repeatGroupService, dependencyValidators, copyParticipants,
                lifecycleParticipants,
                bindingIdSupplier, referenceInstanceIdSupplier, auditRecorder, documentEvidence,
                pendingCleanupService, userContextSupplier, confirmationFacade,
                (tenantId, templateId, requestedStepId) -> StringUtils.hasText(requestedStepId)
                        ? requestedStepId.trim() : "test-single-step",
                templateId -> singleStepConfiguration("test-single-step"));
    }
 
    ElnTemplateBindingServiceImpl(BindingStore store,
            ElnFieldCatalogService fieldCatalogService,
            ElnTemplateRepeatGroupService repeatGroupService,
            List<ElnTemplateBindingDependencyValidator> dependencyValidators,
            List<ElnTemplateVersionCopyParticipant> copyParticipants,
            List<ElnTemplateBindingLifecycleParticipant> lifecycleParticipants,
            Supplier<String> bindingIdSupplier, Supplier<String> referenceInstanceIdSupplier,
            Consumer<AuditEventDTO> auditRecorder, ElnTemplateDocumentEvidence documentEvidence,
            Supplier<UserContext> userContextSupplier,
            ElnTemplateBindingConfirmationFacade confirmationFacade,
            ElnTemplateCheckboxGroupService checkboxGroupService) {
        this(store, fieldCatalogService, repeatGroupService, dependencyValidators, copyParticipants,
                lifecycleParticipants, bindingIdSupplier, referenceInstanceIdSupplier,
                auditRecorder, documentEvidence, userContextSupplier, confirmationFacade);
        this.checkboxGroupService = checkboxGroupService;
    }
 
    private ElnTemplateBindingServiceImpl(BindingStore store,
            ElnFieldCatalogService fieldCatalogService,
            ElnTemplateRepeatGroupService repeatGroupService,
            List<ElnTemplateBindingDependencyValidator> dependencyValidators,
            List<ElnTemplateVersionCopyParticipant> copyParticipants,
            List<ElnTemplateBindingLifecycleParticipant> lifecycleParticipants,
            Supplier<String> bindingIdSupplier, Supplier<String> referenceInstanceIdSupplier,
            Consumer<AuditEventDTO> auditRecorder, ElnTemplateDocumentEvidence documentEvidence,
            ElnPendingBindingCleanupService pendingCleanupService,
            Supplier<UserContext> userContextSupplier,
            ElnTemplateBindingConfirmationFacade confirmationFacade,
            StepAssignmentResolver stepAssignmentResolver,
            StepConfigurationReader stepConfigurationReader) {
        this.store = store;
        this.fieldCatalogService = fieldCatalogService;
        this.repeatGroupService = repeatGroupService;
        this.dependencyValidators = dependencyValidators == null
                ? Collections.emptyList() : new ArrayList<>(dependencyValidators);
        this.copyParticipants = copyParticipants == null
                ? Collections.emptyList() : new ArrayList<>(copyParticipants);
        this.lifecycleParticipants = lifecycleParticipants == null
                ? Collections.emptyList() : new ArrayList<>(lifecycleParticipants);
        this.bindingIdSupplier = bindingIdSupplier;
        this.referenceInstanceIdSupplier = referenceInstanceIdSupplier;
        this.auditRecorder = auditRecorder;
        this.documentEvidence = documentEvidence;
        this.pendingCleanupService = pendingCleanupService;
        this.userContextSupplier = userContextSupplier;
        this.confirmationFacade = confirmationFacade;
        this.stepAssignmentResolver = stepAssignmentResolver;
        this.stepConfigurationReader = stepConfigurationReader;
        this.pendingTimeoutMinutes = 30L;
    }
 
    @Override
    public ElnTemplateVos.AnnotationContext context(TemplateAnnotationAuthorization authorization) {
        prepareDocumentEvidence(authorization);
        ElnTemplateVersionEntity template = requireEditableTemplate(authorization);
        fieldCatalogService.ensureTestSubmissionFields();
        ElnTemplateVos.AnnotationContext result = new ElnTemplateVos.AnnotationContext();
        result.setTemplateId(template.getId());
        result.setTemplateCode(template.getMubanBianhao());
        result.setUpgradeOperationCode(template.getShengbanCaozuoBianma());
        result.setStepConfiguration(stepConfigurationReader.read(template.getId()));
        result.setRepeatGroups(repeatGroupService.list(
                authorization.getTenantId(), template.getId()));
        if (checkboxGroupService != null) {
            result.setCheckboxGroups(checkboxGroupService.list(
                    authorization.getTenantId(), template.getId()));
        }
        for (ElnFieldDefEntity field : store.listFields(authorization.getTenantId())) {
            if (!ENABLED.equals(field.getBizEnabled()) || !fieldVisibleToTemplate(field, template)) {
                continue;
            }
            ElnFieldVos.Detail detail = toFieldDetail(field);
            for (ElnFieldVersionEntity version
                    : store.listFieldVersions(authorization.getTenantId(), field.getId())) {
                boolean preRelease = ElnFieldEnums.VersionStatus.PRE_RELEASE.name()
                        .equals(version.getBizStatus());
                boolean currentPublished = ElnFieldEnums.VersionStatus.PUBLISHED.name()
                        .equals(version.getBizStatus())
                        && version.getId().equals(field.getDangqianZiduanBanbenId());
                if (preRelease || currentPublished) {
                    detail.getVersions().add(toFieldVersion(version));
                }
            }
            if (!detail.getVersions().isEmpty()) {
                result.getFields().add(detail);
            }
        }
        for (ElnTemplateBindingEntity binding
                : store.listBindings(authorization.getTenantId(), template.getId())) {
            if (PENDING.equals(binding.getBangdingZhuangtai())
                    || ACTIVE.equals(binding.getBangdingZhuangtai())) {
                result.getBindings().add(toBinding(binding));
            }
            if (PENDING.equals(binding.getBangdingZhuangtai())
                    && StringUtils.hasText(binding.getLaiyuanBangdingId())) {
                result.getCopiedPendingBindingIds().add(binding.getId());
            }
        }
        return result;
    }
 
    @Override
    @Transactional
    public ElnTemplateVos.Binding reservePrimary(TemplateAnnotationAuthorization authorization,
            ElnTemplateForms.ReserveBinding form) {
        prepareDocumentEvidence(authorization);
        return reservePrimaryPrepared(authorization, form);
    }
 
    private ElnTemplateVos.Binding reservePrimaryPrepared(
            TemplateAnnotationAuthorization authorization, ElnTemplateForms.ReserveBinding form) {
        ElnTemplateVersionEntity template = requireEditableTemplateForUpdate(authorization);
        requireReserveForm(form);
        boolean repeat = Boolean.TRUE.equals(form.getRepeatRequest());
        String stepId = stepAssignmentResolver.resolve(authorization.getTenantId(),
                template.getId(), form.getStepId());
        String repeatGroupCode = repeat
                ? requireRepeatToken(form.getRepeatGroupCode(), "重复组编码无效") : null;
        String prototypeRowId = repeat
                ? requireRepeatToken(form.getRepeatPrototypeRowId(), "原型行标识无效") : null;
        if (repeat && !REPEAT_PROTOTYPE_ROW_ID.equals(prototypeRowId)) {
            throw new DataException("当前阶段原型行标识必须为 prototype");
        }
        if (repeat) {
            repeatGroupService.ensureConfigured(authorization.getTenantId(), template.getId(),
                    repeatGroupCode, form.getMinRows(), form.getMaxRows(),
                    stepId, authorization.getUserId());
        }
        String role = repeat ? REPEAT : PRIMARY;
        String checkboxGroupCode = normalizeCheckboxGroupCode(form.getCheckboxGroupCode());
        String operation = form.getOperationCode().trim();
        ElnTemplateBindingEntity retried = store.findByOperation(
                authorization.getTenantId(), template.getId(), operation);
        if (retried != null) {
            if (!role.equals(retried.getKongjianJuese())
                    || !form.getFieldId().trim().equals(retried.getZiduanDingyiId())
                    || !form.getFieldVersionId().trim().equals(retried.getZiduanBanbenId())
                    || !Objects.equals(repeatGroupCode, retried.getRepeatGroupCode())
                    || !Objects.equals(prototypeRowId, retried.getRepeatPrototypeRowId())
                    || !Objects.equals(checkboxGroupCode, retried.getCheckboxGroupCode())
                    || !Objects.equals(repeat ? null : stepId, retried.getStepId())) {
                throw ElnTemplateOperationException.conflict("绑定操作码已用于其他请求");
            }
            ensureCheckboxGroupConfigured(authorization, template.getId(), checkboxGroupCode,
                    form.getCheckboxGroupMinSelected(), form.getCheckboxGroupMaxSelected());
            return toBinding(retried);
        }
        ElnFieldDefEntity field = requireField(authorization.getTenantId(), form.getFieldId());
        ElnFieldVersionEntity version = requireSelectableVersion(
                authorization.getTenantId(), field, form.getFieldVersionId(), template);
        validateCheckboxGroupAssignment(authorization, null, checkboxGroupCode,
                role, repeatGroupCode, repeat ? null : stepId, version);
        ensureCheckboxGroupConfigured(authorization, template.getId(), checkboxGroupCode,
                form.getCheckboxGroupMinSelected(), form.getCheckboxGroupMaxSelected());
        for (ElnTemplateBindingEntity binding
                : store.listBindings(authorization.getTenantId(), template.getId())) {
            if (!isLive(binding)) continue;
            if (!repeat && PRIMARY.equals(binding.getKongjianJuese())
                    && field.getZiduanBianma().equals(binding.getZiduanBianma())) {
                throw ElnTemplateOperationException.conflict("同一模板字段只能有一个有效主控件");
            }
            if (repeat && REPEAT.equals(binding.getKongjianJuese())) {
                if (repeatGroupCode.equals(binding.getRepeatGroupCode())
                        && !prototypeRowId.equals(binding.getRepeatPrototypeRowId())) {
                    throw ElnTemplateOperationException.conflict("同一重复组只能有一条原型行");
                }
                if (repeatGroupCode.equals(binding.getRepeatGroupCode())
                        && field.getZiduanBianma().equals(binding.getZiduanBianma())) {
                    throw ElnTemplateOperationException.conflict("同一重复组字段只能绑定一次");
                }
            }
        }
        String tag = repeat
                ? "eln.repeat." + repeatGroupCode + "." + prototypeRowId + "."
                        + field.getZiduanBianma()
                : "eln.field." + field.getZiduanBianma();
        ElnTemplateBindingEntity created = newBinding(authorization, template, field, version,
                role, null, tag, operation);
        created.setRepeatGroupCode(repeatGroupCode);
        created.setRepeatPrototypeRowId(prototypeRowId);
        created.setCheckboxGroupCode(checkboxGroupCode);
        created.setStepId(repeat ? null : stepId);
        insert(created);
        audit("ELN_TEMPLATE_BINDING_RESERVE", authorization.getTenantId(),
                authorization.getUserId(), operation, template.getId(), created.getId(),
                null, created, null, "SUCCESS");
        return toBinding(created);
    }
 
    @Override
    @Transactional
    public ElnTemplateVos.Binding reserveReference(TemplateAnnotationAuthorization authorization,
            String primaryBindingId, String operationCode) {
        prepareDocumentEvidence(authorization);
        ElnTemplateVersionEntity template = requireEditableTemplateForUpdate(authorization);
        String operation = requireText(operationCode, "操作码不能为空");
        ElnTemplateBindingEntity retried = store.findByOperation(
                authorization.getTenantId(), template.getId(), operation);
        if (retried != null) {
            if (!REFERENCE.equals(retried.getKongjianJuese())
                    || !trim(primaryBindingId).equals(retried.getYinyongShiliId())) {
                throw ElnTemplateOperationException.conflict("绑定操作码已用于其他请求");
            }
            return toBinding(retried);
        }
        ElnTemplateBindingEntity primary = requireBindingForUpdate(
                authorization, primaryBindingId);
        if (!ACTIVE.equals(primary.getBangdingZhuangtai())
                || !PRIMARY.equals(primary.getKongjianJuese())) {
            throw ElnTemplateOperationException.conflict("引用控件必须指向有效主控件");
        }
        ElnFieldDefEntity field = requireField(
                authorization.getTenantId(), primary.getZiduanDingyiId());
        ElnFieldVersionEntity version = requireSelectableVersion(authorization.getTenantId(), field,
                primary.getZiduanBanbenId(), template);
        String instanceId = referenceInstanceIdSupplier.get();
        if (instanceId == null || !instanceId.matches("[0-9a-fA-F]{32}")) {
            throw new DataException("引用实例标识生成失败");
        }
        String tag = "eln.ref." + field.getZiduanBianma() + "." + instanceId.toLowerCase();
        ElnTemplateBindingEntity created = newBinding(authorization, template, field, version,
                REFERENCE, primary.getId(), tag, operation);
        insert(created);
        audit("ELN_TEMPLATE_BINDING_RESERVE", authorization.getTenantId(),
                authorization.getUserId(), operation, template.getId(), created.getId(),
                null, created, null, "SUCCESS");
        return toBinding(created);
    }
 
    @Override
    @Transactional
    public ElnTemplateVos.Binding changeCheckboxGroup(
            TemplateAnnotationAuthorization authorization,
            String bindingId,
            ElnTemplateForms.ChangeCheckboxGroup form) {
        if (form == null || form.getExpectedVersion() == null) {
            throw new DataException("绑定期望版本不能为空");
        }
        String operation = requireText(form.getOperationCode(), "操作码不能为空");
        String checkboxGroupCode = normalizeCheckboxGroupCode(form.getCheckboxGroupCode());
        ElnTemplateBindingEntity replayed = store.findByOperation(
                authorization.getTenantId(), authorization.getTemplateId(), operation);
        if (replayed != null) {
            if (replayed.getId().equals(trim(bindingId))
                    && Objects.equals(checkboxGroupCode, replayed.getCheckboxGroupCode())) {
                return toBinding(replayed);
            }
            throw ElnTemplateOperationException.conflict("选择组操作码已用于其他请求");
        }
        requireEditableTemplateForUpdate(authorization);
        ElnTemplateBindingEntity current = requireBindingForUpdate(authorization, bindingId);
        if (!isLive(current)) {
            throw ElnTemplateOperationException.conflict("只有待确认或有效绑定可以修改选择组");
        }
        if (!form.getExpectedVersion().equals(current.getFVersion())) {
            throw ElnTemplateOperationException.conflict("绑定状态已变化,请刷新后重试");
        }
        ElnFieldVersionEntity version = requireFieldVersion(
                authorization.getTenantId(), current.getZiduanBanbenId());
        validateCheckboxGroupAssignment(authorization, current.getId(), checkboxGroupCode,
                current.getKongjianJuese(), current.getRepeatGroupCode(),
                current.getStepId(), version);
        ensureCheckboxGroupConfigured(authorization, authorization.getTemplateId(),
                checkboxGroupCode, form.getCheckboxGroupMinSelected(),
                form.getCheckboxGroupMaxSelected());
        if (Objects.equals(checkboxGroupCode, current.getCheckboxGroupCode())) {
            return toBinding(current);
        }
        ElnTemplateBindingEntity after = copy(current);
        after.setCheckboxGroupCode(checkboxGroupCode);
        after.setCaozuoBianma(operation);
        casExpected(current, after, current.getBangdingZhuangtai(), form.getExpectedVersion());
        ElnTemplateBindingEntity persisted = requireBinding(authorization, current.getId());
        removeUnusedCheckboxGroups(authorization.getTenantId(),
                authorization.getTemplateId(), authorization.getUserId());
        audit("ELN_TEMPLATE_BINDING_CHECKBOX_GROUP_CHANGE", authorization.getTenantId(),
                authorization.getUserId(), operation, authorization.getTemplateId(),
                current.getId(), current, persisted, null, "SUCCESS");
        return toBinding(persisted);
    }
 
    @Override
    @Transactional
    public ElnTemplateVos.CheckboxGroup changeCheckboxGroupRule(
            TemplateAnnotationAuthorization authorization, String groupCode,
            ElnTemplateForms.ChangeCheckboxGroupRule form) {
        if (form == null || form.getExpectedVersion() == null) {
            throw new DataException("选择组期望版本不能为空");
        }
        String operation = requireText(form.getOperationCode(), "操作码不能为空");
        requireEditableTemplateForUpdate(authorization);
        if (checkboxGroupService == null) throw new DataException("选择组服务不可用");
        ElnTemplateVos.CheckboxGroup before = checkboxGroupService.list(
                        authorization.getTenantId(), authorization.getTemplateId()).stream()
                .filter(item -> Objects.equals(item.getGroupCode(), trim(groupCode)))
                .findFirst().orElse(null);
        ElnTemplateVos.CheckboxGroup changed = checkboxGroupService.change(
                authorization.getTenantId(), authorization.getTemplateId(), groupCode,
                form.getMinSelected(), form.getMaxSelected(), form.getExpectedVersion(),
                authorization.getUserId());
        audit("ELN_TEMPLATE_CHECKBOX_GROUP_RULE_CHANGE", authorization.getTenantId(),
                authorization.getUserId(), operation, authorization.getTemplateId(),
                changed.getGroupCode(), before, changed, null, "SUCCESS");
        return changed;
    }
 
    @Override
    @Transactional
    public ElnTemplateVos.Binding createPrivateFieldAndReserve(
            TemplateAnnotationAuthorization authorization, ElnTemplateForms.PrivateField form) {
        prepareDocumentEvidence(authorization);
        ElnTemplateVersionEntity template = requireEditableTemplateForUpdate(authorization);
        if (form == null || !StringUtils.hasText(form.getOperationCode())) {
            throw new DataException("私有字段操作码不能为空");
        }
        ElnTemplateBindingEntity retried = store.findByOperation(authorization.getTenantId(),
                template.getId(), form.getOperationCode().trim());
        if (retried != null) {
            requireSamePrivateFieldRequest(authorization, template, retried, form);
            ensureCheckboxGroupConfigured(authorization, template.getId(),
                    normalizeCheckboxGroupCode(form.getCheckboxGroupCode()),
                    form.getCheckboxGroupMinSelected(), form.getCheckboxGroupMaxSelected());
            return toBinding(retried);
        }
        ElnFieldForms.TemplateFieldCreate command = new ElnFieldForms.TemplateFieldCreate();
        command.setTenantId(authorization.getTenantId());
        command.setTemplateCode(template.getMubanBianhao());
        command.setOperatorId(authorization.getUserId());
        command.setBeizhu(form.getBeizhu());
        command.setZiduanMingcheng(form.getZiduanMingcheng());
        command.setShujuLeixing(form.getShujuLeixing());
        command.setDanwei(form.getDanwei());
        command.setShifouBitian(form.getShifouBitian());
        command.setPiciMoshi(ElnFieldEnums.BatchMode.RECORD_PRIVATE.name());
        command.setKongjianPeizhi(form.getKongjianPeizhi());
        command.setBinding(manualBinding());
        ElnFieldVos.Detail created = fieldCatalogService.createTemplateFieldAndPreRelease(command);
        if (created == null || !StringUtils.hasText(created.getId())
                || created.getVersions() == null || created.getVersions().size() != 1
                || !ElnFieldEnums.VersionStatus.PRE_RELEASE.name().equals(
                        created.getVersions().get(0).getBizStatus())) {
            throw new DataException("私有字段创建结果无效");
        }
        ElnTemplateForms.ReserveBinding reserve = new ElnTemplateForms.ReserveBinding();
        reserve.setFieldId(created.getId());
        reserve.setFieldVersionId(created.getVersions().get(0).getId());
        reserve.setOperationCode(form.getOperationCode());
        reserve.setStepId(form.getStepId());
        reserve.setCheckboxGroupCode(form.getCheckboxGroupCode());
        reserve.setCheckboxGroupMinSelected(form.getCheckboxGroupMinSelected());
        reserve.setCheckboxGroupMaxSelected(form.getCheckboxGroupMaxSelected());
        return reservePrimaryPrepared(authorization, reserve);
    }
 
    private void ensureCheckboxGroupConfigured(TemplateAnnotationAuthorization authorization,
                                               String templateId, String groupCode,
                                               Integer minSelected, Integer maxSelected) {
        if (checkboxGroupService == null || groupCode == null) return;
        checkboxGroupService.ensureConfigured(authorization.getTenantId(), templateId,
                groupCode, minSelected, maxSelected, authorization.getUserId());
    }
 
    @Override
    @Transactional
    public void activate(TemplateAnnotationAuthorization authorization, String bindingId,
                         String operationCode) {
        requireEditableTemplateForUpdate(authorization);
        ElnTemplateBindingEntity observed = requireBinding(authorization, bindingId);
        ElnTemplateBindingEntity lockedPrimary = null;
        if (REFERENCE.equals(observed.getKongjianJuese())) {
            lockedPrimary = requireBindingForUpdate(
                    authorization, observed.getYinyongShiliId());
        }
        ElnTemplateBindingEntity before = requireBindingForUpdate(authorization, bindingId);
        if (REFERENCE.equals(before.getKongjianJuese())) {
            requireValidReferencePrimary(before, lockedPrimary);
        }
        rejectCopiedBindingSingleTransition(before);
        if (ACTIVE.equals(before.getBangdingZhuangtai())) {
            return;
        }
        if (!PENDING.equals(before.getBangdingZhuangtai())) {
            throw ElnTemplateOperationException.conflict("只有待确认绑定可以激活");
        }
        ElnTemplateBindingEntity after = copy(before);
        after.setBangdingZhuangtai(ACTIVE);
        after.setZhuangtaiYuanyin(null);
        cas(before, after, PENDING);
        ElnTemplateBindingEntity persisted = requireBinding(authorization, bindingId);
        audit("ELN_TEMPLATE_BINDING_ACTIVATE", authorization.getTenantId(),
                authorization.getUserId(), requireText(operationCode, "操作码不能为空"),
                authorization.getTemplateId(), bindingId, before, persisted, null, "SUCCESS");
    }
 
    @Override
    @Transactional
    public void cancel(TemplateAnnotationAuthorization authorization, String bindingId,
                       String operationCode, String reason) {
        requireEditableTemplateForUpdate(authorization);
        ElnTemplateBindingEntity before = requireBinding(authorization, bindingId);
        rejectCopiedBindingSingleTransition(before);
        if (CANCELLED.equals(before.getBangdingZhuangtai())) {
            return;
        }
        if (!PENDING.equals(before.getBangdingZhuangtai())) {
            throw ElnTemplateOperationException.conflict("只有待确认绑定可以取消");
        }
        ElnTemplateBindingEntity after = copy(before);
        after.setBangdingZhuangtai(CANCELLED);
        after.setZhuangtaiYuanyin(requireText(reason, "取消原因不能为空"));
        cas(before, after, PENDING);
        terminateBinding(authorization.getTenantId(), bindingId, authorization.getUserId());
        ElnTemplateBindingEntity persisted = requireBinding(authorization, bindingId);
        audit("ELN_TEMPLATE_BINDING_CANCEL", authorization.getTenantId(),
                authorization.getUserId(), requireText(operationCode, "操作码不能为空"),
                authorization.getTemplateId(), bindingId, before, persisted, reason, "SUCCESS");
    }
 
    @Override
    public ElnTemplateVos.RepairContext repairContext(TemplateAnnotationAuthorization authorization,
                                                      String bindingId) {
        requireEditableTemplate(authorization);
        ElnTemplateBindingEntity binding = requireActiveBinding(authorization, bindingId);
        ElnTemplateVos.ChangeCheck check = changeCheck("repair", authorization,
                Collections.singletonList(binding), activeSnapshots(authorization),
                Collections.emptyList(), null);
        ElnTemplateVos.RepairContext result = new ElnTemplateVos.RepairContext();
        copyCheck(check, result);
        result.setBinding(toBinding(binding));
        return result;
    }
 
    @Override
    public void confirmRepair(TemplateAnnotationAuthorization authorization, String bindingId,
                              ElnTemplateForms.RepairConfirm form) {
        confirmationFacade.execute(() -> {
            ElnTemplateBindingEntity current = requireBinding(authorization, bindingId);
            if (ACTIVE.equals(current.getBangdingZhuangtai()) && form != null
                    && Objects.equals(form.getOperationCode(), current.getCaozuoBianma())) {
                return;
            }
            requireEditableTemplateForUpdate(authorization);
            current = requireBinding(authorization, bindingId);
            if (ACTIVE.equals(current.getBangdingZhuangtai()) && form != null
                    && Objects.equals(form.getOperationCode(), current.getCaozuoBianma())) {
                return;
            }
            ElnTemplateVos.RepairContext check = repairContext(authorization, bindingId);
            requireConfirmation(check, form);
            ElnTemplateBindingEntity after = copy(current);
            after.setCaozuoBianma(form.getOperationCode());
            casExpected(current, after, ACTIVE,
                    form.getExpectedVersions().get(bindingId));
            ElnTemplateBindingEntity persisted = requireBinding(authorization, bindingId);
            audit("ELN_TEMPLATE_BINDING_REPAIR", authorization.getTenantId(),
                    authorization.getUserId(), form.getOperationCode(), authorization.getTemplateId(),
                    bindingId, current, persisted, null, "SUCCESS");
        }, error -> failureAudit("REPAIR", authorization.getTenantId(), authorization.getUserId(),
                operation(form), authorization.getTemplateId(), bindingId, error));
    }
 
    @Override
    @Transactional
    public ElnTemplateVos.ChangeCheck checkUpgrade(TemplateAnnotationAuthorization authorization,
                                                   String bindingId, String targetVersionId) {
        requireEditableTemplate(authorization);
        ElnTemplateBindingEntity primary = requireActivePrimaryForUpdate(
                authorization, bindingId);
        ElnFieldDefEntity field = requireField(
                authorization.getTenantId(), primary.getZiduanDingyiId());
        ElnFieldVersionEntity target = requireSelectableVersion(authorization.getTenantId(), field,
                targetVersionId, requireTemplate(authorization));
        List<ElnTemplateBindingEntity> affected = fieldBindingFamily(authorization, primary);
        List<ElnTemplateVos.Diagnostic> dependencies = validateUpgrade(
                authorization, ids(affected), target.getId());
        List<ElnTemplateVos.ControlSnapshot> controls = activeSnapshots(authorization);
        Set<String> affectedIds = ids(affected);
        for (ElnTemplateVos.ControlSnapshot control : controls) {
            if (affectedIds.contains(control.getBindingId())) {
                control.setFieldVersionId(target.getId());
                control.setControlAlias(target.getZiduanMingcheng());
                control.setControlType(controlType(target.getShujuLeixing()));
                control.setControlConfig(DocxExpectedControlConfig.from(
                        target.getShujuLeixing(), target.getKongjianPeizhi()));
            }
        }
        return changeCheck("upgrade:" + target.getId(), authorization,
                affected, controls, dependencies, target.getId());
    }
 
    @Override
    public void confirmUpgrade(TemplateAnnotationAuthorization authorization, String bindingId,
                               ElnTemplateForms.UpgradeConfirm form) {
        confirmationFacade.execute(() -> confirmUpgradeInternal(authorization, bindingId, form),
                error -> failureAudit("UPGRADE", authorization.getTenantId(),
                        authorization.getUserId(), operation(form), authorization.getTemplateId(),
                        bindingId, error));
    }
 
    private void confirmUpgradeInternal(TemplateAnnotationAuthorization authorization,
                                        String bindingId, ElnTemplateForms.UpgradeConfirm form) {
        if (isUpgradeRetry(authorization, bindingId, form)) {
            return;
        }
        requireEditableTemplateForUpdate(authorization);
        if (isUpgradeRetry(authorization, bindingId, form)) {
            return;
        }
        ElnTemplateVos.ChangeCheck check = checkUpgrade(
                authorization, bindingId, form == null ? null : form.getTargetFieldVersionId());
        requireConfirmation(check, form);
        List<ElnTemplateBindingEntity> beforeSnapshots = new ArrayList<>();
        List<ElnTemplateBindingEntity> afterSnapshots = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : check.getExpectedVersions().entrySet()) {
            ElnTemplateBindingEntity before = requireActiveBinding(authorization, entry.getKey());
            beforeSnapshots.add(copy(before));
            ElnTemplateBindingEntity after = copy(before);
            ElnFieldVersionEntity target = requireFieldVersion(
                    authorization.getTenantId(), form.getTargetFieldVersionId());
            validateCheckboxGroupAssignment(authorization, before.getId(),
                    before.getCheckboxGroupCode(), before.getKongjianJuese(),
                    before.getRepeatGroupCode(), before.getStepId(), target);
            after.setZiduanBanbenId(target.getId());
            after.setKongjianBieming(target.getZiduanMingcheng());
            after.setKongjianLeixing(controlType(target.getShujuLeixing()));
            after.setCaozuoBianma(bindingOperationCode(form.getOperationCode(), before.getId()));
            casExpected(before, after, ACTIVE, entry.getValue());
            afterSnapshots.add(requireActiveBinding(authorization, before.getId()));
        }
        audit("ELN_TEMPLATE_BINDING_UPGRADE", authorization.getTenantId(),
                authorization.getUserId(), form.getOperationCode(), authorization.getTemplateId(),
                bindingId, beforeSnapshots, afterSnapshots,
                null, "SUCCESS");
    }
 
    @Override
    @Transactional
    public ElnTemplateVos.ChangeCheck checkRemove(TemplateAnnotationAuthorization authorization,
                                                  String bindingId) {
        requireEditableTemplate(authorization);
        ElnTemplateBindingEntity binding = requireActiveBindingForUpdate(
                authorization, bindingId);
        Set<String> affected = Collections.singleton(binding.getId());
        if (PRIMARY.equals(binding.getKongjianJuese()) && hasLiveReferences(authorization, binding)) {
            throw new DataException("主控件仍有引用,不能删除");
        }
        List<ElnTemplateVos.Diagnostic> dependencies = validateRemoval(authorization, affected);
        List<ElnTemplateVos.ControlSnapshot> controls = activeSnapshots(authorization);
        controls.removeIf(item -> binding.getId().equals(item.getBindingId()));
        ElnTemplateVos.ChangeCheck result = changeCheck("remove", authorization,
                Collections.singletonList(binding), controls, dependencies, null);
        audit("ELN_TEMPLATE_BINDING_REMOVE_CHECK", authorization.getTenantId(),
                authorization.getUserId(), result.getOperationCode(), authorization.getTemplateId(),
                bindingId, binding, result, null, "SUCCESS");
        return result;
    }
 
    @Override
    public void confirmRemove(TemplateAnnotationAuthorization authorization, String bindingId,
                              ElnTemplateForms.RemoveConfirm form) {
        confirmationFacade.execute(() -> {
            ElnTemplateBindingEntity current = requireBinding(authorization, bindingId);
            if (REMOVED.equals(current.getBangdingZhuangtai())
                    && form != null && Objects.equals(
                            form.getOperationCode(), current.getCaozuoBianma())) {
                return;
            }
            requireEditableTemplateForUpdate(authorization);
            current = requireBinding(authorization, bindingId);
            if (REMOVED.equals(current.getBangdingZhuangtai())
                    && form != null && Objects.equals(
                            form.getOperationCode(), current.getCaozuoBianma())) {
                return;
            }
            ElnTemplateVos.ChangeCheck check = checkRemove(authorization, bindingId);
            requireConfirmation(check, form);
            requireObservedControlTags(check, form, current.getKongjianBiaoqian());
            ElnTemplateBindingEntity after = copy(current);
            after.setBangdingZhuangtai(REMOVED);
            after.setCaozuoBianma(form.getOperationCode());
            casExpected(current, after, ACTIVE, form.getExpectedVersions().get(bindingId));
            terminateBinding(authorization.getTenantId(), bindingId, authorization.getUserId());
            removeUnusedCheckboxGroups(authorization.getTenantId(),
                    authorization.getTemplateId(), authorization.getUserId());
            ElnTemplateBindingEntity persisted = requireBinding(authorization, bindingId);
            audit("ELN_TEMPLATE_BINDING_REMOVE", authorization.getTenantId(),
                    authorization.getUserId(), form.getOperationCode(), authorization.getTemplateId(),
                    bindingId, current, persisted, null, "SUCCESS");
        }, error -> failureAudit("REMOVE", authorization.getTenantId(), authorization.getUserId(),
                operation(form), authorization.getTemplateId(), bindingId, error));
    }
 
    @Override
    public void confirmRemoveMissing(String bindingId,
                                     ElnTemplateForms.RemoveMissingConfirm form) {
        UserContext user = requireUserContext();
        confirmationFacade.execute(() -> {
            if (form == null || form.getExpectedVersion() == null) {
                throw new DataException("绑定期望版本不能为空");
            }
            String operation = requireText(form.getOperationCode(), "操作码不能为空");
            String reason = requireText(form.getReason(), "确认删除原因不能为空");
            ElnTemplateBindingEntity observed = requireBinding(user.getTenantId(), bindingId);
            if (REMOVED.equals(observed.getBangdingZhuangtai())
                    && operation.equals(observed.getCaozuoBianma())) {
                if (Objects.equals(reason, trim(observed.getZhuangtaiYuanyin()))) {
                    return;
                }
                throw ElnTemplateOperationException.conflict(
                        "确认删除操作码已用于其他原因");
            }
            ElnTemplateVersionEntity template = requireEditableTemplateForUpdate(
                    user.getTenantId(), observed.getMubanId());
            ElnTemplateBindingEntity current = requireBindingForUpdate(
                    user.getTenantId(), bindingId);
            if (REMOVED.equals(current.getBangdingZhuangtai())
                    && operation.equals(current.getCaozuoBianma())) {
                if (Objects.equals(reason, trim(current.getZhuangtaiYuanyin()))) {
                    return;
                }
                throw ElnTemplateOperationException.conflict(
                        "确认删除操作码已用于其他原因");
            }
            if (!ACTIVE.equals(current.getBangdingZhuangtai())) {
                throw ElnTemplateOperationException.conflict("只有有效绑定可以确认缺失删除");
            }
            String fileId = uniqueDocxFileId(template.getMubanFile());
            if (documentEvidence.containsControlTag(
                    user.getTenantId(), fileId, current.getKongjianBiaoqian())) {
                throw new DataException("服务端文档证据显示控件仍然存在");
            }
            if (PRIMARY.equals(current.getKongjianJuese())
                    && hasLiveReferences(user.getTenantId(), template.getId(), current)) {
                throw new DataException("主控件仍有引用,不能删除");
            }
            validateRemoval(user.getTenantId(), template.getId(),
                    Collections.singleton(current.getId()));
            ElnTemplateBindingEntity after = copy(current);
            after.setBangdingZhuangtai(REMOVED);
            after.setCaozuoBianma(operation);
            after.setZhuangtaiYuanyin(reason);
            casExpected(current, after, ACTIVE, form.getExpectedVersion());
            terminateBinding(user.getTenantId(), bindingId, user.getUserId());
            removeUnusedCheckboxGroups(user.getTenantId(), template.getId(), user.getUserId());
            ElnTemplateBindingEntity persisted = requireBinding(user.getTenantId(), bindingId);
            audit("ELN_TEMPLATE_BINDING_REMOVE", user.getTenantId(), user.getUserId(), operation,
                    template.getId(), bindingId, current, persisted,
                    reason, "SUCCESS");
        }, error -> failureAudit("REMOVE", user.getTenantId(), user.getUserId(),
                form == null ? null : form.getOperationCode(),
                templateIdForFailure(user.getTenantId(), bindingId), bindingId, error));
    }
 
    private void terminateBinding(String tenantId, String bindingId, String userId) {
        for (ElnTemplateBindingLifecycleParticipant participant : lifecycleParticipants) {
            participant.bindingTerminated(tenantId, bindingId, userId);
        }
    }
 
    private void removeUnusedCheckboxGroups(String tenantId, String templateId,
            String operatorId) {
        if (checkboxGroupService == null) return;
        Set<String> usedGroupCodes = new LinkedHashSet<>();
        for (ElnTemplateBindingEntity binding : store.listBindings(tenantId, templateId)) {
            String groupCode = trim(binding.getCheckboxGroupCode());
            if (isLive(binding) && groupCode != null) usedGroupCodes.add(groupCode);
        }
        checkboxGroupService.removeUnused(
                tenantId, templateId, usedGroupCodes, operatorId);
    }
 
    @Override
    @Transactional
    public ElnTemplateVos.ChangeCheck checkPromoteReference(
            TemplateAnnotationAuthorization authorization, String referenceBindingId) {
        requireEditableTemplate(authorization);
        ElnTemplateBindingEntity reference = requireActiveBinding(authorization, referenceBindingId);
        if (!REFERENCE.equals(reference.getKongjianJuese())) {
            throw new DataException("只能提升引用控件");
        }
        ElnTemplateBindingEntity primary = requireActivePrimaryForUpdate(
                authorization, reference.getYinyongShiliId());
        reference = requireActiveBindingForUpdate(authorization, referenceBindingId);
        requireValidReferencePrimary(reference, primary);
        List<ElnTemplateBindingEntity> affected = fieldBindingFamily(authorization, primary);
        if (!ids(affected).contains(reference.getId())) {
            throw new DataException("待提升引用不属于主控件引用集合");
        }
        List<ElnTemplateVos.Diagnostic> dependencies = validatePromotion(
                authorization, primary.getId(), reference.getId());
        List<ElnTemplateVos.ControlSnapshot> controls = activeSnapshots(authorization);
        controls.removeIf(item -> primary.getId().equals(item.getBindingId()));
        for (ElnTemplateVos.ControlSnapshot control : controls) {
            if (reference.getId().equals(control.getBindingId())) {
                control.setControlRole(PRIMARY);
                control.setPrimaryBindingId(null);
                control.setControlTag("eln.field." + reference.getZiduanBianma());
                control.setStepId(primary.getStepId());
            } else if (primary.getId().equals(control.getPrimaryBindingId())) {
                control.setPrimaryBindingId(reference.getId());
            }
        }
        return changeCheck("promote", authorization,
                affected, controls, dependencies, null);
    }
 
    @Override
    public void confirmPromoteReference(TemplateAnnotationAuthorization authorization,
            String referenceBindingId, ElnTemplateForms.PromoteConfirm form) {
        confirmationFacade.execute(() -> {
            ElnTemplateBindingEntity possibleRetry = requireBinding(authorization, referenceBindingId);
            if (PRIMARY.equals(possibleRetry.getKongjianJuese()) && ACTIVE.equals(
                    possibleRetry.getBangdingZhuangtai()) && form != null
                    && Objects.equals(bindingOperationCode(
                            form.getOperationCode(), possibleRetry.getId()),
                            possibleRetry.getCaozuoBianma())) {
                return;
            }
            requireEditableTemplateForUpdate(authorization);
            possibleRetry = requireBinding(authorization, referenceBindingId);
            if (PRIMARY.equals(possibleRetry.getKongjianJuese()) && ACTIVE.equals(
                    possibleRetry.getBangdingZhuangtai()) && form != null
                    && Objects.equals(bindingOperationCode(
                            form.getOperationCode(), possibleRetry.getId()),
                            possibleRetry.getCaozuoBianma())) {
                return;
            }
            ElnTemplateVos.ChangeCheck check = checkPromoteReference(
                    authorization, referenceBindingId);
            requireConfirmation(check, form);
            ElnTemplateBindingEntity reference = requireActiveBinding(
                    authorization, referenceBindingId);
            requireObservedControlTags(check, form, reference.getKongjianBiaoqian());
            ElnTemplateBindingEntity primary = requireActiveBinding(
                    authorization, reference.getYinyongShiliId());
            List<ElnTemplateBindingEntity> family = fieldBindingFamily(authorization, primary);
            List<ElnTemplateBindingEntity> transitionOrder = new ArrayList<>();
            transitionOrder.add(primary);
            transitionOrder.add(reference);
            for (ElnTemplateBindingEntity member : family) {
                if (!primary.getId().equals(member.getId())
                        && !reference.getId().equals(member.getId())) {
                    transitionOrder.add(member);
                }
            }
            List<ElnTemplateBindingEntity> changed = new ArrayList<>();
            for (ElnTemplateBindingEntity before : transitionOrder) {
                ElnTemplateBindingEntity after = copy(before);
                if (primary.getId().equals(before.getId())) {
                    after.setBangdingZhuangtai(REMOVED);
                } else if (reference.getId().equals(before.getId())) {
                    after.setKongjianJuese(PRIMARY);
                    after.setYinyongShiliId(null);
                    after.setKongjianBiaoqian("eln.field." + reference.getZiduanBianma());
                    after.setStepId(primary.getStepId());
                } else {
                    after.setYinyongShiliId(reference.getId());
                }
                after.setCaozuoBianma(bindingOperationCode(
                        form.getOperationCode(), before.getId()));
                casExpected(before, after, ACTIVE,
                        form.getExpectedVersions().get(before.getId()));
                changed.add(requireBinding(authorization, before.getId()));
            }
            audit("ELN_TEMPLATE_BINDING_PROMOTE", authorization.getTenantId(),
                    authorization.getUserId(), form.getOperationCode(), authorization.getTemplateId(),
                    referenceBindingId, family, changed,
                    null, "SUCCESS");
        }, error -> failureAudit("PROMOTE", authorization.getTenantId(), authorization.getUserId(),
                operation(form), authorization.getTemplateId(), referenceBindingId, error));
    }
 
    @Override
    public void confirmVersionCopy(TemplateAnnotationAuthorization authorization,
                                   ElnTemplateForms.VersionCopyConfirm form) {
        confirmationFacade.execute(() -> confirmVersionCopyInternal(authorization, form),
                error -> failureAudit("VERSION_COPY_CONFIRM", authorization.getTenantId(),
                        authorization.getUserId(), form == null ? null : form.getUpgradeOperationCode(),
                        authorization.getTemplateId(), null, error));
    }
 
    private void confirmVersionCopyInternal(TemplateAnnotationAuthorization authorization,
                                            ElnTemplateForms.VersionCopyConfirm form) {
        ElnTemplateVersionEntity template = requireEditableTemplateForUpdate(authorization);
        if (form == null || !StringUtils.hasText(form.getUpgradeOperationCode())
                || !form.getUpgradeOperationCode().trim().equals(template.getShengbanCaozuoBianma())) {
            throw new DataException("升版操作码无效");
        }
        String upgradeOperation = form.getUpgradeOperationCode().trim();
        List<ElnTemplateBindingEntity> copies = copiedBindings(authorization);
        if (copies.isEmpty()) {
            throw new DataException("本次升版没有可确认的复制绑定");
        }
        boolean allPending = true;
        boolean allActive = true;
        for (ElnTemplateBindingEntity binding : copies) {
            String expectedOperation = upgradeOperation + ":" + binding.getLaiyuanBangdingId();
            if (!expectedOperation.equals(binding.getCaozuoBianma())) {
                throw new DataException("升版复制绑定操作码无效");
            }
            allPending &= PENDING.equals(binding.getBangdingZhuangtai());
            allActive &= ACTIVE.equals(binding.getBangdingZhuangtai());
        }
        if (allActive) {
            requireVersionCopyRetryVersions(copies, form.getExpectedVersions());
            requireControls(snapshots(copies), form.getControls());
            return;
        }
        if (!allPending) {
            throw ElnTemplateOperationException.conflict(
                    "升版复制绑定必须全部为待确认或全部为已激活状态");
        }
        for (ElnTemplateBindingEntity binding : copies) {
            if (binding.getDaoqiShijian() != null) {
                throw ElnTemplateOperationException.conflict("升版复制绑定状态无效");
            }
            ElnFieldVersionEntity version = requireFieldVersion(
                    authorization.getTenantId(), binding.getZiduanBanbenId());
            ElnFieldDefEntity field = requireField(
                    authorization.getTenantId(), binding.getZiduanDingyiId());
            if (!field.getId().equals(version.getZiduanDingyiId())) {
                throw new DataException("升版复制绑定的字段版本关系无效");
            }
            boolean published = ElnFieldEnums.VersionStatus.PUBLISHED.name()
                    .equals(version.getBizStatus());
            boolean privatePreRelease = ElnFieldEnums.VersionStatus.PRE_RELEASE.name()
                    .equals(version.getBizStatus())
                    && ElnFieldEnums.Scope.TEMPLATE.name().equals(field.getZuoyongFanwei())
                    && template.getMubanBianhao().equals(field.getMubanBianhao());
            if (!published && !privatePreRelease) {
                throw new DataException("升版复制只能继承已发布字段版本或同模板的预发布私有字段版本");
            }
        }
        Map<String, Integer> expected = versions(copies);
        requireExpectedVersions(expected, form.getExpectedVersions());
        requireControls(snapshots(copies), form.getControls());
        Map<String, String> bindingMap = new LinkedHashMap<>();
        List<ElnTemplateBindingEntity> beforeSnapshots = new ArrayList<>();
        List<ElnTemplateBindingEntity> afterSnapshots = new ArrayList<>();
        copies.sort(Comparator.comparing(ElnTemplateBindingEntity::getLaiyuanBangdingId));
        for (ElnTemplateBindingEntity before : copies) {
            beforeSnapshots.add(copy(before));
            ElnTemplateBindingEntity after = copy(before);
            after.setBangdingZhuangtai(ACTIVE);
            casExpected(before, after, PENDING, expected.get(before.getId()));
            afterSnapshots.add(requireActiveBinding(authorization, before.getId()));
            bindingMap.put(before.getLaiyuanBangdingId(), before.getId());
        }
        for (ElnTemplateVersionCopyParticipant participant : copyParticipants) {
            participant.afterBindingsActivated(authorization.getTenantId(),
                    template.getLaiyuanMubanId(), template.getId(), bindingMap);
        }
        audit("ELN_TEMPLATE_BINDING_VERSION_COPY_CONFIRM", authorization.getTenantId(),
                authorization.getUserId(), form.getUpgradeOperationCode(), template.getId(), null,
                beforeSnapshots, afterSnapshots, null, "SUCCESS");
    }
 
    private ElnTemplateBindingEntity newBinding(TemplateAnnotationAuthorization authorization,
            ElnTemplateVersionEntity template, ElnFieldDefEntity field,
            ElnFieldVersionEntity version, String role, String primaryBindingId,
            String tag, String operation) {
        ElnTemplateBindingEntity created = new ElnTemplateBindingEntity();
        created.setId(bindingIdSupplier.get());
        created.setFTenantId(authorization.getTenantId());
        created.setMubanId(template.getId());
        created.setMubanBianhao(template.getMubanBianhao());
        created.setZiduanDingyiId(field.getId());
        created.setZiduanBianma(field.getZiduanBianma());
        created.setZiduanBanbenId(version.getId());
        created.setKongjianBiaoqian(tag);
        created.setKongjianBieming(version.getZiduanMingcheng());
        created.setKongjianLeixing(controlType(version.getShujuLeixing()));
        created.setKongjianJuese(role);
        created.setYinyongShiliId(primaryBindingId);
        created.setBangdingZhuangtai(PENDING);
        created.setCaozuoBianma(operation);
        if (pendingTimeoutMinutes <= 0) {
            throw new DataException("PENDING 绑定超时时间配置无效");
        }
        long timeoutMillis;
        try {
            timeoutMillis = Math.multiplyExact(pendingTimeoutMinutes, 60L * 1000L);
        } catch (ArithmeticException e) {
            throw new DataException("PENDING 绑定超时时间配置无效");
        }
        created.setDaoqiShijian(new Date(System.currentTimeMillis() + timeoutMillis));
        created.setFVersion(0);
        created.setFDeleteMark(0);
        created.setFCreatorUserId(authorization.getUserId());
        created.setFLastModifyUserId(authorization.getUserId());
        return created;
    }
 
    private ElnTemplateVos.ChangeCheck changeCheck(String action,
            TemplateAnnotationAuthorization authorization,
            List<ElnTemplateBindingEntity> affected,
            List<ElnTemplateVos.ControlSnapshot> controls,
            List<ElnTemplateVos.Diagnostic> dependencies, String targetVersionId) {
        ElnTemplateVos.ChangeCheck result = new ElnTemplateVos.ChangeCheck();
        result.setExpectedVersions(versions(affected));
        result.setControls(sortedSnapshots(controls));
        result.setDependencies(dependencies == null ? new ArrayList<>() : dependencies);
        result.setOperationCode(operationCode(action, authorization, affected, targetVersionId));
        return result;
    }
 
    private void requireConfirmation(ElnTemplateVos.ChangeCheck check,
                                     ElnTemplateForms.ChangeConfirm form) {
        if (form == null || !check.getOperationCode().equals(form.getOperationCode())) {
            throw ElnTemplateOperationException.conflict("预检操作码无效,请重新预检");
        }
        requireExpectedVersions(check.getExpectedVersions(), form.getExpectedVersions());
        requireControls(check.getControls(), form.getControls());
    }
 
    private static void requireObservedControlTags(ElnTemplateVos.ChangeCheck check,
                                                   ElnTemplateForms.ChangeConfirm form,
                                                   String removedTag) {
        List<String> observedTags = form.getObservedControlTags();
        if (observedTags == null) {
            throw ElnTemplateOperationException.conflict("DOCX 控件标签证据未提交");
        }
        Set<String> observed = new LinkedHashSet<>();
        for (String tag : observedTags) {
            if (!StringUtils.hasText(tag) || !observed.add(tag)) {
                throw ElnTemplateOperationException.conflict("DOCX 控件标签证据无效");
            }
        }
        for (ElnTemplateVos.ControlSnapshot control : check.getControls()) {
            String expectedTag = control.getControlTag();
            if (Collections.frequency(observedTags, expectedTag) != 1) {
                throw ElnTemplateOperationException.conflict("DOCX 控件标签证据不完整");
            }
        }
        if (observed.contains(removedTag)) {
            throw ElnTemplateOperationException.conflict("DOCX 控件标签证据包含已移除控件");
        }
    }
 
    private static void requireExpectedVersions(Map<String, Integer> expected,
                                                Map<String, Integer> actual) {
        if (actual == null || !expected.equals(actual)) {
            throw ElnTemplateOperationException.conflict("受影响绑定版本集合不完整或已变化");
        }
    }
 
    private static void requireControls(List<ElnTemplateVos.ControlSnapshot> expected,
                                        List<ElnTemplateVos.ControlSnapshot> actual) {
        if (!canonicalControls(expected).equals(canonicalControls(actual))) {
            throw ElnTemplateOperationException.conflict("控件快照不完整或与预检结果不一致");
        }
        Map<String, ElnTemplateVos.ControlSnapshot> actualByBindingId = new LinkedHashMap<>();
        for (ElnTemplateVos.ControlSnapshot item : actual) {
            if (item == null || actualByBindingId.put(item.getBindingId(), item) != null) {
                throw ElnTemplateOperationException.conflict("控件快照不完整或与预检结果不一致");
            }
        }
        for (ElnTemplateVos.ControlSnapshot item : expected) {
            ElnTemplateVos.ControlSnapshot observed = actualByBindingId.get(item.getBindingId());
            if (!DocxControlConfigMatcher.matches(item.getControlType(),
                    item.getControlConfig(), observed.getControlConfig())) {
                throw ElnTemplateOperationException.conflict("控件快照不完整或与预检结果不一致");
            }
        }
    }
 
    private List<ElnTemplateVos.Diagnostic> validateUpgrade(
            TemplateAnnotationAuthorization authorization, Set<String> bindingIds,
            String targetVersionId) {
        List<ElnTemplateVos.Diagnostic> result = new ArrayList<>();
        for (ElnTemplateBindingDependencyValidator validator : dependencyValidators) {
            addDiagnostics(result, validator.validateUpgrade(authorization.getTenantId(),
                    authorization.getTemplateId(), bindingIds, targetVersionId));
        }
        rejectDependencyErrors(result);
        return result;
    }
 
    private List<ElnTemplateVos.Diagnostic> validateRemoval(
            TemplateAnnotationAuthorization authorization, Set<String> bindingIds) {
        return validateRemoval(authorization.getTenantId(),
                authorization.getTemplateId(), bindingIds);
    }
 
    private List<ElnTemplateVos.Diagnostic> validateRemoval(
            String tenantId, String templateId, Set<String> bindingIds) {
        List<ElnTemplateVos.Diagnostic> result = new ArrayList<>();
        for (ElnTemplateBindingDependencyValidator validator : dependencyValidators) {
            addDiagnostics(result, validator.validateRemoval(tenantId, templateId, bindingIds));
        }
        rejectDependencyErrors(result);
        return result;
    }
 
    private List<ElnTemplateVos.Diagnostic> validatePromotion(
            TemplateAnnotationAuthorization authorization, String primaryId, String referenceId) {
        List<ElnTemplateVos.Diagnostic> result = new ArrayList<>();
        for (ElnTemplateBindingDependencyValidator validator : dependencyValidators) {
            addDiagnostics(result, validator.validatePromotion(authorization.getTenantId(),
                    authorization.getTemplateId(), primaryId, referenceId));
        }
        rejectDependencyErrors(result);
        return result;
    }
 
    private static void rejectDependencyErrors(List<ElnTemplateVos.Diagnostic> diagnostics) {
        for (ElnTemplateVos.Diagnostic diagnostic : diagnostics) {
            if (diagnostic != null && "ERROR".equalsIgnoreCase(diagnostic.getSeverity())) {
                throw new DataException(StringUtils.hasText(diagnostic.getMessage())
                        ? diagnostic.getMessage() : "绑定依赖校验失败");
            }
        }
    }
 
    private static void addDiagnostics(List<ElnTemplateVos.Diagnostic> target,
                                       List<ElnTemplateVos.Diagnostic> source) {
        if (source != null) {
            target.addAll(source);
        }
    }
 
    private List<ElnTemplateBindingEntity> fieldBindingFamily(
            TemplateAnnotationAuthorization authorization, ElnTemplateBindingEntity primary) {
        List<ElnTemplateBindingEntity> result = new ArrayList<>();
        result.add(primary);
        for (ElnTemplateBindingEntity item
                : store.listBindings(authorization.getTenantId(), authorization.getTemplateId())) {
            if (isLive(item) && REFERENCE.equals(item.getKongjianJuese())
                    && primary.getId().equals(item.getYinyongShiliId())) {
                if (PENDING.equals(item.getBangdingZhuangtai())) {
                    throw new DataException("主控件仍有待确认引用,请先完成或取消引用标注");
                }
                if (!primary.getZiduanBanbenId().equals(item.getZiduanBanbenId())) {
                    throw new DataException("引用控件字段版本与主控件不一致");
                }
                result.add(item);
            }
        }
        result.sort(Comparator.comparing(ElnTemplateBindingEntity::getId));
        return result;
    }
 
    private boolean hasLiveReferences(TemplateAnnotationAuthorization authorization,
                                      ElnTemplateBindingEntity primary) {
        return hasLiveReferences(authorization.getTenantId(),
                authorization.getTemplateId(), primary);
    }
 
    private boolean hasLiveReferences(String tenantId, String templateId,
                                      ElnTemplateBindingEntity primary) {
        for (ElnTemplateBindingEntity item
                : store.listBindings(tenantId, templateId)) {
            if (isLive(item) && REFERENCE.equals(item.getKongjianJuese())
                    && primary.getId().equals(item.getYinyongShiliId())) {
                return true;
            }
        }
        return false;
    }
 
    private List<ElnTemplateBindingEntity> copiedBindings(
            TemplateAnnotationAuthorization authorization) {
        List<ElnTemplateBindingEntity> result = new ArrayList<>();
        for (ElnTemplateBindingEntity binding
                : store.listBindings(authorization.getTenantId(), authorization.getTemplateId())) {
            if (StringUtils.hasText(binding.getLaiyuanBangdingId())) {
                result.add(binding);
            }
        }
        result.sort(Comparator.comparing(ElnTemplateBindingEntity::getId));
        return result;
    }
 
    private static void requireVersionCopyRetryVersions(
            List<ElnTemplateBindingEntity> copies, Map<String, Integer> requestedVersions) {
        if (requestedVersions == null || !ids(copies).equals(requestedVersions.keySet())) {
            throw ElnTemplateOperationException.conflict("升版复制绑定版本集合不完整");
        }
        for (ElnTemplateBindingEntity binding : copies) {
            Integer requested = requestedVersions.get(binding.getId());
            if (requested == null || binding.getFVersion() == null
                    || requested == Integer.MAX_VALUE
                    || binding.getFVersion() != requested + 1) {
                throw ElnTemplateOperationException.conflict("升版复制绑定幂等版本无效");
            }
        }
    }
 
    private static void rejectCopiedBindingSingleTransition(
            ElnTemplateBindingEntity binding) {
        if (StringUtils.hasText(binding.getLaiyuanBangdingId())) {
            throw ElnTemplateOperationException.conflict("升版复制绑定只能批量确认");
        }
    }
 
    private boolean isUpgradeRetry(TemplateAnnotationAuthorization authorization,
                                   String bindingId, ElnTemplateForms.UpgradeConfirm form) {
        if (form == null || !StringUtils.hasText(form.getOperationCode())
                || !StringUtils.hasText(form.getTargetFieldVersionId())) {
            return false;
        }
        ElnTemplateBindingEntity binding = requireBinding(authorization, bindingId);
        if (!ACTIVE.equals(binding.getBangdingZhuangtai())
                || !PRIMARY.equals(binding.getKongjianJuese())
                || !form.getTargetFieldVersionId().equals(binding.getZiduanBanbenId())) {
            return false;
        }
        for (ElnTemplateBindingEntity member : fieldBindingFamily(authorization, binding)) {
            if (!form.getTargetFieldVersionId().equals(member.getZiduanBanbenId())
                    || !bindingOperationCode(form.getOperationCode(), member.getId())
                    .equals(member.getCaozuoBianma())) {
                return false;
            }
        }
        return true;
    }
 
    private ElnTemplateVersionEntity requireEditableTemplate(
            TemplateAnnotationAuthorization authorization) {
        if (authorization == null || !StringUtils.hasText(authorization.getTenantId())
                || !StringUtils.hasText(authorization.getTemplateId())) {
            throw new DataException("模板标注授权无效");
        }
        return requireEditableTemplate(authorization.getTenantId(), authorization.getTemplateId());
    }
 
    private ElnTemplateVersionEntity requireEditableTemplate(String tenantId, String templateId) {
        ElnTemplateVersionEntity template = store.findTemplate(tenantId, trim(templateId));
        if (template == null || !DRAFT.equals(template.getBizStatus())
                || !ENABLED.equals(template.getBizEnabled())) {
            throw ElnTemplateOperationException.conflict("只有启用的草稿模板可以修改绑定");
        }
        return template;
    }
 
    private ElnTemplateVersionEntity requireEditableTemplateForUpdate(
            TemplateAnnotationAuthorization authorization) {
        if (authorization == null || !StringUtils.hasText(authorization.getTenantId())
                || !StringUtils.hasText(authorization.getTemplateId())) {
            throw new DataException("模板标注授权无效");
        }
        return requireEditableTemplateForUpdate(
                authorization.getTenantId(), authorization.getTemplateId());
    }
 
    private ElnTemplateVersionEntity requireEditableTemplateForUpdate(
            String tenantId, String templateId) {
        ElnTemplateVersionEntity template = store.findTemplateForUpdate(
                tenantId, trim(templateId));
        if (template == null || !DRAFT.equals(template.getBizStatus())
                || !ENABLED.equals(template.getBizEnabled())) {
            throw ElnTemplateOperationException.conflict("只有启用的草稿模板可以修改绑定");
        }
        return template;
    }
 
    private ElnTemplateVersionEntity requireTemplate(TemplateAnnotationAuthorization authorization) {
        ElnTemplateVersionEntity template = store.findTemplate(
                authorization.getTenantId(), authorization.getTemplateId());
        if (template == null) {
            throw new DataException("模板不存在或不属于当前租户");
        }
        return template;
    }
 
    private ElnFieldDefEntity requireField(String tenantId, String fieldId) {
        ElnFieldDefEntity field = store.findField(tenantId, trim(fieldId));
        if (field == null || !ENABLED.equals(field.getBizEnabled())) {
            throw new DataException("字段不存在、已停用或不属于当前租户");
        }
        return field;
    }
 
    private ElnFieldVersionEntity requireFieldVersion(String tenantId, String versionId) {
        ElnFieldVersionEntity version = store.findFieldVersion(tenantId, trim(versionId));
        if (version == null) {
            throw new DataException("字段版本不存在或不属于当前租户");
        }
        return version;
    }
 
    private ElnFieldVersionEntity requireSelectableVersion(String tenantId, ElnFieldDefEntity field,
            String versionId, ElnTemplateVersionEntity template) {
        ElnFieldVersionEntity version = requireFieldVersion(tenantId, versionId);
        if (!field.getId().equals(version.getZiduanDingyiId())) {
            throw new DataException("字段版本不属于所选字段");
        }
        if (ElnFieldEnums.Scope.TEMPLATE.name().equals(field.getZuoyongFanwei())
                && !template.getMubanBianhao().equals(field.getMubanBianhao())) {
            throw new DataException("模板私有字段不属于当前模板");
        }
        if (!ElnFieldEnums.Scope.GLOBAL.name().equals(field.getZuoyongFanwei())
                && !ElnFieldEnums.Scope.TEMPLATE.name().equals(field.getZuoyongFanwei())) {
            throw new DataException("字段作用范围无效");
        }
        boolean preRelease = ElnFieldEnums.VersionStatus.PRE_RELEASE.name()
                .equals(version.getBizStatus());
        boolean currentPublished = ElnFieldEnums.VersionStatus.PUBLISHED.name()
                .equals(version.getBizStatus())
                && version.getId().equals(field.getDangqianZiduanBanbenId());
        if (!preRelease && !currentPublished) {
            throw new DataException("只能选择预发布或当前已发布字段版本");
        }
        return version;
    }
 
    private ElnTemplateBindingEntity requireBinding(
            TemplateAnnotationAuthorization authorization, String bindingId) {
        ElnTemplateBindingEntity binding = requireBinding(authorization.getTenantId(), bindingId);
        if (!authorization.getTemplateId().equals(binding.getMubanId())) {
            throw ElnTemplateOperationException.conflict("绑定不属于授权模板");
        }
        return binding;
    }
 
    private ElnTemplateBindingEntity requireBindingForUpdate(
            TemplateAnnotationAuthorization authorization, String bindingId) {
        ElnTemplateBindingEntity binding = requireBindingForUpdate(
                authorization.getTenantId(), bindingId);
        if (!authorization.getTemplateId().equals(binding.getMubanId())) {
            throw ElnTemplateOperationException.conflict("绑定不属于授权模板");
        }
        return binding;
    }
 
    private ElnTemplateBindingEntity requireBinding(String tenantId, String bindingId) {
        ElnTemplateBindingEntity binding = store.findBinding(tenantId, trim(bindingId));
        if (binding == null) {
            throw ElnTemplateOperationException.conflict("绑定不存在或不属于当前租户");
        }
        return binding;
    }
 
    private ElnTemplateBindingEntity requireBindingForUpdate(String tenantId, String bindingId) {
        ElnTemplateBindingEntity binding = store.findBindingForUpdate(tenantId, trim(bindingId));
        if (binding == null) {
            throw ElnTemplateOperationException.conflict("绑定不存在或不属于当前租户");
        }
        return binding;
    }
 
    private ElnTemplateBindingEntity requireActiveBinding(
            TemplateAnnotationAuthorization authorization, String bindingId) {
        ElnTemplateBindingEntity binding = requireBinding(authorization, bindingId);
        if (!ACTIVE.equals(binding.getBangdingZhuangtai())) {
            throw ElnTemplateOperationException.conflict("绑定不是有效状态");
        }
        return binding;
    }
 
    private ElnTemplateBindingEntity requireActiveBindingForUpdate(
            TemplateAnnotationAuthorization authorization, String bindingId) {
        ElnTemplateBindingEntity binding = requireBindingForUpdate(authorization, bindingId);
        if (!ACTIVE.equals(binding.getBangdingZhuangtai())) {
            throw ElnTemplateOperationException.conflict("绑定不是有效状态");
        }
        return binding;
    }
 
    private ElnTemplateBindingEntity requireActivePrimary(
            TemplateAnnotationAuthorization authorization, String bindingId) {
        ElnTemplateBindingEntity binding = requireActiveBinding(authorization, bindingId);
        if (!PRIMARY.equals(binding.getKongjianJuese())) {
            throw new DataException("操作目标必须是主控件");
        }
        return binding;
    }
 
    private ElnTemplateBindingEntity requireActivePrimaryForUpdate(
            TemplateAnnotationAuthorization authorization, String bindingId) {
        ElnTemplateBindingEntity binding = requireActiveBindingForUpdate(
                authorization, bindingId);
        if (!PRIMARY.equals(binding.getKongjianJuese())) {
            throw new DataException("操作目标必须是主控件");
        }
        return binding;
    }
 
    private UserContext requireUserContext() {
        UserContext user = userContextSupplier.get();
        if (user == null || !StringUtils.hasText(user.getTenantId())
                || !StringUtils.hasText(user.getUserId())) {
            throw new DataException("登录态无效");
        }
        return user;
    }
 
    private void insert(ElnTemplateBindingEntity binding) {
        try {
            store.insert(binding);
        } catch (DuplicateKeyException e) {
            throw ElnTemplateOperationException.conflict("绑定已存在或发生并发冲突");
        }
    }
 
    private void cas(ElnTemplateBindingEntity before,
                     ElnTemplateBindingEntity after, String expectedStatus) {
        if (before.getFVersion() == null
                || !store.compareAndSet(after, before.getFVersion(), expectedStatus)) {
            throw ElnTemplateOperationException.conflict("绑定状态已变化,请重新预检");
        }
    }
 
    private void casExpected(ElnTemplateBindingEntity before, ElnTemplateBindingEntity after,
                             String expectedStatus, Integer expectedVersion) {
        if (expectedVersion == null || before.getFVersion() == null
                || !expectedVersion.equals(before.getFVersion())
                || !store.compareAndSet(after, expectedVersion, expectedStatus)) {
            throw ElnTemplateOperationException.conflict("绑定状态已变化,请重新预检");
        }
    }
 
    private List<ElnTemplateVos.ControlSnapshot> activeSnapshots(
            TemplateAnnotationAuthorization authorization) {
        List<ElnTemplateVos.ControlSnapshot> result = new ArrayList<>();
        for (ElnTemplateBindingEntity binding
                : store.listBindings(authorization.getTenantId(), authorization.getTemplateId())) {
            if (ACTIVE.equals(binding.getBangdingZhuangtai())) {
                result.add(snapshotWithConfig(binding));
            }
        }
        return sortedSnapshots(result);
    }
 
    private List<ElnTemplateVos.ControlSnapshot> snapshots(
            List<ElnTemplateBindingEntity> bindings) {
        List<ElnTemplateVos.ControlSnapshot> result = new ArrayList<>();
        for (ElnTemplateBindingEntity binding : bindings) {
            result.add(snapshotWithConfig(binding));
        }
        return sortedSnapshots(result);
    }
 
    private static List<ElnTemplateVos.ControlSnapshot> sortedSnapshots(
            List<ElnTemplateVos.ControlSnapshot> controls) {
        List<ElnTemplateVos.ControlSnapshot> result = controls == null
                ? new ArrayList<>() : new ArrayList<>(controls);
        result.sort(Comparator.comparing(ElnTemplateVos.ControlSnapshot::getBindingId));
        return result;
    }
 
    public static ElnTemplateVos.ControlSnapshot snapshot(ElnTemplateBindingEntity binding) {
        ElnTemplateVos.ControlSnapshot result = new ElnTemplateVos.ControlSnapshot();
        result.setBindingId(binding.getId());
        result.setControlTag(binding.getKongjianBiaoqian());
        result.setControlAlias(binding.getKongjianBieming());
        result.setControlType(binding.getKongjianLeixing());
        result.setControlRole(binding.getKongjianJuese());
        result.setFieldVersionId(binding.getZiduanBanbenId());
        result.setPrimaryBindingId(binding.getYinyongShiliId());
        result.setRepeatGroupCode(binding.getRepeatGroupCode());
        result.setRepeatPrototypeRowId(binding.getRepeatPrototypeRowId());
        result.setStepId(binding.getStepId());
        return result;
    }
 
    private ElnTemplateVos.ControlSnapshot snapshotWithConfig(
            ElnTemplateBindingEntity binding) {
        ElnTemplateVos.ControlSnapshot result = snapshot(binding);
        result.setControlConfig(bindingControlConfig(binding));
        return result;
    }
 
    private ElnTemplateVos.Binding toBinding(ElnTemplateBindingEntity source) {
        ElnTemplateVos.Binding result = new ElnTemplateVos.Binding();
        result.setId(source.getId());
        result.setTemplateId(source.getMubanId());
        result.setFieldId(source.getZiduanDingyiId());
        result.setFieldCode(source.getZiduanBianma());
        result.setFieldVersionId(source.getZiduanBanbenId());
        result.setControlTag(source.getKongjianBiaoqian());
        result.setControlAlias(source.getKongjianBieming());
        result.setControlType(source.getKongjianLeixing());
        result.setControlRole(source.getKongjianJuese());
        result.setPrimaryBindingId(source.getYinyongShiliId());
        result.setRepeatGroupCode(source.getRepeatGroupCode());
        result.setRepeatPrototypeRowId(source.getRepeatPrototypeRowId());
        result.setCheckboxGroupCode(source.getCheckboxGroupCode());
        result.setStepId(source.getStepId());
        result.setControlConfig(bindingControlConfig(source));
        result.setStatus(source.getBangdingZhuangtai());
        result.setVersion(source.getFVersion());
        return result;
    }
 
    private Map<String, Object> bindingControlConfig(ElnTemplateBindingEntity binding) {
        ElnFieldVersionEntity version = requireFieldVersion(
                binding.getFTenantId(), binding.getZiduanBanbenId());
        if (!binding.getZiduanDingyiId().equals(version.getZiduanDingyiId())) {
            throw new DataException("绑定字段版本关系无效");
        }
        return DocxExpectedControlConfig.from(
                version.getShujuLeixing(), version.getKongjianPeizhi());
    }
 
    private static boolean fieldVisibleToTemplate(ElnFieldDefEntity field,
                                                  ElnTemplateVersionEntity template) {
        return ElnFieldEnums.Scope.GLOBAL.name().equals(field.getZuoyongFanwei())
                || (ElnFieldEnums.Scope.TEMPLATE.name().equals(field.getZuoyongFanwei())
                && template.getMubanBianhao().equals(field.getMubanBianhao()));
    }
 
    private static ElnFieldVos.Detail toFieldDetail(ElnFieldDefEntity source) {
        ElnFieldVos.Detail result = new ElnFieldVos.Detail();
        result.setId(source.getId());
        result.setZiduanBianma(source.getZiduanBianma());
        result.setZuoyongFanwei(source.getZuoyongFanwei());
        result.setMubanBianhao(source.getMubanBianhao());
        result.setDangqianZiduanBanbenId(source.getDangqianZiduanBanbenId());
        result.setBizEnabled(source.getBizEnabled());
        result.setBeizhu(source.getBeizhu());
        return result;
    }
 
    private static ElnFieldVos.Version toFieldVersion(ElnFieldVersionEntity source) {
        ElnFieldVos.Version result = new ElnFieldVos.Version();
        result.setId(source.getId());
        result.setZiduanDingyiId(source.getZiduanDingyiId());
        result.setBanbenHao(source.getBanbenHao());
        result.setZiduanMingcheng(source.getZiduanMingcheng());
        result.setShujuLeixing(source.getShujuLeixing());
        result.setDanwei(source.getDanwei());
        result.setShifouBitian(source.getShifouBitian());
        result.setPiciMoshi(source.getPiciMoshi());
        result.setBinding(StringUtils.hasText(source.getBangdingPeizhi())
                ? JsonUtil.getJsonToBean(source.getBangdingPeizhi(), ElnFieldForms.Binding.class)
                : null);
        result.setKongjianPeizhi(parseMap(source.getKongjianPeizhi()));
        result.setRecommendedCheckboxGroupCode(source.getRecommendedCheckboxGroupCode());
        result.setRecommendedCheckboxMinSelected(source.getRecommendedCheckboxMinSelected());
        result.setRecommendedCheckboxMaxSelected(source.getRecommendedCheckboxMaxSelected());
        result.setBizStatus(source.getBizStatus());
        result.setZuofeiYuanyin(source.getZuofeiYuanyin());
        result.setChuangjianShijian(source.getFCreatorTime());
        result.setGengxinShijian(source.getFLastModifyTime());
        return result;
    }
 
    private static void copyCheck(ElnTemplateVos.ChangeCheck source,
                                  ElnTemplateVos.ChangeCheck target) {
        target.setOperationCode(source.getOperationCode());
        target.setExpectedVersions(source.getExpectedVersions());
        target.setControls(source.getControls());
        target.setDependencies(source.getDependencies());
    }
 
    private static Map<String, Integer> versions(List<ElnTemplateBindingEntity> bindings) {
        List<ElnTemplateBindingEntity> sorted = new ArrayList<>(bindings);
        sorted.sort(Comparator.comparing(ElnTemplateBindingEntity::getId));
        Map<String, Integer> result = new LinkedHashMap<>();
        for (ElnTemplateBindingEntity binding : sorted) {
            result.put(binding.getId(), binding.getFVersion());
        }
        return result;
    }
 
    private static Set<String> ids(List<ElnTemplateBindingEntity> bindings) {
        Set<String> result = new LinkedHashSet<>();
        List<ElnTemplateBindingEntity> sorted = new ArrayList<>(bindings);
        sorted.sort(Comparator.comparing(ElnTemplateBindingEntity::getId));
        for (ElnTemplateBindingEntity binding : sorted) {
            result.add(binding.getId());
        }
        return result;
    }
 
    private static List<ElnTemplateBindingEntity> asList(
            ElnTemplateBindingEntity first, ElnTemplateBindingEntity second) {
        List<ElnTemplateBindingEntity> result = new ArrayList<>();
        result.add(first);
        result.add(second);
        return result;
    }
 
    private static List<String> canonicalControls(List<ElnTemplateVos.ControlSnapshot> controls) {
        if (controls == null) {
            return Collections.singletonList("<null>");
        }
        List<String> result = new ArrayList<>();
        for (ElnTemplateVos.ControlSnapshot item : controls) {
            if (item == null) {
                result.add("<null-item>");
            } else {
                result.add(value(item.getBindingId()) + "\u0000" + value(item.getControlTag())
                        + "\u0000" + value(item.getControlAlias()) + "\u0000"
                        + value(item.getControlType()) + "\u0000" + value(item.getControlRole())
                        + "\u0000" + value(item.getFieldVersionId()) + "\u0000"
                        + value(item.getPrimaryBindingId()) + "\u0000"
                        + value(item.getRepeatGroupCode()) + "\u0000"
                        + value(item.getRepeatPrototypeRowId()) + "\u0000"
                        + value(item.getStepId()));
            }
        }
        Collections.sort(result);
        return result;
    }
 
    private static String operationCode(String action,
            TemplateAnnotationAuthorization authorization,
            List<ElnTemplateBindingEntity> affected, String targetVersionId) {
        StringBuilder source = new StringBuilder(action).append('\u0000')
                .append(authorization.getTenantId()).append('\u0000')
                .append(authorization.getTemplateId()).append('\u0000');
        for (Map.Entry<String, Integer> item : versions(affected).entrySet()) {
            source.append(item.getKey()).append(':').append(item.getValue()).append(';');
        }
        source.append('\u0000').append(value(targetVersionId));
        return "eln-binding-" + action.substring(0, action.indexOf(':') < 0
                ? action.length() : action.indexOf(':')) + "-" + sha256(source.toString());
    }
 
    private static String bindingOperationCode(String operation, String bindingId) {
        String result = requireText(operation, "操作码不能为空") + ":"
                + requireText(bindingId, "绑定 ID 不能为空");
        if (result.length() > 160) {
            throw new DataException("绑定操作码超过 160 个字符");
        }
        return result;
    }
 
    private static String sha256(String source) {
        try {
            byte[] digest = MessageDigest.getInstance("SHA-256")
                    .digest(source.getBytes(StandardCharsets.UTF_8));
            StringBuilder result = new StringBuilder();
            for (byte item : digest) {
                result.append(String.format("%02x", item & 0xff));
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("JVM 不支持 SHA-256", e);
        }
    }
 
    private void audit(String actionCode, String tenantId, String userId, String operation,
            String templateId, String bindingId, Object before, Object after,
            String reason, String result) {
        Map<String, Object> snapshot = new LinkedHashMap<>();
        snapshot.put("operationCode", operation);
        snapshot.put("templateId", templateId);
        snapshot.put("bindingId", bindingId);
        snapshot.put("reason", reason);
        snapshot.put("result", result);
        snapshot.put("before", before);
        snapshot.put("after", after);
        auditRecorder.accept(AuditEventDTO.builder()
                .operationId(operation)
                .tenantId(tenantId)
                .operatorId(userId)
                .eventTime(new Date())
                .eventType("DATA_CHANGE")
                .actionCode(actionCode)
                .actionLabel(actionCode)
                .bizModule("eln")
                .bizType("eln_template_binding")
                .targetTable("eln_template_binding")
                .targetId(bindingId == null ? templateId : bindingId)
                .reason(reason)
                .dataSnapshot(JsonUtil.getObjectToString(snapshot))
                .build());
    }
 
    private void failureAudit(String action, String tenantId, String userId, String operation,
                              String templateId, String bindingId, RuntimeException error) {
        audit("ELN_TEMPLATE_BINDING_CONFIRM_FAILED", tenantId, userId, operation,
                templateId, bindingId, null, null,
                action + ": " + error.getMessage(), "FAILED");
    }
 
    private String templateIdForFailure(String tenantId, String bindingId) {
        ElnTemplateBindingEntity binding = store.findBinding(tenantId, trim(bindingId));
        return binding == null ? null : binding.getMubanId();
    }
 
    private void requireSamePrivateFieldRequest(TemplateAnnotationAuthorization authorization,
            ElnTemplateVersionEntity template, ElnTemplateBindingEntity binding,
            ElnTemplateForms.PrivateField form) {
        ElnFieldDefEntity field = requireField(
                authorization.getTenantId(), binding.getZiduanDingyiId());
        ElnFieldVersionEntity version = requireFieldVersion(
                authorization.getTenantId(), binding.getZiduanBanbenId());
        Integer required = form.getShifouBitian() == null ? 0 : form.getShifouBitian();
        Map<String, Object> expectedBinding = parseMap(
                JsonUtil.getObjectToString(manualBinding()));
        boolean same = PRIMARY.equals(binding.getKongjianJuese())
                && field.getId().equals(version.getZiduanDingyiId())
                && field.getId().equals(binding.getZiduanDingyiId())
                && version.getId().equals(binding.getZiduanBanbenId())
                && ElnFieldEnums.Scope.TEMPLATE.name().equals(field.getZuoyongFanwei())
                && template.getMubanBianhao().equals(field.getMubanBianhao())
                && Objects.equals(trimToNull(form.getBeizhu()), trimToNull(field.getBeizhu()))
                && ElnFieldEnums.VersionStatus.PRE_RELEASE.name().equals(version.getBizStatus())
                && Objects.equals(trimToNull(form.getZiduanMingcheng()),
                        trimToNull(version.getZiduanMingcheng()))
                && Objects.equals(trimToNull(form.getShujuLeixing()),
                        trimToNull(version.getShujuLeixing()))
                && Objects.equals(trimToNull(form.getDanwei()), trimToNull(version.getDanwei()))
                && Objects.equals(required, version.getShifouBitian())
                && ElnFieldEnums.BatchMode.RECORD_PRIVATE.name().equals(version.getPiciMoshi())
                && Objects.equals(expectedBinding, parseMap(version.getBangdingPeizhi()))
                && Objects.equals(form.getKongjianPeizhi(), parseMap(version.getKongjianPeizhi()))
                && Objects.equals(normalizeCheckboxGroupCode(form.getCheckboxGroupCode()),
                        binding.getCheckboxGroupCode())
                && Objects.equals(stepAssignmentResolver.resolve(authorization.getTenantId(),
                        template.getId(), form.getStepId()), binding.getStepId());
        if (!same) {
            throw ElnTemplateOperationException.conflict("私有字段操作码已用于其他请求");
        }
    }
 
    private static void requireValidReferencePrimary(ElnTemplateBindingEntity reference,
                                                      ElnTemplateBindingEntity primary) {
        if (primary == null || !REFERENCE.equals(reference.getKongjianJuese())
                || !ACTIVE.equals(primary.getBangdingZhuangtai())
                || !PRIMARY.equals(primary.getKongjianJuese())
                || !primary.getId().equals(reference.getYinyongShiliId())
                || !primary.getMubanId().equals(reference.getMubanId())
                || !primary.getZiduanDingyiId().equals(reference.getZiduanDingyiId())
                || !primary.getZiduanBanbenId().equals(reference.getZiduanBanbenId())) {
            throw ElnTemplateOperationException.conflict(
                    "引用控件必须指向同模板、同字段版本的有效主控件");
        }
    }
 
    private static ElnFieldForms.Binding manualBinding() {
        ElnFieldForms.Read read = new ElnFieldForms.Read();
        read.setSource(ElnFieldEnums.ReadSource.NONE.name());
        ElnFieldForms.Write write = new ElnFieldForms.Write();
        write.setTarget("ELN_RECORD");
        ElnFieldForms.Binding binding = new ElnFieldForms.Binding();
        binding.setRead(read);
        binding.setWrite(write);
        return binding;
    }
 
    @SuppressWarnings("unchecked")
    private static Map<String, Object> parseMap(String json) {
        return StringUtils.hasText(json) ? JsonUtil.getJsonToBean(json, Map.class) : null;
    }
 
    private static String controlType(String dataType) {
        if (ElnFieldEnums.DataType.TEXT.name().equals(dataType)
                || ElnFieldEnums.DataType.DECIMAL.name().equals(dataType)) {
            return ElnTemplateEnums.ControlType.TEXT.name();
        }
        if (ElnFieldEnums.DataType.TEXTAREA.name().equals(dataType)) {
            return ElnTemplateEnums.ControlType.MULTILINE.name();
        }
        if (ElnFieldEnums.DataType.SELECT.name().equals(dataType)) {
            return ElnTemplateEnums.ControlType.DROPDOWN.name();
        }
        if (ElnFieldEnums.DataType.CHECKBOX.name().equals(dataType)) {
            return ElnTemplateEnums.ControlType.CHECKBOX.name();
        }
        if (ElnFieldEnums.DataType.DATE.name().equals(dataType)
                || ElnFieldEnums.DataType.DATETIME.name().equals(dataType)) {
            return ElnTemplateEnums.ControlType.DATE.name();
        }
        throw new DataException("字段数据类型不支持 Word 控件绑定");
    }
 
    private static String uniqueDocxFileId(String attachments) {
        try {
            List<ElnDocumentFileVo> files = JsonUtil.getJsonToList(attachments, ElnDocumentFileVo.class);
            String result = null;
            if (files != null) {
                for (ElnDocumentFileVo file : files) {
                    if (file != null && StringUtils.hasText(file.getFileId())) {
                        String id = file.getFileId().trim();
                        boolean docx = "docx".equalsIgnoreCase(file.getFileExtension())
                                || id.toLowerCase().endsWith(".docx");
                        if (docx) {
                            if (result != null) {
                                throw new DataException("模板必须且只能包含一个 DOCX 附件");
                            }
                            result = id;
                        }
                    }
                }
            }
            if (result == null) {
                throw new DataException("模板必须且只能包含一个 DOCX 附件");
            }
            return result;
        } catch (DataException e) {
            throw e;
        } catch (RuntimeException e) {
            throw new DataException("模板附件无效");
        }
    }
 
    private static boolean isLive(ElnTemplateBindingEntity binding) {
        return PENDING.equals(binding.getBangdingZhuangtai())
                || ACTIVE.equals(binding.getBangdingZhuangtai());
    }
 
    private static void requireReserveForm(ElnTemplateForms.ReserveBinding form) {
        if (form == null || !StringUtils.hasText(form.getFieldId())
                || !StringUtils.hasText(form.getFieldVersionId())
                || !StringUtils.hasText(form.getOperationCode())) {
            throw new DataException("字段、字段版本和操作码不能为空");
        }
    }
 
    private static String requireRepeatToken(String value, String message) {
        String token = requireText(value, message);
        if (!token.matches("[A-Za-z0-9_-]{1,80}")) {
            throw new DataException(message);
        }
        return token;
    }
 
    private static String normalizeCheckboxGroupCode(String value) {
        String code = trimToNull(value);
        if (code != null && !code.matches("[A-Za-z0-9_-]{1,80}")) {
            throw new DataException("选择组编码只能包含字母、数字、下划线和短横线,且不能超过80个字符");
        }
        return code;
    }
 
    private void validateCheckboxGroupAssignment(
            TemplateAnnotationAuthorization authorization,
            String excludedBindingId,
            String checkboxGroupCode,
            String role,
            String repeatGroupCode,
            String stepId,
            ElnFieldVersionEntity version) {
        if (checkboxGroupCode == null) {
            return;
        }
        if ((!PRIMARY.equals(role) && !REPEAT.equals(role))
                || !ElnTemplateEnums.ControlType.CHECKBOX.name().equals(
                        controlType(version.getShujuLeixing()))) {
            throw new DataException("只有可编辑复选框可以加入选择组");
        }
        ElnFieldForms.Binding bindingConfig = StringUtils.hasText(version.getBangdingPeizhi())
                ? JsonUtil.getJsonToBean(version.getBangdingPeizhi(), ElnFieldForms.Binding.class)
                : null;
        String readSource = bindingConfig == null || bindingConfig.getRead() == null
                ? null : trimToNull(bindingConfig.getRead().getSource());
        if (readSource != null && !ElnFieldEnums.ReadSource.NONE.name().equals(readSource)) {
            throw new DataException("只读来源复选框不能加入选择组");
        }
        if (excludedBindingId != null) {
            List<ElnTemplateVos.Diagnostic> diagnostics = new ArrayList<>();
            for (ElnTemplateBindingDependencyValidator validator : dependencyValidators) {
                addDiagnostics(diagnostics, validator.validateCheckboxGroup(
                        authorization.getTenantId(), authorization.getTemplateId(),
                        excludedBindingId));
            }
            rejectDependencyErrors(diagnostics);
        }
        boolean defaultChecked = isDefaultChecked(version);
        int defaultCheckedMembers = 0;
        for (ElnTemplateBindingEntity member
                : store.listBindings(authorization.getTenantId(), authorization.getTemplateId())) {
            if (!isLive(member) || Objects.equals(excludedBindingId, member.getId())
                    || !checkboxGroupCode.equals(member.getCheckboxGroupCode())) {
                continue;
            }
            if (!role.equals(member.getKongjianJuese())
                    || (PRIMARY.equals(role) && !Objects.equals(stepId, member.getStepId()))
                    || (REPEAT.equals(role)
                    && !Objects.equals(repeatGroupCode, member.getRepeatGroupCode()))) {
                throw new DataException("同一选择组必须位于同一步骤和同一普通或重复作用域");
            }
            if (isDefaultChecked(requireFieldVersion(
                    authorization.getTenantId(), member.getZiduanBanbenId()))) {
                defaultCheckedMembers++;
            }
        }
        Integer maxSelected = checkboxGroupMaxSelected(authorization, checkboxGroupCode);
        if (defaultChecked && maxSelected != null && defaultCheckedMembers >= maxSelected) {
            throw new DataException("选择组默认勾选数不能超过最多选择数 " + maxSelected);
        }
    }
 
    private Integer checkboxGroupMaxSelected(
            TemplateAnnotationAuthorization authorization, String groupCode) {
        if (checkboxGroupService != null) {
            for (ElnTemplateVos.CheckboxGroup group : checkboxGroupService.list(
                    authorization.getTenantId(), authorization.getTemplateId())) {
                if (groupCode.equals(group.getGroupCode())) {
                    return group.getMaxSelected();
                }
            }
        }
        return 1;
    }
 
    private static boolean isDefaultChecked(ElnFieldVersionEntity version) {
        Map<String, Object> config = parseMap(version.getKongjianPeizhi());
        return config != null && Boolean.TRUE.equals(config.get("defaultChecked"));
    }
 
    private static String operation(ElnTemplateForms.ChangeConfirm form) {
        return form == null ? null : form.getOperationCode();
    }
 
    private static String requireText(String text, String message) {
        if (!StringUtils.hasText(text)) {
            throw new DataException(message);
        }
        return text.trim();
    }
 
    private static String trim(String text) {
        return text == null ? null : text.trim();
    }
 
    private static String trimToNull(String text) {
        return StringUtils.hasText(text) ? text.trim() : null;
    }
 
    private static String value(String text) {
        return text == null ? "" : text;
    }
 
    private static ElnTemplateVos.StepConfiguration singleStepConfiguration(String stepId) {
        ElnTemplateVos.Step step = new ElnTemplateVos.Step();
        step.setId(stepId);
        step.setName("实验步骤");
        step.setOrder(1);
        ElnTemplateVos.StepConfiguration result = new ElnTemplateVos.StepConfiguration();
        result.setSingleStep(true);
        result.setSteps(Collections.singletonList(step));
        return result;
    }
 
    private static ElnTemplateBindingEntity copy(ElnTemplateBindingEntity source) {
        ElnTemplateBindingEntity copy = new ElnTemplateBindingEntity();
        copy.setId(source.getId());
        copy.setMubanId(source.getMubanId());
        copy.setMubanBianhao(source.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(source.getYinyongShiliId());
        copy.setRepeatGroupCode(source.getRepeatGroupCode());
        copy.setRepeatPrototypeRowId(source.getRepeatPrototypeRowId());
        copy.setCheckboxGroupCode(source.getCheckboxGroupCode());
        copy.setStepId(source.getStepId());
        copy.setBangdingZhuangtai(source.getBangdingZhuangtai());
        copy.setCaozuoBianma(source.getCaozuoBianma());
        copy.setLaiyuanBangdingId(source.getLaiyuanBangdingId());
        copy.setDaoqiShijian(source.getDaoqiShijian());
        copy.setZhuangtaiYuanyin(source.getZhuangtaiYuanyin());
        copy.setFTenantId(source.getFTenantId());
        copy.setFVersion(source.getFVersion());
        copy.setFCreatorUserId(source.getFCreatorUserId());
        copy.setFLastModifyUserId(source.getFLastModifyUserId());
        copy.setFDeleteMark(source.getFDeleteMark());
        return copy;
    }
 
    private List<DocxControlSnapshot> prepareDocumentEvidence(
            TemplateAnnotationAuthorization authorization) {
        if (authorization == null || !StringUtils.hasText(authorization.getTenantId())
                || !StringUtils.hasText(authorization.getTemplateId())
                || !StringUtils.hasText(authorization.getFileId())) {
            throw new DataException("模板标注授权无效");
        }
        List<DocxControlSnapshot> controls = documentEvidence.readControls(
                authorization.getTenantId(), authorization.getFileId());
        if (controls == null) {
            throw new DataException("DOCX 控件证据无效");
        }
        if (pendingCleanupService != null) {
            pendingCleanupService.reconcileExpired(authorization.getTenantId(),
                    authorization.getTemplateId(), new Date(), controls);
        }
        return controls;
    }
 
    private static ElnTemplateDocumentEvidence evidence(
            ObjectProvider<ElnTemplateDocumentEvidence> provider) {
        ElnTemplateDocumentEvidence evidence = provider.getIfAvailable();
        return evidence == null ? (tenantId, fileId) -> {
            throw new DataException("DOCX 控件证据服务不可用");
        } : evidence;
    }
 
    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() : null;
        String userId = user == null || !StringUtils.hasText(user.getUserId())
                ? null : user.getUserId().trim();
        return new UserContext(tenantId, userId);
    }
 
    public interface BindingStore {
        ElnTemplateVersionEntity findTemplate(String tenantId, String templateId);
        ElnTemplateVersionEntity findTemplateForUpdate(String tenantId, String templateId);
        List<ElnFieldDefEntity> listFields(String tenantId);
        List<ElnFieldVersionEntity> listFieldVersions(String tenantId, String fieldId);
        ElnFieldDefEntity findField(String tenantId, String fieldId);
        ElnFieldVersionEntity findFieldVersion(String tenantId, String versionId);
        ElnTemplateBindingEntity findBinding(String tenantId, String bindingId);
        ElnTemplateBindingEntity findBindingForUpdate(String tenantId, String bindingId);
        ElnTemplateBindingEntity findByOperation(String tenantId, String templateId,
                                                 String operationCode);
        List<ElnTemplateBindingEntity> listBindings(String tenantId, String templateId);
        void insert(ElnTemplateBindingEntity binding);
        boolean compareAndSet(ElnTemplateBindingEntity replacement,
                              int expectedVersion, String expectedStatus);
    }
 
    private static final class MyBatisBindingStore implements BindingStore {
        private final ElnTemplateMapper templateMapper;
        private final ElnFieldDefMapper fieldMapper;
        private final ElnFieldVersionMapper fieldVersionMapper;
        private final ElnTemplateBindingMapper bindingMapper;
 
        private MyBatisBindingStore(ElnTemplateMapper templateMapper,
                ElnFieldDefMapper fieldMapper, ElnFieldVersionMapper fieldVersionMapper,
                ElnTemplateBindingMapper bindingMapper) {
            this.templateMapper = templateMapper;
            this.fieldMapper = fieldMapper;
            this.fieldVersionMapper = fieldVersionMapper;
            this.bindingMapper = bindingMapper;
        }
 
        @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.selectOne(Wrappers.<ElnTemplateVersionEntity>lambdaQuery()
                    .eq(ElnTemplateVersionEntity::getFTenantId, tenantId)
                    .eq(ElnTemplateVersionEntity::getId, templateId)
                    .and(q -> q.isNull(ElnTemplateVersionEntity::getFDeleteMark)
                            .or().eq(ElnTemplateVersionEntity::getFDeleteMark, 0))
                    .last("FOR UPDATE"));
        }
 
        @Override
        public ElnFieldDefEntity findField(String tenantId, String fieldId) {
            return fieldMapper.selectOne(Wrappers.<ElnFieldDefEntity>lambdaQuery()
                    .eq(ElnFieldDefEntity::getFTenantId, tenantId)
                    .eq(ElnFieldDefEntity::getId, fieldId)
                    .and(q -> q.isNull(ElnFieldDefEntity::getFDeleteMark)
                            .or().eq(ElnFieldDefEntity::getFDeleteMark, 0)));
        }
 
        @Override
        public List<ElnFieldDefEntity> listFields(String tenantId) {
            return fieldMapper.selectList(Wrappers.<ElnFieldDefEntity>lambdaQuery()
                    .eq(ElnFieldDefEntity::getFTenantId, tenantId)
                    .and(q -> q.isNull(ElnFieldDefEntity::getFDeleteMark)
                            .or().eq(ElnFieldDefEntity::getFDeleteMark, 0))
                    .orderByAsc(ElnFieldDefEntity::getZiduanBianma));
        }
 
        @Override
        public List<ElnFieldVersionEntity> listFieldVersions(String tenantId, String fieldId) {
            return fieldVersionMapper.selectList(Wrappers.<ElnFieldVersionEntity>lambdaQuery()
                    .eq(ElnFieldVersionEntity::getFTenantId, tenantId)
                    .eq(ElnFieldVersionEntity::getZiduanDingyiId, fieldId)
                    .and(q -> q.isNull(ElnFieldVersionEntity::getFDeleteMark)
                            .or().eq(ElnFieldVersionEntity::getFDeleteMark, 0))
                    .orderByAsc(ElnFieldVersionEntity::getBanbenHao)
                    .orderByAsc(ElnFieldVersionEntity::getId));
        }
 
        @Override
        public ElnFieldVersionEntity findFieldVersion(String tenantId, String versionId) {
            return fieldVersionMapper.selectOne(Wrappers.<ElnFieldVersionEntity>lambdaQuery()
                    .eq(ElnFieldVersionEntity::getFTenantId, tenantId)
                    .eq(ElnFieldVersionEntity::getId, versionId)
                    .and(q -> q.isNull(ElnFieldVersionEntity::getFDeleteMark)
                            .or().eq(ElnFieldVersionEntity::getFDeleteMark, 0)));
        }
 
        @Override
        public ElnTemplateBindingEntity findBinding(String tenantId, String bindingId) {
            return bindingMapper.selectOne(Wrappers.<ElnTemplateBindingEntity>lambdaQuery()
                    .eq(ElnTemplateBindingEntity::getFTenantId, tenantId)
                    .eq(ElnTemplateBindingEntity::getId, bindingId)
                    .and(q -> q.isNull(ElnTemplateBindingEntity::getFDeleteMark)
                            .or().eq(ElnTemplateBindingEntity::getFDeleteMark, 0)));
        }
 
        @Override
        public ElnTemplateBindingEntity findBindingForUpdate(String tenantId, String bindingId) {
            return bindingMapper.selectOne(Wrappers.<ElnTemplateBindingEntity>lambdaQuery()
                    .eq(ElnTemplateBindingEntity::getFTenantId, tenantId)
                    .eq(ElnTemplateBindingEntity::getId, bindingId)
                    .and(q -> q.isNull(ElnTemplateBindingEntity::getFDeleteMark)
                            .or().eq(ElnTemplateBindingEntity::getFDeleteMark, 0))
                    .last("FOR UPDATE"));
        }
 
        @Override
        public ElnTemplateBindingEntity findByOperation(String tenantId, String templateId,
                                                        String operationCode) {
            return bindingMapper.selectOne(Wrappers.<ElnTemplateBindingEntity>lambdaQuery()
                    .eq(ElnTemplateBindingEntity::getFTenantId, tenantId)
                    .eq(ElnTemplateBindingEntity::getMubanId, templateId)
                    .eq(ElnTemplateBindingEntity::getCaozuoBianma, operationCode)
                    .and(q -> q.isNull(ElnTemplateBindingEntity::getFDeleteMark)
                            .or().eq(ElnTemplateBindingEntity::getFDeleteMark, 0)));
        }
 
        @Override
        public List<ElnTemplateBindingEntity> listBindings(String tenantId, String templateId) {
            return bindingMapper.selectList(Wrappers.<ElnTemplateBindingEntity>lambdaQuery()
                    .eq(ElnTemplateBindingEntity::getFTenantId, tenantId)
                    .eq(ElnTemplateBindingEntity::getMubanId, templateId)
                    .and(q -> q.isNull(ElnTemplateBindingEntity::getFDeleteMark)
                            .or().eq(ElnTemplateBindingEntity::getFDeleteMark, 0))
                    .orderByAsc(ElnTemplateBindingEntity::getId));
        }
 
        @Override
        public void insert(ElnTemplateBindingEntity binding) {
            bindingMapper.insert(binding);
        }
 
        @Override
        public boolean compareAndSet(ElnTemplateBindingEntity replacement,
                                     int expectedVersion, String expectedStatus) {
            return bindingMapper.update(null,
                    Wrappers.<ElnTemplateBindingEntity>lambdaUpdate()
                            .eq(ElnTemplateBindingEntity::getFTenantId, replacement.getFTenantId())
                            .eq(ElnTemplateBindingEntity::getId, replacement.getId())
                            .eq(ElnTemplateBindingEntity::getFVersion, expectedVersion)
                            .eq(ElnTemplateBindingEntity::getBangdingZhuangtai, expectedStatus)
                            .set(ElnTemplateBindingEntity::getZiduanBanbenId,
                                    replacement.getZiduanBanbenId())
                            .set(ElnTemplateBindingEntity::getKongjianBiaoqian,
                                    replacement.getKongjianBiaoqian())
                            .set(ElnTemplateBindingEntity::getKongjianBieming,
                                    replacement.getKongjianBieming())
                            .set(ElnTemplateBindingEntity::getKongjianLeixing,
                                    replacement.getKongjianLeixing())
                            .set(ElnTemplateBindingEntity::getKongjianJuese,
                                    replacement.getKongjianJuese())
                            .set(ElnTemplateBindingEntity::getYinyongShiliId,
                                    replacement.getYinyongShiliId())
                            .set(ElnTemplateBindingEntity::getRepeatGroupCode,
                                    replacement.getRepeatGroupCode())
                            .set(ElnTemplateBindingEntity::getRepeatPrototypeRowId,
                                    replacement.getRepeatPrototypeRowId())
                            .set(ElnTemplateBindingEntity::getCheckboxGroupCode,
                                    replacement.getCheckboxGroupCode())
                            .set(ElnTemplateBindingEntity::getStepId,
                                    replacement.getStepId())
                            .set(ElnTemplateBindingEntity::getBangdingZhuangtai,
                                    replacement.getBangdingZhuangtai())
                            .set(ElnTemplateBindingEntity::getCaozuoBianma,
                                    replacement.getCaozuoBianma())
                            .set(ElnTemplateBindingEntity::getZhuangtaiYuanyin,
                                    replacement.getZhuangtaiYuanyin())
                            .set(ElnTemplateBindingEntity::getFVersion, expectedVersion + 1)) == 1;
        }
    }
 
    public static final class UserContext {
        private final String tenantId;
        private final String userId;
 
        public UserContext(String tenantId, String userId) {
            this.tenantId = tenantId;
            this.userId = userId;
        }
 
        public String getTenantId() { return tenantId; }
        public String getUserId() { return userId; }
    }
 
    @FunctionalInterface
    interface StepAssignmentResolver {
        String resolve(String tenantId, String templateId, String requestedStepId);
    }
 
    @FunctionalInterface
    interface StepConfigurationReader {
        ElnTemplateVos.StepConfiguration read(String templateId);
    }
}