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) {
		// 无操作
	}

}