高章伟
2022-02-18 8b5f4c6c281cfa548f92de52c8021e37aa81901e
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
/*
 * 借出备品配套明细选择画面
 * 只显示Fixture_Set_Detail__c有值的明细
 */
public with sharing class ReceivingNoteDetailSelectController extends CreateRelationListPagingCtrlBase {
    private List<LineExtraInfo> extraInfoList;  // viewList と同じ順番、同じ件数
    private String raesid;  // 保存清单配套选择画面传来的值
    private String returl {get;set;}
    public Boolean isAcceptance {get;set;}
 
    public override Integer getSearchNumMax() {
        //各ページに制御あれば、最大件数を指定する
        searchNumMax = Integer.valueOf(Label.Product_Select_Limit);
        //TODO change
        searchNumMax = 100;
        return searchNumMax;
    }
 
    public override Boolean getIsNeedRunSearch() {
        return true;
        //isNeedRunSearch = true;
        //return isNeedRunSearch;
    }
    /* 選択されたデータ取得用Soql Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' From ReceivingNoteDetail__c';
        selectedDataSql += ' where ReceivingNoteSummary__c = \'' + String.escapeSingleQuotes(parentId) + '\'';
        //Fixture_Set_Detail__c没有值不能检索出数据
        selectedDataSql += '   and Fixture_Set_Detail__c != null';
        // OLY_OCM-286 まず全部selectして group by Fixture_Set_Detail__c のlogicにてcountしたいですが
        // Fixture_Set_Detail__c を検索時、全部キャンセルした明細の行が表示しなくなるため、
        // and Cancel_Select__c = False を必ず有効にしてください。
        // selectedDataSql += '   and Cancel_Select__c = False';
        selectedDataSql += '   and Delete_Flag__c = False';
        selectedDataSql += '   and Change_Point__c != \'删除\'';
        selectedDataSql += ' order by RNDAssert__c nulls last, Fixture_Set_Detail__r.SortInt__c, UniqueKey__c';
        return selectedDataSql;
    }
 
    // 検索元対象オブジェクトAPI名
    public override String getOriginObjName() {
        // オブジェクトAPI名
        originObjName = 'Fixture_Set_Detail__c';
        return originObjName;
    }
    public override String getOriginObjColumns() {
        // 項目セット
        //rentx add Fixture_Set_New_Quantity__c at 20210827
        originObjColumns =  'Id, Quantity__c, Is_Body__c, Is_Optional__c, LastModifiedDate, Fixture_Set_New_Quantity__c';
        return originObjColumns;
    }
 
    public override String getObjName() {
        // オブジェクトAPI名
        objName = 'ReceivingNoteDetail__c';
        return objName;
    }
    public override String getColumnLeftFieldSetName() {
        // 左の項目セット
        columnLeftFieldSetName = 'ReceivingNoteDetailSelect_left';
        return columnLeftFieldSetName;
    }
    public override String getColumnRightFieldSetName() {
        // 右の項目セット
        columnRightFieldSetName = 'ReceivingNoteDetailSelect_right';
        return columnRightFieldSetName;
    }
 
    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        return new List<String>{'Id'
                                , 'Is_Body__c'
                                , 'UniqueKey__c'
                                , 'Rental_Num__c'
                                //, 'VF_Rental_Num__c'
                                //, 'RNDAssert__c'
                                , 'passNo3__c'
                                , 'Fixture_Set_Detail__r.SortInt__c'
                                , 'Fixture_Set_Detail__r.Is_Optional__c'
                                , 'EquipmentSet_Managment_Code__c'
                                , 'Salesdepartment__c'
                                , 'SalesProvince__c'
                                , 'Product_category__c'
                                , 'Equipment_Type__c'
                                , 'Manage_type__c'
                                , 'unknow_serial_NO_product__c'
                                , 'Loaner_accsessary__c'
                                , 'DataConfirmation__c'
                                , 'Is_First_RND_F__c'
                                , 'Product_Old_Model_F__c'
                                , 'Fixture_Set_Detail__r.Product2__c'
                                , 'Fixture_Set_Detail__r.Fixture_Model_No_F__c'
                                , 'Set_Arrival_Product__c'
                                , 'Fixture_Arrival_Product__c'
                                , 'Default_Fixture_Arrival_Product__c'
                                , 'Product_Arrival_Product__c'
                                //add by rentx 20210728 start 新品收货_集中备品_建立新品入库标准配套
                                , 'Fixture_Set_Detail__r.Fixture_Set_New__c'
                                , 'Fixture_Set_Detail__r.Fixture_Set_New_Quantity__c'
                                , 'Fixture_Set_New_Quantity__c'
                                , 'Fixture_Set_Detail__r.LastModifiedDate'
                                , 'LastModifiedDate'
                                , 'Fixture_Set_Detail__r.Quantity__c'
                                //add by rentx 20210728 end 新品收货_集中备品_建立新品入库标准配套
                            };
    }
 
    // 画面里直接可以输入的項目 List
    public override List<String> getWritableColumnFieldList() {
        //update by rentx 20210728 start 新品收货_集中备品_建立新品入库标准配套
        // return new List<String>{'Rental_Num__c'};
        return new List<String>{'Fixture_Set_New_Quantity__c'};
        //update by rentx 20210728 end 新品收货_集中备品_建立新品入库标准配套
    }
    // getObjName 连 getOriginObjName 的 FK
    public override String getFKColumnField() {
        return 'Fixture_Set_Detail__c';
    }
 
    public override String getRecordTypeId() {
        //ページレイアウトを収得するのレコードタイプ
        recordTypeId = '';
        return recordTypeId;
    }
 
    // ページコントローラに検索処理は、WhereSoql作成のみ、パラメータとして、コンポーネントに渡される
    public override String getSqlWhereStr() {
        sqlWhereStr = '';
 
        sqlWhereStr = this.makeSoql();
 
        return sqlWhereStr;
    }
    public override String getOrderbyStr() {
        return 'order by SortInt__c';
    }
 
    /*****************ソート時再検索条件(画面からの入力条件を無視するため)******************/
    private List<String> sidList;
    public String saveType { get; set; }
    public ReceivingNoteSummary__c parentObj { get; set; }
    public ReceivingNoteDetail__c sonObj { get; set; }
    public List<ReceivingNoteDetail__c> selectedGroupData { get; set; }
    private String deleteAdd_ApprovalErrorMessage = '第{0}行 付属品{1}件(草案中的追加付属品 {2}件) 更新失败 减少的数量大于草案中的追加付属品的数量';
    private String deleteAdd_ApprovalMessage = '第{0}行 付属品{1}件(草案中的追加付属品 {2}件) 成功更新成 付属品{3}件(草案中的追加付属品 {4}件)';
 
    public ReceivingNoteDetailSelectController() {
        isNeedRunSearch = true;
        String sids = ApexPages.currentPage().getParameters().get('sids'); // 一览Id
        raesid = ApexPages.currentPage().getParameters().get('raesid');    // 清单Id
        returl = ApexPages.currentPage().getParameters().get('returl');
        isAcceptance = String.isNotBlank(returl);
 
        sidList = sids.split(',');
        if(sidList.size()>0) {
            // 借出备品配套
            //02517%3Aa2P0k000000PEkjEAG%3A1
            parentId = sidList.get(0);
            //备品配套下的所有明细
            if (!String.isBlank(this.parentId)) {
                //画面上ヘタ表示の項目はここで追加
                List<ReceivingNoteDetail__c> sonObjs = [SELECT Id
                            , Name
                            , ReceivingNoteSummary__c
                            , ReceivingNoteSummary__r.Id
                            , ReceivingNoteSummary__r.Name
                            , ReceivingNoteSummary__r.ReceivingNote__c
                            , ReceivingNoteSummary__r.Fixture_Set__r.Loaner_name__c
                         FROM ReceivingNoteDetail__c
                        WHERE ReceivingNoteSummary__c = :parentId
                          AND Delete_Flag__c = false];
                if (sonObjs.size() > 0) {
                    parentObj = sonObjs.get(0).ReceivingNoteSummary__r;
                    sonObj = sonObjs.get(0);
                    if (String.isBlank(parentObj.Fixture_Set__c )) {
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '收货一览没有指定备品配套,不能进行操作!'));
                        return ;
                    }
                } else {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '没有找到收货一览,请进行正确的操作!'));
                    return ;
                }
            }
        }
    }
 
    public void init() {
        isNeedSearchFirst = true;
        viewList = new List<WrapperInfo>();
        extraInfoList = new List<LineExtraInfo>();  // viewList と同じ順番、同じ件数
        getSqlWhereStr();
    }
 
    public PageReference searchOpp() {
 
        // 選択済みの製品を取得
        myComponentController.getSelectedDataInfo();
 
        getSqlWhereStr();
        // コンポーネントにSoqlを発行して、ページングする
        myComponentController.searchAndPaging();
        return null;
    }
 
    public PageReference save() {
        //update by rentx 20210729 start 新品收货_集中备品_建立新品入库标准配套
        //新品配套数量若有变化(目前: 为了防止好几个人在同时修改此数据),保存时报错提示:重新刷新画面
        //需要按照init的条件再查一次 在和现在画面上展示的数量作比对 若数量不一致 则保存提示 重新刷新画面
        //获取当前备品收货清单配套一览 获取所有有备品配套明细一览的 收货清单明细
        // 配套有任何更新(不局限数量、新品数量字段修改,比如主体、选配字段有修改也算更新)都check,错误提示改成【备品配套已更新,请重新刷新页面】
        if (parentObj != null) {
            List<ReceivingNoteDetail__c> sonObjs = [SELECT Id
                            , Name
                            , ReceivingNoteSummary__c
                            , SortInt_F__c
                            , Fixture_Set_Detail__r.Fixture_Set_New_Quantity__c
                            , Fixture_Set_Detail__r.LastModifiedDate 
                         FROM ReceivingNoteDetail__c
                        WHERE ReceivingNoteSummary__c = :parentObj.Id
                          AND Delete_Flag__c = false];
            if (sonObjs != null && sonObjs.size() > 0) {
                Map<String,Datetime> checkMap = new Map<String,Datetime>();
                for (ReceivingNoteDetail__c detail : sonObjs) {
                    Datetime tempTime = detail.Fixture_Set_Detail__r.LastModifiedDate;
                    checkMap.put(detail.SortInt_F__c, tempTime );
                }
                for (WrapperInfo wprInfo : viewList) {
                    ReceivingNoteDetail__c robj = (ReceivingNoteDetail__c) wprInfo.sobj;
                    if (checkMap.containsKey(robj.SortInt_F__c)) {
                        Datetime ttime = robj.Fixture_Set_Detail__r.LastModifiedDate;
                        if (checkMap.get(robj.SortInt_F__c) != ttime ) {
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '备品配套已更新,请重新刷新页面!' ));
                        return null;
                        }
                    }
                }
            }
        }
        //update by rentx 20210729 end 新品收货_集中备品_建立新品入库标准配套
 
        //20170906 upsert by UniqueKey__c
        List<ReceivingNoteDetail__c> mfUpsert = new List<ReceivingNoteDetail__c>();
        List<ReceivingNoteDetail__c> mfUpdate = new List<ReceivingNoteDetail__c>();
        Savepoint sp = Database.setSavepoint();
        Set<String> clearUniqueKeySet = new Set<String>();
        // 有删除未审批的追加附属品
        Boolean haveAdd_ApprovalDelete = false;
 
        try {
            // 同一附属品 一括設定する
            // if (parentObj.Same_Accessory_flag__c) {
            //     if ([SELECT Id
            //            FROM ReceivingNoteSummary__c
            //           WHERE ReceivingNote__c = :parentObj.ReceivingNote__c
            //             AND Fixture_Set__c = :parentObj.Fixture_Set__c
            //             AND Same_Accessory_flag__c = true
            //             AND Cancel_Select__c = false
            //             AND Id IN (
            //                     SELECT ReceivingNoteSummary__c
            //                       FROM ReceivingNoteDetail__c
            //                      WHERE Rental_Apply_Equipment_Set__r.ReceivingNote__c = :parentObj.ReceivingNote__c
            //                        AND Rental_Apply_Equipment_Set__r.Fixture_Set__c = :parentObj.Fixture_Set__c
            //                        AND Rental_Apply_Equipment_Set__r.Same_Accessory_flag__c = true
            //                        AND Rental_Apply_Equipment_Set__r.Cancel_Select__c = false
            //                        AND Is_Body__c = false
            //                        AND Cancel_Select__c = true
            //                        AND Cancel_Reason__c != '重新分配' // OLY_OCM-163#comment-20120592 通过取消理由判断
            //                 )
            //             ].size() > 0) {
 
            //         // 申請から進んだ明細がある場合
            //         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
            //                 System.Label.SameAccessory_CannotSync));
            //         return null;
            //     }
            // }
 
            // 画面中チェックされた対象、確定ボタンを押下すると、一つずつ順番に明細を選択のため。
            List<ReceivingNoteSummary__c> sameRAES_objs = null;
 
            // 申請書ロック(Add_Approval_Status__c 更新のため)
            List<ReceivingNote__c> raObjs = [
                SELECT Id, Name
                       // Status__c,
                       // Add_Approval_Status__c,
                       // RequestNoJoinStr2__c
                  FROM ReceivingNote__c
                 WHERE Id = :parentObj.ReceivingNote__c
                   FOR UPDATE];
            if (raObjs.size() == 0) {
                throw new ControllerUtil.myException('没有检索出正确的收货清单,不能进行操作');
            }
            ReceivingNote__c raObj = raObjs[0];
            // parentObj のみ ロック
            //sameRAES_objs = [
            //    SELECT Id
            //         , Name
            //           // Fixture_Set_Idx__c,
            //           // ReceivingNote__r.RequestNoJoinStr2__c,
            //           // Rental_Num__c, Same_Accessory_flag__c,
            //           // Loaner_name__c,
            //           // Loaner_name_F__c,
            //           // Loaner_code__c,
            //           // Fixture_Set__c,
            //         , ReceivingNote__c
            //         , First_RND__c
            //           // First_RAESD__c,
            //           // Loaner_code_F__c,
            //           // UniqueKey__c
            //      FROM ReceivingNoteSummary__c
            //     WHERE Id = :parentObj.Id
            //       FOR UPDATE];
 
            // if (sameRAES_objs[0].Rental_Num__c > 1 && sameRAES_objs[0].Same_Accessory_flag__c) {
                // 同一付属品の一覧もロック
             sameRAES_objs = [
                 SELECT Id, Name
                        // Fixture_Set_Idx__c,
                        // ReceivingNote__r.RequestNoJoinStr2__c,
                        // Rental_Num__c,Same_Accessory_flag__c,
                        // Loaner_name__c,
                        // Loaner_name_F__c,
                        // Loaner_code__c,
                        // Fixture_Set__c,
                      , ReceivingNote__c
                      , First_RND__c
                        // Loaner_code_F__c,
                        // UniqueKey__c
                   FROM ReceivingNoteSummary__c
                  WHERE ReceivingNote__c = :parentObj.ReceivingNote__c
                    AND Fixture_Set__c = :parentObj.Fixture_Set__c
                    AND Id IN: sidList
                    // AND Same_Accessory_flag__c = true
                    // AND Cancel_Select__c = false
                    FOR UPDATE];
            if (sameRAES_objs.size() == 0) {
                throw new ControllerUtil.myException('没有检索出正确的收货清单一览,不能进行操作!');
            }
 
            Map<Id, Map<String, ReceivingNoteDetail__c>> rndMapSet = new Map<Id, Map<String, ReceivingNoteDetail__c>>();
            Map<Id, ReceivingNoteDetail__c> rndfirstMap = new Map<Id, ReceivingNoteDetail__c>();
            String soql ='';
            final String soqlStr = 'Select {0} {1} ';
            String strColumus1 = myComponentController.strColumus;
            if (strColumus1.contains(',passNo2__c') == false || strColumus1.contains('passNo2__c,') == false) {
                strColumus1 += ',passNo2__c';
            }
 
            if (strColumus1.contains(',ReceivingNoteSummary__c') == false || strColumus1.contains('ReceivingNoteSummary__c,') == false) {
                strColumus1 += ',ReceivingNoteSummary__c';
            }
 
            soql += String.format(soqlStr, new String[] {strColumus1 , ' From ReceivingNoteDetail__c WHERE ReceivingNoteSummary__c = :sameRAES_objs'});
            for (ReceivingNoteDetail__c rnd : Database.query(soql)) {
                if (rndMapSet.containsKey(rnd.ReceivingNoteSummary__c) == false) {
                    rndMapSet.put(rnd.ReceivingNoteSummary__c, new Map<String, ReceivingNoteDetail__c>());
                }
                if (rndfirstMap.containsKey(rnd.ReceivingNoteSummary__c) == false && rnd.Is_First_RND_F__c) {
                    rndfirstMap.put(rnd.ReceivingNoteSummary__c, rnd);
                }
                rndMapSet.get(rnd.ReceivingNoteSummary__c).put(rnd.UniqueKey__c, rnd);
            }
            // }
            // SUM出没有还没有批准的追加附属品和已经批准或者不是追加附属品的数量
            // 因为 #getSelectedDataSql() 用 Fixture_Set_Detail__c
            // 所以这里也用 AND Fixture_Set_Detail__c != null
            //List<AggregateResult> appendedGroupBy = [
            //        SELECT Fixture_Set_Detail__c, Count(Id) cnt
            //          FROM ReceivingNoteDetail__c
            //         WHERE ReceivingNoteSummary__c = :parentObj.Id
            //           AND Delete_Flag__c = false
            //           // AND Cancel_Select__c = false
            //           // AND Fixture_Set_Detail__c != null
            //         GROUP BY Fixture_Set_Detail__c];
            /* Key Fixture_Set_Detail__c value↓
             *                           Draft_Appended -> 未批准的追加附属品数量
             *                           Not_Draft_Appended -> 不是未批准的追加附属品数量
             *                           Accsessarys -> 所有的附属品数量
             */
            // Map<String, Map<String, Integer>> add_ApprovalMaps = new Map<String, Map<String, Integer>>();
            // for (AggregateResult a : appendedGroupBy) {
            //     Integer Draft_Appended = a.get('Draft_Appended__c') == null ? 0 : Integer.valueOf(a.get('Draft_Appended__c'));
            //     Integer Not_Draft_Appended = a.get('Not_Draft_Appended__c') == null ? 0 : Integer.valueOf(a.get('Not_Draft_Appended__c'));
            //     add_ApprovalMaps.put(String.valueOf(a.get('Fixture_Set_Detail__c')),
            //         new Map<String, Integer>{
            //             'Draft_Appended' => Draft_Appended,
            //             'Not_Draft_Appended' => Not_Draft_Appended,
            //             'Accsessarys' => a.get('cnt') == null ? 0 : Integer.valueOf(a.get('cnt'))
            //         });
            // }
            List<WrapperInfo> targetViewList = new List<WrapperInfo>();
            // 删除未审批追加附属品ERROR信息
            String deleteAdd_ApprovalErrorMessages = '';
            // 删除未审批追加附属品信息
            // 因为有Error的时候不现实成功信息所以需要分开保存最后判断显示什么信息
            String deleteAdd_ApprovalMessages = '';
            Boolean haveError = false;
            Integer j = 0;
 
            for (WrapperInfo wprInfo : viewList) {
                ReceivingNoteDetail__c robj = (ReceivingNoteDetail__c) wprInfo.sobj;
                // targetViewList.add(wprInfo);
                if (j == 0 && robj.Fixture_Set_New_Quantity__c < 1) {
                // if (j == 0 && robj.Fixture_Set_New_Quantity__c < 1) {
                // From 王硕 20180104 没有强制要求必须申请标配的备品。 非选配的也可以不申请。
                   // robj.Rental_Num__c.addError('非追加附属品,数量不能为0');
                   robj.Fixture_Set_New_Quantity__c.addError('非追加附属品,数量不能为0');
                   return null;
                }
                // 当数量大于0或者数量为0但是是草案中的追加附属品的话可以修改数量
                // if (robj.Rental_Num__c > 0 || robj.Draft_Appended__c == 1) {
                //     if (add_ApprovalMaps.containsKey(robj.Fixture_Set_Detail__c)) {
                //         Map<String, Integer> add_ApprovalMap = add_ApprovalMaps.get(robj.Fixture_Set_Detail__c);
                //         //有删除操作。并且未审批追加附属品大于0
                //         if (robj.Rental_Num__c < add_ApprovalMap.get('Accsessarys') && add_ApprovalMap.get('Draft_Appended') > 0) {
                //             haveAdd_ApprovalDelete = true;
                //             // 明细数量小于已批准的追加附属品加上非追加附属品
                //             if (robj.Rental_Num__c < add_ApprovalMap.get('Not_Draft_Appended')
                //                     && raObj.Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())
                //                     && raObj.Add_Approval_Status__c == FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())) {
                //                 deleteAdd_ApprovalErrorMessages += String.format(deleteAdd_ApprovalErrorMessage,
                //                                                 new String[]{String.valueOf(wprInfo.lineNo + 1),
                //                                                              String.valueOf(add_ApprovalMap.get('Accsessarys')),
                //                                                              String.valueOf(add_ApprovalMap.get('Draft_Appended'))});
                //                 deleteAdd_ApprovalErrorMessages += '\n';
                //                 haveError = true;
                //             }
                //             // 有删除操作并且明细数量大于等于已批准的追加附属品加上非追加附属品
                //             else if (robj.Rental_Num__c >= add_ApprovalMap.get('Not_Draft_Appended')
                //                     && raObj.Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())
                //                     && raObj.Add_Approval_Status__c == FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())) {
                //                 deleteAdd_ApprovalMessages += String.format(deleteAdd_ApprovalMessage,
                //                                                 new String[]{String.valueOf(wprInfo.lineNo + 1),
                //                                                              String.valueOf(add_ApprovalMap.get('Accsessarys')),
                //                                                              String.valueOf(add_ApprovalMap.get('Draft_Appended')),
                //                                                              String.valueOf(robj.Rental_Num__c),
                //                                                              String.valueOf(add_ApprovalMap.get('Draft_Appended') - (add_ApprovalMap.get('Accsessarys') - robj.Rental_Num__c))});
                //                 deleteAdd_ApprovalMessages += '\n';
                //             }
                //         }
                //     }
                //     targetViewList.add(wprInfo);
                // } else if (String.isNotBlank(robj.Id)) {
                //     if (raObj.Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())) {
                //         if (!parentObj.Substitute_flag__c) {
                //             robj.Rental_Num__c.addError('只有在草案中的状态下可以减少数量');
                //             return null;
                //         } else if (parentObj.Yi_Assigned_Cnt__c > 0) {
                //             // 分配代替品后,选择配套明细--'已分配件数 Yi_Assigned_Cnt__c'>0且状态为'草案中'时减少数量,报error
                //             robj.Rental_Num__c.addError('有明细已分配,不能减少数量');
                //             return null;
                //         }
                //     }
                // }
                j ++;
            }
 
            if (haveError) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, deleteAdd_ApprovalErrorMessages));
                return null;
            }
 
            //OLY_OCM-171 与可以选择存放地的简档一致
            Boolean is2B = System.Label.ProfileId_EquCenAdmin.contains(Userinfo.getProfileId())
                                   || Userinfo.getProfileId() == System.Label.ProfileId_SystemAdmin;
                                // || System.Label.ProfileId_EquCenCheckAndDepot.contains(Userinfo.getProfileId())
                                // || Userinfo.getProfileId() == System.Label.ProfileId_EquipmentCenter;
 
            Map<Id, ReceivingNoteDetail__c> setIdFirstDetailMap = new Map<Id, ReceivingNoteDetail__c>();
            Integer index = 0;
 
            for (WrapperInfo wprInfo : viewList) {
                ReceivingNoteDetail__c robj = (ReceivingNoteDetail__c) wprInfo.sobj;
                LineExtraInfo extraInfo = extraInfoList.get(wprInfo.lineNo);
                Integer maxIndexInLoop = null;
                System.debug(robj.Rental_Num__c);
                //update byr entx 20210728 新品收货_集中备品_建立新品入库标准配套 start
                // for (Integer i = 0; i < robj.Rental_Num__c; i++) {
                for (Integer i = 0; i < robj.Fixture_Set_New_Quantity__c; i++) {
                //update byr entx 20210728 新品收货_集中备品_建立新品入库标准配套 end
                    // sameRAES_objs には自分の明細か、申請 直後の明細しかないか の条件があります。
                    // なので、直接cloneしてOKです。
                    for (ReceivingNoteSummary__c sameRAES_obj : sameRAES_objs) {
                        System.debug(sameRAES_obj);
 
                        // default是 clone, 但是 下面的Logic有对 rupsobj = xxx; 设值的地方
                        ReceivingNoteDetail__c rupsobj = robj.clone(false);
 
                        if (index == 0 && i == 0) {
                            rupsobj = rndfirstMap.get(sameRAES_obj.Id);
                            resetrnd(robj, rupsobj);
                            rupsobj.Is_Body__c = robj.Is_Body__c;
                            rupsobj.Fixture_Set_Detail__c = robj.Fixture_Set_Detail__c;
                            //addby rentx start
                            // rupsobj.Rental_Num__c = robj.Rental_Num__c;
                            rupsobj.Fixture_Set_New_Quantity__c = robj.Fixture_Set_New_Quantity__c;
                            //add by rentx end
                            System.debug('sameRAES_objID ' + sameRAES_obj.Id);
                            System.debug('sameRAES_objF ' + sameRAES_obj.First_RND__c);
                            rupsobj.Id = sameRAES_obj.First_RND__c;
                            rupsobj.passNo3__c = String.valueOf(i+1);
                            mfUpdate.add(rupsobj);
 
                        }
                        else {
                            // 借出申请RequestNoJoinStr2__c:借出申请配套一览Id:配套明细Id
                            String uniqueKeyStr = raObj.Id + ':' + sameRAES_obj.Id
                                    + ':'+ robj.Fixture_Set_Detail__c + ':';
                            String uk = uniqueKeyStr;
                            String passNo3 = String.valueOf(i+1);
                            // default値は最初に設定した
                            if (i < extraInfo.indexFromUniqueKeyList.size()) {
                                // rupsobj.passNo3__c = String.valueOf(extraInfo.indexFromUniqueKeyList[i]);
                                passNo3 = String.valueOf(extraInfo.indexFromUniqueKeyList[i]);
                                uk = uniqueKeyStr + (extraInfo.indexFromUniqueKeyList[i] - 1);
                                uniqueKeyStr += passNo3;
                            } else if (extraInfo.maxIndexFromUniqueKey != null) {
                                if (maxIndexInLoop == null) { maxIndexInLoop = extraInfo.maxIndexFromUniqueKey; }
                                maxIndexInLoop++;
                                uniqueKeyStr = raObj.Id + ':' + sameRAES_obj.Id
                                        + ':'+ robj.Fixture_Set_Detail__c + ':'+ maxIndexInLoop;
                                uk = raObj.Id + ':' + sameRAES_obj.Id
                                        + ':'+ robj.Fixture_Set_Detail__c + ':'+ (maxIndexInLoop - 1);
                                // rupsobj.passNo3__c = String.valueOf(maxIndexInLoop);
                                passNo3 = String.valueOf(maxIndexInLoop);
                            } else {
                                // uniqueKeyStr に default の passNo3__c を使う
                                uk = uniqueKeyStr + String.valueOf(i);
                                uniqueKeyStr += passNo3;
                            }
 
                            if (rndMapSet.get(sameRAES_obj.Id).containsKey(uniqueKeyStr)) {
                                rupsobj = rndMapSet.get(sameRAES_obj.Id).get(uniqueKeyStr).clone(false);
 
                            }
                            else if (rndMapSet.get(sameRAES_obj.Id).containsKey(uk)) {
                                rupsobj = rndMapSet.get(sameRAES_obj.Id).get(uk).clone(false);
                            }
                            else if (i == 0) {
                                rupsobj.DataConfirmation__c = false;
                                rupsobj.EquipmentSet_Managment_Code__c = null;
                                rupsobj.Salesdepartment__c = null;
                                rupsobj.SalesProvince__c = null;
                                rupsobj.Product_category__c = null;
                                rupsobj.Equipment_Type__c = null;
                                rupsobj.Manage_type__c = null;
                                rupsobj.unknow_serial_NO_product__c = null;
                                rupsobj.Loaner_accsessary__c = null;
                            }
                            rupsobj.Is_Body__c = robj.Is_Body__c;
                            rupsobj.Fixture_Set_Detail__c = robj.Fixture_Set_Detail__c;
                            //add by rentx start
                            // rupsobj.Rental_Num__c = robj.Rental_Num__c;
                            rupsobj.Fixture_Set_New_Quantity__c = robj.Fixture_Set_New_Quantity__c;
                            //add by rentx end
                            resetrnd(robj, rupsobj);
 
                            if (String.isNotBlank(passNo3)) {
                                rupsobj.passNo3__c = passNo3;
                            }
                            else {
                                rupsobj.passNo3__c = String.valueOf(i+1);
                            }
                            rupsobj.Id = null;
                            System.debug(uniqueKeyStr);
                            System.debug(rupsobj.Id);
                            System.debug(rupsobj.passNo3__c + '测试uniqueKeyStr:' + uniqueKeyStr);
                            rupsobj.UniqueKey__c          = uniqueKeyStr;
                            rndMapSet.get(sameRAES_obj.Id).put(uniqueKeyStr, rupsobj);
                            // 配套(or 申请)·から
                            rupsobj.ReceivingNoteSummary__c = sameRAES_obj.Id;
 
                            // rupsobj.ReceivingNote__c               = sameRAES_obj.ReceivingNote__c;
 
                            mfUpsert.add(rupsobj);
                            if (setIdFirstDetailMap.containsKey(sameRAES_obj.Id) == false || rupsobj.Is_Body__c == true) {
                                setIdFirstDetailMap.put(sameRAES_obj.Id, rupsobj);
                            }
                            if (String.isBlank(rupsobj.Id)
                                    && !String.isBlank(uniqueKeyStr)) {
                                // IdあるのレコードをIdクリアSetに追加
                                clearUniqueKeySet.add(uniqueKeyStr);
                            }
                        }
                    }
                }
                index ++;
            }
            System.debug(mfUpsert);
            if (mfUpsert.isEmpty() && mfUpdate.isEmpty()) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                        '请输入明细的数量。'));
                return null;
            }
            else {
                if (isAcceptance) {
                    Set<String> fsdIdSet = new Set<String>();
                    List<ReceivingNoteDetail__c> rndList = [SELECT Id
                                , UniqueKey__c
                                , AcceptanceResult__c
                                , Fixture_Set_Detail__c
                                , Change_Point__c
                                , ReceivingNoteSummary__c
                                , Manage_type__c
                             FROM ReceivingNoteDetail__c
                            WHERE ReceivingNoteSummary__c IN :sidList
                              AND Delete_Flag__c = false];
                    Map<String, ReceivingNoteDetail__c> rndMap = new Map<String, ReceivingNoteDetail__c>();
                    for (ReceivingNoteDetail__c rnd : rndList) {
                        rndMap.put(rnd.UniqueKey__c, rnd);
                        if (String.isNotBlank(rnd.Fixture_Set_Detail__c)
                            && rnd.Change_Point__c != '新建') {
                            fsdIdSet.add(''+rnd.ReceivingNoteSummary__c+rnd.Fixture_Set_Detail__c);
                        }
                    }
                    for (ReceivingNoteDetail__c rnd : mfUpsert) {
                        if (rndMap.containsKey(rnd.UniqueKey__c)) {
                            if (rndMap.get(rnd.UniqueKey__c).Change_Point__c == '删除') {
                                rnd.Change_Point__c = '';
                            }
                        }
                        else {
                            if (fsdIdSet.contains(''+rnd.ReceivingNoteSummary__c+rnd.Fixture_Set_Detail__c)) {
                                rnd.Change_Point__c = '增加';
                            }
                            else {
                                rnd.Change_Point__c = '新建';
                                //rnd.DataConfirmation__c = false;
                                //rnd.EquipmentSet_Managment_Code__c = null;
                                //rnd.Salesdepartment__c = null;
                                //rnd.SalesProvince__c = null;
                                //rnd.Product_category__c = null;
                                //rnd.Equipment_Type__c = null;
                                //rnd.Manage_type__c = null;
                                //rnd.unknow_serial_NO_product__c = null;
                                //rnd.Loaner_accsessary__c = null;
 
                            }
                        }
                    }
                }
                //upsert mfUpsert UniqueKey__c;
                // Upsert
                if (mfUpsert.size() > 0) {
                    FixtureUtil.withoutUpsertRnd(mfUpsert);
                }
                if (mfUpdate.size() > 0) {
                    FixtureUtil.withoutUpdate(mfUpdate);
                }
 
                // 削除
                FixtureUtil.delRND_excludedUpserted(sameRAES_objs, mfUpsert, mfUpdate, isAcceptance);
                // System.debug('备品配套借出一览明细保存成功');
                // for (ReceivingNoteSummary__c sameRAES_obj: sameRAES_objs) {
                //     ReceivingNoteDetail__c rupsobj = setIdFirstDetailMap.get(sameRAES_obj.Id);
                //     sameRAES_obj.First_RND__c = rupsobj.Id;
                // }
                //update sameRAES_objs;
                // FixtureUtil.withoutUpdate(sameRAES_objs);
            }
 
            //申请书的追加附属品状态需
            //因为是申请的状态所以需要要看是不是申请书下所有的追加附属品(不只是这一个一览下的)
            // List<AggregateResult> add_Approvals = [Select Count(Id) cnt, SUM(Draft_Appended__c) Draft_Appended__c
            //         From ReceivingNoteDetail__c
            //        Where ReceivingNote__c = :parentObj.ReceivingNote__c
            //          AND Cancel_Select__c = false
            //          AND Fixture_Set_Detail__c != null
            //          AND ApplyPersonAppended_F__c = true
            //        Group by ReceivingNote__c];
            // Integer Draft_Appended = 0;
            // Integer add_ApprovalCount = 0;
            // if (!add_Approvals.isEmpty()) {
            //     Draft_Appended = add_Approvals[0].get('Draft_Appended__c') == null ? 0 : Integer.valueOf(add_Approvals[0].get('Draft_Appended__c'));
            //     add_ApprovalCount = add_Approvals[0].get('cnt') == null ? 0 : Integer.valueOf(add_Approvals[0].get('cnt'));
            // }
 
            List<ReceivingNote__c> raList = new List<ReceivingNote__c>();
            // 有草案中的追加附属品并且申请书的状态不是草案中,&& 不是分配代替品 的需要改变状态为草案中
            // if (Draft_Appended > 0
            //         && raObj.Add_Approval_Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())
            //         && (raObj.Status__c == FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Yi_Pi_Zhun.ordinal())
            //             || raObj.Status__c == FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Yi_Chu_Ku_Zhi_Shi.ordinal()))
            //         && parentObj.Substitute_Select_Again__c == false) {
            //     raObj.Add_Approval_Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal());
            //     raList.add(raObj);
            // }
            // 申请书单位已经没有草案中的附属品
            // else if (Draft_Appended == 0) {
            //     //没有追加附属品状态为空
            //     if (add_ApprovalCount == 0 && String.isNotBlank(raObj.Add_Approval_Status__c)) {
            //         raObj.Add_Approval_Status__c = '';
            //     }
            //     // 有追加附属品状态为草案中
            //     else if (add_ApprovalCount > 0  && raObj.Add_Approval_Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Yi_Pi_Zhun.ordinal())) {
            //         raObj.Add_Approval_Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Yi_Pi_Zhun.ordinal());
            //     }
            //     raList.add(raObj);
            // }
            if (!raList.isEmpty()) {
                FixtureUtil.withoutUpdate(raList);
            }
            // 更新成功才添加成功信息
            if (haveAdd_ApprovalDelete == true) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, deleteAdd_ApprovalMessages));
 
            }
 
        } catch (Exception ex) {
            System.debug(ex.getStackTraceString());
            ApexPages.addMessages(ex);
            Database.rollback(sp);
            // Id をクリア
            for (ReceivingNoteDetail__c robj : mfUpsert) {
                if (clearUniqueKeySet.contains(robj.UniqueKey__c)) {
                    robj.Id = null;
                }
            }
            return null;
        }
 
        // 因为不能更新sidList所以需要在更新sidList前return
        if (haveAdd_ApprovalDelete == true) {
            return null;
        }
 
        if (saveType == '1') {
            searchOpp();
            saveType = '';
            return null;
        } else if (saveType == '2') {
        // ソート時の変更ある
            myComponentController.getSelectedDataInfo();
            getSqlWhereStr();
            myComponentController.sortTable();
            saveType = '';
            return null;
        } else {
            //借出备品配套明细选择画面
            List<String> uniqStrs = parentId.split(':');
            //画面参数为多个配套明细的UniqueKey__c,同一附属品情况下,一括设定该备品配套(group)下的所有借出备品配套明细
            //非同一附属品情况下,依次设定该备品配套所存在的借出备品配套明细的设定
            //判断是否同一附属品
            // if(parentObj.Same_Accessory_flag__c){
                sidList.remove(0);
            // }
            // else{
            //     system.debug('●●●●● uniqStrs  ' + uniqStrs );
 
            //     String tempSize = uniqStrs.get(uniqStrs.size()-1);
            //     // 分配代替品画面
            //     if (parentObj.Substitute_Select_Again__c) {
            //         tempSize = tempSize.substring(0, 1);
            //     }
 
            //     if(Integer.valueOf(tempSize) < parentObj.Rental_Num__c){
            //         List<String> uniqStrsTemp = new List<String> ();
            //         uniqStrsTemp.addall(uniqStrs);
            //         uniqStrsTemp.remove(uniqStrsTemp.size()-1);
            //         Integer currObjBan = Integer.valueOf(tempSize);
            //         uniqStrsTemp.add( (currObjBan + 1) + '');
            //         String uniqStrsNew = String.join(uniqStrsTemp, ':');
            //         sidList.set(0, uniqStrsNew);
            //     }else{
            //         sidList.remove(0);
            //     }
 
            // }
 
            // if (sidList.size() > 0) {
            //     String chkIdsStr = String.join(sidList, ',');
            //     PageReference pg = new PageReference('/apex/RentalFixtureSetDetilSelect');
            //     pg.getParameters().put('sids',chkIdsStr);
            //     pg.setRedirect(true);
            //     return pg;
            // } else {
                String returl1 = '/apex/ReceivingNoteWaitingReceipt?parId='+ parentObj.ReceivingNote__c;
                if (isAcceptance) {
                    returl1 = returl;
                }
                // 借出申请页面
                PageReference pg = new PageReference(returl1);
                pg.setRedirect(true);
                return pg;
            // }
        }
    }
 
    /**
     * メッセージ追加
     * @param robj 借出备品配套明细选择画面里显示的明细
     * @param rupsobj 实际需要Upsert的明细
    */
    private void resetrnd(ReceivingNoteDetail__c robj, ReceivingNoteDetail__c rupsobj) {
        // 配套入库产品
        rupsobj.Set_Arrival_Product__c = robj.Fixture_Set_Detail__r.Product2__c;
        if (null == rupsobj.Product_Arrival_Product__c) {
            rupsobj.Product_Arrival_Product__c = rupsobj.Default_Fixture_Arrival_Product__c;
            rupsobj.Product_Arrival_Product__c = rupsobj.Default_Fixture_Arrival_Product__c;
        }
        // 配套后,产品没变则清空
        if (rupsobj.Is_First_RND_F__c
            && rupsobj.Product_Old_Model_F__c == robj.Fixture_Set_Detail__r.Fixture_Model_No_F__c
        ) {
            rupsobj.Fixture_Arrival_Product__c = null;
            rupsobj.Fixture_Arrival_Process__c = null;
            rupsobj.Fixture_Arrival_Product__c = null;
            rupsobj.Fixture_Arrival_Process__c = null;
        }
        // 配套后,产品变了则设为变体
        else if (rupsobj.Is_First_RND_F__c
            && rupsobj.Product_Old_Model_F__c != robj.Fixture_Set_Detail__r.Fixture_Model_No_F__c
        ) {
            rupsobj.Fixture_Arrival_Product__c = robj.Set_Arrival_Product__c;
            rupsobj.Fixture_Arrival_Process__c = '变体';
        }
    }
 
 
    public PageReference cancel() {
        PageReference ret = null;
        if (!String.isBlank(parentObj.ReceivingNote__c)) {
            ret = new PageReference('/apex/ReceivingNoteWaitingReceipt?parId=' + parentObj.ReceivingNote__c);
        }
        return ret;
    }
 
    public PageReference goBack() {
        PageReference ret = null;
        if (isAcceptance) {
            ret = new PageReference(returl);
        }
        else if (!String.isBlank(parentObj.ReceivingNote__c)) {
            ret = new PageReference('/apex/ReceivingNoteSummarySelect?pt_recid=' + parentObj.ReceivingNote__c + '&raesid=' + raesid);
        }
        return ret;
    }
 
    private String makeSoql() {
 
        String soql ='';
        soql += 'where Id != null';
 
        //备品配套下的所有明细
        if (!String.isBlank(this.parentId)) {
system.debug('●●●●● parentObj ' + parentObj );
            soql += ' and Fixture_Set__c = \'' + parentObj.Fixture_Set__c + '\'';
        }
        // soql += ' order by SortInt__c';
        system.debug(soql);
        return soql;
    }
 
    public override void setViewList(List<sObject> queryList) {
        viewList = new List<WrapperInfo>();                             // selectedGroupData と同じ順番、同じ件数
        extraInfoList = new List<LineExtraInfo>();  // viewList と同じ順番、同じ件数
        Set<Id> selectedFSDSet = new Set<Id>();
        // 選択済みの明细
        if (selectedData.size() > 0) {
            selectedGroupData = new List<ReceivingNoteDetail__c>();
            Map<Integer, ReceivingNoteDetail__c> sltFixtureMap = new Map<Integer, ReceivingNoteDetail__c>();
            Map<Integer, Integer> sltFixtureCnt = new Map<Integer, Integer>();
            Map<Integer, LineExtraInfo> sltExtraInfoMap = new Map<Integer, LineExtraInfo>();
            // グループリスト取得
            // group by Fixture_Set_Detail__c
            // order by Fixture_Set_Detail__r.SortInt__c
            for (SObject sobj : selectedData) {
                ReceivingNoteDetail__c raesdobj = (ReceivingNoteDetail__c) sobj;
                //设置新品配套数 by rentx 20210825 start 
                raesdobj.Fixture_Set_New_Quantity__c = raesdobj.Fixture_Set_Detail__r.Fixture_Set_New_Quantity__c;
                //设置新品配套数 by rentx 20210825 end
                //之前数量的逻辑不要了  直接取备品配套明细上的数量就可以 add by rentx 20210827 start
                raesdobj.Rental_Num__c = raesdobj.Fixture_Set_Detail__r.Quantity__c;
                //之前数量的逻辑不要了  直接取备品配套明细上的数量就可以 add by rentx 20210827 end 
 
 
                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);
                        selectedGroupData.add(raesdobj);
                        sltFixtureCnt.put(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue(), 0);
                        LineExtraInfo extraInfo = new LineExtraInfo(raesdobj);
                        extraInfoList.add(extraInfo);
                        sltExtraInfoMap.put(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue(), extraInfo);
                    }
                // } else {
                //     LineExtraInfo extraInfo = sltExtraInfoMap.get(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue());
                //     extraInfo.updateExtraInfo(raesdobj);
                // }
                // if (raesdobj.Cancel_Select__c) {
                //     // 念のため追加した
                //     continue;
                // }
 
                /*注释 by rentx 20210827   ReceivingNoteDetail__c nobj = sltFixtureMap.get(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue());
                Integer nCnt = sltFixtureCnt.get(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue());
                nCnt++;
                sltFixtureCnt.put(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue(), nCnt);
                nobj.Rental_Num__c = nCnt;
                //nobj.VF_Rental_Num__c = nCnt;*/
                selectedFSDSet.add(raesdobj.Fixture_Set_Detail__c);
            }
            for (Integer i = 0; i < selectedGroupData.size(); i++) {
                // 501を超えた場合前500のみを出す
                if (i >= getSearchNumMax()) { break; }
                ReceivingNoteDetail__c raesdobj = selectedGroupData[i];
                WrapperInfo info = new WrapperInfo(raesdobj, myComponentController);
                //if (String.isNotBlank(raesdobj.RNDAssert__c)) {
                    // info.canEdit = false;
                //}
                viewList.add(info);
                viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
                raesdobj.passNo2__c = raesdobj.Fixture_Set_Detail__r.SortInt__c.format().leftpad(2, '0');
            }
        }
        if (queryList.size() == 0) {
            return;
        }
 
        Savepoint sp = Database.setSavepoint();
        ReceivingNoteDetail__c rnd;
        // 数式項目値を取れるのために、一回Insertする
        List<ReceivingNoteDetail__c> tempList = new List<ReceivingNoteDetail__c>();
        for (Integer i = 0; i < queryList.size(); i++) {
            // 501を超えた場合前500のみを出す
            if (i == getSearchNumMax()) { break; }
            ReceivingNoteDetail__c mf = new ReceivingNoteDetail__c();
            mf.Fixture_Set_Detail__c                = queryList[i].Id;
            Fixture_Set_Detail__c fsdobj            = (Fixture_Set_Detail__c) queryList[i];
            mf.Is_Body__c                           = fsdobj.Is_Body__c;
 
            //设置新品配套数 start 20210825 
            mf.Fixture_Set_New_Quantity__c = fsdobj.Fixture_Set_New_Quantity__c;
            //设置数量
            mf.Rental_Num__c                        = fsdobj.Quantity__c;
            //设置新品配套数 end 20210825 
            /*注释 by rentx 20210827 if (selectedData.size() > 0) {
                fsdobj.Quantity__c = 0;
            } else {
                fsdobj.Quantity__c = fsdobj.Quantity__c == null ? 0 : fsdobj.Quantity__c;
            }*/
            System.debug(fsdobj.Is_Optional__c);
            System.debug(fsdobj.Quantity__c);
            /*if 注释 by rentx 20210827 (fsdobj.Is_Optional__c == false) {
                mf.Rental_Num__c                        = fsdobj.Quantity__c;
                //mf.VF_Rental_Num__c                     = fsdobj.Quantity__c;
                System.debug('aaaaaa');
            }
            else {
                mf.Rental_Num__c                        = 0;
                //mf.VF_Rental_Num__c                     = 0;
                System.debug('bbbbbb');
            }*/
            mf.DataMigration_Flag__c                = true;
            if (viewList.size() == 0
                    && i == 0) {
                mf.Id = sonObj.Id;
                rnd = mf;
            }
            else {
                mf.ReceivingNoteSummary__c        = parentObj.Id;
                mf.ReceivingNote__c                      = parentObj.ReceivingNote__c;
                tempList.add(mf);
            }
        }
 
        if (rnd != null) {
            Database.SaveResult[] results = FixtureUtil.withoutupdate(new ReceivingNoteDetail__c[]{rnd}, false);
        }
 
        Database.SaveResult[] results = FixtureUtil.withoutInsert(tempList, false);
 
        final String soqlStr = 'Select {0} {1} ';
        String whereStr = ' FROM ReceivingNoteDetail__c WHERE (ID in: tempList ' + (rnd == null ? '' : ' OR Id = \'' + rnd.Id+ '\'') + ' ) AND Delete_Flag__c = false ';
        String soql = String.format(soqlStr, new String[] {myComponentController.strColumus , whereStr});
        System.debug(soql);
        tempList = Database.query(soql);
        System.debug(tempList);
        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) + ']条 upsert error:' + dmlResult);
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                            '第[' + (i + 1) + ']条 upsert 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(ReceivingNoteDetail__c fsd : tempList){
            ReceivingNoteDetail__c robj;
            if (fsd.Id != sonObj.Id) {
                robj = fsd.clone(false);
            }
            else {
                robj = fsd;
            }
            robj.DataMigration_Flag__c = false;
            //add by rentx 20210825 start 新品配套数赋值
            robj.Fixture_Set_New_Quantity__c = robj.Fixture_Set_Detail__r.Fixture_Set_New_Quantity__c;
            //add by rentx 20210825 end 新品配套数赋值
 
            fsDMap.put(fsd.Fixture_Set_Detail__c, robj);
        }
 
        Integer addedNum = 0;
        Map<Integer, ReceivingNoteDetail__c> sltFixtureMap = new Map<Integer, ReceivingNoteDetail__c>();
        for (Integer i = 0; i < queryList.size(); i++) {
 
            addedNum ++;
            // 501を超えた場合前500のみを出す
            if (addedNum == getSearchNumMax()) { break; }
 
            if (selectedFSDSet.contains(queryList[i].Id)) {
                continue;
            }
 
            SObject mf = fsDMap.get(queryList[i].Id);
            ReceivingNoteDetail__c raesdobj = (ReceivingNoteDetail__c) mf;
            if (!sltFixtureMap.containsKey(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue())) {
                sltFixtureMap.put(raesdobj.Fixture_Set_Detail__r.SortInt__c.intValue(), raesdobj);
                // 2回目以降、設定してない行は0にする
                // if (!selectedData.isEmpty()) {
                // OLY_OCM-404: 选择配套明细里,无论主体还是附属品,都设置默认数量为0。
                // raesdobj.Rental_Num__c    = 0;
                // raesdobj.VF_Rental_Num__c = 0;
                // }
                WrapperInfo info = new WrapperInfo(raesdobj, myComponentController);
                if (viewList.size() == 0) {
                    // info.canEdit = false;
                }
                viewList.add(info);
                extraInfoList.add(new LineExtraInfo(null));
                viewList[viewList.size() - 1].lineNo = viewList.size() - 1;
                raesdobj.passNo2__c = raesdobj.Fixture_Set_Detail__r.SortInt__c.format().leftpad(2, '0');
                //raesdobj.IndexFromUniqueKey_Text__c = viewList.size().format().leftpad(2, '0');
            }
        }
 
