游畅
2023-04-29 cc266a1e4080bb3ecc47ea4a202dd549545111e1
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
// RentalFixtureSetAssignAgencyCtrlTest
public with sharing class RentalFixtureSetAssignAgencyController {
    public List<EsdInfo> esdList { get; set; }
    public FixtureDeliverySlip__c slip { get; set; }
    public Boolean done_flg { get; set; }
    private String taId;
    public Boolean readOnly { get;  set; }
    public Rental_Apply__c parentObj { get; private set; }
    public String qrcode {get;set;}
    public Boolean slipEnabled {get;set;}
    public String cancelReason {get;set;}
    public String cancelReasonRemark {get;set;}
    private Boolean isSameCity ;
    public String stepName {get;set;}
    public Date masterDate {get;set;} // 主单的预计出货日
    public List<String> bieBeiPinFenLeiList; //别备品分类 //20210508 ljh add
 
    public RentalFixtureSetAssignAgencyController() {
        taId = ApexPages.currentPage().getParameters().get('pt_recid');
        stepName = '无';
    }
    public PageReference init() {
 
        done_flg = false;
        slipEnabled = false;
        isSameCity = false;
        bieBeiPinFenLeiList = new List<String>(); //20210508 ljh add
        if (taId != null) {
            readOnly = false;
            String rasql = 'SELECT Id'
                         + ', Name'
                         + ', Yi_loaner_arranged__c'
                         + ', demo_purpose2__c'
                         + ', Asset_loaner_start_day__c'
                         + ', Asset_loaner_closed_day__c'
                         + ', Hope_Lonaer_date_Num__c'
                         + ', Campaign_EndDate_F__c'
                         + ', requestNoJoinStr2__c'
                         + ', ToAgency__c'
                         + ', StockDown_ng_num__c'
                         + ', DeliverySlip__c'
                         + ', Status__c'
                         + ', Old_Rental_Apply__r.Asset_loaner_start_date__c'
                         + ', Delivery_Agency__c'
                         + ', SalesdeptSelect__c'
                         + ', OwnerId'
                         + ', Cancel_Reason__c'//20210707 SFDC-C448KZ you
                         + ', Loaner_cancel_reason__c'//20210707 SFDC-C448KZ you
                         + ', Loaner_cancel_request__c'//20210707 SFDC-C448KZ you
                         + ', Equipment_Type_F__c' //20210508 LJH ADD 1672
                         + ', Wei_Assigned_Cnt__c' // 20210624 ljh add SFDC-C448GR start
                         + ', Campaign__r.IF_Approved__c' // 20220315 ljh add
                         + ', Campaign__r.Meeting_Approved_No__r.Name' // 20220315 ljh add 
                         + ', Campaign__r.Approved_Status__c' // 20220315 ljh add 
                         //+ ', Hospital__r.TradeComplianceStatus__c' // 贸易合规 you 
                         + ' FROM Rental_Apply__c'
                         + ' WHERE Id=\'' + taId + '\'';
            List<Rental_Apply__c>  raList = (List<Rental_Apply__c>) Consum_ApplyUtil.withoutQueryList(rasql);
            if(raList.isEmpty()) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '借出申请不存在!'));
                return null;
            }
            parentObj = raList[0];
            List<User> owners = [SELECT OCM_man_province_Rental__c FROM User WHERE Id=:parentObj.OwnerId LIMIT 1];
            if(owners.isEmpty()) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '申请者不存在!'));
                return null;
            }
            else {
                isSameCity = owners[0].OCM_man_province_Rental__c == parentObj.ToAgency__c;
            }
            masterDate = parentObj.Old_Rental_Apply__r.Asset_loaner_start_date__c;
 
            //20210508 ljh add 1672 start
            if (bieBeiPinFenLeiList.size() == 0 && String.isNotBlank(parentObj.Equipment_Type_F__c)) {
                for (String et : parentObj.Equipment_Type_F__c.split(',')) {
                    bieBeiPinFenLeiList.add(et);
                }
            }
            //20210508 ljh add 1672 end
 
            esdList = new List<EsdInfo>();
            List<Rental_Apply_Equipment_Set_Detail__c> eList = getDetails();
            for (Rental_Apply_Equipment_Set_Detail__c esd : eList) {
                EsdInfo ei = new EsdInfo(esd);
                esdList.add(ei);
            }
            if (!esdList.isEmpty()) {
                if (parentObj.Yi_loaner_arranged__c > 0) {
                    readOnly = true;
                }
                // 20210624 ljh add SFDC-C448GR start
                // 全部下架且非同城时才可编辑
                // else if(parentObj.StockDown_ng_num__c == 0 && !isSameCity) {
                //     slipEnabled = true;
                // }
                // 全部分配且非同城时才可编辑
                else if(parentObj.Wei_Assigned_Cnt__c == 0 && !isSameCity) {
                    slipEnabled = true;
                }
                // 20210624 ljh add SFDC-C448GR end
            }
            else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有借出明细!'));
                return null;
            }
        }
        if(parentObj == null) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '借出申请不存在!'));
            return null;
        }
        if(parentObj.DeliverySlip__c != null) {
            List<FixtureDeliverySlip__c> slipList = [
                SELECT Id
                     , DeliveryType__c
                     , Name
                     , Distributor_method__c
                     , DeliveryCompany__c
                     , Wh_Staff__c
                  FROM FixtureDeliverySlip__c
                 WHERE Id=:parentObj.DeliverySlip__c
                 LIMIT 1
            ];
            if(slipList.isEmpty()) {
                slip = new FixtureDeliverySlip__c();
                slip.DeliveryType__c = '发货';
                slip.Wh_Staff__c = Userinfo.getUserId();
            }
            else {
                slip = slipList[0];
            }
        }
        else {
            slip = new FixtureDeliverySlip__c();
            slip.DeliveryType__c = '发货';
            slip.Wh_Staff__c = Userinfo.getUserId();
        }
        return null;
    }
    // 检索运输单
    public void searchSlip() {
        done_flg = false;
        String qryString = 'select Combine_Pack__c, Name, Id, DeliveryCompany_SlipNo__c,DeliveryType__c,Distributor_method__c,DeliveryCompany__c,Wh_Staff__c '
                + 'from FixtureDeliverySlip__c '
                + 'where Name =\''+ slip.Name +'\' and DeliveryType__c = \'发货\'';
        if (String.isNotBlank(slip.Distributor_method__c)) {
            qryString += ' and Distributor_method__c = \''+ slip.Distributor_method__c +'\'';
        }
        if (String.isNotBlank(slip.DeliveryCompany__c)) {
            qryString += ' and DeliveryCompany__c = \''+ slip.DeliveryCompany__c +'\'';
        }
        List<FixtureDeliverySlip__c> slipList = Database.query(qryString);
 
        if (slipList.size() > 0) {
            if (slipList.size() > 1) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '当前条件检索到复数条运输单,请追加检索条件!'));
                return ;
            }
            slip = slipList[0];
        }
        return ;
    }
    //20210518 ljh add 1289 start
    private Map<Id, Rental_Apply_Equipment_Set__c> getReasMap(Boolean cancle) {
        List<Rental_Apply_Equipment_Set__c> raesList = getReas(cancle,null);
        Map<Id, Rental_Apply_Equipment_Set__c> raesMap = new Map<Id, Rental_Apply_Equipment_Set__c>();
 
        for(Rental_Apply_Equipment_Set__c raesd:raesList) {
            raesMap.put(raesd.Id, raesd);
        }
        return raesMap;
    }
    //获取一览 cancle false 所有 else 未取消  raesId null 申请属下的所有一览 else 指定一览
    private List<Rental_Apply_Equipment_Set__c> getReas(Boolean cancle,Id raesId) {
        String soql = 'Select Id, Loaner_centre_mail_address__c, Fixture_Set__c, Substitute_Select_Again__c,Cancel_Select__c,canDelete__c,Test_Day__c,';
        soql += 'Rental_Apply__c, Irreplaceable_flag__c, Same_Accessory_flag__c, Received_Confirm__c, IndexFromUniqueKey__c,Old_RetalFSetDetail_Cnt__c,';
        soql += 'Rental_Num__c, Groupby_SortInt__c, Canceled__c, Canceled_Id__c, RetalFSetDetail_Cnt__c, Old_Rental_Apply__c,Rental_Start_Date__c,Rental_End_Date__c';
        if(cancle){
            soql += ' ,Loaner_code_F__c';
        }
        if(raesId != null){
            soql += ' ,Rental_Apply__r.Status__c,RAES_Status__c,Shippment_loaner_time2__c';
        }
        soql += ' From Rental_Apply_Equipment_Set__c';
        if(raesId != null){
            soql += ' Where Id = \'' + raesId+'\'';
        }else{
            soql += ' Where Rental_Apply__c = \'' + taId+'\'';
        }
        
        if(!cancle){
            soql +='AND Cancel_Select__c = '+cancle;
        }
        soql +=' ORDER BY Name';
        List<Rental_Apply_Equipment_Set__c> raess = Database.query(soql);
        return raess;
    }
    private List<Rental_Apply_Equipment_Set_Detail__c> getDetails(List<Rental_Apply_Equipment_Set__c> delRaesId) {
        List<Rental_Apply_Equipment_Set_Detail__c> eList = [
                SELECT Id FROM Rental_Apply_Equipment_Set_Detail__c WHERE Rental_Apply_Equipment_Set__c in :delRaesId
              ORDER BY Rental_Apply_Equipment_Set__r.Name, Rental_Apply_Equipment_Set__c, Is_Body__c DESC, Name
        ];
        return eList;
    }
    //20210518 ljh add 1289 end
    private Map<Id, Rental_Apply_Equipment_Set_Detail__c> getDetailsMap() {
        List<Rental_Apply_Equipment_Set_Detail__c> raesdList = getDetails();
        Map<Id, Rental_Apply_Equipment_Set_Detail__c> raesdMap = new Map<Id, Rental_Apply_Equipment_Set_Detail__c>();
 
        for(Rental_Apply_Equipment_Set_Detail__c raesd:raesdList) {
            raesdMap.put(raesd.Id, raesd);
        }
        return raesdMap;
    }
    private List<Rental_Apply_Equipment_Set_Detail__c> getDetails() {
        List<Rental_Apply_Equipment_Set_Detail__c> eList = [
                SELECT Id
                     , AgencyTempCancel__c
                     , Asset__c
                     , Asset__r.Internal_asset_location__c
                     , Asset__r.Internal_Asset_number_key__c
                     , Asset__r.SerialNumber
                     , Asset__r.Equipment_Type__c //20210508 ljh add 1672
                     , Cancel_Select__c
                     , DeliverySlip__c
                     , Fixture_Model_No_text__c
                     , Fixture_Model_No__c
                     , Fixture_OneToOne_Link_Id__c
                     , Fixture_QRCode_F__c
                     , Fixture_Set_Detail__c
                     , Fixture_Set_Id__c
                     , FSD_Fixture_Model_No__c
                     , FSD_Id__c
                     , FSD_Is_OneToOne_F__c
                     , FSD_Is_Optional_F__c
                     , FSD_Name_CHN__c
                     , FSD_OneToOneAccessory_Cnt_F__c
                     , IndexFromUniqueKey__c
                     , IndexFromUniqueKey_Text__c
                     , Internal_asset_location__c
                     , Internal_asset_location_before__c
                     , Is_Body__c
                     , Product_category_text__c
                     , RAESD_Status__c
                     , Rental_Apply_Equipment_Set__c
                     , Rental_Apply_Equipment_Set__r.First_RAESD__r.Fixture_Model_No__c
                     , Rental_Apply_Equipment_Set__r.Rental_Start_Date__c //20210519 ljh add 1829 start
                     , Rental_Apply_Equipment_Set__r.Irreplaceable_flag__c //20210519 ljh add 1829 start
                     , Rental_Apply_Equipment_Set__r.canDelete__c //20210519 ljh add 1829 start
                     , Rental_Apply_Equipment_Set__r.Substitute_flag__c //20210526 ljh 1829 add
                     , Rental_Apply_Equipment_Set__r.RAES_Status__c
                     , Rental_Apply_Equipment_Set__r.Shippment_loaner_time2__c
                     , Rental_Apply__r.Status__c //20210519 ljh add 1829 end
                     , Rental_Apply__r.Request_approval_time__c //20220309 SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 
                     , Add_Request_approval_time__c //20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 
                     , ApplyToShipmentWorkTime__c   //20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 
                     , Rental_Num__c
                     , Rental_Start_Date__c
                     , Select_Time__c
                     , SerialNumber__c
                     , SerialNumber_F__c
                     , SerialNumber_text__c
                     , Shippment_loaner_time__c
                     , StockDown__c
                     , LastModifiedDate
                     , LastModifiedBy.Name
                     , AgencyAssignAdd__c
                     , Rental_Apply__c
                     , Equipment_Type__c //20210508 ljh add 1834
                  FROM Rental_Apply_Equipment_Set_Detail__c
                 WHERE Rental_Apply__c = :taId
                   AND Cancel_Select__c = False
              ORDER BY Rental_Apply_Equipment_Set__r.Name, Rental_Apply_Equipment_Set__c, Is_Body__c DESC, Name
        ];
        return eList;
    }
    // 一览取消
    public void cancelSet() {
        done_flg = false;
        Savepoint sp = Database.setSavepoint();
        try {
            //20210420 ljh update start
            // if(String.isBlank(cancelReason)|| String.isBlank(cancelReasonRemark)){
            //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '取消理由和备注不可为空!'));
            //     return;
            // }
 
            // if(String.isBlank(cancelReason)) {
            //     if(String.isBlank(cancelReasonRemark)){
            //         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '取消理由和取消理由备注不可为空!'));
            //     }else{
            //         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '取消理由不可为空!'));  
            //     } 
            //     return;
            // }else if(String.isBlank(cancelReasonRemark)){
            //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '取消理由备注不可为空!'));
            //     return;
            // }
            // //20210420 ljh update end
           
            Set<Id> raesIdSet = new Set<Id>();
            Set<Id> mainIdSet = new Set<Id>();
            for(EsdInfo esd: esdList) {
                if(esd.checked) {
                    raesIdSet.add(esd.rec.Rental_Apply_Equipment_Set__c);
                    if(esd.rec.Is_Body__c) {
                        mainIdSet.add(esd.rec.Asset__c);
                    }
                }
            }
            Map<Id, Rental_Apply_Equipment_Set__c> raesMap = new Map<Id, Rental_Apply_Equipment_Set__c>([
                SELECT Id
                     , Cancel_Select__c
                     , Yi_loaner_arranged__c
                FROM Rental_Apply_Equipment_Set__c
                WHERE Id=:raesIdSet
                AND Cancel_Select__c = false
                AND Yi_loaner_arranged__c = 0
                FOR UPDATE
            ]);
 
            List<Rental_Apply_Equipment_Set__c> updateRaesList = new List<Rental_Apply_Equipment_Set__c>();
            for(Id raesId: raesIdSet) {
                if(raesMap.containsKey(raesId)) {
                    updateRaesList.add(new Rental_Apply_Equipment_Set__c(Id=raesId
                        , Cancel_Select__c = true
                        // , Cancel_Reason__c = cancelReason  //20210707 SFDC-C448KZ you
                        // , Loaner_cancel_Remarks__c = cancelReasonRemark));
                        , Cancel_Reason__c = this.parentObj.Cancel_Reason__c==null ? '':this.parentObj.Cancel_Reason__c
                        , Loaner_cancel_reason__c = this.parentObj.Loaner_cancel_reason__c
                        , Loaner_cancel_Remarks__c = this.parentObj.Loaner_cancel_request__c==null? this.parentObj.Loaner_cancel_reason__c :this.parentObj.Loaner_cancel_request__c
                        ));
                }
                else {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, raesId + '一览不可取消'));
                    return;
                }
            }
            if(!updateRaesList.isEmpty()) {
                FixtureUtil.withoutUpdate(updateRaesList);
                List<Rental_Apply_Equipment_Set_Detail__c> raesdList = [
                    SELECT Id
                         , Asset__c
                    FROM Rental_Apply_Equipment_Set_Detail__c
                    WHERE Rental_Apply_Equipment_Set__c IN:raesMap.keySet()
                    AND StockDown__c = true
                    AND Cancel_Select__c = true
                    FOR UPDATE
                ];
                List<Fixture_OneToOne_Link__c> linkList = new List<Fixture_OneToOne_Link__c>([
                    SELECT Id FROM Fixture_OneToOne_Link__c WHERE Main_Asset__c IN:mainIdSet
                ]);
                for(Fixture_OneToOne_Link__c link:linkList) {
                    link.Select_Accessory_Asset_Cnt__c = 0;
                }
                // link里的已分配数清空   
                Oly_TriggerHandler.bypass(AssetHandlerCheck.class.getName());
                FixtureUtil.withoutUpdate(linkList);
                Oly_TriggerHandler.clearBypass(AssetHandlerCheck.class.getName());
 
                init();
                done_flg = true;
            }
            //Database.rollback(sp);
        }
        catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
        }
       // cancelReason = '';
       // cancelReasonRemark = '';
    }
 
    // 日期适用按钮
    public void applyDate() {
        done_flg = false;
        String strMessage = null;
        Boolean hasError = false;
        if (parentObj.Asset_loaner_start_day__c == null) {
            hasError = true;
            strMessage = '请输入[备品预计出货日]';
        }
        if (parentObj.Asset_loaner_start_day__c != null && parentObj.Asset_loaner_start_day__c < Date.today()) {
            hasError = true;
            strMessage = '[备品预计出货日]必须入力从今天开始起的日期 ';
        }
        if (hasError) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, strMessage));
            return;
        }
        else {
            // 给打勾明细所在的一览设备品预计出货日
            Set<Id> raesIdSet = new Set<Id>();
            Boolean hasChecked = false;
            for(EsdInfo esd: esdList) {
                if((esd.checked || raesIdSet.contains(esd.rec.Rental_Apply_Equipment_Set__c))) {
                    hasChecked = true;
                    //20210519 ljh update 1829 start
                    if(esd.tempDetailStatus == '取消' && !esd.rec.Is_Body__c) {
                    //if(esd.tempDetailStatus == '取消') {
                        esd.tempDate = null;
                    }
                    //20210519 ljh update 1829 start
                    //else if(esd.rec.Is_Body__c) {
                    else if(esd.rec.Is_Body__c && esd.tempOldRaesIdSub == null) {
                    //20210519 ljh update 1829 end
                        esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c = parentObj.Asset_loaner_start_day__c;
                        esd.tempDate = parentObj.Asset_loaner_start_day__c;
                        raesIdSet.add(esd.rec.Rental_Apply_Equipment_Set__c);
                    }
                    else {
                        esd.tempDate = parentObj.Asset_loaner_start_day__c;
                    }
                }
                //20210521 ljh add 1829 start
                if(esd.tempOldRaesIdSub != null && raesIdSet.contains(esd.tempOldRaesIdSub)){
                    if(esd.tempDetailStatus == '取消'){
                        esd.tempDate = null;
                    }
                    else {
                        esd.tempDate = parentObj.Asset_loaner_start_day__c;
                    }
                }
                //20210521 ljh add 1829 end 
            }
            if(!hasChecked) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '未选择适用的一览!'));
            }
        }
    }
    private Boolean isRaStatusOK() {
 
        List<String> statusList = System.Label.StatusProcessState.split(',');
 
        //检查是否可以继续
        // 20210809  ljh SFDC-C5HDC7 update start
        List<Rental_Apply__c> RaTarList = [
            SELECT Campaign__c
                 , Repair__c
                 , Campaign__r.Status
                 , Campaign__r.IF_Approved__c
                 , Campaign__r.Meeting_Approved_No__c
                 , Campaign__r.Approved_Status__c    //20220315 sx obpm备品决裁状态相关修改
                 // ,repair__r.Return_Without_Repair_Date__c
                 , Return_Without_Repair_Date_F__c
                 // , Repair__r.Repair_Final_Inspection_Date__c
                 , Repair_Final_Inspection_Date_F__c
                 // , Repair__r.Repair_Shipped_Date__c
                 , RC_return_to_office__c 
                 , demo_purpose2__c //1822 yc 20211025 已购待货目的,新品已有发货日不能出库
                 , Follow_UP_Opp__r.Shipping_Finished_Day_Func__c //1822 yc 20211025 已购待货目的,新品已有发货日不能出库
                 , next_action__c //1822 yc 20211108
                 ,AccDealerBlacklist__c//贸易合规 you
                 ,EquipmentGuaranteeFlg__c//贸易合规 you
                 , QIS_number__r.ReplaceDeliveryDate__c //1822 yc 20211108
              FROM Rental_Apply__c
             WHERE id =:taId
        ];
        for (Rental_Apply__c RaTar : RaTarList) {
            // 20230215 ljh DB202301265636 学会取消申请也拦截 start
            // if( RaTar.Campaign__r.Status == '取消'){
            //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '学会已取消,不能继续操作了'));
             //贸易合规 you
            if(System.Label.TradeComplianceStatusFlagBP =='true' && RaTar.AccDealerBlacklist__c == '1' && RaTar.EquipmentGuaranteeFlg__c==false){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, System.Label.IFTradeComplianceAlertBP));
                return false; 
            }else if( RaTar.Campaign__r.Status == '取消' || RaTar.Campaign__r.Status == '取消申请中' ){
                String tempS = '';
                if(RaTar.Campaign__r.Status == '取消'){
                    tempS = '已取消';
                }else{
                    tempS = '申请取消中';
                }
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '学会'+tempS+',不能继续操作了'));
            // 20230215 ljh DB202301265636 学会取消申请也拦截 end
                return false;
            }
            // else if(RaTar.Repair__r.Repair_Final_Inspection_Date__c != null){
            else if(RaTar.repair__c!=null && RaTar.Repair_Final_Inspection_Date_F__c != null ){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '存在修理最终检测日,不能继续了'));
                return false;
            }
            // else if(RaTar.repair__r.Return_Without_Repair_Date__c != null && RaTar.repair__c!=null ){
            else if(RaTar.repair__c!=null && RaTar.Return_Without_Repair_Date_F__c != null){    
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '未修理归还日不为空,不能出库'));
                return false;
            }
            // else if(RaTar.Repair__r.Repair_Shipped_Date__c != null ){
            else if(RaTar.repair__c!=null && RaTar.RC_return_to_office__c != null){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '存在RC修理返送日,不能继续了'));
                return false;
            }
            // 20210809  ljh SFDC-C5HDC7 update end
            //1822 yc 20211025 已购待货目的,新品已有发货日不能出库 start
            else if(RaTar.demo_purpose2__c=='已购待货' && RaTar.Follow_UP_Opp__r.Shipping_Finished_Day_Func__c!= null){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '已购待货目的,新品已有发货日,不能继续了'));
                return false;
            }
            //1822 yc 20211025 已购待货目的,新品已有发货日不能出库 end
            //1822 yc 20211108 start
            else if(RaTar.demo_purpose2__c=='索赔QIS' && RaTar.next_action__c=='无偿更换' && RaTar.QIS_number__r.ReplaceDeliveryDate__c!= null){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '索赔QIS目的,QIS已有新品发货日,不能继续了'));
                return false;
            }//1822 yc 20211108 end
            //20220225 sx start obpm 办事处增加判断:是否申请决裁勾着没有决裁编号不能进行操作
            else if(RaTar.Campaign__c != null && RaTar.Campaign__r.IF_Approved__c && RaTar.Campaign__r.Meeting_Approved_No__c == null){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, '已申请决裁但决裁编码为空'));
                return false;
            }
            //20220225 sx end obpm 办事处增加判断:是否申请决裁勾着没有决裁编号不能进行操作
            //20220315 sx  obpm备品决裁状态相关修改 add start
            else if(RaTar.Campaign__c != null && RaTar.Campaign__r.IF_Approved__c && RaTar.Campaign__r.Meeting_Approved_No__c != null && statusList.contains(RaTar.Campaign__r.Approved_Status__c)){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, '已申请决裁但决裁状态不符合条件'));
                return false;
            }
            //20220315 sx  obpm备品决裁状态相关修改 add end
        }
        return true;
    }
    /**
    @description 分配按钮
    */
    public void assign() {
        done_flg = false;
        if(!isRaStatusOK()) {
            return;
        }
        Savepoint sp = Database.setSavepoint();
        try {
            Map<Id, Rental_Apply_Equipment_Set_Detail__c> raesdMap = getDetailsMap(); // 取最新的明细数据
            Map<Id, Rental_Apply_Equipment_Set__c> updateRaesMap = new Map<Id, Rental_Apply_Equipment_Set__c>(); // 用于更新一览的预计货日
            List<Rental_Apply_Equipment_Set_Detail__c> updateRaesdList = new List<Rental_Apply_Equipment_Set_Detail__c>(); // 更新明细
            List<Rental_Apply_Equipment_Set_Detail__c> cancelRaesdList = new List<Rental_Apply_Equipment_Set_Detail__c>(); // 更新取消的明细
            List<Rental_Apply_Equipment_Set_Detail__c> insertRaesdList = new List<Rental_Apply_Equipment_Set_Detail__c>(); // 追加明细
            Map<Id, Rental_Apply_Equipment_Set_Detail__c> deleteRaesdMap = new Map<Id, Rental_Apply_Equipment_Set_Detail__c>(); // 删除因重新分配而取消的明细
            List<Rental_Apply_Equipment_Set__c>  deleteRaesList = new List<Rental_Apply_Equipment_Set__c>(); //20210521 ljh add 1829 删除分配替代品中间的生成的一览
            Map<Id,Rental_Apply_Equipment_Set__c>  updateRaesMap1 = new Map<Id,Rental_Apply_Equipment_Set__c>(); //20210523 ljh add 1829 更新替代分配一览
            Rental_Apply__c updateRa = null;
 
            Set<String> oldLinkIdSet = new Set<String> (); // 换分配或删明细时旧的link已分配数量要清0
            Set<Id> raesIdSet = new Set<Id>();
            Set<Id> raesIdSetCheck = new Set<Id>(); //20210601 ljh add 1829
            Set<Id> raesIdSubSet = new Set<Id>(); //20210520 ljh add 1829
            Set<Id> mainIds = new Set<Id>(); // 主体Id集合,用于检查是否有重复分配
 
            Datetime now = System.now();
            Id userId =  Userinfo.getUserId();
            Set<Id> assIdSet = new Set<Id>();
            Boolean hasChecked = false;
            //20210518 ljh add 1829 start
            Map<Id, Id> mapOnId = new Map<Id, Id>();
            List<Rental_Apply_Equipment_Set__c> getReasListAll = getReas(true,null);//获取所有一览
            Map<Id, Rental_Apply_Equipment_Set__c> getReasMap = getReasMap(false);//未取消的一览
            Map<String,Integer> fsIndexMap =  new Map<String,Integer>();
            for(Rental_Apply_Equipment_Set__c reas:getReasListAll){
                if(fsIndexMap.containsKey(reas.Loaner_code_F__c)){
                    if(Integer.valueOf(reas.IndexFromUniqueKey__c) > fsIndexMap.get(reas.Loaner_code_F__c) ){
                        fsIndexMap.put(reas.Loaner_code_F__c,Integer.valueOf(reas.IndexFromUniqueKey__c));
                    }
                }else{
                    fsIndexMap.put(reas.Loaner_code_F__c,Integer.valueOf(reas.IndexFromUniqueKey__c));
                }
                
            }
            //遍历数据 新增的一览和明细
            Map<String,Date> RentalStartDateMap = new Map<String,Date>();
            for(EsdInfo esd: esdList) {
                if(esd.checked || raesIdSetCheck.contains(esd.rec.Rental_Apply_Equipment_Set__c)){
                    Rental_Apply_Equipment_Set_Detail__c raesd = raesdMap.get(esd.rec.Id);
                    if (esd.checked && esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c == null) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '请输入[备品预计出货日]'));
                        return;
                    }
                    if (esd.checked && esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c != null && esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c < Date.today()) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '[备品预计出货日]必须入力从今天开始起的日期'));
                        return;
                    }
                    if(esd.rec.Is_Body__c && esd.rec.Asset__c == null && !esd.SubChecked) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, esd.rec.Fixture_Model_No__c + '未分配,无法保存!'));
                        return;
                    }
                    if(raesd != null && raesd.LastModifiedDate != esd.rec.LastModifiedDate) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, raesd.Fixture_Model_No__c + '后台数据被' + raesd.LastModifiedBy.Name + '修改,请刷新画面!'));
                        return;
                    }
                    if(esd.checked && esd.SubChecked){
                        if(!IsCanSubReas(esd.rec.Rental_Apply_Equipment_Set__c)) return;//验证是否可分配替代品 已有两处限制1.初始化class中 2.扫描的时候 若101可注释此行代码
                        raesIdSubSet.add(esd.rec.Rental_Apply_Equipment_Set__c);
                    }
                    if(esd.rec.Is_Body__c) { 
                        raesIdSetCheck.add(esd.rec.Rental_Apply_Equipment_Set__c);
                    }
                    RentalStartDateMap.put(esd.rec.Rental_Apply_Equipment_Set__c,esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c);
                }                     
            }
            // 20210906 ljh SFDC-C568C4 update start
            List<Rental_Apply_Equipment_Set__c> raesNUList = new List<Rental_Apply_Equipment_Set__c>();
            Set<Id> nRAEId = new Set<Id>();
            for(EsdInfo esd: esdList) {
                if(mainIds.contains(esd.rec.Asset__c)) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, esd.tempSerial + '不可被同时分配给多个配套一览!'));
                    return;
                }
                if(esd.rec.Is_Body__c && esd.rec.Asset__c != null) {
                    mainIds.add(esd.rec.Asset__c);
                    if(raesIdSubSet.contains(esd.tempOldRaesIdSub)){
                        if(esd.tempOldRaesIdSub != null && getReasMap.get(esd.tempOldRaesIdSub) != null){
                            Rental_Apply_Equipment_Set__c craes = getReasMap.get(esd.tempOldRaesIdSub);//原一览
                            Rental_Apply_Equipment_Set__c robj = new Rental_Apply_Equipment_Set__c(); //替换生成的新的一览
                            robj = craes.clone();
                            // 4.新增一條相同的“借出備品配套一覽”記錄----clone一条新记录(直接修改分配替代品页面选中的那条记录,然后插入数据库)
                            robj.Old_RetalFSetDetail_Cnt__c = craes.canDelete__c?craes.Old_RetalFSetDetail_Cnt__c:craes.RetalFSetDetail_Cnt__c; // 原配套明细数
                            // 防止clone时与申请单内已有备品配套UK重复
                            // 20210914 ljh SFDC-C568C4 update
                            if(fsIndexMap.containsKey(esd.tempModel)){
                                robj.IndexFromUniqueKey__c = fsIndexMap.get(esd.tempModel)+1;
                                Integer tempIndex = fsIndexMap.get(esd.tempModel)+1;
                                fsIndexMap.put(esd.tempModel,tempIndex);
                            }else{
                                robj.IndexFromUniqueKey__c = 1;
                            }
                            // 20210914 ljh SFDC-C568C4 update
                            // 20210914 ljh SFDC-C568C4 add start
                            if(!fsIndexMap.containsKey(esd.tempModel)){
                                fsIndexMap.put(esd.tempModel, 1);
                            }
                            // 20210914 ljh SFDC-C568C4 add end
                            //robj.Groupby_SortInt__c = craes.Groupby_SortInt__c;
                            robj.Irreplaceable_flag__c = false;    // 代替品不可
                            robj.Same_Accessory_flag__c = false;   // 同一附属品
                            robj.Substitute_flag__c = true;        // 代替品Flag勾选
                            robj.Fixture_Set__c = esd.tempFixtureSet; //保有设备
                            robj.Cancel_Select__c = false; 
                            robj.Cancel_Reason__c = '';
                            robj.Rental_Start_Date__c = RentalStartDateMap.containsKey(esd.tempOldRaesIdSub)?RentalStartDateMap.get(esd.tempOldRaesIdSub):craes.Rental_Start_Date__c ;
                            robj.Rental_End_Date__c = setRentalEndDate(robj.Rental_Start_Date__c, parentObj);
 
                            //robj.Rental_End_Date__c  = robj.Rental_Start_Date__c + Integer.valueOf(craes.Test_Day__c);
                            // 新记录 Canceled__c & Canceled_Id__c 为选中一览的Id
                            robj.Canceled__c = craes.canDelete__c?craes.Canceled__c:craes.Id;
                            robj.Canceled_Id__c = craes.canDelete__c?robj.Canceled_Id__c:craes.Id;
                            if(!craes.canDelete__c){
                                craes.Cancel_Select__c = true; 
                                craes.Cancel_Reason__c = '分配代替品';
                                // 20210906 ljh SFDC-C6D9C2 add start
                                craes.Rental_Start_Date__c = null;
                                craes.Rental_End_Date__c = null;
                                // 20210906 ljh SFDC-C6D9C2 add end
                                robj.canDelete__c = true;
                                raesNUList.add(craes);
                                raesNUList.add(robj);
                                // FixtureUtil.withoutUpsertObjects(new Rental_Apply_Equipment_Set__c[]{craes,robj});
                                // 原一览关联clone出来的新一览
                                nRAEId.add(craes.Id);
                                // craes.New_Rental_Apply_Equipment__c = robj.Id;
                                //FixtureUtil.withoutUpsertObjects(new Rental_Apply_Equipment_Set__c[]{craes});
                            }else{
                                robj.canDelete__c = true;
                                raesNUList.add(robj);
                                // FixtureUtil.withoutUpsertObjects(new Rental_Apply_Equipment_Set__c[]{robj});
                                // 原一览关联clone出来的新一览
                                nRAEId.add(craes.Canceled__c);
                                // Rental_Apply_Equipment_Set__c oldCraes = new Rental_Apply_Equipment_Set__c();
                                // oldCraes.Id = craes.Canceled__c;
                                // oldCraes.New_Rental_Apply_Equipment__c = robj.Id;
                                //FixtureUtil.withoutUpsertObjects(new Rental_Apply_Equipment_Set__c[]{oldCraes}); 
                                deleteRaesList.add(craes);
                            }
                            // mapOnId.put(esd.tempOldRaesIdSub,robj.Id);   
                        }
                    }
                }
            } 
            FixtureUtil.withoutUpsertObjects(raesNUList);
            // 原一览关联clone出来的新一览
            List<Rental_Apply_Equipment_Set__c> nRAEList = new List<Rental_Apply_Equipment_Set__c>(); 
            Map<Id,List<Id>> tempMap = new Map<Id,List<Id>>();
            List<Id> IdList = new List<Id>();
            Map<Id,Rental_Apply_Equipment_Set__c> cancelidMap = new Map<Id,Rental_Apply_Equipment_Set__c>();
            for(Rental_Apply_Equipment_Set__c raeT:[Select Id,Canceled__c,Canceled__r.First_RAESD__r.Queue_Time_Text__c,Canceled__r.First_RAESD__r.Queue_Day_Text__c From Rental_Apply_Equipment_Set__c WHERE Canceled__c IN :nRAEId order by CreatedDate desc]){
                if(tempMap.containsKey(raeT.Canceled__c)){
                    IdList = tempMap.get(raeT.Canceled__c);
                    IdList.add(raeT.Id);
                    tempMap.put(raeT.Canceled__c,IdList);
                }else{
                    IdList = new List<Id>();
                    IdList.add(raeT.Id);
                    tempMap.put(raeT.Canceled__c,IdList);
                    cancelidMap.put(raeT.Id,raeT); //新一览id和新一览数据  //20210914 you SFDC-C6E3WQ 
                }                
            }
            system.debug('===='+cancelidMap);
            for(Id key:tempMap.keySet()){
                Rental_Apply_Equipment_Set__c tempRae = new Rental_Apply_Equipment_Set__c();
                tempRae.Id = key;
                tempRae.New_Rental_Apply_Equipment__c = tempMap.get(key)[0];
 
                nRAEList.add(tempRae);
                if(tempMap.get(key).size() == 2){
                    mapOnId.put(tempMap.get(key)[1],tempMap.get(key)[0]);
                }else{
                    mapOnId.put(key,tempMap.get(key)[0]);
                }
            }
            FixtureUtil.withoutUpsertObjects(nRAEList);
            // System.debug('zheli:'+mapOnId);
            // 20210906 ljh SFDC-C568C4 update end
            //重新构造esdlist  原一览关联clone出来的新一览
            for(Integer i = 0; i < esdList.size(); i++) {
                EsdInfo esd4 = esdList[i];
                //分配替代品new 关联reasId
                if(esd4.tempOldRaesIdSub != null && mapOnId.containsKey(esd4.tempOldRaesIdSub) && getReasMap.containsKey(esd4.tempOldRaesIdSub)){
                    esd4.rec.Rental_Apply_Equipment_Set__c = mapOnId.get(esd4.tempOldRaesIdSub);
                    if(esd4.rec.Is_Body__c){
                        esd4.checked = true;
                    }
                    esd4.tempDate = RentalStartDateMap.get(esd4.tempOldRaesIdSub);
                }
            }
            //20210518 ljh add 1829 end
            for(EsdInfo esd: esdList) {
                // if(esd.rec.Is_Body__c){
                //     System.debug('zheli00:'+esd.checked);
                // }
                //20210518 ljh update 1829 start
                /*
                if(mainIds.contains(esd.rec.Asset__c)) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, esd.tempSerial + '不可被同时分配给多个配套一览!'));
                    return;
                }
                if(esd.rec.Is_Body__c && esd.rec.Asset__c != null) {
                    mainIds.add(esd.rec.Asset__c);
                }*/
                //20210518 ljh update 1829 end
                if(esd.checked || raesIdSet.contains(esd.rec.Rental_Apply_Equipment_Set__c)) {
                    //20210523 ljh update 1829 start
                    // if(esd.rec.Is_Body__c && esd.rec.Asset__c == null && !esd.SubChecked) {
                    //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, esd.rec.Fixture_Model_No__c + '未分配,无法保存!'));
                    //     return;
                    // }
                    //20210523 ljh update 1829 end
                    hasChecked = true;
                    if(!raesdMap.containsKey(esd.rec.Id)) {
                        //20210518 ljh update 1829 start
                        //if(esd.tempStatus == '追加') {
                        if(esd.tempStatus == '追加' || esd.tempOldRaesIdSub != null) {
                        //20210518 ljh update 1829 end
                            esd.rec.Id = null;
                            esd.rec.Select_Time__c = now;
                            if(esd.tempOldRaesIdSub != null && esd.tempStatus == '取消'){
                                //替代扫描的做临时取消
                                esd.rec.AgencyTempCancel__c = true;
                                esd.rec.AgencyTempCancelTime__c = now;
                                esd.rec.Select_Time__c = null;
                            }
                            insertRaesdList.add(esd.rec);
                        }
                        //20210518 ljh update 添加if 1829 start
                        // 不continue的情况  1.本次替代扫描(esd.tempOldRaesIdSub != null)&esd.tempStatus != '取消'
                        if( esd.tempOldRaesIdSub == null || esd.tempStatus == '取消'){
                            continue;
                        }
                        //20210518 ljh update 添加if 1829 end    
                    }    
                    Rental_Apply_Equipment_Set_Detail__c raesd = raesdMap.get(esd.rec.Id);
                    //20210519  ljh 1829 update start
                    // if(raesd.LastModifiedDate != esd.rec.LastModifiedDate) {
                    //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, raesd.Fixture_Model_No__c + '后台数据被' + raesd.LastModifiedBy.Name + '修改,请刷新画面!'));
                    //     return;
                    // }
                    // 与后台数据做比较,防止重复更新  //20210519  ljh 1829 update 下面的If 增加 raesd != null &&
                    if(esd.rec.Asset__c != null) {
                        //20210523 ljh add 1829 start
                        //一对一还是需要在这里更新
                        //system.debug('zheli000:'+esd.tempStatus+'~'+esd.tempModel+'~'+esd.SubChecked+'~'+oldLinkIdSet);
                        if(esd.SubChecked && esd.tempStatus == '取消' && raesd != null && raesd.Fixture_OneToOne_Link_Id__c != null){
                            oldLinkIdSet.add(raesd.Fixture_OneToOne_Link_Id__c);
                        }
                        //20210523 ljh add 1829 end
                        if(raesd != null && !esd.SubChecked && //20210523 ljh 条件 add 1829
                        (raesd.Asset__c != esd.rec.Asset__c // 保有设备变化
                            || raesd.Fixture_OneToOne_Link_Id__c != esd.rec.Fixture_OneToOne_Link_Id__c)) { // link变化
                            // 换link时旧link里的已分配数在明细更新时清掉
                            oldLinkIdSet.add(raesd.Fixture_OneToOne_Link_Id__c);
                            assIdSet.add(esd.rec.Asset__c); //20210523 ljh 1829 看代码没用到
                            assIdSet.add(raesd.Asset__c); //20210523 ljh 1829 看代码没用到
 
                            esd.rec.Select_Time__c = now;
                            if(raesd.StockDown__c) {
                                // 下架后重新分配
                                /*raesd.Cancel_Select__c = true;
                                raesd.Cancel_Reason__c = '重新分配';
                                cancelRaesdList.add(raesd);
 
                                // 用画面上显示的造明细
                                esd.rec.Id = null;
                                esd.rec.StockDown__c = false;
                                esd.rec.Fixture_Model_No_text__c      = raesd.FSD_Fixture_Model_No__c;
                                esd.rec.Fixture_Name_text__c          = raesd.FSD_Name_CHN__c;
                                esd.rec.Canceled__c                   = raesd.Id;
                                esd.rec.FSD_Is_Optional__c            = raesd.FSD_Is_Optional_F__c;
                                esd.rec.FSD_Is_OneToOne__c            = raesd.FSD_Is_OneToOne_F__c;
                                esd.rec.FSD_OneToOneAccessory_Cnt__c  = raesd.FSD_OneToOneAccessory_Cnt_F__c;
                                esd.rec.Rental_Num__c                 = raesd.Rental_Num__c;
                                esd.rec.LastModifiedDate              = null;//20210522 ljh add 1829
                                esd.rec.LastModifiedById              = null;//20210522 ljh add 1829
                                insertRaesdList.add(esd.rec);*/
                                /**
                                20210916 ljh 现在没有下架操作,分配后发货,点击发货按钮的时候更新下架,
                                所以不存在下架后重新分配 为了覆盖率注释代码
                                */ 
                            }
                            else {
                                updateRaesdList.add(esd.rec);
                            }
                        }
                    }
                    else { // 画面上取消,后台做临时取消
                        //20210523 ljh add  if 1829 end
                        //system.debug('zheli001:'+esd.tempModel+'~'+esd.SubChecked+'~'+raesd.Fixture_OneToOne_Link_Id__c);
                        if(raesd.Fixture_OneToOne_Link_Id__c != null){
                            oldLinkIdSet.add(raesd.Fixture_OneToOne_Link_Id__c); 
                        }
                        //20210523 ljh add  if 1829 end
                        if(!raesd.StockDown__c) {
                            // 针对从link追加出来的明细,未下架时取消直接删除
                            if(raesd.AgencyAssignAdd__c) {
                                deleteRaesdMap.put(raesd.Id, raesd);
                            }
                            else if(esd.tempOldRaesIdSub == null && !esd.SubChecked){ //20210523 add if 1829 
                                // 本来申请的做临时取消
                                esd.rec.AgencyTempCancel__c = true;
                                esd.rec.AgencyTempCancelTime__c = now;
                                updateRaesdList.add(esd.rec);
                            }
                        }
                        else if(esd.tempOldRaesIdSub == null && !esd.SubChecked){ //20210523 add if 1829 
                            raesd.Cancel_Select__c = true;
                            raesd.Cancel_Reason__c = '重新分配';
                            cancelRaesdList.add(raesd);
                        }
                    }
                    if(esd.rec.Is_Body__c) { 
                        raesIdSet.add(esd.rec.Rental_Apply_Equipment_Set__c);
                        //20210519 ljh update ljh 1829 start  增加条件 esd.tempOldRaesIdSub == null  !esd.SubChecked
                        //if(esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c != raesd.Rental_Start_Date__c) {
                        if(!esd.SubChecked &&
                            (   raesd == null ||
                                (raesd != null && esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c != raesd.Rental_Start_Date__c)
                            )
                        ) { 
                            if (esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c == null && esd.tempOldRaesIdSub == null) {
                                
                                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '请输入[备品预计出货日]'));
                                return;
                            }
                            if (esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c != null && esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c < Date.today() && esd.tempOldRaesIdSub == null) {
                                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '[备品预计出货日]必须入力从今天开始起的日期'));
                                return;
                            }
                        //20210519 ljh update ljh 1829 end 
                            //20210430 ljh XLII-C2F3AN start
                            //if(esd.tempDate == null) {
                            if(esd.tempOldRaesIdSub == null) { //20210520 ljh 1829 add 
                                esd.tempDate = esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c;
                            }
                            //}
                            //20210430 ljh XLII-C2F3AN end
                            Date endDay = esd.tempDate;
                            //system.debug('zheli000:'+esd.tempDate+'~'+parentObj.Hope_Lonaer_date_Num__c);
                            switch on parentObj.demo_purpose2__c{
                                when '试用(无询价)','试用(有询价)','新产品评价','其他','协议借用' {
                                    endDay = esd.tempDate + intValueOf(parentObj.Hope_Lonaer_date_Num__c);
                                }
                                when '一般用户','保修用户','市场多年保修','再修理','索赔QIS','已购待货','故障排查' {
                                    endDay = esd.tempDate + 30;
                                }
                                when '学会展会' {
                                    endDay = parentObj.Campaign_EndDate_F__c + 5;
                                }
                            }
                            //esd.tempDate = esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c;
                            updateRaesMap.put(esd.rec.Rental_Apply_Equipment_Set__c,
                                                new Rental_Apply_Equipment_Set__c(
                                                    Id = esd.rec.Rental_Apply_Equipment_Set__c
                                                  , Rental_Start_Date__c = esd.tempDate
                                                  , Rental_End_Date__c = endDay));
                            if(updateRa == null) {
                                updateRa = new Rental_Apply__c(Id=parentObj.Id
                                    , Asset_loaner_start_day__c=esd.tempDate
                                    , Asset_loaner_closed_day__c=endDay
                                );
                            }
                            else {
                                if(esd.tempDate > updateRa.Asset_loaner_start_day__c) {
                                    updateRa.Asset_loaner_start_day__c = esd.tempDate;
                                }
                                if(endDay > updateRa.Asset_loaner_closed_day__c) {
                                    updateRa.Asset_loaner_closed_day__c = endDay;
                                }
                            }
                        }   
                    }
                    //对于分配替代之后下架在分配 把可删除标记 false 20210527 ljh 1829 start
                    if(esd.tempOldRaesIdSub == null && !esd.SubChecked){
                        Rental_Apply_Equipment_Set__c oldUpdateCraes = new Rental_Apply_Equipment_Set__c();
                        oldUpdateCraes.Id = esd.rec.Rental_Apply_Equipment_Set__c;
                        oldUpdateCraes.canDelete__c = false;
                        updateRaesMap1.put(esd.rec.Rental_Apply_Equipment_Set__c,oldUpdateCraes);
                    }
                    //20210527 ljh 1829 end
                }
            }
            if(!hasChecked) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '请勾选后再分配!'));
                return;
            }
            Boolean needReset = false;
            // 必须先更新一览的预计出货日,否则明细分配不上
            if(!updateRaesMap.isEmpty()) {
                //print('更新一览', updateRaesMap);
                FixtureUtil.withoutUpdate(updateRaesMap.values());
                if(updateRa != null) {
                    List<Rental_Apply__c> raList = [
                        SELECT Id
                          , Asset_loaner_start_day__c
                          , Asset_loaner_closed_day__c
                        FROM Rental_Apply__c
                        WHERE Id=:parentObj.Id
                    ];
                    if(!raList.isEmpty()
                        && (raList[0].Asset_loaner_start_day__c == null
                            || raList[0].Asset_loaner_closed_day__c == null)) {
                        FixtureUtil.withoutUpdate(new List<Rental_Apply__c> {updateRa});
                    }
                }
                updateRaesMap.clear();
                updateRa = null;
                needReset = true;
            }
            Map<Id, Fixture_OneToOne_Link__c> updateLinkMap = new Map<Id, Fixture_OneToOne_Link__c>();
            // 旧link清0
            //system.debug('更新link00:'+oldLinkIdSet);
            if(!oldLinkIdSet.isEmpty()) {
                for(String linkId:oldLinkIdSet) {
                    if(String.isBlank(linkId)){
                        continue;
                    }
                    updateLinkMap.put(linkId, new Fixture_OneToOne_Link__c(Id=linkId, Select_Accessory_Asset_Cnt__c=0));
                }
            }
            List<Asset> assList = [SELECT Id FROM Asset WHERE Id IN:assIdSet FOR UPDATE];
            Oly_TriggerHandler.bypass(AssetHandlerCheck.class.getName());
            // 删除明细
            if(!deleteRaesdMap.isEmpty()) {
                //print('删除明细', deleteRaesdMap);
                FixtureUtil.withoutDelete(deleteRaesdMap.values());
                needReset = true;
            }
            if(!cancelRaesdList.isEmpty()) {
                updateRaesdList.addAll(cancelRaesdList);
                //FixtureUtil.withoutUpdate(cancelRaesdList);
            }
            //20210522 ljh add 1829 start
            if(updateRaesMap1.size() > 0){
                //更新删除验证标识
                FixtureUtil.withoutUpdate(updateRaesMap1.values());
            }
            //20210522 ljh add 1829 end
            // 更新现有明细
            if(!updateRaesdList.isEmpty()) {
                for(Rental_Apply_Equipment_Set_Detail__c raesd: updateRaesdList) {
                    String linkId = raesd.Fixture_OneToOne_Link_Id__c;
                    if(String.isBlank(linkId)){
                        continue;
                    }
                    Fixture_OneToOne_Link__c link;
                    // link分配数量占用
                    if(updateLinkMap.containsKey(linkId)) {
                        link = updateLinkMap.get(linkId);
                    }
                    else {
                        link = new Fixture_OneToOne_Link__c(Id = linkId, Select_Accessory_Asset_Cnt__c = 0);
                    }
                    link.Select_Accessory_Asset_Cnt__c += 1;
                    updateLinkMap.put(linkId, link);
                }
                //print('更新明细', updateRaesdList);
                FixtureUtil.withoutUpsertObjects(updateRaesdList);
                needReset = true;
            }
            // 插入后设置一览的第一条明细,并在最后更新
            List<Rental_Apply_Equipment_Set_Detail__c> rupsobjList =new List<Rental_Apply_Equipment_Set_Detail__c>();//20210914 you SFDC-C6E3WQ
                
            // 插入新追加的明细
            if(!insertRaesdList.isEmpty()) {
                for(Rental_Apply_Equipment_Set_Detail__c raesd: insertRaesdList) {
                    String linkId = raesd.Fixture_OneToOne_Link_Id__c;
                    if(String.isBlank(linkId)){
                        continue;
                    }
                    Fixture_OneToOne_Link__c link;
                    // link分配数量占用
                    if(updateLinkMap.containsKey(linkId)) {
                        link = updateLinkMap.get(linkId);
                    }
                    else {
                        link = new Fixture_OneToOne_Link__c(Id = linkId, Select_Accessory_Asset_Cnt__c = 0);
                    }
                    link.Select_Accessory_Asset_Cnt__c += 1;
                    updateLinkMap.put(linkId, link);
                }
                //print('新建明细', insertRaesdList);
                FixtureUtil.withoutUpsertObjects(insertRaesdList);
                for(Rental_Apply_Equipment_Set_Detail__c raesd: insertRaesdList) {
                    if(raesd.Is_Body__c) {
                        Id raesId = raesd.Rental_Apply_Equipment_Set__c;
                        //20210914 you SFDC-C6E3WQ start
                        system.debug('20210914=='+raesId);
                        if(cancelidMap.containsKey(raesId)){
                           raesd.Queue_Time_Text__c = cancelidMap.get(raesId).Canceled__r.First_RAESD__r.Queue_Time_Text__c;
                           raesd.Queue_Day_Text__c = cancelidMap.get(raesId).Canceled__r.First_RAESD__r.Queue_Day_Text__c;
                        }
                        rupsobjList.add(raesd);
                        //20210914 you SFDC-C6E3WQ end
                        updateRaesMap.put(raesId, new Rental_Apply_Equipment_Set__c(Id=raesId, First_RAESD__c=raesd.Id));
                    }
                }
                needReset = true;
            }
            if(!updateLinkMap.isEmpty()) {
                //print('更新link', updateLinkMap);
                FixtureUtil.withoutUpdate(updateLinkMap.values());
                needReset = true;
            }
            // 一览的第一条明细必须待新明细插入后才能设
            if(!updateRaesMap.isEmpty()) {
                //print('更新一览', updateRaesMap);
                FixtureUtil.withoutUpdate(updateRaesMap.values());
                needReset = true;
            }
            // Upsert 
            FixtureUtil.withoutUpsertObjects(rupsobjList);//20210914 you SFDC-C6E3WQ
            //20210522 ljh add 1829 start
            if(deleteRaesList.size() > 0){
                //删除中间替代
                //先删除一览明细,在删除一览吧~为了释放内存~
                FixtureUtil.withoutDelete(getDetails(deleteRaesList));
                FixtureUtil.withoutDelete(deleteRaesList);
                needReset = true;
            }
            Oly_TriggerHandler.clearBypass(AssetHandlerCheck.class.getName());
            //20210522 ljh add 1829 end
            if(needReset) {
                init();
                done_flg = true;
            }
            //Database.rollback(sp);
        }
        catch (Exception ex) {
            system.debug('=====' + ex.getMessage()+ex.getStackTraceString());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
            done_flg = false;
        }
    }
    //// 调试用
    //private void print(String title, Map<Id, Object> m) {
    //    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, title));
    //    for(Id a:m.keyset()) {
    //        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '' + m.get(a)));
    //    }
    //}
    //// 调试用
    //private void print(String title, List<Object> l) {
    //    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, title));
    //    for(Object o:l) {
    //        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info, '' + o));
    //    }
    //}
    /**
    @description 根据主体型号和打勾情况,找出要分配的一览,返回一览的第一条明细和最后一条明细的下标+1
    @param linkList 主体连着的所有一对一link
    @return 最匹配的一览Id
    */
    private Id getBestRaesId(Asset mainAsset, List<Fixture_OneToOne_Link__c> linkList) {
        Id bestRaesId = null;
        // 一览Id->一览下的明细
        Map<Id,List<EsdInfo>> detailsMap = new Map<Id, List<EsdInfo>>();
        // 有勾选的
        for(EsdInfo esd:esdList) {
            Id raesId = esd.rec.Rental_Apply_Equipment_Set__c;
            if(esd.checked || detailsMap.containsKey(esd.rec.Rental_Apply_Equipment_Set__c)) {
                List<EsdInfo> tempList = new List<EsdInfo>();
                if(detailsMap.containsKey(raesId)) {
                    tempList = detailsMap.get(raesId);
                }
                tempList.add(esd);
                detailsMap.put(raesId, tempList);
            }
        }
        if(!detailsMap.isEmpty()) {
            Integer minDis = null;
            for(Id raesId: detailsMap.keySet()) {
                Integer distance = getRaesMatchingDistance(detailsMap.get(raesId), mainAsset.Fixture_Model_No_F__c, linkList) ;
                if(distance == null) {
                    // 只要有型号不符合就停止
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '分配的主体型号与当前勾选的申请型号不符'));
                    return null;
                }
                else if(minDis == null || distance < minDis) {
                    bestRaesId = raesId;
                    minDis = distance;
                }
            }
        }
        // 没有勾选的
        else {
            for(EsdInfo esd:esdList) {
                // 扫出的主体如果已被分配给一览,直接返回
                if(esd.rec.Asset__c == mainAsset.Id) {
                    return esd.rec.Rental_Apply_Equipment_Set__c;
                }
                // 扫出的主体还没被分配给画面上的任何一览,则跳过已分配的,给还没分配的配套做匹配
                if(esd.rec.Asset__c != null || esd.rec.AgencyTempCancel__c || esd.tempStatus == '取消') {
                    continue;
                }
                Id raesId = esd.rec.Rental_Apply_Equipment_Set__c;
                List<EsdInfo> tempList = new List<EsdInfo>();
                if(detailsMap.containsKey(raesId)) {
                    tempList = detailsMap.get(raesId);
                }
                tempList.add(esd);
                detailsMap.put(raesId, tempList);
            }
            Integer minDis = null;
            for(Id raesId: detailsMap.keySet()) {
                Integer distance = getRaesMatchingDistance(detailsMap.get(raesId), mainAsset.Fixture_Model_No_F__c, linkList) ;
                if(distance != null && (minDis == null || distance < minDis)) {
                    bestRaesId = raesId;
                    minDis = distance;
                }
            }
            if(bestRaesId == null) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有匹配的一览'));
            }
        }
        return bestRaesId;
    }
 
    /**
    @description 计算每个一览和主体所带的link的匹配程度
    @param details 一览内的明细
    @param mainModel 主体型号
    @param linkList 主体下的link
    @return 配套与link之间的差异数,null表示无穷大
    */
    private Integer getRaesMatchingDistance (List<EsdInfo> details, String mainModel, List<Fixture_OneToOne_Link__c> linkList) {
        Map<String, Integer> modelCountMap = new Map<String, Integer>();
        for(EsdInfo esd : details) {
            if(esd.rec.Is_Body__c) {
                if(mainModel != esd.tempModel) {
                    return null;
                }
            }
            else {
                Integer cnt = 0;
                if(modelCountMap.containsKey(esd.tempModel)) {
                    cnt = modelCountMap.get(esd.tempModel);
                }
                modelCountMap.put(esd.tempModel, cnt + 1);
            }
        }
        Integer distance = 0;
        for(Fixture_OneToOne_Link__c link: linkList) {
            if(modelCountMap.containsKey(link.Accessory_Asset__r.Fixture_Model_No_F__c)) {
                distance += Math.abs(intValueOf(link.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c) - modelCountMap.get(link.Accessory_Asset__r.Fixture_Model_No_F__c));
                modelCountMap.remove(link.Accessory_Asset__r.Fixture_Model_No_F__c);
            }
            else {
                distance += intValueOf(link.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c);
            }
        }
        for(String model: modelCountMap.keySet()) {
            distance += modelCountMap.get(model);
        }
        return distance;
    }
    /**
    @description 将一览的画面信息恢复到扫码匹配之前
    @param raesId 一览Id
    */
    private void clearRaesd(Id raesId) {
        Integer i = esdList.size()-1;
        while(i >= 0) {
            EsdInfo esd = esdList[i];
            if(esd.rec.Rental_Apply_Equipment_Set__c == raesId) {
                if(esd.rec.Id == null) {
                    esdList.remove(i);
                }
                else {
                    esd.tempLocation = '';
                    esd.tempKey = '';
                    esd.tempSerial = '';
                    esd.tempEquipmentType = '';// 备品分类 //20210510 ljh add 1672
                    esd.tempOldRaesIdSub = null; //20210520 ljh add 1829
                    esd.SubChecked = false; //20210520 ljh add 1829
                    esd.tempFixtureSet = null; //20210520 ljh add 1829
                    esd.tempStatus  = ''; //20210520 ljh add 1829
                    esd.tempDetailStatus = esd.rec.RAESD_Status__c;
                    esd.rec.Asset__c = null;
                    esd.rec.Select_Time__c = null;
                }
                if(esd.rec.Is_Body__c) {
                    break;
                }
            }
            i--;
        }
    }
    //20210519 ljh add 1829
    /*
    //验证是否可分配
    可分配代替品前提1 -- 备品借出申请的状态:“已批准”到“已出库指示”
    可分配代替品前提2 -- 所选借出备品配套一览的状态:‘已批准’到‘出库前已检测’
    代替品不可 Irreplaceable_flag__c
    */
    public Boolean IsCanSubReas(Id raesId){
        List<Rental_Apply_Equipment_Set__c> IsCanSubList = getReas(true,raesId);
        if(IsCanSubList.size() != 1){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '数据有误,不能继续操作了'));
            return false;
        }else if(IsCanSubList[0].Rental_Apply__r.Status__c != '已批准' && IsCanSubList[0].Rental_Apply__r.Status__c!= '已出库指示'){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '申请书状态不符合分配代替品条件,请确认申请的状态'));
            return false;    
        }else if(IsCanSubList[0].RAES_Status__c == '草案中' || IsCanSubList[0].RAES_Status__c == '申请中' || IsCanSubList[0].Shippment_loaner_time2__c != null){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '一览的状态不符合分配替代品条件'));
            return false;
        }else if(IsCanSubList[0].Irreplaceable_flag__c){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '申请人勾选了代替品不可'));
            return false;
        }
        return true;
    }
    //20210519 ljh add 1829
    // 扫一扫按钮
    public void scanAndMatch() {
        done_flg = false;
        Boolean IsSub = false; //是否是分配替代 //20210513 ljh add 1829
        Id OldRaesId;
        if(String.isBlank(qrcode)) {
            return ;
        }
        //20210513 ljh add 1829 start
        else{
            //system.debug('qrcode'+qrcode);
            //qrcode+';'+scanType
            //scanType = 2;{!esdInfo.rec.Rental_Apply_Equipment_Set__c}
            if(qrcode.contains(';')){
                //两行代码不可换顺序
                IsSub = Integer.valueOf(qrcode.split(';')[1]) == 2?true:false;
                OldRaesId = qrcode.split(';')[2];
                qrcode = qrcode.split(';')[0];   
            }
        }
        if(IsSub){
           //验证是否可以【分配替代品】
            if(!IsCanSubReas(OldRaesId)) return;
        }
        //20210513 ljh add 1829 end
        Savepoint sp = Database.setSavepoint();
 
        try {
            Datetime now = System.now();
            //system.debug('qrcode:'+qrcode+'===bieBeiPinFenLeiList'+bieBeiPinFenLeiList);
            List<Asset> mainAssetList = [
                SELECT Id
                     , Fixture_Model_No_F__c
                     , Internal_asset_location__c
                     , SerialNumber
                     , Salesdepartment__c
                     , SalesProvince__c
                     , Product_category__c
                     , Equipment_Type__c
                     , Internal_Asset_number_key__c
                  FROM Asset
                 WHERE Fixture_QRCode__c =: qrcode
                   //AND Main_OneToOne__c = true //20210508 ljh add 1834
                   AND You_Xiao_Ku_Cun__c > 0
                 LIMIT 1
            ];
 
            //system.debug('+mainAssetList:'+mainAssetList);
            if(mainAssetList.isEmpty()) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '保有设备不存在或已被分配'));
                return;
            }else if(bieBeiPinFenLeiList.size()>0 && !bieBeiPinFenLeiList.contains(mainAssetList[0].Equipment_Type__c)){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '分配备品的备品分类与借用目的不符'));
                return;
            }
            Asset mainAsset = mainAssetList[0];
            List<Fixture_OneToOne_Link__c> linkList = [
                SELECT Id
                     , Accessory_Asset__c
                     , Accessory_Asset__r.Fixture_Model_No_F__c
                     , Accessory_Asset__r.Internal_asset_location__c
                     , Accessory_Asset__r.SerialNumber
                     , Accessory_Asset__r.Equipment_Type__c // 备品分类 //20210510 ljh add 1672
                     , Accessory_Asset__r.Internal_Asset_number_key__c
                     , Accessory_Asset__r.Loaner_accsessary__c //20210519 ljh add 1829
                     , Main_Asset__c
                     , Main_Asset__r.Fixture_Model_No_F__c
                     , Main_Asset__r.Internal_asset_location__c
                     , Main_Asset__r.SerialNumber
                     , In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c
                     , Select_Accessory_Asset_Cnt__c
                  FROM Fixture_OneToOne_Link__c
                 WHERE Main_Asset__c=:mainAsset.Id
            ];
 
 
            //20210513 ljh add 1829 start
            Map<String,Fixture_OneToOne_Link__c> linkMap = new Map<String,Fixture_OneToOne_Link__c>();
            for(Fixture_OneToOne_Link__c link:linkList) {
                linkMap.put(link.Accessory_Asset__r.Fixture_Model_No_F__c, link);
            }
            Map<String, Fixture_Set_Detail__c> fsdModelMap;
            //分配替代品
            if(IsSub){ 
                //根据型号找到标准配套
                List<Fixture_Set__c> fsList = [
                    SELECT Id
                         // , Name
                         , Fixture_Set_Body_Model_No__c
                    FROM Fixture_Set__c
                    WHERE Fixture_Set_Body_Model_No__c=:mainAsset.Fixture_Model_No_F__c 
                    LIMIT 1
                ];
                if(fsList.isEmpty()) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '保有设备的标准配套不存在'));
                    return;
                }
                if(OldRaesId == null) {
                    return;
                }
                // 标准配套明细
                fsdModelMap = getFsdModelMap(fsList[0].Id);
 
                //报错: 1.备品一对一 比标准配套多 2.link里可分配的数量比标准配套多
                for(Fixture_OneToOne_Link__c link: linkList) {
                    Integer cnt = intValueOf(link.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c); // link里可分配的数量
                    if(!fsdModelMap.containsKey(link.Accessory_Asset__r.Fixture_Model_No_F__c)) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, link.Accessory_Asset__r.Fixture_Model_No_F__c + '没有相应的配套明细,请添加后重试!'));
                        clearRaesd(OldRaesId);
                        return;
                    }else{
                        Integer cntFs = Integer.valueOf(fsdModelMap.get(link.Accessory_Asset__r.Fixture_Model_No_F__c).Quantity__c);
                        if(cnt>cntFs){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, link.Accessory_Asset__r.Fixture_Model_No_F__c + '实物附属品多于标准配套,请确认后再分配。'));
                            clearRaesd(OldRaesId);
                            return;
                        }
                    } 
                }
                //页面显示  原来的申请取消 新的显示出来 
                // 恢复到未分配
                clearRaesd(OldRaesId);
                Integer newRaesIndex = 0; // 要替代的保有设备 + 1
                //Date mainDate = null;
                for(Integer i = 0; i < esdList.size(); i++) {
                    //重新替代分配
                    if(esdList[i].tempOldRaesIdSub == OldRaesId){
                        esdList.remove(i--);
                    }
                }
                for(Integer i = 0; i < esdList.size(); i++) {
                    EsdInfo esd1 = esdList[i];
                    if( esd1.rec.Rental_Apply_Equipment_Set__c == OldRaesId) {
                        if(esd1.rec.Fixture_Model_No__c == mainAsset.Fixture_Model_No_F__c){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '分配代替品不能选择当前配套'));
                            return;
                        }
                        newRaesIndex = i;
                        esd1.tempStatus = '取消';
                        esd1.tempDetailStatus = '取消';
                        if(!esd1.rec.Is_Body__c){
                            esd1.tempDate =  null;
                        }
                        esd1.SubChecked = true;
                    }
                }
                List<Fixture_Set_Detail__c> fsdList = (List<Fixture_Set_Detail__c>)fsdModelMap.values();
                // 遍历配套明细
                for(Fixture_Set_Detail__c fsd: fsdList) {
                    Integer index = 1;
                    // 20210707 ljh update
                    // Integer cnt = -1;
                    Integer cnt = 0;
                    Integer quantity = Integer.valueOf(fsd.Quantity__c);
                    Integer cntfs = quantity;
                    Boolean inLink = linkMap.containsKey(fsd.Fixture_Model_No_F__c);
                    Fixture_OneToOne_Link__c link;
                    if(inLink){
                        link = linkMap.get(fsd.Fixture_Model_No_F__c);
                        cnt = intValueOf(link.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c); // link里可分配的数量 
                    }
                    while(quantity > 0) {
                        Rental_Apply_Equipment_Set_Detail__c raesd = new Rental_Apply_Equipment_Set_Detail__c();
                        raesd.Asset__c = fsd.Is_Body__c?mainAsset.Id:(inLink?link.Accessory_Asset__c:null);
                        if(!fsd.Is_Body__c && inLink){
                            raesd.Fixture_OneToOne_Link_Id__c = link.Id;
                        }
                        raesd.FSD_Is_OneToOne__c = fsd.Is_OneToOne__c; //主体这个false ***
                        raesd.Rental_Apply__c = parentObj.Id;
                        //raesd1.Rental_Apply_Equipment_Set__c = raesId;
                        raesd.Is_Body__c = fsd.Is_Body__c;
                        if(fsd.Is_Body__c){
                            raesd.Loaner_accsessary__c = false; 
                        }else if(inLink){
                            raesd.Loaner_accsessary__c = link.Accessory_Asset__r.Loaner_accsessary__c; 
                        }
                        raesd.IndexFromUniqueKey__c = index++;
                        raesd.AgencyAssignAdd__c = false; //办事处追加
                        raesd.Fixture_Set_Detail__c = fsd.Id;
                        raesd.IndexFromUniqueKey_Text__c = fsd.SortInt_F__c;
 
                        EsdInfo esd = new EsdInfo(raesd);
                        esd.tempLocation = fsd.Is_Body__c?mainAsset.Internal_asset_location__c: (inLink?link.Accessory_Asset__r.Internal_asset_location__c:'');
                        esd.tempModel = fsd.Is_Body__c?mainAsset.Fixture_Model_No_F__c:(inLink?link.Accessory_Asset__r.Fixture_Model_No_F__c:fsd.Fixture_Model_No_F__c);
                        esd.tempKey = fsd.Is_Body__c?mainAsset.Internal_Asset_number_key__c:(inLink?link.Accessory_Asset__r.Internal_Asset_number_key__c:'');
                        esd.tempSerial = fsd.Is_Body__c?mainAsset.SerialNumber:(inLink?link.Accessory_Asset__r.SerialNumber:'');
                        esd.tempEquipmentType = fsd.Is_Body__c?mainAsset.Equipment_Type__c:(inLink?link.Accessory_Asset__r.Equipment_Type__c:'');// 备品分类 //20210510 ljh add 1672
                        esd.tempDetailStatus = '已分配';
                        esd.tempStatus = '已分配';
                        esd.tempOldRaesIdSub = OldRaesId;
                        esd.tempFixtureSet = fsd.Fixture_Set__c;
                        esd.editable = false;
                        // 20210707 ljh update
                        // if((cntfs-quantity > cnt) && !fsd.Is_Body__c){
                        if((cntfs-quantity >= cnt) && !fsd.Is_Body__c){
                            //一对一中没有的或者一对一数量小于标准配套数量 
                            esd.tempStatus = '取消';
                            esd.tempDetailStatus = '取消'; 
                            raesd.Fixture_OneToOne_Link_Id__c = null;
                            raesd.Asset__c = null;
                            raesd.AgencyAssignAdd__c = true; //办事处追加
                        }
                        newRaesIndex++; // 新的一览插入的位置 
                        if(newRaesIndex < esdList.size()) {
                            esdList.add(newRaesIndex,esd);
                        }else {
                            esdList.add(esd);
                        }
                        quantity--;
                    }                  
                }
            }
            //20210513 ljh add 1829 end
            else{
                Id raesId = getBestRaesId(mainAsset, linkList); // 一次只给一个还没分配的一览分配
                if(raesId == null) {
                    return;
                } 
                // 恢复到未分配
                clearRaesd(raesId);
                //20210520 ljh add 1829 start
                for(Integer i = 0; i < esdList.size(); i++) {
                    //重新替代分配
                    if(esdList[i].tempOldRaesIdSub == raesId){
                        esdList.remove(i--);
                    }
                }
                //20210520 ljh add 1829 end
                Id fsId = null;
                List<EsdInfo> esdListOneSet = new List<EsdInfo>();
                Integer lastIndex = 0; // 一览中最后一条明细的下标 + 1
                Date mainDate = null;
                for(Integer i = 0; i < esdList.size(); i++) {
                    EsdInfo esd = esdList[i];
                    if( esd.rec.Rental_Apply_Equipment_Set__c == raesId) {
                        esdListOneSet.add(esd);
                        lastIndex = i;
                        if(esd.rec.Is_Body__c) {
                            fsId = esd.rec.Fixture_Set_Id__c;
                            // 分配主体
                            esd.rec.Asset__c = mainAsset.Id;
                            esd.rec.AgencyTempCancel__c = false;
                            esd.rec.AgencyTempCancelTime__c = null;
                            esd.rec.IndexFromUniqueKey__c = 1;
                            // 画面显示用
                            esd.tempLocation = mainAsset.Internal_asset_location__c;
                            esd.tempKey = mainAsset.Internal_Asset_number_key__c;
                            esd.tempSerial = mainAsset.SerialNumber;
                            esd.tempEquipmentType = mainAsset.Equipment_Type__c;// 备品分类 //20210510 ljh add 1672;
                            esd.tempStatus = '已分配';
                            esd.tempDetailStatus = '已分配';
                            mainDate = esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c;
                        }
                    }
                }
                lastIndex++; // 一览最后明细下标 + 1
 
                // 配套明细
                //Map<String, Fixture_Set_Detail__c> fsdModelMap = getFsdModelMap(fsId); //20210521 ljh update 1829
                fsdModelMap = getFsdModelMap(fsId);
                // 按link去匹配明细
                for(Fixture_OneToOne_Link__c link: linkList) {
                    Boolean isMatch = false;
                    Integer cnt = intValueOf(link.In_wh_Fu_Shu_Pin_You_Xiao_Ku_Cun_F__c); // link里可分配的数量
                    Integer cntFs = 1;
                    Integer index = 1;
                    //20210521 ljh add 1829 start
                    if(!fsdModelMap.containsKey(link.Accessory_Asset__r.Fixture_Model_No_F__c)) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, link.Accessory_Asset__r.Fixture_Model_No_F__c + '没有相应的配套明细,请添加后重试!'));
                        clearRaesd(raesId);
                        return;
                    }else{
                        cntFs = Integer.valueOf(fsdModelMap.get(link.Accessory_Asset__r.Fixture_Model_No_F__c).Quantity__c);
                        if(cnt>cntFs){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, link.Accessory_Asset__r.Fixture_Model_No_F__c + '实物附属品多于标准配套,请确认后再分配。'));
                            clearRaesd(raesId);
                            return;
                        }
                    }
                    //20210521 ljh add 1829 end
                    for(EsdInfo esd: esdListOneSet) {
                        if(esd.rec.Is_Body__c) {
                            continue;
                        }
                        if(link.Accessory_Asset__r.Fixture_Model_No_F__c == esd.tempModel && cnt > 0) {
                            cnt--;
                            index++;
                            // 明细分配
                            esd.rec.Asset__c = link.Accessory_Asset__c;
                            esd.rec.Fixture_OneToOne_Link_Id__c = link.Id;
                            esd.rec.FSD_Is_OneToOne__c = true;
                            esd.rec.AgencyTempCancel__c = false;
                            esd.rec.AgencyTempCancelTime__c = null;
 
                            // 画面显示
                            esd.tempLocation = link.Accessory_Asset__r.Internal_asset_location__c;
                            esd.tempKey = link.Accessory_Asset__r.Internal_Asset_number_key__c;
                            esd.tempSerial = link.Accessory_Asset__r.SerialNumber;
                            esd.tempEquipmentType = link.Accessory_Asset__r.Equipment_Type__c;// 备品分类 //20210510 ljh add 1672
                            if(esd.tempStatus != '追加') {
                                esd.tempStatus = '已分配';
                            }
                            esd.tempDetailStatus = '已分配';
                            esd.tempDate = mainDate;
                            isMatch = true;
                        }
                    }
                    // 有link但没有明细,或link里的数量超过借出明细数,追加明细(没有超过标准配套)
                    if(!isMatch || cnt > 0) {
                        while(cnt > 0) {
                            Rental_Apply_Equipment_Set_Detail__c raesd = new Rental_Apply_Equipment_Set_Detail__c();
                            raesd.Asset__c = link.Accessory_Asset__c;
                            raesd.Fixture_OneToOne_Link_Id__c = link.Id;
                            raesd.FSD_Is_OneToOne__c = true;
                            raesd.Rental_Apply__c = parentObj.Id;
                            raesd.Rental_Apply_Equipment_Set__c = raesId;
                            raesd.Is_Body__c = false;
                            raesd.IndexFromUniqueKey__c = index++;
                            raesd.AgencyAssignAdd__c = true;
                            if(fsdModelMap.containsKey(link.Accessory_Asset__r.Fixture_Model_No_F__c)) {
                                Fixture_Set_Detail__c fsd = fsdModelMap.get(link.Accessory_Asset__r.Fixture_Model_No_F__c);
                                raesd.Fixture_Set_Detail__c = fsd.Id;
                                raesd.IndexFromUniqueKey_Text__c = fsd.SortInt_F__c;
                            }
                            //20210521 ljh update 1829 start
                            // else {
                            //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, link.Accessory_Asset__r.Fixture_Model_No_F__c + '没有相应的配套明细,请添加后重试!'));
                            //     clearRaesd(raesId);
                            //     return;
                            // }
                            //20210521 ljh update 1829 end
                            EsdInfo esd = new EsdInfo(raesd);
                            esd.tempStatus = '追加';
                            esd.tempLocation = link.Accessory_Asset__r.Internal_asset_location__c;
                            esd.tempModel = link.Accessory_Asset__r.Fixture_Model_No_F__c;
                            esd.tempKey = link.Accessory_Asset__r.Internal_Asset_number_key__c;
                            esd.tempSerial = link.Accessory_Asset__r.SerialNumber;
                            esd.tempEquipmentType = link.Accessory_Asset__r.Equipment_Type__c;// 备品分类 //20210510 ljh add 1672
                            esd.tempDetailStatus = '已分配';
                            esd.tempDate = mainDate;
                            if(lastIndex < esdList.size()) {
                                esdList.add(lastIndex++, esd);
                            }
                            else {
                                esdList.add(esd);
                            }
                            cnt--;
                        }
                    }
                }
                // 没有被分配的明细,取消
                for(EsdInfo esd: esdListOneSet) {
                    if(esd.rec.Asset__c == null) {
                        esd.tempStatus = '取消';
                        esd.tempDetailStatus = '取消';
                        esd.tempDate = null;
                    }
                }
            }
        }
        catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            Database.rollback(sp);
        }
    }
    private Map<String, Fixture_Set_Detail__c> getFsdModelMap(Id fsId) {
        List<Fixture_Set_Detail__c> fsdList = [
            SELECT Id
                 , Fixture_Model_No_F__c
                 , Quantity__c //20210518 ljh 1829 add
                 , Is_Body__c //20210521 ljh 1829 add
                 , Is_OneToOne__c  //20210521 ljh 1829 add
                 , Fixture_Set__c //20210521 ljh 1829 add
                 , SortInt_F__c
            FROM Fixture_Set_Detail__c
            WHERE Fixture_Set__c=:fsId
            ORDER BY SortInt_F__c // 20211018 ljh add 防止默认查询不按照顺序
        ];
        Map<String, Fixture_Set_Detail__c> fsdModelMap = new Map<String, Fixture_Set_Detail__c>();
        for(Fixture_Set_Detail__c fsd:fsdList) {
            fsdModelMap.put(fsd.Fixture_Model_No_F__c, fsd);
        }
        return fsdModelMap;
    }
    private Integer intValueOf(Object obj){
        if(obj == null){
            return 0;
        }
        return Integer.valueOf((Decimal) obj);
    }
 
    /**
    @decription 下架按钮
    */
    // public void stockDown() {
    //     done_flg = false;
    //     if(!isRaStatusOK()) {
    //         return;
    //     }
    //     Map<Id, Rental_Apply_Equipment_Set_Detail__c> raesdMap = getDetailsMap();
    //     List<Rental_Apply_Equipment_Set_Detail__c> updateRaesdList = new List<Rental_Apply_Equipment_Set_Detail__c>();
    //     Set<Id> raesIdSet = new Set<Id>();
    //     Datetime now = System.now();
    //     Id userId =  Userinfo.getUserId();
    //     Boolean hasChecked = false;
    //     for (EsdInfo esd : esdList) {
    //         if(!raesdMap.containsKey(esd.rec.Id)) {
    //             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, esd.tempModel + '不存在或追加后未保存,请刷新画面重试!')) ;
    //             return;
    //         }
    //         Rental_Apply_Equipment_Set_Detail__c raesd = raesdMap.get(esd.rec.Id);
    //         if(esd.checked || raesIdSet.contains(esd.rec.Rental_Apply_Equipment_Set__c)) {
    //             if(esd.rec.AgencyTempCancel__c) {continue;}
    //             hasChecked = true;
    //             if(raesd.LastModifiedDate != esd.rec.LastModifiedDate) {
    //                 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, raesd.Fixture_Model_No__c + '后台数据被' + raesd.LastModifiedBy.Name + '修改,请刷新画面!'));
    //                 return;
    //             }
    //             if(esd.rec.Asset__c == null) {
    //                 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '未分配不可下架!'));
    //                 return;
    //             }
    //             else if(raesd.Asset__c == null) {
    //                 ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '请保存分配结果后重试!'));
    //                 return;
    //             }
    //             else if(!raesd.StockDown__c) {
    //                 raesd.StockDown__c = true;
    //                 raesd.StockDown_time__c = now;
    //                 raesd.StockDown_staff__c = userId;
    //                 raesd.Shipment_request_time2__c = now;
    //                 raesd.Shipment_request__c = true;
    //                 updateRaesdList.add(raesd);
    //             }
    //             if(esd.rec.Is_Body__c) {
    //                 raesIdSet.add(esd.rec.Rental_Apply_Equipment_Set__c);
    //             }
    //         }
    //     }
    //     if(!hasChecked) {
    //         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '未选择下架的一览!'));
    //         return;
    //     }
    //     Savepoint sp = Database.setSavepoint();
    //     try {
    //         if(!updateRaesdList.isEmpty()) {
    //             //print('更新明细', updateRaesdList);
    //             FixtureUtil.withoutUpdate(updateRaesdList);
    //             // 只要有下架就设为出库指示
    //             if(parentObj.Status__c!='已出库指示') {
    //                 Rental_Apply__c ra = new Rental_Apply__c(Id = parentObj.Id, Status__c='已出库指示');
    //                 FixtureUtil.withoutUpdate(new List<Rental_Apply__c> {ra});
    //             }
    //             init();
    //             done_flg = true;
    //         }
    //     }
    //     catch (Exception ex) {
    //         system.debug('=====' + ex.getMessage());
    //         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
    //         Database.rollback(sp);
    //         done_flg = false;
    //     }
    // }
    /**
    @description 发货按钮,切换发货单信息是否可编辑
    */
    public void shipment() {
        done_flg = false;
        if(!isRaStatusOK()) {
            return;
        }
 
        Id userId =  Userinfo.getUserId(); // 20210624 ljh add SFDC-C448GR
        Datetime now = System.now();
        if(isSameCity) {
            slip.Name = parentObj.Name + '_Dummy_SameCity';
            slip.DeliveryCompany__c = '其他';
            slip.Distributor_method__c = '其他';
            slip.Shippment_loaner_time__c = now;
        }
        Boolean insertSlip = (slip.Id == null);
        Map<Id, Rental_Apply_Equipment_Set_Detail__c> raesdMap = getDetailsMap();
        Savepoint sp = Database.setSavepoint();
        try {
            Set<Id> raesIdSet = new Set<Id>();
            List<Id> mainIdList = new List<Id>();
            List<Rental_Apply_Equipment_Set_Detail__c> updateRaesdList = new List<Rental_Apply_Equipment_Set_Detail__c>();
            if(esdList.isEmpty()) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有明细,不能发货!'));
                return;
            }
            Map<Datetime, List<Rental_Apply_Equipment_Set_Detail__c>> approvalMap = new Map<Datetime, List<Rental_Apply_Equipment_Set_Detail__c>>();// 20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长
            for(EsdInfo esd:esdList) {
                if(!raesdMap.containsKey(esd.rec.Id)) {
                    continue;
                }
                Rental_Apply_Equipment_Set_Detail__c raesd = raesdMap.get(esd.rec.Id);
                if(esd.checked || raesIdSet.contains(esd.rec.Rental_Apply_Equipment_Set__c)) {
                    if(raesd.Is_Body__c) {
                        mainIdList.add(raesd.Asset__c);
                        raesIdSet.add(esd.rec.Rental_Apply_Equipment_Set__c);
 
                        // add lc 20220927 SFDC-CJ48VE 备品预计出库日逻辑调整 start
                        // 备品预计出库日应该等于今天,否则不能发货
                        if( esd.rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c != Date.today() ){
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '备品预计出货日应该等于今天,否则不能发货!'));
                            return;
                        }
                        // add lc 20220927 SFDC-CJ48VE 备品预计出库日逻辑调整 end
                    }
 
                    // 分配时临时取消的在发货后彻底取消
                    if(raesd.AgencyTempCancel__c) {
                        raesd.Cancel_Select__c = true;
                        raesd.Cancel_Reason__c = '被动取消';
                        raesd.Loaner_cancel_Remarks__c = '该主体下没有可对应此型号的库存';
                        updateRaesdList.add(raesd);
                        continue;
                    }
                    if(raesd.LastModifiedDate != esd.rec.LastModifiedDate) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, raesd.Fixture_Model_No__c + '后台数据被' + raesd.LastModifiedBy.Name + '修改,请刷新画面!'));
                        return;
                    }
                    // 20210624 ljh update SFDC-C448GR
                    // if(esd.rec.Select_Time__c == null) {
                    if(esd.rec.Asset__c == null) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '未分配不可发货!'));
                        return;
                    }
                    // 20210624 ljh update SFDC-C448GR
                    // else if(raesd.Select_Time__c == null) {
                    else if(raesd.Asset__c == null) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '请保存分配结果后重试!'));
                        return;
                    }
                    // 20210624 ljh update SFDC-C448GR start
                    // else if(!raesd.StockDown__c) {
                    //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '未下架不可发货!'));
                    //     return;
                    // }
                    // 20210624 ljh update SFDC-C448GR end
                    else if(raesd.Shippment_loaner_time__c != null) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,esd.tempModel + '已发货,请刷新画面!'));
                        return;
                    }
                    // 20210624 ljh update SFDC-C448GR start
                    else if(!raesd.StockDown__c) {
                        raesd.StockDown__c = true;
                        raesd.StockDown_time__c = now;
                        // raesd.StockDown_staff__c = userId;//20210728 1719
                        raesd.Shipment_request_time2__c = now;
                        raesd.Shipment_request__c = true;
                    }
                    // 20210624 ljh update SFDC-C448GR end
                    raesd.Inspection_result__c = 'OK';
                    // 发货前检测时间和检测人在trigger里设
                    raesd.Shippment_loaner_time__c = now;
                    // 20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 start
                    Datetime keyDt = raesd.Add_Request_approval_time__c != null?raesd.Add_Request_approval_time__c:raesd.Rental_Apply__r.Request_approval_time__c;
                    List<Rental_Apply_Equipment_Set_Detail__c> tempRaesdL;
                    if(approvalMap.containsKey(keyDt)){
                        tempRaesdL = approvalMap.get(keyDt);
                    }else{
                        tempRaesdL = new List<Rental_Apply_Equipment_Set_Detail__c>();
                    }
                    tempRaesdL.add(raesd);                        
                    approvalMap.put(keyDt,tempRaesdL);
                    // 20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 end  
                    updateRaesdList.add(raesd);
                }
                else {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '必须全部勾选发货'));
                    return;
                }
            }
 
            if(String.isBlank(parentObj.Delivery_Agency__c)){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '发货-办事处为空,不能发货'));
                return;
            }
            Id addressId;
            List<Shipment_address__c> shipmentAddressList = [SELECT Id,Name FROM Shipment_address__c WHERE Name =: parentObj.Delivery_Agency__c];
            if(shipmentAddressList.size() > 0){
                addressId = shipmentAddressList[0].Id;
            }
            else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '该办事处【办事处地址】无值,请确认!'));
                return;
            }
            if(String.isBlank(slip.Name)
                || String.isBlank(slip.DeliveryCompany__c)
                || String.isBlank(slip.Distributor_method__c)
                || String.isBlank(slip.Wh_Staff__c)) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '发货物流信息必填!'));
                return;
            }
            //20201209 ljh update end
            // 删除link
            if(!mainIdList.isEmpty()) {
                Oly_TriggerHandler.bypass(AssetHandlerCheck.class.getName());
                FixtureUtil.delOtOLinkData(mainIdList);
                Oly_TriggerHandler.clearBypass(AssetHandlerCheck.class.getName());
            }
            if(!updateRaesdList.isEmpty()) {
                slip.Shippment_loaner_time__c = now;
                FixtureUtil.withoutUpsertObjects(new List<FixtureDeliverySlip__c> {slip});
                // 20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 start
                map<String,Decimal> ApplyToShipmentMap = new map<String,Decimal>();
                if(approvalMap.size() > 0 ){
                    // dtList[0] 第一个就是最小时间
                    List<Datetime> dtList = new List<Datetime>(approvalMap.keySet());
                    Date startDateSOQL  = date.newinstance(dtList[0].year(), dtList[0].month(), dtList[0].day());
                    List<OlympusCalendar__c> ocList = [SELECT Id, Date__c,IsWorkDay__c 
                                     FROM OlympusCalendar__c
                                    WHERE Date__c >= :startDateSOQL
                                      AND Date__c <= :Date.today()
                                    ORDER BY Date__c ASC];
                    Map<Date,String> ocMap = new Map<Date,String>();
                    for(OlympusCalendar__c oc:ocList){
                        String IsWorkDay = oc.IsWorkDay__c.format();
                        ocMap.put(oc.Date__c,IsWorkDay);
                    }
                    for(Datetime dt:dtList){
                        Boolean startFlag = false;
                        Boolean endFlag = false;
                        Datetime startTime = dt;
                        Date startDate = Date.newInstance(startTime.year(),startTime.month(),startTime.day());
                        Datetime endTime = Datetime.now();
                        Date endDate = Date.today();
                        // 审批时间是非奥林巴斯工作日  
                        // if(ocList[0].IsWorkDay__c == 0){
                        if(ocMap.get(startDate) == '0'){
                            for(OlympusCalendar__c oc:ocList){
                                if(startDate < oc.Date__c && oc.IsWorkDay__c == 1){
                                    startTime = Datetime.newInstance(oc.Date__c.year(),oc.Date__c.month(),oc.Date__c.day(),0,0,0);
                                    startDate = oc.Date__c;
                                    startFlag = true;
                                    break;
                                }
                            }
                        }
                        // 发货时间是非奥林巴斯工作日
                        if(ocList[ocList.size() - 1].IsWorkDay__c == 0){
                            for(Integer i = ocList.size() - 1; i >= 0;i--){
                                if(ocList[i].IsWorkDay__c == 1){
                                    endTime = Datetime.newInstance(ocList[i].Date__c.addDays(1).year(),ocList[i].Date__c.addDays(1).month(),ocList[i].Date__c.addDays(1).day(),0,0,0);
                                    endDate = ocList[i].Date__c.addDays(1);
                                    endFlag = true;
                                    break;
                                }
                            }
                        }
                        Decimal timeDifLast;
                        if(ocList[0].IsWorkDay__c == 0 && ocList[ocList.size() - 1].IsWorkDay__c == 0 && !startFlag && !endFlag){
                            timeDifLast = 0;
                        }else{
                            Long startL = startTime.getTime();
                            Long tendL = endTime.getTime();
                            Long timeDif = tendL - startL;                            
                            Decimal time11 = timeDif*1.00;
                            Decimal time12 = 24*3600*1000*1.00;
                            timeDifLast = time11/time12;                            
                            Integer tempWeek = 0;
                            for(OlympusCalendar__c oc:ocList){
                                if(oc.IsWorkDay__c == 0 && startDate < oc.Date__c && oc.Date__c < endDate){
                                    tempWeek++;
                                }
                            }
                            timeDifLast = timeDifLast - tempWeek;
                        }
                        // dtestLast 四舍五入 保留1位小数
                        for(Rental_Apply_Equipment_Set_Detail__c raesd00:approvalMap.get(dt)){
                            ApplyToShipmentMap.put(raesd00.Id,timeDifLast.setScale(1));
                        }
                    }
                }
                // 20220309 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 end 
                // 明细和申请连到发货单上
                for(Rental_Apply_Equipment_Set_Detail__c raesd: updateRaesdList) {
                    if(!raesd.Cancel_Select__c) {
                        raesd.DeliverySlip__c = slip.Id;
                    }
                    // 20220315 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 start
                    if(ApplyToShipmentMap.containsKey(raesd.Id)){
                        raesd.ApplyToShipmentWorkTime__c = ApplyToShipmentMap.get(raesd.Id);
                    }
                    // 20220315 ljh SFDC-CC6CLJ phase5上线课题131 提交申请到备品出库时长 end
                }
                FixtureUtil.withoutUpdate(updateRaesdList);
                // 20210624 ljh update SFDC-C448GR start
                // Rental_Apply__c ra = new Rental_Apply__c(Id=parentObj.Id, DeliverySlip__c = slip.Id, Delivery_Agency__c = parentObj.Delivery_Agency__c, Agency_Address_Id__c = addressId );
                Rental_Apply__c ra = new Rental_Apply__c();
                ra.Id = parentObj.Id;
                if(parentObj.Status__c!='已出库指示') {
                    ra.Status__c = '已出库指示';
                }
                ra.DeliverySlip__c = slip.Id;
                ra.Delivery_Agency__c = parentObj.Delivery_Agency__c; 
                ra.Agency_Address_Id__c = addressId;
                //ra.Outbound_TradeStatus__c = parentObj.Hospital__r.TradeComplianceStatus__c;//贸易合规 you
                // 20210624 ljh update SFDC-C448GR end
 
                //20220217 sx add 备品借出申请-决裁控制 No.4 出库成功时,把此时点的决裁编号和决裁状态写到决裁编号(出库)和决裁状态(出库)上
                if (String.isNotBlank(parentObj.Campaign__c) && parentObj.Campaign__r.IF_Approved__c){
                    // ra.ApprovedNo_Delivery__c = parentObj.Campaign__r.Meeting_Approved_No__r.MeetingApprovedNo__c;
                    // ra.Approved_State_Delivery__c = parentObj.Campaign__r.Meeting_Approved_No__r.ProcessState__c;
                    ra.ApprovedNo_Delivery__c = parentObj.Campaign__r.Meeting_Approved_No__r.Name;
                    ra.Approved_State_Delivery__c = parentObj.Campaign__r.Approved_Status__c;
                }
                FixtureUtil.withoutUpdate(new List<Rental_Apply__c> {ra});
            }
            // 同城时自动收货
            if(isSameCity && !raesIdSet.isEmpty()) {
                List<Rental_Apply_Equipment_Set__c> raesList = new List<Rental_Apply_Equipment_Set__c>();
                Date rentalEndDate = setRentalEndDate(Date.today(), parentObj);
                for(Id raesId:raesIdSet) {
                    raesList.add(new Rental_Apply_Equipment_Set__c(Id=raesId, Received_Confirm__c = 'OK', Rental_Start_Date__c = Date.today(), Rental_End_Date__c = rentalEndDate));
                }
                FixtureUtil.withoutUpdate(raesList);
            }
            init();
            done_flg = true;
        }
        catch (Exception ex) {
            system.debug('=====' + ex.getMessage());
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getDmlMessage(0)));
            ApexPages.addMessages(ex);
            Database.rollback(sp);
            // 运输单插入成功,但明细或申请更新失败时,运输单的假Id要清掉
            if(insertSlip) {
                slip.Id = null;
            }
            done_flg = false;
        }
    }
 
    public Date setRentalEndDate(Date startDate, Rental_Apply__c rentalApplyObj) {
        Date endDate = null;
        switch on rentalApplyObj.demo_purpose2__c{
            when '试用(无询价)','试用(有询价)','新产品评价','其他','协议借用' {
                endDate = startDate + intValueOf(rentalApplyObj.Hope_Lonaer_date_Num__c);
            }
            when '一般用户','保修用户','市场多年保修','再修理','索赔QIS','已购待货','故障排查' {
                endDate = startDate + 30;
            }
            when '学会展会' {
                endDate = rentalApplyObj.Campaign_EndDate_F__c + 5;
            }
        }
 
        return endDate;
    }
    
 
    public class EsdInfo {
        public Rental_Apply_Equipment_Set_Detail__c rec { get; set; }
        public Boolean checked {get;set;}
        public boolean editable { get; set; }
        public boolean IsCanSub { get; set; } //20210519 ljh add 1829
        public boolean SubChecked { get; set; } //20210519 ljh add 1829
        public String tempStatus {get;set;} // 已分配/取消/追加
        public Date tempDate {get;set;} //出货日
        public String tempLocation {get;set;} // 存放地
        public String tempSerial {get;set;} // 机身编号
        public String tempKey {get;set;} // 固定资产编号Key
        public String tempEquipmentType {get;set;} // 备品分类 //20210510 ljh add 1672
        public String tempDetailStatus {get;set;}  
        public String tempModel {get;set;}
        public ID tempOldRaesIdSub {get;set;} //20210518 ljh add 1829 
        public ID tempFixtureSet {get;set;} //20210519 ljh add 1829
        
 
        public EsdInfo(Rental_Apply_Equipment_Set_Detail__c rec) {
            this.rec = rec;
            this.checked = false;
            this.editable = rec.Shippment_loaner_time__c == null && rec.Is_Body__c;
            /*
            可分配代替品前提1 -- 备品借出申请的状态:“已批准”到“已出库指示”
            可分配代替品前提2 -- 所选借出备品配套一览的状态:‘已批准’到‘出库前已检测’
            代替品不可 Irreplaceable_flag__c
            */
            this.IsCanSub = (rec.Rental_Apply_Equipment_Set__r.Irreplaceable_flag__c) ||
                (rec.Rental_Apply__r.Status__c != '已批准' && rec.Rental_Apply__r.Status__c!= '已出库指示')  ||
                (rec.Rental_Apply_Equipment_Set__r.RAES_Status__c == '草案中' || rec.Rental_Apply_Equipment_Set__r.RAES_Status__c == '申请中' || rec.Rental_Apply_Equipment_Set__r.Shippment_loaner_time2__c != null);
            this.tempModel = rec.Fixture_Model_No__c;
            this.tempLocation = rec.Asset__r.Internal_asset_location__c;
            this.tempKey = rec.Asset__r.Internal_Asset_number_key__c;
            this.tempSerial = rec.Asset__r.SerialNumber;
            this.tempEquipmentType = rec.Asset__r.Equipment_Type__c; //20210510 ljh add 1672
            this.tempDetailStatus = rec.RAESD_Status__c;
            this.tempDate = rec.Rental_Apply_Equipment_Set__r.Rental_Start_Date__c;
            this.SubChecked = false; //20210520 ljh add 1829
            if(rec.Asset__c == null) {
                this.tempStatus = '';
            }
            else if(rec.Select_Time__c != null) {
                this.tempStatus = '已分配';
            }
        }
    }
}