global class HistoryTaskBatch implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext BC) {
        String soql = 'SELECT Activity_Date__c,Event__c,Id,Daily_Report__c,Event__r.ActivityDate__c,Event__r.Daily_Report__c FROM task__c WHERE Daily_Report_Status__c = null AND Activity_Date__c!=null';
        return Database.getQueryLocator(soql);

    }

    global void execute(Database.BatchableContext BC,List<task__c> tasks) {
        List<String> taskIds = new List<String>();
        Map<String,task__c> taskMaps = new Map<String,task__c>();
        List<task__c> updateTask = new List<task__c>();
        for(task__c task : tasks){
            if(task.Event__c == null){
                taskIds.add(task.Id);
                taskMaps.put(task.Id, task);
            }else{
                task.Activity_Date__c = task.Event__r.ActivityDate__c;
                task.Daily_Report__c = task.Event__r.Daily_Report__c;
                updateTask.add(task);
            }
        }
        if (taskIds.size() > 0) {
            List<Event> events = [SELECT EventC_ID__c,Task_ID__c,Id FROM Event WHERE Task_ID__c IN :taskIds];
            Map<String,task__c> eventC2TaskMaps = new Map<String,task__c>();
            List<String> eventcIds = new List<String>();
            for(Event e : events){
                System.debug(e.EventC_ID__c+'------'+taskMaps.containsKey(e.Task_ID__c)+'-----'+taskMaps);
                if (e.EventC_ID__c != null && taskMaps.containsKey(e.Task_ID__c)) {
                    eventcIds.add(e.EventC_ID__c);
                    eventC2TaskMaps.put(e.EventC_ID__c, taskMaps.get(e.Task_ID__c));
                }
            }
            if (eventcIds.size() > 0) {
                List<Event__c> eventcs = [SELECT ActivityDate__c,Daily_Report__c FROM Event__c WHERE Id IN :eventcIds];
                for(Event__c ec : eventcs){
                    if (eventC2TaskMaps.containsKey(ec.Id)) {
                        eventC2TaskMaps.get(ec.Id).Event__c = ec.Id;
                        eventC2TaskMaps.get(ec.Id).Activity_Date__c = ec.ActivityDate__c;
                        eventC2TaskMaps.get(ec.Id).Daily_Report__c = ec.Daily_Report__c;
                        updateTask.add(eventC2TaskMaps.get(ec.Id));
                    }
                }
            }
        }
        if (updateTask.size() > 0) {
            update updateTask;
        }
    }

    global void finish(Database.BatchableContext BC) {

    }
    @TestVisible private void test() {
        Integer i = 0;
        
    }
       
}