system.debug('●●●●● setViewList END ' );
    }
 
 
    public class LineExtraInfo {
        public Integer maxIndexFromUniqueKey;           // { get; set; }
        public List<Decimal> indexFromUniqueKeyList;    // { get; set; }
        public Set<String> raesdUniqueKeySet;           // { get; set; }
 
        // Cancel_Select 処理しない
        public LineExtraInfo(ReceivingNoteDetail__c raesdobj) {
            // maxIndexFromUniqueKey を null にする
            raesdUniqueKeySet = new Set<String>();
            indexFromUniqueKeyList = new List<Decimal>();
            if (raesdobj == null || String.isBlank(raesdobj.Id)) {
                // 新規行、空のインスタンスを返す
                return;
            }
            // if (raesdobj.Cancel_Select__c) {
            //     throw new ControllerUtil.myException('raesdobj is Canceled.');
            // }
            // raesdUniqueKeySet.add(raesdobj.UniqueKey__c);
            // indexFromUniqueKeyList.add(raesdobj.passNo3__c);
            // maxIndexFromUniqueKey = raesdobj.passNo3__c.intValue();
        }
 
        // Cancel_Select も処理対象 (maxIndexFromUniqueKeyを更新するために)
        public void updateExtraInfo(ReceivingNoteDetail__c raesdobj) {
            if (raesdobj == null || String.isBlank(raesdobj.Id)
                    || maxIndexFromUniqueKey == null) {
                // 新規行、なにも更新しない
                return;
            }
            // if (raesdUniqueKeySet.contains(raesdobj.UniqueKey__c)) {
            //     return;
            // }
            // if (!raesdobj.Cancel_Select__c) {
            //     raesdUniqueKeySet.add(raesdobj.UniqueKey__c);
            //     indexFromUniqueKeyList.add(raesdobj.passNo3__c);
            // }
            // Integer indexFromUniqueKey = raesdobj.passNo3__c.intValue();
            // if (indexFromUniqueKey > maxIndexFromUniqueKey) {
            //     maxIndexFromUniqueKey = raesdobj.passNo3__c.intValue();
            // }
        }
    }
    public void sendEmail() {
        Savepoint sp = Database.setSavepoint();
        try{
            String emailBody = System.currentPageReference().getParameters().get('emailBody');
            String templateBody = '【自由填写内容】\n{0}\n';
                   templateBody += '备品配套:\n';
            emailBody = String.format(templateBody, new List<String> {emailBody});
            String emailMsg = '';
            List<ReceivingNoteSummary__c> selectedRnsList = [
                    SELECT Id
                         , No_Matching_Reminder_Email_Text__c
                         , Fixture_Set__r.Name
                      FROM ReceivingNoteSummary__c
                     WHERE Id =:parentId
                     FOR UPDATE
                    ];
            for (ReceivingNoteSummary__c rns : selectedRnsList) {
                rns.No_Matching_Reminder_Email_Text__c = null;
            }
            update selectedRnsList;
            for (ReceivingNoteSummary__c rns : selectedRnsList) {
                rns.No_Matching_Reminder_Email_Text__c = emailBody + rns.Fixture_Set__r.Name;
            }
            update selectedRnsList;
            ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.INFO, '已发送');
            ApexPages.addMessage(vfApplyMsg);
        }
        catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addMessages(e);
        }
    }
}