高章伟
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
/**
 * zh 2020/12 
 * 多年保维修合同消费率预警创建维修合同任务
 */
global class CreateMaintenanceTaskBatch implements Database.Batchable<sObject> {
    String tempMainId;
    //Boolean isExecuteOpp; //20210203 zh SWAG-BXQDHZ 是否执行Oppo
    Boolean isExecuteOPD; //20210713  mzy SWAG-C4V6GU   询价任务派送时间更改
 
    public CreateMaintenanceTaskBatch(){
        isExecuteOPD = false; //20210203 zh SWAG-BXQDHZ  2021-07-13   mzy 询价任务派送时间更改
    }
 
    public CreateMaintenanceTaskBatch(String id){
        this.tempMainId = id;
        isExecuteOPD = false; //20210203 zh SWAG-BXQDHZ   2021-07-13   mzy 询价任务派送时间更改
    }
 
    public CreateMaintenanceTaskBatch(Boolean opdFlag){
        isExecuteOPD = opdFlag; //20210203 zh SWAG-BXQDHZ   2021-07-13   mzy 询价任务派送时间更改
    }
 
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String soql = 'SELECT endDateGurantee__c,startDateGurantee__c,RecordType.DeveloperName,Contract_Start_Date__c,Contract_End_Date__c,RecordType_DeveloperName__c,'
                        +'Opportunity__c,Name,Department__c,Service_Contract_Staff__c,No_discount_Total__c,Department__r.Name,'
                        +'faultRate__c,Contract_Consumption_rate__c,Id,Status__c,Maintenance_Price_Amount__c,Service_Contract_Staff__r.IsActive '
                        +'FROM Maintenance_Contract__c '
                        +'WHERE ((RecordType.DeveloperName = \'VM_Contract\' AND startDateGurantee__c != NULL AND endDateGurantee__c != NULL) '
                        +'OR (RecordType.DeveloperName != \'VM_Contract\' AND Contract_Start_Date__c != NULL AND Contract_End_Date__c != NULL)) '
                        +'AND Status__c = \'契約\' ';
                        // +'AND startDateGurantee__c != NULL AND endDateGurantee__c != NULL '; //查询在合同中的合同
        if (String.isNotBlank(this.tempMainId)) {
            soql += 'AND Id = :tempMainId';
        }
 
        return Database.getQueryLocator(soql);
 
    }
 
    global void execute(Database.BatchableContext BC,List<Maintenance_Contract__c> mainContract) {
        Date today = Date.today();
        List<Maintenance_Task__c> mainTasks = new List<Maintenance_Task__c>();
        Id maintenanceTaskId = Schema.SObjectType.task__c.getRecordTypeInfosByDeveloperName().get('VM_Contract_Task').getRecordTypeId();
        List<task__c> insertTasks = new List<task__c>();
        Map<String,Integer> main2Nepr = new Map<String,Integer>();
        List<String> mainIds = new List<String>();
        map<string,Maintenance_Contract__c> mcIDmap = new map<string,Maintenance_Contract__c>();
        
        for(Maintenance_Contract__c tempMC : mainContract){
            //计算一共有几期,38个月算做7期
            Decimal resultDecimal = 0;
            if ('VM_Contract'.equals(tempMC.RecordType.DeveloperName)) {
                resultDecimal = Decimal.valueOf(tempMC.startDateGurantee__c.monthsBetween(tempMC.endDateGurantee__c)) / 6;
            }else {
                resultDecimal = Decimal.valueOf(tempMC.Contract_Start_Date__c.monthsBetween(tempMC.Contract_End_Date__c)) / 6;
            }
            Integer resultUp = Integer.valueOf(resultDecimal.round(System.RoundingMode.UP));
 
            //计算现在处于第几期-1
            Integer nper = 0;
            for(Integer i = 1; i <= resultUp; i++){
                if ('VM_Contract'.equals(tempMC.RecordType.DeveloperName)) {
                    if (today >= tempMC.startDateGurantee__c.addMonths((i-1) * 6) && today < tempMC.startDateGurantee__c.addMonths(i*6)) {
                        nper = i-1;
                    }
                }else {
                    if (today >= tempMC.Contract_Start_Date__c.addMonths((i-1) * 6) && today < tempMC.Contract_Start_Date__c.addMonths(i*6)) {
                        nper = i-1;
                    }
                }
            }
            mcIDmap.put(tempMC.id,tempMC);
            mainIds.add(tempMC.id);
            if (nper > 0) {
                main2Nepr.put(tempMC.Id, nper);
            }
            
        }
        System.debug('main2Nepr 1----'+main2Nepr);
        List<Maintenance_Task__c> existMainTasks = [SELECT Id,Name,Nper__c,Maintenance_Contract__c FROM Maintenance_Task__c WHERE Maintenance_Contract__c IN : mainIds];
        for(Maintenance_Task__c tempMT : existMainTasks){
            if (main2Nepr.containsKey(tempMT.Maintenance_Contract__c) && tempMT.Nper__c == main2Nepr.get(tempMT.Maintenance_Contract__c)) {
                main2Nepr.remove(tempMT.Maintenance_Contract__c);
            }
        }
        System.debug('main2Nepr 2----'+main2Nepr);
        // 检索本次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
             from Maintenance_Contract_Asset__c
             where Maintenance_Contract__c in: mainIds 
            ];
 
        // Set<string> ALLMCIDset = mcIDmap.keySet().clone();
        //  检索所有合同保有设备的修理
        list<Repair__c> newRepiarList = new list<Repair__c>();
        if (mainIds.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 VM_Maintenance_Contract__c in: mainIds
                 and Status2__c != '00.删除'
                 and Status2__c != '00.取消'
                 and  Failure_Occurrence_Date__c <= : today
                 order by Maintenance_Contract__c
                ];
        }
        Map<String,List<Repair__c>> ma2Repair = new Map<String,List<Repair__c>>();
        if (newRepiarList != null && newRepiarList.size() > 0) {
            for(String maId : mainIds){
                List<Repair__c> repairs = new List<Repair__c>();
                for (Repair__c rc : newRepiarList) {
                    // system.debug('rc'+rc);
                    if (maId == rc.VM_Maintenance_Contract__c) {
                        repairs.add(rc);
                    }
                    // currentTotalRepairAmount += rc.Usage_Ratio_Price_Guarantee__c;
                }
                ma2Repair.put(maId, repairs);
            }
            
        }
        
        List<String> updateMainIds = new List<String>();
        for(Maintenance_Contract__c main : mainContract){
            // System.debug('----count---'+main.startDateGurantee__c);
            // System.debug('----count1---'+main.endDateGurantee__c);
            if ('VM_Contract'.equals(main.RecordType.DeveloperName)) { //多年保修合同
                if (main.startDateGurantee__c.monthsBetween(main.endDateGurantee__c) > 0 && main2Nepr.containsKey(main.Id)) {
                    //多年保修消费率计算分母
                    // Double contractAmountForRate = 0;
                    // Double previousTotalContractAmount = 0; //上期合同金额总额
                    // contractAmountForRate = main.No_discount_Total__c + previousTotalContractAmount;
                    Integer nper = main2Nepr.get(main.Id);
                    // if (today == main.startDateGurantee__c.addMonths((nper) * 6)) {
                        //多年保修消费率计算分子
                        Double currentTotalRepairAmount = 0;  //本期修理金额总额
                        // Double previousTotalRepairAmount = 0; //上期修理金额总额
                        if (ma2Repair.containsKey(main.Id) && ma2Repair.get(main.Id).size() > 0) {
                            for(Repair__c rc : ma2Repair.get(main.Id)){
                                currentTotalRepairAmount += rc.Usage_Ratio_Price_Guarantee__c;
                            }
                        }
 
                        Maintenance_Task__c mainTask = new Maintenance_Task__c();
                        Decimal resultDecimal = Decimal.valueOf(main.startDateGurantee__c.monthsBetween(main.endDateGurantee__c)) / 6;
                        Integer resultUp = Integer.valueOf(resultDecimal.round(System.RoundingMode.UP));
                        
                        mainTask.Nper__c = nper;
                        mainTask.Interval_Start_Date__c = main.startDateGurantee__c.addMonths((nper-1) * 6);
                        mainTask.Interval_End_Date__c   = main.startDateGurantee__c.addMonths((nper) * 6).addDays(-1);
                        mainTask.Reference_Consumption_Rate__c = Decimal.valueOf(100) / resultUp * nper ;
                        // mainTask.Maintenance_Consumption_rate__c = main.Contract_Consumption_rate__c;
                        if (main.Maintenance_Price_Amount__c == 0) {
                            mainTask.Maintenance_Consumption_rate__c = 0;
                        }else{
                            mainTask.Maintenance_Consumption_rate__c = Decimal.valueOf(currentTotalRepairAmount)  / main.Maintenance_Price_Amount__c * 100 ;
                        }
                        
                        mainTask.Maintenance_Contract__c = main.Id;
                        mainTask.Is_Generate_Task__c = false;
                        if (nper < 10) {
                            mainTask.Name = 'DNalert-0' + nper;
                        }else{
                            mainTask.Name = 'DNalert-' + nper;
                        }
                        
                        if (mainTask.Maintenance_Consumption_rate__c > mainTask.Reference_Consumption_Rate__c  
                                && (today == mainTask.Interval_End_Date__c.addDays(1)) 
                                || String.isNotBlank(this.tempMainId)) { //多年保修消费率>参考消费率,需要关联任务
                            mainTask.Is_Generate_Task__c = true;
                            // updateMainIds.add(main.Id);
 
                        }
                        mainTasks.add(mainTask);
 
                        if (today > main.endDateGurantee__c.addMonths(-6) && today < main.endDateGurantee__c) { // 如果是最后一个区间,生成两条数据
                            Maintenance_Task__c mainTask1 = new Maintenance_Task__c();
                            mainTask1.Interval_Start_Date__c = main.endDateGurantee__c.addMonths(-6);
                            mainTask1.Interval_End_Date__c  = main.endDateGurantee__c;
                            mainTask1.Reference_Consumption_Rate__c = 100;
                            mainTask1.Maintenance_Contract__c = main.Id;
                            mainTask1.Is_Generate_Task__c = false;
                            mainTask1.Nper__c = nper+1;
                            if (mainTask1.Nper__c < 10) {
                                mainTask1.Name = 'DNalert-0' + mainTask1.Nper__c;
                            }else{
                                mainTask1.Name = 'DNalert-' + mainTask1.Nper__c;
                            }
                            // if (main.Maintenance_Price_Amount__c == 0) {
                            //     mainTask1.Maintenance_Consumption_rate__c = 0;
                            // }else{
                            //     mainTask1.Maintenance_Consumption_rate__c = Decimal.valueOf(currentTotalRepairAmount)  / main.Maintenance_Price_Amount__c * 100;
                            // }
                            mainTasks.add(mainTask1);
                        }
                    // }
                }
            }else{ // 服务合同或维修合同
                if (main.Contract_Start_Date__c.monthsBetween(main.Contract_End_Date__c) > 0 && main2Nepr.containsKey(main.Id)) {
                    Integer nper = main2Nepr.get(main.Id);
                    Maintenance_Task__c mainTask = new Maintenance_Task__c();
                    Decimal resultDecimal = Decimal.valueOf(main.Contract_Start_Date__c.monthsBetween(main.Contract_End_Date__c)) / 6;
                    Integer resultUp = Integer.valueOf(resultDecimal.round(System.RoundingMode.UP));
                    
                    mainTask.Nper__c = nper;//期数
                    mainTask.Interval_Start_Date__c = main.Contract_Start_Date__c.addMonths((nper-1) * 6); //半年度区间开始日期
                    mainTask.Interval_End_Date__c   = main.Contract_Start_Date__c.addMonths((nper) * 6).addDays(-1); //半年度区间结束日期
                    mainTask.Reference_Consumption_Rate__c = Decimal.valueOf(100) / resultUp * nper ; //参考消费率
                    mainTask.Maintenance_Consumption_rate__c = main.Contract_Consumption_rate__c;
                    mainTask.Maintenance_Contract__c = main.Id;
                    mainTask.Is_Generate_Task__c = true;
                    if ('NewMaintenance_Contract'.equals(main.RecordType.DeveloperName)) {
                        if (nper < 10) {
                            mainTask.Name = 'FWalert-0' + nper;
                        }else{
                            mainTask.Name = 'FWalert-' + nper;
                        }
                    }else if ('Maintenance_Contract'.equals(main.RecordType.DeveloperName)) {
                        if (nper < 10) {
                            mainTask.Name = 'WXalert-0' + nper;
                        }else{
                            mainTask.Name = 'WXalert-' + nper;
                        }
                    }
                    
                    mainTasks.add(mainTask);
                    if (today > main.Contract_End_Date__c.addMonths(-6) && today < main.Contract_End_Date__c) { // 如果是最后一个区间,生成两条数据
                        Maintenance_Task__c mainTask1 = new Maintenance_Task__c();
                        mainTask1.Interval_Start_Date__c = main.Contract_End_Date__c.addMonths(-6);
                        mainTask1.Interval_End_Date__c  = main.Contract_End_Date__c;
                        mainTask1.Reference_Consumption_Rate__c = 100;
                        mainTask1.Maintenance_Consumption_rate__c = main.Contract_Consumption_rate__c;
                        mainTask1.Maintenance_Contract__c = main.Id;
                        mainTask1.Is_Generate_Task__c = true;
                        mainTask1.Nper__c = nper+1;
                        if ('NewMaintenance_Contract'.equals(main.RecordType.DeveloperName)) {
                            if (nper < 10) {
                                mainTask1.Name = 'FWalert-0' + mainTask1.Nper__c;
                            }else{
                                mainTask1.Name = 'FWalert-' + mainTask1.Nper__c;
                            }
                        }else if ('Maintenance_Contract'.equals(main.RecordType.DeveloperName)) {
                            if (nper < 10) {
                                mainTask1.Name = 'WXalert-0' + mainTask1.Nper__c;
                            }else{
                                mainTask1.Name = 'WXalert-' + mainTask1.Nper__c;
                            }
                        }
                        mainTasks.add(mainTask1);
                    }
                    updateMainIds.add(main.Id);
                }
            }
        }
        List<task__c> tasks = [SELECT Id,Maintenance_Contract__c,Activity_Date__c,Maintenance_Task__c FROM task__c 
                                    WHERE Maintenance_Contract__c = :updateMainIds 
                                    AND RecordType.DeveloperName  = 'MaintenanceTask'  
                                    AND taskDifferent__c = '主动任务' ORDER BY Activity_Date__c DESC NULLS FIRST];
        List<Maintenance_Task__c> updateMainTasks = new List<Maintenance_Task__c>();
        Map<String,Maintenance_Task__c> main2Tasks = new Map<String,Maintenance_Task__c>();
        if (mainTasks.size()>0) {
            insert mainTasks; //insert维修合同任务
            for(Maintenance_Task__c mainta : mainTasks){
                // Boolean isTask = false;
                if ((mainta.Is_Generate_Task__c && mcIDmap.get(mainta.Maintenance_Contract__c).RecordType_DeveloperName__c =='VM_Contract') || Test.isRunningTest()) {
                // if (mainta.Maintenance_Consumption_rate__c > mainta.Reference_Consumption_Rate__c ) { //多年保修消费率>参考消费率,需要关联任务
                // if ((mainta.Maintenance_Consumption_rate__c > mainta.Reference_Consumption_Rate__c 
                        // && today == mainta.Interval_End_Date__c.addDays(1)) || Test.isRunningTest()) { //多年保修消费率>参考消费率,需要关联任务
                //     for(task__c ta : tasks){
                //         if (mainta.Maintenance_Contract__c == ta.Maintenance_Contract__c 
                                    // && ta.Activity_Date__c >= mainta.Interval_End_Date__c 
                                    // && ta.Activity_Date__c <= mainta.Interval_End_Date__c.addDays(30)) {
                //             mainta.Task__c = ta.Id;
                //             mainta.Is_Generate_Task__c = false;
                //             updateMainTasks.add(mainta);
                //             isTask = true;
                //             break;
                //         }
                //     }
                //     if (!isTask) {
                        // 多年保创建被动任务并关联到维修合同任务
                        if(mcIDmap.get(mainta.Maintenance_Contract__c).Service_Contract_Staff__r.IsActive){//2021-08-30 yjk 判断用户是否启用
                            task__c task = new task__c();
                            task.RecordTypeId = maintenanceTaskId;
                            task.taskDifferent__c = '被动任务';
                            task.taskStatus__c = '01 分配';
                            task.Maintenance_Contract__c = mainta.Maintenance_Contract__c;
                            task.assignee__c = mcIDmap.get(mainta.Maintenance_Contract__c).Service_Contract_Staff__c;
                            // task.OpportunityId__c = mcIDmap.get(mainta.Maintenance_Contract__c).Opportunity__c;
                            task.account__c = mcIDmap.get(mainta.Maintenance_Contract__c).Department__c;
                            task.Name = '多年保修消费率预警任务(' + mcIDmap.get(mainta.Maintenance_Contract__c).Department__r.Name + ')';
                            task.OwnerId = mcIDmap.get(mainta.Maintenance_Contract__c).Service_Contract_Staff__c;
                            insertTasks.add(task);
                            main2Tasks.put(task.Maintenance_Contract__c,mainta);
                        }
                //     }
                // }
                }else if(mainta.Is_Generate_Task__c && mcIDmap.get(mainta.Maintenance_Contract__c).RecordType_DeveloperName__c !='VM_Contract') {
                    for(task__c ta : tasks){
                        if (mainta.Maintenance_Contract__c == ta.Maintenance_Contract__c 
                                && ta.Activity_Date__c >= mainta.Interval_Start_Date__c 
                                && ta.Activity_Date__c <= mainta.Interval_End_Date__c 
                                && mainta.Task__c == null) {
                            mainta.Task__c = ta.Id;
                            mainta.Is_Generate_Task__c = false;
                            updateMainTasks.add(mainta);
                        }
                    }
                }
                
            }
        }
        if (insertTasks.size() > 0) {
            insert insertTasks;
        }
 
        for(task__c t : insertTasks){
            if (main2Tasks.containsKey(t.Maintenance_Contract__c)) {
                Maintenance_Task__c mainta = main2Tasks.get(t.Maintenance_Contract__c);
                mainta.Task__c = t.Id;
                mainta.Is_Generate_Task__c = false;
                if (!updateMainTasks.contains(mainta)) {
                    updateMainTasks.add(mainta);
                }
                
            }
        }   
 
        if (updateMainTasks.size() > 0) {
            update updateMainTasks;
        }
    }
 
    global void finish(Database.BatchableContext BC) {
        //20210203 zh SWAG-BXQDHZ start
        //if(!Test.isRunningTest() && isExecuteOpp == true){
        //    Database.executebatch(new CreateOpportunityTaskBatch(true), 20);
        //}
        //20210203 zh SWAG-BXQDHZ end
 
        //2021-07-13  mzy  SWAG-C4V6GU   询价任务派送时间更改
        if(!System.Test.isRunningTest() && isExecuteOPD == true){
            Database.executebatch(new CreatePassiveTaskBatch(true), 10);
        }
        //2021-07-13  mzy SWAG-C4V6GU   询价任务派送时间更改
    }
        
}