高章伟
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
//Rental_Apply_Equipment_Set__c トリガHandler
//    <runTest>RentalApplyEquipmentSetDetailHandlerTest</runTest>
//    <runTest>RentalFixtureManage13Test</runTest>
//    <runTest>RentalFixtureManage1Test</runTest>
//    <runTest>RentalFixtureManage2Test</runTest>
//    <runTest>RentalFixtureManage3Test</runTest>
//    <runTest>RentalFixtureManage4Test</runTest>
//    <runTest>RentalFixtureManage5Test</runTest>
//    <runTest>RentalApplyEquipmentSetHandlerTest</runTest>
public without sharing class RentalApplyEquipmentSetHandler extends Oly_TriggerHandler {
    private Map<Id, Rental_Apply_Equipment_Set__c> newMap;
    private Map<Id, Rental_Apply_Equipment_Set__c> oldMap;
    private List<Rental_Apply_Equipment_Set__c> newList;
    private List<Rental_Apply_Equipment_Set__c> oldList;
    private static final Map<String,Schema.RecordTypeInfo>  DEVELOPERNAMEMAP  = Schema.SObjectType.Rental_Apply__c.getRecordTypeInfosByDeveloperName();//记录类型 20210609 ljh add 1732
    public RentalApplyEquipmentSetHandler() { 
        Integer i = 0;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        i ++;
        if (Trigger.isUpdate || Trigger.isUndelete || Trigger.isDelete) {
            this.newMap = new Map<Id, Rental_Apply_Equipment_Set__c>();
            this.newList = new List<Rental_Apply_Equipment_Set__c>();
            this.oldMap = (Map<Id, Rental_Apply_Equipment_Set__c>) Trigger.oldMap;   // old そのまま利用
            this.oldList = (List<Rental_Apply_Equipment_Set__c>) Trigger.old;        // old そのまま利用
            // 大前提 Fixture_Set__c ですが下記の属性が設定されています
            // 参照関係に含まれる参照レコードは削除できません。
            if (Trigger.isUpdate || Trigger.isUndelete) {
                for (SObject nSObj : Trigger.new) {
                    Rental_Apply_Equipment_Set__c nObj = (Rental_Apply_Equipment_Set__c) nSObj;
                    Rental_Apply_Equipment_Set__c oObj = null;
                    if (Trigger.isUpdate) {
                        oObj = oldMap.get(nObj.Id);
                    }
                    if (Trigger.isUndelete && String.isBlank(nObj.Fixture_Set__c)) {
                        // 旧データ、beipin2 の trigger 実行しない
                        continue;
                    }
                    else if (Trigger.isUpdate && String.isBlank(nObj.Fixture_Set__c)
                            && String.isNotBlank(oObj.Fixture_Set__c)) {
                        nObj.addError('不能清空借出备品配套 Fixture_Set__c');
                    } else {
                        this.newList.add(nObj);
                        this.newMap.put(nObj.Id, nObj);
                    }
                }
            }
        }
        else {
            // insert
            this.newMap = (Map<Id, Rental_Apply_Equipment_Set__c>) Trigger.newMap;
            this.oldMap = (Map<Id, Rental_Apply_Equipment_Set__c>) Trigger.oldMap;
            this.newList = (List<Rental_Apply_Equipment_Set__c>) Trigger.new;
            this.oldList = (List<Rental_Apply_Equipment_Set__c>) Trigger.old;
        }
    }
 
    protected override void beforeInsert() {
        beforeSetValue();
    }
 
    protected override void beforeUpdate() {
        beforeSetValue();
    }
 
    protected override void afterInsert() {
        Set<Id> raesIdSet = new Set<Id>();
        formulaToTextCheck();
        for (Rental_Apply_Equipment_Set__c nObj : newList) {
            if (nObj.Min_Final_reply_day_Text__c != nObj.Min_Final_reply_day_F__c
                    || nObj.Received_Confirm_Status_Text__c != nObj.Received_Confirm_Status_F__c) {
                raesIdSet.add(nObj.Id);
            }
        }
        // Batch では@future実行できません
        if (raesIdSet.size() > 0 && !System.isBatch()) {
            // before 数式の値がnullになる可能性がありますのでここでも一回チェックします
            formulaToTextCheck(raesIdSet);
        }
    }
 
    protected override void afterUpdate() {
        // キャンセルコピー コピーを先にやらにとcancelフラグが全部falseに変更しますので
        // cancelCopy();
        Map<Id, Rental_Apply_Equipment_Set__c> raesdCMap = new Map<Id, Rental_Apply_Equipment_Set__c>();
        Map<Id, Rental_Apply_Equipment_Set__c> raesdNGMap = new Map<Id, Rental_Apply_Equipment_Set__c>();
        Set<Id> raesIdSet = new Set<Id>();
        for (Rental_Apply_Equipment_Set__c nObj : newList) {
            Rental_Apply_Equipment_Set__c oObj = oldMap.get(nObj.Id);
            if (oObj.Cancel_Select__c == false && nObj.Cancel_Select__c == true) {
                raesdCMap.put(nObj.Id, nObj);
            }
 
            //申请者收货NG变更到不是NG或申请者不是NG到NG的时候需要更新对应的明细(为了修改姓名)
            if ((oObj.Received_Confirm__c != 'NG' && nObj.Received_Confirm__c == 'NG')
                    || (oObj.Received_Confirm__c == 'NG' && nObj.Received_Confirm__c != 'NG')) {
                raesdNGMap.put(nObj.Id, nObj);
            }
 
            if (nObj.Min_Final_reply_day_Text__c != nObj.Min_Final_reply_day_F__c
                    || nObj.Received_Confirm_Status_Text__c != nObj.Received_Confirm_Status_F__c) {
                raesIdSet.add(nObj.Id);
            }
        }
        recCancelNGDetail(raesdCMap, raesdNGMap, true);
        // before では数式項目がnullの場合があります
        formulaToTextCheck();
        // 下一次借用预计出库时间  状态:已出库-->回收后-检测结果OK  2021118 ljh 排队
        NextShippmentDate();
        // OLY_OCM-530: 一览从申请单A分到申请单B时,会检查A下是否有至少一条一览,如果没有则报错
        checkOldApplyNotNull();
        // Batch では@future実行できません
        if (raesIdSet.size() > 0 && !System.isBatch()) {
            // before 数式の値がnullになる可能性がありますのでここでも一回チェックします
            formulaToTextCheck(raesIdSet);
        }
    }
 
    // before 数式の値がnullになる可能性がありますのでここでも一回チェックします
    @future
    private static void formulaToTextCheck(Set<Id> raesdIdSet) {
        List<Rental_Apply_Equipment_Set__c> raesList = [SELECT Id
                    , Min_Final_reply_day_Text__c
                    , Min_Final_reply_day_F__c
                    ,  Received_Confirm_Status_Text__c
                    ,  Received_Confirm_Status_F__c
                 FROM Rental_Apply_Equipment_Set__c
                WHERE Id = :raesdIdSet];
        List<Rental_Apply_Equipment_Set__c> updateRaesList = new List<Rental_Apply_Equipment_Set__c>();
        for (Rental_Apply_Equipment_Set__c raes : raesList) {
            if (raes.Min_Final_reply_day_Text__c != raes.Min_Final_reply_day_F__c
                    || raes.Received_Confirm_Status_Text__c != raes.Received_Confirm_Status_F__c) {
                raes.Min_Final_reply_day_Text__c = raes.Min_Final_reply_day_F__c;
                raes.Received_Confirm_Status_Text__c = raes.Received_Confirm_Status_F__c;
                updateRaesList.add(raes);
            }
        }
        if (updateRaesList.size() > 0) {
            update updateRaesList;
        }
 
    }
 
    protected override void afterDelete() {
        deleteEquipmentError();      // OLY_OCM-530: 如果是非"草案中"状态,删除一览则报错
    }
 
    // OLY_OCM-530: 新分的申请单名后缀num是根据一览的Old_Rental_Apply___c条数判断的,如果分出的申请单下一览是null,那么计算num时,这条分单就被忽略了。
    // ---> 所以需要保证每个申请单下至少有一个一览(一览从申请单A分到申请单B时,会检查A下是否有至少一条一览,如果没有则报错)
    private void checkOldApplyNotNull() {
        Set<String> oRaIds = new Set<String>();                 // 原申请单s
        Rental_Apply_Equipment_Set__c nObj = null;
        List<Rental_Apply_Equipment_Set__c> oRaesList = new List<Rental_Apply_Equipment_Set__c>();
        for (Rental_Apply_Equipment_Set__c oObj : this.oldList) {
            //20210609 ljh add 1732 start
            if(oObj.RARecordTypeId__c == DEVELOPERNAMEMAP.get('AgencyRequest').getRecordTypeId()){
                break;
            }
            //20210609 ljh add 1732 end
            nObj = this.newMap.get(oObj.Id);
            if(oObj.Rental_Apply__c != nObj.Rental_Apply__c && oObj.Rental_Apply__c != null) {
                oRaIds.add(oObj.Rental_Apply__c);
                oRaesList.add(oObj);
            }
        }
 
        if (oRaIds.size() != 0) {
            Set<String>  emptyRaObjs = checkRentalApplyNotExistRAES(oRaesList, oRaIds); // oldRaesList分单(转移)到新申请单后,没有一览的原申请单
            if (emptyRaObjs.size() != 0) {
                List<Rental_Apply__c> raNameList = [
                        Select Id, Name
                        From Rental_Apply__c
                        Where Id in :emptyRaObjs];
                Map<Id, String> raNameMap = new Map<Id, String>();
                for (Rental_Apply__c ra : raNameList) {
                    raNameMap.put(ra.Id, ra.Name);
                }
                for (Rental_Apply_Equipment_Set__c oObj : oRaesList) {
                    if (emptyRaObjs.contains(oObj.Rental_Apply__c)) {
                        nObj = this.newMap.get(oObj.Id);
                        nObj.addError('申请单 ' + raNameMap.get(oObj.Rental_Apply__c) + ', 下一览不能为空');
                    }
                }
            }
        }
    }
 
    /**
     * @param oldRaesList 分单(转移)前的一览List
     * @param raIds 原申请单
     * @return 返回oldRaesList分单(转移)到新申请单后,没有一览的原申请单
     */
    public static Set<String> checkRentalApplyNotExistRAES(List<Rental_Apply_Equipment_Set__c> oldRaesList, Set<String> raIds) {
        Set<String> emptyRaIds = new Set<String>();     // emptyRaIds--一览为空的申请单
        Set<String> oIds = new Set<String>();
        for (Rental_Apply_Equipment_Set__c oObj : oldRaesList) {
            if (oObj.Id != null && false == oIds.contains(oObj.Id)) {
                oIds.add(oObj.Id);
            }
        }
        AggregateResult[] leftRaesRA = [                // (原申请单s中除了原一览s的一览)存在的申请单
                Select Rental_Apply__c
                From Rental_Apply_Equipment_Set__c
                Where Id Not In :oIds
                AND Rental_Apply__c In :raIds
                group by Rental_Apply__c];
 
 
        if (leftRaesRA.size() == 0) {
            return raIds;
        } else {
            Set<String> notERaIds = new Set<String>();
            for (AggregateResult ar : leftRaesRA) {
                notERaIds.add(ar.get('Rental_Apply__c').toString());
            }
            for (String idObj : raIds) {
                if (false == notERaIds.contains(idObj)) {
                    emptyRaIds.add(idObj);
                }
            }
        }
 
        return emptyRaIds;
    }
 
 
    // OLY_OCM-530: 如果是非"草案中"状态,删除一览则报错
    private void deleteEquipmentError() {
        for (Rental_Apply_Equipment_Set__c oObj : oldList) {
            //20210522 ljh 1829 update start
            //if (oObj.RAES_Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal())) {
            if (oObj.RAES_Status__c != FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal()) && !oObj.canDelete__c) {
            //20210522 ljh 1829 update end
                oObj.addError('非草案中状态的一览不能删除');
            }
        }
    }
 
    private void beforeSetValue() {
 
        // List<Id> raesIdList = new List<Id>();
        Set<Id> fisSet = new Set<Id>();
        for (Rental_Apply_Equipment_Set__c nObj : newList) {
            // raesIdList.add(nObj.Id);
            if (String.isNotBlank(nObj.Fixture_Set__c)) {
                fisSet.add(nObj.Fixture_Set__c);
            }
        }
 
        // Map<Id, Rental_Apply_Equipment_Set__c> raesMap = new Map<Id, Rental_Apply_Equipment_Set__c>([
        //             SELECT Id, Fixture_Set__r.Name
        //             FROM Rental_Apply_Equipment_Set__c
        //             where Id in :raesIdList]);
        Map<Id, Fixture_Set__c> fdMap = new Map<Id, Fixture_Set__c>();
        if (fisSet.size() > 0) {
            fdMap = new Map<Id, Fixture_Set__c>([
                    SELECT Id, Name
                    FROM Fixture_Set__c
                    where Id in :fisSet]);
        }
 
        User applyUser = null;   // 申請中になったとき、ログインユーザーからプレセス用の上司を設定
        for (Rental_Apply_Equipment_Set__c nObj : newList) {
            // raesIdList.add(nObj.Id);
            Rental_Apply_Equipment_Set__c oObj = null;
            if (Trigger.isUpdate) {
                oObj = oldMap.get(nObj.Id);
                if (oObj.Received_Confirm__c != nObj.Received_Confirm__c) {
                    if (nObj.Received_Confirm__c == null) {
                        nObj.Loaner_received_time__c = null;
                    } else {
                        nObj.Loaner_received_time__c = Datetime.now();
                    }
                }
            }
            nObj.Demo_purpose2_T__c = nObj.Demo_purpose2__c;
            nObj.Loaner_centre_mail_address__c = nObj.Loaner_centre_mail_address_F__c;
            if (nObj.Asset_return_time__c == null) {
                nObj.Asset_return_time__c = nObj.Asset_return_time_F__c;
            }
            nObj.Received_Confirm_Text__c = nObj.Received_Confirm__c;
 
            Fixture_Set__c fs;
            if (fdMap.containsKey(nObj.Fixture_Set__c)) {
                fs = fdMap.get(nObj.Fixture_Set__c);
            }
            //画面显示用clone出来的数据不需要设置Name
            if (nObj.DataMigration_Flag__c == false
                    && String.isNotBlank(nObj.Fixture_Set__c)
                    && fs != null
                    && nObj.IndexFromUniqueKey__c != null) {
                String split_ApplyNum = nObj.RequestNoJoinStr2__c;
                if (nObj.Rental_Apply_r_Name__c.contains('_')) {
                    // XXXX-YYYY_1 (ZZZZ_1)
                    List<String> split_ApplyNumList = nObj.Rental_Apply_r_Name__c.split('_');
                    String raName = split_ApplyNumList[split_ApplyNumList.size() - 2];      // XXXX-YYYY (ZZZZ)
                    split_ApplyNum = split_ApplyNumList[split_ApplyNumList.size() - 1];     // 1
                    split_ApplyNumList = raName.split('-');     // [XXXX, YYYY]  ([ZZZZ])
                    if (split_ApplyNumList.size() > 1) {
                        // YYYY_1
                        split_ApplyNum = split_ApplyNumList[split_ApplyNumList.size() - 1] + '_' + split_ApplyNum;
                    } else {
                        // ZZZZ_1
                        split_ApplyNum = nObj.Rental_Apply_r_Name__c;
                    }
                }
                nObj.Name = split_ApplyNum + ':' + fs.Name + ':' + nObj.IndexFromUniqueKey__c.format().leftpad(3,'0');
 
                // 如果是分配代替品名字加:Sub
                if (nObj.Substitute_Select_Again__c) {
                    nObj.Name += ':Sub';
                }
 
                //一览时申请者收货NG的话名字添加NG
                if (nObj.Received_Confirm__c == 'NG') {
                    nObj.Name += ':NG';
                }
 
                //取消的时候名字加Canceled
                if (nObj.Cancel_Select__c) {
                    nObj.Name += ':Canceled';
                }
            }
 
            if (nObj.DataMigration_Flag__c == false && (!Trigger.isUpdate || String.isNotBlank(nObj.Fixture_Set__c))) {
                nObj.UniqueKey__c = nObj.RequestNoJoinStr2__c + ':'+ nObj.Fixture_Set__c + ':'+ nObj.IndexFromUniqueKey__c;
                if (nObj.Cancel_Select__c || nObj.Substitute_Select_Again__c) {
                    nObj.UniqueKey__c += nObj.Id;
                }
            }
 
            // 取消分配
            if (Trigger.isInsert || oObj.Cancel_Select__c != nObj.Cancel_Select__c) {
                if (nObj.Cancel_Select__c && nObj.NG_Select_Again__C == false) {
                    nObj.Cancel_Date__c = System.today();
                    nObj.Cancel_Time__c = MainFixtureSelectController.getCurrentTime();
                    nObj.Cancel_Mem__c = UserInfo.getUserId();
                    nObj.Rental_Start_Date__c = null;
                    nObj.Rental_End_Date__c = null;
                    // 使用入力规则
                    //if (String.isBlank(nObj.Cancel_Reason__c)) {
                    //    nObj.Cancel_Reason__c.addError('必须输入取消理由。');
                    //}
                } else {
                    nObj.Cancel_Date__c = null;
                    nObj.Cancel_Time__c = null;
                    nObj.Cancel_Mem__c = null;
                    nObj.Cancel_Reason__c = null;
                    // TODO 取消理由备注 确认
                    if (String.isNotBlank(nObj.Loaner_cancel_Remarks__c)) {
                        nObj.Loaner_cancel_Remarks__c = null;
                    }
                }
            }
 
            // liucheng 20171112
            // 配套备品型号(借出时)
            if (String.isBlank(nObj.Loaner_code_text__c)) {
                nObj.Loaner_code_text__c =  nObj.Loaner_code__c;
            }
            // 配套备品名称(借出时)
            if (String.isBlank(nObj.Loaner_name_text__c)) {
                nObj.Loaner_name_text__c = nObj.Loaner_name__c;
            }
 
            if (String.isBlank(nObj.Equipment_Set_Borrowed__c) && fs != null) {
                // 备品set(借出时)
                nObj.Equipment_Set_Borrowed__c = fs.Name;
            }
 
//bp2 OLY_OCM-85 通过 EquipmentSetDailyBatch 会自动延期,4个审批流程不需要了
// 所以不需要了
//            // ----------------------------------------------------------------------
//            // ここより、承認プロセス用に、经理、部长、总监を更新する
//            // ----------------------------------------------------------------------
//            // 申請中かどうかのチェック
//            if ( ( Trigger.isInsert || oObj.Extend_Status__c != nObj.Extend_Status__c)
//                    && nObj.Extend_Status__c == '申请中') {
//                if (applyUser == null) {
//                    applyUser = [SELECT Id, Name, SalesManager__c, BuchangApprovalManagerSales__c, JingliApprovalManager__c, BuchangApprovalManager__c, ZongjianApprovalManager__c FROM User WHERE Id = :nObj.applyUser__c];
//                }
//                nObj.SalesManager__c = applyUser.SalesManager__c == null
//                        ? applyUser.Id : applyUser.SalesManager__c;
//                nObj.BuchangApprovalManagerSales__c = applyUser.BuchangApprovalManagerSales__c == null
//                        ? applyUser.Id : applyUser.BuchangApprovalManagerSales__c;
//                nObj.JingliApprovalManager__c = applyUser.JingliApprovalManager__c == null
//                        ? applyUser.Id : applyUser.JingliApprovalManager__c;
//                nObj.BuchangApprovalManager__c = applyUser.BuchangApprovalManager__c == null
//                        ? applyUser.Id : applyUser.BuchangApprovalManager__c;
//                nObj.ZongjianApprovalManager__c = applyUser.ZongjianApprovalManager__c == null
//                        ? applyUser.Id : applyUser.ZongjianApprovalManager__c;
//            }
//            // ----------------------------------------------------------------------
//            // ここまで、承認プロセス用に、经理、总监を更新する
//            // ----------------------------------------------------------------------
 
            // 必ず最後で置く
            nObj.Received_Confirm_Status_Text__c = nObj.Received_Confirm_Status_F__c;
            nObj.Canceled_Id__c = nObj.Canceled__c;
            nObj.Substitute_flag__c = nObj.Substitute_Select_Again__c;
            nObj.NG_Final_reply_day_Text__c = nObj.NG_Final_reply_day_F__c;
            nObj.Yizhouweixiu_Final_reply_day_Text__c = nObj.Yizhouweixiu_Final_reply_day_F__c;
            nObj.Extend_Final_reply_day_Text__c = nObj.Extend_Final_reply_day_F__c;
            nObj.QIS_Final_reply_day_Text__c = nObj.QIS_Final_reply_day_F__c;
            nObj.Repair_cancel_Final_reply_day_Text__c = nObj.Repair_cancel_Final_reply_day_F__c;
            nObj.Return_to_office_Final_reply_day_Text__c = nObj.Return_to_office_Final_reply_day_F__c;
            nObj.Repair_delete_Final_reply_day_Text__c = nObj.Repair_delete_Final_reply_day_F__c;
            nObj.Yigoudaihuo_Final_reply_day_Text__c = nObj.Yigoudaihuo_Final_reply_day_F__c;
            nObj.Guzhangpaicha_Final_reply_day_Text__c = nObj.Guzhangpaicha_Final_reply_day_F__c;
            nObj.Repair_Agreed_Quotation_Text__c = nObj.Repair_Agreed_Quotation_F__c;
            nObj.Return_to_office_Final_reply_day_U_RC__c = nObj.Return_to_office_Final_reply_day_U_RC_F__c;
            nObj.Extend_Date__c = nObj.Extend_Date_F__c;
            /*
               Min_Final_reply_day_F__c =
               MIN(
                   NG_Final_reply_day_Text__c
                   Yizhouweixiu_Final_reply_day_Text__c
                   Extend_Final_reply_day_Text__c
                   QIS_Final_reply_day_Text__c
                   Repair_cancel_Final_reply_day_Text__c
                   Return_to_office_Final_reply_day_Text__c
                   Repair_delete_Final_reply_day_Text__c
                   Yigoudaihuo_Final_reply_day_Text__c
               )
               Min_Final_reply_day_Text__cの設定は最後にする必要があります
            */
            nObj.Min_Final_reply_day_Text__c = nObj.Min_Final_reply_day_F__c;
            // nObj.Final_reply_day2__c = nObj.Final_reply_day__c;
        }
    }
 
    //明細更新メソッド(Batch 专用)    更新明細:一覧Cancel明細もCancel
    //                          一覧申请者收获NG明細更新Name
    //                          必須項目:Cancel_Reason__c, Loaner_cancel_Remarks__c
    // @param raesdCMap Cancel一覧Map
    // @param raesdNGMap 申请者NG変更一覧Map
    // @return 保存结果
    public static Database.SaveResult[] recCancelNGDetailBatch(Map<Id, Rental_Apply_Equipment_Set__c> raesdCMap, Map<Id, Rental_Apply_Equipment_Set__c> raesdNGMap) {
        return recCancelNGDetail(raesdCMap, raesdNGMap, false);
    }
 
    //明細更新メソッド    更新明細:一覧Cancel明細もCancel
    //                          一覧申请者收获NG明細更新Name
    //                          必須項目:Cancel_Reason__c, Loaner_cancel_Remarks__c
    // @param raesdCMap Cancel一覧Map
    // @param raesdNGMap 申请者NG変更一覧Map
    // @param allOrNone  不允许部分保存
    // @return 保存结果
    private static Database.SaveResult[] recCancelNGDetail(Map<Id, Rental_Apply_Equipment_Set__c> raesdCMap, Map<Id, Rental_Apply_Equipment_Set__c> raesdNGMap, Boolean allOrNone) {
        // null.isEmpty の場合えラー
        if (raesdCMap == null) {
            raesdCMap = new Map<Id, Rental_Apply_Equipment_Set__c>();
        }
        // null.isEmpty の場合えラー
        if (raesdNGMap == null) {
            raesdNGMap = new Map<Id, Rental_Apply_Equipment_Set__c>();
        }
        //更新明细
        Map<Id, Rental_Apply_Equipment_Set_Detail__c> raesdMap = new Map<Id, Rental_Apply_Equipment_Set_Detail__c>();
 
        //取消更新的明细
        if (!raesdCMap.isEmpty()) {
            List<Rental_Apply_Equipment_Set_Detail__c> raesds = [
                    Select Id, Rental_Apply_Equipment_Set__c, Is_Body__c
                      From Rental_Apply_Equipment_Set_Detail__c
                     Where Rental_Apply_Equipment_Set__c = :raesdCMap.keySet() 
                       AND Cancel_Select__c = false
                       AND DeliverySlip__c = null];
            set<Id> Rental_ApplyId = new set<Id>(); //备品借出申请 20210708 SFDC-C448KZ you
            for (Rental_Apply_Equipment_Set_Detail__c raesd :raesds) {
                raesd.Cancel_Select__c = true;
                raesd.Cancel_Mem__c = UserInfo.getUserId();
                raesd.Cancel_Date__c = Date.today();
                raesd.Cancel_Time__c = MainFixtureSelectController.getCurrentTime();
                raesd.Cancel_Reason__c = raesdCMap.get(raesd.Rental_Apply_Equipment_Set__c).Cancel_Reason__c;
                raesd.Loaner_cancel_Remarks__c = raesdCMap.get(raesd.Rental_Apply_Equipment_Set__c).Loaner_cancel_Remarks__c;
                //20210706 SFDC-C448KZ you
                raesd.Loaner_cancel_reason__c = raesdCMap.get(raesd.Rental_Apply_Equipment_Set__c).Loaner_cancel_reason__c;
                raesdMap.put(raesd.Id, raesd);
                Rental_ApplyId.add(raesdCMap.get(raesd.Rental_Apply_Equipment_Set__c).Rental_Apply__c);
            }
            //20210708 SFDC-C448KZ you start
            //1)一览全部取消(部份主动,被动),申请单的“取消理由”为被动取消, “取消理由备注”为一览中最新得 
            //2)一览全部取消(全部主或全部被动),申请单的“取消理由”“取消理由备注”更新为一览中最新更新的配套的取消理由备注;
            if(Rental_ApplyId.size() > 0){
                List<Rental_Apply_Equipment_Set__c> raesslist = [select id,Cancel_Reason__c,Loaner_cancel_reason__c,Loaner_cancel_Remarks__c,Rental_Apply__c from Rental_Apply_Equipment_Set__c where Rental_Apply__c in: Rental_ApplyId  order by Rental_Apply__c,LastModifiedDate];
                // Map<String,String> raessMap = new Map<String,String>();
                Map<String,Rental_Apply_Equipment_Set__c> raessMap1 = new Map<String,Rental_Apply_Equipment_Set__c>();
                for (Rental_Apply_Equipment_Set__c raess :raesslist) {
                    String mapkey = '';
                    // String mapValue = '';
                    // 这里是不是判断有问题
                    if(raess.Cancel_Reason__c==null){
                        mapkey = raess.Rental_Apply__c +'_'+ 'null';
                    }
                    if(raess.Cancel_Reason__c=='主动取消'){
                        mapkey = raess.Rental_Apply__c +'_'+ '主动取消';
                    }
                    if(raess.Cancel_Reason__c=='被动取消'){
                        mapkey = raess.Rental_Apply__c +'_'+ '被动取消';
                    }
                    // mapValue = raess.Cancel_Reason__c+':'+raess.Loaner_cancel_reason__c +':'+raess.Loaner_cancel_Remarks__c; 
                    // raessMap.put(mapkey,mapValue);
                    // raessMap.put(raess.Rental_Apply__c, mapValue);
                    raessMap1.put(mapkey, raess);
                    raessMap1.put(raess.Rental_Apply__c, raess);
 
                }  
                List<Rental_Apply__c> updateRentalApplyList = new List<Rental_Apply__c>();
                for (Id rentaId:Rental_ApplyId) {
                    String key_null = rentaId +'_'+ 'null';
                    String key_zd = rentaId +'_'+ '主动取消';
                    String key_bd = rentaId +'_'+ '被动取消';
                    Rental_Apply__c ra = new Rental_Apply__c(); 
                    ra.Id = rentaId;
                    String mapValue1='';
                    Rental_Apply_Equipment_Set__c raeSet = new Rental_Apply_Equipment_Set__c();
                    if (raessMap1.containsKey(key_null)) {
                        // 含有未取消
                        continue;
                    } else if (raessMap1.containsKey(key_zd) && raessMap1.containsKey(key_bd)){
                        // 既有主动也有被动
                        //raeSet = raessMap1.get(rentaId);
                        raeSet = raessMap1.get(key_bd);
                        ra.Cancel_Reason__c='被动取消';
                        
                    } else if (raessMap1.containsKey(key_zd)) {
                        // 全部主动
                        raeSet = raessMap1.get(key_zd);
                        ra.Cancel_Reason__c=raeSet.Cancel_Reason__c;
                        
                    } else if(raessMap1.containsKey(key_bd)) {
                        // 全部被动
                        raeSet = raessMap1.get(key_bd);
                        ra.Cancel_Reason__c=raeSet.Cancel_Reason__c;
                    
                    }
                    if (String.isBlank(raeSet.Id)) {
                        continue;
                    }
                    ra.Loaner_cancel_reason__c = raeSet.Loaner_cancel_reason__c;
                    ra.Loaner_cancel_request__c = raeSet.Loaner_cancel_Remarks__c;
                    updateRentalApplyList.add(ra);
                    //20210708 SFDC-C448KZ you end
                    /*
                    if (raessMap.containsKey(key_null)) {
                        // 含有未取消
                        continue;
                    } else if (raessMap.containsKey(key_zd) && raessMap.containsKey(key_bd)){
                        // 既有主动也有被动
                        mapValue1 = raessMap.get(rentaId);
                        String[] array1 = mapValue1.split(':');
                        ra.Cancel_Reason__c='被动取消';
                        ra.Loaner_cancel_reason__c = array1[1];
                        ra.Loaner_cancel_request__c = array1[2];
                    } else if (raessMap.containsKey(key_zd)) {
                        // 全部主动
                        mapValue1 = raessMap.get(key_zd);
                        String[] array2 = mapValue1.split(':');
                        ra.Cancel_Reason__c=array2[0];
                        ra.Loaner_cancel_reason__c = array2[1];
                        ra.Loaner_cancel_request__c = array2[2];
                    } else if(raessMap.containsKey(key_bd)) {
                        // 全部被动
                        mapValue1 = raessMap.get(key_bd);
                        String[] array3 = mapValue1.split(':');
                        ra.Cancel_Reason__c=array3[0];
                        ra.Loaner_cancel_reason__c = array3[1];
                        ra.Loaner_cancel_request__c = array3[2];
                    }
                    updateRentalApplyList.add(ra);
                    */
 
                }
                if (!updateRentalApplyList.isEmpty()) {
                     update updateRentalApplyList;
                 }
               
                
            }
            //20210708 SFDC-C448KZ you end
        }
 
        //申请者收货NG的明细
        if (!raesdNGMap.isEmpty()) {
            List<Rental_Apply_Equipment_Set_Detail__c> raesds = [
                    Select Id, Rental_Apply_Equipment_Set__c
                      From Rental_Apply_Equipment_Set_Detail__c
                     Where Rental_Apply_Equipment_Set__c = :raesdNGMap.keySet()];
            for (Rental_Apply_Equipment_Set_Detail__c raesd :raesds) {
                if (!raesdMap.containsKey(raesd.Id)) {
                    raesdMap.put(raesd.Id, raesd);
                }
            }
        }
 
        if (!raesdMap.isEmpty()) {
            return Database.update(raesdMap.values(), allOrNone);
        }
        return null;
    }
 
    // private void cancelCopy() {
    //     Map<Id, Rental_Apply_Equipment_Set__c> raesdMap = new Map<Id, Rental_Apply_Equipment_Set__c>();
 
    //     for (Rental_Apply_Equipment_Set__c nObj : newList) {
    //         Rental_Apply_Equipment_Set__c oObj = oldMap.get(nObj.Id);
    //         if (nObj.Ra_Cancel_Select__c == false
    //                 && (oObj.Cancel_Select__c == false && nObj.Cancel_Select__c == true)) {
    //             Rental_Apply_Equipment_Set__c nraescolone = new Rental_Apply_Equipment_Set__c();
    //             nraescolone.Rental_Apply__c = nObj.Rental_Apply__c;
    //             nraescolone.Fixture_Set__c = nObj.Fixture_Set__c;
    //             nraescolone.Canceled_Id__c = nObj.Id;
    //             raesdMap.put(nObj.Id, nraescolone);
    //         }
    //     }
 
    //     if (raesdMap.isEmpty()) {
    //         return;
    //     }
    //     System.debug(raesdMap.values().size());
    //     insert raesdMap.values();
 
    //     List<Rental_Apply_Equipment_Set_Detail__c> raesds = [Select Id, Rental_Apply__c,
    //             Fixture_Set_Detail__c, IndexFromUniqueKey__c, Rental_Apply_Equipment_Set__c
    //             FROM Rental_Apply_Equipment_Set_Detail__c
    //             WHERE Rental_Apply_Equipment_Set__c =: raesdMap.keySet()
    //             AND Cancel_Select__c = false];
    //     List<Rental_Apply_Equipment_Set_Detail__c> raesdList = new List<Rental_Apply_Equipment_Set_Detail__c>();
    //     for (Rental_Apply_Equipment_Set_Detail__c raesd : raesds) {
    //         Rental_Apply_Equipment_Set_Detail__c craesd = new Rental_Apply_Equipment_Set_Detail__c();
    //         craesd.Rental_Apply_Equipment_Set__c = raesdMap.get(raesd.Rental_Apply_Equipment_Set__c).Id;
    //         craesd.Rental_Apply__c = raesd.Rental_Apply__c;
    //         craesd.Fixture_Set_Detail__c = raesd.Fixture_Set_Detail__c;
    //         craesd.IndexFromUniqueKey__c = raesd.IndexFromUniqueKey__c;
    //         craesd.Canceled_Id__c = raesd.Id;
    //         raesdList.add(craesd);
    //     }
    //     if (!raesdList.isEmpty()) {
    //         insert raesdList;
    //     }
    // }
 
    //before 数式の値がnullになる可能性がありますのでここでも一回チェックします
    private void formulaToTextCheck() {
        List<Rental_Apply_Equipment_Set__c> raess = new List<Rental_Apply_Equipment_Set__c>();
        for (Rental_Apply_Equipment_Set__c nObj : newList) {
            
            if (nObj.Received_Confirm_Status_Text__c != nObj.Received_Confirm_Status_F__c
                  || nObj.Min_Final_reply_day_Text__c != nObj.Min_Final_reply_day_F__c
                  || ((String.isNotBlank(nObj.Old_Rental_Apply_F__c) && String.isNotBlank(nObj.Old_Rental_Apply__c) && nObj.Old_Rental_Apply_F__c != nObj.Old_Rental_Apply__c)
                    || (String.isNotBlank(nObj.Old_Rental_Apply_F__c) && String.isBlank(nObj.Old_Rental_Apply__c))
                    || (String.isBlank(nObj.Old_Rental_Apply_F__c) && String.isNotBlank(nObj.Old_Rental_Apply__c))
                  )// 20210817 XHL add 
                  ) {
                Rental_Apply_Equipment_Set__c raes = new Rental_Apply_Equipment_Set__c();
                raes.Id = nObj.Id;
                // 20210817 XHL update start
                // raes.Received_Confirm_Status_Text__c = nObj.Received_Confirm_Status_F__c;
                // raes.Min_Final_reply_day_Text__c = nObj.Min_Final_reply_day_F__c;
                // 分单理由 是 补充借用 的备品借出申请,创建 借出备品配套一览 时 为 旧借出申请  赋值 
                if((String.isNotBlank(nObj.Old_Rental_Apply_F__c) && String.isNotBlank(nObj.Old_Rental_Apply__c) && nObj.Old_Rental_Apply_F__c != nObj.Old_Rental_Apply__c)
                    || (String.isNotBlank(nObj.Old_Rental_Apply_F__c) && String.isBlank(nObj.Old_Rental_Apply__c))
                    || (String.isBlank(nObj.Old_Rental_Apply_F__c) && String.isNotBlank(nObj.Old_Rental_Apply__c))
                    ){
                    raes.Old_Rental_Apply__c = nObj.Old_Rental_Apply_F__c; // 20210816 XHL add
                }
                if (nObj.Received_Confirm_Status_Text__c != nObj.Received_Confirm_Status_F__c
                  || nObj.Min_Final_reply_day_Text__c != nObj.Min_Final_reply_day_F__c){
                    raes.Received_Confirm_Status_Text__c = nObj.Received_Confirm_Status_F__c;
                    raes.Min_Final_reply_day_Text__c = nObj.Min_Final_reply_day_F__c;
                }
                // 20210817 XHL update end
                raess.add(raes);
            }
        }
        if (!raess.isEmpty()) {
            update raess;
        }
    }
 
    // 20211118 ljh 排队
    /*
    根据if 状态:已出库--检测ok的(检测NG和欠品的:不显示时间) && 最新预定归还日 RAES_Final_reply_day__c 有值 && new != old{
        最新预定归还日+8个工作日(奥林巴斯日历)
    }
    */
    private void NextShippmentDate() {
        Date minDate = Date.newInstance(4000, 12, 31);
        Date maxDate = Date.newInstance(1700, 1, 1);
        Map<Date, List<String>> dLMap = new Map<Date, List<String>>();
        List<Rental_Apply_Equipment_Set_Detail__c> upRdList = new List<Rental_Apply_Equipment_Set_Detail__c>();
        for (Rental_Apply_Equipment_Set__c nObj : newList) {
            if(nObj.RARecordTypeId__c != '01210000000NPGK'){
                Rental_Apply_Equipment_Set__c oObj = oldMap.get(nObj.Id);
                // 第一条是主体 && 第一条状态满足 && 最新预定归还日发生改变
                List<String> statusList = new String[]{'已出库','申请者已收货','医院已装机确认','已回寄','已回收','回收后已CDS'};
                if(nObj.First_RAESD_Is_Main__c == true 
                    && String.isNotBlank(nObj.First_Status_All__c) && statusList.contains(nObj.First_Status_All__c)
                    && oObj.Final_reply_day_text__c != nObj.Final_reply_day_text__c){
                    // 最新预定归还日+8个工作日(奥林巴斯日历)
                    Date date1 = nObj.Final_reply_day_text__c;
                    if (minDate > date1) {
                        minDate = date1;
                    }
                    if (maxDate < date1) {
                        maxDate = date1;
                    }
                    if(!dLMap.containsKey(date1)){
                        dLMap.put(date1,new List<String>());
                    }
                    dLMap.get(date1).add(nObj.First_RAESD__c);
                }
            }
        }
        if(dLMap.size() > 0 ){
            List<OlympusCalendar__c> ocList = [SELECT Id
                        , Date__c
                     FROM OlympusCalendar__c
                    WHERE Date__c >= :minDate
                      AND Date__c <= :maxDate.addDays(30)
                      AND IsWorkDay__c = 1
                    ORDER BY Date__c ASC];
            Map<Date, Date> dateadd8Map = new Map<Date, Date>();
            Integer ocListSize = ocList.size();
            if (ocListSize > 8) {
                for (Integer i = 0; i < ocListSize - 8; i ++) {
                    dateadd8Map.put(ocList[i].Date__c, ocList[i + 8].Date__c);
                }
                for(Date d:dLMap.keySet()){
                    if (dateadd8Map.containsKey(d)) {
                        for(String rdId:dLMap.get(d)){
                            Rental_Apply_Equipment_Set_Detail__c raesd = new Rental_Apply_Equipment_Set_Detail__c();
                            raesd.Id = rdId;
                            raesd.NextShippmentDate__c = dateadd8Map.get(d);
                            upRdList.add(raesd);
                        }
                    }else{
                        for (Integer i = 0; i < ocListSize - 8; i ++) {
                            // 也可以都用加上等于 这个ocList[i + 8] 代码虽然简洁了,但是效率就慢了
                            if(d < ocList[i].Date__c){
                                for(String rdId:dLMap.get(d)){
                                    Rental_Apply_Equipment_Set_Detail__c raesd = new Rental_Apply_Equipment_Set_Detail__c();
                                    raesd.Id = rdId;
                                    raesd.NextShippmentDate__c = ocList[i + 7].Date__c;
                                    upRdList.add(raesd);
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
        if(upRdList.size() > 0){
            update upRdList;
        }
    }
 
}