public with sharing class LwcDailyReportController {
    @AuraEnabled
    public static DataWrap init(String recordId) {
        DataWrap dw = new DataWrap();
        Daily_Report__c report;
        User reportOwner;
        //报告书做成权限
        Boolean reportReportFlg = true;
        System.debug('recordId:' +recordId);
        String newLeadRecordType = [select Id from RecordType where  SobjectType = 'Lead' and DeveloperName = 'NewDaily_Report'].Id;
        dw.newLeadRecordType = newLeadRecordType;
        if(String.isBlank(recordId)){
            //新增
            report = new Daily_Report__c();
            report.Reporter__c = UserInfo.getUserId();
            // report.Reported_Date__c = date.today();
            List<Event__c> returnEvents = new List<Event__c>();
            for(Integer i=0;i<3;i++){
                Event__c e = new Event__c();
                returnEvents.add(e);
            }
            dw.returnEvents = returnEvents;
            dw.report = report;
            dw.currentUserId = UserInfo.getUserId();
            reportOwner = [ Select Id,Name,State_Hospital__c,Employee_No__c,Department,Job_Category__c,Category4__c,Category6__c,ManagerId,
            Manager.Email,BuchangApprovalManager__c,BuchangApprovalManagerSales__c,ProfileId,Profile.Name,Batch_User__c  From User Where Id = :report.Reporter__c];
            dw.reportOwner = reportOwner;
            dw.profileName = reportOwner.Profile.Name;
            dw.batchUser = reportOwner.Batch_User__c;
            System.debug('profileName1>>>' + dw.profileName);
            System.debug('batchUser1>>>' + dw.batchUser);
        }else{
            System.debug('日报编辑-----' );
            //编辑
            report = [select id, name, Reporter__c, Reported_Date__c, Daily_Report_Data_Type__c,ActivityDate__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,
                                            Report_Deadline__c,Approved_DateTime__c, CreatedById,CreatedBy.Name,Feed_Back_From_Manager__c,
                                            FeedbackManager__c,FeedbackManager__r.Name,Planning_Time__c, Submission_Elapsed_Hour__c, Approval_Elapsed_Time__c,
                                            Activity_ID__c, Manager_Mail__c, Status_With_Check__c //, OCM_man_province__c
                                            , ownerid // 任务和日报管理 2020-05-21 update by vivek 
                                            from Daily_Report__c where Id = :recordId];
            // 報告者情報を取得
            reportOwner = [ Select Id,Name,State_Hospital__c,Employee_No__c,Department,Job_Category__c,Category4__c,Category6__c,ManagerId,
            Manager.Email,BuchangApprovalManager__c,BuchangApprovalManagerSales__c,ProfileId,Profile.Name,Batch_User__c From User Where Id = :report.Reporter__c];

            if (report.Status__c == '作成中' || report.Status__c == '非承認' || UserInfo.getUserId() == reportOwner.Id) {
                dw.reportStatusFlg = true;
            } else {
                dw.reportStatusFlg = false;
            }
            //日报下的报告一览
            List<Event__c> returnEvents = [select id,Subject__c,StartDateTime__c,DurationInMinutes__c,EndDateTime__c,
            ActivityDate__c,BeforeActivityDate__c,ActivityDateTime__c,Main_Visit_Location__c,UseReport__c,
            Activity_Type2__c,Purpose_Type__c,Related_Opportunity1__c,OPDPlan_Flag__c,Opd_Plan__c,Find_Imitations_Flag__c,
            Related_Opportunity1_ID__c,Related_Opportunity2__c,Related_Opportunity2_ID__c,Account_ID__c,
            Related_Opportunity3__c,Related_Opportunity3_ID__c,InsReport_ID__c,
            // Related_Opportunity4__c,InsReport_ID__c,
            SLAReportInfo__c,
            // Related_Opportunity4_ID__c,Related_Opportunity5__c,Related_Opportunity5_ID__c,
            Related_Service1__c,Related_Service1_ID__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,
            Visitor_Place_Free__c,Location__c,whatid__c,Daily_Report__c,Event_ID__c,
            IsScheduled__c,AppCdId__c,SyncCreatedDate__c,Activity_Purpose__c,Activity_PurposeFSE__c,
            Activity_PurposeEscFSE__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,eventStatus__c,Description__c,
            delayReason__c,delayReasonOther__c,delayReasonSelect__c,delayReasonSelectFSE__c,OPD_ID__c,
            CancelReason__c,cancelReasonSelectFSE__c,cancelReasonSelect__c,cancelReasonOther__c,
            Infrastructure_Project1__c,Infrastructure_Project2__c,
            delayToDate__c,Purpose__c from Event__c where Daily_Report__c =: recordId order by createdDate];
            //从event标准事件中取出生成报告一览
            System.debug('returnEvents.size:' +returnEvents.size());
            List<Event__c> eList = getEvent(report,reportOwner);
            returnEvents.addAll(eList);
            System.debug('eList.size:' +eList.size());
            System.debug('returnEvents.size:' +returnEvents.size());
            Set<String> evIds = new Set<String>();
            Set<String> reportEventIds = new Set<String>();
            for(Event__c eve : returnEvents){
                if(String.isNotBlank(eve.Event_ID__c)){
                    evIds.add(eve.Event_ID__c);
                }
                reportEventIds.add(eve.Id);
            }
            List<Event> eventList = new List<Event>();
            // Report_Contract__c Report_Contract_Type__c 只能从报告一览Event__c对象上读取---改为从SLA报告书里读取
            // List<Event__c> eventReportList = [Select Id ,Event_ID__c,Report_Contract__c,Report_Contract_Type__c From Event__c Where Event_ID__c In :evIds];
          
            List<SLAReportInfo__c> sLAReportInfoList = [Select Id ,Distribution_Person__c,Distribution_Method__c,Event__c From SLAReportInfo__c Where Event__c In :reportEventIds];
            if(sLAReportInfoList.size()>0 && returnEvents.size()>0) {
                for(Event__c eve : returnEvents) {
                    for(SLAReportInfo__c eve2 : sLAReportInfoList) {
                        if(eve.ID == eve2.Event__c) {
                            eve.Report_Contract__c = eve2.Distribution_Person__c;
                            eve.Report_Contract_Type__c = eve2.Distribution_Method__c;
                        }
                    }
                }
            }
            List<Event__c> eventInfoList = [Select Id ,InsReport_ID__c,Infrastructure_Project1__c,Infrastructure_Project2__c ,
            Purpose_TypeFSE2__c,Purpose_TypeFSE3__c ,Purpose_TypeEscFSE2__c,Purpose_TypeEscFSE3__c 
            ,FaultPreventionTraining_FLAG__c
            ,NewInstallTarin_FLAG__c
            ,OPD_FLAG__c
            ,SIS_ET_FLAG__c
            ,SIS_FLAG__c
            ,SIS_ENG_FLAG__c
            ,delayToDate__c // zzm 20231115 事件过来的活动延期时，延期日期清空bug
            From Event__c Where Id In :reportEventIds];
            if(eventInfoList.size()>0 && returnEvents.size()>0) {
                for(Event__c eve : returnEvents) {
                    for(Event__c eve2 : eventInfoList) {
                        if(eve.ID == eve2.ID) {
                            eve.Infrastructure_Project1__c = eve2.Infrastructure_Project1__c;
                            eve.Infrastructure_Project2__c = eve2.Infrastructure_Project2__c;
                            eve.InsReport_ID__c = eve2.InsReport_ID__c;
                            eve.Purpose_TypeFSE2__c = eve2.Purpose_TypeFSE2__c;
                            eve.Purpose_TypeFSE3__c = eve2.Purpose_TypeFSE3__c;
                            eve.Purpose_TypeEscFSE2__c = eve2.Purpose_TypeEscFSE2__c;
                            eve.NewInstallTarin_FLAG__c = eve2.NewInstallTarin_FLAG__c;
                            eve.FaultPreventionTraining_FLAG__c = eve2.FaultPreventionTraining_FLAG__c;
                            eve.OPD_FLAG__c = eve2.OPD_FLAG__c;
                            eve.SIS_ET_FLAG__c = eve2.SIS_ET_FLAG__c;
                            eve.SIS_FLAG__c = eve2.SIS_FLAG__c;
                            eve.SIS_ENG_FLAG__c = eve2.SIS_ENG_FLAG__c;
                            // zzm 20231115 事件过来的活动延期时，延期日期清空bug start 
                            if(eve2.delayToDate__c !=null) {
                                eve.delayToDate__c = eve2.delayToDate__c;
                            }
                            // zzm 20231115 事件过来的活动延期时，延期日期清空bug end
                            // eve.IsAlertInputDep__c = true; //测试用
                        }
                    }
                }
            }
            returnEvents = CheckAlertInputDep(returnEvents);
            // Infrastructure_Project1__c = e.Infrastructure_Project1__c,
            // Infrastructure_Project2__c = e.Infrastructure_Project2__c,
            if(evIds.size()>0){
                eventList = [select id,cancelReasonSelectFSE__c,cancelReasonSelect__c,delayReasonSelectFSE__c,
                delayReasonSelect__c,Task_ID__c from Event where id in: evIds];
            }
            if(eventList.size()>0){
                Set<String> taskIds = new Set<String>();
                Map<String,String> idsMap = new Map<String,String>();
                for(Event eve : eventList){
                    if(String.isNotBlank(eve.Task_ID__c)){
                        taskIds.add(eve.Task_ID__c);
                        idsMap.put(eve.Task_ID__c,eve.id);
                    }
                }
                if(taskIds.size()>0){
                    List<task__c> taskList = [select id,cancelReasonSelectFSE__c,cancelReasonSelect__c,delayReasonSelectFSE__c,taskStatus__c,
                    delayReasonSelect__c,taskDifferent__c,delayTaskDelay__c,delayDate__c,Finish_Date__c from task__c where id in: taskIds];
                    for(task__c task : taskList){
                        for(Event__c eve : returnEvents){
                            if(eve.Event_ID__c==idsMap.get(task.id)){
                                //说明这个报告一览(event__c)的标准事件(event)下面绑定了自定义的任务（task__c）
                                // zzm 20231115 事件过来的活动延期时，延期日期清空bug start 
                                if(task.delayDate__c !=null ) {
                                    eve.delayToDate__c = task.delayDate__c;//延期时间
                                }
                                // zzm 20231115 事件过来的活动延期时，延期日期清空bug end 

                                
                                eve.cancelReasonSelectFSE__c = task.cancelReasonSelectFSE__c;//取消理由(选项)FSE
                                eve.cancelReasonSelect__c = task.cancelReasonSelect__c;//取消理由(选项)
                                eve.delayReasonSelectFSE__c = task.delayReasonSelectFSE__c;//延期理由(选项)   FSE
                                eve.delayReasonSelect__c = task.delayReasonSelect__c;//延期理由(选项)
                                //下面五个是我在报告一览上新建的五个字段
                                eve.taskId__c = task.id;
                                eve.taskDifferent__c = task.taskDifferent__c;
                                eve.delayTaskDelay__c = task.delayTaskDelay__c;
                                eve.Finish_Date__c = task.Finish_Date__c;
                                eve.backEventStatus__c = task.taskStatus__c;
                            }
                        }
                    }
                }
            }
            Integer num = returnEvents.size();
            if(num<3){
                //不足三条就要用空的补到
                for(Integer i=0;i<3-num;i++){
                    Event__c e = new Event__c();
                    returnEvents.add(e);
                }
            }
            dw.returnEvents = returnEvents;
        }
        // カスタム設定から報告書作成に設定されているプロファイルを取得
        List<report_report__c> rrList = report_report__c.getall().values();
        for(report_report__c rr : rrList){
            // 報告書作成権限を設定
            if(reportOwner.ProfileId == rr.Profile_ID_1__c  ){
                reportReportFlg = false;
            }
        }
        dw.report = report;
        dw.reportReportFlg = reportReportFlg;
        dw.currentUserId = UserInfo.getUserId();
        if(report.Working_Time_From__c!=null){
            dw.beforeHour = report.Working_Time_From__c.hour();
            dw.beforeMinute = report.Working_Time_From__c.minute();
        }
        if(report.Working_Time_To__c!=null){
            dw.afterHour = report.Working_Time_To__c.hour();
            dw.afterMinute = report.Working_Time_To__c.minute();
        }
        dw.reportOwner = reportOwner;
        String Job_Category = [Select toLabel(Job_Category__c) from User Where Id = :report.Reporter__c].Job_Category__c;
        dw.Job_Category = Job_Category;
        dw.profileName = reportOwner.Profile.Name;
        dw.batchUser = reportOwner.Batch_User__c;
        System.debug('profileName>>>' + dw.profileName);
        System.debug('batchUser>>>' + dw.batchUser);
        return dw;
    }
    // 2018/11/21 SWAG-B6Q8BS 判断是否需要弹窗更新客户信息 start
    public static List<Event__c> CheckAlertInputDep(List<Event__c> activities) {
        String Alertlines = '';
        Boolean IsAlertInputDep = false;
        
        list<ID> DepIDList = new list<ID>();
        for (Integer i = 0; i < activities.size(); i++) {
            Event__c a = activities.get(i);
            a.IsAlertInputDep__c = false;   
            if (a.whatid__c != null && a.whatid__c.startsWith('001')) {
                DepIDList.add(a.whatid__c);
            }
        }
        if(DepIDList.size() == 0){
            return activities;
        }
        Date dateToday = Date.today();
        Integer year = dateToday.year();
        Integer month = dateToday.month();

        if (month < 4) {
            year -= 1;
        }

        Date dateFinalStartDate = Date.newInstance(year, 4, 1);
        system.debug('===DepIDList=='+DepIDList+'==dateFinalStartDate==='+dateFinalStartDate);
        string yearP = year - 1868 + 'P';
        Map<ID,Account> DepartMap = 
            New Map<ID,Account> ([select id, ParentId 
                                    from Account 
                                    where id in: DepIDList 
                                    and Parent.CreateDate__c <: dateFinalStartDate
                                    and Hospital__r.OCM_Category__c like '%H%'
                                    and Parent.RecordType.DeveloperName in 
                                    ('Department_Class_GI','Department_Class_BF',
                                    'Department_Class_GS','Department_Class_URO',
                                    'Department_Class_GYN')]); 
        
        Map<Id, AggregateResult> ANCLMap = new Map<Id, AggregateResult> ();
        system.debug('===DepartMap=='+DepartMap);
        if(DepartMap != null && DepartMap.size() > 0 ){
            List<ID> DCIDList = new List<ID>();
            for(Account temDep: DepartMap.values()){
                DCIDList.add(temDep.ParentId);
            }

            ANCLMap = new Map<Id, AggregateResult>(
                [select Account__c Id, Max(Name) Name1
                from Account_Number_of_case__c
                where Account__c in: DCIDList
                    and OCM_Period__c =: yearP
                    and (BF_KPI_input__c  ='登录完毕'
                    or GI_KPI_input__c  ='登录完毕'
                    or GS_KPI_input__c  ='登录完毕' 
                    or GYN_KPI_input__c ='登录完毕'
                    or URO_KPI_input__c ='登录完毕')
                    group by Account__c
            ]);
        system.debug('===activities=='+activities+'==DepartMap=='+DepartMap+'====='+ANCLMap);
            for (Integer i = 0; i < activities.size(); i++) {
                Event__c a = activities[i];
                if (a.whatid__c != null && a.whatid__c.startsWith('001')) {
                   system.debug('进来了'+a.whatid__c);
                    if(DepartMap.get(a.whatid__c)!=null && 
                        ANCLMap.get(DepartMap.get(a.whatid__c).ParentId) ==null){
                        IsAlertInputDep = true;
                        a.IsAlertInputDep__c = true;
                        if(Alertlines.equals('')){
                            Alertlines = ''+ i;
                        }else{
                            Alertlines+= '||' + i;
                        }

                    }
                }
            }
        }
        return activities;
    }
    // 2018/11/21 SWAG-B6Q8BS 判断是否需要弹窗更新客户信息 end
    public static List<Event__c> getEvent(Daily_Report__c report,User reportOwner){
        List<Event__c> ecNewList = new List<Event__c>();
        String status = report.Status__c;
        Date d = report.Reported_Date__c;
        System.debug('getEvent:' +d);
        if (status == '作成中') {
            List<Event> calenderList = ControllerUtil.eventSelectByDate(d, reportOwner);
            List<String> delEventId = new List<String>();
            List<String> nextEcIds = new List<String>();
            for (Event e : calenderList) {
                if (e.NextEventC_ID__c != null) nextEcIds.add(e.NextEventC_ID__c);
                if (e.EventC_ID__c != null){
                    delEventId.add(e.EventC_ID__c);
                }
            }
            List<Event__c> delEventCList = [select id from Event__c where id = :delEventId and eventStatus__c = '取消'];
            for(Integer i = 0 ; i < calenderList.size() ; i++){
                if(calenderList[i].EventC_ID__c != null){
                    for(Event__c ec :delEventCList) {
                        if(calenderList[i].EventC_ID__c == ec.Id){
                            calenderList.remove(i);
                            i--;
                            break;
                        }
                    }
                }
            }
            Map<String, Event__c> nextEcMap = new Map<String, Event__c>();
            if (nextEcIds.size() > 0) {
                List<Event__c> nextEcList = ControllerUtil.getNextEventCList(nextEcIds);
                for (Event__c ec : nextEcList) {
                    nextEcMap.put(ec.Id, ec);
                }
            }
            
            for (Event e : calenderList) {
                if (!String.isBlank(e.EventC_ID__c)) {
                    // 
                } else {
                    String location = null;
                    String whatid = null;
                    String visitorPlaceFree = null;
                    if (!String.isBlank(e.Location) && String.isBlank(e.whatid__c)) {
                        visitorPlaceFree = e.Location;
                    } else {
                        location = e.Location;
                        whatid = e.whatid__c;
                    }
                    String eventCStatus= '';
                    if ('05 延期'.equals(e.EventStatus__c)) {
                        eventCStatus = '延期';
                    }else if ('04 取消'.equals(e.EventStatus__c)) {
                        eventCStatus = '取消';
                    }
                    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,
                        ActivityDate__c = e.ActivityDate,
                        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,
                        Opd_Plan__c = e.Opd_Plan__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,
                        //event的Related_Opportunity4_ID__c 对应 event_c的Infrastructure_Project1__c的值
                        Infrastructure_Project1__c = e.Related_Opportunity4_ID__c, 
                        // Related_Opportunity5__c = e.Related_Opportunity5__c,
                        Infrastructure_Project2__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,
                        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,
                        Purpose__c = e.Subject

                        // ,
                        // Report_Contract__c = e.Report_Contract__c,
                        // Report_Contract_Type__c = e.Report_Contract_Type__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')) {
                        ec.Account_ID__c = e.whatid__c;
                        ec.Campaign_ID__c = null;
                    }else if (e.whatid__c != null && e.whatid__c.startsWith('701')) {
                        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);
                }
            }
        }
        return ecNewList;
    }
    /** 日報取得 url redirect */
    @AuraEnabled
    public static Result getDailyReport(Date reportDate,String reporter){
        Result re = new Result();
        Daily_Report__c report;
        List<Daily_Report__c> reportList = new List<Daily_Report__c>();
        if(reportDate != null && String.isNotBlank(reporter)){
            // 報告者、日付から日報を取得
            reportList = [select id, name, 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,FeedbackManager__r.Name,
                        Planning_Time__c, Submission_Elapsed_Hour__c, Approval_Elapsed_Time__c,Report_Deadline__c,
                        Activity_ID__c, Manager_Mail__c, Status_With_Check__c //, OCM_man_province__c
                        from Daily_Report__c where Reported_Date__c =: reportDate and OwnerId =: reporter];
            // 日報がない場合
            if(reportList.size() <= 0){
                // savepoint
                // insert成功しても権限により取得できない場合、insertそのものをrollbackする
                Savepoint sp = Database.setSavepoint();
                report = new Daily_Report__c();
                report.Reporter__c = reporter;
                report.Status__c = '作成中';
                report.Daily_Report_Data_Type__c = '通常';
                report.Reported_Date__c = reportDate;
                report.Working_Time_From__c = Datetime.newInstance(reportDate.year(), reportDate.month(), reportDate.day(), 8, 45, 0);
                report.Working_Time_To__c = Datetime.newInstance(reportDate.year(), reportDate.month(), reportDate.day(), 17, 30, 0);
                report.OwnerId = reporter;
                try {
                    insert report;
                    reportList = reportSelectById(report.id);
                    if(reportList.size() == 0){
                        // 参照権限がありません。
                        re.code = 500;
                        re.msg = System.Label.Error_Message10;
                        Database.rollback(sp);
                        return re;
                    }
                    report = reportList.get(0);
                } catch (Exception ex) {
                    re.code = 500;
                    re.msg = System.Label.Error_Message10;
                }
            }else{
                report = reportList.get(0);
            }
            re.code = 200;
            re.msg = report.id;
        } else {
            re.code = 500;
            if(reportDate != null){
                re.msg = '请设定日期';
            } else {
                re.msg = '请设定报告人';
            }
        }
        return re;
    }
    @AuraEnabled
    public static Result saveContact(String contactJson) {
        system.debug('saveContact');
        system.debug(contactJson);
        Result r = new Result();
        try{
            RecordType rd = [select id,DeveloperName, SobjectType from RecordType where SobjectType='Contact' and DeveloperName='Doctor'];
            Contact con = (Contact) JSON.deserialize(contactJson, Contact.class);
            //默认是医生的记录类型
            con.recordTypeId = rd.id;
            system.debug(con);
            insert con;
            r.code = 200;
            r.msg = con.id;
        }catch(Exception e){
            r.code = 500;
            // r.msg = e.getMessage()+',错误行数：'+e.getLineNumber();
            r.msg = e.getDmlMessage(0);
        }finally{
            return r;
        }
        return r;
    }
    @AuraEnabled
    public static Result saveActivity(String jsonStr,Integer beforeHour,Integer beforeMinute,Integer afterHour,
    Integer afterMinute,String visit,String visitAim,
    String purposeType1,String purposeType2,String purposeType3,
    // String purposeType4,String purposeType5,
    String contactId1,String contactId2,String contactId3,
    // String contactId4,String contactId5,
    String accountId,String reportJsonStr,Integer shour,Integer sminute,Integer ehour,Integer eminute
    ,String relatedOpportunity1,String relatedOpportunity2,String relatedOpportunity3,String relatedService1
    ,String infrastructureProject1,String infrastructureProject2
    ) {

        System.debug('saveActivity beforeMinute:' + beforeMinute );
        Savepoint sp = Database.setSavepoint();
        system.debug('saveActivity');
        system.debug('relatedService1' +relatedService1); //涉及的维修合同
        Daily_Report__c report = (Daily_Report__c)JSON.deserialize(reportJsonStr, Daily_Report__c.class);
        User reportOwner = [ Select Id,Job_Category__c,Category4__c,Manager.Email From User Where Id = :report.Reporter__c];
        Date reportedDate = report.Reported_Date__c;
        String reportedId = report.Id;
        report.Working_Time_From__c = Datetime.newInstance(reportedDate.year(), reportedDate.month(), reportedDate.day(), shour, sminute, 0);
        report.Working_Time_To__c = Datetime.newInstance(reportedDate.year(), reportedDate.month(), reportedDate.day(), ehour, eminute, 0);
        report.Manager_Mail__c = reportOwner.Manager.Email;
        Datetime datetimeNow = datetime.now();
        if(report.Planning_Time__c == null){
            report.Planning_Time__c = datetimeNow.addHours(8);
        }

        //  //非服务的可以不用填写分钟数
        // if(reportOwner.Job_Category__c!='销售服务'){ 
        //     if(beforeMinute ==null ) {
        //         beforeMinute = 0;
        //     } 
        //     if(afterMinute ==null) {
        //         afterMinute = 0;
        //     } 
        // }
        if(beforeHour>afterHour || (beforeHour==afterHour&&beforeMinute> afterMinute)) {
            beforeHour = 1;
            afterHour = 2;
            beforeMinute = 0;
            afterMinute = 0;
        }

        // 承認日を設定
        if(report.Status__c == '承認'){
            if(report.Approved_Date__c == null){
                report.Approved_Date__c = date.today();
                report.Approved_DateTime__c = datetimeNow;
                // 申請から承認までの時間を設定
                Date startD = report.Submit_Date_New__c;
                Date endD = Date.today();
                if(startD >= endD){
                    report.Approval_Elapsed_Time__c = 0;
                }
                else{
                    Datetime endDT = datetimeNow;
                    Integer betweenDay = startD.daysBetween(endD) - 1;
                    report.Approval_Elapsed_Time__c = betweenDay * 24 + endDT.hour();
                }
            }
        }
        if(report.Status__c == '承認' || report.Status__c == '非承認'){
            report.FeedbackManager__c = reportOwner.ManagerId;
        }
        //zzm 20231021 报告一览保存的时候，不保存日报相关的内容了
        // upsert report;
        Result r = new Result();
        SLAReportInfo__c slaInfo = new SLAReportInfo__c();
        System.debug('event_c jsonStr' +jsonStr);
            
        try{
            Event__c ev = (Event__c)JSON.deserialize(jsonStr, Event__c.class);
            System.debug('event__c Purpose__c：' + ev.Purpose__c);
            ev.StartDateTime__c = Datetime.newInstance(reportedDate.year(), reportedDate.month(), reportedDate.day(), beforeHour, beforeMinute, 0);
            ev.EndDateTime__c = Datetime.newInstance(reportedDate.year(), reportedDate.month(), reportedDate.day(), afterHour, afterMinute, 0);
            ev.ActivityDateTime__c = ev.StartDateTime__c;
            String planPurposeText = ev.nextPlanTimePurpose__c;
            ev.nextPlanTimePurpose__c = beforeHour + ',' + beforeMinute + ',' + afterHour + ',' + afterMinute+ ',' + planPurposeText;
            ev.Daily_Report__c = reportedId;
            ev.Activity_Type2__c = visit;
            String taskId = ev.taskId__c;
            ev.taskDifferent__c = null;
            ev.delayTaskDelay__c = false;
            ev.Finish_Date__c = null;
            ev.taskId__c = null;
            ev.backEventStatus__c = null; 
            if(ev.eventStatus__c != '延期') {
                ev.delayToDate__c = null;
            }
            if(reportOwner.Job_Category__c=='销售服务'){
                ev.Activity_PurposeFSE__c = visitAim;
                ev.Purpose_TypeFSE__c = purposeType1;
                ev.Purpose_TypeFSE2__c = purposeType2;
                ev.Purpose_TypeFSE3__c = purposeType3;
                // ev.Purpose_TypeFSE4__c = purposeType4;
                // ev.Purpose_TypeFSE5__c = purposeType5;
            }else{
                ev.Activity_PurposeEscFSE__c = visitAim;
                ev.Purpose_TypeEscFSE__c = purposeType1;
                ev.Purpose_TypeEscFSE2__c = purposeType2;
                ev.Purpose_TypeEscFSE3__c = purposeType3;
                // ev.Purpose_TypeEscFSE4__c = purposeType4;
                // ev.Purpose_TypeEscFSE5__c = purposeType5;
            }
           
           


            if(String.isNotBlank(contactId1)){
                ev.Visitor1_ID__c = contactId1;
                slaInfo.Visitor1__c = contactId1;
            }else{
                ev.Visitor1_ID__c = null;
                slaInfo.Visitor1__c = null;
            }
            if(String.isNotBlank(contactId2)){
                ev.Visitor2_ID__c = contactId2;
                slaInfo.Visitor2__c = contactId2;
            }else{
                ev.Visitor2_ID__c = null;
                slaInfo.Visitor2__c = null;
            }
            if(String.isNotBlank(contactId3)){
                ev.Visitor3_ID__c = contactId3;
                slaInfo.Visitor3__c = contactId3;
            }else{
                ev.Visitor3_ID__c = null;
                slaInfo.Visitor3__c = null;
            }
            // if(String.isNotBlank(contactId4)){
            //     ev.Visitor4_ID__c = contactId4;
            //     slaInfo.Visitor4__c = contactId4;
            // }else{
            //     ev.Visitor4_ID__c = null;
            //     slaInfo.Visitor4__c = null;
            // }
            // if(String.isNotBlank(contactId5)){
            //     ev.Visitor5_ID__c = contactId5;
            //     slaInfo.Visitor5__c = contactId5;
            // }else{
            //     ev.Visitor5_ID__c = null;
            //     slaInfo.Visitor5__c = null;
            // }
   
            //zzm 230906 start
            if(String.isNotBlank(relatedOpportunity1)){
                ev.Related_Opportunity1_ID__c = relatedOpportunity1;
            }else{
                ev.Related_Opportunity1_ID__c = null;
            }
            if(String.isNotBlank(relatedOpportunity2)){
                ev.Related_Opportunity2_ID__c = relatedOpportunity2;
            }else{
                ev.Related_Opportunity2_ID__c = null;
            }
            if(String.isNotBlank(relatedOpportunity3)){
                ev.Related_Opportunity3_ID__c = relatedOpportunity3;
            }else{
                ev.Related_Opportunity3_ID__c = null;
            }
            if(String.isNotBlank(relatedService1)){
                ev.Related_Service1_ID__c = relatedService1;
            }else{
                ev.Related_Service1_ID__c = null;
            }
            if(String.isNotBlank(infrastructureProject1)){
                ev.Infrastructure_Project1__c = infrastructureProject1;
            }else{
                ev.Infrastructure_Project1__c = null;
            }
            if(String.isNotBlank(infrastructureProject2)){
                ev.Infrastructure_Project2__c = infrastructureProject2;
            }else{
                ev.Infrastructure_Project2__c = null;
            }
            if(String.isNotBlank(accountId)) {
                ev.whatid__c = accountId;
            }
            if(String.isNotBlank(accountId) && visit == '社外イベント') {
                ev.Campaign_ID__c = accountId;
                String locationName = [select Name from Campaign where Id = :accountId].Name;
                ev.Location__c = locationName;
            }
            // if(String.isNotBlank(accountId)){
            if(String.isNotBlank(accountId) && visit != '社外イベント'){
            
                ev.Account_ID__c = accountId;
                // String locationName = [select Name from Account where Id = :accountId].Name;
                Account acctmp = ControllerUtil.getAccountForId(accountId);
                if(acctmp !=null) {
                    ev.Location__c =acctmp.Name;
                    ev.HospitalMainResponsibility__c = acctmp.Parent.OwnerId;
                    ev.MainResponsibilityDirector__c = acctmp.Parent.Owner.ZongjianId__c;
                    ev.MainResponsibilityMinister__c = acctmp.Parent.Owner.BuzhangxiaoshouId__c;
                    ev.MainResponsibilityManager__c = acctmp.Parent.Owner.JinglixiaoshouId__c;
                }
                
                // String locationName = ControllerUtil.getAccountNameForId(accountId);
                // if(String.isNotBlank(locationName)) {
                //     ev.Location__c = locationName;
                // }
                
            //zzm 230906 end
            }else{
                ev.Account_ID__c = null;
            }
            if(String.isBlank(ev.whatid__c)){
                ev.Location__c = null;
            }
            Set<Id> actDelListForDelIns = new Set<Id>();
            if(String.isNotBlank(ev.Id)){
                // update ev;
                addOtherFields(ev,report.Status__c,reportOwner.Job_Category__c,reportedDate);
                ev = ControllerUtil.updateEvent(ev);
                actDelListForDelIns.add(ev.Id);
                r.msg = 'update';
            }else{
            //填充其他数据
                addOtherFields(ev,report.Status__c,reportOwner.Job_Category__c,reportedDate);
                // insert ev;
                ev = ControllerUtil.updateEvent(ev);
                r.msg = ev.Id;
            }
            //把SLA报告书的业务逻辑加进来
            
            // if(reportOwner.Job_Category__c=='销售服务' && String.isNotBlank(relatedService1)
            if(String.isNotBlank(relatedService1)
                && String.isNotBlank(ev.Report_Contract__c) && String.isNotBlank(ev.Report_Contract_Type__c)) {
                List<SLAReportInfo__c>  slaInfos = [SELECT Id FROM SLAReportInfo__c WHERE Event__c = :ev.Id ];
               if(String.isNotBlank(accountId)) {
                    slaInfo.Account_ID__c = accountId;
                }
                slaInfo.Maintenance_Contract__c = relatedService1;
                slaInfo.Distribution_Person__c = ev.Report_Contract__c;
                slaInfo.Distribution_Method__c = ev.Report_Contract_Type__c;
                slaInfo.Event__c = ev.Id;
                //存在就更新
                if(slaInfos.size()>0) {
                    slaInfo.Id = slaInfos[0].Id;
                } else {
                    List<NewMaintenanceReport_Task__c> reportTasks = [SELECT Id,ActualDistributionTimes_Quarter__c,NewMaintenance_Contract__c,Distribution_Start_Date__c,Distribution_End_Date__c,Distribution_Person__c,NewMaintenance_Contract__r.Contract_Consumption_rate__c FROM NewMaintenanceReport_Task__c WHERE NewMaintenance_Contract__c =:relatedService1];
                    Date today = Date.today();
                    for (NewMaintenanceReport_Task__c reportTask : reportTasks) {
                        if (today >= reportTask.Distribution_Start_Date__c && today <= reportTask.Distribution_End_Date__c) {
                            slaInfo.SLATask__c = reportTask.Id;
                            slaInfo.Distribution_Consumption_Rate__c = reportTask.NewMaintenance_Contract__r.Contract_Consumption_rate__c;
                        }
                    }
                }
                // List<SLAReportInfo__c>  updateSlaInfos = new List<SLAReportInfo__c>();
                // updateSlaInfos.add(slaInfo);
                slaInfo = ControllerUtil.UpdateSLAInfo(slaInfo);
                // UpSert slaInfo;
               
                ev.SLAReportInfo__c = slaInfo.Id;
                update ev;
            }

            


            if(String.isNotBlank(taskId)){
                task__c task = [select id,cancelReasonSelectFSE__c,cancelReasonSelect__c,delayReasonSelectFSE__c,
                delayReasonSelect__c,taskDifferent__c,delayTaskDelay__c,Finish_Date__c from task__c where id =: taskId];
                if(reportOwner.Job_Category__c == '销售服务' && ev.cancelReasonSelectFSE__c != null){
                    task.cancelReasonSelectFSE__c = ev.cancelReasonSelectFSE__c;
                }else if(reportOwner.Job_Category__c != '销售服务' && ev.cancelReasonSelect__c != null){
                    task.cancelReasonSelect__c = ev.cancelReasonSelect__c;
                }else{
                    task.cancelReasonSelect__c = null;
                }
                // 延期理由赋值
                if(reportOwner.Job_Category__c == '销售服务' && ev.delayReasonSelectFSE__c != null){
                    task.delayReasonSelectFSE__c = ev.delayReasonSelectFSE__c;
                }else if(reportOwner.Job_Category__c != '销售服务' && ev.delayReasonSelect__c != null){
                    task.delayReasonSelect__c = ev.delayReasonSelect__c;
                }else{
                    task.delayReasonSelect__c = null;
                }
                update task;
            }
            List<Event__c> actList = new List<Event__c>();
            actList.add(ev);
            activitiesSet(actList,reportedDate,reportedId,reportOwner.Category4__c,actDelListForDelIns);
            slaAbout(reportedId,actList);
            r.code = 200;
        }catch(Exception e){
            r.code = 500;
            Database.rollback(sp);
            System.debug(e.getMessage()+',错误行数：'+e.getLineNumber());

            r.msg = e.getMessage()+',错误行数：'+e.getLineNumber();
            // r.msg = e.getDmlMessage(0);
        }finally{
            return r;
        }
        return r;
    }
    @AuraEnabled
    public static Result saveAllData(String eventsStr,String reportStr,Integer beforeHour,Integer beforeMinute,
    Integer afterHour,Integer afterMinute,String reportedId
    ) {
        system.debug('saveAllData');
        system.debug(eventsStr);
        system.debug(reportStr);
        Savepoint sp = Database.setSavepoint();
        Result r = new Result();
        try{
            system.debug('111111111111111');
            List<Event__c> evList = (List<Event__c>)JSON.deserialize(eventsStr, List<Event__c>.class);
            Daily_Report__c dr = (Daily_Report__c) JSON.deserialize(reportStr, Daily_Report__c.class);
            User reportOwner = [ Select Id,Job_Category__c,ManagerId,Manager.Email,Category4__c From User Where Id = :dr.Reporter__c];
            Date reportedDate = dr.Reported_Date__c;
            dr.Working_Time_From__c = Datetime.newInstance(reportedDate.year(), reportedDate.month(), reportedDate.day(), beforeHour, beforeMinute, 0);
            dr.Working_Time_To__c = Datetime.newInstance(reportedDate.year(), reportedDate.month(), reportedDate.day(), afterHour, afterMinute, 0);
            dr.Manager_Mail__c = reportOwner.Manager.Email;
            Datetime datetimeNow = datetime.now();
            if(dr.Planning_Time__c == null){
                dr.Planning_Time__c = datetimeNow.addHours(8);
            }
            // 承認日を設定
            if(dr.Status__c == '承認'){
                if(dr.Approved_Date__c == null){
                    dr.Approved_Date__c = date.today();
                    dr.Approved_DateTime__c = datetimeNow;
                    // 申請から承認までの時間を設定
                    Date startD = dr.Submit_Date_New__c;
                    Date endD = Date.today();
                    if(startD >= endD){
                        dr.Approval_Elapsed_Time__c = 0;
                    }
                    else{
                        Datetime endDT = datetimeNow;
                        Integer betweenDay = startD.daysBetween(endD) - 1;
                        dr.Approval_Elapsed_Time__c = betweenDay * 24 + endDT.hour();
                    }
                }
            }
            // フィードバックしたマネージャーを設定
            if(dr.Status__c == '承認' || dr.Status__c == '非承認'){
                dr.FeedbackManager__c = reportOwner.ManagerId;
            }
            // ControllerUtil.updDailyReport(dr);//zzm 20231122 不能更改活动的时间 bug修复
            // upsert dr;
            List<Event__c> insertEvs = new List<Event__c>();
            List<Event__c> updateEvs = new List<Event__c>();
            Set<Id> actDelListForDelIns = new Set<Id>();
            List<String> taskIds = new List<String>();
            for(Event__c ev : evList){
                taskIds.add(ev.taskId__c);
            }
            Map<Id, task__c> taskMap = new Map<Id, task__c>([
           select id,cancelReasonSelectFSE__c,cancelReasonSelect__c,delayReasonSelectFSE__c,
                    delayReasonSelect__c,taskDifferent__c,delayTaskDelay__c,Finish_Date__c from task__c where id in :taskIds
                ]);

           
            System.debug('saveAllData:taskMap：' + taskMap.size());  
            List<String> campaignIds = new List<String>();
            List<String> accountIds = new List<String>();
            for(Event__c ev : evList){
                if(String.isNotBlank(ev.taskId__c)){
                    // task__c task = [select id,cancelReasonSelectFSE__c,cancelReasonSelect__c,delayReasonSelectFSE__c,
                    // delayReasonSelect__c,taskDifferent__c,delayTaskDelay__c,Finish_Date__c from task__c where id =: ev.taskId__c];
                    task__c task = taskMap.get(ev.taskId__c);
                    if(reportOwner.Job_Category__c == '销售服务' && ev.cancelReasonSelectFSE__c != null){
                        task.cancelReasonSelectFSE__c = ev.cancelReasonSelectFSE__c;
                    }else if(reportOwner.Job_Category__c != '销售服务' && ev.cancelReasonSelect__c != null){
                        task.cancelReasonSelect__c = ev.cancelReasonSelect__c;
                    }else{
                        task.cancelReasonSelect__c = null;
                    }
                    // 延期理由赋值
                    if(reportOwner.Job_Category__c == '销售服务' && ev.delayReasonSelectFSE__c != null){
                        task.delayReasonSelectFSE__c = ev.delayReasonSelectFSE__c;
                    }else if(reportOwner.Job_Category__c != '销售服务' && ev.delayReasonSelect__c != null){
                        task.delayReasonSelect__c = ev.delayReasonSelect__c;
                    }else{
                        task.delayReasonSelect__c = null;
                    }
                    update task;
                }
                if(ev.eventStatus__c != '延期') {
                    ev.delayToDate__c = null;
                }
                ev.taskDifferent__c = null;
                ev.delayTaskDelay__c = false;
                ev.Finish_Date__c = null;
                ev.taskId__c = null;
                ev.backEventStatus__c = null;
                if(String.isNotBlank(ev.whatid__c) && ev.Activity_Type2__c == '社外イベント') {
                    campaignIds.add(ev.whatid__c);
                }
                if(String.isNotBlank(ev.whatid__c) && ev.Activity_Type2__c != '社外イベント') {
                    accountIds.add(ev.whatid__c);
                }
                if(String.isNotBlank(ev.Id)){
                    //更改
                    updateEvs.add(ev);
                    actDelListForDelIns.add(ev.id);
                }else{
                    //新增
                    ev.Daily_Report__c = dr.Id;
                    insertEvs.add(ev);
                }
            }
            Map<String,Campaign> campaignMaps = new Map<String,Campaign>();
            if(campaignIds.size()>0) {
                Map<String,Campaign> campaignMaptmp = new Map<String,Campaign>([select Id, Name from Campaign where Id in :campaignIds]);
                campaignMaps = campaignMaptmp;
            }

            Map<String,Account> accountMaps = new Map<String,Account>();
            if(accountIds.size()>0) {
                Map<String,Account> accountMaptmp = ControllerUtil.getAccounts(accountIds);
                accountMaps = accountMaptmp;
            }

            List<Event__c> eventListAll = new List<Event__c>();
            if(insertEvs.size()>0){
                for(Event__c ev : insertEvs){
                    
                    if(ev.ActivityDate__c ==null) {
                        ev.ActivityDate__c =reportedDate;
                    }
                    if(String.isNotBlank(ev.whatid__c) && ev.Activity_Type2__c == '社外イベント' 
                    && dr.Status__c != '承認'  && dr.Status__c != '非承認') { //zzm 23-12-11上级批准日报时，跳过学会会议的权限
                        ev.Location__c = campaignMaps.get(ev.whatid__c).Name;
                        // String locationName = [select Name from Campaign where Id = :ev.whatid__c].Name;
                        // ev.Location__c = locationName;
                    }
                    // if(String.isNotBlank(accountId)){
                    if(String.isNotBlank(ev.whatid__c) && ev.Activity_Type2__c != '社外イベント'){
                        // Account　acctmp = accountMaps.get(ev.whatid__c);
                        ev.Account_ID__c = ev.whatid__c;
                        ev.Location__c = accountMaps.get(ev.whatid__c).Name;
                        ev.HospitalMainResponsibility__c = accountMaps.get(ev.whatid__c).Parent.OwnerId;
                        ev.MainResponsibilityDirector__c = accountMaps.get(ev.whatid__c).Parent.Owner.ZongjianId__c;
                        ev.MainResponsibilityMinister__c = accountMaps.get(ev.whatid__c).Parent.Owner.BuzhangxiaoshouId__c;
                        ev.MainResponsibilityManager__c = accountMaps.get(ev.whatid__c).Parent.Owner.JinglixiaoshouId__c;
                                                // String locationName = ControllerUtil.getAccountNameForId(ev.whatid__c);

                        // if(String.isNotBlank(locationName)) {
                        //     ev.Location__c = locationName;
                        // }
                        // String locationName = [select Name from Account where Id = :ev.whatid__c].Name;
                        // ev.Location__c = locationName;
                    //zzm 230906 end
                    } else {
                        ev.Account_ID__c = null;
                    }
                    if(String.isBlank(ev.whatid__c)){
                        ev.Location__c = null;
                    }
                    //填充其他数据
                    addOtherFields(ev,dr.Status__c,reportOwner.Job_Category__c,dr.ActivityDate__c);
                }
                // insertEvs = ControllerUtil.updateEventList(insertEvs);
                // insert insertEvs;
                eventListAll.addAll(insertEvs);
            }
            if(updateEvs.size()>0){
               
                // updateEvs = ControllerUtil.updateEventList(updateEvs);
                // update updateEvs;
                for(Event__c ev: updateEvs) {
                    if(String.isNotBlank(ev.whatid__c) && ev.Activity_Type2__c == '社外イベント' 
                    && dr.Status__c != '承認'  && dr.Status__c != '非承認') { //zzm 23-12-11上级批准日报时，跳过学会会议的权限
                        ev.Location__c = campaignMaps.get(ev.whatid__c).Name;
                    }

                    if(String.isNotBlank(ev.whatid__c) && ev.Activity_Type2__c != '社外イベント' ) { //zzm 23-12-15 DB202312354407
                        ev.Account_ID__c = ev.whatid__c;
                        ev.Location__c = accountMaps.get(ev.whatid__c).Name;
                        ev.HospitalMainResponsibility__c = accountMaps.get(ev.whatid__c).Parent.OwnerId;
                        ev.MainResponsibilityDirector__c = accountMaps.get(ev.whatid__c).Parent.Owner.ZongjianId__c;
                        ev.MainResponsibilityMinister__c = accountMaps.get(ev.whatid__c).Parent.Owner.BuzhangxiaoshouId__c;
                        ev.MainResponsibilityManager__c = accountMaps.get(ev.whatid__c).Parent.Owner.JinglixiaoshouId__c;
                    }  else {
                        ev.Account_ID__c = null;
                    }

                    if(String.isBlank(ev.whatid__c)) {
                        ev.Location__c  = null;
                    }
                    addOtherFields(ev,dr.Status__c,reportOwner.Job_Category__c,dr.ActivityDate__c);

                }
                eventListAll.addAll(updateEvs);
            }
            eventListAll = ControllerUtil.updateEventList(eventListAll);
            ControllerUtil.updDailyReport(dr);//zzm 20231122 不能更改活动的时间 bug修复

            List<String> newMcIds = new List<String>();
            for(Event__c ev : eventListAll) {
                if(String.isNotBlank(ev.Related_Service1_ID__c)
                && String.isNotBlank(ev.Report_Contract__c) 
                && String.isNotBlank(ev.Report_Contract_Type__c)) {
                    newMcIds.add(ev.Related_Service1_ID__c);
                }
                
            }
            List<NewMaintenanceReport_Task__c> reportTasks = 
                [SELECT Id,
                    ActualDistributionTimes_Quarter__c,
                    NewMaintenance_Contract__c,
                    Distribution_Start_Date__c,
                    Distribution_End_Date__c,
                    Distribution_Person__c,
                    NewMaintenance_Contract__r.Contract_Consumption_rate__c 
                FROM NewMaintenanceReport_Task__c WHERE NewMaintenance_Contract__c in:newMcIds];

            // List<String> eventAndSLaIds = new List<String>();
            List<SLAReportInfo__c> slaInfos = new List<SLAReportInfo__c>();
            //sla 报告书的逻辑
            for(Event__c ev : eventListAll) {
                if(String.isNotBlank(ev.Related_Service1_ID__c)
                && String.isNotBlank(ev.Report_Contract__c) 
                && String.isNotBlank(ev.Report_Contract_Type__c)) {
                    SLAReportInfo__c slaInfo = new SLAReportInfo__c();
                    
                    if(String.isNotBlank(ev.Visitor1_ID__c)){
                        slaInfo.Visitor1__c = ev.Visitor1_ID__c;
                    }else{
                        slaInfo.Visitor1__c = null;
                    }
                    if(String.isNotBlank(ev.Visitor2_ID__c)){
                        slaInfo.Visitor2__c = ev.Visitor2_ID__c;
                    }else{
                        slaInfo.Visitor2__c = null;
                    }
                    if(String.isNotBlank(ev.Visitor3_ID__c)){
                        slaInfo.Visitor3__c = ev.Visitor3_ID__c;
                    }else{
                        slaInfo.Visitor3__c = null;
                    }
                    if(String.isNotBlank(ev.Account_ID__c)) {
                        slaInfo.Account_ID__c = ev.Account_ID__c;
                    }
                    slaInfo.Maintenance_Contract__c = ev.Related_Service1_ID__c;
                    
                    slaInfo.Distribution_Person__c = ev.Report_Contract__c;
                    slaInfo.Distribution_Method__c = ev.Report_Contract_Type__c;
                    slaInfo.Event__c = ev.Id;
                    Date today = Date.today();
                    //同一个时间段只一条NewMaintenanceReport_Task__c符合的数据
                    for (NewMaintenanceReport_Task__c reportTask : reportTasks) {
                        if(ev.Related_Service1_ID__c == reportTask.NewMaintenance_Contract__c) {
                            if (today >= reportTask.Distribution_Start_Date__c && today <= reportTask.Distribution_End_Date__c) {
                                slaInfo.SLATask__c = reportTask.Id;
                                slaInfo.Distribution_Consumption_Rate__c = reportTask.NewMaintenance_Contract__r.Contract_Consumption_rate__c;
                            }
                        }
                    }
                    if(String.isNotBlank(ev.SLAReportInfo__c)) {
                        slaInfo.Id = ev.SLAReportInfo__c;                    
                    } 
                    slaInfos.add(slaInfo);
                    // eventAndSLaIds.add(ev.Id);
                }
            }
            slaInfos = ControllerUtil.UpdateSLAInfoList(slaInfos);
            // UpSert slaInfos;
            // List<SLAReportInfo__c>  updateSLaInfos = [SELECT Id,Event__c FROM SLAReportInfo__c WHERE Event__c in :eventAndSLaIds ];
            List<Event__c> tempUpdateEvent =new List<Event__c>();
            for(SLAReportInfo__c slaInfo:slaInfos) {
                for(Event__c evetmp:eventListAll) {
                    if(slaInfo.Event__c == evetmp.Id) {
                        evetmp.SLAReportInfo__c = slaInfo.Id;
                        tempUpdateEvent.add(evetmp);
                    }
                }

            }
            if(tempUpdateEvent.size()>0) {
                ControllerUtil.updateEventList(tempUpdateEvent);
            }
            // eventListAll = ControllerUtil.updateEventList(eventListAll);
            // update eventListAll;

           /*  //把SLA报告书的业务逻辑加进来
            
            // if(reportOwner.Job_Category__c=='销售服务' && String.isNotBlank(relatedService1)
            if(String.isNotBlank(relatedService1)
                && String.isNotBlank(ev.Report_Contract__c) && String.isNotBlank(ev.Report_Contract_Type__c)) {
                List<SLAReportInfo__c>  slaInfos = [SELECT Id FROM SLAReportInfo__c WHERE Event__c = :ev.Id ];
               if(String.isNotBlank(accountId)) {
                    slaInfo.Account_ID__c = accountId;
                }
                slaInfo.Maintenance_Contract__c = relatedService1;
                slaInfo.Distribution_Person__c = ev.Report_Contract__c;
                slaInfo.Distribution_Method__c = ev.Report_Contract_Type__c;
                slaInfo.Event__c = ev.Id;


                //存在就更新
                if(slaInfos.size()>0) {
                    slaInfo.Id = slaInfos[0].Id;
                } else {
                    List<NewMaintenanceReport_Task__c> reportTasks = [SELECT Id,ActualDistributionTimes_Quarter__c,NewMaintenance_Contract__c,Distribution_Start_Date__c,Distribution_End_Date__c,Distribution_Person__c,NewMaintenance_Contract__r.Contract_Consumption_rate__c FROM NewMaintenanceReport_Task__c WHERE NewMaintenance_Contract__c =:relatedService1];
                    Date today = Date.today();
                    for (NewMaintenanceReport_Task__c reportTask : reportTasks) {
                        if (today >= reportTask.Distribution_Start_Date__c && today <= reportTask.Distribution_End_Date__c) {
                            slaInfo.SLATask__c = reportTask.Id;
                            slaInfo.Distribution_Consumption_Rate__c = reportTask.NewMaintenance_Contract__r.Contract_Consumption_rate__c;
                        }
                    }
                }
                UpSert slaInfo;
                ev.SLAReportInfo__c = slaInfo.Id;
                update ev;
            }*/




            activitiesSet(evList,dr.Reported_Date__c,dr.Id,reportOwner.Category4__c,actDelListForDelIns);
            slaAbout(dr.id,evList);
            r.code = 200;
        }catch(Exception e){
            r.code = 500;
            //  if (e.getMessage().contains(',') && e.getMessage().contains('[')){
            //     String eMessage = e.getMessage();
            //     Integer left = eMessage .indexof(',') + 1;
            //     Integer right = eMessage.lastIndexof('[')-2;
            //     r.msg = eMessage.substring(left,right);
            // }else {
            //     r.msg = e.getMessage()+',错误行数：'+e.getLineNumber();
            // }

             r.msg = e.getMessage()+',错误行数：'+e.getLineNumber();
            Database.rollback(sp);
            // r.msg = e.getMessage()+',错误行数：'+e.getLineNumber();
            // r.msg = e.getDmlMessage(0);
        }finally{
            return r;
        }
        return r;
    }
    public static void addOtherFields(Event__c ev,String reportStatus,String reportOwnerJobCategory,Date reportedDate){
         //231113 zzm start
        String Purpose = '';
        if(String.isNotBlank(ev.Activity_PurposeFSE__c)) {
            Purpose = ev.Activity_PurposeFSE__c;
        } else if(String.isNotBlank(ev.Activity_PurposeEscFSE__c)){
            Purpose = ev.Activity_PurposeEscFSE__c;
        }
        //zzm 231213 DB202312088802 2s组自定义主题 start
        if(String.isNotBlank(ev.Subject__c)) {
            if(String.isNotBlank(Purpose) && !ev.Subject__c.contains(Purpose)) {
                ev.Subject__c += '-' + Purpose;
            }
            if(String.isNotBlank(ev.Location__c) && !ev.Subject__c.contains(ev.Location__c)) {
                ev.Subject__c += '(' +ev.Location__c +')';  
            } 
        }
        //zzm 231213 DB202312088802 2s组自定义主题 end
        else if(String.isNotBlank(Purpose) && String.isNotBlank(ev.Location__c)){
          ev.Subject__c = Purpose+'(' +ev.Location__c +')';  
        } else{
            ev.Subject__c = Purpose;
        }
        //231113 zzm end
        if(reportedDate !=null ) {
            ev.ActivityDate__c = reportedDate;
        }
        
        if (reportStatus == '申請中') {
            ev.Mail_Send_Btn__c = (ev.Mail_Send_Btn__c == '0' || String.isBlank(ev.Mail_Send_Btn__c)) ? '1' : '0';
        }
        
        // if (ev.whatid__c != null && ev.whatid__c.startsWith('001')) {
        //     // 訪問場所はAccountの場合
        //     ev.Account_ID__c = ev.whatid__c;
        //     ev.Campaign_ID__c = null;
        // } else if (ev.whatid__c != null && ev.whatid__c.startsWith('701')) {
        //     // 訪問場所はCampaignの場合
        //     ev.Account_ID__c = null;
        //     ev.Campaign_ID__c = ev.whatid__c;
        // } else {
        //     ev.Account_ID__c = null;
        //     ev.Campaign_ID__c = null;
        // }

        //zh 20210623 SLA报告书任务：活动区分为合同季报时，使用报告书不能勾选 start
        if (ev.UseReport__c && '合同季报'.equals(ev.Purpose_TypeFSE__c)) {
            ev.UseReport__c = false;
        }
        //zh 20210623 SLA报告书任务：活动区分为合同季报时，使用报告书不能勾选 end
        if((reportOwnerJobCategory == '销售服务'||ev.Purpose_TypeEscFSE__c=='休假') && (ev.Purpose_TypeFSE__c != null || 
            ev.Purpose_TypeFSE2__c != null || ev.Purpose_TypeFSE3__c != null
            || ev.Purpose_TypeFSE4__c != null || ev.Purpose_TypeFSE5__c != null)){
            ev.Purpose_Type__c = ev.Purpose_TypeFSE__c;
            ev.Purpose_Type2__c =ev.Purpose_TypeFSE2__c;
            ev.Purpose_Type3__c =ev.Purpose_TypeFSE3__c;
            // ev.Purpose_Type4__c =ev.Purpose_TypeFSE4__c;
            // ev.Purpose_Type5__c =ev.Purpose_TypeFSE5__c;
        }else if((reportOwnerJobCategory != '销售服务'||ev.Purpose_TypeEscFSE__c=='休假') && (ev.Purpose_TypeEscFSE__c != null ||
            ev.Purpose_TypeEscFSE2__c != null || ev.Purpose_TypeEscFSE3__c != null
            || ev.Purpose_TypeEscFSE4__c != null || ev.Purpose_TypeEscFSE5__c != null)){
            ev.Purpose_Type__c = ev.Purpose_TypeEscFSE__c;
            ev.Purpose_Type2__c =ev.Purpose_TypeEscFSE2__c;
            ev.Purpose_Type3__c =ev.Purpose_TypeEscFSE3__c;
            // ev.Purpose_Type4__c =ev.Purpose_TypeEscFSE4__c;
            // ev.Purpose_Type5__c =ev.Purpose_TypeEscFSE5__c;
        }else{
            ev.Purpose_Type__c = null;
            ev.Purpose_Type2__c =null;
            ev.Purpose_Type3__c =null;
            // ev.Purpose_Type4__c =null;
            // ev.Purpose_Type5__c =null;
        }
    }
    //活動1,2,3の設定
    public static void activitiesSet(List<Event__c> actList,Date reportedDate,String reportId,String category4,Set<Id> actDelListForDelIns){
        List<Activity_History_Daily_Report__c> ahdrUpSertList = new List<Activity_History_Daily_Report__c>();
        for (Event__c ev : actList) {
            // 訪問者1を設定
            if(!String.isBlank(ev.Visitor1_ID__c)){
                Activity_History_Daily_Report__c ahdr = new Activity_History_Daily_Report__c();
                ahdr = new Activity_History_Daily_Report__c();
                ahdr.Daily_Report__c = reportId;
                ahdr.Contact__c = ev.Visitor1_ID__c;
                ahdr.EventC_ID__c = ev.Id;
                ahdr.Start_Time__c = ev.StartDateTime__c;
                ahdr.End_Time__c = ev.EndDateTime__c;
                ahdr.Subject__c = ev.Subject__c;
                ahdr.Place__c = ev.Location__c;
                ahdr.Date__c = reportedDate;
                ahdr.Sales_Division__c = category4;
                ahdrUpSertList.add(ahdr);
            }
            // 訪問者2を設定
            if(!String.isBlank(ev.Visitor2_ID__c)){
                Activity_History_Daily_Report__c ahdr = new Activity_History_Daily_Report__c();
                ahdr.Daily_Report__c = reportId;
                ahdr.Contact__c = ev.Visitor2_ID__c;
                ahdr.EventC_ID__c = ev.Id;
                ahdr.Start_Time__c = ev.StartDateTime__c;
                ahdr.End_Time__c = ev.EndDateTime__c;
                ahdr.Subject__c = ev.Subject__c;
                ahdr.Place__c = ev.Location__c;
                ahdr.Date__c = reportedDate;
                ahdr.Sales_Division__c = category4;
                ahdrUpSertList.add(ahdr);
            }
            // 訪問者3を設定
            if(!String.isBlank(ev.Visitor3_ID__c)){
                Activity_History_Daily_Report__c ahdr = new Activity_History_Daily_Report__c();
                ahdr.Daily_Report__c = reportId;
                ahdr.Contact__c = ev.Visitor3_ID__c;
                ahdr.EventC_ID__c = ev.Id;
                ahdr.Start_Time__c = ev.StartDateTime__c;
                ahdr.End_Time__c = ev.EndDateTime__c;
                ahdr.Subject__c = ev.Subject__c;
                ahdr.Place__c = ev.Location__c;
                ahdr.Date__c = reportedDate;
                ahdr.Sales_Division__c = category4;
                ahdrUpSertList.add(ahdr);
            }
            // 訪問者4を設定
            // if(!String.isBlank(ev.Visitor4_ID__c)){
            //     Activity_History_Daily_Report__c ahdr = new Activity_History_Daily_Report__c();
            //     ahdr.Daily_Report__c = reportId;
            //     ahdr.Contact__c = ev.Visitor4_ID__c;
            //     ahdr.EventC_ID__c = ev.Id;
            //     ahdr.Start_Time__c = ev.StartDateTime__c;
            //     ahdr.End_Time__c = ev.EndDateTime__c;
            //     ahdr.Subject__c = ev.Subject__c;
            //     ahdr.Place__c = ev.Location__c;
            //     ahdr.Date__c = reportedDate;
            //     ahdr.Sales_Division__c = category4;
            //     ahdrUpSertList.add(ahdr);
            // }
            // 訪問者5を設定
            // if(!String.isBlank(ev.Visitor5_ID__c)){
            //     Activity_History_Daily_Report__c ahdr = new Activity_History_Daily_Report__c();
            //     ahdr.Daily_Report__c = reportId;
            //     ahdr.Contact__c = ev.Visitor5_ID__c;
            //     ahdr.EventC_ID__c = ev.Id;
            //     ahdr.Start_Time__c = ev.StartDateTime__c;
            //     ahdr.End_Time__c = ev.EndDateTime__c;
            //     ahdr.Subject__c = ev.Subject__c;
            //     ahdr.Place__c = ev.Location__c;
            //     ahdr.Date__c = reportedDate;
            //     ahdr.Sales_Division__c = category4;
            //     ahdrUpSertList.add(ahdr);
            // }
        }
        
        List<Event_Oppotunity__c> eoUpSertList = new List<Event_Oppotunity__c>();
        Map<String, String> oppChkMap = new Map<String, String>();
        for (Event__c ev : actList) {
            // 関連する引合1を設定
            if(!String.isBlank(ev.Related_Opportunity1_ID__c)){
                Event_Oppotunity__c eo = new Event_Oppotunity__c();
                eo.Daily_Report__c = reportId;
                eo.Opportunity__c = ev.Related_Opportunity1_ID__c;
                eo.EventC_ID__c = ev.Id;
                eo.Start_Time__c = ev.StartDateTime__c;
                eo.End_Time__c = ev.EndDateTime__c;
                eo.Subject__c = ev.Subject__c;
                eo.Place__c = ev.Location__c;
                eo.Date__c = reportedDate;
                eo.Sales_Division__c = category4;
                eoUpSertList.add(eo);
                oppChkMap.put(ev.Related_Opportunity1_ID__c, ev.Related_Opportunity1_ID__c);
            }
    
            // 関連する引合2を設定
            if(!String.isBlank(ev.Related_Opportunity2_ID__c) && !oppChkMap.containsKey(ev.Related_Opportunity2_ID__c)){
                Event_Oppotunity__c eo = new Event_Oppotunity__c();
                eo.Daily_Report__c = reportId;
                eo.Opportunity__c = ev.Related_Opportunity2_ID__c;
                eo.EventC_ID__c = ev.Id;
                eo.Start_Time__c = ev.StartDateTime__c;
                eo.End_Time__c = ev.EndDateTime__c;
                eo.Subject__c = ev.Subject__c;
                eo.Place__c = ev.Location__c;
                eo.Date__c = reportedDate;
                eo.Sales_Division__c = category4;
                eoUpSertList.add(eo);
                
                oppChkMap.put(ev.Related_Opportunity2_ID__c, ev.Related_Opportunity2_ID__c);
            }
    
            // 関連する引合3を設定
            if(!String.isBlank(ev.Related_Opportunity3_ID__c) && !oppChkMap.containsKey(ev.Related_Opportunity3_ID__c)){
                Event_Oppotunity__c eo = new Event_Oppotunity__c();
                eo.Daily_Report__c = reportId;
                eo.Opportunity__c = ev.Related_Opportunity3_ID__c;
                eo.EventC_ID__c = ev.Id;
                eo.Start_Time__c = ev.StartDateTime__c;
                eo.End_Time__c = ev.EndDateTime__c;
                eo.Subject__c = ev.Subject__c;
                eo.Place__c = ev.Location__c;
                eo.Date__c = reportedDate;
                eo.Sales_Division__c = category4;
                eoUpSertList.add(eo);
                
                oppChkMap.put(ev.Related_Opportunity3_ID__c, ev.Related_Opportunity3_ID__c);
            }
    
            // 関連する引合4を設定
            // if(!String.isBlank(ev.Related_Opportunity4_ID__c) && !oppChkMap.containsKey(ev.Related_Opportunity4_ID__c)){
            //     Event_Oppotunity__c eo = new Event_Oppotunity__c();
            //     eo.Daily_Report__c = reportId;
            //     eo.Opportunity__c = ev.Related_Opportunity4_ID__c;
            //     eo.EventC_ID__c = ev.Id;
            //     eo.Start_Time__c = ev.StartDateTime__c;
            //     eo.End_Time__c = ev.EndDateTime__c;
            //     eo.Subject__c = ev.Subject__c;
            //     eo.Place__c = ev.Location__c;
            //     eo.Date__c = reportedDate;
            //     eo.Sales_Division__c = category4;
            //     eoUpSertList.add(eo);
            //     oppChkMap.put(ev.Related_Opportunity4_ID__c, ev.Related_Opportunity4_ID__c);
            // }
            // 関連する引合5を設定
            // if(!String.isBlank(ev.Related_Opportunity5_ID__c) && !oppChkMap.containsKey(ev.Related_Opportunity5_ID__c)){
            //     Event_Oppotunity__c eo = new Event_Oppotunity__c();
            //     eo.Daily_Report__c = reportId;
            //     eo.Opportunity__c = ev.Related_Opportunity5_ID__c;
            //     eo.EventC_ID__c = ev.Id;
            //     eo.Start_Time__c = ev.StartDateTime__c;
            //     eo.End_Time__c = ev.EndDateTime__c;
            //     eo.Subject__c = ev.Subject__c;
            //     eo.Place__c = ev.Location__c;
            //     eo.Date__c = reportedDate;
            //     eo.Sales_Division__c = category4;
            //     eoUpSertList.add(eo);
            // }
        }
    
        List<Event_Service__c> esUpSertList = new List<Event_Service__c>();
        Event_Service__c es = new Event_Service__c();
        Map<String, String> esChkMap = new Map<String, String>();
        for (Event__c ev : actList) {
            // 関連するサービス契約1を設定
            if(!String.isBlank(ev.Related_Service1_ID__c)){
                es = new Event_Service__c();
                es.Daily_Report__c = reportId;
                es.Service__c = ev.Related_Service1_ID__c;
                es.EventC_Id__c = ev.Id;
                es.Start_Time__c = ev.StartDateTime__c;
                es.End_Time_del__c = ev.EndDateTime__c;
                es.Subject__c = ev.Subject__c;
                es.Place_del__c = ev.Location__c;
                es.Date__c = reportedDate;
                es.Sales_Division__c = category4;
                esUpSertList.add(es);
                
                esChkMap.put(ev.Related_Service1_ID__c, ev.Related_Service1_ID__c);
            }
            
            // 関連するサービス契約2を設定
            if(!String.isBlank(ev.Related_Service2_ID__c) && !esChkMap.containsKey(ev.Related_Service2_ID__c)){
                es = new Event_Service__c();
                es.Daily_Report__c = reportId;
                es.Service__c = ev.Related_Service2_ID__c;
                es.EventC_ID__c = ev.Id;
                es.Start_Time__c = ev.StartDateTime__c;
                es.End_Time_del__c = ev.EndDateTime__c;
                es.Subject__c = ev.Subject__c;
                es.Place_del__c = ev.Location__c;
                es.Date__c = reportedDate;
                es.Sales_Division__c = category4;
                esUpSertList.add(es);
            }
        }
        // システム管理者権限で更新
        ControllerUtil.eventDelIns(actDelListForDelIns,ahdrUpSertList,eoUpSertList,esUpSertList);
    }
    //SLA相关
    public static void slaAbout(String repordId,List<Event__c> activities){
        Daily_Report__c report = reportSelectById(repordId)[0];
        //20201106 zh CHAN-BUV2TF 保存时把报告一览带入任务 start
        Set<String> eventOkId = new Set<String>();
        // 报告一览和事件关联map
        Map<String,Event__c> eventCAndEventMap = new Map<String,Event__c>();
        // 报告一览和任务关联map
        Map<String,Event__c> eventCAndTaskMap = new Map<String,Event__c>();
        //20210622 zh SLA和报告一览关联 start
        Map<String,Event__c> eventCAndSLA = new Map<String,Event__c>();
        List<String> SLAIds = new List<String>();
        Map<String,String> eventCAndMainC = new Map<String,String>();
        List<String> mainCIds = new List<String>();
        //20210622 zh SLA和报告一览关联 end
        List<task__c> taskupdateList = new List<task__c>();
        for(Event__c activi :activities){
            if(String.isBlank(activi.eventstatus__c) && !String.isBlank(activi.Event_ID__c)){
                eventOkId.add(activi.Event_ID__c);
                eventCAndEventMap.put(activi.Event_ID__c, activi);
            }
            // 保存的时候为任务的报告一览赋值。
            //sla信息更新 zh start
            if(String.isBlank(activi.eventstatus__c) && !String.isBlank(activi.SLAReportInfo__c) && '合同季报'.equals(activi.Purpose_TypeFSE__c)){
                eventCAndSLA.put(activi.SLAReportInfo__c,activi);
                SLAIds.add(activi.SLAReportInfo__c);
            }
            if (String.isBlank(activi.eventstatus__c) && activi.UseReport__c && !activi.SLARecorded__c && activi.Related_Service1_ID__c!=null) {
                mainCIds.add(activi.Related_Service1_ID__c);
                eventCAndMainC.put(activi.Id, activi.Related_Service1_ID__c);
            }
            //sla信息更新 zh end
        }
        if(eventOkId.size() > 0){
            // 找出所有需要完成的任务对应的事件
            List<Event> eventList = [select id,task_id__c from Event where id = :eventOkId];
            Set<String> taskId = new Set<String>();
            // Map<String,String> ifCalDlyMap = new Map<String,String>();
            for(Event e : eventList){
                taskId.add(e.task_id__c);
                if(eventCAndEventMap.containsKey(e.Id)){
                    eventCAndTaskMap.put(e.task_id__c, eventCAndEventMap.get(e.Id));
                }
            }
            // 获取任务
            List<task__c> taskList = [select id,Owner.Name,OwnerId,FeedbackDescription__c ,name,cancelReason__c,cancelReasonSelect__c,cancelReasonSelectFSE__c,delayReasonOther__c,delayReasonSelect__c,delayReasonSelectFSE__c,cancelReasonOther__c,cancelDate__c,taskDifferent__c,delayTask__c,taskStatus__c,Event__c,delayToDate__c,delayReason__c,isDelay__c from task__c where id = :taskId];
            for(task__c task : taskList){
                if(eventCAndTaskMap.containsKey(task.Id) && task.Event__c == null){
                    task.Event__c = eventCAndTaskMap.get(task.Id).id;
                    task.Daily_Report__c = eventCAndTaskMap.get(task.Id).Daily_Report__c;//20201110 zh CHAN-BUV2TF
                    taskupdateList.add(task);
                }
            }
        }
        if(taskupdateList.size() > 0){
            update taskupdateList;
        }
        if('申請中'.equals(report.Status__c )){
            LwcDailyReportController.updateTask(report.id);
            //sla信息更新 zh start
            //2021-08-27 杨杰克 修改逻辑：是否逾期都调用saveSLADetails方法，将是否逾期传入方法，方法内做逻辑处理
            System.debug('slaAbout:' );
            System.debug('eventCAndSLA.size():' +eventCAndSLA.size() );
            System.debug(eventCAndSLA );
            System.debug('SLAIds.size():' +SLAIds.size() );
            System.debug(SLAIds );

            if (eventCAndSLA.size()>0 && SLAIds.size()>0) {
                UpdateSLACompleteNumber.saveSLADetails(eventCAndSLA, SLAIds,report.Submit_DateTime_New__c <= report.Report_Deadline__c );
            }

            if (report.Submit_DateTime_New__c <= report.Report_Deadline__c ) { //提交日超过最后提交期限，不计入次数
                if (eventCAndMainC.size()>0 && mainCIds.size()>0) {
                    UpdateSLACompleteNumber.saveSLARecorded(eventCAndMainC, mainCIds);
                }
            }
        }
    }
    private static List<Daily_Report__c> reportSelectById(String id){
        List<Daily_Report__c> reportList = [select id, name, Reporter__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,Report_Deadline__c,
                                            Approved_DateTime__c, CreatedById, Feed_Back_From_Manager__c, FeedbackManager__c,FeedbackManager__r.Name,
                                            Planning_Time__c, Submission_Elapsed_Hour__c, Approval_Elapsed_Time__c,
                                            Activity_ID__c, Manager_Mail__c, Status_With_Check__c //, OCM_man_province__c
                                            , ownerid // 任务和日报管理 2020-05-21 update by vivek 
                                            from Daily_Report__c where Id = :id];
        return reportList;
    }
    // 任务框架bug 应对 by zys start 提出来放到future里面去
    @future
    public static void updateTask(string reportid){
        //230904 zzm add start 101错误
        // String cancelRecordType = [select Id from RecordType where  SobjectType = 'CancelPostponePlan__c' and DeveloperName = 'CancelType'].Id;
        // String postponeRecordType = [select Id from RecordType where  SobjectType = 'CancelPostponePlan__c' and DeveloperName = 'PostponeType'].Id;

        String cancelRecordType = Schema.SObjectType.CancelPostponePlan__c.getRecordTypeInfosByDeveloperName().get('CancelType').getRecordTypeId();
        String postponeRecordType = Schema.SObjectType.CancelPostponePlan__c.getRecordTypeInfosByDeveloperName().get('PostponeType').getRecordTypeId();

        System.debug('zzm ---cancelRecordType:' +cancelRecordType);
        System.debug('zzm ---postponeRecordType:' +postponeRecordType);
        //230904 zzm add end 101错误
        //Savepoint sp = Database.setSavepoint();
        String logstr =  ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = 'LwcDailyReportController';
        iflog.ErrorLog__c = '';
        try{
            List<Daily_Report__c> reportList = [select id, name, Reporter__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,Report_Deadline__c,
                                                Approved_DateTime__c, CreatedById, Feed_Back_From_Manager__c, FeedbackManager__c,FeedbackManager__r.Name,
                                                Planning_Time__c, Submission_Elapsed_Hour__c, Approval_Elapsed_Time__c,
                                                Activity_ID__c, Manager_Mail__c, Status_With_Check__c //, OCM_man_province__c
                                                , ownerid // 任务和日报管理 2020-05-21 update by vivek 
                                                from Daily_Report__c where Id = :reportid];
            Daily_Report__c report = reportList[0];
            // 保存时更新任务的报告一览
            // 找出所有的事件。
            Set<String> eventCalId = new Set<String>();
            Set<String> eventDlyId = new Set<String>();
            Set<String> eventOkId = new Set<String>();
            // 报告一览和事件关联map
            Map<String,Event__c> eventCAndEventMap = new Map<String,Event__c>();
            // 事件和任务关联map
            Map<String,Event> eventAndTaskMap = new Map<String,Event>();
            List<Event> updateEventList = new List<Event>();
            List<CancelPostponePlan__c> insertCancelPostponePlan = new List<CancelPostponePlan__c>();
            // 报告一览和任务关联map
            Map<String,Event__c> eventCAndTaskMap = new Map<String,Event__c>();
            // 任务和OPD关联map
            Map<String,OPDPlan__c> taskAndOPDMap = new Map<String,OPDPlan__c>();
            
            list<event__c> eventCList =ControllerUtil.getEventCList(report.Reported_Date__c, report);
            Map<String,task__c> initTaskMap = new Map<String,task__c>(); //20210429 zh SWAG-C2HCCB 任务状态修改 源任务Id和最新任务关联Map
            
            for(event__c tempEvent :eventCList){
                if(tempEvent.eventstatus__c == '取消' && !String.isBlank(tempEvent.Event_ID__c)){
                    // 更新任务取消信息
                    // 找出所有事件，再根据事件找到任务，再更新任务状态
                    eventCalId.add(tempEvent.Event_ID__c);
                    eventCAndEventMap.put(tempEvent.Event_ID__c, tempEvent);
                }
                if(tempEvent.eventstatus__c == '延期' && !String.isBlank(tempEvent.Event_ID__c)){
                    // 更新任务延期信息
                    eventDlyId.add(tempEvent.Event_ID__c);
                    eventCAndEventMap.put(tempEvent.Event_ID__c, tempEvent);
                }
                // 如果不是延期或取消，直接更新任务状态为完成
                if(String.isBlank(tempEvent.eventstatus__c) && !String.isBlank(tempEvent.Event_ID__c)){
                    eventOkId.add(tempEvent.Event_ID__c);
                    eventCAndEventMap.put(tempEvent.Event_ID__c, tempEvent);
                }
                // 保存的时候为任务的报告一览赋值。
            }
            // 找出所有的任务。
            List<task__c> taskupdateList = new List<task__c>();
            if(eventDlyId.size() > 0 || eventCalId.size() > 0 ){
                List<Event> eventList = 
                [select id,task_id__c,Opd_Plan__c,OPDPlan_Flag__c,EventStatus__c,cancelReason__c,cancelReasonOther__c,cancelReasonSelect__c,cancelReasonSelectFSE__c,cancelDate__c,isDelay__c,delayReason__c,delayReasonOther__c,delayReasonSelect__c,delayReasonSelectFSE__c  
                //2021-08-24 mzy  SWAG-C5784H 【委托】事件无法延期 start
                ,Subject 
                //2021-08-24 mzy  SWAG-C5784H 【委托】事件无法延期 end
                from Event 
                where id in :eventDlyId or id in :eventCalId];
                Set<String> taskId = new Set<String>();
                Map<String,String> ifCalDlyMap = new Map<String,String>();

                //2021-08-24 mzy  SWAG-C5784H 【委托】事件无法延期 start
                //保存任务为空的事件 
                List<String> EmptyTasksEventList = new List<String>();
                //保存事件的操作
                Map<String,String>  ifCalDlyEventMap = new Map<String,String>();
                //保存事件的主题名
                Map<String,String> SubjectNameMap = new Map<String,String>();
                //2021-08-24 mzy  SWAG-C5784H 【委托】事件无法延期 end

                for(Event e : eventList){

                    //2021-08-24 mzy  SWAG-C5784H 【委托】事件无法延期 start
                    SubjectNameMap.put(e.Id,e.Subject);

                    if(e.task_Id__c == null){
                    EmptyTasksEventList.add(e.Id);
                    if(eventDlyId.contains(e.Id)){
                        ifCalDlyEventMap.put(e.Id,'延期');
                    }
                    if(eventCalId.contains(e.Id)){
                        ifCalDlyEventMap.put(e.Id,'取消');
                    }
                    continue;
                    }
                    //2021-08-24 mzy  SWAG-C5784H 【委托】事件无法延期 end

                    taskId.add(e.task_id__c);
                    //20210525 zh 任务框架修改 start
                    eventAndTaskMap.put(e.task_id__c,e);
                    
                    if(eventCAndEventMap.containsKey(e.Id)){
                        eventCAndTaskMap.put(e.task_id__c, eventCAndEventMap.get(e.Id));
                    }
                    if(eventDlyId.contains(e.Id)){
                            ifCalDlyMap.put(e.task_id__c,'延期');
                    }
                    if(eventCalId.contains(e.Id)){
                        ifCalDlyMap.put(e.task_id__c,'取消');
                    }
                    //20210525 zh 任务框架修改 end
                }
                // zh延期理由，取消理由
                List<task__c> taskList = 
                [select id,delayTaskDelay__c,recordTypeId,
                Owner.Name,OwnerId,name,GeneratePlan__c,// 2022-1-7 yjk GeneratePlan__c,recordTypeId
                cancelReason__c,cancelReasonSelect__c,
                cancelReasonSelectFSE__c,delayReasonOther__c,
                delayReasonSelect__c,delayReasonSelectFSE__c,
                cancelReasonOther__c,cancelDate__c,taskDifferent__c,
                delayTask__c,taskStatus__c,Event__c,delayToDate__c,
                delayReason__c,isDelay__c,Initial_Task__c,Initial_Task_Different__c, 
                Maintenance_Contract__c,NewMaintenanceReport_Task__c, //20210626 zh
                Opd_Plan__c, //20210118 SWAG-BX7F9W you 
                FeedbackDescription__c, //20211102  yjk
                Opd_Plan__r.Status__c //2021-08-26 mzy SWAG-C66D37 【委托】日报取消，OPD计划取消  start
                from task__c where id in :taskId];
                // zh延期理由，取消理由
                // 延期日期为当月，补充延期日期对应的日报Map:reportDateIdMap start
                List<Date> reportDateList = new List<Date>();
                Map<Date,String> reportDateIdMap = new Map<Date,String>();
                for(task__c task : taskList){
                    if(ifCalDlyMap.get(task.Id) == '延期'){
                        if(eventCAndTaskMap.containsKey(task.Id)){
                            if(eventCAndTaskMap.get(task.Id).delayToDate__c.year() == report.Reported_Date__c.year()
                                && eventCAndTaskMap.get(task.Id).delayToDate__c.Month() ==  report.Reported_Date__c.Month()){
                                reportDateList.add(eventCAndTaskMap.get(task.Id).delayToDate__c);
                            }
                        }
                    }
                }
                //2021-08-24 mzy SWAG-C5784H 【委托】事件无法延期 start
                for(Event e : eventList){
                    if(ifCalDlyEventMap.get(e.id) == '延期'){
                        if(eventCAndEventMap.containsKey(e.Id)){
                            if(eventCAndEventMap.get(e.Id).delayToDate__c.year() == report.Reported_Date__c.year()
                                && eventCAndEventMap.get(e.Id).delayToDate__c.Month() ==  report.Reported_Date__c.Month()){
                            reportDateList.add(eventCAndEventMap.get(e.Id).delayToDate__c); 
                            }else if(eventCAndEventMap.get(e.Id).delayToDate__c.year() == report.Reported_Date__c.year()
                                && eventCAndEventMap.get(e.Id).delayToDate__c.Month() ==  report.Reported_Date__c.Month()+1){
                                reportDateList.add(eventCAndEventMap.get(e.Id).delayToDate__c); 
                            }
                        }
                    }
                }
                //2021-08-24 mzy SWAG-C5784H 【委托】事件无法延期 end
                List<Daily_Report__c> reportAllList = 
                [select id,Reported_Date__c 
                from Daily_Report__c 
                where Reported_Date__c = :reportDateList
                and OwnerId = :report.OwnerId ];
                for(Daily_Report__c rep :reportAllList){
                    reportDateIdMap.put(rep.Reported_Date__c, rep.Id);
                }
                // 延期日期为当月，补充延期日期对应的日报Map:reportDateIdMap end
                //2021-08-24 mzy SWAG-C5784H 【委托】事件无法延期 start
                if(EmptyTasksEventList.size()>0){                 
                    for(String eId : EmptyTasksEventList){
                        String subjectName = SubjectNameMap.get(eid);
                        //如果是取消,则更新事件的状态,取消理由,取消事件
                        if(ifCalDlyEventMap.get(eId)== '取消'){
                            Event tempE = new Event();
                            tempE.Id = eId;
                            tempE.cancelReason__c = eventCAndEventMap.get(eId).CancelReason__c;
                            tempE.cancelReasonOther__c = eventCAndEventMap.get(eId).cancelReasonOther__c;
                            tempE.cancelReasonSelect__c = eventCAndEventMap.get(eId).cancelReasonSelect__c;
                            tempE.cancelReasonSelectFSE__c = eventCAndEventMap.get(eId).cancelReasonSelectFSE__c;
                            tempE.EventStatus__c = '04 取消';
                            tempE.cancelDate__c = Date.today();
                            tempE.EventC_ID__c = eventCAndEventMap.get(eId).id;
                            if(subjectName!=null&&String.isNotBlank(subjectName)&&subjectName.contains('【')){
                                tempE.Subject = subjectName.split('【')[0] + '【已取消】';
                            }else if(subjectName!=null&&String.isNotBlank(subjectName)){
                                tempE.Subject = subjectName + '【已取消】';
                            }else {
                                tempE.Subject = '【已取消】';
                            }
                            updateEventList.add(tempE);
                        }
                        //如果是延期,则更新事件的状态,
                        if(ifCalDlyEventMap.get(eId)== '延期'){
                            Event tempE = new Event();
                            tempE.Id = eId;
                            tempE.delayReason__c = eventCAndEventMap.get(eId).delayReason__c;
                            tempE.delayReasonSelectFSE__c = eventCAndEventMap.get(eId).delayReasonSelectFSE__c;
                            tempE.delayReasonSelect__c = eventCAndEventMap.get(eId).delayReasonSelect__c;
                            tempE.delayReasonOther__c = eventCAndEventMap.get(eId).delayReasonOther__c;
                            tempE.EventStatus__c = '05 延期';
                            tempE.isDelay__c = true;
                            tempE.EventC_ID__c = eventCAndEventMap.get(eId).id;
                            if(subjectName!=null&&String.isNotBlank(subjectName)&&subjectName.contains('【')){                            
                                tempE.Subject = subjectName.split('【')[0] + '【已延期】';
                            }else if(subjectName!=null&&String.isNotBlank(subjectName)){
                                tempE.Subject = subjectName + '【已延期】';
                            }else {
                                tempE.Subject = '【已延期】';
                            }

                            Event__c dlyevt = new Event__c();
                            dlyevt = eventCAndEventMap.get(eId);
                            Integer dlybetweenDay = dlyevt.StartDateTime__c.date().daysBetween(dlyevt.delayToDate__c);
                            //原事件赋值延期至时间
                            tempE.delayToDate__c = dlyevt.StartDateTime__c.addDays(dlybetweenDay).Date();
                            updateEventList.add(tempE);
                            // 1.如果延期日期是本月，创建新的事件                        
                            // 2.如果延期日期是下个月，创建新的事件
                            // 事件
                            Event dlyec = ControllerUtil.getEventList(dlyevt.Id);
                            dlyec.StartDateTime = dlyevt.StartDateTime__c.addDays(dlybetweenDay);
                            dlyec.ActivityDate = dlyevt.delayToDate__c;
                            dlyec.whatid__c = dlyevt.whatid__c;
                            dlyec.EventC_ID__c = null;
                            dlyec.id = null;
                            dlyec.EventStatus__c = '02 接受';
                            if(dlyec.Subject!=null&&String.isNotBlank(dlyec.Subject)){
                                dlyec.Subject = dlyec.Subject.Split('【')[0]; 
                            }
                            insert dlyec;
                        }
                    } 
                }
                //2021-08-24 mzy SWAG-C5784H 【委托】事件无法延期 end
                for(task__c task : taskList){
                    // 如果取消，更新任务状态，取消理由，取消时间
                    if(ifCalDlyMap.get(task.Id) == '取消'){
                        if(eventCAndTaskMap.containsKey(task.Id)){
                            // zh延期理由，取消理由
                            // task.cancelReason__c = eventCAndTaskMap.get(task.Id).cancelReason__c;
                            task.cancelReason__c = eventCAndTaskMap.get(task.Id).CancelReason__c;
                            task.cancelReasonOther__c = eventCAndTaskMap.get(task.Id).cancelReasonOther__c;
                            task.cancelReasonSelect__c = eventCAndTaskMap.get(task.Id).cancelReasonSelect__c;
                            task.cancelReasonSelectFSE__c = eventCAndTaskMap.get(task.Id).cancelReasonSelectFSE__c;
                            task.FeedbackDescription__c = task.FeedbackDescription__c == null || ''.equals(task.FeedbackDescription__c) ? eventCAndTaskMap.get(task.Id).Description__c : task.FeedbackDescription__c;//2021-9-23 yjk 将报告一览的结果写入任务的反馈内容
                            // zh延期理由，取消理由
                            task.taskStatus__c = '04 取消';
                            task.cancelDate__c = Date.today();
                            task.Event__c = eventCAndTaskMap.get(task.Id).id;
                            task.Daily_Report__c = eventCAndTaskMap.get(task.Id).Daily_Report__c; // 20201110 zh CHAN-BUV2TF
                            if (task.Initial_Task__c != null) {
                                initTaskMap.put(task.Initial_Task__c,task);
                            }
                            taskupdateList.add(task);
                            //20210525 zh 任务框架修改 start
                            if (eventAndTaskMap.containsKey(task.Id)) {
                                Event tempE = eventAndTaskMap.get(task.Id);
                                tempE.cancelReason__c = eventCAndTaskMap.get(task.Id).CancelReason__c;
                                tempE.cancelReasonOther__c = eventCAndTaskMap.get(task.Id).cancelReasonOther__c;
                                tempE.cancelReasonSelect__c = eventCAndTaskMap.get(task.Id).cancelReasonSelect__c;
                                tempE.cancelReasonSelectFSE__c = eventCAndTaskMap.get(task.Id).cancelReasonSelectFSE__c;
                                tempE.EventStatus__c = '04 取消';
                                tempE.cancelDate__c = Date.today();
                                tempE.EventC_ID__c = eventCAndTaskMap.get(task.Id).id;
                                //2021-09-03  mzy SWAG-C5784H 【委托】事件无法延期 start
                                //tempE.Subject = SubjectNameMap.get(tempE.Id) + '【已取消】';
                                if(SubjectNameMap.get(tempE.Id)!=null){
                                tempE.Subject = SubjectNameMap.get(tempE.Id).split('【')[0] + '【已取消】';  
                                }else{
                                    tempE.Subject = eventAndTaskMap.get(task.Id).Subject + '【已取消】';
                                }
                                //2021-09-03  mzy  SWAG-C5784H 【委托】事件无法延期 end
                                updateEventList.add(tempE);
                            }
                            //2021-08-26 mzy SWAG-C66D37 【委托】日报取消，OPD计划取消  start
                            //如果OPD状态是取消、完毕、完毕未报告、待提交报告，就不取消opd
                            if(task.Opd_Plan__c!=null&&(task.Opd_Plan__r.Status__c !='取消'&&task.Opd_Plan__r.Status__c !='完毕'&&task.Opd_Plan__r.Status__c !='完毕未报告'&&task.Opd_Plan__r.Status__c !='待提交报告')){
                            //2021-08-26 mzy SWAG-C66D37 【委托】日报取消，OPD计划取消  end
                                //取消OPD计划
                                CancelPostponePlan__c tempCancelPostponePlan = new  CancelPostponePlan__c();
                                //0.OPD计划
                                tempCancelPostponePlan.CancelOPDPlan__c = task.Opd_Plan__c;
                                //1.延期状态
                                tempCancelPostponePlan.Status__c = '取消成功';
                                //2.记录类型
                                // tempCancelPostponePlan.RecordTypeId = '01210000000gQyL';
                                //230904 zzm start
                                tempCancelPostponePlan.RecordTypeId = cancelRecordType;
                                //230904 zzm end
                                //4.取消理由
                                //2021-11-02  mzy  任务管理改善 start
                                Integer FIELDMAX = 25;
                                Map<String,String> TaskAndOPDMapping = new Map<String,String>();
                                TaskEventReportOPD__c mpdmapping = null;
                                mpdmapping = TaskEventReportOPD__c.getValues('TaskAndOPD_Cancel');
                                for (Integer i = 1; i <= FIELDMAX; i++) {
                                    if(mpdmapping!=null){
                                        String lpadI = ('00' + i).right(3);
                                        String SSColumn = 'SS_Column_' + lpadI + '__c';
                                        String taskSC = String.valueOf(mpdMapping.get(SSColumn));
                                        if(String.isNotBlank(taskSC)){
                                            String FRColumn = 'From_Column_' + lpadI + '__c';
                                            String OPDFC = String.valueOf(mpdMapping.get(FRColumn));
                                            TaskAndOPDMapping.put(taskSC, OPDFC);
                                        }
                                    }
                                }
                                
                                String reason = TaskAndOPDMapping.get(eventCAndTaskMap.get(task.Id).CancelReason__c);
                                tempCancelPostponePlan.cancelReasonCombobox__c = reason == null || ''.equals(reason) ? '其他': reason;
                                insertCancelPostponePlan.add(tempCancelPostponePlan);
                            }
                            //20210525 zh 任务框架修改 end
                        }
                    }
                    // 如果延期，更新任务状态，延期时间delayToDate__c，延期理由delayReason__c，延期标记
                    // 1.如果延期日期是本月，创建新的事件，报告一览以及已接受的任务。
                    // 2.如果延期日期是下个月，创建新的事件，以及已接受的任务。
                    if(ifCalDlyMap.get(task.Id) == '延期'){
                        System.debug('延期需要进来:'+ifCalDlyMap.get(task.Id));
                        if(eventCAndTaskMap.containsKey(task.Id)){
                            //2021-10-13  mzy  任务管理改善  satrt
                            //上级分配任务 和主动任务、被动任务平级  , 判断 是被动任务的地方也要 加上上级分配任务
                            if ('07 未执行'.equals(task.taskStatus__c) && ('被动任务'.equals(task.Initial_Task_Different__c)||'上级分配任务'.equals(task.Initial_Task_Different__c)) ) { 
                            //2021-10-13  mzy  任务管理改善  end
                            }else { //20210429 zh SWAG-C2HCCB 任务状态修改
                                // 更新任务状态等信息。
                                // zh延期理由，取消理由
                                task.delayReason__c = eventCAndTaskMap.get(task.Id).delayReason__c;
                                task.delayReasonSelectFSE__c = eventCAndTaskMap.get(task.Id).delayReasonSelectFSE__c;
                                task.delayReasonSelect__c = eventCAndTaskMap.get(task.Id).delayReasonSelect__c;
                                task.delayReasonOther__c = eventCAndTaskMap.get(task.Id).delayReasonOther__c;
                                task.FeedbackDescription__c = task.FeedbackDescription__c == null || ''.equals(task.FeedbackDescription__c) ? eventCAndTaskMap.get(task.Id).Description__c : task.FeedbackDescription__c;//2021-9-23 yjk 将报告一览的结果写入任务的反馈内容
                                // zh延期理由，取消理由
                                task.delayToDate__c = eventCAndTaskMap.get(task.Id).delayToDate__c;
                                task.delayDate__c = Date.today(); // zh 20210108 延期日期
                                task.taskStatus__c = '05 延期';
                                task.Event__c = eventCAndTaskMap.get(task.Id).id;
                                task.Daily_Report__c = eventCAndTaskMap.get(task.Id).Daily_Report__c; //20201110 zh CHAN-BUV2TF
                                task.isDelay__c = true;
                                // task.Name = task.Owner.Name+' 测试任务 '+task.taskStatus__c;
                                System.debug('延期理由需要不为空:'+eventCAndTaskMap.get(task.Id).delayReasonSelect__c);
                                taskupdateList.add(task);

                                //20210525 zh 任务框架修改 start
                                if (eventAndTaskMap.containsKey(task.Id)) {
                                    Event tempE = eventAndTaskMap.get(task.Id);
                                    tempE.delayReason__c = eventCAndTaskMap.get(task.Id).delayReason__c;
                                    tempE.delayReasonSelectFSE__c = eventCAndTaskMap.get(task.Id).delayReasonSelectFSE__c;
                                    tempE.delayReasonSelect__c = eventCAndTaskMap.get(task.Id).delayReasonSelect__c;
                                    tempE.delayReasonOther__c = eventCAndTaskMap.get(task.Id).delayReasonOther__c;
                                    tempE.EventStatus__c = '05 延期';
                                    tempE.isDelay__c = true;
                                    tempE.Task_ID__c = task.Id;
                                    tempE.EventC_ID__c = eventCAndTaskMap.get(task.Id).id;
                                    //2021-09-03  mzy SWAG-C5784H 【委托】事件无法延期 start
                                    if(SubjectNameMap.get(tempE.Id)!=null){
                                    tempE.Subject = SubjectNameMap.get(tempE.Id).split('【')[0] + '【已延期】';  
                                    }else{
                                        tempE.Subject = eventAndTaskMap.get(tempE.Id).subject + '【已延期】';
                                    }
                                    tempE.delayToDate__c = eventCAndTaskMap.get(task.Id).delayToDate__c;
                                    //2021-09-03  mzy  SWAG-C5784H 【委托】事件无法延期 end

                                    System.debug('事件延期理由需要不为空:'+tempE.delayReasonSelect__c);
                                    updateEventList.add(tempE);
                                }
                                //2021-08-26 mzy SWAG-C66D37 【委托】日报取消，OPD计划取消  start
                                //如果OPD状态是取消、完毕、完毕未报告 待提交报告，就不延期opd
                                if(task.Opd_Plan__c!=null&&(task.Opd_Plan__r.Status__c !='取消'&&task.Opd_Plan__r.Status__c !='完毕'&&task.Opd_Plan__r.Status__c !='完毕未报告'&&task.Opd_Plan__r.Status__c !='待提交报告')){
                                //2021-08-26 mzy SWAG-C66D37 【委托】日报取消，OPD计划取消  end
                                    //延期OPD计划
                                    CancelPostponePlan__c tempCancelPostponePlan = new  CancelPostponePlan__c();
                                    //0.OPD计划
                                    tempCancelPostponePlan.CancelOPDPlan__c = task.Opd_Plan__c;
                                    //1.延期状态
                                    tempCancelPostponePlan.Status__c = '延期成功';
                                    //2.记录类型
                                    // tempCancelPostponePlan.RecordTypeId = '01210000000gQyM';
                                    //230904 zzm start
                                    tempCancelPostponePlan.RecordTypeId = postponeRecordType;
                                    //230904 zzm end
                                    //4.取消理由
                                    //2021-11-02   mzy  任务管理改善开发计划  start
                                    Integer FIELDMAX = 25;
                                    Map<String,String> TaskAndOPDMapping = new Map<String,String>();
                                    TaskEventReportOPD__c mpdmapping = null;
                                    mpdmapping = TaskEventReportOPD__c.getValues('TaskAndOPD_Delay');
                                    for (Integer i = 1; i <= FIELDMAX; i++) {
                                        if(mpdmapping!=null){
                                            String lpadI = ('00' + i).right(3);
                                            String SSColumn = 'SS_Column_' + lpadI + '__c';
                                            String taskSC = String.valueOf(mpdMapping.get(SSColumn));
                                            if(String.isNotBlank(taskSC)){
                                                String FRColumn = 'From_Column_' + lpadI + '__c';
                                                String OPDFC = String.valueOf(mpdMapping.get(FRColumn));
                                                TaskAndOPDMapping.put(taskSC, OPDFC);
                                            }
                                        }
                                    }
                                    String reason = TaskAndOPDMapping.get(eventCAndTaskMap.get(task.Id).delayReason__c);
                                    tempCancelPostponePlan.cancelReasonCombobox__c = reason == null || ''.equals(reason) ? '其他': reason;
                                    tempCancelPostponePlan.NextPlanDate__c = eventCAndTaskMap.get(task.Id).delayToDate__c;
                                    tempCancelPostponePlan.ApplyType__c = '延期';
                                    tempCancelPostponePlan.isDailyReportDelay__c = true; //2022-1-11 yjk 是否日報取消設為true
                                    insertCancelPostponePlan.add(tempCancelPostponePlan);
                                }
                                //20210525 zh 任务框架修改 end
                                // 延期日期是本月，创建新的事件，报告一览以及已接受的任务。 start
                                if(eventCAndTaskMap.get(task.Id).delayToDate__c.year() == report.Reported_Date__c.year() && eventCAndTaskMap.get(task.Id).delayToDate__c.Month() ==  report.Reported_Date__c.Month()){

                                    // 延期日期是本月。创建新的事件，报告一览以及已接受的任务。
                                    Event__c dlyevt = new Event__c();
                                    dlyevt = eventCAndTaskMap.get(task.Id);
                                    if(reportDateIdMap.containsKey(dlyevt.delayToDate__c)){
                                    // 判断延期日期是否有对应日报一览，因为非工作日不会生成日报一览。
                                        // 任务
                                        task__c delayTask = new task__c();
                                        //20210118 SWAG-BX7F9W you start
                                        delayTask.Opd_Plan__c = task.Opd_Plan__c;
                                        //20210118 SWAG-BX7F9W you end
                                        delayTask.Maintenance_Contract__c = task.Maintenance_Contract__c;
                                        delayTask.NewMaintenanceReport_Task__c = task.NewMaintenanceReport_Task__c;
                                        delayTask.taskStatus__c = '02 接受'; // 状态
                                        delayTask.assignee__c = report.OwnerId; //被分配者
                                        delayTask.OwnerId = report.OwnerId;
                                        delayTask.ConfirmDate__c = Date.today(); //接受时间
                                        delayTask.Activity_Date__c = eventCAndTaskMap.get(task.Id).delayToDate__c; //拜访日期 20201105 zh CHAN-BUV2TF
                                        delayTask.Event__c = null;
                                        delayTask.Daily_Report__c = reportDateIdMap.get(dlyevt.delayToDate__c);// 日报一览 20201110 zh CHAN-BUV2TF
                                        delayTask.taskDifferent__c = '主动任务';
                                        //2021-10-13  mzy  任务管理改善  satrt
                                        //上级分配任务 和主动任务、被动任务平级  , 判断 是被动任务的地方也要 加上上级分配任务
                                        /*if(task.taskDifferent__c == '被动任务' || task.delayTaskDelay__c == true){
                                            delayTask.delayTaskDelay__c = true;
                                        }*/
                                        if(task.taskDifferent__c == '被动任务' ||task.taskDifferent__c == '上级分配任务' || task.delayTaskDelay__c == true){
                                            delayTask.delayTaskDelay__c = true;
                                        }
                                        //2021-10-13  mzy  任务管理改善  end
                                        delayTask.Initial_Task__c = task.Initial_Task__c == null ? task.Id : task.Initial_Task__c; //20210428 zh 初始任务
                                        if (String.isNotBlank(eventCAndTaskMap.get(task.Id).whatid__c)) {
                                            if(eventCAndTaskMap.get(task.Id).whatid__c.startsWith('701')){
                                                delayTask.Campaign__c = eventCAndTaskMap.get(task.Id).whatid__c;//市场活动
                                            }
                                            if(eventCAndTaskMap.get(task.Id).whatid__c.startsWith('001')){
                                                delayTask.account__c = eventCAndTaskMap.get(task.Id).whatid__c;//客户
                                            }
                                        }

                                        if (eventCAndTaskMap.get(task.Id).Related_Opportunity1_ID__c != null) {
                                            delayTask.OpportunityId__c = eventCAndTaskMap.get(task.Id).Related_Opportunity1_ID__c;
                                        }
                                        
                                        delayTask.delayTaskP__c = task.Id;
                                        delayTask.Name = task.Name;
                                        delayTask.recordTypeId = task.recordTypeId; //2022-1-7 yjk 增加新延期任务的类型赋值
                                        delayTask.GeneratePlan__c = task.GeneratePlan__c; //2022-1-7 yjk 增加新延期任务的需要拜访字段赋值
                                        insert delayTask;
                                        task.delayTask__c = delayTask.Id;
                                        //20210429 zh SWAG-C2HCCB 任务状态修改 start
                                        if (task.Initial_Task__c != null) {
                                            initTaskMap.put(task.Initial_Task__c,delayTask);
                                        }else{
                                            task.Event__c = delayTask.Event__c;
                                            task.Daily_Report__c = delayTask.Daily_Report__c;
                                        }
                                        //20210429 zh SWAG-C2HCCB 任务状态修改 end
                                        Integer dlybetweenDay = dlyevt.StartDateTime__c.date().daysBetween(dlyevt.delayToDate__c);
                                        if(task!=null){                                         
                                            // 事件
                                            Event dlyec = ControllerUtil.getEventList(dlyevt.Id);
                                            dlyec.StartDateTime = dlyevt.StartDateTime__c.addDays(dlybetweenDay);
                                            dlyec.task_id__c = delayTask.Id;
                                            dlyec.ActivityDate = dlyevt.delayToDate__c;
                                            dlyec.whatid__c = dlyevt.whatid__c;
                                            dlyec.EventC_ID__c = null;
                                            dlyec.id = null;
                                            dlyec.EventStatus__c = '02 接受';
                                            if(dlyec.Subject!=null&&String.isNotBlank(dlyec.Subject)){
                                                dlyec.Subject = dlyec.Subject.Split('【')[0]; 
                                            }
                                            dlyec.EventStatus__c = '02 接受';
                                            insert dlyec;
                                        }
                                    }else{
                                        // 非工作日，只生成事件
                                        // 任务
                                        task__c delayTask = new task__c();
                                        //20210118 SWAG-BX7F9W you start
                                        delayTask.Opd_Plan__c = task.Opd_Plan__c;
                                        //20210118 SWAG-BX7F9W you end
                                        delayTask.Maintenance_Contract__c = task.Maintenance_Contract__c;
                                        delayTask.NewMaintenanceReport_Task__c = task.NewMaintenanceReport_Task__c;
                                        delayTask.taskStatus__c = '02 接受'; // 状态
                                        delayTask.assignee__c = report.OwnerId; //被分配者
                                        delayTask.OwnerId = report.OwnerId;
                                        // delayTask.taskDifferent__c = task.taskDifferent__c;
                                        delayTask.taskDifferent__c = '主动任务';
                                        //2021-10-13  mzy  任务管理改善  satrt
                                        //上级分配任务 和主动任务、被动任务平级  , 判断 是被动任务的地方也要 加上上级分配任务
                                        /*if(task.taskDifferent__c == '被动任务' || task.delayTaskDelay__c == true){
                                            delayTask.delayTaskDelay__c = true;
                                        }*/
                                        if(task.taskDifferent__c == '被动任务' ||task.taskDifferent__c == '上级分配任务' || task.delayTaskDelay__c == true){
                                            delayTask.delayTaskDelay__c = true;
                                        }
                                        //2021-10-13  mzy  任务管理改善  end
                                        delayTask.Initial_Task__c = task.Initial_Task__c == null ? task.Id : task.Initial_Task__c; //20210428 zh 初始任务
                                        delayTask.ConfirmDate__c = Date.today(); //接受时间
                                        delayTask.Activity_Date__c = eventCAndTaskMap.get(task.Id).delayToDate__c; //拜访日期 20201105 zh CHAN-BUV2TF
                                        // delayTask.Event__c = dlyevt.Id;
                                        if (String.isNotBlank(eventCAndTaskMap.get(task.Id).whatid__c)) {
                                            if(eventCAndTaskMap.get(task.Id).whatid__c.startsWith('701')){
                                                delayTask.Campaign__c = eventCAndTaskMap.get(task.Id).whatid__c;//市场活动
                                            }
                                            if(eventCAndTaskMap.get(task.Id).whatid__c.startsWith('001')){
                                                delayTask.account__c = eventCAndTaskMap.get(task.Id).whatid__c;//客户
                                            }
                                        }
                                        if (eventCAndTaskMap.get(task.Id).Related_Opportunity1_ID__c != null) {
                                            delayTask.OpportunityId__c = eventCAndTaskMap.get(task.Id).Related_Opportunity1_ID__c;
                                        }
                                        delayTask.FeedbackDescription__c = task.FeedbackDescription__c == null || ''.equals(task.FeedbackDescription__c) ? eventCAndTaskMap.get(task.Id).Description__c : task.FeedbackDescription__c;//2021-9-23 yjk 将报告一览的结果写入任务的反馈内容
                                        delayTask.delayTaskP__c = task.Id;
                                        delayTask.Name = task.Name;
                                        delayTask.recordTypeId = task.recordTypeId; //2022-1-7 yjk 增加新延期任务的类型赋值
                                        delayTask.GeneratePlan__c = task.GeneratePlan__c; //2022-1-7 yjk 增加新延期任务的需要拜访字段赋值
                                        insert delayTask;
                                        task.delayTask__c = delayTask.Id;
                                        //20210429 zh SWAG-C2HCCB 任务状态修改 start
                                        if (task.Initial_Task__c != null) {
                                            initTaskMap.put(task.Initial_Task__c,delayTask);
                                        }else{
                                            task.Event__c = delayTask.Event__c;
                                            task.Daily_Report__c = delayTask.Daily_Report__c;
                                        }
                                        //20210429 zh SWAG-C2HCCB 任务状态修改 end
                                        Integer dlybetweenDay = dlyevt.StartDateTime__c.date().daysBetween(dlyevt.delayToDate__c);
                                        //2021-08-26 mzy SWAG-C66D37 【委托】日报取消，OPD计划取消  start
                                        //延期时,如果有OPD计划,则不生成新事件
                                        //if(task!=null&&task.Opd_Plan__c==null){ 2022-1-11 yjk 有opd也新建事件。不从opd触发器新建事件
                                        if(task!=null){                                          
                                            // 事件
                                            Event dlyec = ControllerUtil.getEventList(dlyevt.Id);
                                            dlyec.StartDateTime = dlyevt.StartDateTime__c.addDays(dlybetweenDay);
                                            dlyec.task_id__c = delayTask.Id;
                                            dlyec.ActivityDate = dlyevt.delayToDate__c;
                                            dlyec.whatid__c = dlyevt.whatid__c;
                                            dlyec.EventC_ID__c = null;
                                            dlyec.id = null;
                                            dlyec.EventStatus__c = '02 接受';
                                            if(dlyec.Subject!=null&&String.isNotBlank(dlyec.Subject)){
                                                dlyec.Subject = dlyec.Subject.Split('【')[0]; 
                                            }
                                            insert dlyec;
                                        }
                                        //2021-08-26 mzy SWAG-C66D37 【委托】日报取消，OPD计划取消  start
                                    }
                                }else if(report.Reported_Date__c.monthsBetween(eventCAndTaskMap.get(task.Id).delayToDate__c) == 1){
                                    // 延期日期是下个月,创建事件和任务。
                                    Event__c dlyevt = new Event__c();
                                    dlyevt = eventCAndTaskMap.get(task.Id);
                                    dlyevt.whatid__c = eventCAndTaskMap.get(task.Id).whatid__c; 
                                    // 任务
                                    task__c delayTask = new task__c();
                                    //20210118 SWAG-BX7F9W you start
                                    delayTask.Opd_Plan__c = task.Opd_Plan__c;
                                    //20210118 SWAG-BX7F9W you end
                                    delayTask.Maintenance_Contract__c = task.Maintenance_Contract__c;
                                    delayTask.NewMaintenanceReport_Task__c = task.NewMaintenanceReport_Task__c;
                                    delayTask.taskStatus__c = '02 接受'; // 状态
                                    delayTask.assignee__c = report.OwnerId; //被分配者
                                    delayTask.OwnerId = report.OwnerId;
                                    // delayTask.taskDifferent__c = task.taskDifferent__c;
                                    delayTask.taskDifferent__c = '主动任务';
                                    // 添加一个标记，标记改任务是被动任务的延期任务
                                    delayTask.FeedbackDescription__c = task.FeedbackDescription__c == null || ''.equals(task.FeedbackDescription__c) ? eventCAndTaskMap.get(task.Id).Description__c : task.FeedbackDescription__c;//2021-9-23 yjk 将报告一览的结果写入任务的反馈内容
                                    if(task.taskDifferent__c == '被动任务' ||task.taskDifferent__c == '上级分配任务' || task.delayTaskDelay__c == true){
                                        delayTask.delayTaskDelay__c = true;
                                    }
                                    //2021-10-13  mzy  任务管理改善  end
                                    delayTask.Initial_Task__c = task.Initial_Task__c == null ? task.Id : task.Initial_Task__c; //20210428 zh 初始任务
                                    delayTask.ConfirmDate__c = Date.today(); //接受时间
                                    delayTask.Activity_Date__c = eventCAndTaskMap.get(task.Id).delayToDate__c; //拜访日期 20201105 zh CHAN-BUV2TF
                                    // delayTask.Event__c = dlyevt.Id;
                                    if (String.isNotBlank(eventCAndTaskMap.get(task.Id).whatid__c)) {
                                        if(eventCAndTaskMap.get(task.Id).whatid__c.startsWith('701')){
                                            delayTask.Campaign__c = eventCAndTaskMap.get(task.Id).whatid__c;//市场活动
                                        }
                                        if(eventCAndTaskMap.get(task.Id).whatid__c.startsWith('001')){
                                            delayTask.account__c = eventCAndTaskMap.get(task.Id).whatid__c;//客户
                                        }
                                    }
                                    if (eventCAndTaskMap.get(task.Id).Related_Opportunity1_ID__c != null) {
                                        delayTask.OpportunityId__c = eventCAndTaskMap.get(task.Id).Related_Opportunity1_ID__c;
                                    }
                                    // delayTask.account__c = eventCAndTaskMap.get(task.Id).whatid__c; //客户
                                    delayTask.delayTaskP__c = task.Id;
                                    // delayTask.CreatedById = task.OwnerId;
                                    delayTask.Name = task.Name;
                                    delayTask.recordTypeId = task.recordTypeId; //2022-1-7 yjk 增加新延期任务的类型赋值
                                    delayTask.GeneratePlan__c = task.GeneratePlan__c; //2022-1-7 yjk 增加新延期任务的需要拜访字段赋值
                                    insert delayTask;
                                    task.delayTask__c = delayTask.Id;
                                    //20210429 zh SWAG-C2HCCB 任务状态修改 start
                                    if (task.Initial_Task__c != null) {
                                        initTaskMap.put(task.Initial_Task__c,delayTask);
                                    }else{
                                        task.Event__c = delayTask.Event__c;
                                        task.Daily_Report__c = delayTask.Daily_Report__c;
                                    }
                                    //20210429 zh SWAG-C2HCCB 任务状态修改 end
                                    Integer dlybetweenDay = dlyevt.StartDateTime__c.date().daysBetween(dlyevt.delayToDate__c);
                                    // 事件
                                    Event dlyec = ControllerUtil.getEventList(dlyevt.Id);
                                    dlyec.StartDateTime = dlyevt.StartDateTime__c.addDays(dlybetweenDay);
                                    dlyec.task_id__c = delayTask.Id;
                                    dlyec.ActivityDate = dlyevt.delayToDate__c;
                                    dlyec.whatid__c = dlyevt.whatid__c;
                                    dlyec.EventC_ID__c = null;
                                    dlyec.id = null;
                                    dlyec.EventStatus__c = '02 接受';
                                    if(dlyec.Subject!=null&&String.isNotBlank(dlyec.Subject)){
                                        dlyec.Subject = dlyec.Subject.Split('【')[0]; 
                                    }
                                    insert dlyec;
                                    // 延期日期是下个月，创建新的事件，以及已接受的任务。 end
                                }else{

                                }
                            }
                        }
                    }
                }
            }
            // 如果有对应任务直接更新任务状态为完成。start
            if(eventOkId.size() > 0){
                // 找出所有需要完成的任务对应的事件
                List<Event> eventList = [select id,task_id__c from Event where id = :eventOkId];
                Set<String> taskId = new Set<String>();
                for(Event e : eventList){
                        taskId.add(e.task_id__c);
                        if(eventCAndEventMap.containsKey(e.Id)){
                            eventCAndTaskMap.put(e.task_id__c, eventCAndEventMap.get(e.Id));
                        }
                        if (!eventAndTaskMap.containsKey(e.Id)) {
                            eventAndTaskMap.put(e.task_id__c, e);
                        }
                    if(String.IsBlank(e.task_id__c)){
                        e.EventStatus__c = '03 完成';
                        e.EventC_ID__c = eventCAndEventMap.get(e.Id).id;
                        updateEventList.add(e);
                    }
                }
                // 获取任务
                List<task__c> taskList = [select id,Owner.Name,OwnerId,Opd_Plan__c,NeedActivity__c,FeedbackDescription__c,name,cancelReason__c,cancelReasonSelect__c,cancelReasonSelectFSE__c,delayReasonOther__c,delayReasonSelect__c,delayReasonSelectFSE__c,cancelReasonOther__c,cancelDate__c,taskDifferent__c,delayTask__c,taskStatus__c,Event__c,delayToDate__c,delayReason__c,isDelay__c,Initial_Task__c,Initial_Task_Different__c,Maintenance_Contract__c,NewMaintenanceReport_Task__c from task__c where id = :taskId];
                List<task__c> updateSLATask = new List<task__c>();
                for(task__c task : taskList){
                    if(eventCAndTaskMap.containsKey(task.Id)){
                        if(task.taskStatus__c != '03 完成'){
                            updateSLATask.add(task);
                        }
                        // task.cancelReason__c = eventCAndTaskMap.get(task.Id).cancelReason__c;
                        if (task.taskStatus__c != '07 未执行' && task.NeedActivity__c) {//2021-9-17 yjk 补充判断，如果是opd任务，不能在日报提交时完成
                            task.taskStatus__c= '03 完成';
                            //20210525 zh 任务框架修改 start
                            if (eventAndTaskMap.containsKey(task.Id)) {
                                Event tempE = eventAndTaskMap.get(task.Id);
                                tempE.EventStatus__c = '03 完成';
                                tempE.EventC_ID__c = eventCAndTaskMap.get(task.Id).id;
                                updateEventList.add(tempE);
                            }
                            //20210525 zh 任务框架修改 end
                        }
                        task.Event__c = eventCAndTaskMap.get(task.Id).id;
                        task.Daily_Report__c = eventCAndTaskMap.get(task.Id).Daily_Report__c; // 20201110 zh CHAN-BUV2TF
                        task.FeedbackDescription__c = task.FeedbackDescription__c == null || ''.equals(task.FeedbackDescription__c) ? eventCAndTaskMap.get(task.Id).Description__c : task.FeedbackDescription__c;//2021-9-23 yjk 将报告一览的结果写入任务的反馈内容
                        // task.Name = task.owner.Name+'测试任务'+task.taskStatus__c;
                        //20210429 zh SWAG-C2HCCB 任务状态修改 start
                        if (task.Initial_Task__c != null) {
                            initTaskMap.put(task.Initial_Task__c,task);
                        }
                        taskupdateList.add(task);
                    }
                }
            }
            //20210429 zh SWAG-C2HCCB 任务状态修改 start
            //如果有初始任务，修改初始任务的报告一览和日报一览以及状态
            if (initTaskMap.keySet().size()>0) {
                List<task__c> taskList = [SELECT Id,Event__c,Daily_Report__c,FeedbackDescription__c,taskStatus__c,taskDifferent__c,Activity_Date__c,CreateDate__c FROM task__c WHERE Id IN :initTaskMap.keySet()];
                for(task__c task : taskList){
                    if (initTaskMap.containsKey(task.Id)) {
                        task.Event__c = initTaskMap.get(task.Id).Event__c;
                        task.Daily_Report__c = initTaskMap.get(task.Id).Daily_Report__c;
                        task.cancelReasonOther__c = initTaskMap.get(task.Id).cancelReasonOther__c == null?'':initTaskMap.get(task.Id).cancelReasonOther__c;
                        task.cancelReasonSelectFSE__c = initTaskMap.get(task.Id).cancelReasonSelectFSE__c == null?'':initTaskMap.get(task.Id).cancelReasonSelectFSE__c;
                        task.cancelReasonSelect__c = initTaskMap.get(task.Id).cancelReasonSelect__c == null?'':initTaskMap.get(task.Id).cancelReasonSelect__c;
                        task.cancelReason__c = initTaskMap.get(task.Id).cancelReason__c == null?'':initTaskMap.get(task.Id).cancelReason__c;
                        //取消/完成不允许更新未执行
                        //源任务如果是主动任务，允许状态从未执行更新为延期
                        if ('主动任务'.equals(task.taskDifferent__c)) {
                            if (task.taskStatus__c != '07 未执行' ) {
                                task.taskStatus__c = initTaskMap.get(task.Id).taskStatus__c == '02 接受' ? '05 延期' : initTaskMap.get(task.Id).taskStatus__c;
                            }else{
                                if (initTaskMap.get(task.Id).taskStatus__c == '02 接受' && initTaskMap.get(task.Id).Activity_Date__c > task.CreateDate__c.addDays(60)) { //超过60天的延期任务
                                    task.taskStatus__c = '05 延期';
                                }
                            }
                        }else{ //被动任务
                            if (task.taskStatus__c != '07 未执行' ) {
                                task.taskStatus__c = initTaskMap.get(task.Id).taskStatus__c == '02 接受' ? '05 延期' : initTaskMap.get(task.Id).taskStatus__c;
                            }
                        }
                        taskupdateList.add(task);
                    }
                }
            }
            if(taskupdateList.size() > 0){
                update taskupdateList;
            }
            // 如果有对应任务直接更新任务状态为完成。end
            if(updateEventList.size()>0){
                update updateEventList;
            }
            if(insertCancelPostponePlan.size() > 0){
                insert insertCancelPostponePlan;
            }

        }catch(Exception ex){
            logstr += '\n' + ex.getMessage();
            String exstr = String.valueOf(ex);
            iflog = NFMUtil.QLMmakeRowData(exstr,iflog);
            if(ex.getCause()!=null){
                iflog.ErrorLog__c = ex.getCause()+'\r\n';
            }
            iflog.ErrorLog__c += iflog.Log__c +'\r\n'+ ex.getStackTraceString();
            insert iflog;
        }
    }
    @AuraEnabled
    public static String queryDepartmentClass(String accId) {
        Account a = [select id,Department_Class__c from Account where id =: accId];
        return a.Department_Class__c;
    }
    @AuraEnabled
    public static LeadResult queryAbountIndo(String accId,String contactId) {
        LeadResult r = new LeadResult();
        Account acc = [select id,Department_Class__c,name,Hospital__c from Account where id =: accId];  //添加Hospital__c by DTT-亚楠 20240109
        r.acc = acc;
        if(String.isNotBlank(contactId)){
            Contact con = [SELECT Id,Name FROM Contact WHERE Id = :contactId];//去除AWS_Data_Id__c by DTT-亚楠 20240109
            // r.awsId = con.AWS_Data_Id__c;//pipl还原 by DTT-亚楠 20240109
            r.con = con;
        }
        return r;
    }
    public class LeadResult {
        @AuraEnabled public Account acc;
        @AuraEnabled public String awsId;
        @AuraEnabled public Contact con;
    }
    @AuraEnabled
    public static String queryHospital(String accId) {
        Account a = [select id,Hospital__c from Account where id =: accId];
        return a.Hospital__c;
    }
    @AuraEnabled
    public static Account getAccountForJs(String id){
        return [select Id, Name, Department_Class__r.Name, Department_Class__r.Id,
                Hospital__r.Name, Hospital__r.Id, Hospital__r.OCM_Category__c
                from Account where Id = :id];
    }
    public class Result {
        @AuraEnabled public Integer code;//状态码
        @AuraEnabled public String msg;//返回信息
        // @AuraEnabled public String eventId;//手动创建的报告一览第一次保存时，赋值event_ID
    }
    public class DataWrap {
        @AuraEnabled public Daily_Report__c report;
        @AuraEnabled public User reportOwner;
        @AuraEnabled public Boolean reportReportFlg;
        @AuraEnabled public String currentUserId;
        @AuraEnabled public List<Event__c> returnEvents;
        @AuraEnabled public Integer beforeHour;
        @AuraEnabled public Integer beforeMinute;
        @AuraEnabled public Integer afterHour;
        @AuraEnabled public Integer afterMinute;
        @AuraEnabled public Boolean reportStatusFlg;
        @AuraEnabled public String Job_Category;
        @AuraEnabled public String newLeadRecordType;
        @AuraEnabled public String profileName;
        @AuraEnabled public Boolean batchUser;
    }
    @AuraEnabled
    public static String addReportOPWithEvaluationPDF(String repOwnerId,String dailyReportId, 

    String eventId, String recordType, String aId, String visitor1, String visitor2, String visitor3,
    // String visitor4, String visitor5, 
    
     String opp1, String opp2, String opp3, Date reportDate, 
     // String opp4, String opp5,
    String evaluationPDFNumber, String pro1, DateTime sTime, DateTime eTime) {
        String rt = selectRecordType(recordType);
        List<Account> aList = selectAccount(aId);
        Report__c r = new Report__c();
        
        if(aList.size() != 0){
            Account a = aList.get(0);
            r.Hospital_Department__c = a.Id;
            r.Department_Class_Ref__c = a.Department_Class__r.Id;
            r.Hospital_Reference__c = a.Hospital__r.Id;
        } else {
            r.Manual_Name__c = aId;
        }
        
        if (String.isBlank(dailyReportId) == false) r.Daily_Report__c = dailyReportId;
        r.OwnerId = repOwnerId;
        r.RecordTypeId = rt;
        if (String.isBlank(eventId) == false) r.Event_Id__c = eventId;
        r.Evaluation_PDF_number__c = evaluationPDFNumber;
        if(reportDate != null){
            r.Date__c = reportDate;
        }
        if(visitor1 != null && visitor1 != ''){
            r.Practitioner1__c = visitor1;
        }
        if(visitor2 != null && visitor2 != ''){
            r.Practitioner2__c = visitor2;
        }
        if(visitor3 != null && visitor3 != ''){
            r.Practitioner3__c = visitor3;
        }
        // if(visitor4 != null && visitor4 != ''){
        //  r.Practitioner4__c = visitor4;
        // }
        // if(visitor5 != null && visitor5 != ''){
        //  r.Practitioner5__c = visitor5;
        // }

        List<String> oppIdList = new List<String>();
        if(opp1 != null && opp1 != ''){
            oppIdList.add(opp1);
        }
        if(opp2 != null && opp2 != ''){
            oppIdList.add(opp2);
        }
        if(opp3 != null && opp3 != ''){
            oppIdList.add(opp3);
        }
        // if(opp4 != null && opp4 != ''){
        //  oppIdList.add(opp4);
        // }
        // if(opp5 != null && opp5 != ''){
        //  oppIdList.add(opp5);
        // }

        if(oppIdList.size() > 0){
            if(opp1 != null && opp1 != ''){
                r.Opportunity1__c = opp1;
            }
            if(opp2 != null && opp2 != ''){
                r.Opportunity2__c = opp2;
            }
            if(opp3 != null && opp3 != ''){
                r.Opportunity3__c = opp3;
            }
            //康康p课题需要修改字段类型 后续跟进
            //   if(opp4 != null && opp4 != ''){
                //     r.Opportunity4__c = opp4;
            //   }
            //   if(opp5 != null && opp5 != ''){
                //     r.Opportunity5__c = opp5;
            //   }
            r.Opportunity_Situation__c = '引合発生';
        }
        else{
            r.Opportunity_Situation__c = '引合無';
        }
        
        if (String.isBlank(pro1) == false) {
            r.Product1__c = pro1;
        }

        if (sTime != null) {
            r.Operation_From__c =sTime;
        }
        if (eTime != null) {
            r.Operation_To__c =eTime;
        }
        upsert r;

        if (String.isBlank(eventId) == false) updateEvent(r.id,eventId,recordType);

        return r.id;
    }
    @AuraEnabled
    // public static String addReportNT(String repOwnerId,String dailyReportId, String eventId, String recordType, String aId, String visitor1, String visitor2, String visitor3, String visitor4, String visitor5, DateTime sTime, DateTime eTime){
    public static String addReportNT(String repOwnerId,String dailyReportId, String eventId, String recordType, String aId, String visitor1, String visitor2, String visitor3, DateTime sTime, DateTime eTime){
        String rt = selectRecordType(recordType);
        List<Account> aList = selectAccount(aId);

        Report__c r = new Report__c();
        if(aList.size() != 0){
            Account a = aList.get(0);
            r.Hospital_Department__c = a.Id;
            r.Department_Class_Ref__c = a.Department_Class__r.Id;
            r.Hospital_Reference__c = a.Hospital__r.Id;
        } else {
            r.Manual_Name__c = aId;
        }
        

        r.Daily_Report__c = dailyReportId;
        r.OwnerId = repOwnerId;
        r.RecordTypeId = rt;
        r.TrainingPersonnelType__c = '';
        r.Event_Id__c = eventId;
        if(visitor1 != null && visitor1 != ''){
            r.Practitioner1__c = visitor1;
        }
        if(visitor2 != null && visitor2 != ''){
            r.Practitioner2__c = visitor2;
        }
        if(visitor3 != null && visitor3 != ''){
            r.Practitioner3__c = visitor3;
        }
        // if(visitor4 != null && visitor4 != ''){
        //  r.Practitioner4__c = visitor4;
        // }
        // if(visitor5 != null && visitor5 != ''){
        //  r.Practitioner5__c = visitor5;
        // }
        if(sTime != null){
            r.From__c = sTime;
        }
        if(eTime != null){
            r.To__c = eTime;
        }
        // r.Location__c = mainPlace;
        upsert r;

        updateEvent(r.id,eventId,recordType);

        return r.id;
    }
    public static void updateEvent(String rId, String eventId, String recordType){
        Event__c e = [
            select id,Maintenance_Contract_ID__c, Asset_Manual_ID__c, Rental_Apply_ID__c,
                   Product_Description_Id__c, OPD_ID__c, NTC_ID__c, ReportAccompanied_ID__c, CityStatus_ID__c, Improvement_ID__c, Conflict_ID__c, Claim_ID__c
              from Event__c where id =:eventId
        ];
        System.debug('updateEvent:' +recordType);
        if(recordType == 'Rental_Apply'){
            e.Rental_Apply_ID__c = rId;
        }
        if(recordType == 'Asset_Manual'){
            e.Asset_Manual_ID__c = rId;
        }
        if(recordType == 'Product_Explanation'){
            e.Product_Description_Id__c = rId;
        }
        else if(recordType == 'OPD' || recordType == 'SIS'){
            e.OPD_ID__c = rId;
        }
        else if(recordType == 'NTC'){
            e.NTC_ID__c = rId;
        }
        else if(recordType == 'On_Call'){
            e.OnCall_ID__c = rId;
        }
        else if(recordType == 'Visit_With'){
            e.ReportAccompanied_ID__c = rId;
        }
        else if(recordType == 'MarketCondition'){
            e.CityStatus_ID__c = rId;
        }
        else if(recordType == 'Improvement'){
            e.Improvement_ID__c = rId;
        }
        else if(recordType == 'Competitor'){
            e.Conflict_ID__c = rId;
        }
        else if(recordType == 'Complaint'){
            e.Claim_ID__c = rId;
        }

        if(recordType == 'NewInstallTarin' ) {
            e.NewInstallTarin_FLAG__c = true;            
        } else if( recordType == 'FaultPreventionTraining' ) {
            e.FaultPreventionTraining_FLAG__c = true;
        } else if(recordType == 'OPD') {
            e.OPD_FLAG__c = true;
        } else if(recordType == 'SIS' ) {
            e.SIS_FLAG__c = true;     
        } else if( recordType == 'SIS_ET' ) {
            e.SIS_ET_FLAG__c = true;
        } else if(recordType == 'SIS_ENG') {
            e.SIS_ENG_FLAG__c = true;
            
        }
        update e;
    }
    public static String selectRecordType(String recordTypeName){
        List<RecordType> rtList = [select id from RecordType where IsActive = true and DeveloperName =:recordTypeName];
        return rtList.get(0).id;
    }
    public static List<Account> selectAccount(String aId){
        List<Account> aList = new List<Account>();
        if (aId != null && aId.startsWith('001')) {
            aList = [select Id, Department_Class__r.Id, Hospital__r.Id from Account where Id =:aId];
        }
        return aList;
    }
    //取消申请
    @AuraEnabled
    public static String cancleApply(String recordId) {
        List<Daily_Report__c> report = [Select Id from Daily_Report__c Where Id= :recordId];
        if(report.size()>0){
            report[0].Status__c = '作成中';
            try {
               update report; 
            }
            catch ( Exception e) {
                // return e.getDmlMessage(0);
                return e.getMessage();
            }
            
            
        }
        return '1';
    }
    @AuraEnabled
    public static String getContactAwsIdByCOntactId(String contactId){
        Contact con = [SELECT Id,AWS_Data_Id__c FROM Contact WHERE Id = :contactId];
        return con.AWS_Data_Id__c;
    }
    //zzm 231113 日报取消延期bug修复 start
    @AuraEnabled
    public static Event__c getEventCById(String eventcID){
        Event__c eventc = [SELECT Id,Event_ID__c FROM Event__c WHERE Id = :eventcID];
        return eventc;
    }
    //zzm 231113 日报取消延期bug修复 start
}