global class MonthlyVisitBatch1 implements Database.Batchable<SObject> , Database.Stateful{
    
    private final List<String> oppIdList = null;
    
    global MonthlyVisitBatch1(){
    }

    global MonthlyVisitBatch1(List<String> str){
        oppIdList = str;
    }

    global Database.QueryLocator start(Database.BatchableContext BC){
        //作成中-草案中  申請中-申请中  非承認-不批准  承認-批准
        //限制日报的日期在当月
        String sql = 'select Opportunity__c, id from Event_Oppotunity__c '
                   + 'where Daily_Report__r.MonthlyReportFlg__c = 1 ' 
                   + 'limit 1' ;
        System.debug('ou---test123sql:'+sql);          
        return Database.getQueryLocator(sql);
    }

    global void execute(Database.BatchableContext BC, List<Event_Oppotunity__c> eoList){
        System.debug('test123');
        Map<String,Integer> NumMap = new Map<String,Integer>();
        List<String> opp2IdList = new List<String>();

        List<Event_Oppotunity__c> eoppList = new List<Event_Oppotunity__c>();
        if(oppIdList <> null){
            eoppList = [
            select id,Opportunity__c, Daily_Report__r.Status__c from Event_Oppotunity__c
            Where Daily_Report__r.MonthlyReportFlg__c = 1
            And Opportunity__c in :oppIdList
            ];
        }else{
            eoppList = [
            select id,Opportunity__c, Daily_Report__r.Status__c from Event_Oppotunity__c
            Where Daily_Report__r.MonthlyReportFlg__c = 1
            ];
        }
        System.debug('test123eoppList：'+eoppList);

        if(eoppList.Size() > 0){
            for(Event_Oppotunity__c eopp : eoppList){
                opp2IdList.add(eopp.Opportunity__c);

                if(eopp.Daily_Report__r.Status__c == '申請中' || eopp.Daily_Report__r.Status__c == '承認'){
                    if(NumMap.containsKey(eopp.Opportunity__c)){
                        NumMap.put(eopp.Opportunity__c,NumMap.get(eopp.Opportunity__c)+1);
                    }else{
                        NumMap.put(eopp.Opportunity__c,1);
                    }
                }
                System.debug('ou---test123NumMap：'+NumMap);

            }
    
            List<Opportunity2__c> opp2List = [select Id, Opportunity__c, MonthlyVisitsNum__c
                                          from Opportunity2__c 
                                          where Opportunity__c in :opp2IdList];
    
            if(opp2List.Size() > 0 ){
                for(Opportunity2__c opp2 : opp2List){
                    opp2.MonthlyVisitsNum__c = 0;
                    System.debug('ou---test123NumMap111：'+NumMap);
                    if(numMap.containsKey(opp2.Opportunity__c)){
                        opp2.MonthlyVisitsNum__c = numMap.get(opp2.Opportunity__c);
                    }
                    
                }
                update opp2List;
            }
        }
        
    }

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