高章伟
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
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
/**
 * 备品配套选择
 */
public with sharing class ConsumFixtureSetSelectController extends CreateRelationListPagingCtrlBase {
    private List<LineExtraInfo> extraInfoList;  // viewList と同じ順番、同じ件数
 
    public String anchorElement {get; set;}
    public override Integer getSearchNumMax() {
        //各ページに制御あれば、最大件数を指定する
        // searchNumMax = Integer.valueOf(Label.Product_Select_Limit);
        //TODO change
        // searchNumMax = 100;
        pagesize = '10000';
        return 10001;
    }
 
    /* 選択されたデータ取得用Soql Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' From Consum_Apply_Equipment_Set__c';
        selectedDataSql += ' where Consum_Apply__c = \'' + String.escapeSingleQuotes(parentId) + '\'';
        selectedDataSql += '   and Cancel_Select__c = False';
        // 跳转分配代替品画面--选中一览不在这里显示
        if (String.isNotBlank(inRaesId)) {
            selectedDataSql += ' and Id = null';
        }
        selectedDataSql += (' order by '
                        //+ 'Fixture_Set__r.Loaner_code__c,'
                        + 'IndexFromUniqueKey__c');
        myComponentController.columnRightRW.put('Model_No__c', 'r');
        myComponentController.columnRightRW.put('You_Xiao_Qi_Ku_Cun_Jia__c', 'r');
        myComponentController.columnRightRW.put('Yi_Guo_Qi_Ku_Cun_Jia__c', 'r');
        myComponentController.columnRightRW.put('You_Xiao_Ku_Cun_Jia__c', 'r');
        myComponentController.columnRightRW.put('Consum_Start_Date__c', 'r');
        for (Integer i = 0; i < myComponentController.titleRight.size(); i ++) {
            System.debug(myComponentController.titleRight[i]);
            if (myComponentController.titleRight[i] == Consum_Apply_Equipment_Set__c.You_Xiao_Ku_Cun_Jia__c.getDescribe().getLabel()) {
                myComponentController.titleRight[i] = '库存';
                break;
            }
        }
        return selectedDataSql;
    }
 
    // 検索元対象オブジェクトAPI名
    public override String getOriginObjName() {
        // オブジェクトAPI名
        originObjName = 'Asset';
        return originObjName;
    }
    public override String getOriginObjColumns() {
        // 項目セット
        originObjColumns =  'Id, Fixture_Model_No_F__c, Consumable_Guaranteen_end__c, You_Xiao_Ku_Cun__c';
        return originObjColumns;
    }
 
    public override String getObjName() {
        // オブジェクトAPI名
        objName = 'Consum_Apply_Equipment_Set__c';
        return objName;
    }
    public override String getColumnLeftFieldSetName() {
        // 左の項目セット
        columnLeftFieldSetName = '';
        return columnLeftFieldSetName;
    }
    public override String getColumnRightFieldSetName() {
        // 右の項目セット
        columnRightFieldSetName = 'ConsumFixtureSetSelect_right';
        return columnRightFieldSetName;
    }
 
    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        return new List<String>{'Id', 'Consum_Apply__c', 'Consum_Apply__r.Status__c', 'Consum_Num__c',
                                //'Fixture_Set__r.Name',
                                'RetalFSetDetail_Cnt__c', 'Model_No__c', 'UniqueKey__c', 'VF_Consum_Num__c', 'Consum_Start_Date_After_15_Day__c'};
    }
    public override List<String> getHiddenFieldList() {
        //return new List<String>{'Substitute_Select_Again__c'};
        return new List<String>();
    }
    // 画面里直接可以输入的項目 List
    public override List<String> getWritableColumnFieldList() {
        return new List<String>{'Consum_Num__c', 'Irreplaceable_flag__c', 'Same_Accessory_flag__c'};
    }
    // getObjName 连 getOriginObjName 的 FK
    public override String getFKColumnField() {
        return '';
    }
 
    public override String getRecordTypeId() {
        //ページレイアウトを収得するのレコードタイプ
        recordTypeId = '';
        return recordTypeId;
    }
 
    // ページコントローラに検索処理は、WhereSoql作成のみ、パラメータとして、コンポーネントに渡される
    public override String getSqlWhereStr() {
        sqlWhereStr = '';
 
        if(getIsNeedRunSearch()){
            sqlWhereStr = this.makeSoql(keywdSort, true);
        }
 
        return sqlWhereStr;
 
    }
    public override String getOrderbyStr() {
        return 'order by Id';
    }
 
    public override Boolean getIsNeedRunSearch() {
        return isReset == false;
    }
 
    public override Boolean getShowRecordCountMSG() {
        return false;
    }
 
    /*****************ソート時再検索条件(画面からの入力条件を無視するため)******************/
    private String keywdSort = null;
    public String keyword { get; set; }
    public String category3 { get; set; }
    public String category4 { get; set; }
 
    public String inRaesId { get; set;}   // 分配代替品传入参数
    public boolean isRadio { get; set;}   // 分配代替品(true)--选择配套画面只能单选
    public List<Consum_Apply_Equipment_Set__c> selectedRaesList { get; set; }   // 选中一览,非ListView显示--分配代替品
    // substituteId 現状 保存 btn 部分refersh ではない、その部分のロジック使われってないです。
    private String substituteId;          // 保存 btn(部分 refersh), 的时候 退避 保存后 借出一览的Id, 画面上选别的行的时候可以拿Id更新
 
    public Boolean saveType { get; set; }
    public Consum_Apply__c parentObj { get; set; }
    public Consum_Apply_Equipment_Set__c caes { get; set; }
    public List<Consum_Apply_Equipment_Set__c> selectedGroupData { get; set; }
 
    private Map<Date, Date> after15DayMap = new Map<Date, Date>(); 
    private Map<Date, OlympusCalendar__c> calendarMap = new Map<Date, OlympusCalendar__c>();
    private Map<String, Integer> excludedModelWherMap = new Map<String, Integer>();
    private Set<String> excludedModelWherSelectSet = new Set<String>();
    private Set<String> resetSet = new Set<String>();
    private Boolean isReset = false;
    // Equipment_Type__c != '检测用备品' 的保佑设备才可以申请
    // BTreeIndexKey__c =
    // Asset_Owner__c
    // Asset_loaner_category__c
    // Freeze_sign_Abandoned_Flag__c
    // Delete_Flag__c
    // AssetManageConfirm__c
    private String assetWhereBase = ' BTreeIndexKey__c = \'Olympus:耗材:false:false:true\' AND Equipment_Type__c != \'检测用备品\' AND Fixture_OneToOne_Link__c = null AND Internal_asset_location__c != null  AND RecordTypeId = \'01210000000kOPR\' AND ' + FixtureUtil.getAssetSoqlBase();
 
    public ConsumFixtureSetSelectController(ApexPages.StandardController stdController) {
        this();
    }
 
    public ConsumFixtureSetSelectController() {
        parentId = ApexPages.currentPage().getParameters().get('pt_recid');
        inRaesId = ApexPages.currentPage().getParameters().get('raesid');
        isRadio = String.isBlank(this.inRaesId) ? false : true;   // 分配代替品--选择配套画面只能单选
        String typeTypeStr = ApexPages.currentPage().getParameters().get('saveType');
        if(typeTypeStr == 'true'){
            saveType = true;
        }
        else{
            saveType = false;
        }
        system.debug('==zheli1=='+this.parentId);
        
        caes = new Consum_Apply_Equipment_Set__c();
        caes.Consum_Start_Date__c = Date.today();
        //备品配套下的所有明细
        if (!String.isBlank(this.parentId)) {
            List<Consum_Apply__c> parentObjs = [
                    SELECT Id
                         , Name
                         , Status__c
                         , RequestNoJoinStr2__c
                         , demo_purpose2__c
                         , Internal_asset_location_F__c
                         , Salesdepartment__c
                         , Person_In_Charge__c
                         , Salesdept__c
                         , WorkPlace__c
                         , Request_shipping_day__c
                         //, Asset_loaner_start_day__c
                      FROM Consum_Apply__c
                     WHERE Id = :parentId];
            if (parentObjs.size() > 0) {
                parentObj = parentObjs.get(0);
            }
            //Integer aaa=Integer.valueof(parentObjs);
            
        }
 
        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 Consum_Apply_Equipment_Set__c
                    where Id = :inRaesId];
            if (selectedRaesList.size() == 0) {
                throw new ControllerUtil.myException('沒有指定备品借出申请一览或者数据不正。');
            }
        }
    }
 
    public void init() {
        extraInfoList = new List<LineExtraInfo>();  // viewList と同じ順番、同じ件数
        showRecordCountMSG = false;
        searchOppSetParam();
        getSqlWhereStr();
    }
 
    private void searchOppSetParam() {
        keywdSort = keyword;
    }
 
    public PageReference searchOpp() {
        excludedModelWherMap = new Map<String, Integer>();
        excludedModelWherSelectSet = new Set<String>();
        if (viewList != null && viewList.size()>0){
            for(WrapperInfo winfo:viewList){
                if (winfo.check){
                    Consum_Apply_Equipment_Set__c caes = (Consum_Apply_Equipment_Set__c) winfo.sobj;
                    String modelNo = caes.Model_No__c;
                    excludedModelWherMap.put(modelNo, Integer.valueOf(caes.Consum_Num__c));
                }
            }
        }
        if (selectedData.size() > 0) {
            for (SObject sobj : selectedData) {
                Consum_Apply_Equipment_Set__c raesobj = (Consum_Apply_Equipment_Set__c) sobj;
                excludedModelWherSelectSet.add(raesobj.Model_No__c);
            }
        }
        saveType = false;
 
        searchOppSetParam();
 
        if(!getIsNeedRunSearch() && isReset == false){
            return null;
        }
 
        // 選択済みの製品を取得
        myComponentController.getSelectedDataInfo();
 
        getSqlWhereStr();
        // コンポーネントにSoqlを発行して、ページングする
        myComponentController.searchAndPaging();
        isReset = false;
        String message = '按型号汇总后得到 ' + viewList.size() + ' 条数据';
        // message = '<strong style="color:red">' + message + '</strong>';
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, message));
        return null;
    }
 
    // public List<SelectOption> getCategory2Ops() {
    //     return Consum_ApplyUtil.getPlickList('Product2', 'Category2__c');
    // }
 
    // public List<SelectOption> getCategory3Ops() {
    //     return Consum_ApplyUtil.getPlickList('Product2', 'Category3__c');
    // }
 
    public PageReference save() {
 
        //20170906 upsert by UniqueKey__c
        List<Consum_Apply_Equipment_Set__c> mfUpsert = new List<Consum_Apply_Equipment_Set__c>();
        List<Consum_Apply_Equipment_Set__c> mfUpsert1 = new List<Consum_Apply_Equipment_Set__c>(); //存打勾的一览
        List<Consum_Apply_Equipment_Set__c> mfUpsert2 = new List<Consum_Apply_Equipment_Set__c>(); // 存最终保留的一览
        isReset = ApexPages.currentPage().getParameters().get('reset') == 'YES';
        String chkIdsStr = '';
        Savepoint sp = Database.setSavepoint();
        Set<String> clearUniqueKeySet = new Set<String>();
        Map<Id, Consum_Apply_Equipment_Set__c> caesMap = new Map<Id, Consum_Apply_Equipment_Set__c>();
        List<Consum_Apply_Equipment_Set_Detail__c> carsdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
        try {
            List<Consum_Apply__c> raUpdate = [
                    SELECT Id
                         , RequestNoJoinStr2__c
                         , Status__c
                      FROM Consum_Apply__c where Id = :parentId for Update];
            if (raUpdate.isEmpty()) {
                throw new ControllerUtil.myException('没有找到申请单。');
            }
            Set<String> selectAssetIdSet = new Set<String>();
            for (Consum_Apply_Equipment_Set_Detail__c caesd : [SELECT Id, Asset__c
                                                                 FROM Consum_Apply_Equipment_Set_Detail__c
                                                                WHERE Consum_Apply__c = :parentId]
            ) {
                if (String.isNotBlank(caesd.Asset__c)) {
                    selectAssetIdSet.add(caesd.Asset__c);
                }
            }
 
            Boolean haveCheck = false;
            Map<String, Integer> caesCountMap = new Map<String, Integer>();
            for (WrapperInfo wprInfo : viewList) {
                Consum_Apply_Equipment_Set__c robj = (Consum_Apply_Equipment_Set__c) wprInfo.sobj;
                if (wprInfo.check) {
                    if (String.isNotBlank(robj.Id)) {
                        caesCountMap.put(robj.Id , 0);
                    }
                    haveCheck = true;
                    if (isReset) {
                        robj.Consum_Num__c = null;
                        resetSet.add(robj.Model_No__c);
                    }
                }
            }
 
            if (haveCheck == false) {
                throw new ControllerUtil.myException('请选择需要操作的一览');
            }
 
            if (caesCountMap.isEmpty() == false) {
                List<AggregateResult> caesdGroup = [SELECT count(Id) cnt, Consum_Apply_Equipment_Set__c
                         FROM Consum_Apply_Equipment_Set_Detail__c
                        WHERE Consum_Apply_Equipment_Set__c in :caesCountMap.keySet()
                          AND Asset__c != null
                          AND Detail_Finish__c = false
                        GROUP BY Consum_Apply_Equipment_Set__c];
                for (AggregateResult a : caesdGroup) {
                    String carsId = String.valueOf(a.get('Consum_Apply_Equipment_Set__c'));
                    Integer caesdCount = Integer.valueOf(a.get('cnt'));
                    caesCountMap.put(carsId, caesdCount);
                }
            }
 
            Set<String> modelNoSet = new Set<String>();
            // 画面中チェックされた対象、確定ボタンを押下すると、一つずつ順番に明細を選択のため。
            List<WrapperInfo> targetViewList = new List<WrapperInfo>();
            String wher = ' and ( ';
            for (WrapperInfo wprInfo : viewList) {
                Consum_Apply_Equipment_Set__c robj = (Consum_Apply_Equipment_Set__c) wprInfo.sobj;
                // 没打勾的不作为处理对象
                if (wprInfo.check) {
                    if (raUpdate[0].Status__c != '草案中'
                            && robj.Consum_Num__c != robj.VF_Consum_Num__c) {
                        // 0の場合deleteされるので、入力規則がすりぬけるので、ここでもチェックが必要です
                        robj.Consum_Num__c.addError('只有在草案中的状态下可以变更数量');
                        return null;
                    }
                    Integer num = 0;
                    // 如果不是动物实验
                    //2021-04-30 mzy update  备品课题-1577  start
                    if (parentObj.demo_purpose2__c != '动物实验' && parentObj.demo_purpose2__c != 'ET展箱') {
                    //2021-04-30 mzy update  备品课题-1577  end
                        // 如果没有效期库存(有效期为空)
                        if (robj.You_Xiao_Qi_Ku_Cun_Jia__c == null) {
                            num = Integer.valueOf(robj.You_Xiao_Ku_Cun_Jia__c);
                        }
                        else {
                            // 有效期不为空
                            num = Integer.valueOf(robj.You_Xiao_Qi_Ku_Cun_Jia__c);
                        }
                    }
                    else {
                        num = Integer.valueOf(robj.You_Xiao_Ku_Cun_Jia__c);
                    }
                    System.debug(robj.Consum_Num__c);
                    System.debug(robj.VF_Consum_Num__c);
                    System.debug(num);
                    Integer caesdCount = 0;
                    if (String.isNotBlank(robj.Id)) {
                        caesdCount = caesCountMap.get(robj.Id);
                    }
 
                    if (robj.Consum_Num__c != null && (robj.Consum_Num__c - caesdCount) > num) {
                        throw new ControllerUtil.myException('型号' + robj.Model_No__c + '没有足够的有效库存,请重新选择');
                    }
                    if (String.isNotBlank(robj.Id)) {
                        caesMap.put(robj.Id, robj);
                    }
                     mfUpsert1.add(robj);
                    if (robj.Consum_Num__c > 0) {
                        targetViewList.add(wprInfo);
                        mfUpsert.add(robj);
                        // 有数量的不作为删除对象
                        mfUpsert2.add(robj);
                        if (modelNoSet.contains(robj.Model_No__c) == false) {
                            modelNoSet.add(robj.Model_No__c);
                            wher += ' (Fixture_Model_No_F__c like \'%' + String.escapeSingleQuotes(robj.Model_No__c.replaceAll('%', '\\%')) + '%\'';
                            if (parentObj.demo_purpose2__c != '动物实验' && robj.Consum_Start_Date__c != null && parentObj.demo_purpose2__c != 'ET展箱') { //2021-04-30 mzy update  备品课题-1577 
                                System.debug(after15DayMap);
                                System.debug(robj.Consum_Start_Date__c);
                                Date d;
                                if (after15DayMap.containsKey(robj.Consum_Start_Date__c)) {
                                    d = after15DayMap.get(robj.Consum_Start_Date__c);
                                    robj.Consum_Start_Date_After_15_Day__c = d;
                                }
                                else {
                                    d = Consum_ApplyUtil.getWD_addday(robj.Consum_Start_Date__c, 15);
                                    robj.Consum_Start_Date_After_15_Day__c = d;
                                    after15DayMap.put(robj.Consum_Start_Date__c, d);
                                }
                                wher += ' AND (Consumable_Guaranteen_end__c = null OR Consumable_Guaranteen_end__c > ' + String.valueOf(d.year()) + '-' + String.valueOf(d.month()).leftPad(2, '0') + '-' + String.valueOf(d.day()).leftPad(2, '0') + ' )';
                            }
                            wher += ') OR';
                        }
                    }
                }
                else {
                    // 没打勾的不作为删除对象
                    mfUpsert2.add(robj);
                }
            }
 
            if (caesMap.isEmpty() == false) {
                caesMap = new Map<Id, Consum_Apply_Equipment_Set__c>([SELECT Id
                            , Consum_Num__c
                         FROM Consum_Apply_Equipment_Set__c
                        WHERE Id = :caesMap.keySet()
                          FOR UPDATE]);
            }
 
            if (mfUpsert.size() > 0) {
                wher = wher.removeEnd('OR');
                Date day = Date.today();
                Consum_ApplyUtil.withoutUpsert(mfUpsert);
                String soql = 'SELECT Id'
                            + ' , Fixture_Model_No_F__c'
                            + ' , You_Xiao_Ku_Cun__c'
                            + ' FROM Asset'
                            + ' WHERE (Id != null'
                            + wher + ')'
                            + ' AND ' + assetWhereBase
                            + ' )';
                List<String> conditionList = new List<String>();
                conditionList.addAll(selectAssetIdSet);
                Consum_ApplyUtil.withoutQueryListWithConditionList(soql + ' OR Id = :conditionList ' + ' FOR UPDATE', conditionList);
 
                Map<String, List<Asset>> assetMap = new Map<String, List<Asset>>(); //型号->List<Asset>
                Map<String, Integer> assetCountMap = new Map<String, Integer>();  // AssetId->有效库存
                System.debug(soql);
 
                String soqlAssetDepart = soql + ' AND (Salesdepartment__c = \'' + parentObj.Salesdepartment__c + '\''
                                                 + 'OR Salesdepartment__c = \'0.备品中心\')'
                                              +' ORDER BY Salesdepartment__c DESC, Consumable_Guaranteen_end__c nulls LAST';
 
                List<sObject> assetListDepart = Consum_ApplyUtil.withoutQueryList(soqlAssetDepart);
 
                for (sObject sobj : assetListDepart) {
                    Asset ass = (Asset) sobj;
                    if (assetMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                        assetMap.put(ass.Fixture_Model_No_F__c, new List<Asset>());
                    }
                    assetMap.get(ass.Fixture_Model_No_F__c).add(ass);
                    assetCountMap.put(ass.Id, Integer.valueOf(ass.You_Xiao_Ku_Cun__c));
                }
                Integer g = 0;
                for (Consum_Apply_Equipment_Set__c caes : mfUpsert) {
                    LineExtraInfo extraInfo;
                    if (extraInfoList.size() > 0 && g < extraInfoList.size() ) {
                        extraInfo = extraInfoList[g];
                    }
                    Integer maxIndexInLoop = null;
                    Integer maxIndexDeLoop = null;
                    if (assetMap.containsKey(caes.Model_No__c) || caesCountMap.containsKey(caes.Id)) {
                        List<Asset> assList = assetMap.get(caes.Model_No__c);
                        Integer caesdCount = 0;
                        if (String.isNotBlank(caes.Id)
                            && caesCountMap.containsKey(caes.Id)) {
                            caesdCount = caesCountMap.get(caes.Id);
                        }
                        for (Integer i = 0; i < caes.Consum_Num__c; i ++) {
                            Consum_Apply_Equipment_Set_Detail__c carsd = new Consum_Apply_Equipment_Set_Detail__c();
                            carsd.Consum_Apply_Equipment_Set__c = caes.Id;
                            carsd.Consum_Apply__c = parentObj.Id;
                            carsd.IndexFromUniqueKey__c = i+1;
                            carsd.Degree_Of_Importance__c = i+1;
                            if (extraInfo != null) {
                                if (i < extraInfo.indexFromUniqueKeyList.size()) {
                                    carsd.IndexFromUniqueKey__c = extraInfo.indexFromUniqueKeyList[i];
                                } else if (extraInfo.maxIndexFromUniqueKey != null) {
                                    if (maxIndexInLoop == null) { maxIndexInLoop = extraInfo.maxIndexFromUniqueKey; }
                                    maxIndexInLoop++;
                                    carsd.IndexFromUniqueKey__c = maxIndexInLoop;
                                }
 
                                if (i < extraInfo.degree_Of_ImportanceList.size()) {
                                    carsd.Degree_Of_Importance__c = extraInfo.degree_Of_ImportanceList[i];
                                } else if (extraInfo.maxDegree_Of_Importance != null) {
                                    if (maxIndexDeLoop == null) { maxIndexDeLoop = extraInfo.maxDegree_Of_Importance; }
                                    maxIndexDeLoop++;
                                    carsd.Degree_Of_Importance__c = maxIndexDeLoop;
                                }
                            }
                            // 已经有的明细不再设置保有设备
                            if (i >= caesdCount
                                    && (caesMap.containsKey(caes.Id) == false
                                    || (caesMap.containsKey(caes.Id)
                                            && caesMap.get(caes.Id).Consum_Num__c < (i + 1)
                                        )
                                    || String.isBlank(carsd.Asset__c))
                                ) {
                                // carsd.Degree_Of_Importance__c = i + 1;
                                Boolean haveass = false;
                                for (Asset ass : assList) {
                                    if (assetCountMap.get(ass.Id) > 0) {
                                        carsd.Asset__c = ass.Id;
                                        assetCountMap.put(ass.Id, assetCountMap.get(ass.Id) - 1);
                                        haveass = true;
                                        break;
                                    }
                                }
                                if (haveass == false) {
                                    throw new ControllerUtil.myException('型号' + caes.Model_No__c + '没有足够的有效库存,请重新选择');
                                }
                            }
                            System.debug(carsd.Degree_Of_Importance__c);
                            carsd.UniqueKey__c = parentObj.RequestNoJoinStr2__c + ':'+ caes.Id + ':' + caes.Model_No__c + ':' + carsd.Degree_Of_Importance__c;
                            carsdList.add(carsd);
                        }
                    }
                    else {
                        throw new ControllerUtil.myException('型号' + caes.Model_No__c + '没有有效库存,请重新选择');
                    }
                    g ++;
                }
                if (carsdList.size() > 0) {
                    Consum_ApplyUtil.withoutUpsertCaesd(carsdList);
                }
            }
            else {
                if (selectAssetIdSet.size() > 0) {
                    String soql = 'SELECT Id'
                            + ' , Fixture_Model_No_F__c'
                            + ' , You_Xiao_Ku_Cun__c'
                            + ' FROM Asset'
                            + ' WHERE (Id != null'
                            + ' AND ' + assetWhereBase
                            + ' )';
                    List<String> conditionList = new List<String>();
                    conditionList.addAll(selectAssetIdSet);
                    Consum_ApplyUtil.withoutQueryListWithConditionList(soql + ' AND Id = :conditionList ' + ' FOR UPDATE', conditionList);
                }
            }
 
            Consum_ApplyUtil.delCAESD_excludedUpserted(mfUpsert1, carsdList);
            Consum_ApplyUtil.delCAES_excludedUpserted(parentObj, mfUpsert2);
 
            // Rental_Apply_Equipment_Set_Detail__c robj = (Rental_Apply_Equipment_Set_Detail__c) wprInfo.sobj;
            // LineExtraInfo extraInfo = extraInfoList.get(wprInfo.lineNo);
            // Integer maxIndexInLoop = null;
            // for (Integer i = 0; i < robj.Rental_Num__c; i++) {
            //     // sameRAES_objs には自分の明細か、申請 直後の明細しかないか の条件があります。
            //     // なので、直接cloneしてOKです。
            //     for (Rental_Apply_Equipment_Set__c sameRAES_obj : sameRAES_objs) {
            //         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 (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);
            //         }
            //     }
            // }
 
        } catch (Exception ex) {
            ApexPages.addMessages(ex);
            System.debug(ex.getMessage() + ex.getStackTraceString());
            Database.rollback(sp);
            for (Consum_Apply_Equipment_Set__c caes : mfUpsert) {
                if (String.isNotBlank(caes.Id)
                        && caesMap.containsKey(caes.Id) == false
                    ) {
                    caes.Id = null;
                }
            }
            return null;
        }
        if (isReset) {
            Set<String> modelSet = new Set<String>();
            for (WrapperInfo wprInfo : viewList) {
                Consum_Apply_Equipment_Set__c robj = (Consum_Apply_Equipment_Set__c) wprInfo.sobj;
                if (wprInfo.check) {
                    robj.Id = null;
                }
                modelSet.add(robj.Model_No__c);
            }
            Integer selectSize = selectedData.size();
            for (Integer i = selectSize - 1; i >= 0 ; i --) {
                Consum_Apply_Equipment_Set__c raesobj = (Consum_Apply_Equipment_Set__c) selectedData[i];
                if (modelSet.contains(raesobj.Model_No__c)) {
                    selectedData.remove(i);
                }
 
            }
            searchOpp();
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '重置成功'));
            return null;
        }
        PageReference pa = new PageReference('/apex/ConsumFixtureSetSelect?pt_recid=' + parentId);
        pa.getParameters().put('message','保存成功');
        pa.getParameters().put('level','info');
        pa.getParameters().put('saveType','true');
        pa.setRedirect(true);
        // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存成功'));
        return pa;
    }
 
    // /**
    //  * 保存画面上的选择 -- 在非草案中执行,只会根据Id更新
    //  * @param targetViewList 画面上显示的WrapperInfo
    //  * @param mfUpsert 需要更新的一览List -- 保存出错清空ID的时候需要用,所以需要传进来
    //  */
    // private void updateRaesList(List<WrapperInfo> targetViewList, List<Consum_Apply_Equipment_Set__c> mfUpsert) {
    //     Map<String, Consum_Apply_Equipment_Set__c> needUpdateRaesMap = new Map<String, Consum_Apply_Equipment_Set__c>();
    //     for (WrapperInfo wprInfo : targetViewList) {
    //         Consum_Apply_Equipment_Set__c robj = (Consum_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<Consum_Apply_Equipment_Set__c> raess = [SELECT Id, Consum_Apply__c, Fixture_Set__c
    //                                                    FROM Consum_Apply_Equipment_Set__c
    //                                                   WHERE Fixture_Set__c in:needUpdateRaesMap.keySet()
    //                                                     AND Fixture_Set__c != null
    //                                                     AND Consum_Apply__c = :parentId
    //                                                     AND Cancel_Select__c = false
    //                                                     FOR UPDATE];
    //     Map<String, Consum_Apply_Equipment_Set__c> raesMap = new Map<String, Consum_Apply_Equipment_Set__c>();
    //     for (Consum_Apply_Equipment_Set__c raes : raess) {
    //         Consum_Apply_Equipment_Set__c raes1 = needUpdateRaesMap.get(raes.Fixture_Set__c);
    //         Consum_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 PageReference cancel() {
        PageReference ret = null;
        if (!String.isBlank(this.parentId)) {
            ret = new PageReference('/' + this.parentId);
        }
        return ret;
    }
 
    private String makeSoql(String keyword, Boolean islike) {
 
        String soql ='';
        soql += 'where Id != null AND ';
        soql += assetWhereBase;
        // ToDo 以下两个条件是需要的。测试注释
        // if (String.isNotBlank(parentObj.Internal_asset_location_F__c)) {
            soql += ' AND Internal_asset_location__c = \'上海 备品中心\'';
        // }
        if (String.isNotBlank(parentObj.Salesdepartment__c)) {
            soql += ' AND (Salesdepartment__c = \'' + parentObj.Salesdepartment__c + '\' OR Salesdepartment__c = \'0.备品中心\')';
        }
        else {
            soql += ' AND Salesdepartment__c = \'0.备品中心\'';
        }
 
        if (String.isNotBlank(category3)) {
            soql += ' AND Category3__c = \'' + String.escapeSingleQuotes(category3) + '\'';
        }
 
        if (String.isNotBlank(category4)) {
            soql += ' AND Category4__c = \'' + String.escapeSingleQuotes(category4) + '\'';
        }
 
        if (!String.isBlank(keyword)) {
            String[] vals = keyword.split(' ');
            soql += ' and (';
            String fmodelno = '';
            for (String v : vals) {
                // 使用型号进行检索
                if (islike) {
                    fmodelno += ' Fixture_Model_No_F__c like \'%' + String.escapeSingleQuotes(v.replaceAll('%', '\\%')) + '%\' or';
                }
                else {
                    fmodelno += ' Fixture_Model_No_F__c = \'' + String.escapeSingleQuotes(v) + '\' 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 void showMessage() {
        String level = ApexPages.currentPage().getParameters().get('level');
        String message = ApexPages.currentPage().getParameters().get('message');
        if(String.isNotBlank(level) && String.isNotBlank(message)){
            if(level == 'info'){
                ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.INFO, message);
                ApexPages.addMessage(vfApplyMsg);
            }
            else if(level == 'warning'){
                ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.WARNING, message);
                ApexPages.addMessage(vfApplyMsg);
            }
            else if(level == 'error'){
                ApexPages.Message vfApplyMsg = new ApexPages.Message(ApexPages.severity.ERROR, message);
                ApexPages.addMessage(vfApplyMsg);
            }
        }
    }
 
    public override void setViewList(List<sObject> queryList) {
        // 从保存跳转而来时,打印保存成功信息
        if(saveType){
            showMessage();
        }
 
 
        extraInfoList = new List<LineExtraInfo>();  // viewList と同じ順番、同じ件数
        Set<String> modelSet = new Set<String>();
        Map<Consum_ApplyUtil.CUCUNTYPE, Map<String, Integer>> countMap = new Map<Consum_ApplyUtil.CUCUNTYPE, Map<String, Integer>>();
        String wher = '';
        Date td = Date.today();
        selectedGroupData = new List<Consum_Apply_Equipment_Set__c>();
        Map<String, Date> fDateMap = new Map<String, Date>();
        if (selectedData.size() > 0) {
            List<Consum_Apply_Equipment_Set__c> cardList = (List<Consum_Apply_Equipment_Set__c>)selectedData;
            List<Consum_Apply_Equipment_Set_Detail__c> caesdList = [SELECT Id
                        , IndexFromUniqueKey__c
                        , Fixture_Model_No_F__c
                        , Cancel_Select__c
                        , UniqueKey__c
                        , Degree_Of_Importance__c
                     FROM Consum_Apply_Equipment_Set_Detail__c
                    WHERE Consum_Apply_Equipment_Set__c = :cardList
                    ORDER BY Degree_Of_Importance__c];
            Map<String, LineExtraInfo> sltExtraInfoMap = new Map<String, LineExtraInfo>();
            for (Consum_Apply_Equipment_Set_Detail__c caersd : caesdList) {
                if (!sltExtraInfoMap.containsKey(caersd.Fixture_Model_No_F__c)) {
                    if (!caersd.Cancel_Select__c) {
                        LineExtraInfo extraInfo = new LineExtraInfo(caersd);
                        sltExtraInfoMap.put(caersd.Fixture_Model_No_F__c, extraInfo);
                        extraInfoList.add(extraInfo);
                    }
                }
                else {
                    LineExtraInfo extraInfo = sltExtraInfoMap.get(caersd.Fixture_Model_No_F__c);
                    extraInfo.updateExtraInfo(caersd);
                }
            }
            Map<String, Consum_Apply_Equipment_Set__c> subsFixtureMap = new Map<String, Consum_Apply_Equipment_Set__c>();   // 用于存代替分配的一览
            // 20170906 グループリスト取得
            // order by Fixture_Set__c, Fixture_Set__r.Loaner_code__c, IndexFromUniqueKey__c
            Date minDate = Date.newInstance(4000, 12, 31);
            Date maxDate = Date.newInstance(1700, 1, 1);
            Map<Date, OlympusCalendar__c> calendarMap = Consum_ApplyUtil.getOlympusCalendarMAp(minDate, maxDate);
            for (SObject sobj : selectedData) {
                Consum_Apply_Equipment_Set__c raesobj = (Consum_Apply_Equipment_Set__c) sobj;
                modelSet.add(raesobj.Model_No__c);
                selectedGroupData.add(raesobj);
                wher += raesobj.Model_No__c + ' ';
                if (raesobj.Consum_Start_Date__c != null) {
                    if (raesobj.Consum_Start_Date__c > maxDate) {
                        maxDate = raesobj.Consum_Start_Date__c;
                    }
                    if (raesobj.Consum_Start_Date__c < minDate) {
                        minDate = raesobj.Consum_Start_Date__c;
                    }
                }
                if (raesobj.Consum_Start_Date__c != null) {
                    if (calendarMap.containsKey(raesobj.Consum_Start_Date__c)) {
                        fDateMap.put(raesobj.Model_No__c, calendarMap.get(raesobj.Consum_Start_Date__c).After_15_WorkDay__c);
                    }
                    else {
                         fDateMap.put(raesobj.Model_No__c, Consum_ApplyUtil.getWD_addday(raesobj.Consum_Start_Date__c, 15));
                    }
                }
                else {
                    fDateMap.put(raesobj.Model_No__c, td);
                }
                // wher += ') OR';
            }
        }
 
        // 把已勾选的加入
        if(viewList!=null && viewList.size()>0){
            for(WrapperInfo winfo : viewList){
                Consum_Apply_Equipment_Set__c raesobj = (Consum_Apply_Equipment_Set__c) winfo.sobj;
                wher += raesobj.Model_No__c + ' ';
                if (winfo.check && excludedModelWherSelectSet.contains(raesobj.Model_No__c) == false) {
                    selectedGroupData.add(raesobj);
                    if (raesobj.Consum_Start_Date__c != null) {
                        if (calendarMap.containsKey(raesobj.Consum_Start_Date__c)) {
                            fDateMap.put(raesobj.Model_No__c, calendarMap.get(raesobj.Consum_Start_Date__c).After_15_WorkDay__c);
                        }
                        else {
                             fDateMap.put(raesobj.Model_No__c, Consum_ApplyUtil.getWD_addday(raesobj.Consum_Start_Date__c, 15));
                        }
                    }
                    else {
                        fDateMap.put(raesobj.Model_No__c, td);
                    }
                }
            }
        }
        viewList = new List<WrapperInfo>();
        if (selectedGroupData.size() > 0) {
            category3 = '';
            category4 = '';
            // wher = wher.removeEnd('OR');
            String soql = 'SELECT Id'
                                + ' , Fixture_Model_No_F__c'
                                + ' , You_Xiao_Ku_Cun__c'
                                + ' , Consumable_Guaranteen_end__c'
                            + ' FROM Asset '
                            + makeSoql(wher, true)
                             + ' FOR UPDATE';
                             System.debug(soql);
            List<Asset> assList = Consum_ApplyUtil.withoutQueryList(soql);
            countMap = Consum_ApplyUtil.getAssetKucun(assList, fDateMap);
            for (SObject sobj : selectedGroupData) {
                Consum_Apply_Equipment_Set__c raesobj = (Consum_Apply_Equipment_Set__c) sobj;
                System.debug(countMap);
                if (countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_QI_Ku_Cun).containsKey(raesobj.Model_No__c)) {
                    raesobj.You_Xiao_Qi_Ku_Cun_Jia__c     = countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_QI_Ku_Cun).get(raesobj.Model_No__c);
                    raesobj.Yi_Guo_Qi_Ku_Cun_Jia__c       = countMap.get(Consum_ApplyUtil.CUCUNTYPE.Yi_Guo_Qi_Ku_Cun).get(raesobj.Model_No__c);
                }
                raesobj.You_Xiao_Ku_Cun_Jia__c        = countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_Ku_Cun).get(raesobj.Model_No__c);
                raesobj.Consum_Num__c = raesobj.RetalFSetDetail_Cnt__c;
                raesobj.VF_Consum_Num__c = raesobj.RetalFSetDetail_Cnt__c;
                if (excludedModelWherMap.containsKey(raesobj.Model_No__c)) {
                    raesobj.Consum_Num__c = excludedModelWherMap.get(raesobj.Model_No__c);
                    raesobj.VF_Consum_Num__c = raesobj.Consum_Num__c;
                }
                if (resetSet.contains(raesobj.Model_No__c)) {
                    raesobj.Consum_Num__c = null;
                    raesobj.VF_Consum_Num__c = raesobj.Consum_Num__c;
                    raesobj.Consum_Start_Date__c = null;
                }
                if (viewList.size() >= 500) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '画面最大只能显示500种型号的备品,请设置检索条件后重试'));
                    return ;
                }
                viewList.add(new WrapperInfo(raesobj, 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(raesobj.Substitute_Select_Again__c));
                // if (raesobj.You_Xiao_Ku_Cun_Jia__c == 0
                //         || (parentObj.demo_purpose2__c != '动物实验'
                //                 && (raesobj.You_Xiao_Qi_Ku_Cun_Jia__c == null
                //                         || raesobj.You_Xiao_Qi_Ku_Cun_Jia__c == 0
                //                     )
                //             )
                //     ) {
                //     viewList[viewList.size() - 1].check = false;
                //     viewList[viewList.size() - 1].oldCheck = false;
                //     // viewList[viewList.size() - 1].canEdit = false;
                // }
            }
        }
        if (queryList.size() == 0) {
            return;
        }
 
        // 数式項目値を取れるのために、一回Insertする
        Map<String, Integer> assetyouxiaoqiMap = new Map<String, Integer>();
        Map<String, Integer> assetguoqiMap = new Map<String, Integer>();
        Map<String, Integer> assetyouxiaoMap = new Map<String, Integer>();
        Date tod = Date.today();
        if (caes.Consum_Start_Date__c != null) {
            tod = caes.Consum_Start_Date__c;
        }
        Date tod15 = Date.today();
        Date todb22;
        if (calendarMap.containsKey(tod) == false) {
            calendarMap.putAll(Consum_ApplyUtil.getOlympusCalendarMAp(tod, tod));
        }
        //2021-04-30 mzy update  备品课题-1577   start
        if (parentObj.demo_purpose2__c != '动物实验' && parentObj.demo_purpose2__c != 'ET展箱' ) {
        //2021-04-30 mzy update  备品课题-1577   end
            if (calendarMap.containsKey(tod) && calendarMap.get(tod).After_15_WorkDay__c != null) {
                tod15 = calendarMap.get(tod).After_15_WorkDay__c;
            }
            else {
                tod15 = Consum_ApplyUtil.getWD_addday(tod, 15);
            }
        }
        if (calendarMap.containsKey(tod) && calendarMap.get(tod).Before_22_WorkDay__c != null) {
            todb22 = calendarMap.get(tod).Before_22_WorkDay__c;
        }
        else {
            todb22 = Consum_ApplyUtil.getWD_addday(tod, -22);
        }
        for (Integer i = 0; i < queryList.size(); i++) {
            Asset ass = (Asset)queryList[i];
            if(excludedModelWherMap.containsKey(ass.Fixture_Model_No_F__c)){
                continue;
            }
            if (assetyouxiaoMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                assetyouxiaoMap.put(ass.Fixture_Model_No_F__c, 0);
            }
            if (ass.Consumable_Guaranteen_end__c != null) {
                if (assetyouxiaoqiMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                    assetyouxiaoqiMap.put(ass.Fixture_Model_No_F__c, 0);
                    assetguoqiMap.put(ass.Fixture_Model_No_F__c, 0);
                }
                if (ass.Consumable_Guaranteen_end__c > tod15) {
                    assetyouxiaoqiMap.put(ass.Fixture_Model_No_F__c, assetyouxiaoqiMap.get(ass.Fixture_Model_No_F__c) + Integer.valueOf(ass.You_Xiao_Ku_Cun__c));
                }
                else {
                    assetguoqiMap.put(ass.Fixture_Model_No_F__c, assetguoqiMap.get(ass.Fixture_Model_No_F__c) + Integer.valueOf(ass.You_Xiao_Ku_Cun__c));
                }
            }
            assetyouxiaoMap.put(ass.Fixture_Model_No_F__c, assetyouxiaoMap.get(ass.Fixture_Model_No_F__c) + Integer.valueOf(ass.You_Xiao_Ku_Cun__c));
        }
        List<Consum_Apply_Equipment_Set__c> tempList = new List<Consum_Apply_Equipment_Set__c>();
        Integer j = 0;
        for (String key : assetyouxiaoMap.keySet()) {
            if (modelSet.contains(key)) {
                continue;
            }
            // 501を超えた場合前500のみを出す
            if (j == getSearchNumMax()) { break; }
            Consum_Apply_Equipment_Set__c mf = new Consum_Apply_Equipment_Set__c();
            mf.Consum_Apply__c               = parentId;
            mf.You_Xiao_Qi_Ku_Cun_Jia__c     = assetyouxiaoqiMap.get(key);
            mf.Yi_Guo_Qi_Ku_Cun_Jia__c       = assetguoqiMap.get(key);
            mf.You_Xiao_Ku_Cun_Jia__c        = assetyouxiaoMap.get(key);
            mf.Model_No__c                   = key;
            mf.DataMigration_Flag__c         = true;
            mf.Consum_Start_Date__c          = tod;
            mf.Consum_Can_Request_approval_Date__c = todb22;
 
            tempList.add(mf);
            j ++;
        }
        calAfter15Day(tod);
 
        // Database.SaveResult[] results = FixtureUtil.withoutInsert(tempList, false);
        // final String soqlStr = 'Select {0} {1} ';
        // String whereStr = ' FROM Consum_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(Consum_Apply_Equipment_Set__c fsd : tempList){
            Consum_Apply_Equipment_Set__c robj = fsd.clone(false);
            // 根据OLY_OCM-404的需求设置默认数量为1
            robj.Consum_Num__c = null;
            robj.VF_Consum_Num__c = null;
            robj.DataMigration_Flag__c = false;
            fsDMap.put(fsd.Model_No__c, robj);
        }
 
        Integer addedNum = 0;
        for (Integer i = 0; i < tempList.size(); i++) {
            addedNum ++;
            // 501を超えた場合前500のみを出す
            if (addedNum == getSearchNumMax()) { break; }
            Consum_Apply_Equipment_Set__c mf = (Consum_Apply_Equipment_Set__c) fsDMap.get(tempList[i].Model_No__c);
            extraInfoList.add(new LineExtraInfo(null));
            if(excludedModelWherMap.containsKey(mf.Model_No__c)){
                continue;
            }
            if (viewList.size() >= 500) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '画面最大只能显示500种型号的备品,请设置检索条件后重试'));
                return ;
            }
            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));
            //2021-04-30 mzy update  备品课题-1577  
            if (parentObj.demo_purpose2__c != '动物实验' && parentObj.demo_purpose2__c != 'ET展箱') {
                if (mf.You_Xiao_Ku_Cun_Jia__c == 0
                        || (mf.You_Xiao_Qi_Ku_Cun_Jia__c != null
                                && mf.You_Xiao_Qi_Ku_Cun_Jia__c <= 0
                           )
                ) {
                    viewList[viewList.size() - 1].canEdit = false;
                }
            }
            else if (mf.You_Xiao_Ku_Cun_Jia__c <= 0) {
                viewList[viewList.size() - 1].canEdit = false;
            }
        }
    }
 
    private Date calAfter15Day(Date d){
        if(!calendarMap.containsKey(d)){
            calendarMap.putAll(Consum_ApplyUtil.getOlympusCalendarMAp(d, d));
        }
        Date d1 = d;
        if (calendarMap.containsKey(d) && calendarMap.get(d).After_15_WorkDay__c != null) {
            d1 = calendarMap.get(d).After_15_WorkDay__c;
        }
        else {
            d1 = Consum_ApplyUtil.getWD_addday(d, 15);
        }
        if (after15DayMap.containsKey(d) == false) {
            after15DayMap.put(d, d1);
        }
        return d1;
    }
 
 
    public void reSetYouXiaoKuCun() {
        Savepoint sp = Database.setSavepoint();
        try {
            String index = ApexPages.currentPage().getParameters().get('index');
            String dateStr = ApexPages.currentPage().getParameters().get('date');
            if (caes.Consum_Start_Date__c != null) {
                Date today = Date.Today();                                   // 运行当天
                Date inputDate = caes.Consum_Start_Date__c; // 手填的预计使用日
                Date inputDate15 = calAfter15Day(inputDate);                 // 预计使用日后15个工作日
                // ToDo 谁说过动物实验时用今天计算有效期数量的?
                //2021-04-30  mzy  udpate 备品课题-1577  start                
                //Date dateForCompare = parentObj.demo_purpose2__c == '动物实验' ? today : inputDate15;
                Date dateForCompare = null;
                if(parentObj.demo_purpose2__c == '动物实验' || parentObj.demo_purpose2__c == 'ET展箱' ){
                    dateForCompare = today;
                }else {
                    dateForCompare = inputDate15;
                }        
                //2021-04-30  mzy update 备品课题-1577  end         
                Map<String, WrapperInfo> infoMap = new Map<String, WrapperInfo>();
                List<Consum_Apply_Equipment_Set__c> caesList = new List<Consum_Apply_Equipment_Set__c>();
                for (WrapperInfo info : viewList) {
                    if (info.check) {
                        Consum_Apply_Equipment_Set__c caes = (Consum_Apply_Equipment_Set__c)info.sobj;
                        if (String.isNotBlank(caes.Id)) {
                            caes.Consum_Num__c = 0;
                            caesList.add(caes);
                        }
                        caes.You_Xiao_Qi_Ku_Cun_Jia__c = null;
                        caes.Yi_Guo_Qi_Ku_Cun_Jia__c = null;
                        caes.You_Xiao_Ku_Cun_Jia__c = 0;
                        infoMap.put(caes.Model_No__c, info);
                    }
                }
                Consum_ApplyUtil.delCAESD_excludedUpserted(caesList, new List<Consum_Apply_Equipment_Set_Detail__c>());
                FixtureUtil.withoutDelete(caesList);
                // String model = '%' + String.escapeSingleQuotes(caes.Model_No__c.replaceAll('%', '\\%')) + '%';
                String soql = ' SELECT Id'
                        + ' , Fixture_Model_No_F__c'
                        + ' , Consumable_Guaranteen_end__c'
                        + ' , You_Xiao_Ku_Cun__c'
                     + ' FROM Asset '
                     + makeSoql(null, false);
                List<String> conditionList = new List<String>();
                conditionList.addAll(infoMap.keySet());
                soql += ' and Fixture_Model_No_F__c = :conditionList ';
                    // + ' WHERE ' + assetWhereBase
                    //   + ' AND Fixture_Model_No_F__c like \'%' + String.escapeSingleQuotes(caes.Model_No__c.replaceAll('%', '\\%')) + '%\'';
                System.debug(soql);
                System.debug(conditionList);
                List<Asset> assList = Consum_ApplyUtil.withoutQueryListWithConditionList(soql, conditionList);
                Map<String, List<Asset>> assMap = new Map<String, List<Asset>>();
                for (Asset ass : assList) {
                    if (assMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                        assMap.put(ass.Fixture_Model_No_F__c, new List<Asset>());
                    }
                    assMap.get(ass.Fixture_Model_No_F__c).add(ass);
                }
                System.debug(assList);
                for (String key : assMap.keySet()) {
                    Consum_Apply_Equipment_Set__c caes = (Consum_Apply_Equipment_Set__c)infoMap.get(key).sobj;
                    for (Asset ass : assMap.get(key)) {
                        if (ass.Consumable_Guaranteen_end__c != null) {
                            if (caes.You_Xiao_Qi_Ku_Cun_Jia__c == null) {
                                caes.You_Xiao_Qi_Ku_Cun_Jia__c = 0;
                                caes.Yi_Guo_Qi_Ku_Cun_Jia__c = 0;
                            }
                            if (ass.Consumable_Guaranteen_end__c > dateForCompare) {
                                caes.You_Xiao_Qi_Ku_Cun_Jia__c += ass.You_Xiao_Ku_Cun__c;
                            }
                            if (ass.Consumable_Guaranteen_end__c <= dateForCompare) {
                                caes.Yi_Guo_Qi_Ku_Cun_Jia__c += ass.You_Xiao_Ku_Cun__c;
                            }
                        }
                        caes.You_Xiao_Ku_Cun_Jia__c += ass.You_Xiao_Ku_Cun__c;
                    }
                     if (calendarMap.containsKey(inputDate) && calendarMap.get(inputDate).Before_22_WorkDay__c != null) {
                         caes.Consum_Can_Request_approval_Date__c = calendarMap.get(inputDate).Before_22_WorkDay__c;
                    }
                    else {
                        caes.Consum_Can_Request_approval_Date__c = Consum_ApplyUtil.getWD_addday(inputDate, -22);
                    }
                }
                // for (Asset ass : assList) {
                //     if (ass.Consumable_Guaranteen_end__c != null) {
                //         if (caes.You_Xiao_Qi_Ku_Cun_Jia__c == null) {
                //             caes.You_Xiao_Qi_Ku_Cun_Jia__c = 0;
                //             caes.Yi_Guo_Qi_Ku_Cun_Jia__c = 0;
                //         }
                //         if (ass.Consumable_Guaranteen_end__c > dateForCompare) {
                //             caes.You_Xiao_Qi_Ku_Cun_Jia__c += ass.You_Xiao_Ku_Cun__c;
                //         }
                //         if (ass.Consumable_Guaranteen_end__c <= dateForCompare) {
                //             caes.Yi_Guo_Qi_Ku_Cun_Jia__c += ass.You_Xiao_Ku_Cun__c;
                //         }
                //     }
                // }
                for (String key : infoMap.keySet()) {
                    WrapperInfo info = infoMap.get(key);
                    Consum_Apply_Equipment_Set__c caes = (Consum_Apply_Equipment_Set__c)info.sobj;
                    caes.Id = null;
                    caes.Consum_Start_Date__c = inputDate;
                }
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM, '适用成功'));
            }
        }
        catch(Exception e) {
            Database.rollback(sp);
            System.debug(e.getMessage() + e.getStackTraceString());
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
        }
    }
 
    public class LineExtraInfo {
        public Integer maxIndexFromUniqueKey;           // { get; set; }
        public List<Decimal> indexFromUniqueKeyList;    // { get; set; }
        public Integer maxDegree_Of_Importance;           // { get; set; }
        public List<Decimal> degree_Of_ImportanceList;    // { get; set; }
        public Set<String> raesdUniqueKeySet;           // { get; set; }
 
        // Cancel_Select 処理しない
        public LineExtraInfo(Consum_Apply_Equipment_Set_Detail__c raesdobj) {
            // maxIndexFromUniqueKey を null にする
            raesdUniqueKeySet = new Set<String>();
            indexFromUniqueKeyList = new List<Decimal>();
            degree_Of_ImportanceList = 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.IndexFromUniqueKey__c);
            maxIndexFromUniqueKey = raesdobj.IndexFromUniqueKey__c.intValue();
            degree_Of_ImportanceList.add(raesdobj.Degree_Of_Importance__c);
            maxDegree_Of_Importance = raesdobj.Degree_Of_Importance__c.intValue();
        }
 
        // Cancel_Select も処理対象 (maxIndexFromUniqueKeyを更新するために)
        public void updateExtraInfo(Consum_Apply_Equipment_Set_Detail__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.IndexFromUniqueKey__c);
                degree_Of_ImportanceList.add(raesdobj.Degree_Of_Importance__c);
            }
            Integer indexFromUniqueKey = raesdobj.IndexFromUniqueKey__c.intValue();
            if (indexFromUniqueKey > maxIndexFromUniqueKey) {
                maxIndexFromUniqueKey = raesdobj.IndexFromUniqueKey__c.intValue();
            }
 
            Integer degree_Of_Importance = raesdobj.Degree_Of_Importance__c.intValue();
            if (degree_Of_Importance > maxDegree_Of_Importance) {
                maxDegree_Of_Importance = raesdobj.Degree_Of_Importance__c.intValue();
            }
        }
    }
}