global class NextMonthVisitTwoBatch implements Database.Batchable<sObject>, Database.Stateful {
    
    //HWAG-BML3AC 询价任务创建 精琢技术 wql 2020/04/10 start
    //soql语句
    private String query;
    //用于单条传入id更新询价
    // private String oppoId;
    //用于批量传入id更新询价
    // private List<String> oppoList;
    //用于未来可能出现当前月更新当前月的情况留的入口
    private Boolean thisMonthExecuteFlag;
    //用于执行batch同时记录日志信息
    private BatchIF_Log__c iflog;


    global NextMonthVisitTwoBatch() {
        // this.query = query;
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'NextMonthVisitTwoBatch start1\n';
        iflog.ErrorLog__c = '';
        insert iflog;

        thisMonthExecuteFlag = false;
    }
    // global NextMonthVisitTwoBatch(String oppoId) {
    //     this.oppoId = oppoId;
    //     iflog = new BatchIF_Log__c();
    //     iflog.Type__c = 'PushNotification';
    //     iflog.Is_Error__c = 0;
    //     iflog.Log__c = 'NextMonthVisitTwoBatch start2\n';
    //     iflog.ErrorLog__c = '';
    //     insert iflog;

    //     thisMonthExecuteFlag = false;
        
    // }

    // global NextMonthVisitTwoBatch(List<String> oppoList) {
    //     this.oppoList = oppoList;
    //     iflog = new BatchIF_Log__c();
    //     iflog.Type__c = 'PushNotification';
    //     iflog.Is_Error__c = 0;
    //     iflog.Log__c = 'NextMonthVisitTwoBatch start3\n';
    //     iflog.ErrorLog__c = '';
    //     insert iflog;

    //     thisMonthExecuteFlag = false;
        
    // }

    //给未来计划可能更新当前月留的入口
    global NextMonthVisitTwoBatch(boolean refresh) {
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'NextMonthVisitTwoBatch start4\n';
        iflog.ErrorLog__c = '';
        insert iflog;

        thisMonthExecuteFlag = refresh;
        
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {

        Date today  = date.today();
        //本月第一天
        Date thisMonthFirstDay = today.addMonths(0).toStartOfMonth();
        //本月最后一天
        Date thisMonthLastDay = today.addMonths(1).toStartOfMonth().addDays(-1);

        //下月的第一天
        Date nextMonthFirstDay = today.addMonths(1).toStartOfMonth();
        //下月的最后一天
        Date nextMonthLastDay = today.addMonths(2).toStartOfMonth().addDays(-1);

    
        String query =
                  'select Id,ActivityDate, EventC_ID__c, Related_Opportunity1_ID__c, ';
             query +=  ' Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c,';
             query +=  ' Related_Opportunity5_ID__c ';
             query +=  ' from event ';
             query +=  ' where ';
             if (thisMonthExecuteFlag){
                query +=  '  ActivityDate >= :thisMonthFirstDay ';
                query +=  ' AND ActivityDate <= :thisMonthLastDay ';
             } else {
                query +=  '  ActivityDate >= :nextMonthFirstDay';
                query +=  ' AND ActivityDate <= :nextMonthLastDay';
             }

        // if (!string.isblank(oppoId)) {
        //     query += ' or Related_Opportunity1_ID__c = :oppoId or Related_Opportunity2_ID__c =:oppoId';
        //     query +='  or Related_Opportunity3_ID__c = :oppoId or Related_Opportunity4_ID__c =:oppoId';
        //     query +='  or Related_Opportunity5_ID__c = :oppoId';
        // }

        // if (oppoList != null) {
        //     query += ' or Related_Opportunity1_ID__c = :oppoList or Related_Opportunity2_ID__c =:oppoList';
        //     query +='  or Related_Opportunity3_ID__c = :oppoList or Related_Opportunity4_ID__c =:oppoList';
        //     query +='  or Related_Opportunity5_ID__c = :oppoList';
        // }
            System.debug('sql语句：'+query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Event> evList) {
        try{
            

            //获取报告一览上的五个询价id 排除为空的情况
            List<String> idList =new List<String>();
            if(evList.size() > 0){
                for(Event e :evList){
                    if(e.Related_Opportunity1_ID__c != null){
                        idList.add(e.Related_Opportunity1_ID__c);
                    }
                    if(e.Related_Opportunity2_ID__c !=null){
                        idList.add(e.Related_Opportunity2_ID__c);
                    }
                    if(e.Related_Opportunity3_ID__c !=null){
                        idList.add(e.Related_Opportunity3_ID__c);
                    }
                    if(e.Related_Opportunity4_ID__c !=null){
                        idList.add(e.Related_Opportunity4_ID__c);
                    }
                    if(e.Related_Opportunity5_ID__c !=null){
                        idList.add(e.Related_Opportunity5_ID__c);
                    }
                }
            }
            //存放需要更新的询价集合
             List<Opportunity> opportunityList  = new List<Opportunity>();
            

            //去重 不然更新相同id会报错
             List<String> tempList =new List<String>();
             for(String i : idList){
                if(!tempList.contains(i)){
                    tempList.add(i);
                }
             }
             //根据id集合循环遍历，存放需要更新的询价id
            for(String t:tempList){

                Opportunity oppo = new Opportunity();
                oppo.Id = t;
                oppo.IsNextMonthOfVisit__c = true;
                opportunityList.add(oppo);
            }

            //更新询价并添加日志
            if (opportunityList.size() > 0) {

                Database.SaveResult[] lsr = Database.update(opportunityList, false);
                for (Integer tIdx = 0; tIdx < lsr.size(); tIdx++) {
                    Database.SaveResult sr = lsr[tIdx];
                    System.debug('sr.isSuccess:' + sr.isSuccess());
                    if (!sr.isSuccess()) {
                        Database.Error emsg = sr.getErrors()[0];
                        iflog.ErrorLog__c += 'ERROR ' + opportunityList[tIdx].Id + ' Opportunity:' + emsg + '\n';
                    }
                }
                // update opportunityList;
            }
        }catch(Exception e){
            iflog.ErrorLog__c += 'ERROR ： Opportunity:' + e.getMessage() + '\n';
       
        }
        
    }

    global void finish(Database.BatchableContext BC) {
        //更新该日志的数据信息
        iflog.Log__c += '\nNextMonthVisitTwoBatch end';
        String tmp = iflog.ErrorLog__c;
        if (tmp.length() > 65000) {
            tmp = tmp.substring(0, 65000);
            tmp += ' ...have more lines...';
            iflog.ErrorLog__c = tmp;
        }
        update iflog;
    }
    //HWAG-BML3AC 询价任务创建 精琢技术 wql 2020/04/10 end
}