liuyn
2024-03-11 a87f1c3df03078814ee97ad0c8ac200a232419e9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
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
/* 用于新维修合同二期,计算每个合同到上月月底的合同消费率
1) 检索上一期维修合同:包括合同价格、合同开始日期;
2) 检索出上一期维修合同所有的维修合同保有设备;
3) 检索出这些维修合同保有设备之前的上上期维修合同保有设备;
4) 计算出上一期维修合同开始日期到当前日期的上月月末的的合同金额、上一期开始日期到当前日期的上月月末的修理报价金额;
5) 计算出上上期维修合同上一期维修合同首次报价日(目前未知)到结束日期的的合同金额、上一期开始日期到结束日期的修理报价金额;
6) 储存上一期维修合同、上一期维修合同保有设备在保有设备上;
*Date:2019-12-06
*/ 
global class AssetUpdateContractBatch implements Database.Batchable<sObject>, Database.Stateful {
    // 设定运行的维修合同的ID
    public string TestID;
 
    // 设定执行日期
    public Date TestDate;
    
    // 设定每月或者每日执行
    public Boolean IsDaily;
 
    // 是否运行所有维修合同
    public Boolean isAll = false;
 
    // 设定运行的维修合同的list<ID>
    public list<string> TestIDList;
 
    // 报错的维修合同ID
    public String logstr = '';
 
    // 报错信息
    public String errorstr = '';
 
    Boolean IsNeedExecute = false;
 
 
    global Integer totalCount = 0; // 总件数
    global Integer failedCount = 0; // 失败件数
 
    global List<String> emailMessages = new List<String>();
    //  按照当日执行。 只执行合同结束日大于当日前40天的维修合同
    global AssetUpdateContractBatch() {
        this.TestDate = Date.today();
        this.isAll = false;
        this.isDaily = isDaily(this.TestDate);
    }
    // 按照设定结束日期执行。 只执行合同结束日大于设定结束日期前40天的维修合同
    global AssetUpdateContractBatch(Date testDate) {
        this.TestDate = testDate;
        this.isAll = false;
        this.isDaily = isDaily(this.TestDate);
    }
 
    // 按照设定结束日期执行所有维修合同,基本上不会使用;
    global AssetUpdateContractBatch(Date testDate , boolean isAll) {
        this.TestDate = testDate;
        this.isAll = isAll;
        this.isDaily = isDaily(this.TestDate);
    }
 
    // 按照设定结束日期执行选定的维修合同
    global AssetUpdateContractBatch(string TestID, Date testDate) {
        this.TestID = TestID;
        this.TestDate = testDate;
        this.isDaily = isDaily(this.TestDate);
    }
 
    // 按照设定结束日期执行选定的维修合同组
    global AssetUpdateContractBatch(list<string> TestIDList, Date testDate) {
        this.TestIDList = TestIDList;
        this.TestDate = testDate;
        this.isDaily = isDaily(this.TestDate);
    }
 
    //2021-06-16  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
    global AssetUpdateContractBatch(Boolean NeedExecute) {
        this.TestDate = Date.today();
        this.isAll = false;
        this.isDaily = isDaily(this.TestDate);
        this.IsNeedExecute = needExecute;
    }
    //2021-06-16  mzy  WLIG-BYHD79  SFDC环境batch合并调查  end
 
    global Database.QueryLocator start(Database.BatchableContext bc) {
        string query =
            ' select id , previousTotalRepairAmount__c , currentTotalRepairAmount__c ,' +
            ' previousTotalContractAmount__c , currentTotalContractAmountVM__c , currentTotalGuaranteePrice__c '+
            ' , RecordType_DeveloperName__c  ' +
            '  from Maintenance_Contract__c '
            + ' where Status__c in (\'契約\',\'契約満了\') ';
 
        if (string.isNotBlank(TestID) ) {
            query += ' and id =: TestID';
        } else if (TestIDList != null && TestIDList.size() > 0) {
            query += ' and id in: TestIDList';
        } else if (!isAll) {
            query += ' and Contract_End_Date__c > '
                     + testDate.addDays(-50).format().replace('/', '-') ;
        }
        if(isDaily){
           query += ' and Contract_End_Date__c = ' + 
                    testDate.addDays(-1).format().replace('/', '-'); 
        }
        //system.debug('query:'+query);
        testDate = Datecheck(testDate);
 
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext BC,
                        list<Maintenance_Contract__c> MCList) {
        
 
        map<string, asset> updateAssetMap = new map<string, asset>();
        map<string, Maintenance_Contract__c> UpdateMCMap =
            new map<string, Maintenance_Contract__c>();
        map<string,Maintenance_Contract__c> mcIDmap = new map<string,Maintenance_Contract__c>();
 
        // 20210906 gzw 计算维修合同报价/保有设备 上的实际报价金额
        map<string,Decimal> mcAssetmap = new map<string,Decimal>();
        map<string,List<Maintenance_Contract_Asset_Estimate__c>> mcaasmap = new map<string,List<Maintenance_Contract_Asset_Estimate__c>>();
        // 20210906 gzw 计算维修合同报价/保有设备 上的实际报价金额
 
 
        Set<Id> newAssetIDset = new Set<Id>();
        Set<ID> allAssetIDSet = new Set<ID>();
        List<asset> allAssetList = new List<asset>();
        // 初始化维修合同消费率相关金额字段为0;
        for (Maintenance_Contract__c tempMC : MCList) {
            mcIDmap.put(tempMC.id,null);
            tempMC.currentTotalRepairAmount__c  = 0;
            tempMC.previousTotalRepairAmount__c = 0;
            tempMC.previousTotalContractAmount__c = 0;
            tempMC.currentTotalContractAmountVM__c  = 0;
            tempMC.currentTotalGuaranteePrice__c = 0;
            UpdateMCMap.put(tempMC.id, tempMC);
        }
        //system.debug('UpdateMCMap1:' + UpdateMCMap);
        map<string, Maintenance_Contract_Asset__c> newToOldMCA =
            new map<string, Maintenance_Contract_Asset__c>();
        map<string, Maintenance_Contract_Asset__c> assetIDtoMCA =
            new map<string, Maintenance_Contract_Asset__c>();
        // 检索本次batch涉及的维修合同对应的保有设备
        list<Maintenance_Contract_Asset__c> mcaList =
            [select Id, Asset__c, Maintenance_Contract__c,
             Estimate_Cost_formula__c,
             startDate_sum__c,
             endDate_sum__c,
             No_discount__c,
             GuaranteePrice_Amount_Text__c,
             Maintenance_Contract__r.Status__c,
             Maintenance_Contract__r.Name,
             Maintenance_Contract__r.Contract_End_Date__c,
             Maintenance_Contract__r.Contract_Start_Date__c,
             Maintenance_Contract__r.RecordType_DeveloperName__c,
             Maintenance_Contract__r.Estimation_Id__r.Submit_quotation_day__c,
             Maintenance_Contract__r.RecordType.DeveloperName
             , ifHaveleftInPrevious__c
             ,Maintenance_Contract__r.URF_Contract__c
             from Maintenance_Contract_Asset__c
             where Maintenance_Contract__c in: mcIDmap.keyset()
            ];
        //system.debug('mcaList1:' + mcaList);
        //给当期维修合同保有设备赋值
        // 20210906 gzw 计算维修合同报价/保有设备 上的实际报价金额
        // 检索本次batch涉及的维修合同报价/保有设备
        list<Maintenance_Contract_Asset_Estimate__c> mcaasList =
            [select Id, Asset__c,ContractAsset_key__c,Maintenance_Contract_Estimate__r.Maintenance_Contract__c, ContractAsset_Amont__c
             from Maintenance_Contract_Asset_Estimate__c
             where Maintenance_Contract_Estimate__r.Maintenance_Contract__c in: mcIDmap.keyset()
             and Asset__c != null
            ];
        for (Maintenance_Contract_Asset_Estimate__c mcae :mcaasList) {
            List<Maintenance_Contract_Asset_Estimate__c> temp = new List<Maintenance_Contract_Asset_Estimate__c>();
            System.debug( 'ContractAsset_key__c ++++++++++++++ '+   mcae.ContractAsset_key__c);
            if (mcaasmap.containsKey(mcae.ContractAsset_key__c)) {
                temp = mcaasmap.get(mcae.ContractAsset_key__c);
            }
            temp.add(mcae);
            mcaasmap.put(mcae.ContractAsset_key__c, temp);
        }
        // 20210906 gzw 计算维修合同报价/保有设备 上的实际报价金额
       
        //给当期维修合同保有设备赋值                   
        //updateCurrentMCAsset ( mcaList,  UpdateMCMap, allAssetIDSet, newToOldMCA,
        //                         newAssetIDset,  assetIDtoMCA);
        for (Maintenance_Contract_Asset__c mca : mcaList) {
            Maintenance_Contract__c tempMC = UpdateMCMap.get(mca.Maintenance_Contract__c); 
            //如果是多年保修合同且输入日期晚于结束日期,则使用保有设备上的全额no discount 和计提金额
            // 计算本期合同金额(多年保修故障风险率用)、合同金额(多年保修故障风险率管理用)
            if (testDate > mca.endDate_sum__c &&
                    mca.Maintenance_Contract__r.RecordType.DeveloperName.equals('VM_Contract')) {
                tempMC.currentTotalContractAmountVM__c +=
                    mca.No_discount__c == null ?
                    0 :
                    mca.No_discount__c;
                 tempMC.currentTotalGuaranteePrice__c +=
                    mca.GuaranteePrice_Amount_Text__c == null ?
                    0 :
                    mca.GuaranteePrice_Amount_Text__c;
                 
                //continue;
            } 
            //如果是多年保修合同且输入日期晚于开始日期,则使用保有设备上的全额no discount 和计提金额 按照日期比例
            // 计算本期合同金额(多年保修故障风险率用)、合同金额(多年保修故障风险率管理用)
            else if ( testDate >= mca.startDate_sum__c &&
                        mca.Maintenance_Contract__r.RecordType.DeveloperName.equals('VM_Contract')) {
                Decimal tempNo_discount =  mca.No_discount__c == null ?
                                           0 :
                                           mca.No_discount__c;
                Decimal GuaranteePrice_Amount =  mca.GuaranteePrice_Amount_Text__c == null ?
                                           0 :
                                           mca.GuaranteePrice_Amount_Text__c;
                system.debug('mca.startDate_sum__c.daysBetween(testDate):'+
                    mca.startDate_sum__c.daysBetween(testDate));
                tempMC.currentTotalContractAmountVM__c +=
                    tempNo_discount * (mca.startDate_sum__c.daysBetween(testDate) + 1) /
                    (mca.startDate_sum__c.daysBetween(mca.endDate_sum__c) + 1);
                tempMC.currentTotalGuaranteePrice__c +=
                    GuaranteePrice_Amount * (mca.startDate_sum__c.daysBetween(testDate) + 1) /
                    (mca.startDate_sum__c.daysBetween(mca.endDate_sum__c) + 1);
                //continue;
            }
            // 服务合同需要再检索上期维修合同保有设备剩余
            if (mca.Maintenance_Contract__r.RecordType.DeveloperName.equals('NewMaintenance_Contract')) {
                newAssetidset.add(mca.Asset__c);
            }
            // 找出来检索出来的维修合同保有中的最新的
            if (assetIDtoMCA.containsKey(mca.Asset__c)) {
                Maintenance_Contract_Asset__c tempMCA =
                    assetIDtoMCA.get(mca.Asset__c);
                if (tempMCA.endDate_sum__c < mca.endDate_sum__c) {
                    assetIDtoMCA.put(mca.Asset__c, mca);
                }
            } else {
                assetIDtoMCA.put(mca.Asset__c, mca);
            }
            allAssetIDSet.add(mca.Asset__c);
            newToOldMCA.put(mca.id, null);
        }
        system.debug('allAssetIDSet:' + allAssetIDSet);
        //system.debug('newToOldMCA:' + newToOldMCA);
        allAssetList =
            [select id, CurrentContract_F__c,
             CurrentContract_F__r.Contract_End_Date__c,
             CurrentContract_F_asset__c,
             CurrentContract_F_asset__r.endDate_sum__c
             ,URF_Maintenance_Contract__c
             ,URF_Maintenance_Contract__r.Contract_End_Date__c
             from asset
             where id in: allAssetIDSet];
        // 更新保有设备上的上一期维修合同和维修合同保有设备
        // 找出来的不一定是最新的,因为还会和保有设备上对比一下
        for (asset ass : allAssetList) {
            Maintenance_Contract_Asset__c tempMCA =
                assetIDtoMCA.get(ass.Id);
            if (tempMCA != null) {
                if (tempMCA.Maintenance_Contract__r.URF_Contract__c==true && 
                    (ass.URF_Maintenance_Contract__c == null ||
                       ass.URF_Maintenance_Contract__r.Contract_End_Date__c <= tempMCA.endDate_sum__c
                        )) {
                    ass.URF_Maintenance_Contract__c = tempMCA.Maintenance_Contract__c;
                }
                if (tempMCA.Maintenance_Contract__r.URF_Contract__c==false &&
                    (
                        ass.CurrentContract_F__c == null  ||
                        ass.CurrentContract_F_asset__c == null ||
                        ass.CurrentContract_F_asset__r.endDate_sum__c <=
                        tempMCA.endDate_sum__c
                    )
                    ){
                    ass.CurrentContract_F__c = tempMCA.Maintenance_Contract__c;
                    ass.CurrentContract_F_asset__c = tempMCA.id;
                }
                
                updateAssetMap.put(ass.id, ass);
            }
 
        }
        
        //检索出历届保有设备
        list<Maintenance_Contract_Asset__c> allMCAList =
            [select Id, Asset__c, Maintenance_Contract__c,
             Estimate_Cost_formula__c,
             startDate_sum__c,
             endDate_sum__c,
             ifHaveleftInPrevious__c,
             Maintenance_Contract__r.Status__c,
             Maintenance_Contract__r.Name,
             Maintenance_Contract__r.Contract_End_Date__c,
             Maintenance_Contract__r.Contract_Start_Date__c,
             Maintenance_Contract__r.RecordType_DeveloperName__c,
             Maintenance_Contract__r.Estimation_Id__r.Submit_quotation_day__c,
             Maintenance_Contract__r.RecordType.DeveloperName,
             Maintenance_Contract__r.First_Estimate_Date__c
             from Maintenance_Contract_Asset__c
             where Asset__c in: newAssetidset
             and Maintenance_Contract__r.RecordType.DeveloperName = 'NewMaintenance_Contract'
                     and Maintenance_Contract__r.Status__c in ('契約', '契約満了')
                     order by Asset__c, endDate_sum__c desc
            ];
       // system.debug('allMCAList:' + allMCAList);
        Set<string> ALLMCIDset = mcIDmap.keySet().clone();
       // system.debug('ALLMCIDset1:' + ALLMCIDset);
        map<string, Maintenance_Contract_Asset__c> oldToNewMCA =
            new map<string, Maintenance_Contract_Asset__c>();
        map<string, Maintenance_Contract_Asset__c> strToOldMCA =
            new map<string, Maintenance_Contract_Asset__c>();
        ID tempAssetID;
        Maintenance_Contract_Asset__c newMCA = null;
        // 构建上一期维修合同保有设备和对应的上上期维修合同保有设备之间的关系
        for (Maintenance_Contract_Asset__c tempMCA : allMCAList) {
            if (tempMCA.Asset__c != tempAssetID) {
                tempAssetID = tempMCA.Asset__c;
                newMCA = tempMCA;
                continue;
            }
            system.debug('tempMCA:'+tempMCA);
            system.debug('newMCA:'+newMCA);
            if (newToOldMCA.containsKey(newMCA.id)  && newMCA.ifHaveleftInPrevious__c
                    && tempMCA.Maintenance_Contract__r.First_Estimate_Date__c != null
                    && tempMCA.Estimate_Cost_formula__c  != null
 
               ) {
                newToOldMCA.put(newMCA.id, tempMCA);
                string str = '' + (ID) tempMCA.Maintenance_Contract__c + tempMCA.Asset__c;
                Maintenance_Contract__c newMC =
                    UpdateMCMap.get(newMCA.Maintenance_Contract__c);
                // 如果保存在上一期维修合同的首次报价日早于或等于合同结束日,则计算上一期合同金额
                if(tempMCA.Maintenance_Contract__r.First_Estimate_Date__c <= tempMCA.endDate_sum__c){
                    newMC.previousTotalContractAmount__c +=
                        tempMCA.Estimate_Cost_formula__c
                        * (getTheFirstDayOftheMonth(tempMCA.Maintenance_Contract__r.First_Estimate_Date__c).daysBetween(
                                tempMCA.endDate_sum__c)+1)
                        / (tempMCA.startDate_sum__c.daysBetween(tempMCA.endDate_sum__c)+1);
                }
                oldToNewMCA.put(str, newMCA);
          //      system.debug(oldToNewMCA.get(str));
                strToOldMCA.put(str, tempMCA);
                ALLMCIDset.add(tempMCA.Maintenance_Contract__c);
            }
            newMCA = tempMCA;
        }
       // system.debug('newToOldMCA2:' + newToOldMCA);
       // system.debug('oldToNewMCA:' + oldToNewMCA);
       // system.debug('strToOldMCA:' + strToOldMCA);
      //  system.debug('ALLMCIDset2:' + ALLMCIDset);
      //  检索所有合同保有设备的修理
        list<Repair__c> newRepiarList = new list<Repair__c>();
        if (ALLMCIDset.size() > 0) {
            newRepiarList =
                [select Id, Usage_Ratio_Price_Contract__c,
                 Usage_Ratio_Price_Guarantee__c,Usage_Ratio_Price_Service__c,
                 Delivered_Product__c,
                 Repair_cost__c,
                 Maintenance_Contract__c,
                 Maintenance_Contract__r.Contract_Start_Date__c,
                 Maintenance_Contract__r.Contract_End_Date__c,
                 Failure_Occurrence_Date__c,
                 Repair_Quotation_Id__c,
                 VM_Maintenance_Contract__c
                 from Repair__c
                 where (Maintenance_Contract__c != null or VM_Maintenance_Contract__c != null)
                 and (Maintenance_Contract__c in: ALLMCIDset
                      or VM_Maintenance_Contract__c in: ALLMCIDset)
                 and Status2__c != '00.删除'
                 and Status2__c != '00.取消'
                 and  Failure_Occurrence_Date__c <= : testDate
                 order by Maintenance_Contract__c
                ];
        }
        //system.debug('newRepiarList:' + newRepiarList);
       /* map<id, list<Repair__c>> MCIDtoRepiarMap =
            new map<id, list<Repair__c>> ();
        map<id, list<Repair__c>> MCAIDtoRepiarMap =
            new map<id, list<Repair__c>> ();*/
        // 根据记录类型的不同,分别计算上一期和上上期的修理金额
        if (newRepiarList != null && newRepiarList.size() > 0) {
            for (Repair__c rc : newRepiarList) {
                system.debug('rc'+rc);
                string mcID = rc.Maintenance_Contract__c == null ?
                          rc.VM_Maintenance_Contract__c : rc.Maintenance_Contract__c;
                if ( mcIDmap.containsKey(mcID)) {
                    Maintenance_Contract__c tempMC = UpdateMCMap.get(mcID);
                    System.debug( 'mcID ++++++++++++++ '+   mcID + rc.Delivered_Product__c);
                    // 20210906 gzw 计算维修合同报价/保有设备 上的实际报价金额
                    if(tempMC.RecordType_DeveloperName__c.equals('Maintenance_Contract')){
                        tempMC.currentTotalRepairAmount__c += rc.Usage_Ratio_Price_Contract__c;
                        if (mcAssetmap.containsKey(mcID + rc.Delivered_Product__c)) {
                            mcAssetmap.put(mcID + rc.Delivered_Product__c, mcAssetmap.get(mcID + rc.Delivered_Product__c) + rc.Usage_Ratio_Price_Contract__c);
                        }else{
                            mcAssetmap.put(mcID + rc.Delivered_Product__c, rc.Usage_Ratio_Price_Contract__c);
                        }
                    }else if(tempMC.RecordType_DeveloperName__c.equals('NewMaintenance_Contract')){
                        tempMC.currentTotalRepairAmount__c += rc.Usage_Ratio_Price_Service__c;
                        if (mcAssetmap.containsKey(mcID + rc.Delivered_Product__c)) {
                            mcAssetmap.put(mcID + rc.Delivered_Product__c, mcAssetmap.get(mcID + rc.Delivered_Product__c) + rc.Usage_Ratio_Price_Service__c);
                        }else{
                            mcAssetmap.put(mcID + rc.Delivered_Product__c, rc.Usage_Ratio_Price_Service__c);
                        }
                    }else if(tempMC.RecordType_DeveloperName__c.equals('VM_Contract')){
                        tempMC.currentTotalRepairAmount__c += rc.Usage_Ratio_Price_Guarantee__c;
                        if (mcAssetmap.containsKey(mcID + rc.Delivered_Product__c)) {
                            mcAssetmap.put(mcID + rc.Delivered_Product__c, mcAssetmap.get(mcID + rc.Delivered_Product__c) + rc.Usage_Ratio_Price_Guarantee__c);
                        }else{
                            mcAssetmap.put(mcID + rc.Delivered_Product__c, rc.Usage_Ratio_Price_Guarantee__c);
                        }
                    }
                    // 20210906 gzw 计算维修合同报价/保有设备 上的实际报价金额
                }
                string mcaIDandAssetID = '' + mcID + rc.Delivered_Product__c;
                system.debug('mcaIDandAssetID'+mcaIDandAssetID);
                if (oldToNewMCA.containsKey(mcaIDandAssetID )
                   ) {
                    Maintenance_Contract_Asset__c OldMCA =
                        strToOldMCA.get(mcaIDandAssetID);
                    
                    //system.debug('OldMCA.Maintenance_Contract__r.First_Estimate_Date__c:'+OldMCA.Maintenance_Contract__r.First_Estimate_Date__c);
                    if (rc.Failure_Occurrence_Date__c >=
                            getTheFirstDayOftheMonth(OldMCA.Maintenance_Contract__r.First_Estimate_Date__c)
                            && rc.Failure_Occurrence_Date__c <= OldMCA.endDate_sum__c
                            && OldMCA.Maintenance_Contract__r.First_Estimate_Date__c <= OldMCA.endDate_sum__c
                             ) {
                        Maintenance_Contract_Asset__c tempNewMCA =
                            oldToNewMCA.get(mcaIDandAssetID);
                        Maintenance_Contract__c newMC =
                            UpdateMCMap.get(tempNewMCA.Maintenance_Contract__c);
                        if(newMC.RecordType_DeveloperName__c.equals('NewMaintenance_Contract')){
                        newMC.previousTotalRepairAmount__c += rc.Usage_Ratio_Price_Service__c;
                        } 
                    }
 
                }
            }
        }
        //system.debug('UpdateMCMap last:' + UpdateMCMap);
        StaticParameter.EventOpportunityPileUpExeFlg = true;
        // EventC⇒Event処理後、逆更新をスルー用
        StaticParameter.NotUpdEventCFlg = true;
        // 積み上げ処理後、トリガをスルー用
        StaticParameter.EscapeNFM001Trigger = true;
        StaticParameter.EscapeNFM001AgencyContractTrigger = true;
        StaticParameter.EscapeNFM001AgencyContractTrigger2 = true;
        StaticParameter.EscapeNFM007Trigger = true;
        StaticParameter.EscapeOpportunityBefUpdTrigger = true;
        StaticParameter.EscapeOpportunityHpDeptUpdTrigger = true;
        StaticParameter.EscapeSyncOpportunityTrigger = true;
        StaticParameter.EscapeMaintenanceContractAfterUpdateTrigger = true;
        StaticParameter.EscapeSyncProduct2Trigger = true;
        // trueのとき、リードのトリガーをスルーする
        StaticParameter.EscapeLeadTrigger = true;
        StaticParameter.EscapeAccountTrigger = true;
 
        StaticParameter.EscapeConsumableOrderDetail2Trigger = true;
 
        StaticParameter.EscapeNFM010UpsertStatuAchievementsTrigger = true;
        // 直销耗材不直销 ConsumableAssetHander
        StaticParameter.ConsumableAssetHanderTrigger = true;
 
        // 跳过不涉及备品借出的逻辑
        StaticParameter.rentalApplyIsRunning = true;
 
        // accountdailyUpdate 跳过 更新询价
        StaticParameter.EscapeOpportunityownerUpdate  = true;
        // 20210906 gzw 计算维修合同报价/保有设备 上的实际报价金额
        List<Maintenance_Contract_Asset_Estimate__c> McaeupList = new List<Maintenance_Contract_Asset_Estimate__c>();
        for (String str :mcAssetmap.keyset()) {
            if (mcaasmap.containsKey(str)) {
                for (Maintenance_Contract_Asset_Estimate__c mca: mcaasmap.get(str) ) {
                    mca.ContractAsset_Amont__c = mcAssetmap.get(str);
                    McaeupList.add(mca);
                }
            }
        }
        if (McaeupList.size() > 0) {
            update McaeupList;
        }
        // 20210906 gzw 计算维修合同报价/保有设备 上的实际报价金额
        Database.SaveResult[] saveResults = Database.update(UpdateMCMap.values(), false);
            //                system.debug('saveResults'+saveResults);
        totalCount = + saveResults.size();
        for (Integer i = 0; i < saveResults.size(); i++) {
            if (!saveResults.get(i).isSuccess() || Test.isRunningTest()) {
                logstr += '维修合同:' + UpdateMCMap.values().get(i).Id + ',';
                errorstr += saveResults.get(i).getErrors() + '\n';
                failedCount ++;
            }
        }
        system.debug('11111111111111111111111updateAssetMap'+updateAssetMap.values());
        updateAsset (updateAssetMap.values());
    }
    global void finish(Database.BatchableContext BC) {
        BatchIF_Log__c batchIfLog = new BatchIF_Log__c();
        batchIfLog.Type__c = 'MCAssetUpdate';
        if (logstr.length() > 60000) {
            logstr = logstr.substring(0, 60000);
        }
        batchIfLog.Log__c = logstr;
        logstr += '\nBatchMCAssetUpdateEnd';
        if (errorstr.length() > 60000) {
            batchIfLog.ErrorLog__c = errorstr.substring(0, 60000);
        } else {
            batchIfLog.ErrorLog__c = errorstr.substring(0, errorstr.length());
        }
        insert batchIfLog;
        emailMessages.add('失败日志ID为:' + batchIfLog.Id);
        sendFieldEmail();
 
 
        //2021-04-21  mzy  add  start
        //目前不希望EventToEventDetailsBatch 运行
        IsNeedExecute = false;
        if(!Test.isRunningTest() &&IsNeedExecute==true){
            //batch里调用下一个batch时,希望跟原有的Schedule里面传的条数保持一致
            Id execBTId = Database.executebatch(new EventToEventDetailsBatch(true),20);
        }
        //2021-04-21  mzy  add  end
    }
     // 更新当期维修合同保有设备
    private void updateCurrentMCAsset (list<Maintenance_Contract_Asset__c> mcaList,
                                      map<id, Maintenance_Contract__c> UpdateMCMap,
                                       Set<ID> allAssetIDSet,
                                       map<id, Maintenance_Contract_Asset__c> newToOldMCA,
                                      Set<Id> newAssetIDset,
                                       map<id, Maintenance_Contract_Asset__c> assetIDtoMCA
                                      ) {
        for (Maintenance_Contract_Asset__c mca : mcaList) {
            Maintenance_Contract__c tempMC = UpdateMCMap.get(mca.Maintenance_Contract__c); 
            //如果是多年保修合同且输入日期晚于结束日期,则使用保有设备上的全额no discount 和计提金额
            // 计算本期合同金额(多年保修故障风险率用)、合同金额(多年保修故障风险率管理用)
            if (testDate > mca.endDate_sum__c &&
                    mca.Maintenance_Contract__r.RecordType.DeveloperName.equals('VM_Contract')) {
                tempMC.currentTotalContractAmountVM__c +=
                    mca.No_discount__c == null ?
                    0 :
                    mca.No_discount__c;
                 tempMC.currentTotalGuaranteePrice__c +=
                    mca.GuaranteePrice_Amount_Text__c == null ?
                    0 :
                    mca.GuaranteePrice_Amount_Text__c;
                 
                //continue;
            } 
            //如果是多年保修合同且输入日期晚于开始日期,则使用保有设备上的全额no discount 和计提金额 按照日期比例
            // 计算本期合同金额(多年保修故障风险率用)、合同金额(多年保修故障风险率管理用)
            else if ( testDate >= mca.startDate_sum__c &&
                        mca.Maintenance_Contract__r.RecordType.DeveloperName.equals('VM_Contract')) {
                Decimal tempNo_discount =  mca.No_discount__c == null ?
                                           0 :
                                           mca.No_discount__c;
                Decimal GuaranteePrice_Amount =  mca.GuaranteePrice_Amount_Text__c == null ?
                                           0 :
                                           mca.GuaranteePrice_Amount_Text__c;
                system.debug('mca.startDate_sum__c.daysBetween(testDate):'+
                    mca.startDate_sum__c.daysBetween(testDate));
                tempMC.currentTotalContractAmountVM__c +=
                    tempNo_discount * (mca.startDate_sum__c.daysBetween(testDate) + 1) /
                    (mca.startDate_sum__c.daysBetween(mca.endDate_sum__c) + 1);
                tempMC.currentTotalGuaranteePrice__c +=
                    GuaranteePrice_Amount * (mca.startDate_sum__c.daysBetween(testDate) + 1) /
                    (mca.startDate_sum__c.daysBetween(mca.endDate_sum__c) + 1);
                //continue;
            }
            // 服务合同需要再检索上期维修合同保有设备剩余
            if (mca.Maintenance_Contract__r.RecordType.DeveloperName.equals('NewMaintenance_Contract')) {
                newAssetidset.add(mca.Asset__c);
            }
            // 找出来检索出来的维修合同保有中的最新的
            if (assetIDtoMCA.containsKey(mca.Asset__c)) {
                Maintenance_Contract_Asset__c tempMCA =
                    assetIDtoMCA.get(mca.Asset__c);
                if (tempMCA.endDate_sum__c < mca.endDate_sum__c) {
                    assetIDtoMCA.put(mca.Asset__c, mca);
                }
            } else {
                assetIDtoMCA.put(mca.Asset__c, mca);
            }
            allAssetIDSet.add(mca.Asset__c);
            newToOldMCA.put(mca.id, null);
        }
    }
    // 更新保有设备,并记录下出错数据ID和出错信息
    private void updateAsset (list<Asset> assetList) {
        Database.SaveResult[] saveResults = Database.update(assetList, false);
        totalCount = + saveResults.size();
        for (Integer i = 0; i < saveResults.size(); i++) {
            if (!saveResults.get(i).isSuccess() || Test.isRunningTest()) {
                logstr += 'asset:' + assetList.get(i).Id + ',';
                errorstr += saveResults.get(i).getErrors() + '\n';
                failedCount ++;
            }
        }
    }
 
    // 如果 testDate 有值,则返回testDate 值,否则如果当天是当月1日,则取上月最后一日
    @TestVisible
    public static Date Datecheck(Date testDate) {
        Date today = testDate;
        if (testDate == null) {
             today = Date.today();
        }
        today = today.addDays(-1);   
        return today;
    }
    // 判断是否每天执行的batch
    @TestVisible
    private static Boolean isDaily(Date testDate) {
        if(testDate!=null && testDate.day()==1)
            return false;
        return true;
    }
     @TestVisible
    private static void test() {
        integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        
    }
    /*
    public Date PickEarlierDate( Date tempDate1, Date tempDate2) {
        if (tempDate2 == null) {
            return tempDate1;
        } else {
            return tempDate2 > tempDate1 ? tempDate1 : tempDate2;
        }
    }*/
    // 获取 当月第一天
    public Date getTheFirstDayOftheMonth( Date tempDate) {
        if (tempDate == null) {
            return null;
        } else {
            return Date.newInstance(tempDate.year(), tempDate.month(), 1);
        }
    }
 
    // 发送提醒邮件
    private void sendFieldEmail() {
        PretechBatchEmailUtil be = new PretechBatchEmailUtil();
        String[] toList = new String[] {UserInfo.getUserEmail()};
        String title = '更新维修合同上一期上上期消费率失败';
        String[] ccList = new String[] {};
        if (System.Test.isRunningTest()) {
            be.successMail('', 1);
        }
        if (emailMessages.size() > 0 && failedCount > 0) {
            be.failedMail(toList, ccList, title,
                          String.join(this.emailMessages, '\n'),
                          totalCount, totalCount - failedCount, failedCount,'',false);
            if(!Test.isRunningTest())
            be.send();
        }
    }
}