liuyn
2024-03-11 a87f1c3df03078814ee97ad0c8ac200a232419e9
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
/**
 * 备品配套选择
 */
public with sharing class RentalFixtureSetSelectController extends CreateRelationListPagingCtrlBase {
    //20201015  ljh SFDC-BU947L 跟新是否是opd客户字段  add
     @TestVisible private void test() {
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
    }
    public override Integer getSearchNumMax() {
        //各ページに制御あれば、最大件数を指定する
        // searchNumMax = Integer.valueOf(Label.Product_Select_Limit);
        //TODO change
        // searchNumMax = 100;
        pagesize = '100';
        return searchNumMax;
    }
 
    /* 選択されたデータ取得用Soql Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' From Rental_Apply_Equipment_Set__c';
        selectedDataSql += ' where Rental_Apply__c = \'' + String.escapeSingleQuotes(parentId) + '\'';
        selectedDataSql += '   and Fixture_Set__c != null';
        selectedDataSql += '   and Cancel_Select__c = False';
        // 跳转分配代替品画面--选中一览不在这里显示
        if (String.isNotBlank(inRaesId)) {
            selectedDataSql += ' and Id = null';
        }
        selectedDataSql += ' order by Fixture_Set__r.Loaner_code__c, Fixture_Set__c, IndexFromUniqueKey__c';
        return selectedDataSql;
    }
 
    // 検索元対象オブジェクトAPI名
    public override String getOriginObjName() {
        // オブジェクトAPI名
        originObjName = 'Fixture_Set__c';
        return originObjName;
    }
    public override String getOriginObjColumns() {
        // 項目セット
        originObjColumns =  'Id';
        return originObjColumns;
    }
 
    public override String getObjName() {
        // オブジェクトAPI名
        objName = 'Rental_Apply_Equipment_Set__c';
        return objName;
    }
    public override String getColumnLeftFieldSetName() {
        // 左の項目セット
        columnLeftFieldSetName = '';
        return columnLeftFieldSetName;
    }
    public override String getColumnRightFieldSetName() {
        // 右の項目セット
        columnRightFieldSetName = 'RentalFixtureSetSelect_right';
        return columnRightFieldSetName;
    }
 
    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        return new List<String>{'Id', 'Rental_Apply__c', 'Rental_Apply__r.Status__c', 'Rental_Num__c', 'Fixture_Set__r.Name',
                                'RetalFSetDetail_Cnt__c', 'Same_Accessory_flag__c'};
    }
    public override List<String> getHiddenFieldList() {
        return new List<String>{'Substitute_Select_Again__c', 'Same_Accessory_flag__c'};
    }
    // 画面里直接可以输入的項目 List
    public override List<String> getWritableColumnFieldList() {
        return new List<String>{'Rental_Num__c', 'Irreplaceable_flag__c', 'Same_Accessory_flag__c'};
    }
    // getObjName 连 getOriginObjName 的 FK
    public override String getFKColumnField() {
        return 'Fixture_Set__c';
    }
 
    public override String getRecordTypeId() {
        //ページレイアウトを収得するのレコードタイプ
        recordTypeId = '';
        return recordTypeId;
    }
 
    // ページコントローラに検索処理は、WhereSoql作成のみ、パラメータとして、コンポーネントに渡される
    public override String getSqlWhereStr() {
        sqlWhereStr = '';
 
        if(getIsNeedRunSearch()){
            sqlWhereStr = this.makeSoql(keywdSort);
        }
 
        return sqlWhereStr;
 
    }
    public override String getOrderbyStr() {
        return 'order by Loaner_code__c, Id';
    }
 
    public override Boolean getIsNeedRunSearch() {
        return true;
    }
 
    /*****************ソート時再検索条件(画面からの入力条件を無視するため)******************/
    private String keywdSort = null;
    public String keyword { get; set; }
 
    public String inRaesId { get; set;}   // 分配代替品传入参数
    public boolean isRadio { get; set;}   // 分配代替品(true)--选择配套画面只能单选
    public List<Rental_Apply_Equipment_Set__c> selectedRaesList { get; set; }   // 选中一览,非ListView显示--分配代替品
    // substituteId 現状 保存 btn 部分refersh ではない、その部分のロジック使われってないです。
    private String substituteId;          // 保存 btn(部分 refersh), 的时候 退避 保存后 借出一览的Id, 画面上选别的行的时候可以拿Id更新
 
    public String saveType { get; set; }
    public Rental_Apply__c parentObj { get; set; }
    public List<Rental_Apply_Equipment_Set__c> selectedGroupData { get; set; }
 
    public RentalFixtureSetSelectController(ApexPages.StandardController stdController) {
        this();
    }
 
    public RentalFixtureSetSelectController() {
        parentId = ApexPages.currentPage().getParameters().get('pt_recid');
        inRaesId = ApexPages.currentPage().getParameters().get('raesid');
        isRadio = String.isBlank(this.inRaesId) ? false : true;   // 分配代替品--选择配套画面只能单选
 
        //备品配套下的所有明细
        if (!String.isBlank(this.parentId)) {
            List<Rental_Apply__c> parentObjs = [
                    SELECT Id,
                           Status__c,
                           IsOPD_Account__c,//20201012 ljh SFDC-BU947L 跟新是否是opd客户字段  add
                           RequestNoJoinStr2__c
                      FROM Rental_Apply__c
                     WHERE Id = :parentId];
            if (parentObjs.size() > 0) {
                parentObj = parentObjs.get(0);
            }
        }
 
        
        if (parentObj == null) {
            throw new ControllerUtil.myException('沒有指定备品借出申请或者数据不正。');
        }
 
        // OLY_OCM-404 分配代替品,跳转页面显示原选中一览信息
        if (!String.isBlank(this.inRaesId)) {
            this.selectedRaesList = [
                    select Id, Name, Fixture_Set__c, Loaner_code_F__c, Loaner_name_F__c, RetalFSetDetail_Cnt__c
                    from Rental_Apply_Equipment_Set__c
                    where Id = :inRaesId];
            if (selectedRaesList.size() == 0) {
                throw new ControllerUtil.myException('沒有指定备品借出申请一览或者数据不正。');
            }
        }
    }
 
    public void init() {
        searchOppSetParam();
        getSqlWhereStr();
 
    }
 
    private void searchOppSetParam() {
        keywdSort = keyword;
    }
 
    public PageReference searchOpp() {
        searchOppSetParam();
 
        if(!getIsNeedRunSearch()){
            return null;
        }
 
        // 選択済みの製品を取得
        myComponentController.getSelectedDataInfo();
 
        getSqlWhereStr();
        // コンポーネントにSoqlを発行して、ページングする
        myComponentController.searchAndPaging();
        return null;
    }
 
    public PageReference save() {
 
        //20170906 upsert by UniqueKey__c
        List<Rental_Apply_Equipment_Set__c> mfUpsert = new List<Rental_Apply_Equipment_Set__c>();
        String chkIdsStr = '';
        Savepoint sp = Database.setSavepoint();
        Set<String> clearUniqueKeySet = new Set<String>();
 
        try {
            //PlanProdDetail__c  20240229 sx 修改为从OPD.计划借出备品取
            List<Rental_Apply__c> raUpdate = [
                    select Id
                    ,RequestNoJoinStr2__c
                    , Demo_purpose1__c, Account__c, Hospital__c, OPDplan__r.PlanProdDetail__c, OPDPlan__r.PlanProdDetailSys__c, repeatFixtureApprovalStatus__c, OPDRepeatFixture__c                //PlanProdDetail__c  20240229 sx 修改为从OPD.计划借出备品取
                      from Rental_Apply__c where Id = :parentId for Update];
            if (raUpdate.isEmpty()) {
                throw new ControllerUtil.myException('没有找到申请单。');
            }
 
            // 画面中チェックされた対象、確定ボタンを押下すると、一つずつ順番に明細を選択のため。
            List<WrapperInfo> targetViewList = new List<WrapperInfo>();
            List<String> OpdProductList = new List<String>();
            List<String> otherFixture = new List<String>();
 
            //20231025 备品智能化 - OPD生成的备品借出配套在备品不允许删除 sx start 
            if(raUpdate[0].OPDplan__r.PlanProdDetail__c != null){                        //PlanProdDetail__c  20240229 sx 修改为从OPD.计划借出备品取
                String fixTrim = raUpdate[0].OPDplan__r.PlanProdDetail__c.trim();            //PlanProdDetail__c  20240229 sx 修改为从OPD.计划借出备品取
                System.debug('fixTrim====='+fixTrim);
                List<String> fixtureStrings = fixTrim.split(';');
                System.debug('fixtureStrings====='+fixtureStrings);
                if(fixtureStrings.size() > 0){
                    for(String fixString : fixtureStrings){
                        String tempString = fixString.trim();
                        System.debug('tempString====='+tempString);
                        if(tempString.indexOf('*')!= -1){
                            System.debug('substring==='+tempString.substring(0, tempString.indexOf('*')));
                            OpdProductList.add(tempString.substring(0, tempString.indexOf('*')));
                        }
                    }
                }
            }
 
            //当前OPD配套的Id 20231025 备品智能化 - OPD生成的备品借出配套在备品不允许删除 sx start
            List<Fixture_Set__c> OpdProductId = [SELECT Id, Name FROM Fixture_Set__c where Fixture_Set_Body_Model_No__c IN:OpdProductList];
            String s = 'SELECT Id, Name FROM Fixture_Set__c where Fixture_Set_Body_Model_No__c IN' + OpdProductList;
            List<String> opdString = new List<String>();
            for(Fixture_Set__c fs : OpdProductId){
                opdString.add(fs.Id);
            }
            System.debug('opdString===='+opdString);
            //20231025 备品智能化 - OPD生成的备品借出配套在备品不允许删除 sx end
            for (WrapperInfo wprInfo : viewList) {
                Rental_Apply_Equipment_Set__c robj = (Rental_Apply_Equipment_Set__c) wprInfo.sobj;
 
                //20231025 备品智能化 - OPD生成的备品借出配套在备品不允许删除 sx start
                System.debug('OpdProductList=='+OpdProductList);
                System.debug('robj.Fixture_Set__c=='+robj.Fixture_Set__c);
                if(!opdString.contains(robj.Fixture_Set__c) && wprInfo.check && robj.Rental_Num__c != 0){
                    otherFixture.add(robj.Fixture_Set__c);
                }
                //20231025 备品智能化 - OPD生成的备品借出配套在备品不允许删除 sx end
                if (robj.Rental_Num__c > 0 && wprInfo.check) { 
                    targetViewList.add(wprInfo);
 
                // 検索したデータが対象外です
                } else if ((!wprInfo.check && wprInfo.oldCheck)
                        || (wprInfo.check && robj.VF_Rental_Num__c > robj.Rental_Num__c && robj.Rental_Num__c == 0)) {
                    //20231025 sx 备品智能化 - OPD生成的备品借出配套在备品不允许删除 sx start
                    String fixSetString = robj.Fixture_Set__c;
                    System.debug('fixSetStrin===='+fixSetString);
                    System.debug('opdString==='+opdString);
                    if(opdString.contains(fixSetString)){
                        robj.Rental_Num__c.addError('OPD计划添加的配套不可以删除');
                        return null;
                    }
                    //20231025 sx 备品智能化 - OPD生成的备品借出配套在备品不允许删除 sx end
                    if (robj.Rental_Apply__r.Status__c != '草案中' && robj.Id != this.inRaesId) {
                        // 0の場合deleteされるので、入力規則がすりぬけるので、ここでもチェックが必要です
                        robj.Rental_Num__c.addError('只有在草案中的状态下可以减少数量');
                        return null;
                    }
                }
            }
            
            
            //20231025  备品智能化 - 重复性重复追加重复配套 sx start
            System.debug('otherFixture====' + otherFixture);
            String tempFixtureString = '';
            String tempRentalString = '';
            if(otherFixture.size() > 0){
                //List<String> chukuStatus = new List<String>{ '已出库指示', '已下架', '出库前已检测', '已出库', '申请者已收货', '医院已装机确认', '已回寄', '欠品中', '已回收' };
                System.debug('raUpdate[0]==='+raUpdate[0]);
                System.debug('raUpdate[0]'+raUpdate[0].Account__c + 'Account__c'+ raUpdate[0].Hospital__c);
                //医院或者客户同时为空时 没有重复配套
                if(raUpdate[0].Account__c != null || raUpdate[0].Hospital__c != null){
                    // 20231214  sx 修改 未出库的数量>0 之前判断有没有重复的配套
                    List<Rental_Apply_Equipment_Set__c> accountRaList = [SELECT Id, Rental_Apply__r.Account__c, Rental_Apply__r.Hospital__c, Loaner_code_F__c 
                                                FROM Rental_Apply_Equipment_Set__c WHERE Rental_Apply__r.Account__c = :raUpdate[0].Account__c AND Rental_Apply__r.Hospital__c = :raUpdate[0].Hospital__c AND Rental_Apply__r.Shippment_ng_num__c > 0 AND Rental_Apply__r.Id != :parentId];
                    
                    System.debug('accountRaList===' + accountRaList);
                    //之前未出库的所有配套
                    Set<String> accountFixture = new Set<String>();
                    for(Rental_Apply_Equipment_Set__c account : accountRaList){
                        accountFixture.add(account.Loaner_code_F__c);
                    }
 
                    List<Fixture_Set__c>  otherFixtureSet = [SELECT Id, Fixture_Set_Body_Model_No__c FROM Fixture_Set__c WHERE Id IN :otherFixture];
                    system.debug('accountFixture==='+accountFixture);
                    system.debug('otherFixtureSet==='+otherFixtureSet);
                    if(raUpdate[0].Demo_purpose1__c == '产品试用'){
                        if(accountRaList.size()>0){
                            for(Fixture_Set__c other : otherFixtureSet){
                                for(String account : accountFixture){
                                    if(other.Fixture_Set_Body_Model_No__c.equals(account)){
                                        tempFixtureString += account + ';';
                                    }
                                }
                            }
                        }
                        
                        for(Fixture_Set__c other : otherFixtureSet){
                                //备品追加产品字段
                                tempRentalString += other.Fixture_Set_Body_Model_No__c + ';'; 
                        }
                    }
                }
            }
            System.debug('tempFixtureString==='+tempFixtureString);
            if(String.isNotBlank(tempFixtureString) || String.isNotBlank(tempRentalString)){
                Rental_Apply__c tempRa = new Rental_Apply__c();
                tempRa.Id = parentId;
                tempRa.repeatFixtureTXT__c = tempFixtureString;
                tempRa.RentalAddFixture__c = tempRentalString;
                UPDATE tempRa;
            }
 
            //20231222 sx add  如果other配套=0的时候就不存在新加的配套,需要把重复配套字段清空
            if(otherFixture.size() == 0){
                Rental_Apply__c tempRa = new Rental_Apply__c();
                tempRa.Id = parentId;
                tempRa.repeatFixtureTXT__c = '';
                tempRa.RentalAddFixture__c = '';
                UPDATE tempRa;
            }
 
            //20231025  备品智能化 - 重复性重复申请申请需要走审批流,但审批通过才可以追加重复配套  
            //同科室下所有明细存在出库指示及之后(包含出库指示)就不可以添加配套 需要提交特殊审批 sx end
            List<String> chkIdList = new List<String>();
 
            // 分配代替品画面
            if (String.isNotBlank(inRaesId)) {
 
                // 1. check--前台控制后再确认
                if (targetViewList.size() != 1) {
                    throw new ControllerUtil.myException('请选择一条数据'); 
                }
                Rental_Apply_Equipment_Set__c robj = (Rental_Apply_Equipment_Set__c) targetViewList.get(0).sobj;
 
                if (robj.Rental_Num__c != 1) {
                    throw new ControllerUtil.myException('数量只能为1'); 
                }
                if (robj.Fixture_Set__c == this.selectedRaesList[0].Fixture_Set__c) {
                    throw new ControllerUtil.myException('分配代替品不能选择当前配套'); 
                }
                if (robj.Irreplaceable_flag__c || robj.Same_Accessory_flag__c) {
                    throw new ControllerUtil.myException('代替品不可和同一附属品不可选'); 
                }
 
                // 2.獲取頁面選中記錄
                List<Rental_Apply_Equipment_Set__c> raess = [Select Id, Loaner_centre_mail_address__c, Fixture_Set__c, Substitute_Select_Again__c,
                        Rental_Apply__c, Irreplaceable_flag__c, Same_Accessory_flag__c, Received_Confirm__c, IndexFromUniqueKey__c,
                        Rental_Num__c, Groupby_SortInt__c, Canceled__c, Canceled_Id__c, RetalFSetDetail_Cnt__c, Old_Rental_Apply__c
                        From Rental_Apply_Equipment_Set__c
                        Where id = :inRaesId AND Cancel_Select__c = false
                            for update];
 
                if (raess.isEmpty()) {
                    throw new ControllerUtil.myException('没有检索到可以分配代替品的借出备品配套一览');
                }
                Rental_Apply_Equipment_Set__c craes = raess[0];
                if (craes.Irreplaceable_flag__c) {
                    throw new ControllerUtil.myException('这条数据不能分配替代品');
                }
 
                // 备品智能化项目对应 20231122 by lc Start
                Boolean isMainAssign = false;
                List<Rental_Apply_Equipment_Set_Detail__c> mainRaesdObjs = [
                        SELECT Id, Asset__c, Intervention_Reason__c 
                        FROM Rental_Apply_Equipment_Set_Detail__c 
                        WHERE Rental_Apply_Equipment_Set__c =: craes.Id 
                        AND Cancel_Select__c = false 
                        AND Is_Body__c = true];
 
                // 如果分配代替品时,原配套已经主体分配或已有人工干预理由的,则需要标记出来,后续记录人工干预理由时需要使用
                if (!mainRaesdObjs.isEmpty() && mainRaesdObjs.size() > 0 
                    && (String.isNotEmpty(mainRaesdObjs[0].Asset__c) || String.isNotEmpty(mainRaesdObjs[0].Intervention_Reason__c))
                ) {
                    isMainAssign = true;
                }
                // 备品智能化项目对应 20231122 by lc End
 
                // 3.更新狀態取消分配(Sys) 、取消理由 
                craes.Cancel_Select__c = true; 
                craes.Cancel_Reason__c = '分配代替品';
 
                // 4.新增一條相同的“借出備品配套一覽”記錄----clone一条新记录(直接修改分配替代品页面选中的那条记录,然后插入数据库)
                robj.Old_RetalFSetDetail_Cnt__c = craes.RetalFSetDetail_Cnt__c; // 原配套明细数
                if (String.isBlank(substituteId)){
                    robj.IndexFromUniqueKey__c = 0;    // 防止clone时与申请单内已有备品配套UK重复
                } else {
                    robj.IndexFromUniqueKey__c = 1;    // 如果不是clone,比如先保存过,则UK不会重复(暂时无用)
                }
                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勾选
                // 新记录Canceled__c & Canceled_Id__c为选中一览的Id
                robj.Canceled__c = craes.Id;
                robj.Canceled_Id__c = craes.Id;
                robj.IsCancelMainAssign__c = isMainAssign; // 备品智能化项目对应
                robj.Old_Rental_Apply__c = craes.Old_Rental_Apply__c; // OLY_OCM-251 分单后新申请单Name根据其下一览的旧借出申请取得,所以需要复制
 
                robj.Id = substituteId;
                // 这里的upsert使用ID
                FixtureUtil.withoutUpsertObjects(new Rental_Apply_Equipment_Set__c[]{craes, robj});
 
                // 原一览关联clone出来的新一览
                craes.New_Rental_Apply_Equipment__c = robj.Id;
                FixtureUtil.withoutUpsertObjects(new Rental_Apply_Equipment_Set__c[]{craes});
 
                if (String.isBlank(substituteId)) {     // 暂时无用
                    // 今回2.5代替品分配の対応では.代替品分配でCloneされた一覧のUKに自分のIDを追加必要があります(複数回代替品的対策)
                    // 自分のIdがinsert後しかわからないので、ここで再度updateします。update の triggerにて UKにIdが足されることになります。
                    robj.IndexFromUniqueKey__c = 1;
                    FixtureUtil.withoutUpsertObjects(new Rental_Apply_Equipment_Set__c[]{robj});
                }
                String uniqueKeyStr = parentObj.RequestNoJoinStr2__c + ':'+ robj.Fixture_Set__c + ':'+ ((Integer) Math.round(robj.IndexFromUniqueKey__c));
                // 因为配套明细选择画面获取的是Key的最后一位,所以这里就不拼写Id了
                uniqueKeyStr += robj.Id;
                chkIdList.add(uniqueKeyStr);
 
                // 全部更新正常の場合 (要注意、DMLの最後にしないといけないです)、substituteId に Id を退避
                substituteId = robj.Id;
            }
            // 如果申请书的状态不是草案中只能做更新处理
            else if (parentObj.Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())) {
                updateRaesList(targetViewList, mfUpsert);
            }
            else {
                Integer sortInt = 0;
                Map<Id, String> addSameRaesIdMap = new Map<Id, String>();
                for (WrapperInfo wprInfo : targetViewList) {
                    Rental_Apply_Equipment_Set__c robj = (Rental_Apply_Equipment_Set__c) wprInfo.sobj;
                    //20170906 upsert by UniqueKey__c
                    //画面上にチェックした
                    if (wprInfo.check) {
                        sortInt++;
                        robj.Groupby_SortInt__c = sortInt;
                        if (robj.Substitute_Select_Again__c && robj.Rental_Num__c > 1) {
                            throw new ControllerUtil.myException('数量只能为1'); 
                        }
                        for (Integer i = 0; i < robj.Rental_Num__c; i++) {
                            Rental_Apply_Equipment_Set__c rupsobj = robj;
                            if (i > 0) {
                                rupsobj = robj.clone(false);
                            }
                            String uniqueKeyStr = parentObj.RequestNoJoinStr2__c + ':'+ robj.Fixture_Set__c + ':'+ (i+1);
                            // 代替分配的一览会分开显示所以只有一条
                            if (robj.Substitute_Select_Again__c) {
                                uniqueKeyStr += rupsobj.Id;
                            }
                            rupsobj.UniqueKey__c = uniqueKeyStr;
                            rupsobj.IndexFromUniqueKey__c = i+1;
                            mfUpsert.add(rupsobj);
                            // 第一件目
                            if ((i == 0 && rupsobj.RetalFSetDetail_Cnt__c == 0)) {
                                chkIdList.add(UniqueKeyStr);
                            }
                            if (rupsobj.Rental_Num__c > rupsobj.VF_Rental_Num__c
                                  && rupsobj.Same_Accessory_flag__c == true
                                  // 第一次创建一览的时候没有ID
                                  && String.isNotBlank(robj.Id)
                                  && i > 0 && !addSameRaesIdMap.containsKey(robj.Id)) {
                                addSameRaesIdMap.put(robj.Id, robj.Fixture_Set__c);
                            }
                            if (String.isBlank(rupsobj.Id)
                                && !String.isBlank(uniqueKeyStr)) {
                                // 新規の場合、ここ単純に Id にて判断
                                clearUniqueKeySet.add(uniqueKeyStr);
                            }
                        }
                    }
                }
 
                if (!mfUpsert.isEmpty()) {
                    //upsert mfUpsert UniqueKey__c;
                    FixtureUtil.withoutUpsertRaes(mfUpsert);
                }
                if (!addSameRaesIdMap.isEmpty()) {
                    // 需要设置的一览(有值)
                    List<Rental_Apply_Equipment_Set__c> raess = [SELECT Id, Rental_Apply__c, Fixture_Set__c
                                                                   FROM Rental_Apply_Equipment_Set__c
                                                                  WHERE Id in:addSameRaesIdMap.keySet()
                                                                    AND Rental_Apply__c = :parentId];
                    Map<String, Rental_Apply_Equipment_Set__c> raesMap = new Map<String, Rental_Apply_Equipment_Set__c>();
                    for (Rental_Apply_Equipment_Set__c raes : raess) {
                        raesMap.put(raes.Fixture_Set__c, raes);
                    }
                    // 一览下的明细
                    List<Rental_Apply_Equipment_Set_Detail__c> raesds = [SELECT Id,
                                                                        Cancel_Select__c,
                                                                        Fixture_Set_Detail__r.SortInt__c,
                                                                        Fixture_Set_Detail__c,
                                                                        UniqueKey__c,
                                                                        Rental_Apply_Equipment_Set__c,
                                                                        Rental_Num__c,
                                                                        IndexFromUniqueKey__c,
                                                                        IndexFromUniqueKey_Text__c
                                                                   FROM Rental_Apply_Equipment_Set_Detail__c
                                                                  WHERE Rental_Apply_Equipment_Set__c =:raess
                                                                    AND Cancel_Select__c = false
                                                                  // ORDER BY 设置的和Handler一样。
                                                                  ORDER BY Rental_Apply_Equipment_Set__c, Fixture_Set_Detail__r.SortInt__c ASC nulls last];
                    // 一览明细Map
                    Map<Id, List<Rental_Apply_Equipment_Set_Detail__c>> raesdMap = new Map<Id, List<Rental_Apply_Equipment_Set_Detail__c>>();
                    Set<Id> raesdIdSet = new Set<Id>();
                    for (Rental_Apply_Equipment_Set_Detail__c raesd : raesds) {
                        if (!raesdMap.containsKey(raesd.Rental_Apply_Equipment_Set__c)) {
                            raesdMap.put(raesd.Rental_Apply_Equipment_Set__c, new List<Rental_Apply_Equipment_Set_Detail__c>());
                            raesdIdSet = new Set<Id>();
                        }
                        // 因为明细有数量。所以同一个一览里面的同一个Fixture_Set_Detail__c的明细只保存一条
                        if (raesdIdSet.contains(raesd.Fixture_Set_Detail__c)) {
                            continue;
                        }
                        else {
                            raesdIdSet.add(raesd.Fixture_Set_Detail__c);
                        }
                        raesdMap.get(raesd.Rental_Apply_Equipment_Set__c).add(raesd);
                    }
                    Map<Id, List<Rental_Apply_Equipment_Set__c>> sameRAES_objsMap = new Map<Id, List<Rental_Apply_Equipment_Set__c>>();
                    //检索出没有明细的同一附属品一览
                    List<Rental_Apply_Equipment_Set__c> sameRAES_objs = [SELECT Id, Name,
                                                           Fixture_Set_Idx__c,
                                                           Rental_Apply__r.RequestNoJoinStr2__c,
                                                           Rental_Num__c,Same_Accessory_flag__c,
                                                           Loaner_name__c,
                                                           Loaner_name_F__c,
                                                           Loaner_code__c,
                                                           Fixture_Set__c,
                                                           Rental_Apply__c,
                                                           First_RAESD__c,
                                                           Loaner_code_F__c,
                                                           UniqueKey__c
                                                      FROM Rental_Apply_Equipment_Set__c
                                                     WHERE Rental_Apply__c = :parentId
                                                       AND Fixture_Set__c = :addSameRaesIdMap.values()
                                                       AND Same_Accessory_flag__c = true
                                                       AND Cancel_Select__c = false
                                                       AND RetalFSetDetail_Cnt__c = 0
                                                       FOR UPDATE];
                    for (Rental_Apply_Equipment_Set__c raes : sameRAES_objs) {
                        Rental_Apply_Equipment_Set__c raesM = raesMap.get(raes.Fixture_Set__c);
                        if (!sameRAES_objsMap.containsKey(raesM.Id)) {
                            sameRAES_objsMap.put(raesM.Id, new List<Rental_Apply_Equipment_Set__c>());
                        }
                        sameRAES_objsMap.get(raesM.Id).add(raes);
                    }
 
                    // 申請書ロック(Add_Approval_Status__c 更新のため)
                    List<Rental_Apply__c> raObjs = [
                        SELECT Id, Name,
                               Status__c,
                               Add_Approval_Status__c,
                               RequestNoJoinStr2__c
                          FROM Rental_Apply__c
                         WHERE Id = :sameRAES_objs[0].Rental_Apply__c
                           FOR UPDATE];
                    if (raObjs.size() == 0) {
                        throw new ControllerUtil.myException('没有检索出正确的借出备品申请,不能进行操作');
                    }
                    Rental_Apply__c raObj = raObjs[0];
                    // 获取需要追加的统一附属品明细Map
                    Map<Id, List<Rental_Apply_Equipment_Set_Detail__c>> createRaesdMap = createSameRaesd(raesdMap, sameRAES_objsMap, raObj);
                    if (!createRaesdMap.isEmpty()) {
                        // 需要追加的明细List
                        List<Rental_Apply_Equipment_Set_Detail__c> createRaesd = new List<Rental_Apply_Equipment_Set_Detail__c>();
                        for (Id key : createRaesdMap.keySet()) {
                            List<Rental_Apply_Equipment_Set_Detail__c> createRaesdList = createRaesdMap.get(key);
                            if (!createRaesdList.isEmpty()) {
                              createRaesd.addAll(createRaesdList);
                            }
                        }
                        // 有需要追加明细的时候追加明细并且设置First
                        if (!createRaesd.isEmpty()) {
                            FixtureUtil.withoutUpsertRaesd(createRaesd);
                            // 需要更新First的一览
                            List<Rental_Apply_Equipment_Set__c> raesList = new List<Rental_Apply_Equipment_Set__c>();
                            for (Id key : createRaesdMap.keySet()) {
                                List<Rental_Apply_Equipment_Set_Detail__c> createRaesdList = createRaesdMap.get(key);
                                if (!createRaesdList.isEmpty()) {
                                  raesList.add(new Rental_Apply_Equipment_Set__c(Id = key,
                                                                                // 明细检索的时候已经order By了。所以获取第一条就好
                                                                                First_RAESD__c = createRaesdList[0].Id));
                                }
                                // 有需要更新的一览的时候更新
                                if (!raesList.isEmpty()) {
                                    FixtureUtil.withoutUpsertObjects(raesList);
                                }
                            }
 
                        }
                    }
                }
 
                // 削除 delete
                FixtureUtil.delRAES_excludedUpserted(parentObj, mfUpsert);
                //20201012 ljh SFDC-BU947L 跟新是否是opd客户字段  add start
                Boolean IsOPDAccountFlag = false;
                List<Rental_Apply_Equipment_Set__c> sameRAES_objsIs = [select Id,IsOPD_Account__c from Rental_Apply_Equipment_Set__c where Rental_Apply__c = :parentObj.Id and Cancel_Select__c = False];
                if(sameRAES_objsIs.size()>0){
                    for (Rental_Apply_Equipment_Set__c sameRAES_obj : sameRAES_objsIs) {
                        if(sameRAES_obj.IsOPD_Account__c !=null && sameRAES_obj.IsOPD_Account__c.intValue()==1){
                            IsOPDAccountFlag = true;break;
                        }
                    }
                }
                if(IsOPDAccountFlag){
                    parentObj.IsOPD_Account__c = 1;
                }else{
                    parentObj.IsOPD_Account__c = 0;
                }
                update parentObj;
                //20201012 ljh SFDC-BU947L 跟新是否是opd客户字段  add end
            }
 
            // 画面遷移
            if (chkIdList.isEmpty()) {
                PageReference ret = new PageReference('/' + this.parentId);
                return ret;
            }
 
            chkIdsStr = String.join(chkIdList, ',');
        } catch (Exception ex) {
            System.debug(ex.getStackTraceString());
            ApexPages.addMessages(ex);
            Database.rollback(sp);
            // Id をクリア
            for (Rental_Apply_Equipment_Set__c robj : mfUpsert) {
                if (clearUniqueKeySet.contains(robj.UniqueKey__c)) {
                    robj.Id = null;
                }
            }
            return null;
        }
 
        if (saveType == '1') {
            searchOpp();
            saveType = '';
            return null;
        } else {
            PageReference pg = new PageReference('/apex/RentalFixtureSetDetilSelect');
            // 分配代替品跳转到配套明细选择画面,暂时无用
            if (String.isNotBlank(this.inRaesId)) {
                pg.getParameters().put('raesid', this.inRaesId);
            }
            pg.getParameters().put('sids', chkIdsStr);
            pg.setRedirect(true);
            return pg;
        }
    }
 
    /**
     * 保存画面上的选择 -- 在非草案中执行,只会根据Id更新
     * @param targetViewList 画面上显示的WrapperInfo
     * @param mfUpsert 需要更新的一览List -- 保存出错清空ID的时候需要用,所以需要传进来
     */
    private void updateRaesList(List<WrapperInfo> targetViewList, List<Rental_Apply_Equipment_Set__c> mfUpsert) {
        Map<String, Rental_Apply_Equipment_Set__c> needUpdateRaesMap = new Map<String, Rental_Apply_Equipment_Set__c>();
        for (WrapperInfo wprInfo : targetViewList) {
            Rental_Apply_Equipment_Set__c robj = (Rental_Apply_Equipment_Set__c) wprInfo.sobj;
            //画面上にチェックした
            if (wprInfo.check) {
                // 只有在草案中才可以勾选同一附属品、変更前の Same_Accessory_flag__c を確認
                if (wprInfo.additionalInfoMap.get('Same_Accessory_flag__c') == 'false'
                        && robj.Same_Accessory_flag__c == true) {
                    throw new ControllerUtil.myException('只有草案中可以勾选同一附属品。');
                }
                needUpdateRaesMap.put(robj.Fixture_Set__c, robj);
            }
        }
        // 检索申请书下所有一览
        List<Rental_Apply_Equipment_Set__c> raess = [SELECT Id, Rental_Apply__c, Fixture_Set__c
                                                       FROM Rental_Apply_Equipment_Set__c
                                                      WHERE Fixture_Set__c in:needUpdateRaesMap.keySet()
                                                        AND Fixture_Set__c != null
                                                        AND Rental_Apply__c = :parentId
                                                        AND Cancel_Select__c = false
                                                        FOR UPDATE];
        Map<String, Rental_Apply_Equipment_Set__c> raesMap = new Map<String, Rental_Apply_Equipment_Set__c>();
        for (Rental_Apply_Equipment_Set__c raes : raess) {
            Rental_Apply_Equipment_Set__c raes1 = needUpdateRaesMap.get(raes.Fixture_Set__c);
            Rental_Apply_Equipment_Set__c rupsobj = raes1.clone(false);
            // 因为要只是更新所以克隆然后设置Id
            rupsobj.Id = raes.Id;
            mfUpsert.add(rupsobj);
        }
 
        if (!mfUpsert.isEmpty()) {
            //update mfUpsert Id;
            FixtureUtil.withoutUpdate(mfUpsert);
        }
    }
 
    public Map<Id, List<Rental_Apply_Equipment_Set_Detail__c>> createSameRaesd(Map<Id, List<Rental_Apply_Equipment_Set_Detail__c>> raesdMap, Map<Id, List<Rental_Apply_Equipment_Set__c>> sameRAES_objsMap,
                                                                    Rental_Apply__c raObj) {
        List<Rental_Apply_Equipment_Set_Detail__c> mfUpsert = new List<Rental_Apply_Equipment_Set_Detail__c>();
        Map<Id, List<Rental_Apply_Equipment_Set_Detail__c>> raesdUpsertMap = new Map<Id, List<Rental_Apply_Equipment_Set_Detail__c>>();
        for (Id raesId : sameRAES_objsMap.keySet()) {
            Map<Integer, Rental_Apply_Equipment_Set_Detail__c> sltFixtureMap = new Map<Integer, Rental_Apply_Equipment_Set_Detail__c>();
            Map<Integer, RentalFixtureSetDetilSelectController.LineExtraInfo> sltExtraInfoMap = new Map<Integer, RentalFixtureSetDetilSelectController.LineExtraInfo>();
            List<RentalFixtureSetDetilSelectController.LineExtraInfo> extraInfoList = new List<RentalFixtureSetDetilSelectController.LineExtraInfo>();
            // 同一附属品里面没有有明细的一览的时候不对这条同一附属品做操作
            if (!raesdMap.containsKey(raesId)) {
                continue;
            }
            List<Rental_Apply_Equipment_Set_Detail__c> raesds = raesdMap.get(raesId);
            for (Rental_Apply_Equipment_Set_Detail__c sobj : raesds) {
                Rental_Apply_Equipment_Set_Detail__c raesdobj = (Rental_Apply_Equipment_Set_Detail__c) sobj;
                if (!sltFixtureMap.containsKey(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue())) {
                    if (!raesdobj.Cancel_Select__c) {
                        sltFixtureMap.put(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue(), raesdobj);
                        RentalFixtureSetDetilSelectController.LineExtraInfo extraInfo = new RentalFixtureSetDetilSelectController.LineExtraInfo(raesdobj);
                        extraInfoList.add(extraInfo);
                        sltExtraInfoMap.put(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue(), extraInfo);
                    }
                } else {
                    RentalFixtureSetDetilSelectController.LineExtraInfo extraInfo = sltExtraInfoMap.get(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue());
                    extraInfo.updateExtraInfo(raesdobj);
                }
            }
 
            for (Integer j = 0; j < raesds.size(); j ++)
            {
                Integer maxIndexInLoop = null;
                Rental_Apply_Equipment_Set_Detail__c robj = raesds[j];
                for (Integer i = 0; i < robj.Rental_Num__c; i++) {
                    // sameRAES_objs には自分の明細か、申請 直後の明細しかないか の条件があります。
                    RentalFixtureSetDetilSelectController.LineExtraInfo extraInfo = extraInfoList[j];
                    // なので、直接cloneしてOKです。
                    for (Rental_Apply_Equipment_Set__c sameRAES_obj : sameRAES_objsMap.get(raesId)) {
                        Rental_Apply_Equipment_Set_Detail__c rupsobj = robj.clone(false);
                        // 借出申请RequestNoJoinStr2__c:借出申请配套一览Id:配套明细Id
                        String uniqueKeyStr = raObj.RequestNoJoinStr2__c + ':' + sameRAES_obj.Id
                                + ':'+ robj.Fixture_Set_Detail__c + ':';
                        // default値は最初に設定した
                        rupsobj.IndexFromUniqueKey__c = i+1;
                        if (i < extraInfo.indexFromUniqueKeyList.size()) {
                            rupsobj.IndexFromUniqueKey__c = extraInfo.indexFromUniqueKeyList[i];
                            uniqueKeyStr += rupsobj.IndexFromUniqueKey__c;
                        } else if (extraInfo.maxIndexFromUniqueKey != null) {
                            if (maxIndexInLoop == null) { maxIndexInLoop = extraInfo.maxIndexFromUniqueKey; }
                            maxIndexInLoop++;
                            uniqueKeyStr = raObj.RequestNoJoinStr2__c + ':' + sameRAES_obj.Id
                                    + ':'+ robj.Fixture_Set_Detail__c + ':'+ maxIndexInLoop;
                            rupsobj.IndexFromUniqueKey__c = maxIndexInLoop;
                        } else {
                            // uniqueKeyStr に default の IndexFromUniqueKey__c を使う
                            uniqueKeyStr += rupsobj.IndexFromUniqueKey__c;
                        }
 
                        System.debug(rupsobj.IndexFromUniqueKey__c + '测试uniqueKeyStr:' + uniqueKeyStr);
                        rupsobj.UniqueKey__c          = uniqueKeyStr;
                        // 配套(or 申请)·から
                        rupsobj.Rental_Apply_Equipment_Set__c = sameRAES_obj.Id;
                        rupsobj.Rental_Apply__c               = sameRAES_obj.Rental_Apply__c;
                        mfUpsert.add(rupsobj);
                        if (!raesdUpsertMap.containsKey(sameRAES_obj.Id)) {
                            raesdUpsertMap.put(sameRAES_obj.Id, new List<Rental_Apply_Equipment_Set_Detail__c>());
                        }
                        raesdUpsertMap.get(sameRAES_obj.Id).add(rupsobj);
                    }
                }
            }
        }
        return raesdUpsertMap;
    }
 
    public PageReference cancel() {
        PageReference ret = null;
        if (!String.isBlank(this.parentId)) {
            ret = new PageReference('/' + this.parentId);
        }
        return ret;
    }
 
    private String makeSoql(String keyword) {
 
        String soql ='';
        soql += 'where Id != null';
 
        if (!String.isBlank(keyword)) {
            String[] vals = keyword.split(' ');
            soql += ' and (';
            String fmodelno = '';
            for (String v : vals) {
                fmodelno += ' Name like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\' or ';
                fmodelno += ' Loaner_name__c like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\' or';
            }
            fmodelno = fmodelno.removeEnd('or');
            soql += fmodelno + ' )';
            // for (String v : vals) {
            //     soql += ' and Name like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\'';
            // }
        }
        system.debug(soql);
        return soql;
    }
 
    public override void setViewList(List<sObject> queryList) {
        viewList = new List<WrapperInfo>();
 
        if (selectedData.size() > 0) {
 
            selectedGroupData = new List<Rental_Apply_Equipment_Set__c>();
            Map<String, Rental_Apply_Equipment_Set__c> sltFixtureMap = new Map<String, Rental_Apply_Equipment_Set__c>();
            Map<String, Rental_Apply_Equipment_Set__c> subsFixtureMap = new Map<String, Rental_Apply_Equipment_Set__c>();   // 用于存代替分配的一览
            Map<String, Integer> sltFixtureCnt = new Map<String, Integer>();
            // 20170906 グループリスト取得
            // order by Fixture_Set__c, Fixture_Set__r.Loaner_code__c, IndexFromUniqueKey__c
            for (SObject sobj : selectedData) {
                Rental_Apply_Equipment_Set__c raesobj = (Rental_Apply_Equipment_Set__c) sobj;
 
                // 代替分配的一览需要一条一条显示。所以数量为1
                if (raesobj.Substitute_Select_Again__c) {
                    selectedGroupData.add(raesobj);
                    raesobj.Rental_Num__c = 1;
                    raesobj.VF_Rental_Num__c = 1;
                }
                // 非代替品的一览,数量合并后显示一条
                else {
                    if (!sltFixtureMap.containsKey(raesobj.Fixture_Set__c)) {
                        selectedGroupData.add(raesobj);
                        sltFixtureMap.put(raesobj.Fixture_Set__c, raesobj);
                        sltFixtureCnt.put(raesobj.Fixture_Set__c, 0);
                    }
                    Rental_Apply_Equipment_Set__c nobj = sltFixtureMap.get(raesobj.Fixture_Set__c);
                    Integer nCnt = sltFixtureCnt.get(raesobj.Fixture_Set__c);
                    if (!raesobj.Substitute_Select_Again__c) {
                        nCnt++;
                    }
                    sltFixtureCnt.put(raesobj.Fixture_Set__c, nCnt);
                    nobj.Rental_Num__c = nCnt;
                    nobj.VF_Rental_Num__c = nCnt;
                }
            }
 
            //for (Integer i = 0; i < selectedData.size(); i++) {
            for (Integer i = 0; i < selectedGroupData.size(); i++) {
                Rental_Apply_Equipment_Set__c mf = selectedGroupData[i];
                /* not include the selected data num */
                 //501を超えた場合前500のみを出す  
                if (i == getSearchNumMax()) { break; }
                viewList.add(new WrapperInfo(mf, myComponentController));
                viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
                viewList[viewList.size() - 1].check = true;
                viewList[viewList.size() - 1].oldCheck = true;
                viewList[viewList.size() - 1].additionalInfoMap.put('Substitute_Select_Again__c', String.valueOf(mf.Substitute_Select_Again__c));
                viewList[viewList.size() - 1].additionalInfoMap.put('Same_Accessory_flag__c',     String.valueOf(mf.Same_Accessory_flag__c));
                // 分配代替品页面--选中一览不可编辑
                if (String.isNotBlank(inRaesId)) {
                    viewList[viewList.size() - 1].canEdit = false;
                    viewList[viewList.size() - 1].check = false;
                }
            }
        }
 
        if (queryList.size() == 0) {
            return;
        }
 
        Savepoint sp = Database.setSavepoint();
 
        // 数式項目値を取れるのために、一回Insertする
        List<Rental_Apply_Equipment_Set__c> tempList = new List<Rental_Apply_Equipment_Set__c>();
        for (Integer i = 0; i < queryList.size(); i++) {
            // 501を超えた場合前500のみを出す
            if (i == getSearchNumMax()) { break; }
            Rental_Apply_Equipment_Set__c mf = new Rental_Apply_Equipment_Set__c();
            mf.Rental_Apply__c               = parentId;
            mf.Fixture_Set__c                = queryList[i].Id;
            mf.DataMigration_Flag__c         = true;
 
            tempList.add(mf);
        }
 
        Database.SaveResult[] results = FixtureUtil.withoutInsert(tempList, false);
 
        final String soqlStr = 'Select {0} {1} ';
        String whereStr = ' FROM Rental_Apply_Equipment_Set__c WHERE ID in: tempList';
        String soql = String.format(soqlStr, new String[] {myComponentController.strColumus , whereStr});
 
        tempList = Database.query(soql);
        if (queryList.size() != tempList.size()) {
            //error message 検索処理正しくありません、システム管理者に連絡してください。
            for (Integer i = 0; i < results.size(); i ++) {
                Database.SaveResult dmlResult = results[i];
                if (!dmlResult.isSuccess()) {
                    System.debug(System.LoggingLevel.ERROR, '第[' + (i + 1) + ']条 insert error:' + dmlResult);
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                    '第[' + (i + 1) + ']条 insert error:' + dmlResult));
                    // 1件目だけlogに出す
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                        System.Label.CreateRelationListSearchError));
                    Database.rollback(sp);
                    return;
                }
            }
        }
        // 強制ロールバック
        Database.rollback(sp);
        Map<String, SObject> fsDMap = new Map<String,SObject>();
        for(Rental_Apply_Equipment_Set__c fsd : tempList){
            Rental_Apply_Equipment_Set__c robj = fsd.clone(false);
            // 根据OLY_OCM-404的需求设置默认数量为1
            robj.Rental_Num__c = 1;
            robj.VF_Rental_Num__c = 1;
            robj.DataMigration_Flag__c = false;
            fsDMap.put(fsd.Fixture_Set__c, robj);
        }
 
        Integer addedNum = 0;
        for (Integer i = 0; i < queryList.size(); i++) {
 
// TODO where not in selectedFKIdList
            //if (selectedIds.contains(queryList[i].Id)) {
            //    // 跳过已经选择的备品set明细
            //    continue;
            //}
            addedNum ++;
            // 501を超えた場合前500のみを出す
            if (addedNum == getSearchNumMax()) { break; }
            Rental_Apply_Equipment_Set__c mf = (Rental_Apply_Equipment_Set__c) fsDMap.get(queryList[i].Id);
            viewList.add(new WrapperInfo(mf, myComponentController));
            viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
            viewList[viewList.size() - 1].additionalInfoMap.put('Substitute_Select_Again__c', String.valueOf(mf.Substitute_Select_Again__c));
            viewList[viewList.size() - 1].additionalInfoMap.put('Same_Accessory_flag__c',     String.valueOf(mf.Same_Accessory_flag__c));
        }
 
system.debug('●●●●● setViewList END ' );
    }
 
    
          
}