高章伟
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
global class RepairWorkdayBatch implements Database.Batchable<sObject> {
    global final String repairId;
 
    global RepairWorkdayBatch(String id) {
        repairId = id;
    }
 
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'select id, Repair_Start_Date__c, Repair_Final_Inspection_Date__c, TAT_elapsed_workday__c from Repair__c where Repair_Start_Date__c <> null and Repair_Final_Inspection_Date__c = null';
        if (repairId != null && repairId.length() > 0) {
            query += ' and Id = :repairId';
        }
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext BC, List<sObject> rpList) {
        // 日历查询开始
        Date sd = null;
        // 日历查询截至
        Date ed = Date.today();
        for (SObject so : rpList) {
            Repair__c rp = (Repair__c) so;
            // 日历查询开始
            if (sd == null || rp.Repair_Start_Date__c < sd) {
                sd = rp.Repair_Start_Date__c;
            }
        }
        // 取得日历
        Map<String, Integer> ocMap = new Map<String, Integer>();
        if (sd != null) {
            List<OlympusCalendar__c> ocList = [
                select Id, Date__c, IsWorkDay__c
                  from OlympusCalendar__c
                 where Date__c >= :sd
                   and Date__c <= :ed
                 order by Date__c];
 
            for (OlympusCalendar__c oc : ocList) {
                Date d = oc.Date__c;
                Decimal iswd = oc.IsWorkDay__c;
                ocMap.put(d.format(), iswd.intValue());
            }
        }
        // 设定TAT:修理时长(工作日)
        List<Repair__c> updList = new List<Repair__c>();
        for (SObject so : rpList) {
            Repair__c rp = (Repair__c) so;
            Date d1 = rp.Repair_Start_Date__c;
            Date d2 = Date.today();
            Integer days = 0;
            if (d1.daysBetween(d2) >= 0) {
                Repair__c r = new Repair__c(Id = rp.Id);
                for (Integer i = 0; i <= d1.daysBetween(d2); i++) {
                    Date d = d1 + i;
                    if (ocMap.containsKey(d.format())) {
                        days += ocMap.get(d.format());
                    }
                }
                r.TAT_elapsed_workday__c = days;
                updList.add(r);
            }
        }
        if (updList.size() > 0) {
            update updList;
        }
    }
 
    global void finish(Database.BatchableContext BC) {
        // 无操作
    }
 
}