/*
*Author：vivek
*Date：2020-04-07
*/
global class EventToEventDetailsBatch implements Database.Batchable<sObject>, Database.Stateful {
    public String query;

    Boolean IsNeedExecute = false; // 2021-03-09  mzy  WLIG-BYHD79  SFDC环境batch合并调查  是否符合执行条件

    // 检索所有有任务（包括主动任务，被动任务）没有报告一览的事件,下月的
    global EventToEventDetailsBatch(){
        // this.query = 'select id from Event where task_id__c != \'\' and EventC_ID__c = \'\' and ActivityDate >= '+Date.today().format().ReplaceAll('/', '-')+' and ActivityDate < '+ Date.today().toStartOfMonth().addMonths(2).format().ReplaceAll('/', '-');
        //20210626 zh 任务框架修改  月末生成本月的报告一览 延期、取消的事件不生成报告一览 start
        // this.query = 'select id from Event where task_id__c != \'\' and EventC_ID__c = \'\' and ActivityDate < '+ Date.today().toStartOfMonth().addMonths(2).format().ReplaceAll('/', '-');
        this.query = 'select id from Event where task_id__c != \'\' and EventC_ID__c = \'\' and EventStatus__c not in (\'04 取消\',\'05 延期\',\'06 关闭\',\'07 未执行\') and ActivityDate < '+ Date.today().format().ReplaceAll('/', '-');
        //20210626 zh 任务框架修改  月末生成本月的报告一览 end
        system.debug('query:'+query);
    }

    // 2021-03-09  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
    global EventToEventDetailsBatch(Boolean NeedExecute) {
        //20210626 zh 任务框架修改  月末生成本月的报告一览 延期、取消的事件不生成报告一览  start
        // this.query = 'select id from Event where task_id__c != \'\' and EventC_ID__c = \'\' and ActivityDate < '+ Date.today().toStartOfMonth().addMonths(2).format().ReplaceAll('/', '-');
        this.query = 'select id from Event where task_id__c != \'\' and EventC_ID__c = \'\' and EventStatus__c not in (\'04 取消\',\'05 延期\',\'06 关闭\',\'07 未执行\') and ActivityDate < '+ Date.today().format().ReplaceAll('/', '-');
        //20210626 zh 任务框架修改  月末生成本月的报告一览 end
        this.IsNeedExecute = NeedExecute;
    }
    // 2021-03-09  mzy  WLIG-BYHD79  SFDC环境batch合并调查  end


    // 传入where条件
    global EventToEventDetailsBatch(String whereStr) {
        this.query = 'select id from Event where '+whereStr;
        system.debug('query:'+query);
    }

    // 传进去一个id，对这个ID对应的事件进行生成新报告一览
    global EventToEventDetailsBatch(Id evtid){
        this.query = 'select id from Event where id = \'' +evtid +'\'';
        system.debug('query:'+query);
    }

    global Database.QueryLocator start(Database.BatchableContext bc) {
        system.debug('query:'+query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Sobject> scope) {
        Set<String> eventIdSet = new Set<String>();
        Set<Date> eventDateSet = new Set<Date>();
        Set<String> eventOwnIdSet = new Set<String>();
        List<String> nextEcIds = new List<String>();
        //20201106 zh CHAN-BUV2TF 生成报告一览时给事件和任务赋值 start
        List<String> taskIds = new List<String>();
        Map<String,task__c> taskMaps = new Map<String,task__c>();
        Map<String,Event> eventMaps = new Map<String,Event>();
        List<Event> updateEvents = new List<Event>();
        List<task__c> updateTasks = new List<task__c>();
        //20201106 zh CHAN-BUV2TF 生成报告一览时给事件和任务赋值 end

        for(Event eve : (List<Event>)scope){
            eventIdSet.add(eve.Id);
        }
        List<Event> calenderList = [select id, ActivityDate, OwnerId, Subject, whatid__c, EventC_ID__c, NextEventC_ID__c, AppCdId__c, SyncCreatedDate__c, Task_ID__c,EventStatus__c,cancelReason__c,cancelReasonOther__c,cancelReasonSelect__c,cancelReasonSelectFSE__c,delayReason__c,delayReasonOther__c,delayReasonSelect__c,delayReasonSelectFSE__c,delayToDate__c,
                                  StartDateTime, DurationInMinutes, Main_Visit_Location__c, Activity_Type2__c, IsScheduled__c, BeforeActivityDate__c,
                                  Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c, Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c,
                                  Purpose_Type__c, Location, Related_Opportunity1__c, Related_Service1__c, Related_Opportunity1_ID__c, Related_Service1_ID__c,
                                  Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,OPDPlan_Flag__c,
                                  Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                                  Activity_Purpose__c, Activity_PurposeFSE__c, Activity_PurposeEscFSE__c, Purpose_TypeFSE__c, Purpose_TypeEscFSE__c
                                  from Event where id = :eventIdSet];
        for(Event eve : calenderList){
            eventDateSet.add(eve.ActivityDate);
            eventOwnIdSet.add(eve.OwnerId);
            if (eve.NextEventC_ID__c != null) {
                nextEcIds.add(eve.NextEventC_ID__c);
            }
            //20201106 zh CHAN-BUV2TF 生成报告一览时给事件和任务赋值 start
            taskIds.add(eve.Task_ID__c);
            eventMaps.put(eve.Id, eve);
        }
        List<task__c> tasks = [SELECT Id,Event__c,Daily_Report__c FROM task__c WHERE Id = :taskIds];
        for(task__c task : tasks){
            taskMaps.put(task.Id, task);
        }
        //20201106 zh CHAN-BUV2TF 生成报告一览时给事件和任务赋值 end

        // List<User> usrList = [select id,Job_Category__c from user where id = :eventOwnIdSet];
        // Map<String,String> usrJobMap = new Map<String,String>();
        // for(User usr :usrList){
        //     usrJobMap.put(usr.Id, usr.Job_Category__c);
        // }

        Map<String,Daily_Report__c> dailyReporyMap = new Map<String,Daily_Report__c>();
        List<Daily_Report__c> reportlist = [select id, name,OwnerId, Reporter__c,Closest_Work_Day__c, Reported_Date__c, Daily_Report_Data_Type__c,
                                            Working_Time_From__c, Working_Time_To__c, Status__c, Mail_Send_Check__c,
                                            Business_Trip__c, Submit_Date_New__c, Submit_DateTime_New__c, Approved_Date__c,
                                            Approved_DateTime__c, CreatedById, Feed_Back_From_Manager__c, FeedbackManager__c,
                                            Planning_Time__c, Submission_Elapsed_Hour__c, Approval_Elapsed_Time__c,
                                            Activity_ID__c, Manager_Mail__c, Status_With_Check__c from Daily_Report__c where Reported_Date__c = :eventDateSet and OwnerId = :eventOwnIdSet ];
        for(Daily_Report__c rep :reportlist){
            dailyReporyMap.put(''+rep.Reported_Date__c+rep.OwnerId, rep);
        }
        
       /* Map<String, Event__c> nextEcMap = new Map<String, Event__c>();
        if (nextEcIds.size() > 0) {
            List<Event__c> nextEcList = [select Id, Event_ID__c, Daily_Report__c, Subject__c, StartDateTime__c, EndDateTime__c, Main_Visit_Location__c,
                Location__c, whatId__c, Activity_Type2__c, Activity_Type2_Before__c,
                Visitor1__c, Visitor2__c, Visitor3__c, Visitor4__c, Visitor5__c,
                Visitor1_ID__c, Visitor2_ID__c, Visitor3_ID__c, Visitor4_ID__c, Visitor5_ID__c, 
                Companion__c, Purpose__c, Purpose_Type__c, Purpose_Type2__c, Purpose_Type3__c, Purpose_Type4__c, Purpose_Type5__c,
                Purpose_TypeFSE__c, Purpose_TypeFSE2__c, Purpose_TypeFSE3__c, Purpose_TypeFSE4__c, Purpose_TypeFSE5__c,
                Purpose_TypeEscFSE__c, Purpose_TypeEscFSE2__c, Purpose_TypeEscFSE3__c, Purpose_TypeEscFSE4__c, Purpose_TypeEscFSE5__c,
                Related_Opportunity1__c, Related_Opportunity2__c, Related_Opportunity3__c, Related_Opportunity4__c, Related_Opportunity5__c,
                Related_Opportunity1_ID__c, Related_Opportunity2_ID__c, Related_Opportunity3_ID__c, Related_Opportunity4_ID__c, Related_Opportunity5_ID__c,
                Related_Service1__c, Related_Service2__c,
                Related_Service1_ID__c, Related_Service2_ID__c,
                Description__c, Hospital_Info__c, Doctor_Info__c, Technology_Treatment__c,
                New_Query__c, Update_Query__c, Lost_Info__c, VOC__c, Meeting_Info__c, Product_Description_Id__c,
                Maintenance_Contract_ID__c, Asset_Manual_ID__c, Rental_Apply_ID__c,
                OPD_ID__c, NTC_ID__c, ReportAccompanied_ID__c, CityStatus_ID__c, Conflict_ID__c, Claim_ID__c, Improvement_ID__c, OnCall_ID__c,
                nextPlanDate__c, nextPlanTimePurpose__c, Activity_ID__c,
                Minister__c, Minister_Comment__c, Manager__c, Manager_Comment__c,
                Free_Input__c, Visitor_Place_Free__c, Mail_Send_Btn__c,
                Lead_ID__c, Lead_Count__c, InsReport_ID__c,
                Activity_Purpose__c,Activity_PurposeFSE__c,Activity_PurposeEscFSE__c
                ,IsAlertInputDep__c 
        from Event__c where Id in :nextEcIds order by StartDateTime__c];
            for (Event__c ec : nextEcList) {
                nextEcMap.put(ec.Id, ec);
            }
        }
        */
        List<Event__c> ecNewList = new List<Event__c>();
        for(Event e : calenderList){
            if(dailyReporyMap.containsKey(''+e.ActivityDate+e.OwnerId)){
                Daily_Report__c report = new Daily_Report__c();
                report = dailyReporyMap.get(''+e.ActivityDate+e.OwnerId);
                Date d = report.Reported_Date__c;
                // 如果已存在报告一览跳过
                if (report.Status__c == '作成中' && String.isBlank(e.EventC_ID__c)) {
                    
                   
                    
                        String location = null;
                        String whatid = null;
                        String visitorPlaceFree = null;
                        Boolean freeInput = false;
                        if (!String.isBlank(e.Location) && String.isBlank(e.whatid__c)) {
                            freeInput = true;
                            visitorPlaceFree = e.Location;
                        } else {
                            location = e.Location;
                            whatid = e.whatid__c;
                        }
                        //20210527 zh 任务框架修改 start
                        String eventCStatus= '';
                        if ('05 延期'.equals(e.EventStatus__c)) {
                            eventCStatus = '延期';
                        }else if ('04 取消'.equals(e.EventStatus__c)) {
                            eventCStatus = '取消';
                        }
                        //20210527 zh 任务框架修改 end
                        Event__c ec = new Event__c(
                            Subject__c = e.Subject,
                            StartDateTime__c = e.StartDateTime,
                            DurationInMinutes__c = e.DurationInMinutes,
                            EndDateTime__c = e.StartDateTime.addMinutes(e.DurationInMinutes),
                            ActivityDate__c = d,
                            BeforeActivityDate__c = e.BeforeActivityDate__c,
                            ActivityDateTime__c = e.StartDateTime,
                            Main_Visit_Location__c = e.Main_Visit_Location__c,
                            Activity_Type2__c = e.Activity_Type2__c,
                            Purpose_Type__c = e.Purpose_Type__c,
                            Related_Opportunity1__c = e.Related_Opportunity1__c,
                            OPDPlan_Flag__c = e.OPDPlan_Flag__c,
                            Related_Opportunity1_ID__c = e.Related_Opportunity1_ID__c,
                            Related_Opportunity2__c = e.Related_Opportunity2__c,
                            Related_Opportunity2_ID__c = e.Related_Opportunity2_ID__c,
                            Related_Opportunity3__c = e.Related_Opportunity3__c,
                            Related_Opportunity3_ID__c = e.Related_Opportunity3_ID__c,
                            Related_Opportunity4__c = e.Related_Opportunity4__c,
                            Related_Opportunity4_ID__c = e.Related_Opportunity4_ID__c,
                            Related_Opportunity5__c = e.Related_Opportunity5__c,
                            Related_Opportunity5_ID__c = e.Related_Opportunity5_ID__c,
                            Related_Service1__c = e.Related_Service1__c,
                            Related_Service1_ID__c = e.Related_Service1_ID__c,
                            Visitor1__c = e.Visitor1__c,
                            Visitor2__c = e.Visitor2__c,
                            Visitor3__c = e.Visitor3__c,
                            Visitor4__c = e.Visitor4__c,
                            Visitor5__c = e.Visitor5__c,
                            Visitor1_ID__c = e.Visitor1_ID__c,
                            Visitor2_ID__c = e.Visitor2_ID__c,
                            Visitor3_ID__c = e.Visitor3_ID__c,
                            Visitor4_ID__c = e.Visitor4_ID__c,
                            Visitor5_ID__c = e.Visitor5_ID__c,
                            Visitor_Place_Free__c = visitorPlaceFree,
                            Location__c = location,
                            whatid__c = whatid,
                            Daily_Report__c = report.Id,
                            Event_ID__c = e.Id,
                            IsScheduled__c = e.IsScheduled__c,
                            AppCdId__c = e.AppCdId__c,
                            SyncCreatedDate__c = e.SyncCreatedDate__c,
                            Activity_Purpose__c = e.Activity_Purpose__c,
                            Activity_PurposeFSE__c = e.Activity_PurposeFSE__c,
                            Activity_PurposeEscFSE__c = e.Activity_PurposeEscFSE__c,
                            Purpose_TypeFSE__c = e.Purpose_TypeFSE__c,
                            Purpose_TypeEscFSE__c = e.Purpose_TypeEscFSE__c,
                            //20210527 zh 任务框架修改 start
                            eventStatus__c = eventCStatus,
                            delayReason__c = e.delayReason__c,
                            delayReasonOther__c = e.delayReasonOther__c,
                            delayReasonSelect__c = e.delayReasonSelect__c,
                            delayReasonSelectFSE__c = e.delayReasonSelectFSE__c,
                            CancelReason__c = e.cancelReason__c,
                            cancelReasonSelectFSE__c = e.cancelReasonSelectFSE__c,
                            cancelReasonSelect__c = e.cancelReasonSelect__c,
                            cancelReasonOther__c = e.cancelReasonOther__c,
                            delayToDate__c = e.delayToDate__c
                            //20210527 zh 任务框架修改 end
                        );
                        // if(usrJobMap.get(e.OwnerId) != null && usrJobMap.get(e.OwnerId) == '销售服务'){
                        //     ec.Activity_PurposeFSE__c = e.Activity_PurposeFSE__c;
                        //     ec.Purpose_TypeFSE__c = e.Purpose_TypeFSE__c;
                        //     ec.Purpose_Type__c = e.Purpose_TypeFSE__c;
                        // }else if(usrJobMap.get(e.OwnerId) != null && usrJobMap.get(e.OwnerId) != '销售服务'){
                        //     ec.Activity_PurposeEscFSE__c = e.Activity_PurposeEscFSE__c;
                        //     ec.Purpose_TypeEscFSE__c = e.Purpose_TypeEscFSE__c;
                        //     ec.Purpose_Type__c = e.Purpose_TypeFSE__c;
                        // }else{
                        //     // Activity_PurposeFSE__c = e.Activity_PurposeFSE__c,
                        //     // Activity_PurposeEscFSE__c = e.Activity_PurposeEscFSE__c,
                        //     // Purpose_TypeFSE__c = e.Purpose_TypeFSE__c,
                        //     // Purpose_TypeEscFSE__c = e.Purpose_TypeEscFSE__c
                        // }
                        if (e.IsScheduled__c) {
                            ec.IsScheduled_StartDateTime__c = ec.StartDateTime__c;
                            ec.IsScheduled_EndDateTime__c = ec.EndDateTime__c;
                            ec.IsScheduled_Location__c = e.Location;
                            ec.IsScheduled_Subject__c = ec.Subject__c;
                        }
                        if (e.whatid__c != null && e.whatid__c.startsWith('001')) {
                            // 訪問場所はAccountの場合
                            ec.Account_ID__c = e.whatid__c;
                            ec.Campaign_ID__c = null;
                        }
                        else if (e.whatid__c != null && e.whatid__c.startsWith('701')) {
                            // 訪問場所はCampaignの場合
                            ec.Account_ID__c = null;
                            ec.Campaign_ID__c = e.whatid__c;
                        }
                        else {
                            ec.Account_ID__c = null;
                            ec.Campaign_ID__c = null;
                        }
                        /*if (e.NextEventC_ID__c != null && nextEcMap.containsKey(e.NextEventC_ID__c)) {
                            Event__c nextEc = nextEcMap.get(e.NextEventC_ID__c);
                            ec.Visitor1__c = nextEc.Visitor1__c;
                            ec.Visitor2__c = nextEc.Visitor2__c;
                            ec.Visitor3__c = nextEc.Visitor3__c;
                            ec.Visitor4__c = nextEc.Visitor4__c;
                            ec.Visitor5__c = nextEc.Visitor5__c;
                            ec.Visitor1_ID__c = nextEc.Visitor1_ID__c;
                            ec.Visitor2_ID__c = nextEc.Visitor2_ID__c;
                            ec.Visitor3_ID__c = nextEc.Visitor3_ID__c;
                            ec.Visitor4_ID__c = nextEc.Visitor4_ID__c;
                            ec.Visitor5_ID__c = nextEc.Visitor5_ID__c;
                            ec.Purpose_Type2__c = nextEc.Purpose_Type2__c;
                            ec.Purpose_Type3__c = nextEc.Purpose_Type3__c;
                            ec.Purpose_Type4__c = nextEc.Purpose_Type4__c;
                            ec.Purpose_Type5__c = nextEc.Purpose_Type5__c;
                            ec.Related_Opportunity2__c = nextEc.Related_Opportunity2__c;
                            ec.Related_Opportunity3__c = nextEc.Related_Opportunity3__c;
                            ec.Related_Opportunity4__c = nextEc.Related_Opportunity4__c;
                            ec.Related_Opportunity5__c = nextEc.Related_Opportunity5__c;
                            ec.Related_Opportunity2_ID__c = nextEc.Related_Opportunity2_ID__c;
                            ec.Related_Opportunity3_ID__c = nextEc.Related_Opportunity3_ID__c;
                            ec.Related_Opportunity4_ID__c = nextEc.Related_Opportunity4_ID__c;
                            ec.Related_Opportunity5_ID__c = nextEc.Related_Opportunity5_ID__c;
                            ec.Related_Service2__c = nextEc.Related_Service2__c;
                            ec.Related_Service2_ID__c = nextEc.Related_Service2_ID__c;
                            ec.Purpose__c = ec.Subject__c;
                        }
                        */
                        ecNewList.add(ec);
                    
                }
            }
        }
        System.debug('ecNewList======++++++'+ecNewList.size());
        System.debug('ecNewList======++++++'+ecNewList);
        // 这里需要日后进一步修改，现在简单设为创建失败不报错，现在包括以下问题：
        // 1、事件和报告一览 的 选项列表字段值错误: 上门服务: [Purpose_TypeFSE__c] 不一致。无法创建
        database.insert(ecNewList, false);
        //20201106 zh CHAN-BUV2TF 生成报告一览时给事件和任务赋值 start
        for(Event__c eventc : ecNewList){
            if (eventMaps.containsKey(eventc.Event_ID__c)) {
                Event e = eventMaps.get(eventc.Event_ID__c);
                e.EventC_ID__c = eventc.Id;
                if (taskMaps.containsKey(e.Task_ID__c)) {
                    task__c ta = taskMaps.get(e.Task_ID__c);
                    ta.Event__c = eventc.Id;
                    ta.Daily_Report__c = eventc.Daily_Report__c;
                    updateTasks.add(ta);
                }
                
                updateEvents.add(e);
            }
            
            
        }
        database.update(updateEvents);
        database.update(updateTasks);
        //20201106 zh CHAN-BUV2TF 生成报告一览时给事件和任务赋值 end
    }

    global void finish(Database.BatchableContext BC) {

    }
}