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
/**
 * 备品配套选择
 */
public with sharing class ConsumDefaultSelectController extends CreateRelationListPagingCtrlBase {
    public override Integer getSearchNumMax() {
        //各ページに制御あれば、最大件数を指定する
        // searchNumMax = Integer.valueOf(Label.Product_Select_Limit);
        //TODO change
        // searchNumMax = 100;
        pagesize = '100';
        return searchNumMax;
    }
 
    /* 選択されたデータ取得用Soql Fromから*/
    public override String getSelectedDataSql() {
        // オブジェクトAPI名
        selectedDataSql = ' From Consum_Apply_Equipment_Set_Detail__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_Model_No_F__c, Degree_Of_Importance__c';
        myComponentController.columnLeftRW.put('No_Jia__c', 'r');
        myComponentController.columnLeftRW.put('Request_Num_Jia__c', 'r');
        myComponentController.columnLeftRW.put('You_Xiao_Ku_Cun_Jia__c', 'r');
        myComponentController.columnLeftRW.put('You_Xiao_Qi_Ku_Cun_Jia__c', 'r');
        myComponentController.columnLeftRW.put('Yi_Guo_Qi_Ku_Cun_Jia__c', 'r');
        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_Detail__c';
        return objName;
    }
    public override String getColumnLeftFieldSetName() {
        // 左の項目セット
        columnLeftFieldSetName = 'ConsumDefaultSelect_L';
        return columnLeftFieldSetName;
    }
    public override String getColumnRightFieldSetName() {
        // 右の項目セット
        columnRightFieldSetName = 'ConsumDefaultSelect_R';
        return columnRightFieldSetName;
    }
 
    public override List<String> getColumnFieldList() {
        // strColumus 里加 field
        return new List<String>{'Id'
                , 'Consum_Apply__c'
                , 'Consum_Apply__r.Status__c'
                , 'UniqueKey__c'
                , 'SerialNumber__c'
                , 'Consum_Start_Date__c'
                , 'Select_Time__c'
                , 'GroupKey_F__c'
                , 'Asset__c'
                , 'Shipment_request_time2__c'
                , 'Consum_Start_Date_After_15_Day__c'
                , 'Consum_Apply_Equipment_Set__r.Model_No__c'
                , 'Consum_Apply_Equipment_Set__r.Consum_Start_Date__c'
                , 'Consum_Apply_Equipment_Set__r.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 = '';
 
        return sqlWhereStr;
 
    }
    public override String getOrderbyStr() {
        return 'order by Id';
    }
 
    public override Boolean getIsNeedRunSearch() {
        return true;
    }
 
    /*****************ソート時再検索条件(画面からの入力条件を無視するため)******************/
    private String keywdSort = null;
    public String keyword { get; set; }
    public String category2 { get; set; }
    public String category3 { 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更新
    private String wherStr1;
    private static String wherStr;
 
    public String saveType { get; set; }
    public Boolean needOpenPage { get; set; }
    public Consum_Apply__c parentObj { get; set; }
 
    private static String assetWhereBase = ' Delete_Flag__c = False'
             + ' AND Asset_Owner__c = \'Olympus\''
             + ' AND Freeze_sign_Abandoned_Flag__c = False'
             + ' AND Asset_loaner_category__c = \'耗材\''
             + ' AND Equipment_Type__c != \'检测用备品\' '
             + ' AND Fixture_OneToOne_Link__c = null '
             + ' AND Internal_asset_location__c != null '
             + ' AND RecordTypeId = \'01210000000kOPR\'' + ' AND ' + FixtureUtil.getAssetSoqlBase();
 
    public ConsumDefaultSelectController(ApexPages.StandardController stdController) {
        this();
    }
 
    public ConsumDefaultSelectController() {
        parentId = ApexPages.currentPage().getParameters().get('pt_recid');
        inRaesId = ApexPages.currentPage().getParameters().get('raesid');
        savetype = ApexPages.currentPage().getParameters().get('savetype');
        isRadio = String.isBlank(this.inRaesId) ? false : true;   // 分配代替品--选择配套画面只能单选
 
        //备品配套下的所有明细
        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_date__c
                         , Campaign__c
                         , Wei_Assigned_Cnt__c
                         //, Repair__c
                         , Assigned_Not_Shipment__c
                         //, Contract_pdf_updated__c
                      FROM Consum_Apply__c
                     WHERE Id = :parentId];
            if (parentObjs.size() > 0) {
                parentObj = parentObjs.get(0);
                if (String.isBlank(parentObj.Internal_asset_location_F__c)) {
                    throw new ControllerUtil.myException('耗材申请的备品存放地不能为空');
                }
            }
        }
 
        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() {
        searchOppSetParam();
        getSqlWhereStr();
    }
 
    private void searchOppSetParam() {
        keywdSort = keyword;
    }
 
    public PageReference searchOpp() {
        searchOppSetParam();
 
        if(!getIsNeedRunSearch()){
            return null;
        }
 
        // 選択済みの製品を取得
        myComponentController.getSelectedDataInfo();
 
        getSqlWhereStr();
        // コンポーネントにSoqlを発行して、ページングする
        myComponentController.searchAndPaging();
        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>();
        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>();
        try {
 
            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_date__c
                         , Campaign__c
                         , Wei_Assigned_Cnt__c
                         //, Repair__c
                         , Assigned_Not_Shipment__c
                         //, Contract_pdf_updated__c
                      FROM Consum_Apply__c
                     WHERE Id = :parentId
                       FOR UPDATE];
            if (parentObjs.size() > 0) {
                parentObj = parentObjs.get(0);
                if (String.isBlank(parentObj.Internal_asset_location_F__c)) {
                    throw new ControllerUtil.myException('耗材申请的备品存放地不能为空');
                }
            }
            Map<String, Integer> cancelMap = new Map<String, Integer>();
            for (WrapperInfo info : viewList) {
                if (info.check) {
                    Consum_Apply_Equipment_Set_Detail__c caesd = (Consum_Apply_Equipment_Set_Detail__c)info.sobj;
                    if (caesd.Qu_Xiao_Fen_Pei_Shu_Liang_Jia__c != null
                            && caesd.Qu_Xiao_Fen_Pei_Shu_Liang_Jia__c > 0) {
                        // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add start
                        // String key = caesd.GroupKey_F__c;
                        String key = caesd.GroupKey_F__c+caesd.Fixture_Model_No__c;
                        // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add end
                        System.debug(caesd.Consumable_Guaranteen_end_F__c);
                        System.debug(key);
                        if(caesd.Qu_Xiao_Fen_Pei_Shu_Liang_Jia__c>caesd.Jie_Chu_Fen_Pei_Jia__c){
                            throw new ControllerUtil.myException('取消分配数量不可超过已分配数');
                        }
                        cancelMap.put(key, Integer.valueOf(caesd.Qu_Xiao_Fen_Pei_Shu_Liang_Jia__c));
                    }
                }
            }
 
            String soql = 'SELECT Id'
                                + ' , SerialNumber'
                                + ' , Fixture_Model_No_F__c'
                                + ' , You_Xiao_Ku_Cun__c'
                                + ' , Consumable_Guaranteen_end__c'
                                + ' , GroupKey_F__c'
                            + ' FROM Asset'
                           + ' WHERE (Id != null '
                            + wherStr1
                             + ' AND ' + assetWhereBase + ' )';
            System.debug(soql);
            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);
                }
            }
            // 因为保有设备的借出分配数会变,所以需要Lock
            List<String> conditionList = new List<String>();
            conditionList.addAll(selectAssetIdSet);
            Consum_ApplyUtil.withoutQueryListWithConditionList(soql + ' OR Id = :conditionList' + ' FOR UPDATE', conditionList);
 
            List<Consum_Apply_Equipment_Set_Detail__c> carsdList = [SELECT Id
                     FROM Consum_Apply_Equipment_Set_Detail__c
                    WHERE Consum_Apply__c = :parentId
                      AND Cancel_Select__c = False
                      FOR UPDATE];
 
            carsdList = [SELECT Id
                        , Select_Time__c
                        , GroupKey_F__c
                        , Fixture_Model_No__c // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add
                     FROM Consum_Apply_Equipment_Set_Detail__c
                    WHERE Consum_Apply__c = :parentId
                      AND Cancel_Select__c = False
                      AND Select_Time__c != null
                    ORDER BY Degree_Of_Importance__c DESC];
            Map<String, List<Consum_Apply_Equipment_Set_Detail__c>> caesdListMap = new Map<String, List<Consum_Apply_Equipment_Set_Detail__c>>();
            for (Consum_Apply_Equipment_Set_Detail__c caesd : carsdList) {
                // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add start
                String key = caesd.GroupKey_F__c+caesd.Fixture_Model_No__c;
                // if (caesdListMap.containsKey(caesd.GroupKey_F__c) == false) {
                //     caesdListMap.put(caesd.GroupKey_F__c, new List<Consum_Apply_Equipment_Set_Detail__c>());
                // }
                // System.debug(caesd.GroupKey_F__c);
                // caesdListMap.get(caesd.GroupKey_F__c).add(caesd);
                List<Consum_Apply_Equipment_Set_Detail__c> tempCaesdL;
                if(caesdListMap.containsKey(key)){
                    tempCaesdL = caesdListMap.get(key);
                }else{
                    tempCaesdL = new List<Consum_Apply_Equipment_Set_Detail__c>();
                }
                tempCaesdL.add(caesd);                        
                caesdListMap.put(key,tempCaesdL);
                // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add end
            }
            System.debug(caesdListMap);
            List<Consum_Apply_Equipment_Set_Detail__c> caesdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
            for (String key : cancelMap.keySet()) {
                for (Integer i = 0; i < cancelMap.get(key); i ++) {
                    System.debug(key);
                    Consum_Apply_Equipment_Set_Detail__c caesd = caesdListMap.get(key)[i];
                    caesd.Select_Time__c = null;
                    caesd.Asset__c = null;
                    caesdList.add(caesd);
                }
            }
            if (caesdList.size() > 0) {
                FixtureUtil.withoutUpdate(caesdList);
            }
        } catch (Exception ex) {
            ApexPages.addMessages(ex);
            System.debug(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;
        }
        PageReference pa = new PageReference('/apex/ConsumDefaultSelect?pt_recid=' + parentId + '&savetype=1');
        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;
    }
    public void copyNum(){
        for (WrapperInfo info : viewList) {
            if (info.check) {
                Consum_Apply_Equipment_Set_Detail__c caesd = (Consum_Apply_Equipment_Set_Detail__c)info.sobj;
                caesd.Qu_Xiao_Fen_Pei_Shu_Liang_Jia__c = caesd.Jie_Chu_Fen_Pei_Jia__c;
            }
        }
    }
    public override void setViewList(List<sObject> queryList) {
        System.Savepoint sp = Database.setSavepoint();
        try {
 
            viewList = new List<WrapperInfo>();
            Map<Consum_ApplyUtil.CUCUNTYPE, Map<String, Integer>> countMap = new Map<Consum_ApplyUtil.CUCUNTYPE, Map<String, Integer>>();
            if (selectedData.size() > 0) {
                // 20170906 グループリスト取得
                // order by Fixture_Set__c, Fixture_Set__r.Loaner_code__c, IndexFromUniqueKey__c
                // wherStr = '';
                // Date minDate = Date.newInstance(4000, 12, 31);
                // Date maxDate = Date.newInstance(1700, 1, 1);
                // // Map<Date, OlympusCalendar__c> calendarMap = Consum_ApplyUtil.getOlympusCalendarMAp(minDate, maxDate);
                // Map<String, Date> fDateMap = new Map<String, Date>();
                // Date td = Date.today();
                // for (SObject sobj : selectedData) {
                //     Consum_Apply_Equipment_Set_Detail__c caesdobj = (Consum_Apply_Equipment_Set_Detail__c) sobj;
                //     if (modelSet.contains(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c) == false) {
                //         if (String.isBlank(wherStr)) {
                //             wherStr = ' AND (';
                //         }
                //         wherStr += ' (';
                //         wherStr += '(Fixture_Model_No_F__c  = \'' + String.escapeSingleQuotes(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c) + '\'';
                //         Date d1 = caesdobj.Consum_Start_Date_After_15_Day__c == null ? Date.today() : caesdobj.Consum_Start_Date_After_15_Day__c;
                //         wherStr += ' AND Consumable_Guaranteen_end__c >= ' + d1.year() + '-' + String.valueOf(d1.month()).leftPad(2,'0') + '-' + String.valueOf(d1.day()).leftPad(2,'0') + ' )';
                //         wherStr += ' OR Consumable_Guaranteen_end__c = null';
                //         wherStr += ' ) OR';
                //         // key = caesdobj.GroupKey_F__c;
                //         modelSet.add(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c);
                //     }
                // }
 
                // if (String.isNotBlank(wherStr)) {
                //     wherStr = wherStr.removeEnd('OR');
                //     wherStr += ')';
                // }
                // // if (String.isNotBlank(parentObj.Internal_asset_location_F__c)) {
                //     wherStr += ' AND Internal_asset_location__c = \'上海 备品中心\'';
                // // }
                // if (String.isNotBlank(parentObj.Salesdepartment__c)) {
                //     wherStr += ' AND (Salesdepartment__c = \'' + parentObj.Salesdepartment__c + '\' OR Salesdepartment__c = \'0.备品中心\')';
                // }
                // else {
                //     wherStr += ' AND Salesdepartment__c = \'0.备品中心\'';
                // }
 
                // // 检索出保有设备,如果默认分配时间过期的话重新分配
                // String soql = 'SELECT Id'
                //                     + ' , SerialNumber'
                //                     + ' , Fixture_Model_No_F__c'
                //                     + ' , You_Xiao_Ku_Cun__c'
                //                     + ' , Consumable_Guaranteen_end__c'
                //                     + ' , GroupKey_F__c'
                //                 + ' FROM Asset'
                //                + ' WHERE Id != null '
                //                 + wherStr
                //                  + ' AND ' + assetWhereBase;
 
                // System.debug(soql);
                // // 因为保有设备的借出分配数会变,所以需要Lock
                // Database.query(soql + ' FOR UPDATE');
                // List<Asset> assList1 = Database.query(soql +  + ' ORDER BY Salesdepartment__c DESC, Fixture_Model_No_F__c, Consumable_Guaranteen_end__c nulls Last');
                // Map<String, List<AssetBean>> assetMap = new Map<String, List<AssetBean>>();
                // for (Asset ass : assList1) {
                //     if (assetMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                //         assetMap.put(ass.Fixture_Model_No_F__c, new List<AssetBean>());
                //     }
                //     Integer num = ass.You_Xiao_Ku_Cun__c == null ? 0 : Integer.valueOf(ass.You_Xiao_Ku_Cun__c);
                //     assetMap.get(ass.Fixture_Model_No_F__c).add(new AssetBean(ass.Id, num));
                // }
 
                // Boolean haveChangeAss = false;
 
                // List<Consum_Apply_Equipment_Set_Detail__c> caesdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
                // for (SObject sobj : selectedData) {
                //     Consum_Apply_Equipment_Set_Detail__c caesdobj = (Consum_Apply_Equipment_Set_Detail__c) sobj;
                //     // String key;
                //     if (String.isBlank(savetype)) {
                //         if (caesdobj.Select_Time__c == null) {
                //             if (String.isNotBlank(caesdobj.Asset__c)) {
                //                 Date d;
                //                 if (parentObj.demo_purpose2__c != '动物实验' && caesdobj.Consum_Start_Date__c != null) {
                //                     d = caesdobj.Consum_Start_Date_After_15_Day__c;
                //                 }
                //                 else {
                //                     d = td;
                //                 }
                //                 System.debug(d);
                //                 System.debug(caesdobj.Consumable_Guaranteen_end_F__c);
                //                 if (caesdobj.Consumable_Guaranteen_end_F__c == null
                //                         // || caesdobj.Consumable_Guaranteen_end_F__c >= fDateMap.get(key)) {
                //                         || caesdobj.Consumable_Guaranteen_end_F__c >= d
                //                         || parentObj.demo_purpose2__c == '动物实验'
                //                 ) {
                //                     caesdobj.Select_Time__c = Datetime.now();
                //                 }
                //                 else {
                //                     caesdobj.Asset__c = null;
                //                     if (assetMap.containsKey(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c)) {
                //                         for (AssetBean assBean : assetMap.get(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c)) {
                //                             if (assBean.you_Xiao_Ku_Cun > 0) {
                //                                 caesdobj.Asset__c = assBean.assId;
                //                                 caesdobj.Select_Time__c = Datetime.now();
                //                                 assBean.you_Xiao_Ku_Cun -= 1;
                //                                 haveChangeAss = true;
                //                                 break;
                //                             }
                //                         }
                //                     }
                //                 }
                //                 System.debug(caesdobj.Asset__c);
                //                 caesdList.add(caesdobj);
                //             }
                //         }
                //     }
                // }
                // オブジェクトAPI名
                List<Consum_Apply_Equipment_Set_Detail__c> caesdList = new List<Consum_Apply_Equipment_Set_Detail__c>();
                Boolean haveChangeAss = false;
                haveChangeAss = reSetAsset((List<Consum_Apply_Equipment_Set_Detail__c>)selectedData, caesdList, parentObj, true, String.isBlank(savetype));
                if (caesdList.size() > 0) {
                    if (String.isBlank(savetype)) {
                        System.debug(caesdList);
                        Database.SaveResult[] results = FixtureUtil.withoutUpdate(caesdList, false);
                        for (Database.SaveResult sr : results) {
                            if (sr.isSuccess() == false) {
                                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,
                                '明细:' + sr.getId() + ' 自动分配 error:' + sr));
                                Database.rollback(sp);
                                return;
                            }
                        }
                        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '自动分配保存成功'));
                    }
                }
                else if (String.isBlank(savetype)) {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '没有需要自动分配的明细'));
                }
 
                String selectedDataSql1 = ' From Consum_Apply_Equipment_Set_Detail__c';
                selectedDataSql1 += ' where Consum_Apply__c = \'' + String.escapeSingleQuotes(parentId) + '\'';
                selectedDataSql1 += ' and Cancel_Select__c = False';
                // 跳转分配代替品画面--选中一览不在这里显示
                if (String.isNotBlank(inRaesId)) {
                    selectedDataSql1 += ' and Id = null';
                }
                selectedDataSql1 += ' order by Fixture_Model_No_F__c, Consumable_Guaranteen_end_F__c nulls last';
 
                final String soqlStr = 'Select {0} {1} ';
                String soql1 = String.format(soqlStr, new String[] {myComponentController.strColumus , selectedDataSql1});
                selectedData = Consum_ApplyUtil.withoutQueryList(soql1);
                System.debug('zheli:'+selectedData.size());
                if (String.isNotBlank(wherStr1) && String.isBlank(wherStr)) {
                    wherStr = wherStr1;
                }
 
                String soql = 'SELECT Id'
                                    + ' , SerialNumber'
                                    + ' , Fixture_Model_No_F__c'
                                    + ' , You_Xiao_Ku_Cun__c'
                                    + ' , Consumable_Guaranteen_end__c'
                                    + ' , GroupKey_F__c'
                                + ' FROM Asset'
                               + ' WHERE Id != null '
                                + wherStr
                                 + ' AND ' + assetWhereBase
                                 + ' ORDER BY Salesdepartment__c DESC, Fixture_Model_No_F__c, Consumable_Guaranteen_end__c nulls Last';
                System.debug(soql);
                wherStr1 = wherStr;
                List<Asset> assList = Consum_ApplyUtil.withoutQueryList(soql);
                countMap = Consum_ApplyUtil.getAssetKucun1(assList, null, true, true);
                Map<String, Consum_Apply_Equipment_Set_Detail__c> keyMap = new Map<String, Consum_Apply_Equipment_Set_Detail__c>();
                Boolean haveChange = false;
                Set<String> modelKeySet = new Set<String>();
                System.debug('zheli598:'+selectedData.size());
                for (SObject sobj : selectedData) {
                    Consum_Apply_Equipment_Set_Detail__c caesdobj = (Consum_Apply_Equipment_Set_Detail__c) sobj;
                    if (caesdobj.Asset__c == null) {
                        continue;
                    }
                    // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add start
                    // String key = caesdobj.GroupKey_F__c;
                    String key = caesdobj.GroupKey_F__c+caesdobj.Fixture_Model_No__c;
                    // 20220309 ljh  SFDC-CC73U5 132 动物实验&ET展箱 锁定已过期库存 add end
                    if (keyMap.containsKey(key)) {
                        Consum_Apply_Equipment_Set_Detail__c caesd = keyMap.get(key);
                        keyMap.get(key).Request_Num_Jia__c ++;
                        if (caesdobj.Select_Time__c != null) {
                            keyMap.get(key).Jie_Chu_Fen_Pei_Jia__c += 1;
                        }
                        System.debug('zheli598:'+selectedData.size());
                        continue;
                    }
                    keyMap.put(key, caesdobj);
                    if (countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_QI_Ku_Cun).containsKey(key)) {
                        caesdobj.You_Xiao_Qi_Ku_Cun_Jia__c = countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_QI_Ku_Cun).get(key);
                        caesdobj.Yi_Guo_Qi_Ku_Cun_Jia__c   = countMap.get(Consum_ApplyUtil.CUCUNTYPE.Yi_Guo_Qi_Ku_Cun).get(key);
                    }
                    caesdobj.You_Xiao_Ku_Cun_Jia__c        = countMap.get(Consum_ApplyUtil.CUCUNTYPE.You_Xiao_Ku_Cun).get(key);
                    if (caesdobj.Select_Time__c != null) {
                        caesdobj.Jie_Chu_Fen_Pei_Jia__c = 1;
                    }
                    else {
                        caesdobj.Jie_Chu_Fen_Pei_Jia__c = 0;
                    }
 
                    caesdobj.Request_Num_Jia__c = 1;
                    caesdobj.No_Jia__c = viewList.size() + 1;
                    viewList.add(new WrapperInfo(caesdobj, 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(caesdobj.Substitute_Select_Again__c));
                }
            }
            System.debug('zheli634:'+viewList.size());
            if (savetype == '1') {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '保存成功'));
            }
        }
        catch(Exception e) {
            Database.rollback(sp);
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, e.getStackTraceString() + soql ));
            ApexPages.addmessages(e);
        }
    }
 
    public static Boolean reSetAsset(List<Consum_Apply_Equipment_Set_Detail__c> selectedData, List<Consum_Apply_Equipment_Set_Detail__c> caesdList, Consum_Apply__c parentObj, Boolean isdef, Boolean needSet) {
        // 20170906 グループリスト取得
        // order by Fixture_Set__c, Fixture_Set__r.Loaner_code__c, IndexFromUniqueKey__c
        wherStr = '';
        String wherStr2 = '';
        Set<String> modelSet = new Set<String>();
        Map<String, Date> fDateMap = new Map<String, Date>();
        Date td = Date.today();
        Map<Date, OlympusCalendar__c> calendarMap = Consum_ApplyUtil.getOlympusCalendarMAp(td, td);
        if (calendarMap.containsKey(td) && calendarMap.get(td).After_15_WorkDay__c != null) {
            td = calendarMap.get(td).After_15_WorkDay__c;
        }
        else {
            td = Consum_ApplyUtil.getWD_addday(td, 15);
        }
        for (Consum_Apply_Equipment_Set_Detail__c caesdobj : selectedData) {
            if (modelSet.contains(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c) == false) {
                if (String.isBlank(wherStr2)) {
                    wherStr = ' AND (';
                    wherStr2 = ' AND (';
                }
                // wherStr += ' (';
                wherStr2 += ' (';
                wherStr += '(Fixture_Model_No_F__c  = \'' + String.escapeSingleQuotes(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c) + '\'';
                wherStr2 += 'Fixture_Model_No_F__c  = \'' + String.escapeSingleQuotes(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c) + '\'';
                if (parentObj.demo_purpose2__c != '动物实验' 
                    //2021-04-30  mzy 备品课题-1577 start
                    &&parentObj.demo_purpose2__c != 'ET展箱') {
                    //2021-04-30  mzy 备品课题-1577 end    
                    // Date d1 = caesdobj.Consum_Start_Date_After_15_Day__c == null ? td : caesdobj.Consum_Start_Date_After_15_Day__c;
                    // wherStr += ' AND Consumable_Guaranteen_end__c >= ' + d1.year() + '-' + String.valueOf(d1.month()).leftPad(2,'0') + '-' + String.valueOf(d1.day()).leftPad(2,'0') + ' )';
                    wherStr2 += ' AND (Consumable_Guaranteen_end__c >= ' + td.year() + '-' + String.valueOf(td.month()).leftPad(2,'0') + '-' + String.valueOf(td.day()).leftPad(2,'0');
                    // wherStr += ' OR Consumable_Guaranteen_end__c = null';
                    wherStr2 += ' OR Consumable_Guaranteen_end__c = null)';
                }
                wherStr += ' ) OR';
                wherStr2 += ' ) OR';
                // key = caesdobj.GroupKey_F__c;
                modelSet.add(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c);
            }
        }
 
        if (String.isNotBlank(wherStr2)) {
            wherStr = wherStr.removeEnd('OR');
            wherStr2 = wherStr2.removeEnd('OR');
            wherStr += ')';
            wherStr2 += ')';
        }
        // if (String.isNotBlank(parentObj.Internal_asset_location_F__c)) {
            wherStr += ' AND Internal_asset_location__c = \'上海 备品中心\'';
            wherStr2 += ' AND Internal_asset_location__c = \'上海 备品中心\'';
        // } 
        if (String.isNotBlank(parentObj.Salesdepartment__c)) {
            wherStr += ' AND (Salesdepartment__c = \'' + parentObj.Salesdepartment__c + '\' OR Salesdepartment__c = \'0.备品中心\')';
            wherStr2 += ' AND (Salesdepartment__c = \'' + parentObj.Salesdepartment__c + '\' OR Salesdepartment__c = \'0.备品中心\')';
        }
        else {
            wherStr += ' AND Salesdepartment__c = \'0.备品中心\'';
            wherStr2 += ' AND Salesdepartment__c = \'0.备品中心\'';
        }
 
        // 检索出保有设备,如果默认分配时间过期的话重新分配
        String soql = 'SELECT Id'
                            + ' , SerialNumber'
                            + ' , Fixture_Model_No_F__c'
                            + ' , You_Xiao_Ku_Cun__c'
                            + ' , Consumable_Guaranteen_end__c'
                            + ' , GroupKey_F__c'
                        + ' FROM Asset'
                       + ' WHERE Id != null '
                        + wherStr2
                         + ' AND ' + assetWhereBase;
                         System.debug(wherStr);
 
        System.debug(soql);
        // 因为保有设备的借出分配数会变,所以需要Lock
        Consum_ApplyUtil.withoutQueryList(soql + ' FOR UPDATE');
        List<Asset> assList1 = Consum_ApplyUtil.withoutQueryList(soql +  + ' ORDER BY Salesdepartment__c DESC, Fixture_Model_No_F__c, Consumable_Guaranteen_end__c nulls Last');
        Map<String, List<AssetBean>> assetMap = new Map<String, List<AssetBean>>();
        for (Asset ass : assList1) {
            if (assetMap.containsKey(ass.Fixture_Model_No_F__c) == false) {
                assetMap.put(ass.Fixture_Model_No_F__c, new List<AssetBean>());
            }
            Integer num = ass.You_Xiao_Ku_Cun__c == null ? 0 : Integer.valueOf(ass.You_Xiao_Ku_Cun__c);
            assetMap.get(ass.Fixture_Model_No_F__c).add(new AssetBean(ass.Id, num));
        }
 
        Boolean haveChangeAss = false;
 
        for (Consum_Apply_Equipment_Set_Detail__c caesdobj : selectedData) {
            if (caesdobj.Shipment_request_time2__c != null) {
                continue;
            }
            // String key;
            if (needSet) {
                // if (caesdobj.Select_Time__c == null) {
                    // if (String.isNotBlank(caesdobj.Asset__c)) {
                        Date d;
                        // if (parentObj.demo_purpose2__c != '动物实验' && caesdobj.Consum_Start_Date__c != null) {
                        //     d = caesdobj.Consum_Start_Date_After_15_Day__c;
                        // }
                        // else {
                        //     d = td;
                        // }
                        d = td;
                        System.debug(d);
                        System.debug(caesdobj.Consumable_Guaranteen_end_F__c);
                        if (String.isNotBlank(caesdobj.Asset__c)
                                && (caesdobj.Consumable_Guaranteen_end_F__c == null
                                    // || caesdobj.Consumable_Guaranteen_end_F__c >= fDateMap.get(key)) {
                                    || caesdobj.Consumable_Guaranteen_end_F__c >= d
                                    || parentObj.demo_purpose2__c == '动物实验'
                                    //2021-04-30  mzy 备品课题-1577 start
                                    || parentObj.demo_purpose2__c == 'ET展箱'
                                    //2021-04-30  mzy 备品课题-1577 end
                                   )
                        ) {
                            if (caesdobj.Select_Time__c == null) {
                                caesdobj.Select_Time__c = Datetime.now();
                                caesdList.add(caesdobj);
                            }
                        }
                        else {
                            String oasId = caesdobj.Asset__c;
                            caesdobj.Asset__c = null;
                            if (assetMap.containsKey(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c)) {
                                for (AssetBean assBean : assetMap.get(caesdobj.Consum_Apply_Equipment_Set__r.Model_No__c)) {
                                    if (assBean.you_Xiao_Ku_Cun > 0
                                        && (caesdobj.Consumable_Guaranteen_end_F__c == null
                                            // || caesdobj.Consumable_Guaranteen_end_F__c >= fDateMap.get(key)) {
                                            || caesdobj.Consumable_Guaranteen_end_F__c > d
                                            || parentObj.demo_purpose2__c == '动物实验'
                                            //2021-04-30  mzy 备品课题-1577 start
                                            || parentObj.demo_purpose2__c == 'ET展箱'
                                            //2021-04-30  mzy 备品课题-1577 end
                                            )
                                    ) {
                                        caesdobj.Asset__c = assBean.assId;
                                        caesdobj.Select_Time__c = Datetime.now();
                                        assBean.you_Xiao_Ku_Cun -= 1;
                                        haveChangeAss = true;
                                        break;
                                    }
                                }
                            }
                            if (oasId != caesdobj.Asset__c) {
                                caesdList.add(caesdobj);
                            }
                        }
                        System.debug(caesdobj.Asset__c);
                        
                    // }
                // }
            }
        }
        return haveChangeAss;
    }
 
    public void setShipment_request() {
        needOpenPage = false;
        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_date__c
                         , Campaign__c
                         , Campaign__r.Status
                         , Wei_Assigned_Cnt__c
                         //, Repair__c
                         , Assigned_Not_Shipment__c
                         //, Contract_pdf_updated__c
                      FROM Consum_Apply__c
                     WHERE Id = :parentId
                       FOR UPDATE
                     ];
        if (parentObjs.size() == 0) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '耗材申请不正确。请刷新画面重试。'));
            return ;
        }
        else {
            parentObj = parentObjs[0];
        }
        String errorMsg = '';
        if (String.isNotBlank(parentObj.Campaign__c)
            && parentObj.Campaign__r.Status == '取消') {
            errorMsg = '学会取消,不可出库指示';
        }
        // else if (parentObj.Status__c == '已出库指示'
        //     && parentObj.Assigned_Not_Shipment__c == 0) {
        //     errorMsg = '所有的耗材备品一览都进行过出库指示了';
        // }
        // else if (parentObj.Assigned_Not_Shipment__c == 0) {
        //     errorMsg = '没有可以出库指示的明细';
        // }
 
        if (String.isNotBlank(errorMsg)) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, errorMsg));
            return ;
        }
        String msg = ConsumApplyWebService.setShipment_request(parentObj.Id);
        needOpenPage = (msg == '状态更新到已出库指示');
        ApexPages.addmessage(new ApexPages.message(msg == '状态更新到已出库指示' ? ApexPages.severity.CONFIRM : ApexPages.severity.ERROR, msg));
    }
 
    public class AssetBean {
        public Id assId;
        public Integer you_Xiao_Ku_Cun;
 
        public AssetBean(Id assId1, Integer you_Xiao_Ku_Cun1) {
            assId = assId1;
            you_Xiao_Ku_Cun = you_Xiao_Ku_Cun1;
        }
    }
 
}