global class CloseInventoryTaskBatch implements Schedulable, Database.Batchable<sObject> {

    public static List<String> statusList = new List<String>{
            '01 分配', '02 接受', '05 延期'
    };

    global void execute(SchedulableContext sc) {
        Database.executeBatch(new CloseInventoryTaskBatch());
    }

    global CloseInventoryTaskBatch() {
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([
                SELECT Id, taskStatus__c, Finish_Date__c, delayToDate__c 
                FROM task__c 
                WHERE taskStatus__c IN: statusList 
                AND (RecordType.Name = '盘点检查计划' OR RecordType.Name = '温湿度检查计划')]);
    }

    global void execute(Database.BatchableContext BC, list<task__c> scope) {
        Date today = Date.today();
        Integer numberOfDays = Date.daysInMonth(today.year(), today.month());
        Date lastDayOfMonth = Date.newInstance(today.year(), today.month(), numberOfDays);
        // 每个月的最后一天才执行
        if(!Test.isRunningTest()){
            if (today != lastDayOfMonth) {
                return;
            }
        }
        
        List<task__c> tempList = new List<task__c>();
        for (task__c t : scope) {
            if (t.taskStatus__c == '05 延期' && t.delayToDate__c < = today) {
                t.taskStatus__c = '06 关闭';
                tempList.add(t);
            } else if ((t.taskStatus__c == '01 分配' || t.taskStatus__c == '02 接受') && t.Finish_Date__c < = today) {
                t.taskStatus__c = '06 关闭';
                tempList.add(t);
            }
        }

        if (!tempList.isEmpty()) {
            update tempList;
        }
    }

    global void finish(Database.BatchableContext BC) {
    }
}