public without sharing class XinDailyReportController {

    // 2018/11/21 SWAG-B6Q8BS 判断是否需要弹窗更新客户信息 start

    public boolean IsAlertInputDep {get;set;}
    public string Alertlines {get;set;}
    // 2018/11/21  SWAG-B6Q8BS 判断是否需要弹窗更新客户信息 end

    /** 日報　*/
    public Daily_Report__c report {get;set;}
    public Daily_Report__c report_search {get;set;}               // 日報取得ボタン用
    /**　報告者情報　*/
    public User reportOwner {get;set;}
    /**　ログイン者情報　*/
    public User me {get;set;}
    /** 活動リスト */
    public List<Activity> activities {get;set;}
    public List<Activity> TestLink {get;set;}
    public String testStr {get;set;}
    /**　活動リスト件数　*/
    public Integer actSize{get;set;}
    /**　日報変更フラグ　*/
    public boolean allDisableFlg{get;set;}
    /**　申請取消フラグ　*/
    public boolean cancelRequestFlg{get;set;}
    /**　報告状態　*/
    public boolean reportStatusFlg{get;set;}
    /** 日报类型 */
    public boolean reportTypeFlg{get;set;} // 20210426 zh
    /**　マネージャーフラグ　*/
    public boolean managerFlg{get;set;}
    /**　報告者変更フラグ　*/
    public boolean reporterEditFlg{get;set;}
    /**　部长・总监的反馈 変更フラグ　*/
    public boolean ministerCommentEditFlg{get;set;}
    /**　经理的反馈 変更フラグ　*/
    public boolean managerCommentEditFlg{get;set;}
    /**　ステータス　*/
    public String tempStatus{get;set;}
    /**　画面ステータス(0:新規、1:編集、2:編集不可)　*/
    public String displayStatus{get;set;}
    /** 活動インデックス(報告書ボタン用) */
    public String upsertActIndex {get;set;}
    /** 活動訪問先区分(報告書ボタン用) */
    public String upsertActVD {get;set;}
    /** 活動訪問場所(報告書ボタン用) */
    public String upsertActVP {get;set;}
    /** 活動開始時間(報告書ボタン用) */
    public Datetime upsertStartTime {get;set;}
    /** 活動終了時間(報告書ボタン用) */
    public Datetime upsertEndTime {get;set;}
    /** 同行報告作成フラグ */
    public boolean accompanyingReportFlg {get;set;}
    /** 報告書作成フラグ */
    public boolean reportReportFlg {get;set;}
    /** エラーフラグ */
    public boolean error{get;set;}
    /** 新建备品借出申请权限 **/
    public boolean CreateRentalApply{get;set;}
    /**　日報所有人判断フラグ　*/
    public boolean ifReportOwner{get;set;}
    /** エラーメッセージ */
    public String errorMessage{get;set;}
    /** 完了フラグ */
    public boolean completion{get;set;}
    public List<SelectOption> noSltList{get;set;}
    public List<SelectOption> hosptalList{get;set;}
    public List<SelectOption> salesList{get;set;}
    public List<SelectOption> outEventList{get;set;}
    public List<SelectOption> inEventList{get;set;}
    public List<SelectOption> moveList{get;set;}
    public List<SelectOption> vacationList{get;set;}
    public String repoStartHourText{get;set;}
    public String repoStartMinuteText{get;set;}
    public String repoEndHourText{get;set;}
    public String repoEndMinuteText{get;set;}
    public boolean repoErrorFlg{get;set;}
    public String repoErrorMessage{get;set;}
    public String idParam{get;set;}
    public Integer activitiesSize {get;set;}
    //Add By Li Jun 20220224 for PIPL start
    public String idVisitor1PI{set;get;}
    public String idVisitor2PI{set;get;}
    public String idVisitor3PI{set;get;}
    public String idVisitor4PI{set;get;}
    public String idVisitor5PI{set;get;}
    public String staticResource {get; set;}
    //Add By Li Jun 20220224 for PIPL end
//*************************Create 20160630 OCM-231 趙徳芳 Start*************************//
    public String completionFlg{get;set;}
    public Daily_Report__c reportBak {get;set;}
    public String EsetId{get;set;}

    public String eventFlg {get;set;}
    public String eventMsg {get;set;}
//*************************Create 20160630 OCM-231 趙徳芳 End***************************//
    public String etAPPerrorMsg {get;set;}
    public String etAPPMsg1 {get;set;} // 20210603 zh ETAPP与日报联动
    public String etAPPMsg2 {get;set;} // 20210603 zh ETAPP与日报联动
    public String etAPPFlg {get;set;} // 20210603 zh ETAPP与日报联动
    //Add By Li Jun for PIPL 20220225
    public String contactAWSIds{set;get;}
    public String acSize{set;get;}
    /**　コンストラクタ　*/
    public XinDailyReportController() {
        PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo('Contact');
        staticResource = JSON.serialize(piIntegration);
        system.debug('static resource:'+JSON.serialize(staticResource));
        EsetId = ApexPages.currentPage().getParameters().get('id');
        completionFlg =  ApexPages.currentPage().getParameters().get('completion');
        eventFlg = ApexPages.currentPage().getParameters().get('event');
        eventMsg = ApexPages.currentPage().getParameters().get('eventMsg');
        // 20210603 zh ETAPP与日报联动 start
        etAPPFlg = ApexPages.currentPage().getParameters().get('etAPPFlg');
        String etAPPMsg = ApexPages.currentPage().getParameters().get('etAPPMsg');
        if(etAPPMsg != null && etAPPMsg!=''){
            etAPPMsg1 = etAPPMsg.split('。')[0];
            etAPPMsg2 = etAPPMsg.split('。')[1];
        }else{
            etAPPMsg1 = '';
            etAPPMsg2 = '';
        }
        
        // 20210603 zh ETAPP与日报联动 end
    }

    /**　コンストラクタ　*/
    public XinDailyReportController(ApexPages.StandardController controller) {
        PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo('Contact');
        staticResource = JSON.serialize(piIntegration);
        system.debug('static resource:'+JSON.serialize(staticResource));
        EsetId = ApexPages.currentPage().getParameters().get('id');
        completionFlg =  ApexPages.currentPage().getParameters().get('completion');
        eventFlg = ApexPages.currentPage().getParameters().get('event');
        eventMsg = ApexPages.currentPage().getParameters().get('eventMsg');
        // 20210603 zh ETAPP与日报联动 start
        etAPPFlg = ApexPages.currentPage().getParameters().get('etAPPFlg');
        String etAPPMsg = ApexPages.currentPage().getParameters().get('etAPPMsg');
        if(etAPPMsg != null && etAPPMsg!=''){
            etAPPMsg1 = etAPPMsg.split('。')[0];
            etAPPMsg2 = etAPPMsg.split('。')[1];
        }else{
            etAPPMsg1 = '';
            etAPPMsg2 = '';
        }
        // 20210603 zh ETAPP与日报联动 end
    }
    
    
    /** 初期処理 */
    public PageReference init(){
        
        // ログイン者情報取得
        //  SWAG-B3W5BM 2018/08/23  添加 isFormal_Stuff__c 是否在试用期 start
        me = [Select Id, Name, Post__c,isFormal_Stuff__c, Employee_No__c, Department, Job_Category__c, Category4__c, Category6__c, ManagerId, Manager.Email, Batch_User__c, ProfileId From User Where Id = :UserInfo.getUserId()];
        //  SWAG-B3W5BM 2018/08/23  添加 isFormal_Stuff__c 是否在试用期 end
        
        errorMessage = System.Label.Error_Message0;
        accompanyingReportFlg = true;
        reportReportFlg = true;
        repoErrorFlg = false;
        if(completionFlg==null||completionFlg==''){
            completion = false;
        }else{
            completion = true;
        }
        
        ministerCommentEditFlg = true;
        managerCommentEditFlg = true;
        Schema.DescribeSobjectResult s = Rental_Apply__c.sObjectType.getDescribe();
        //  SWAG-B3W5BM 2018/08/23  添加 isFormal_Stuff__c 到是否可以创建备品借出申请的验证规则 start
        if(me != null)
            CreateRentalApply = s.isCreateable() && !me.isFormal_Stuff__c;
        else
            CreateRentalApply = s.isCreateable();
        //  SWAG-B3W5BM 2018/08/23  添加 isFormal_Stuff__c 到是否可以创建备品借出申请的验证规则  end
        repoStartHourText = '';
        repoStartMinuteText = '';
        repoEndHourText = '';
        repoEndMinuteText = '';
        repoErrorMessage = '';
        
        idParam = System.currentPageReference().getParameters().get('id');
        String dtParam = System.currentPageReference().getParameters().get('dt');
        report_search = new Daily_Report__c();
        
        // dtの処理
        if (dtParam == null || dtParam == 'null') {
            dtParam = null;
        } else {
            // Lengthチェック
            if (dtParam.length() != 8) {
                dtParam = null;
            }
            // Formatチェック
            else {
                try {
                    Integer y = Integer.valueOf(dtParam.substring(0, 4));
                    Integer m = Integer.valueOf(dtParam.substring(4, 6));
                    Integer d = Integer.valueOf(dtParam.substring(6, 8));
                    report_search.Reported_Date__c = Date.newInstance(y, m, d);
                } catch (Exception e) {
                    dtParam = null;
                }
            }
        }
        
        // 新規
        if(idParam == null || idParam == 'null'){
            if (dtParam == null) {
                displayStatus = '0';
                report = new Daily_Report__c();
                report.Reporter__c = UserInfo.getUserId();
                report_search.Reporter__c = UserInfo.getUserId();
                activities = new List<Activity>();
                // 三つを表示
                for(Integer i = 0; i < 3; i++){
                    Event__c e = new Event__c();
                    Activity active_activityNew = new Activity();
                    active_activityNew.act = e;
                    activities.add(active_activityNew);
                }
            }
            // dateがあれば、その日の日報を取得
            else {
                report = new Daily_Report__c();
                report.Reporter__c = UserInfo.getUserId();
                report_search.Reporter__c = UserInfo.getUserId();
                PageReference pr = getDailyReport();
                return pr;
            }
        }
        // 編集
        else{
            report_search.Reported_Date__c = date.today();
            displayStatus = '2';
            List<Daily_Report__c> reportList = new List<Daily_Report__c>();
            // 20210426 zh WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 start
            // if (idParam.startsWith('00U')) {
            //     // 活動Idの場合
            //     List<Event> eParamList = ControllerUtil.eventSelectById(idParam);
            //     // ホームの活動から遷移した場合
            //     if(eParamList.size() == 0){
            //         displayStatus = '1';
            //         report = new Daily_Report__c();
            //         Event__c e = new Event__c();
            //         activities = new List<Activity>();
            //         Activity active_activity = new Activity();
            //         active_activity.act = e;
            //         activities.add(active_activity);
            //         errorMessage = System.Label.Error_Message10;
            //         error = true;
            //         reporterEditFlg = true;
            //         return null;
            //     }
            //     Event eParam = eParamList.get(0);
            //     // 活動の日付と所有者から日報を取得
            //     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,
            //                                 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
            //                                 from Daily_Report__c where Reported_Date__c =: eParam.ActivityDate and OwnerId =: eParam.OwnerId];
            //     if(reportList.size() == 0){
            //         // savepoint
            //         // insert成功しても権限により取得できない場合、insertそのものをrollbackする
            //         Savepoint sp = Database.setSavepoint();
                    
            //         Date d = eParam.ActivityDate;
            //         report_search.Reported_Date__c = eParam.ActivityDate;
            //         report = new Daily_Report__c();
            //         report.Reporter__c = eParam.OwnerId;
            //         report.OwnerId = eParam.OwnerId;
            //         report.Status__c = '作成中';
            //         report.Daily_Report_Data_Type__c = '通常';
            //         report.Reported_Date__c = d;
            //         report.Working_Time_From__c = Datetime.newInstance(d.year(), d.month(), d.day(), 8, 45, 0);
            //         report.Working_Time_To__c = Datetime.newInstance(d.year(), d.month(), d.day(), 17, 30, 0);
            //         try {
            //             insert report;
            //         } catch (Exception ex) {
            //             displayStatus = '1';
            //             report = new Daily_Report__c();
            //             Event__c e = new Event__c();
            //             activities = new List<Activity>();
            //             Activity active_activity = new Activity();
            //             active_activity.act = e;
            //             activities.add(active_activity);
            //             errorMessage = System.Label.Error_Message10;
            //             error = true;
            //             reporterEditFlg = true;
                        
            //             Database.rollback(sp);
            //             return null;
            //         }
            //         reportList = reportSelectById(report.id);
                    
            //         if(reportList.size() == 0){
            //             // 参照権限がありません。
            //             displayStatus = '1';
            //             report = new Daily_Report__c();
            //             Event__c e = new Event__c();
            //             activities = new List<Activity>();
            //             Activity active_activity = new Activity();
            //             active_activity.act = e;
            //             activities.add(active_activity);
            //             errorMessage = System.Label.Error_Message10;
            //             error = true;
            //             reporterEditFlg = true;
                        
            //             Database.rollback(sp);
            //             return null;
            //         }
            //     }
            // }else 
            // 20210426 zh WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 end
            if (idParam.startsWith('a0A')) {
                // 日報一覧から遷移した場合
                //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, Approved_DateTime__c, CreatedById, Feed_Back_From_Manager__c, FeedbackManager__c, Planning_Time__c, Submission_Elapsed_Hour__c, Approval_Elapsed_Time__c, Activity_ID__c, Manager_Mail__c from Daily_Report__c where id =:idParam];
                reportList = reportSelectById(idParam);
                if(reportList.size() == 0){
                    // 参照権限がありません。
                    displayStatus = '1';
                    report = new Daily_Report__c();
                    Event__c e = new Event__c();
                    activities = new List<Activity>();
                    Activity active_activity = new Activity();
                    active_activity.act = e;
                    activities.add(active_activity);
                    errorMessage = System.Label.Error_Message10;
                    error = true;
                    reporterEditFlg = true;
                    return null;
                }
            }
            else{
                // Event__CのIdからの場合
                List<Event__c> eParamList = [select id, Daily_Report__c from Event__c where id = :idParam];
                if(eParamList.size() == 0){
                    // 参照権限がありません。
                    displayStatus = '1';
                    report = new Daily_Report__c();
                    Event__c e = new Event__c();
                    activities = new List<Activity>();
                    Activity active_activity = new Activity();
                    active_activity.act = e;
                    activities.add(active_activity);
                    errorMessage = System.Label.Error_Message10;
                    error = true;
                    reporterEditFlg = true;
                    return null;
                }
                Event__c eParam = eParamList.get(0);
                //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, Approved_DateTime__c, CreatedById, Feed_Back_From_Manager__c, FeedbackManager__c, Planning_Time__c, Submission_Elapsed_Hour__c, Approval_Elapsed_Time__c, Activity_ID__c, Manager_Mail__c from Daily_Report__c where id =:eParam.Daily_Report__c];
                reportList = reportSelectById(eParam.Daily_Report__c);
                if(reportList.size() == 0){
                    // 参照権限がありません。
                    displayStatus = '1';
                    report = new Daily_Report__c();
                    Event__c e = new Event__c();
                    activities = new List<Activity>();
                    Activity active_activity = new Activity();
                    active_activity.act = e;
                    activities.add(active_activity);
                    errorMessage = System.Label.Error_Message10;
                    error = true;
                    reporterEditFlg = true;
                    return null;
                }
            }
            report = reportList.get(0);
            report_search.Reported_Date__c = report.Reported_Date__c;
            report_search.Reporter__c = report.Reporter__c;

            if(report.Working_Time_From__c != null){
                Datetime repoStartDatetime = report.Working_Time_From__c;
                repoStartHourText = String.valueOf(repoStartDatetime.hour());
                repoStartMinuteText = zeroFill(String.valueOf(repoStartDatetime.minute()));
            }
            if(report.Working_Time_To__c != null){        
                Datetime reportEndDatetime = report.Working_Time_To__c;
                repoEndHourText = String.valueOf(reportEndDatetime.hour());
                repoEndMinuteText = zeroFill(String.valueOf(reportEndDatetime.minute()));
            }
            
            report.Mail_Send_Check__c = false;

            // 報告者情報を取得
            reportOwner = [ Select  Name, 
                                    State_Hospital__c, 
                                    Employee_No__c,
                                    Department, 
                                    Job_Category__c, 
                                    Category4__c, 
                                    Category6__c, 
                                    ManagerId, 
                                    Manager.Email, 
                                    BuchangApprovalManager__c,
                                    BuchangApprovalManagerSales__c,
                                    ProfileId 
                            From 
                                User 
                            Where 
                                Id = :report.Reporter__c];
            // 日報編集フラグを設定
            if(report.Status__c == '承認' || (report.Status__c == '申請中' && UserInfo.getUserId() != reportOwner.ManagerId)){
                allDisableFlg = true;
                reportTypeFlg = true;
            }
            // 20210426 zh WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 start
            else if (report.Reported_Date__c > Date.today() && !'一日休假'.equals(report.Daily_Report_Data_Type__c) && !'全天培训'.equals(report.Daily_Report_Data_Type__c) ) {
                allDisableFlg = true;
                reportTypeFlg = false;
            }
            // 20210426 zh WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 end
            else{
                allDisableFlg = false;
            }
            
            if (report.Status__c == '作成中' || report.Status__c == '非承認' || UserInfo.getUserId() == reportOwner.Id) {
                reportStatusFlg = true;
            } else {
                reportStatusFlg = false;
            }
            
            // 申請取消フラグを設定
            if (me.Id == report.Reporter__c) {
                ifReportOwner = true;
            } else {
                ifReportOwner = false;
            }
            if (ifReportOwner) {
                if(report.Status__c == '申請中') {
                    cancelRequestFlg = true;
                }
                else{
                    cancelRequestFlg = false;
                }
            }            
            // マネージャーフラグを設定
            if(UserInfo.getUserId() == reportOwner.ManagerId){
                managerFlg = false;
            }
            else{
                managerFlg = true;
            }
            
            // カスタム設定から同行報告書作成に設定されているプロファイルを取得
            List<accompanying_report__c> arList = accompanying_report__c.getall().values();
            for(accompanying_report__c ar : arList){
                // 同行報告作成権限を設定
                if(reportOwner.ProfileId == ar.Profile_ID_1__c){
                    accompanyingReportFlg = false;
                }
            }
            
            // カスタム設定から報告書作成に設定されているプロファイルを取得
            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;
                }
            }
            // 活動を取得
            getEvent();
        }
        tempStatus = report.Status__c;
        
        // 支援の場合は報告者を変更可能
        if(me.Job_Category__c == '支援' && report.Status__c != '承認'){
            reporterEditFlg = false;
        }
        else{
            reporterEditFlg = true;
        }
        
        // 部长・总监的反馈を変更可能
        if (me.Id != report.Reporter__c /*&& report.Status__c != '承認' && report.Status__c != '作成中'*/ && (me.Post__c == '部长' || me.Post__c == '副部长' || me.Post__c == '总监' || me.Post__c == '副总监')) {
            ministerCommentEditFlg = false;
        }
        // 经理的反馈を変更可能
        if (me.Id != report.Reporter__c && report.Status__c != '承認' && report.Status__c != '作成中' && (me.Post__c == '经理' || me.Post__c == '副经理')) {
            managerCommentEditFlg = false;
        }
        reportBak = report;
        //Add By Li Jun for PIPL 20220225 Start 

        List<String> conAWSIds = new List<String>();
        Set<String> contactIdsForReport = new Set<String>();
        for(Activity a:activities){
            if(String.isNotEmpty(a.act.Visitor1_ID__c)&&String.isNotBlank(a.act.Visitor1_ID__c)){
                contactIdsForReport.add(a.act.Visitor1_ID__c);
            }
            if(String.isNotEmpty(a.act.Visitor2_ID__c)&&String.isNotBlank(a.act.Visitor2_ID__c)){
                contactIdsForReport.add(a.act.Visitor2_ID__c);
            }
            if(String.isNotEmpty(a.act.Visitor3_ID__c)&&String.isNotBlank(a.act.Visitor3_ID__c)){
                contactIdsForReport.add(a.act.Visitor3_ID__c);
            }
            if(String.isNotEmpty(a.act.Visitor4_ID__c)&&String.isNotBlank(a.act.Visitor4_ID__c)){
                contactIdsForReport.add(a.act.Visitor4_ID__c);
            }
            if(String.isNotEmpty(a.act.Visitor5_ID__c)&&String.isNotBlank(a.act.Visitor5_ID__c)){
                contactIdsForReport.add(a.act.Visitor5_ID__c);
            }
            system.debug('Activity:'+JSON.serialize(a.act.Visitor1_ID__c));
        }
        List<Contact> conListForReport = new List<Contact>([select id,AWS_Data_Id__c from Contact where id in:contactIdsForReport and AWS_Data_Id__c!='']);
        for(Contact con:conListForReport){
            conAWSIds.add(con.AWS_Data_Id__c);
        }
        contactAWSIds = JSON.serialize(conAWSIds);
        system.debug('Contact AWSIDs:'+contactAWSIds);
        //Add By Li Jun for PIPL 20220225 End
        return null;
    }
    
    /** 日報取得 url redirect */
    public PageReference getDailyReport(){
                displayStatus = '2';
                error = false;
                errorMessage = System.Label.Error_Message0;
                repoErrorFlg = false;
                completion = false;
                
                List<Daily_Report__c> reportList = new List<Daily_Report__c>();
                Date d = report_search.Reported_Date__c;
                String r = report_search.Reporter__c;
                if(d != null && r != null && r != ''){
            // 報告者、日付から日報を取得
            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,
                                        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 =: d and OwnerId =: r];
            
            // 日報がある場合
            if(reportList.size() > 0){
                report = reportList.get(0);
                
                Datetime repoStartDatetime = report.Working_Time_From__c;
                if(repoStartDatetime != null){
                    repoStartHourText = String.valueOf(repoStartDatetime.hour());
                    repoStartMinuteText = zeroFill(String.valueOf(repoStartDatetime.minute()));
                }
                
                Datetime reportEndDatetime = report.Working_Time_To__c;
                if(reportEndDatetime != null){
                    repoEndHourText = String.valueOf(reportEndDatetime.hour());
                    repoEndMinuteText = zeroFill(String.valueOf(reportEndDatetime.minute()));
                }
            }
            // 日報がない場合
            else{
                // savepoint
                // insert成功しても権限により取得できない場合、insertそのものをrollbackする
                Savepoint sp = Database.setSavepoint();
                
                report = new Daily_Report__c();
                report.Reporter__c = r;
                report.Status__c = '作成中';
                report.Daily_Report_Data_Type__c = '通常';
                report.Reported_Date__c = d;
                report.Working_Time_From__c = Datetime.newInstance(d.year(), d.month(), d.day(), 8, 45, 0);
                report.Working_Time_To__c = Datetime.newInstance(d.year(), d.month(), d.day(), 17, 30, 0);
                report.OwnerId = r;
                try {
                    insert report;
                } catch (Exception ex) {
                    displayStatus = '1';
                    report = new Daily_Report__c();
                    Event__c e = new Event__c();
                    activities = new List<Activity>();
                    Activity active_activity = new Activity();
                    active_activity.act = e;
                    activities.add(active_activity);
                    errorMessage = System.Label.Error_Message10;
                    error = true;
                    reporterEditFlg = true;
                    
                    Database.rollback(sp);
                    return null;
                }

                reportList = reportSelectById(report.id);
                if(reportList.size() == 0){
                    // 参照権限がありません。
                    displayStatus = '1';
                    report = new Daily_Report__c();
                    Event__c e = new Event__c();
                    activities = new List<Activity>();
                    Activity active_activity = new Activity();
                    active_activity.act = e;
                    activities.add(active_activity);
                    errorMessage = System.Label.Error_Message10;
                    error = true;
                    reporterEditFlg = true;
                    
                    Database.rollback(sp);
                    return null;
                }
                report = reportList.get(0);
                
                repoStartHourText = '8';
                repoStartMinuteText = '45';
                repoEndHourText = '17';
                repoEndMinuteText = '30';
            }

            PageReference pr = new PageReference('/apex/XinDailyReport?id=' + report.id);
            pr.setRedirect(true);
        
            return pr;
        } else {
            if(d != null){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请设定日期'));
            } else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, '请设定报告人'));
            }
        }
        return null;
    }
    
    /** 申請取消 */
    public PageReference cancelRequest(){
        displayStatus = '2';
        error = false;
        errorMessage = System.Label.Error_Message0;
        repoErrorFlg = false;
        completion = false;
        
        // 日報のステータスを「作成中」に戻す
        report.Status__c = '作成中';
        ControllerUtil.updDailyReport(report);

        PageReference pr = new PageReference('/apex/XinDailyReport?id=' + System.currentPageReference().getParameters().get('id'));
        pr.setRedirect(true);
        
        return pr;
    }
    
    /** 活動取得
     * 前提 Daily_Report__c はすでに検索済み(insert済み)
     * getDailyReport から 呼び出す、init から呼び出す
     */
    private void getEvent(){

        activities = new List<Activity>();
        Activity active_activity = new Activity();
        Date d = report.Reported_Date__c;
        
        List<Event__c> ecNewList = new List<Event__c>();
        // 作成中の場合のみ、Event→EventCへ作成
        if (report.Status__c == '作成中') {
            List<Event> calenderList = ControllerUtil.eventSelectByDate(d, reportOwner);
            // 任务和日报管理 update by vivek start
            // 移除被取消的事件
            List<String> delEventId = new List<String>();
            // 任务和日报管理 update by vivek end
            // 次回の活動予定を取得
            List<String> nextEcIds = new List<String>();
            for (Event e : calenderList) {
                if (e.NextEventC_ID__c != null) nextEcIds.add(e.NextEventC_ID__c);
                // 任务和日报管理 update by vivek start
                if (e.EventC_ID__c != null){
                    delEventId.add(e.EventC_ID__c);
                }
                // 任务和日报管理 update by vivek end
            }
            // 任务和日报管理 update by vivek start
            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;
                        }
                    }
                }
            }
            // 任务和日报管理 update by vivek end
            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) {
                // ①シンプルからEventを新規⇒EventC_ID__cなし⇒Event__c新規
                // ②日報一覧Event__cにより新規⇒EventC_ID__cあり⇒パス
                // ③日報一覧nextEventにより新規⇒EventC_ID__cなし、NextEventC_ID__cあり⇒Event__c新規
                if (!String.isBlank(e.EventC_ID__c)) {
                    // 
                } else {
                    // Locationあり、whatidなしの場合、free input設定（標準のカレンダー追加からそのようなデータが有りそうです。）
                    String location = null;
                    String whatid = null;
                    String visitorPlaceFree = null;
                    Boolean freeInput = false;
                    if (!String.isBlank(e.Location) && String.isBlank(e.whatid__c)) {
                        freeInput = true;
                        visitorPlaceFree = e.Location;
                    } else {
                        location = e.Location;
                        whatid = e.whatid__c;
                    }
                    //20210527 zh 任务框架修改 start
                    String eventCStatus= '';
                    if ('05 延期'.equals(e.EventStatus__c)) {
                        eventCStatus = '延期';
                    }else if ('04 取消'.equals(e.EventStatus__c)) {
                        eventCStatus = '取消';
                    }
                    //20210527 zh 任务框架修改 end
                    Event__c ec = new Event__c(
                        Subject__c = e.Subject,
                        StartDateTime__c = e.StartDateTime,
                        DurationInMinutes__c = e.DurationInMinutes,
                        EndDateTime__c = e.StartDateTime.addMinutes(e.DurationInMinutes),
                        ActivityDate__c = d,
                        BeforeActivityDate__c = e.BeforeActivityDate__c,
                        ActivityDateTime__c = e.StartDateTime,
                        Main_Visit_Location__c = e.Main_Visit_Location__c,
                        Activity_Type2__c = e.Activity_Type2__c,
                        Purpose_Type__c = e.Purpose_Type__c,
                        Related_Opportunity1__c = e.Related_Opportunity1__c,
                        OPDPlan_Flag__c = e.OPDPlan_Flag__c,
                        Opd_Plan__c = e.Opd_Plan__c,  //2022-4-14 yjk 增加opd计划
                        Related_Opportunity1_ID__c = e.Related_Opportunity1_ID__c,
                        Related_Opportunity2__c = e.Related_Opportunity2__c,
                        Related_Opportunity2_ID__c = e.Related_Opportunity2_ID__c,
                        Related_Opportunity3__c = e.Related_Opportunity3__c,
                        Related_Opportunity3_ID__c = e.Related_Opportunity3_ID__c,
                        Related_Opportunity4__c = e.Related_Opportunity4__c,
                        Related_Opportunity4_ID__c = e.Related_Opportunity4_ID__c,
                        Related_Opportunity5__c = e.Related_Opportunity5__c,
                        Related_Opportunity5_ID__c = e.Related_Opportunity5_ID__c,
                        Related_Service1__c = e.Related_Service1__c,
                        Related_Service1_ID__c = e.Related_Service1_ID__c,
                        Visitor1__c = e.Visitor1__c,
                        Visitor2__c = e.Visitor2__c,
                        Visitor3__c = e.Visitor3__c,
                        Visitor4__c = e.Visitor4__c,
                        Visitor5__c = e.Visitor5__c,
                        Visitor1_ID__c = e.Visitor1_ID__c,
                        Visitor2_ID__c = e.Visitor2_ID__c,
                        Visitor3_ID__c = e.Visitor3_ID__c,
                        Visitor4_ID__c = e.Visitor4_ID__c,
                        Visitor5_ID__c = e.Visitor5_ID__c,
                        Visitor_Place_Free__c = visitorPlaceFree,
                        /*Free_Input__c = freeInput,*/
                        Location__c = location,
                        whatid__c = whatid,
                        Daily_Report__c = report.Id,
                        Event_ID__c = e.Id,
                        IsScheduled__c = e.IsScheduled__c,
                        AppCdId__c = e.AppCdId__c,
                        SyncCreatedDate__c = e.SyncCreatedDate__c,
                        Activity_Purpose__c = e.Activity_Purpose__c,
                        Activity_PurposeFSE__c = e.Activity_PurposeFSE__c,
                        Activity_PurposeEscFSE__c = e.Activity_PurposeEscFSE__c,
                        Purpose_TypeFSE__c = e.Purpose_TypeFSE__c,
                        Purpose_TypeEscFSE__c = e.Purpose_TypeEscFSE__c,
                        //20210527 zh 任务框架修改 start
                        eventStatus__c = eventCStatus,
                        delayReason__c = e.delayReason__c,
                        delayReasonOther__c = e.delayReasonOther__c,
                        delayReasonSelect__c = e.delayReasonSelect__c,
                        delayReasonSelectFSE__c = e.delayReasonSelectFSE__c,
                        CancelReason__c = e.cancelReason__c,
                        cancelReasonSelectFSE__c = e.cancelReasonSelectFSE__c,
                        cancelReasonSelect__c = e.cancelReasonSelect__c,
                        cancelReasonOther__c = e.cancelReasonOther__c,
                        delayToDate__c = e.delayToDate__c
                        //20210527 zh 任务框架修改 end
                    );
                    if (e.IsScheduled__c) {
                        ec.IsScheduled_StartDateTime__c = ec.StartDateTime__c;
                        ec.IsScheduled_EndDateTime__c = ec.EndDateTime__c;
                        ec.IsScheduled_Location__c = e.Location;
                        ec.IsScheduled_Subject__c = ec.Subject__c;
                    }
                    if (e.whatid__c != null && e.whatid__c.startsWith('001')) {
                        // 訪問場所はAccountの場合
                        ec.Account_ID__c = e.whatid__c;
                        ec.Campaign_ID__c = null;
                    }
                    else if (e.whatid__c != null && e.whatid__c.startsWith('701')) {
                        // 訪問場所はCampaignの場合
                        ec.Account_ID__c = null;
                        ec.Campaign_ID__c = e.whatid__c;
                    }
                    else {
                        ec.Account_ID__c = null;
                        ec.Campaign_ID__c = null;
                    }
                    
                    if (e.NextEventC_ID__c != null && nextEcMap.containsKey(e.NextEventC_ID__c)) {
                        Event__c nextEc = nextEcMap.get(e.NextEventC_ID__c);
                        ec.Visitor1__c = nextEc.Visitor1__c;
                        ec.Visitor2__c = nextEc.Visitor2__c;
                        ec.Visitor3__c = nextEc.Visitor3__c;
                        ec.Visitor4__c = nextEc.Visitor4__c;
                        ec.Visitor5__c = nextEc.Visitor5__c;
                        ec.Visitor1_ID__c = nextEc.Visitor1_ID__c;
                        ec.Visitor2_ID__c = nextEc.Visitor2_ID__c;
                        ec.Visitor3_ID__c = nextEc.Visitor3_ID__c;
                        ec.Visitor4_ID__c = nextEc.Visitor4_ID__c;
                        ec.Visitor5_ID__c = nextEc.Visitor5_ID__c;
                        ec.Purpose_Type2__c = nextEc.Purpose_Type2__c;
                        ec.Purpose_Type3__c = nextEc.Purpose_Type3__c;
                        ec.Purpose_Type4__c = nextEc.Purpose_Type4__c;
                        ec.Purpose_Type5__c = nextEc.Purpose_Type5__c;
                        ec.Related_Opportunity2__c = nextEc.Related_Opportunity2__c;
                        ec.Related_Opportunity3__c = nextEc.Related_Opportunity3__c;
                        ec.Related_Opportunity4__c = nextEc.Related_Opportunity4__c;
                        ec.Related_Opportunity5__c = nextEc.Related_Opportunity5__c;
                        ec.Related_Opportunity2_ID__c = nextEc.Related_Opportunity2_ID__c;
                        ec.Related_Opportunity3_ID__c = nextEc.Related_Opportunity3_ID__c;
                        ec.Related_Opportunity4_ID__c = nextEc.Related_Opportunity4_ID__c;
                        ec.Related_Opportunity5_ID__c = nextEc.Related_Opportunity5_ID__c;
                        ec.Related_Service2__c = nextEc.Related_Service2__c;
                        ec.Related_Service2_ID__c = nextEc.Related_Service2_ID__c;
                        ec.Purpose__c = ec.Subject__c;
                        // 表示データ補足
                        //                        ec.Hospital_Info__c = nextEc.Hospital_Info__c;
                        //                        ec.Doctor_Info__c = nextEc.Doctor_Info__c;
                        //                        ec.Technology_Treatment__c = nextEc.Technology_Treatment__c;
                        //                        ec.New_Query__c = nextEc.New_Query__c;
                        //                        ec.Update_Query__c = nextEc.Update_Query__c;
                        //                        ec.Lost_Info__c = nextEc.Lost_Info__c;
                        //                        ec.VOC__c = nextEc.VOC__c;
                        //                        ec.Meeting_Info__c = nextEc.Meeting_Info__c;
                        //                        ec.Description__c = nextEc.Description__c;
                        //                        ec.Companion__c = nextEc.Companion__c;
                    }
                    
                    ecNewList.add(ec);
                }
            }
            // 画面上は表示だけ、なので、ここはinsertしない
            //if (ecNewList.size() > 0) ControllerUtil.insEventC(ecNewList);
        }
        
        // 既存のEventC取得
        List<Event__c> eList = ControllerUtil.getEventCList(d, report);
        // 任务和日报管理 2020-05-28 update by vivek start
        // Set<String> eventidSet = new Set<String>();
        // Set<String> taskidSet = new Set<String>();
        // Map<String,String> eventcEventMap = new Map<String,String>();
        // Map<String,task__c> eventTaskMap = new Map<String,task__c>();
        // for(Event__c e :eList ){
        //     if(!String.isBlank(e.Event_ID__c)){
        //         eventidSet.add(e.Event_ID__c);
        //     }
        // }
        // List<Event> eventTaskList = ControllerUtil.getEventsList(eventidSet);
        // for(Event e : eventTaskList){
        //     if(!String.isBlank(e.task_id__c)){
        //         taskidSet.add(e.task_id__c);
        //         eventcEventMap.put(e.task_id__c, e.EventC_ID__c);
        //     }
        // }
        // List<task__c> taskDiffList = [select id,taskDifferent__c,delayTaskDelay__c from task__c where id = :taskidSet];
        // for(task__c t :taskDiffList){
        //     for(String s :eventcEventMap.keySet()){
        //         if(t.id == s){
        //             eventTaskMap.put(eventcEventMap.get(s), t);
        //         }
        //     }
        // }
        // 任务和日报管理 2020-05-28 update by vivek end
        // Eventから変換したEventCを追加
        eList.addAll(ecNewList);

        // 任务和日报管理 2020-05-28 update by vivek start
        // 做一个事件和任务对应的map，用来为页面上每条日报明细对应任务的任务区分赋值，来控制延期日期的判断。
        Set<String> eventidSet = new Set<String>();
        Set<String> taskidSet = new Set<String>();
        Map<String,String> eventcEventMap = new Map<String,String>();
        Map<String,task__c> eventTaskMap = new Map<String,task__c>();
        Map<String,Event> NewEventMap = new Map<String,Event>(); //2021-09-18  mzy  任务管理改善  
        Map<String,Event> NewEventStatusMap = new Map<String,Event>(); //2021-09-18  mzy  任务管理改善  
        for(Event__c e :eList ){
            if(!String.isBlank(e.Event_ID__c)){
                eventidSet.add(e.Event_ID__c);
            }
        }
        List<Event> eventTaskList = ControllerUtil.getEventsList(eventidSet);
        List<Event> eventStatusList = [SELECT id,EventC_ID__c,EventStatus__c FROM event WHERE Id = :eventidSet];
        for(Event e : eventTaskList){
            if(!String.isBlank(e.task_id__c)){
                taskidSet.add(e.task_id__c);
                // eventcEventMap.put(e.task_id__c, e.EventC_ID__c);
                eventcEventMap.put(e.task_id__c, e.Id);
            }
            NewEventMap.put(e.EventC_ID__c,e);   //2021-09-18  mzy  任务管理改善 
        }
        if(eventStatusList.size()>0){
            for(Event e : eventStatusList){
                NewEventStatusMap.put(e.EventC_ID__c,e);
            }
        }
        List<task__c> taskDiffList = [select id,taskDifferent__c,CreateDate__c,
        //2021-09-18 mzy  任务管理改善开发 start
        cancelReasonSelect__c,cancelReasonSelectFSE__c,
        delayReasonSelect__c,delayReasonSelectFSE__c,
        taskStatus__c,
        //2021-09-18 mzy  任务管理改善开发 end
        FeedbackDescription__c,
        delayTaskDelay__c,Initial_Task__c,Initial_Task__r.CreateDate__c,Finish_Date__c from task__c where id = :taskidSet];
        for(task__c t :taskDiffList){
            for(String s :eventcEventMap.keySet()){
                if(t.id == s){
                    eventTaskMap.put(eventcEventMap.get(s), t);
                }
            }
        }
        // 任务和日报管理 2020-05-28 update by vivek end
        
        List<Event__c> finalEList = new List<Event__c>();          // TODO finalEListは何のために？
        if (eList.size() == 0) {
            Event__c e = new Event__c();
            e.ActivityDateTime__c = Datetime.newInstance(d.year(), d.month(), d.day(), 8, 45, 0);              // TODO katsu 定数
            finalEList.add(e);
        // sort
        } else {
            finalEList = sortEventC(eList);
        }
        List<String> AccountIdList = new List<String>(); 
        List<String> CampaignIdList = new List<String>();
        for(Event__c evc: eList){
            if(!String.isBlank(evc.whatid__c)){
                if(evc.whatid__c.startsWith('001')){
                    //Account
                    AccountIdList.add(evc.whatid__c);
                }else if(evc.whatid__c.startsWith('701')){
                    //Campaign
                    CampaignIdList.add(evc.whatid__c);
                }
            }
        }

        Map<String,String> NameMap = new Map<String,String>();

        List<Account> accountList = ControllerUtil.ShowAccount(AccountIdList);
        List<Campaign> campaignList = ControllerUtil.ShowCampaign(CampaignIdList);
        for(Account acc : accountList){
            if(!NameMap.containsKey(acc.Id)){
               NameMap.put(acc.Id, acc.Name); 
            }
        }

        for (Campaign camp : campaignList) {
            if(!NameMap.containsKey(camp.Id)){
               NameMap.put(camp.Id, camp.Name); 
            }
        }
        Map<String, Map<String, String>> accMap = new Map<String, Map<String, String>>();
        Datetime actPlanStartDatetime = null;
        Datetime actPlanEndDatetime = null;
        String[] nextTimePurpose = null;

        for(Integer i = 0; i < eList.size(); i++){
            active_activity = new Activity();
            active_activity.act = eList.get(i);
            if(NewEventStatusMap != null && eList.get(i)!= null && NewEventStatusMap.get(eList.get(i).Id) != null){ //2021-12-28 yjk 增加非空判断
                active_activity.EventStatus = NewEventStatusMap.get(eList.get(i).Id).EventStatus__c;  //2021-09-18  mzy  任务管理改善 
            }
            active_activity.oldLocation = eList.get(i).Location__c;
            active_activity.oldLocationId = eList.get(i).whatid__c;
            active_activity.act.Daily_Report__c = report.Id;
            active_activity.index = i;
            active_activity.isDisabledVisitorPlace = false;
            // 20200420 任务日报管理 add gzw start
            if(eventTaskMap.containsKey(active_activity.act.Event_ID__c)){
                // 取得日报明细对应的任务区分。用来控制延期日期。
                active_activity.taskDifferent = eventTaskMap.get(active_activity.act.Event_ID__c).taskDifferent__c;
                active_activity.delayTaskDelay = eventTaskMap.get(active_activity.act.Event_ID__c).delayTaskDelay__c;
                //2021-09-18 mzy  任务管理改善开发 start
                active_activity.tsk = eventTaskMap.get(active_activity.act.Event_ID__c)==null?new task__c():eventTaskMap.get(active_activity.act.Event_ID__c);
                if(active_activity.tsk.Id!=null){
                    active_activity.isTaskBlank = false;
                }
                //2021-09-18 mzy  任务管理改善开发  end
                //20210722 zh 任务的未执行判断时间修改 start 
                // if (eventTaskMap.get(active_activity.act.Event_ID__c).Initial_Task__c != null) {
                //     active_activity.latestDate = eventTaskMap.get(active_activity.act.Event_ID__c).Initial_Task__r.CreateDate__c;
                // }else{
                //     active_activity.latestDate = eventTaskMap.get(active_activity.act.Event_ID__c).CreateDate__c;
                // }
                active_activity.latestDate = eventTaskMap.get(active_activity.act.Event_ID__c).Finish_Date__c;
                //20210722 zh 任务的未执行判断时间修改 end
                
            }
            active_activity.stringIndex  = ''+active_activity.index;
            active_activity.cancelReason =  active_activity.act.cancelReason__c;
            // zh延期理由，取消理由
            active_activity.delayReason  =  active_activity.act.delayReasonOther__c;
            // zh延期理由，取消理由
            active_activity.delayToDate  =  active_activity.act.delayToDate__c;
            // 20200420 任务日报管理 add gzw end
            active_activity.reportOwner = reportOwner;
            
            if(active_activity.act.StartDateTime__c != null){
                actPlanStartDatetime = active_activity.act.StartDateTime__c;
                active_activity.actStartHourText = String.valueOf(actPlanStartDatetime.hour());
                active_activity.actStartMinuteText = zeroFill(String.valueOf(actPlanStartDatetime.minute()));
            }
            
            if(active_activity.act.EndDateTime__c != null){
                actPlanEndDatetime = active_activity.act.EndDateTime__c;
                if (actPlanEndDatetime.day() != actPlanStartDatetime.day()) {
                    active_activity.actEndHourText = String.valueOf(actPlanEndDatetime.hour() + 24);
                } else {
                    active_activity.actEndHourText = String.valueOf(actPlanEndDatetime.hour());
                }
                active_activity.actEndMinuteText = zeroFill(String.valueOf(actPlanEndDatetime.minute()));
            }
            
            if(active_activity.act.nextPlanTimePurpose__c != null && active_activity.act.nextPlanTimePurpose__c != ''){
                nextTimePurpose = active_activity.act.nextPlanTimePurpose__c.split(',');
                if(nextTimePurpose.size() >= 5){
                    active_activity.planStartHourText = nextTimePurpose[0];
                    active_activity.planStartMinuteText = zeroFill(nextTimePurpose[1]);
                    active_activity.planEndHourText = nextTimePurpose[2];
                    active_activity.planEndMinuteText = zeroFill(nextTimePurpose[3]);
                    active_activity.planPurposeText = '';
                    for (Integer nextColumn = 4; nextColumn < nextTimePurpose.size() - 1; nextColumn++) {
                        active_activity.planPurposeText += nextTimePurpose[nextColumn] + ',';
                    }
                    active_activity.planPurposeText += nextTimePurpose[nextTimePurpose.size() - 1];
                }
            }
            
            if(active_activity.act.Subject__c != null && active_activity.act.Subject__c != ''){
                active_activity.act.Purpose__c = active_activity.act.Subject__c;
            }
            
            if(active_activity.act.whatid__c != null && active_activity.act.whatid__c != ''){
                active_activity.act.Location__c = NameMap.get(active_activity.act.whatid__c);
            }
            activities.add(active_activity);
        }

        for(Integer i = activities.size(); i < 3; i++){
            Event__c eNew = new Event__c();
            Activity active_activityNew = new Activity();
            active_activityNew.act = eNew;
            active_activityNew.act.Daily_Report__c = report.Id;
            active_activityNew.index = i;
            // 20200420 任务日报管理 add gzw start
            active_activityNew.stringIndex = ''+active_activityNew.index;
            // 20200420 任务日报管理 add gzw end
            active_activityNew.reportOwner = reportOwner;
            activities.add(active_activityNew);
        }

        actSize = activities.size();
    }

    /**　保存　*/
    public PageReference save() {
        if(UserInfo.getProfileId() == System.Label.ProfileId_2S1)
            CheckAlertInputDep();
        repoErrorMessage = '';

        Boolean eventFlg = error = repoErrorFlg = completion =false;
        String eventMessage = System.Label.Error_Message0;
        // TODO katsu なぜ ここ再検索？
        try {
            List<Daily_Report__c> reportTest = [select id from Daily_Report__c where OwnerId =:report.Reporter__c and Reported_Date__c =:report.Reported_Date__c];
           
            report = new Daily_Report__c(
                id=reportTest.get(0).id,
                Reporter__c=report.Reporter__c,
                Reported_Date__c=report.Reported_Date__c,
                /*************************Insert 20160531 趙徳芳 Start*************************/
                Closest_Work_Day__c = Date.today(),
                /*************************Insert 20160531 趙徳芳 End***************************/
                Daily_Report_Data_Type__c=report.Daily_Report_Data_Type__c,
                Status__c=report.Status__c,
                Mail_Send_Check__c=report.Mail_Send_Check__c,
                Business_Trip__c=report.Business_Trip__c,
                Submit_Date_New__c=report.Submit_Date_New__c,
                Submit_DateTime_New__c=report.Submit_DateTime_New__c,
                Approved_Date__c=report.Approved_Date__c,
                Approved_DateTime__c=report.Approved_DateTime__c,
                Feed_Back_From_Manager__c=report.Feed_Back_From_Manager__c,
                FeedbackManager__c=report.FeedbackManager__c,
                Planning_Time__c=report.Planning_Time__c,
                Approval_Elapsed_Time__c=report.Approval_Elapsed_Time__c,
                Activity_ID__c=report.Activity_ID__c,
                Manager_Mail__c=report.Manager_Mail__c
                );
        } catch (Exception e) {
            throw new ControllerUtil.myException('无法取得日报信息，报告者或是报告日期不正确。');
            //return null;
        }
        
        List<Activity> actList = new List<Activity>();
        // 報告書ボタンが押された場合
        if(upsertActIndex != null && upsertActIndex != ''){
            actList.add(activities.get(Integer.valueOf(upsertActIndex)));
        }
        // 保存ボタンが押された場合
        else{
            actList = activities;
        }
        
        String repoDate = String.valueOf(report.Reported_Date__c);
        
        // 必須チェック
        if(repoStartHourText == null || repoStartHourText == '' 
            || repoStartMinuteText == null || repoStartMinuteText == ''
            || repoEndHourText == null || repoEndHourText == '' 
            || repoEndMinuteText == null || repoEndMinuteText == ''){
            repoErrorFlg = error = true;
            repoErrorMessage = System.Label.Error_Message3;
        }
        else{
            try{
                Integer repoStartHourNum = Integer.valueOf(repoStartHourText);
                Integer repoStartMinuteNum = Integer.valueOf(repoStartMinuteText);
                Integer repoEndHourNum = Integer.valueOf(repoEndHourText);
                Integer repoEndMinuteNum = Integer.valueOf(repoEndMinuteText);
                // 範囲チェック
                if(repoStartHourNum < 0 || repoStartHourNum > 23 || repoStartMinuteNum < 0 || repoStartMinuteNum > 59 || repoEndHourNum < 0 || repoEndHourNum > 23 || repoEndMinuteNum < 0 || repoEndMinuteNum > 59 ){
                    repoErrorFlg =error = true;
                    repoErrorMessage = System.Label.Error_Message39;
                }
                // 逆転チェック
                else if(repoStartHourNum > repoEndHourNum || (repoStartHourNum == repoEndHourNum && repoStartMinuteNum > repoEndMinuteNum)){
                    repoErrorFlg = error = true;
                    repoErrorMessage = System.Label.Error_Message2;
                }
            }catch(Exception e){
                repoErrorFlg = error = true;
                repoErrorMessage = System.Label.Error_Message39;
            }
        }
        
        Set<ID> eIdList = new Set<ID>();
        // 保存しない活動リスト
        Set<Integer> notUpsertIndexList = new Set<Integer>();
        // 保存ボタンが押された場合
        if(upsertActIndex == null || upsertActIndex == ''){
            // 必須チェック
            if(report.Status__c == null){
                report.Status__c.addError(System.Label.Error_Message3);
                error = true;
            }
            
            // 必須チェック
            if((report.Feed_Back_From_Manager__c == null || report.Feed_Back_From_Manager__c == '' ) && (report.Status__c == '承認' || report.Status__c == '非承認')){
                report.Feed_Back_From_Manager__c.addError(System.Label.Error_Message3); error = true;

            }
            
            // 必須チェック
            if(report.Daily_Report_Data_Type__c == null){
                report.Daily_Report_Data_Type__c.addError(System.Label.Error_Message3);error = true;
            }
            
            String actStartDate = '';
            String actEndDate = '';
            // 保存しない活動インデックス
            Integer notUpsertIndex = 0;
            for (Activity a : activities) {
                if (a.act.Id!= null) eIdList.add(a.act.id);
                a.pt1ErrorFlg = false;
                //a.pt2ErrorFlg = false;
                //a.pt3ErrorFlg = false;
                //a.pt4ErrorFlg = false;
                //a.pt5ErrorFlg = false;
                //a.pt1ErrorMessage = '';
                //a.pt2ErrorMessage = '';
                //a.pt3ErrorMessage = '';
                //a.pt4ErrorMessage = '';
                //a.pt5ErrorMessage = '';
                a.actErrorFlg1 = false;
                a.actErrorFlg2 = false;
                a.actErrorMessage1 = '';
                a.actErrorMessage2 = '';
                a.planErrorFlg1 = false;
                a.planErrorFlg2 = false;
                a.planErrorFlg3 = false;
                a.planErrorMessage1 = '';
                a.planErrorMessage2 = '';
                a.planErrorMessage3 = '';
                // 活動に値が設定された場合|| (a.act.Purpose__c != null && a.act.Purpose__c != '')
                if((a.actStartHourText != null && a.actStartHourText != '')
                 || (a.actStartMinuteText != null && a.actStartMinuteText != '') 
                 || (a.actEndHourText != null && a.actEndHourText != '') 
                 || (a.actEndMinuteText != null && a.actEndMinuteText != '') 
                 || (a.act.Activity_Type2__c != null && a.act.Activity_Type2__c != '') 
                 || (a.act.Location__c != null && a.act.Location__c != '') 
                 || (a.act.Visitor1__c != null && a.act.Visitor1__c != '') 
                 || (a.act.Visitor2__c != null && a.act.Visitor2__c != '') 
                 || (a.act.Visitor3__c != null && a.act.Visitor3__c != '') 
                 || (a.act.Visitor4__c != null && a.act.Visitor4__c != '') 
                 || (a.act.Visitor5__c != null && a.act.Visitor5__c != '') 
                 || (a.act.Main_Visit_Location__c != null && a.act.Main_Visit_Location__c != '') 
                 || (a.act.Companion__c != null && a.act.Companion__c != '') 
                 || (a.act.Purpose_Type__c != null && a.act.Purpose_Type__c != '') 
                 || (a.act.Purpose_Type2__c != null && a.act.Purpose_Type2__c != '') 
                 || (a.act.Purpose_Type3__c != null && a.act.Purpose_Type3__c != '') 
                 || (a.act.Purpose_Type4__c != null && a.act.Purpose_Type4__c != '') 
                 || (a.act.Purpose_Type5__c != null && a.act.Purpose_Type5__c != '') 
                 || (a.act.Related_Opportunity1__c != null && a.act.Related_Opportunity1__c != '') 
                 || (a.act.Related_Opportunity2__c != null && a.act.Related_Opportunity2__c != '') 
                 || (a.act.Related_Opportunity3__c != null && a.act.Related_Opportunity3__c != '')
                 || (a.act.Related_Opportunity4__c != null && a.act.Related_Opportunity4__c != '') 
                 || (a.act.Related_Opportunity5__c != null && a.act.Related_Opportunity5__c != '') 
                 || (a.act.Related_Service1__c != null && a.act.Related_Service1__c != '') 
                 || (a.act.Related_Service2__c != null && a.act.Related_Service2__c != '') 
                 || (a.act.Description__c != null && a.act.Description__c != '') 
                 || a.act.Hospital_Info__c || a.act.Doctor_Info__c || a.act.Technology_Treatment__c 
                 || a.act.New_Query__c || a.act.Update_Query__c || a.act.Lost_Info__c 
                 || a.act.VOC__c || a.act.Meeting_Info__c || a.act.nextPlanDate__c != null 
                 || (a.planStartHourText != null && a.planStartHourText != '') 
                 || (a.planStartMinuteText != null && a.planStartMinuteText != '' ) 
                 || (a.planEndHourText != null && a.planEndHourText != '') 
                 || (a.planEndMinuteText != null && a.planEndMinuteText != '' ) 
                 || (a.planPurposeText != null && a.planPurposeText != '')
                 || (a.act.Activity_PurposeFSE__c != null && a.act.Activity_PurposeFSE__c != '' && reportOwner.Job_Category__c == '销售服务') 
                 || (a.act.Activity_PurposeEscFSE__c != null && a.act.Activity_PurposeEscFSE__c != '' && reportOwner.Job_Category__c != '销售服务')){
                    // 必須チェック
                    if(a.actStartHourText == null || a.actStartHourText == '' 
                        || a.actStartHourText == null || a.actStartHourText == '' 
                        || a.actEndHourText == null || a.actEndHourText == '' 
                        || a.actEndMinuteText == null || a.actEndMinuteText == ''){
                        a.actErrorFlg1 = true;
                        a.actErrorMessage1 = System.Label.Error_Message3;
                        error = true;
                    }
                    else{
                        try{
                            Integer actStartHourNum = Integer.valueOf(a.actStartHourText);
                            Integer actStartMinuteNum = Integer.valueOf(a.actStartMinuteText);
                            Integer actEndHourNum = Integer.valueOf(a.actEndHourText);
                            Integer actEndMinuteNum = Integer.valueOf(a.actEndMinuteText);
                            // 範囲チェック
                            if(actStartHourNum < 0 || actStartHourNum > 23 
                            || actStartMinuteNum < 0 || actStartMinuteNum > 59 
                            || actEndHourNum < 0 || actEndMinuteNum < 0 || actEndMinuteNum > 59 ){
                                a.actErrorFlg1 = true;
                                a.actErrorMessage1 = System.Label.Error_Message39;
                                error = true;
                            }
                            // 逆転チェック
                            else if(actStartHourNum > actEndHourNum 
                            || (actStartHourNum == actEndHourNum && actStartMinuteNum > actEndMinuteNum)){
                                a.actErrorFlg1 = true;
                                a.actErrorMessage1 = System.Label.Error_Message2;
                                error = true;
                            }
                            // 24hチェック
                            else if((actEndHourNum * 60 + actEndMinuteNum) - (actStartHourNum * 60 + actStartMinuteNum) > 24 * 60) {
                                a.actErrorFlg1 = true;
                                a.actErrorMessage1 = '活动时间不能超过24小时';
                                error = true;
                            }
                        }catch(Exception e){
                            a.actErrorFlg1 = true;
                            a.actErrorMessage1 = System.Label.Error_Message39;
                            error = true;
                        }
                    }
                    
                    // 必須チェック
                    if((a.act.Activity_Type2__c == null || a.act.Activity_Type2__c == '')
                    // 20200420 任务日报管理 add gzw start 
                    && String.isBlank(a.act.eventStatus__c)
                    // 20200420 任务日报管理 add gzw end 

                    ){
                        //a.actErrorFlg2 = true;
                        //a.actErrorMessage2 = System.Label.Error_Message3;
                        a.act.Activity_Type2__c.addError(System.Label.Error_Message3);
                        eventFlg = true;
                    }
                    // 访问对象必須チェック
                    if (report.Status__c != '作成中'
                    // 20200420 任务日报管理 add gzw start 
                    && String.isBlank(a.act.eventStatus__c)
                    // 20200420 任务日报管理 add gzw end 
                    //2021-10-15 mzy  任务管理改善  start
                    && a.tsk.taskStatus__c != '03 完成'
                    //2021-10-15 mzy  任务管理改善  end
                    ) {
                         if (!String.isBlank(a.act.Activity_Type2__c) && a.act.Activity_Type2__c == '病院'
                          && a.act.Free_Input__c == false && String.isBlank(a.act.Visitor1_ID__c)) {	//Add By Chen Yanan 20220325 for PIPL
                          //  && a.act.Free_Input__c == false && String.isBlank(a.act.Visitor1__c)) {
                            a.act.Visitor1__c.addError('请至少填写一位访问对象');
                            eventFlg = true;
                         }
                    }
                    // 必須チェック
                    String ad = a.act.Activity_PurposeFSE__c;
                    ad = a.act.Activity_PurposeFSE__c;
                    ad = reportOwner.Job_Category__c;
                    if((a.act.Activity_PurposeFSE__c == null || a.act.Activity_PurposeFSE__c == '') 
                        && reportOwner.Job_Category__c == '销售服务'
                        // 20200420 任务日报管理 add gzw start 
                        && String.isBlank(a.act.eventStatus__c)
                        // 20200420 任务日报管理 add gzw end 
                    ){
                        a.act.Activity_PurposeFSE__c.addError(System.Label.Error_Message3);
                        eventFlg = true;
                    }
                    if((a.act.Activity_PurposeEscFSE__c == null || a.act.Activity_PurposeEscFSE__c == '') 
                    && reportOwner.Job_Category__c != '销售服务'
                     // 20200420 任务日报管理 add gzw start 
                     && String.isBlank(a.act.eventStatus__c)
                     // 20200420 任务日报管理 add gzw end 
                     //2021-10-15 mzy  任务管理改善  start
                    && a.tsk.taskStatus__c != '03 完成'
                    //2021-10-15 mzy  任务管理改善  end
                     ){
                        a.act.Activity_PurposeEscFSE__c.addError(System.Label.Error_Message3);
                        eventFlg = true;
                    }
                    
                    // 必須チェック
                    if(report.Status__c == '申請中' 
                     // 20200420 任务日报管理 add gzw start 
                     && String.isBlank(a.act.eventStatus__c)
                     // 20200420 任务日报管理 add gzw end 
                     //2021-10-15 mzy  任务管理改善  start
                    && a.tsk.taskStatus__c != '03 完成'
                    //2021-10-15 mzy  任务管理改善  end
                    && (a.act.Description__c == null || a.act.Description__c == '')){
                        a.act.Description__c.addError(System.Label.Error_Message3);
                        error = true;
                    }
                    // 主要拜访场所チェック
                  //  if(report.Status__c == '申請中' && a.act.Activity_Type2__c == '病院' && String.isBlank(a.act.Main_Visit_Location__c)){
                  //      a.act.Main_Visit_Location__c.addError('用户拜访时，主要拜访场所不能为空');
                  //      error = true;
                  //  }
                    // 訪問場所チェック
                    if(report.Status__c == '申請中' && a.act.Activity_Type2__c == '病院' 
                     // 20200420 任务日报管理 add gzw start 
                     && String.isBlank(a.act.eventStatus__c)
                     // 20200420 任务日报��理 add gzw end 
                    && (String.isBlank(a.act.whatid__c) || String.isBlank(a.act.Location__c))){
                        a.act.Location__c.addError('用户拜访时，访问场所不能为空');
                        error = true;
                    }
                    
                    // 手入力チェック=販売店，社外イベント
                    //if(report.Status__c == '申請中' && (a.act.Activity_Type2__c == '販売店'||a.act.Activity_Type2__c == '社外イベント')
                    //   && a.act.Free_Input__c == true && (a.act.Visitor_Place_Free__c == null || String.isBlank(a.act.Visitor_Place_Free__c) )){
                    //  a.act.Location__c.addError('提交时，选择手动输入，访问场所不能为空' );
                    //  error = true;
                    //}
                    // 手入力チェック
                    if(report.Status__c == '申請中' && a.act.Activity_Type2__c == '病院' && a.act.Free_Input__c == true
                     // 20200420 任务日报管理 add gzw start 
                     && String.isBlank(a.act.eventStatus__c)
                     // 20200420 任务日报管理 add gzw end 
                    ){
                        a.act.Free_Input__c.addError('申请时，不能手动输入医院，必须选择真实存在的医院');
                        error = true;
                    }
                    //if(report.Status__c == '申請中' && a.act.Find_Imitations_Flag__c == true){
                    //  a.act.Find_Imitations_Flag__c.addError('测试位置结果');
                    //  error = true;
                    //}
                }
                else{
                    if(a.act.Find_Imitations_Flag__c !=true){
                        notUpsertIndexList.add(notUpsertIndex);
                    }
                    //if(a.act.Purpose_TypeFSE__c == null || a.act.Purpose_TypeFSE__c == ''&&
                    //  a.act.Purpose_TypeEscFSE__c == null || a.act.Purpose_TypeEscFSE__c == ''){  
                    //    eventFlg = true;
                    //    eventMessage = '000'+a.act.Purpose_TypeFSE__c+'000'+a.act.Purpose_TypeEscFSE__c;
                    //}
                    //if(eventFlg && report.Status__c=='申請中'){
                    //  errorMessage = '请填写日报完整后，再进行申请12';
                    //  eventFlg = false;
                    //  report.Status__c ='作成中';
                    //  error = true;
                    //  return null;
                    //}else{
                    //  eventFlg = false;
                    //    eventMessage = '';
                    //}

                }
                if ('一日休假'.equals(report.Daily_Report_Data_Type__c) && String.isNotBlank(a.act.Activity_Type2__c) && !'休暇'.equals(a.act.Activity_Type2__c) && String.isBlank(a.act.eventStatus__c) ) {
                    report.Daily_Report_Data_Type__c.addError('全天休假类型的日报拜访区分必须为休假！');
                    error = true;
                }
                if ('全天培训'.equals(report.Daily_Report_Data_Type__c) 
                    && ((reportOwner.Job_Category__c == '销售服务' && a.act.Activity_PurposeFSE__c != null &&  a.act.Activity_PurposeFSE__c != '公司培训')
                        || (reportOwner.Job_Category__c != '销售服务' && a.act.Activity_PurposeEscFSE__c != null &&  a.act.Activity_PurposeEscFSE__c != '培训'))
                    && String.isBlank(a.act.eventStatus__c)){
                    report.Daily_Report_Data_Type__c.addError('全天培训类型的日报拜访目的必须为培训！');
                    error = true;
                }
                //zh SLA定期报告书必须填信息更新 start
                //2021-11-01  mzy  当日报编辑页面【使用报告书】勾选时【涉及的维修合同】为必填项。
                if(((a.act.Purpose_TypeFSE__c != null && a.act.Purpose_TypeFSE__c == '合同季报') || a.act.UseReport__c) &&  a.act.Related_Service1__c == ''  && String.isBlank(a.act.eventStatus__c)
                ){
                    a.act.Related_Service1__c.addError('请填写涉及的维修合同');
                    error = true;
                }
                if((a.act.Purpose_TypeFSE__c != null && a.act.Purpose_TypeFSE__c == '合同季报') && String.isBlank(a.act.SLAReportInfo__c) && String.isBlank(a.act.eventStatus__c) ){
                    a.act.Related_Service1__c.addError('必须进行信息更新');
                    error = true;
                }
                //zh SLA定期报告书必须填信息更新 end

                //mzy 点检改善 start
                if((a.act.Purpose_TypeFSE__c != null && a.act.Purpose_TypeFSE__c == '合同点检') &&  a.act.Related_Service1__c == ''  && String.isBlank(a.act.eventStatus__c)
                ){
                    a.act.Related_Service1__c.addError('请填写涉及的维修合同');
                    error = true;
                }
                //mzy 点检改善 end


                // 次の活動予定
                if(a.act.nextPlanDate__c != null || (a.planStartHourText != null && a.planStartHourText != '') || (a.planStartMinuteText != null && a.planStartMinuteText != '' ) || (a.planEndHourText != null && a.planEndHourText != '') || (a.planEndMinuteText != null && a.planEndMinuteText != '' ) || (a.planPurposeText != null && a.planPurposeText != '')){
                    String planDate = String.valueOf(a.act.nextPlanDate__c);
                    // 必須チェック
                    if (a.act.nextPlanDate__c == null) {
                        a.planErrorFlg1 = true;
                        a.planErrorMessage1 = System.Label.Error_Message3;
                        error = true;
                    }
                    // 未来日チェック
                    if (a.act.nextPlanDate__c != null && a.act.nextPlanDate__c <= report.Reported_Date__c) {
                        a.planErrorFlg1 = true;
                        a.planErrorMessage1 = '请设定比报告日期将来的日期。';
                        error = true;
                    }
                    // 必須チェック
                    if(a.planStartHourText == null || a.planStartHourText == '' || a.planStartHourText == null || a.planStartHourText == '' || a.planEndHourText == null || a.planEndHourText == '' || a.planEndMinuteText == null || a.planEndMinuteText == ''){
                        a.planErrorFlg2 = true;
                        a.planErrorMessage2 = System.Label.Error_Message3;
                        error = true;
                    }
                    // 手入力チェック=販売店，社外イベント
                    //if(report.Status__c == '申請中' && (a.act.Activity_Type2__c == '販売店'||a.act.Activity_Type2__c == '社外イベント')
                    //   && a.act.Free_Input__c == true && (a.act.Visitor_Place_Free__c == null || String.isBlank(a.act.Visitor_Place_Free__c) )){
                    //  a.act.Location__c.addError('提交时，选择手动输入，访问场所不能为空。' );
                    //  error = true;
                    //}
                    else{
                        try{
                            Integer planStartHourNum = Integer.valueOf(a.planStartHourText);
                            Integer planStartMinuteNum = Integer.valueOf(a.planStartMinuteText);
                            Integer planEndHourNum = Integer.valueOf(a.planEndHourText);
                            Integer planEndMinuteNum = Integer.valueOf(a.planEndMinuteText);
                            // 範囲チェック
                            if(planStartHourNum < 0 || planStartHourNum > 23 || planStartMinuteNum < 0 || planStartMinuteNum > 59 || planEndHourNum < 0 || planEndMinuteNum < 0 || planEndMinuteNum > 59 ){
                                a.planErrorFlg2 = true;
                                a.planErrorMessage2 = System.Label.Error_Message39;
                                error = true;
                            }
                            // 逆転チェック
                            else if(planStartHourNum > planEndHourNum || (planStartHourNum == planEndHourNum && planStartMinuteNum > planEndMinuteNum)){
                                a.planErrorFlg2 = true;
                                a.planErrorMessage2 = System.Label.Error_Message2;
                                error = true;
                            // 24hチェック
                            } else if((planEndHourNum * 60 + planEndMinuteNum) - (planStartHourNum * 60 + planStartMinuteNum) > 24 * 60) {
                                a.actErrorFlg1 = true;
                                a.actErrorMessage1 = '活动时间不能超过24小时';
                                error = true;
                            }
                        }catch(Exception e){
                            a.planErrorFlg2 = true;
                            a.planErrorMessage2 = System.Label.Error_Message39;
                            error = true;
                        }
                    }
                    if (a.planPurposeText == null || a.planPurposeText == '') {
                        a.planErrorFlg3 = true;
                        a.planErrorMessage3 = System.Label.Error_Message3;
                        error = true;
                    }
                }
                
                notUpsertIndex++;
            }
            if((report.Status__c == '承認' || report.Status__c == '非承認') && (reportOwner.ManagerId != UserInfo.getUserId()&&reportOwner.BuchangApprovalManager__c != UserInfo.getUserId()&&reportOwner.BuchangApprovalManagerSales__c != UserInfo.getUserId())){
                report.Status__c.addError(System.Label.Error_Message4);
                error = true;
            }
            if (error) return null;
            if(eventFlg){
                eventMessage = eventMessage+ '活动有未填写的项目，请记得下次填写';
            }
           
        }
       
        Activity a = new Activity();

        // 訪問場所、関連する引合、関連するサービス契約の存在チェック
        for (Integer i = 0; i < actList.size(); i++) {
            a = actList.get(i);
            if (a.act.Free_Input__c) {
                a.act.Location__c = a.act.Visitor_Place_Free__c;
                a.act.whatid__c = a.act.Visitor1__c = a.act.Visitor2__c = a.act.Visitor3__c = a.act.Visitor4__c = a.act.Visitor5__c 
                = a.act.Related_Opportunity1__c = a.act.Related_Opportunity2__c = a.act.Related_Opportunity3__c = a.act.Related_Opportunity4__c 
                = a.act.Related_Opportunity5__c = a.act.Related_Service1__c = a.act.Related_Service2__c =null;


            } else if (!String.isBlank(a.act.Location__c) && String.isBlank(a.act.whatid__c)
            // 20200420 任务日报管理 add gzw start 
            && String.isBlank(a.act.eventStatus__c)
            // 20200420 任务日报管理 add gzw end 
            ){
                a.act.Location__c.addError(System.Label.Error_Message5);
                error = true;
            }
            // 20200420 任务日报管理 add gzw start
            if(String.isBlank(a.act.eventStatus__c)){
            // 20200420 任务日报管理 add gzw end 
           
                if(!String.isBlank(a.act.Visitor1__c) && (String.isBlank(a.act.Visitor1_ID__c) || ((String) a.act.Visitor1_ID__c).startsWith('003') == false)){
                    a.act.Visitor1__c.addError(a.act.Visitor1_ID__c + ' ' + System.Label.Error_Message6);
                    error = true;
                }
                
                if(!String.isBlank(a.act.Visitor2__c) && (String.isBlank(a.act.Visitor2_ID__c) || ((String) a.act.Visitor2_ID__c).startsWith('003') == false)){
                    a.act.Visitor2__c.addError(a.act.Visitor2_ID__c + ' ' + System.Label.Error_Message6);
                    error = true;
                }
                
                if(!String.isBlank(a.act.Visitor3__c) && (String.isBlank(a.act.Visitor3_ID__c) || ((String) a.act.Visitor3_ID__c).startsWith('003') == false)){
                    a.act.Visitor3__c.addError(a.act.Visitor3_ID__c + ' ' + System.Label.Error_Message6);
                    error = true;
                }
                
                if(!String.isBlank(a.act.Visitor4__c) && (String.isBlank(a.act.Visitor4_ID__c) || ((String) a.act.Visitor4_ID__c).startsWith('003') == false)){
                    a.act.Visitor4__c.addError(a.act.Visitor4_ID__c + ' ' + System.Label.Error_Message6);
                    error = true;
                }
                
                if(!String.isBlank(a.act.Visitor5__c) && (String.isBlank(a.act.Visitor5_ID__c) || ((String) a.act.Visitor5_ID__c).startsWith('003') == false)){
                    a.act.Visitor5__c.addError(a.act.Visitor5_ID__c + ' ' + System.Label.Error_Message6);
                    error = true;
                }
                
                if(!String.isBlank(a.act.Related_Opportunity1__c) && (String.isBlank(a.act.Related_Opportunity1_ID__c) || ((String) a.act.Related_Opportunity1_ID__c).startsWith('006') == false)){
                    a.act.Related_Opportunity1__c.addError(a.act.Related_Opportunity1_ID__c + ' ' + System.Label.Error_Message7);
                    error = true;
                }
                if(!String.isBlank(a.act.Related_Opportunity2__c) && (String.isBlank(a.act.Related_Opportunity2_ID__c) || ((String) a.act.Related_Opportunity2_ID__c).startsWith('006') == false)){
                    a.act.Related_Opportunity2__c.addError(a.act.Related_Opportunity2_ID__c + ' ' + System.Label.Error_Message7);
                    error = true;
                }
                if(!String.isBlank(a.act.Related_Opportunity3__c) && (String.isBlank(a.act.Related_Opportunity3_ID__c) || ((String) a.act.Related_Opportunity3_ID__c).startsWith('006') == false)){
                    a.act.Related_Opportunity3__c.addError(a.act.Related_Opportunity3_ID__c + ' ' + System.Label.Error_Message7);
                    error = true;
                }
                if(!String.isBlank(a.act.Related_Opportunity4__c) && (String.isBlank(a.act.Related_Opportunity4_ID__c) || ((String) a.act.Related_Opportunity4_ID__c).startsWith('006') == false)){
                    a.act.Related_Opportunity4__c.addError(a.act.Related_Opportunity4_ID__c + ' ' + System.Label.Error_Message7);
                    error = true;
                }
                if(!String.isBlank(a.act.Related_Opportunity5__c) && (String.isBlank(a.act.Related_Opportunity5_ID__c) || ((String) a.act.Related_Opportunity5_ID__c).startsWith('006') == false)){
                    a.act.Related_Opportunity5__c.addError(a.act.Related_Opportunity5_ID__c + ' ' + System.Label.Error_Message7);
                    error = true;
                }
                
                if(!String.isBlank(a.act.Related_Service1__c) && (String.isBlank(a.act.Related_Service1_ID__c) || ((String) a.act.Related_Service1_ID__c).startsWith('a0H') == false)){
                    a.act.Related_Service1__c.addError(a.act.Related_Service1_ID__c + ' ' + System.Label.Error_Message8);
                    error = true;
                }
                if(!String.isBlank(a.act.Related_Service2__c) && (String.isBlank(a.act.Related_Service2_ID__c) || ((String) a.act.Related_Service2_ID__c).startsWith('a0H') == false)){
                    a.act.Related_Service2__c.addError(a.act.Related_Service2_ID__c + ' ' + System.Label.Error_Message8);
                    error = true;
                }
             // 20200420 任务日报管理 add gzw start
            }
            // 20200420 任务日报管理 add gzw end 
        }
        
        // Account,Campaignの逆引きチェック
        List<String> accList = new List<String>();
        List<String> campList = new List<String>();
        for (Integer i=0; i<actList.size(); i++) {
            a = actList.get(i);
            if (!String.isBlank(a.act.whatid__c)) {
                if (a.act.whatid__c.startsWith('001')) {
                    accList.add(a.act.Location__c);
                }
                if (a.act.whatid__c.startsWith('701')) {
                    campList.add(a.act.Location__c);
                }
            }
        }
        // 逆引き
        Map<String, Map<String, String>> accMap = new Map<String, Map<String, String>>();
        Map<String, Map<String, String>> campMap = new Map<String, Map<String, String>>();
        if (accList.size() > 0) accMap = ControllerUtil.getAccsByName(accList);
        if (campList.size() > 0) campMap = ControllerUtil.getCampsByName(campList);

        for (Integer i = 0; i < actList.size(); i++) {
            a = actList.get(i);
            // 批准、不批准：変更があればチェック
            // ほか：常にチェック
            if (((report.Status__c == '承認' || report.Status__c == '非承認')
                    && (a.act.Location__c != a.oldLocation || a.act.whatid__c != a.oldLocationId))
                || (report.Status__c != '承認' && report.Status__c != '非承認')) {
                if (!a.act.Free_Input__c) {
                    if (!String.isBlank(a.act.whatid__c)
                        // 20200420 任务日报管理 add gzw start 
                        && String.isBlank(a.act.eventStatus__c)
                        // 20200420 任务日报管理 add gzw end 
                    ) {
                        if (a.act.whatid__c.startsWith('001')) {
                            // 逆引きの結果あり、且つその結果はwhatidを含む場合、対応するIDをセット
                            if (accMap.containsKey(a.act.Location__c) && accMap.get(a.act.Location__c) != null && accMap.get(a.act.Location__c).containsKey(a.act.whatid__c)) {
                                
                            } else {
                                a.act.Location__c.addError('无法确定访问场所，请再设定一次访问场所。');
                                error = true;
                            }
                        }
                        if (a.act.whatid__c.startsWith('701')) {
                            // 逆引きの結果あり、且つその結果はwhatidを含む場合、対応するIDをセット
                            if (campMap.containsKey(a.act.Location__c) && campMap.get(a.act.Location__c) != null && campMap.get(a.act.Location__c).containsKey(a.act.whatid__c)) {
                                
                            } else {
                                a.act.Location__c.addError('无法确定访问场所，请再设定一次访问场所。');
                                error = true;
                            }
                        }
                    }
                }
            }
        }

        if (error) return null;

        List<Event__c> save_eventsAct = new List<Event__c>();
        List<task__c> save_task = new List<task__c>();   // 2021-09-18  mzy  任务管理改善  start
        Set<Id> eveIdList = new Set<Id>();
        Set<Id> actDelListForDelIns = new Set<Id>();
        boolean upsertFlg = true;
        Integer index = 0;
        Integer indexCycNull = 0;
        //功能目标：新建日报时便开始申请，若为空，则不能保存，若填写完整，可以保存
       for (Integer i = 0; i < actList.size(); i++) {
            a = actList.get(i);
            Event__c ae = activities.get(0).act;
            if(a.act.id==null&&
                (a.act.Activity_Type2__c == null||a.act.Activity_Type2__c == '') ){
                indexCycNull ++;
            }
            
        }
        if( indexCycNull==actList.size() && report.Status__c == '申請中'
            // 20200420 任务日报管理 add gzw start 
            && String.isBlank(a.act.eventStatus__c)
            // 20200420 任务日报管理 add gzw end 
        ){
                errorMessage = '请填写日报完整后，再进行申请';
                eventFlg = false;
                //report.Status__c ='作成中';
                error = true;
                return null;    
            }
        // savepoint
        Savepoint sp = Database.setSavepoint();
        //try {
            etAPPerrorMsg = '';
            for (Integer i = 0; i < actList.size(); i++) {
                upsertFlg = true;
                
                // 訪問者、引合、サビコン設定のループには、項目値を再判断する
                if (notUpsertIndexList.contains(i)) {
                    upsertFlg = false;
                    break;
                }
                
                // 保存しない活動リストにない活動のみ保存

                if(upsertFlg){

                    a = actList.get(i);
                    a.act.Subject__c = a.act.Purpose__c;
                    a.act.ActivityDate__c = report.Reported_Date__c;
                    a.act.Daily_Report__c = report.Id;
                    //a.act.Imitation_Mail__c = 'it_prectech@olympus.com.cn';
                    // メール送信ボタン設定
                    if (report.Status__c == '申請中') {
                        a.act.Mail_Send_Btn__c = (a.act.Mail_Send_Btn__c == '0' || String.isBlank(a.act.Mail_Send_Btn__c)) ? '1' : '0';
                    }
                    
                    if (a.act.whatid__c != null && a.act.whatid__c.startsWith('001')) {
                        // 訪問場所はAccountの場合
                        a.act.Account_ID__c = a.act.whatid__c;
                        a.act.Campaign_ID__c = null;
                    } else if (a.act.whatid__c != null && a.act.whatid__c.startsWith('701')) {
                        // 訪問場所はCampaignの場合
                        a.act.Account_ID__c = null;
                        a.act.Campaign_ID__c = a.act.whatid__c;
                    } else {
                        a.act.Account_ID__c = null;
                        a.act.Campaign_ID__c = null;
                    }

                    //zh 20210623 SLA报告书任务：活动区分为合同季报时，使用报告书不能勾选 start
                    if (a.act.UseReport__c && '合同季报'.equals(a.act.Purpose_TypeFSE__c)) {
                        a.act.UseReport__c = false;
                    }
                    //zh 20210623 SLA报告书任务：活动区分为合同季报时，使用报告书不能勾选 end

                    if((reportOwner.Job_Category__c == '销售服务'||a.act.Purpose_TypeEscFSE__c=='休假') && (a.act.Purpose_TypeFSE__c != null || 
                        a.act.Purpose_TypeFSE2__c != null || a.act.Purpose_TypeFSE3__c != null
                        || a.act.Purpose_TypeFSE4__c != null || a.act.Purpose_TypeFSE5__c != null)){
                        a.act.Purpose_Type__c = a.act.Purpose_TypeFSE__c;
                        a.act.Purpose_Type2__c =a.act.Purpose_TypeFSE2__c;
                        a.act.Purpose_Type3__c =a.act.Purpose_TypeFSE3__c;
                        a.act.Purpose_Type4__c =a.act.Purpose_TypeFSE4__c;
                        a.act.Purpose_Type5__c =a.act.Purpose_TypeFSE5__c;
                    }else if((reportOwner.Job_Category__c != '销售服务'||a.act.Purpose_TypeEscFSE__c=='休假') && (a.act.Purpose_TypeEscFSE__c != null ||
                        a.act.Purpose_TypeEscFSE2__c != null || a.act.Purpose_TypeEscFSE3__c != null
                        || a.act.Purpose_TypeEscFSE4__c != null || a.act.Purpose_TypeEscFSE5__c != null)){
                        a.act.Purpose_Type__c = a.act.Purpose_TypeEscFSE__c;
                        a.act.Purpose_Type2__c =a.act.Purpose_TypeEscFSE2__c;
                        a.act.Purpose_Type3__c =a.act.Purpose_TypeEscFSE3__c;
                        a.act.Purpose_Type4__c =a.act.Purpose_TypeEscFSE4__c;
                        a.act.Purpose_Type5__c =a.act.Purpose_TypeEscFSE5__c;
                    }else{
                        a.act.Purpose_Type__c = null;
                        a.act.Purpose_Type2__c =null;
                        a.act.Purpose_Type3__c =null;
                        a.act.Purpose_Type4__c =null;
                        a.act.Purpose_Type5__c =null;
                    }
                    //20210520 zh ETAPP与日报联动 start
                    if(reportOwner.Job_Category__c == '销售服务' && 'ET APP活动'.equals(a.act.Activity_PurposeFSE__c) && !a.act.ETAPPAct__c && !'延期'.equals(a.act.eventStatus__c) && !'取消'.equals(a.act.eventStatus__c)){
                        // a.act.Activity_PurposeFSE__c.addError('请进行ET APP活动更新！');
                        // error = true;
                        etAPPFlg = 'true';
                        eventMessage = '请确认：是否需要新建目标ET或者进行目标ET的PDCA管理。';
                        etAPPerrorMsg = '若需要建立目标ET，请点击[转至ET APP]新建目标ET。若已建立目标ET，请点击[ET APP活动]进行活动PDCA管理';
                        
                    }else if(reportOwner.Job_Category__c != '销售服务' && 'ET APP活动'.equals(a.act.Activity_PurposeEscFSE__c) && !a.act.ETAPPAct__c && !'延期'.equals(a.act.eventStatus__c) && !'取消'.equals(a.act.eventStatus__c)){
                        // a.act.Activity_PurposeEscFSE__c.addError('请进行ET APP活动更新！');
                        // error = true;
                        etAPPFlg = 'true';
                        eventMessage = '请确认：是否需要新建目标ET或者进行目标ET的PDCA管理。';
                        etAPPerrorMsg = '若需要建立目标ET，请点击[转至ET APP]新建目标ET。若已建立目标ET，请点击[ET APP活动]进行活动PDCA管理';
                    }
                    //20210520 zh ETAPP与日报联动 end
                    // 必須チェック
                    if((a.act.Purpose_Type__c == null || a.act.Purpose_Type__c == '')
                        // 20200420 任务日报管理 add gzw start 
                        && String.isBlank(a.act.eventStatus__c)
                        // 20200420 任务日报管理 add gzw end 

                    ){  
                        a.pt1ErrorFlg = true;
                        eventFlg = true;
                        if(etAPPFlg != 'true'){
                            eventMessage = '活动有未填写的项目，请记得下次填写。 ';
                        }
                    }
                    
                    // 20200420 任务日报管理 add gzw start
                    if( !string.isblank( a.act.eventStatus__c ) &&  a.act.eventStatus__c.equals('取消')){
                    }else if ( !string.isblank( a.act.eventStatus__c ) &&  a.act.eventStatus__c.equals('延期')){
                        // zh延期理由，取消理由
                        a.act.delayReasonOther__c = a.delayReason;
                        // zh延期理由，取消理由
                        a.act.delayToDate__c = a.delayToDate;
                    }

                    //2021-09-18  mzy  任务管理改善  start
                    if(a.isTaskBlank){
                        //任务为空的还是按之前逻辑赋值延期取消理由                        
                        // 取消理由赋值
                        if(reportOwner.Job_Category__c == '销售服务' && a.act.cancelReasonSelectFSE__c != null){
                            a.act.CancelReason__c = a.act.cancelReasonSelectFSE__c;
                        }else if(reportOwner.Job_Category__c != '销售服务' && a.act.cancelReasonSelect__c != null){
                            a.act.CancelReason__c = a.act.cancelReasonSelect__c;
                        }else{
                            a.act.CancelReason__c = null;
                        }
                        // 延期理由赋值
                        if(reportOwner.Job_Category__c == '销售服务' && a.act.delayReasonSelectFSE__c != null){
                            a.act.delayReason__c = a.act.delayReasonSelectFSE__c;
                        }else if(reportOwner.Job_Category__c != '销售服务' && a.act.delayReasonSelect__c != null){
                            a.act.delayReason__c = a.act.delayReasonSelect__c;
                        }else{
                            a.act.delayReason__c = null;
                        }
                    }else {
                        //任务不为空,将任务的延期取消理由赋值到报告一览上
                        //取消理由赋值
                        if(reportOwner.Job_Category__c == '销售服务' && a.tsk.cancelReasonSelectFSE__c != null){
                            a.act.cancelReasonSelectFSE__c = a.tsk.cancelReasonSelectFSE__c;
                            a.act.CancelReason__c = a.tsk.cancelReasonSelectFSE__c;
                        }else if(reportOwner.Job_Category__c != '销售服务' && a.tsk.cancelReasonSelect__c != null){
                            a.act.cancelReasonSelect__c = a.tsk.cancelReasonSelect__c;
                            a.act.CancelReason__c = a.tsk.cancelReasonSelect__c;
                        }else{
                            a.act.CancelReason__c = null;
                        }

                        // 延期理由赋值
                        if(reportOwner.Job_Category__c == '销售服务' && a.tsk.delayReasonSelectFSE__c != null){
                            a.act.delayReasonSelectFSE__c = a.tsk.delayReasonSelectFSE__c;
                            a.act.delayReason__c = a.tsk.delayReasonSelectFSE__c;
                        }else if(reportOwner.Job_Category__c != '销售服务' && a.tsk.delayReasonSelect__c != null){
                            a.act.delayReasonSelect__c = a.tsk.delayReasonSelect__c;
                            a.act.delayReason__c = a.tsk.delayReasonSelect__c;
                        }else{
                            a.act.delayReason__c = null;
                        }

                        //延期/取消时,将理由更新到任务中(哪个报告一览上点的保存哪个报告一栏的任务)
                        //获取是哪条报告一览
                        if(delIndex != null){                            
                            Integer del = Integer.valueOf(delIndex);
                            if(i == del){
                                save_task.add(a.tsk);
                            }
                        }
                    }

                    //2021-09-18 mzy  任务管理改善  end
                      // 20200420 任务日报管理 add gzw end
                    if(eventFlg && report.Status__c=='申請中'
                        // 20200420 任务日报管理 add gzw start 
                        && String.isBlank(a.act.eventStatus__c) && String.isBlank(etAPPerrorMsg) 
                        // 20200420 任务日报管理 add gzw end 
                    ){
                        errorMessage = '请填写日报完整后，再进行申请';
                        eventFlg = false;
                        error = true;
                        report.Status__c ='作成中';
                        return null;
                    }
                    if(reportOwner.Job_Category__c == '销售服务' && a.act.Activity_PurposeFSE__c != null){
                        a.act.Activity_Purpose__c = a.act.Activity_PurposeFSE__c;
                    }else if(reportOwner.Job_Category__c != '销售服务' && a.act.Activity_PurposeEscFSE__c != null){
                        a.act.Activity_Purpose__c = a.act.Activity_PurposeEscFSE__c;
                    }else{
                        a.act.Activity_Purpose__c = null;
                    }
                    /*
                    a.act.Courtesy_Call__c = false;
                    a.act.Customer_Advisory_Corresponding__c = false;
                    a.act.Campain_Or_Event__c = false;
                    a.act.Infomation_Collection__c = false;
                    a.act.Product_Or_Introduction__c = false;
                    //a.act.OPD__c = false;
                    a.act.Inquiry_Or_MaintenanceInquiry__c = false;
                    a.act.Dealerassist_Or_Visit__c = false;
                    a.act.Contract_Negotiations__c = false;
                    a.act.Participate_In_The_Tender__c = false;
                    a.act.Signed_Contract__c = false;
                    a.act.Satisfiedgoods_Installed__c = false;
                    a.act.Send_Or_Take_Equipment__c = false;
                    a.act.Send_Or_Take_Fileclass__c = false;
                    a.act.With_Taiwan__c = false;
                    a.act.New_Installed_Maintenance_Training__c = false;
                    //a.act.NTC__c = false;
                    a.act.Checking__c = false;
                    a.act.Come_Around__c = false;
                    //a.act.ON_CALL__c = false;
                    a.act.Repair_Explanation__c = false;
                    a.act.Complaint_Including_QIS__c = false;
                    a.act.Back_Section__c = false;
                    a.act.Spare_Inspection_Probes__c = false;
                    a.act.Repair_Low_Level__c = false;
                    a.act.Meeting__c = false;
                    a.act.Train__c = false;
                    a.act.Customer_Access__c = false;
                    a.act.Data_Thus__c = false;
                    a.act.Phone_Call__c = false;
                    a.act.Meeting_Participants__c = false;
                    a.act.Product_Training__c = false;
                    a.act.Inquiry_Activities__c = false;
                    a.act.Aftermarket_Matters__c = false;
                    a.act.Inventory_Management__c = false;
                    a.act.Move__c = false;ss
                    a.act.Vacation__c = false;
                    a.act = setPurposeType(a.act, a.act.Purpose_Type__c);
                    a.act = setPurposeType(a.act, a.act.Purpose_Type2__c);
                    a.act = setPurposeType(a.act, a.act.Purpose_Type3__c);
                    a.act = setPurposeType(a.act, a.act.Purpose_Type4__c);
                    a.act = setPurposeType(a.act, a.act.Purpose_Type5__c);
                    */
                    a.act.StartDateTime__c = Datetime.newInstance(report.Reported_Date__c.year(), report.Reported_Date__c.month(), report.Reported_Date__c.day(), Integer.valueOf(a.actStartHourText), Integer.valueOf(a.actStartMinuteText), 0);
                    a.act.EndDateTime__c = Datetime.newInstance(report.Reported_Date__c.year(), report.Reported_Date__c.month(), report.Reported_Date__c.day(), Integer.valueOf(a.actEndHourText), Integer.valueOf(a.actEndMinuteText), 0);
                    a.act.ActivityDateTime__c = a.act.StartDateTime__c;
                    a.act.nextPlanTimePurpose__c = a.planStartHourText + ',' + a.planStartMinuteText + ',' + a.planEndHourText + ',' + a.planEndMinuteText + ',' + a.planPurposeText; 
                    
                    // 計画フラグ
                    //if (report.Reported_Date__c > Date.today()) {
                    //    a.act.IsScheduled__c = true;
                    //}
                    
                    if (a.act.Id != null) {
                        eveIdList.add(a.act.Id);
                        actDelListForDelIns.add(a.act.Id);
                    }
                    
                    save_eventsAct.add(a.act);
                    
                    index++;

                }
                
            }

            // システム管理者権限で更新
            
            //SWAG-B9DBLU ----------UpdateStart--------------
            try {
                ControllerUtil.upsEventC(save_eventsAct);

                //2021-09-18 mzy  任务管理改善  start
                if(save_task.size()>0){
                    update save_task;
                }
                //2021-09-18 mzy  任务管理改善  end
            } catch(Exception e) {
                ApexPages.addMessages(e);
                error = true;
                return null;
            }
            //SWAG-B9DBLU ----------UpdateEnd-------------
            //testStr = '233333======5'+o;
            // 保存ボタンが押された場合
            if(upsertActIndex == null || upsertActIndex == ''){
                // nextEventはトリガで対応
                
                report.Manager_Mail__c = reportOwner.Manager.Email;
                report.Working_Time_From__c = Datetime.newInstance(report.Reported_Date__c.year(), report.Reported_Date__c.month(), report.Reported_Date__c.day(), Integer.valueOf(repoStartHourText), Integer.valueOf(repoStartMinuteText), 0);
                report.Working_Time_To__c = Datetime.newInstance(report.Reported_Date__c.year(), report.Reported_Date__c.month(), report.Reported_Date__c.day(), Integer.valueOf(repoEndHourText), Integer.valueOf(repoEndMinuteText), 0);
                Datetime datetimeNow = datetime.now();
                if(report.Planning_Time__c == null){
                    report.Planning_Time__c = datetimeNow.addHours(8);
                }
                
                // 申請日を設定
                /*if(report.Status__c == '申請中' && tempStatus != '申請中'){
                    //if(report.Submit_Date__c == null){
                        report.Submit_Date__c = date.today();
                        report.Submit_DateTime__c = datetimeNow.addHours(8);
    
                        // 日報作成から申請までの時間を設定
                        Date startD = report.Reported_Date__c;
                        Date endD = Date.today();
                        if(startD >= endD){
                            report.Submission_Elapsed_Time__c = 0;
                        }
                        else{
                            Datetime endDT = datetimeNow.addHours(8);
                            Integer betweenDay = startD.daysBetween(endD) - 1;
                            report.Submission_Elapsed_Time__c = betweenDay * 24 + endDT.hour();
                        }
                    //}
                }*/
                // 承認日を設定
                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;
                }
                
                tempStatus = report.Status__c;
            }
            else{
                upsertActIndex = '';
                report.Status__c = tempStatus;                       // 他の項目保存しますけど、状態を表示した時の状態に戻す
            }
            // 活動1,2,3の設定
            {
                List<Activity_History_Daily_Report__c> ahdrUpSertList = new List<Activity_History_Daily_Report__c>();
                Activity_History_Daily_Report__c ahdr = new Activity_History_Daily_Report__c();
                TestLink = actList;

                for (Integer i=0; i<actList.size(); i++) {
                    testStr = '233333======5:'+a.act.Visitor1__c+'&&&&'+a.act.Visitor1_ID__c;
                    a = actList.get(i);
                    // 訪問者1を設定
                    if(!String.isBlank(a.act.Visitor1__c) && !String.isBlank(a.act.Visitor1_ID__c)){
                        ahdr = new Activity_History_Daily_Report__c();
                        ahdr.Daily_Report__c = report.Id;
                        ahdr.Contact__c = a.act.Visitor1_ID__c;
                        ahdr.EventC_ID__c = a.act.Id;
                        ahdr.Start_Time__c = a.act.StartDateTime__c;
                        ahdr.End_Time__c = a.act.EndDateTime__c;
                        ahdr.Subject__c = a.act.Subject__c;
                        ahdr.Place__c = a.act.Location__c;
                        ahdr.Date__c = report.Reported_Date__c;
                        ahdr.Sales_Division__c = reportOwner.Category4__c;
                        ahdrUpSertList.add(ahdr);
                    }
                    
                    // 訪問者2を設定
                    if(!String.isBlank(a.act.Visitor2__c) && !String.isBlank(a.act.Visitor2_ID__c)){
                        ahdr = new Activity_History_Daily_Report__c();
                        ahdr.Daily_Report__c = report.Id;
                        ahdr.Contact__c = a.act.Visitor2_ID__c;
                        ahdr.EventC_ID__c = a.act.Id;
                        ahdr.Start_Time__c = a.act.StartDateTime__c;
                        ahdr.End_Time__c = a.act.EndDateTime__c;
                        ahdr.Subject__c = a.act.Subject__c;
                        ahdr.Place__c = a.act.Location__c;
                        ahdr.Date__c = report.Reported_Date__c;
                        ahdr.Sales_Division__c = reportOwner.Category4__c;
                        ahdrUpSertList.add(ahdr);
                    }
                    
                    // 訪問者3を設定
                    if(!String.isBlank(a.act.Visitor3__c) && !String.isBlank(a.act.Visitor3_ID__c)){
                        ahdr = new Activity_History_Daily_Report__c();
                        ahdr.Daily_Report__c = report.Id;
                        ahdr.Contact__c = a.act.Visitor3_ID__c;
                        ahdr.EventC_ID__c = a.act.Id;
                        ahdr.Start_Time__c = a.act.StartDateTime__c;
                        ahdr.End_Time__c = a.act.EndDateTime__c;
                        ahdr.Subject__c = a.act.Subject__c;
                        ahdr.Place__c = a.act.Location__c;
                        ahdr.Date__c = report.Reported_Date__c;
                        ahdr.Sales_Division__c = reportOwner.Category4__c;
                        ahdrUpSertList.add(ahdr);
                    }
                    
                    // 訪問者4を設定
                    if(!String.isBlank(a.act.Visitor4__c) && !String.isBlank(a.act.Visitor4_ID__c)){
                        ahdr = new Activity_History_Daily_Report__c();
                        ahdr.Daily_Report__c = report.Id;
                        ahdr.Contact__c = a.act.Visitor4_ID__c;
                        ahdr.EventC_ID__c = a.act.Id;
                        ahdr.Start_Time__c = a.act.StartDateTime__c;
                        ahdr.End_Time__c = a.act.EndDateTime__c;
                        ahdr.Subject__c = a.act.Subject__c;
                        ahdr.Place__c = a.act.Location__c;
                        ahdr.Date__c = report.Reported_Date__c;
                        ahdr.Sales_Division__c = reportOwner.Category4__c;
                        ahdrUpSertList.add(ahdr);
                    }
                    
                    // 訪問者5を設定
                    if(!String.isBlank(a.act.Visitor5__c) && !String.isBlank(a.act.Visitor5_ID__c)){
                        ahdr = new Activity_History_Daily_Report__c();
                        ahdr.Daily_Report__c = report.Id;
                        ahdr.Contact__c = a.act.Visitor5_ID__c;
                        ahdr.EventC_ID__c = a.act.Id;
                        ahdr.Start_Time__c = a.act.StartDateTime__c;
                        ahdr.End_Time__c = a.act.EndDateTime__c;
                        ahdr.Subject__c = a.act.Subject__c;
                        ahdr.Place__c = a.act.Location__c;
                        ahdr.Date__c = report.Reported_Date__c;
                        ahdr.Sales_Division__c = reportOwner.Category4__c;
                        ahdrUpSertList.add(ahdr);
                    }
                }
                
                List<Event_Oppotunity__c> eoUpSertList = new List<Event_Oppotunity__c>();
                Event_Oppotunity__c eo = new Event_Oppotunity__c();
                Map<String, String> oppChkMap = new Map<String, String>();
                Integer oppCount = 0;
                for (Integer i=0; i<actList.size(); i++) {
                    a = actList.get(i);

                    // 関連する引合1を設定
                    if(!String.isBlank(a.act.Related_Opportunity1__c) && !String.isBlank(a.act.Related_Opportunity1_ID__c)){
                        eo = new Event_Oppotunity__c();
                        eo.Daily_Report__c = report.Id;
                        eo.Opportunity__c = a.act.Related_Opportunity1_ID__c;
                        eo.EventC_ID__c = a.act.Id;
                        eo.Start_Time__c = a.act.StartDateTime__c;
                        eo.End_Time__c = a.act.EndDateTime__c;
                        eo.Subject__c = a.act.Subject__c;
                        eo.Place__c = a.act.Location__c;
                        eo.Date__c = report.Reported_Date__c;
                        eo.Sales_Division__c = reportOwner.Category4__c;
                        eoUpSertList.add(eo);
                        
                        oppChkMap.put(a.act.Related_Opportunity1_ID__c, a.act.Related_Opportunity1_ID__c);
                    }

                    // 関連する引合2を設定
                    if(!String.isBlank(a.act.Related_Opportunity2__c) && !String.isBlank(a.act.Related_Opportunity2_ID__c) && !oppChkMap.containsKey(a.act.Related_Opportunity2_ID__c)){
                        eo = new Event_Oppotunity__c();
                        eo.Daily_Report__c = report.Id;
                        eo.Opportunity__c = a.act.Related_Opportunity2_ID__c;
                        eo.EventC_ID__c = a.act.Id;
                        eo.Start_Time__c = a.act.StartDateTime__c;
                        eo.End_Time__c = a.act.EndDateTime__c;
                        eo.Subject__c = a.act.Subject__c;
                        eo.Place__c = a.act.Location__c;
                        eo.Date__c = report.Reported_Date__c;
                        eo.Sales_Division__c = reportOwner.Category4__c;
                        eoUpSertList.add(eo);
                        
                        oppChkMap.put(a.act.Related_Opportunity2_ID__c, a.act.Related_Opportunity2_ID__c);
                    }

                    // 関連する引合3を設定
                    if(!String.isBlank(a.act.Related_Opportunity3__c) && !String.isBlank(a.act.Related_Opportunity3_ID__c) && !oppChkMap.containsKey(a.act.Related_Opportunity3_ID__c)){
                        eo = new Event_Oppotunity__c();
                        eo.Daily_Report__c = report.Id;
                        eo.Opportunity__c = a.act.Related_Opportunity3_ID__c;
                        eo.EventC_ID__c = a.act.Id;
                        eo.Start_Time__c = a.act.StartDateTime__c;
                        eo.End_Time__c = a.act.EndDateTime__c;
                        eo.Subject__c = a.act.Subject__c;
                        eo.Place__c = a.act.Location__c;
                        eo.Date__c = report.Reported_Date__c;
                        eo.Sales_Division__c = reportOwner.Category4__c;
                        eoUpSertList.add(eo);
                        
                        oppChkMap.put(a.act.Related_Opportunity3_ID__c, a.act.Related_Opportunity3_ID__c);
                    }

                    // 関連する引合4を設定
                    if(!String.isBlank(a.act.Related_Opportunity4__c) && !String.isBlank(a.act.Related_Opportunity4_ID__c) && !oppChkMap.containsKey(a.act.Related_Opportunity4_ID__c)){
                        eo = new Event_Oppotunity__c();
                        eo.Daily_Report__c = report.Id;
                        eo.Opportunity__c = a.act.Related_Opportunity4_ID__c;
                        eo.EventC_ID__c = a.act.Id;
                        eo.Start_Time__c = a.act.StartDateTime__c;
                        eo.End_Time__c = a.act.EndDateTime__c;
                        eo.Subject__c = a.act.Subject__c;
                        eo.Place__c = a.act.Location__c;
                        eo.Date__c = report.Reported_Date__c;
                        eo.Sales_Division__c = reportOwner.Category4__c;
                        eoUpSertList.add(eo);
                        
                        oppChkMap.put(a.act.Related_Opportunity4_ID__c, a.act.Related_Opportunity4_ID__c);
                    }

                    // 関連する引合5を設定
                    if(!String.isBlank(a.act.Related_Opportunity5__c) && !String.isBlank(a.act.Related_Opportunity5_ID__c) && !oppChkMap.containsKey(a.act.Related_Opportunity5_ID__c)){
                        eo = new Event_Oppotunity__c();
                        eo.Daily_Report__c = report.Id;
                        eo.Opportunity__c = a.act.Related_Opportunity5_ID__c;
                        eo.EventC_ID__c = a.act.Id;
                        eo.Start_Time__c = a.act.StartDateTime__c;
                        eo.End_Time__c = a.act.EndDateTime__c;
                        eo.Subject__c = a.act.Subject__c;
                        eo.Place__c = a.act.Location__c;
                        eo.Date__c = report.Reported_Date__c;
                        eo.Sales_Division__c = reportOwner.Category4__c;
                        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 (Integer i=0; i<actList.size(); i++) {
                    a = actList.get(i);
                    // 関連するサービス契約1を設定
                    if(!String.isBlank(a.act.Related_Service1__c) && !String.isBlank(a.act.Related_Service1_ID__c)){
                        es = new Event_Service__c();
                        es.Daily_Report__c = report.Id;
                        es.Service__c = a.act.Related_Service1_ID__c;
                        es.EventC_Id__c = a.act.Id;
                        es.Start_Time__c = a.act.StartDateTime__c;
                        es.End_Time_del__c = a.act.EndDateTime__c;
                        es.Subject__c = a.act.Subject__c;
                        es.Place_del__c = a.act.Location__c;
                        es.Date__c = report.Reported_Date__c;
                        es.Sales_Division__c = reportOwner.Category4__c;
                        esUpSertList.add(es);
                        
                        esChkMap.put(a.act.Related_Service1_ID__c, a.act.Related_Service1_ID__c);
                    }
                    
                    // 関連するサービス契約2を設定
                    if(!String.isBlank(a.act.Related_Service2__c) && !String.isBlank(a.act.Related_Service2_ID__c) && !esChkMap.containsKey(a.act.Related_Service2_ID__c)){
                        es = new Event_Service__c();
                        es.Daily_Report__c = report.Id;
                        es.Service__c = a.act.Related_Service2_ID__c;
                        es.EventC_ID__c = a.act.Id;
                        es.Start_Time__c = a.act.StartDateTime__c;
                        es.End_Time_del__c = a.act.EndDateTime__c;
                        es.Subject__c = a.act.Subject__c;
                        es.Place_del__c = a.act.Location__c;
                        es.Date__c = report.Reported_Date__c;
                        es.Sales_Division__c = reportOwner.Category4__c;
                        esUpSertList.add(es);
                    }
                }

                // システム管理者権限で更新
                ControllerUtil.eventDelIns(actDelListForDelIns,ahdrUpSertList,eoUpSertList,esUpSertList);
            }
            if(save_eventsAct.size() > 0){
                report.Activity_ID__c = save_eventsAct.get(0).id;
            }
            // システム管理者権限で更新
            ControllerUtil.updDailyReport(report);
            // SWAG-BD9A76  start 空更新报告一览
            if(report.Status__c == '承認'){
                try {
                    ControllerUtil.upsEventC(save_eventsAct);
                } catch(Exception e) {
                    ApexPages.addMessages(e);
                    error = true;
                    return null;
                }
            }
            // SWAG-BD9A76  end 空更新报告一览
            
            if(report.Status__c == '承認' || (report.Status__c == '申請中' && UserInfo.getUserId() != reportOwner.ManagerId)){
                allDisableFlg = true;
            }
            else{
                allDisableFlg = false;
            }
            
            if (report.Status__c == '作成中' || report.Status__c == '非承認' || UserInfo.getUserId() == reportOwner.Id) {
                reportStatusFlg = true;
            } else {
                reportStatusFlg = false;
            }
            
            // 申請取消フラグを設定
            if(report.Status__c == '申請中') {
                cancelRequestFlg = true;
            }
            else{
                cancelRequestFlg = false;
            }
            
            // 支援の場合は報告者を変更可能
            if(me.Job_Category__c == '支援' && report.Status__c != '承認'){
                reporterEditFlg = false;
            }
            else{
                reporterEditFlg = true;
            }
            
            if(upsertActIndex == null || upsertActIndex == ''){
                completion = true;
            }

            report = reportSelectById(report.id)[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(Activity activi :activities){
                if(String.isBlank(activi.act.eventstatus__c) && !String.isBlank(activi.act.Event_ID__c)){
                    eventOkId.add(activi.act.Event_ID__c);
                    eventCAndEventMap.put(activi.act.Event_ID__c, activi.act);
                }
                // 保存的时候为任务的报告一览赋值。
                //sla信息更新 zh start
                if(String.isBlank(activi.act.eventstatus__c) && !String.isBlank(activi.act.SLAReportInfo__c) && '合同季报'.equals(activi.act.Purpose_TypeFSE__c)){
                    eventCAndSLA.put(activi.act.SLAReportInfo__c,activi.act);
                    SLAIds.add(activi.act.SLAReportInfo__c);
                }
                if (String.isBlank(activi.act.eventstatus__c) && activi.act.UseReport__c && !activi.act.SLARecorded__c && activi.act.Related_Service1_ID__c!=null) {
                    mainCIds.add(activi.act.Related_Service1_ID__c);
                    eventCAndMainC.put(activi.act.Id, activi.act.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;
            }
            //20201106 zh CHAN-BUV2TF 保存时把报告一览带入任务 end

            //      } catch (Exception e) {
            //          Database.rollback(sp);
            //          // エラーメッセージを出す
            //ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
            //          error = true;
            //          return null;
            //      }
            // 任务和日报管理 2020-05-15 update by vivek start
            // 如果日报状态为“承认”，是通过事件和任务生成的报告一览，则更新对应任务的取消和延期信息。
            if('申請中'.equals(report.Status__c )){
                  XinDailyReportController.updateTask( report.id);
                //sla信息更新 zh start
                //2021-08-27 杨杰克 修改逻辑：是否逾期都调用saveSLADetails方法，将是否逾期传入方法，方法内做逻辑处理
                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);
                    }
                }

                //sla信息更新 zh end
                
                // 任务框架bug 应对 by zys start 原代码
                /*
                // 保存时更新任务的报告一览
                // 找出所有的事件。
                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,String> eventAndTaskMap = new Map<String,String>();
                // 报告一览和任务关联map
                Map<String,Event__c> eventCAndTaskMap = new Map<String,Event__c>();
                for(Activity activi :activities){
                    if(activi.act.eventstatus__c == '取消' && !String.isBlank(activi.act.Event_ID__c)){
                        // 更新任务取消信息
                        // 找出所有事件，再根据事件找到任务，再更新任务状态
                        eventCalId.add(activi.act.Event_ID__c);
                        eventCAndEventMap.put(activi.act.Event_ID__c, activi.act);
                    }
                    if(activi.act.eventstatus__c == '延期' && !String.isBlank(activi.act.Event_ID__c)){
                        // 更新任务延期信息
                        eventDlyId.add(activi.act.Event_ID__c);
                        eventCAndEventMap.put(activi.act.Event_ID__c, activi.act);
                    }
                    // 如果不是延期或取消，直接更新任务状态为完成
                    if(String.isBlank(activi.act.eventstatus__c) && !String.isBlank(activi.act.Event_ID__c)){
                        eventOkId.add(activi.act.Event_ID__c);
                        eventCAndEventMap.put(activi.act.Event_ID__c, activi.act);
                    }
                    // 保存的时候为任务的报告一览赋值。
                }
                // 找出所有的任务。
                List<task__c> taskupdateList = new List<task__c>();
                if(eventDlyId.size() > 0 || eventCalId.size() > 0 ){
                    List<Event> eventList = [select id,task_id__c from Event where id = :eventDlyId or id = :eventCalId];
                    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));
                        }
                        if(eventDlyId.contains(e.Id)){
                            ifCalDlyMap.put(e.task_id__c,'延期');
                        }
                        if(eventCalId.contains(e.Id)){
                            ifCalDlyMap.put(e.task_id__c,'取消');
                        }
                    }
                    // zh延期理由，取消理由
                    List<task__c> taskList = [select id,delayTaskDelay__c,Owner.Name,OwnerId,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];
                    // 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);
                                }
                            }
                        }
                    }
                    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

                    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;
                                // zh延期理由，取消理由
                                task.taskStatus__c = '04 取消';
                                task.cancelDate__c = Date.today();
                                task.Event__c = eventCAndTaskMap.get(task.Id).id;
                                taskupdateList.add(task);
                            }
                        }
                        // 如果延期，更新任务状态，延期时间delayToDate__c，延期理由delayReason__c，延期标记
                        // 1.如果延期日期是本月，创建新的事件，报告一览以及已接受的任务。
                        // 2.如果延期日期是下个月，创建新的事件，以及已接受的任务。
                        if(ifCalDlyMap.get(task.Id) == '延期'){
                            if(eventCAndTaskMap.containsKey(task.Id)){
                                // 更新任务状态等信息。
                                // 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;
                                // zh延期理由，取消理由
                                task.delayToDate__c = eventCAndTaskMap.get(task.Id).delayToDate__c;
                                task.taskStatus__c = '05 延期';
                                task.Event__c = eventCAndTaskMap.get(task.Id).id;
                                task.isDelay__c = true;
                                // task.Name = task.Owner.Name+' 测试任务 '+task.taskStatus__c;
                                taskupdateList.add(task);
                                // 延期日期是本月，创建新的事件，报告一览以及已接受的任务。 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);
                                    // dlyevt.Id = null;
                                    dlyevt.Event_ID__c = null;
                                    dlyevt.ActivityDate__c = dlyevt.delayToDate__c;
                                    dlyevt.whatid__c = eventCAndTaskMap.get(task.Id).whatid__c;
                                    // 日报soql优化 start
                                    
                                    if(reportDateIdMap.containsKey(dlyevt.ActivityDate__c)){
                                    // 判断延期日期是否有对应日报一览，因为非工作日不会生成日报一览。
                                        dlyevt.Id = null;
                                        insert dlyevt;
                                        
                                        dlyevt.Daily_Report__c = reportDateIdMap.get(dlyevt.ActivityDate__c);
                                        // 任务
                                        task__c delayTask = new task__c();
                                        delayTask.taskStatus__c = '02 接受'; // 状态
                                        delayTask.assignee__c = report.OwnerId; //被分配者
                                        delayTask.OwnerId = report.OwnerId;
                                        delayTask.ConfirmDate__c = Date.today(); //接受时间
                                        delayTask.Event__c = dlyevt.Id;
                                        delayTask.taskDifferent__c = '主动任务';
                                        if(task.taskDifferent__c == '被动任务' || task.delayTaskDelay__c == true){
                                            delayTask.delayTaskDelay__c = true;
                                        }
                                        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;//客户
                                        }
                                        
                                        delayTask.delayTaskP__c = task.Id;
                                        delayTask.Name = task.Name;
                                        insert delayTask;
                                        task.delayTask__c = delayTask.Id;
                                        // Datetime.addDays(dlybetweenDay)
                                        Integer dlybetweenDay = dlyevt.StartDateTime__c.date().daysBetween(dlyevt.delayToDate__c);
                                        dlyevt.StartDateTime__c = dlyevt.StartDateTime__c.addDays(dlybetweenDay);
                                        dlyevt.EndDateTime__c = dlyevt.EndDateTime__c.addDays(dlybetweenDay);
                                        // 事件
                                        Event dlyec = ControllerUtil.getEventList(dlyevt.Id);
                                        dlyec.task_id__c = delayTask.Id;
                                        update dlyec;

                                        dlyevt.Event_ID__c = dlyec.Id;
                                        dlyevt.eventStatus__c = null;
                                        // zh延期理由，取消理由
                                        dlyevt.CancelReason__c = null;
                                        dlyevt.cancelReasonOther__c = null;
                                        dlyevt.cancelReasonSelect__c = null;
                                        dlyevt.cancelReasonSelectFSE__c = null;
                                        dlyevt.delayReasonSelect__c = null;
                                        dlyevt.delayReasonSelectFSE__c = null;
                                        dlyevt.delayReasonOther__c = null;
                                        // zh延期理由，取消理由
                                        dlyevt.delayToDate__c = null;
                                        // zh延期理由，取消理由
                                        dlyevt.delayReason__c = null;
                                        // zh延期理由，取消理由
                                        update dlyevt;
                                    }else{
                                        // 非工作日，只生成事件
                                        // 任务
                                        task__c delayTask = new task__c();
                                        delayTask.taskStatus__c = '02 接受'; // 状态
                                        delayTask.assignee__c = report.OwnerId; //被分配者
                                        delayTask.OwnerId = report.OwnerId;
                                        // delayTask.taskDifferent__c = task.taskDifferent__c;
                                        delayTask.taskDifferent__c = '主动任务';
                                        if(task.taskDifferent__c == '被动任务' || task.delayTaskDelay__c == true){
                                            delayTask.delayTaskDelay__c = true;
                                        }
                                        delayTask.ConfirmDate__c = Date.today(); //接受时间
                                        // delayTask.Event__c = dlyevt.Id;
                                        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;//客户
                                        }
                                        delayTask.delayTaskP__c = task.Id;
                                        delayTask.Name = task.Name;
                                        insert delayTask;
                                        task.delayTask__c = delayTask.Id;
                                        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;
                                        insert dlyec;
                                    }
                                    // 延期日期是本月，创建新的事件，报告一览以及已接受的任务。 end
                                    // 延期日期是下个月，创建新的事件，以及已接受的任务。 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();
                                    delayTask.taskStatus__c = '02 接受'; // 状态
                                    delayTask.assignee__c = report.OwnerId; //被分配者
                                    delayTask.OwnerId = report.OwnerId;
                                    // delayTask.taskDifferent__c = task.taskDifferent__c;
                                    delayTask.taskDifferent__c = '主动任务';
                                    // 添加一个标记，标记改任务是被动任务的延期任务
                                    if(task.taskDifferent__c == '被动任务' || task.delayTaskDelay__c == true){
                                        delayTask.delayTaskDelay__c = true;
                                    }
                                    delayTask.ConfirmDate__c = Date.today(); //接受时间
                                    // delayTask.Event__c = dlyevt.Id;
                                    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;//客户
                                    }
                                    // delayTask.account__c = eventCAndTaskMap.get(task.Id).whatid__c; //客户
                                    delayTask.delayTaskP__c = task.Id;
                                    // delayTask.CreatedById = task.OwnerId;
                                    delayTask.Name = task.Name;
                                    insert delayTask;
                                    task.delayTask__c = delayTask.Id;
                                    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;
                                    insert dlyec;
                                    // 延期日期是下个月，创建新的事件，以及已接受的任务。 end
                                }else{

                                }

                            }
                        }
                        // if(taskupdateList.size() > 0){
                        //     update taskupdateList;
                        // }
                    }
                }
                // 如果有对应任务直接更新任务状态为完成。start
                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,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.cancelReason__c = eventCAndTaskMap.get(task.Id).cancelReason__c;
                                task.taskStatus__c= '03 完成';
                                // task.cancelDate__c = Date.today();
                                task.Event__c = eventCAndTaskMap.get(task.Id).id;
                                // task.Name = task.owner.Name+'测试任务'+task.taskStatus__c;
                                taskupdateList.add(task);
                            }
                        // }
                    }
                }
                if(taskupdateList.size() > 0){
                    update taskupdateList;
                }
        */
                // 任务框架bug 应对 by zys end
                // 如果有对应任务直接更新任务状态为完成。end
            }
            // if(report.Status__c == '申請中'){
            //     // 保存时更新任务的报告一览
            //     // 找出所有的事件。
            //     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,String> eventAndTaskMap = new Map<String,String>();
            //     // 报告一览和任务关联map
            //     Map<String,Event__c> eventCAndTaskMap = new Map<String,Event__c>();
            //     for(Activity activi :activities){
            //         // 如果不是延期或取消，直接更新任务状态为完成
            //         if(String.isBlank(activi.act.eventstatus__c) && !String.isBlank(activi.act.Event_ID__c)){
            //             eventOkId.add(activi.act.Event_ID__c);
            //             eventCAndEventMap.put(activi.act.Event_ID__c, activi.act);
            //         }
            //         // 保存的时候为任务的报告一览赋值。
            //     }
            //     // 如果有对应任务直接更新任务状态为完成。
            //     if(eventOkId != null){
            //         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));
            //             }
            //             // if(eventDlyId.contains(e.Id)){
            //             //     ifCalDlyMap.put(e.task_id__c,'延期');
            //             // }
            //             // if(eventCalId.contains(e.Id)){
            //             //     ifCalDlyMap.put(e.task_id__c,'取消');
            //             // }
            //         }
            //         // zh延期理由，取消理由
            //         List<task__c> taskList = [select id,Owner.Name,OwnerId,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];
            //         // List<task__c> taskList = [select id,owner.Name,name,cancelDate__c,taskStatus__c,Event__c,delayToDate__c,isDelay__c from task__c where id = :taskId];
            //         // zh延期理由，取消理由
            //         // List<task__c> taskList = [select id,name,cancelDate__c,taskStatus__c,Event__c,delayToDate__c,delayReason__c,isDelay__c from task__c where id = :taskId];
            //         List<task__c> taskupdateLista = new List<task__c>();
            //         for(task__c task : taskList){
            //             // 如果取消，更新任务状态，取消理由，取消时间
            //             // if(ifCalDlyMap.get(task.Id) == '取消'){
            //                 if(eventCAndTaskMap.containsKey(task.Id)){
            //                     // task.cancelReason__c = eventCAndTaskMap.get(task.Id).cancelReason__c;
            //                     task.taskStatus__c= '03 完成';
            //                     // task.cancelDate__c = Date.today();
            //                     task.Event__c = eventCAndTaskMap.get(task.Id).id;
            //                     task.Name = task.owner.Name+'测试任务'+task.taskStatus__c;
            //                     taskupdateLista.add(task);
            //                 }
            //             // }
            //         }
            //         if(taskupdateLista.size() > 0){
            //             update taskupdateLista;
            //         }
            //     }
            // }
            // 任务和日报管理 2020-05-15 update by vivek end
            //*************************Create 20160614 No.153 趙徳芳 Start*************************//
        PageReference ref = 
        new Pagereference('/apex/XinDailyReport?id='+
            EsetId+'&completion=true&event='
            +eventFlg+'&eventMsg='+eventMessage+'&etAPPMsg='+etAPPerrorMsg+'&etAPPFlg='+etAPPFlg);
        ref.setRedirect(true);
        //*************************Create 20160614 No.153 趙徳芳 End***************************//        


        return ref;
    }
    // 任务框架bug 应对 by zys start 提出来放到future里面去
    @future
    private static void updateTask(string reportid){

        //Savepoint sp = Database.setSavepoint();

        String logstr =  ' start\n';
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Type__c = 'XinDailyReportController';
        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,
                                                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 = :eventDlyId or id = :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)){
                        // if(e.task_id__c != null && e.task_id__c != ''){
                            ifCalDlyMap.put(e.task_id__c,'延期');
                        // }else{
                        //     e.EventStatus__c = '05 延期';
                        //     updateEventList.add(e);
                        // }
                        
                    }
                    if(eventCalId.contains(e.Id)){
                        // if(e.task_id__c != null && e.task_id__c != ''){
                            ifCalDlyMap.put(e.task_id__c,'取消');
                        // }else{
                        //     e.EventStatus__c = '04 取消';
                        //     updateEventList.add(e);
                        // }
                    }
                    //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 = :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';
                                //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;
                                System.debug('页面的理由:'+eventCAndTaskMap.get(task.Id).CancelReason__c);
                                System.debug('日报中OPD取消理由Map:'+TaskAndOPDMapping);
                                System.debug('日报中OPD取消理由:'+reason);
                                System.debug('日报中OPD取消理由为null:'+(reason == null));
                                System.debug('日报中OPD取消理由为空字符串:'+(''.equals(reason)));
                                //2021-11-02  mzy  任务管理改善  end
                                
                                // if('客户事件变更或冲突'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '医院取消试用';
                                // }else if('与其他突发事件冲突'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '计划调整变更';
                                // }else if('问题已经解决无需拜访'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '问题已解决无需OPD';
                                // }else if('无合适病例（适合病例流失）OPD取消'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '手术取消';
                                // }else if('问题已解决无需OPD'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '问题已解决无需OPD';
                                // }else if('客户已采购竞品，失单'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '客户已采购竞品，失单';
                                // }else if('客户取消OPD'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '医院取消试用';
                                // }else if('计划重复'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '计划重复';
                                // }else if('其他'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '其他';
                                // }
                                // //2021-09-08 Yjk 补充条件
                                // else if('已失单'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '其他';
                                // }else if('已订货'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '其他';
                                // }else if('与客户安排冲突'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '其他';
                                // }else if('上月已跟进'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '其他';
                                // }else if('项目暂停'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '其他';
                                // }else if('医院建设中'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '其他';
                                // }else if('项目取消'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '其他';
                                // }else if('任务分配不准'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '其他';
                                // }else if('订货推迟'.equals(eventCAndTaskMap.get(task.Id).CancelReason__c)){
                                //     tempCancelPostponePlan.cancelReasonCombobox__c = '其他';
                                // }

                                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)) { //20210429 zh SWAG-C2HCCB 任务状态修改
                            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';
                                    //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;
                                    //2021-11-02   mzy  任务管理改善开发计划  end
                                    // if('客户时间变更或冲突'.equals(eventCAndTaskMap.get(task.Id).delayReason__c)){
                                    //     tempCancelPostponePlan.cancelReasonCombobox__c = '医院试用改期';
                                    // }else if('与其他突发事件冲突'.equals(eventCAndTaskMap.get(task.Id).delayReason__c)){
                                    //     tempCancelPostponePlan.cancelReasonCombobox__c = '工作计划变化';  
                                    // }else if('备品未到'.equals(eventCAndTaskMap.get(task.Id).delayReason__c)){
                                    //     tempCancelPostponePlan.cancelReasonCombobox__c = '备品到货推迟';  
                                    // }else if('无合适病例(适合病例流失)OPD延期'.equals(eventCAndTaskMap.get(task.Id).delayReason__c)){
                                    //     tempCancelPostponePlan.cancelReasonCombobox__c = '手术改期';  
                                    // }else if('日期填写错误'.equals(eventCAndTaskMap.get(task.Id).delayReason__c)){
                                    //     tempCancelPostponePlan.cancelReasonCombobox__c = '日期填写错误';  
                                    // }else if('医院设备不到位'.equals(eventCAndTaskMap.get(task.Id).delayReason__c)){
                                    //     tempCancelPostponePlan.cancelReasonCombobox__c = '医院设备不到位';  
                                    // }else if('其他'.equals(eventCAndTaskMap.get(task.Id).delayReason__c)){
                                    //     tempCancelPostponePlan.cancelReasonCombobox__c = '其他';  
                                    // }
                                    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);
                                    // dlyevt.Id = null;
                                    // dlyevt.Event_ID__c = null;
                                    // dlyevt.ActivityDate__c = dlyevt.delayToDate__c;
                                    // dlyevt.whatid__c = eventCAndTaskMap.get(task.Id).whatid__c;
                                    // 日报soql优化 start
                                    
                                    if(reportDateIdMap.containsKey(dlyevt.delayToDate__c)){
                                    // 判断延期日期是否有对应日报一览，因为非工作日不会生成日报一览。
                                        // dlyevt.Id = null;
                                        // insert dlyevt;
                                        
                                        // dlyevt.Daily_Report__c = reportDateIdMap.get(dlyevt.ActivityDate__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
                                        // Datetime.addDays(dlybetweenDay)
                                        Integer dlybetweenDay = dlyevt.StartDateTime__c.date().daysBetween(dlyevt.delayToDate__c);
                                        // dlyevt.StartDateTime__c = dlyevt.StartDateTime__c.addDays(dlybetweenDay);
                                        // dlyevt.EndDateTime__c = dlyevt.EndDateTime__c.addDays(dlybetweenDay);
                                        //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]; 
                                            }
                                            dlyec.EventStatus__c = '02 接受';
                                            insert dlyec;
                                        }
                                        //2021-08-26 mzy SWAG-C66D37 【委托】日报取消，OPD计划取消  start

                                        // dlyevt.Event_ID__c = dlyec.Id;
                                        // dlyevt.eventStatus__c = null;
                                        // zh延期理由，取消理由
                                        // dlyevt.CancelReason__c = null;
                                        // dlyevt.cancelReasonOther__c = null;
                                        // dlyevt.cancelReasonSelect__c = null;
                                        // dlyevt.cancelReasonSelectFSE__c = null;
                                        // dlyevt.delayReasonSelect__c = null;
                                        // dlyevt.delayReasonSelectFSE__c = null;
                                        // dlyevt.delayReasonOther__c = null;
                                        // zh延期理由，取消理由
                                        // dlyevt.delayToDate__c = null;
                                        // zh延期理由，取消理由
                                        // dlyevt.delayReason__c = null;
                                        // zh延期理由，取消理由
                                        // update dlyevt;
                                    }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
                                    }
                                    // 延期日期是本月，创建新的事件，报告一览以及已接受的任务。 end
                                    // 延期日期是下个月，创建新的事件，以及已接受的任务。 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 将报告一览的结果写入任务的反馈内容
                                    //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.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{

                                }

                            }
                        }
                    }
                    // if(taskupdateList.size() > 0){
                    //     update taskupdateList;
                    // }
                }
            }
            // 如果有对应任务直接更新任务状态为完成。start
            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){
                    // if(e.task_id__c != null && e.task_id__c != ''){
                        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);
                        }
                    // }else{
                    //     e.EventStatus__c = '03 完成';
                    //     updateEventList.add(e);
                    // }

                    //2021-09-07   mzy SWAG-C5784H 【委托】事件无法延期 start
                    //如果事件的任务为空,则将事件改为 03 完成
                    if(String.IsBlank(e.task_id__c)){
                        e.EventStatus__c = '03 完成';
                        e.EventC_ID__c = eventCAndEventMap.get(e.Id).id;
                        updateEventList.add(e);
                    }
                    //2021-09-07   mzy SWAG-C5784H 【委托】事件无法延期 end
                    
                }
                // 获取任务
                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.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
                        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);
                        }
                        //20210429 zh SWAG-C2HCCB 任务状态修改 end
                        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);
                    }
                }
            }
            //20210429 zh SWAG-C2HCCB 任务状态修改 end
            //2022-02-07  mzy  日志修改 start
            //taskupdateList[0].distributionCount__c = Decimal.valueOf('1212121121121');
            //2022-02-07  mzy  日志修改 end
            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();
            //2022-02-07  mzy 日志修改  start            
            //Database.rollback(sp);
            //iflog.ErrorLog__c = 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();
            //2022-02-07  mzy 日志修改  end
            insert iflog;
            
            //Database.rollback(sp);
        }
    }
      // 任务框架bug 应对 by zys end 提出来放到future里面去
    /**　反馈保存　*/
    public PageReference saveComment() {
        error = false;
        List<Activity> actList = new List<Activity>();
        // 保存ボタンが押された場合
        actList = activities;
        
        List<Event__c> save_eventsAct = new List<Event__c>();
        // savepoint
        Savepoint sp = Database.setSavepoint();
        try {
            for (Integer i = 0; i < actList.size(); i++) {
                if (actList[i].act.Id != null) {
                    Event__c event = new Event__c(
                        id = actList[i].act.Id,
                        Minister_Comment__c = actList[i].act.Minister_Comment__c,
                        Manager_Comment__c = actList[i].act.Manager_Comment__c
                    );
                    save_eventsAct.add(event);
                }
            }

            // システム管理者権限で更新
            ControllerUtil.upsEventC(save_eventsAct);
            
        } catch (Exception e) {
            Database.rollback(sp);
            // エラーメッセージを出す
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
            error = true;
            return null;
        }

        PageReference pageRef = new PageReference('/apex/XinDailyReport?id=' + System.currentPageReference().getParameters().get('id'));
        pageRef.setRedirect(true);
        return pageRef;
    }

    /**　追加ボタン　*/
    public void addActivity() {
        Event__c e = new Event__c();
        Date d = date.today();
        e.ActivityDateTime__c = Datetime.newInstance(d.year(), d.month(), d.day(), 8, 45, 0);
        
        Activity a = new Activity();
        a.act = e;
        a.act.Daily_Report__c = report.Id;
        a.index = activities.size();
        // 20200420 任务日报管理 add gzw start
        a.stringIndex = ''+a.index;
        // 20200420 任务日报管理 add gzw end
        activities.add(a);
        actSize = activities.size();
        //Add log by Li Jun 20220407 Start
        system.debug('Activity Data:'+JSON.serialize(activities));
         //Add log by Li Jun 20220407 end
    }
    
    public String delIndex {
        get;
        set {
            delIndex = value;
        }
    }
    
    /**　削除ボタン　*/
    public void deleteActivity() {
        Integer del = Integer.valueOf(delIndex);
        Activity a = activities.get(del);
        // 本当のEventCの場合、EventC削除（トリガにて関連するEvent削除）
        if (!String.isBlank(a.act.id)) {
            ControllerUtil.eventDel(a.act.id);
        // 偽りのEventC（Eventから変換され、画面上に表示だけ、DBにない）の場合、Event削除
        } else {
            if (!String.isBlank(a.act.Event_ID__c)) {
                ControllerUtil.delEventOnly(a.act.Event_ID__c);
            }
        }
        
        activities.remove(del);
        Activity aIndex = new Activity();
        for (Integer i = 0; i < activities.size(); i++) {
            aIndex = activities.get(i);
            aIndex.index = i;
            // 20200420 任务日报管理 add gzw start
            aIndex.stringIndex = ''+aIndex.index;
            // 20200420 任务日报管理 add gzw end
        }
        actSize = activities.size();
    }

    /**　取消活动　*/
    public void calcelActivity() {
        Integer del = Integer.valueOf(delIndex);
        Activity a = activities.get(del);
        // 本当のEventCの場合、EventC削除（トリガにて関連するEvent削除）
        if (!String.isBlank(a.act.id)) {
            ControllerUtil.eventDel(a.act.id);
        // 偽りのEventC（Eventから変換され、画面上に表示だけ、DBにない）の場合、Event削除
        } else {
            if (!String.isBlank(a.act.Event_ID__c)) {
                ControllerUtil.delEventOnly(a.act.Event_ID__c);
            }
        }
        
        activities.remove(del);
        Activity aIndex = new Activity();
        for (Integer i = 0; i < activities.size(); i++) {
            aIndex = activities.get(i);
            aIndex.index = i;
            // 20200420 任务日报管理 add gzw start
            aIndex.stringIndex = ''+aIndex.index;
            // 20200420 任务日报管理 add gzw end
        }
        actSize = activities.size();
    }
    
    /**　活動区分選択リスト　*/
    /*
    public Event__c setPurposeType(Event__c act, String purposeType){
        if(purposeType == null || purposeType == ''){
            return act;
        }
        
        if(purposeType == '礼节性拜访'){
            act.Courtesy_Call__c = true;
        }
        else if(purposeType == '客户咨询对应'){
            act.Customer_Advisory_Corresponding__c = true;
        }
        else if(purposeType == '学会or展会对应'){
            act.Campain_Or_Event__c = true;
        }
        else if(purposeType == '信息搜集'){
            act.Infomation_Collection__c = true;
        }
        else if(purposeType == '产品介绍or推广'){
            act.Product_Or_Introduction__c = true;
        }
        //else if(purposeType == 'OPD'){
        //    act.OPD__c = true;
        //}
        else if(purposeType == '询价or维修询价跟进'){
            act.Inquiry_Or_MaintenanceInquiry__c = true;
        }
        else if(purposeType == '经销商协助or拜访'){
            act.Dealerassist_Or_Visit__c = true;
        }
        else if(purposeType == '合同商谈'){
            act.Contract_Negotiations__c = true;
        }
        else if(purposeType == '参加招标'){
            act.Participate_In_The_Tender__c = true;
        }
        else if(purposeType == '签订合同'){
            act.Signed_Contract__c = true;
        }
        else if(purposeType == '納品(装机)'){
            act.Satisfiedgoods_Installed__c = true;
        }
        else if(purposeType == '送or取设备'){
            act.Send_Or_Take_Equipment__c = true;
        }
        else if(purposeType == '送or取文件类资料'){
            act.Send_Or_Take_Fileclass__c = true;
        }
        else if(purposeType == '跟台'){
            act.With_Taiwan__c = true;
        }
        else if(purposeType == '新品装机使用保养培训'){
            act.New_Installed_Maintenance_Training__c = true;
        }
        //else if(purposeType == 'NTC/TTC'){
        //    act.NTC__c = true;
        //}
        else if(purposeType == '点検'){
            act.Checking__c = true;
        }
        else if(purposeType == '巡回'){
            act.Come_Around__c = true;
        }
        //else if(purposeType == 'ON-CALL'){
        //    act.ON_CALL__c = true;
        //}
        else if(purposeType == '修理説明'){
            act.Repair_Explanation__c = true;
        }
        else if(purposeType == '投诉対応(含QIS）'){
            act.Complaint_Including_QIS__c = true;
        }
        else if(purposeType == '回款'){
            act.Back_Section__c = true;
        }
        else if(purposeType == '备品检查'){
            act.Spare_Inspection_Probes__c = true;
        }
        else if(purposeType == '小修理对应'){
            act.Repair_Low_Level__c = true;
        }
        else if(purposeType == '开会'){
            act.Meeting__c = true;
        }
        else if(purposeType == '培训'){
            act.Train__c = true;
        }
        else if(purposeType == '顧客訪問対応'){
            act.Customer_Access__c = true;
        }
        else if(purposeType == '准备资料'){
            act.Data_Thus__c = true;
        }
        else if(purposeType == '电话拜访'){
            act.Phone_Call__c = true;
        }
        else if(purposeType == '会議参加'){
            act.Meeting_Participants__c = true;
        }
        else if(purposeType == '产品培训'){
            act.Product_Training__c = true;
        }
        else if(purposeType == '询价进行活动'){
            act.Inquiry_Activities__c = true;
        }
        else if(purposeType == '售后事宜'){
            act.Aftermarket_Matters__c = true;
        }
        else if(purposeType == '库存管理'){
            act.Inventory_Management__c = true;
        }
        else if(purposeType == '移動'){
            act.Move__c = true;
        }
        else if(purposeType == '休暇'){
            act.Vacation__c = true;
        }
        
        return act;
    }
    */

    /**　活動内部クラス　*/
    class Activity {
        public Integer index {get;set;}
        // 20200420 任务日报管理 add gzw start
        public string stringIndex {get;set;}
        public string cancelReason {get;set;}
        public string delayReason {get;set;}
        public String taskDifferent {get;set;}
        public boolean delayTaskDelay {get;set;}
        public Date delayToDate {get;set;}
        public Date latestDate {get;set;} //20210430 SWAG-C2HCCB 任务状态修改
         // 20200420 任务日报管理 add gzw end

        public String oldLocation {get;set;}
        public String oldLocationId {get;set;}
        public Event__c act {get;set;}
        //2021-09-18  mzy 任务管理改善开发  start
        public Task__c tsk {get;set;}
        public Boolean isTaskBlank {get;set;}
        public String EventStatus {get;set;}
        //2021-09-18  mzy  任务管理改善开发 end
        public Activity_History_Daily_Report__c ah1 {get;set;}
        public Activity_History_Daily_Report__c ah2 {get;set;}
        public Activity_History_Daily_Report__c ah3 {get;set;}
        public Activity_History_Daily_Report__c ah4 {get;set;}
        public Activity_History_Daily_Report__c ah5 {get;set;}
        public Event_Oppotunity__c eo1 {get;set;}
        public Event_Oppotunity__c eo2 {get;set;}
        public Event_Oppotunity__c eo3 {get;set;}
        public Event_Oppotunity__c eo4 {get;set;}
        public Event_Oppotunity__c eo5 {get;set;}
        public Report__c rProduct {get;set;}
        public User reportOwner{get;set;}
        public boolean pt1ErrorFlg{get;set;}
        //public boolean pt2ErrorFlg{get;set;}
        //public boolean pt3ErrorFlg{get;set;}
        //public boolean pt4ErrorFlg{get;set;}
        //public boolean pt5ErrorFlg{get;set;}
        //public String pt1ErrorMessage{get;set;}
        //public String pt2ErrorMessage{get;set;}
        //public String pt3ErrorMessage{get;set;}
        //public String pt4ErrorMessage{get;set;}
        //public String pt5ErrorMessage{get;set;}
        public String actStartHourText{get;set;}
        public String actStartMinuteText{get;set;}
        public String actEndHourText{get;set;}
        public String actEndMinuteText{get;set;}
        public boolean actErrorFlg1{get;set;}
        public boolean actErrorFlg2{get;set;}
        public String actErrorMessage1{get;set;}
        public String actErrorMessage2{get;set;}
        public String planStartHourText{get;set;}
        public String planStartMinuteText{get;set;}
        public String planEndHourText{get;set;}
        public String planEndMinuteText{get;set;}
        public String planPurposeText{get;set;}
        public boolean planErrorFlg1{get;set;}
        public boolean planErrorFlg2{get;set;}
        public boolean planErrorFlg3{get;set;}
        public String planErrorMessage1{get;set;}
        public String planErrorMessage2{get;set;}
        public String planErrorMessage3{get;set;}
        public boolean isDisabledVisitorPlace{get;set;}

        
        public Activity() {
            index = 0;
            // 20200420 任务日报管理 add gzw start
            stringIndex = ''+index;
            // 20200420 任务日报管理 add gzw end
            oldLocation = null;
            oldLocationId = null;
            act = new Event__c();
            //2021-09-18  mzy 任务管理改善开发  start
            tsk = new Task__c();
            isTaskBlank = true;
            EventStatus = '';
            //2021-09-18  mzy  任务管理改善开发 end
            ah1 = new Activity_History_Daily_Report__c();
            ah2 = new Activity_History_Daily_Report__c();
            ah3 = new Activity_History_Daily_Report__c();
            ah4 = new Activity_History_Daily_Report__c();
            ah5 = new Activity_History_Daily_Report__c();
            eo1 = new Event_Oppotunity__c(); eo2 = new Event_Oppotunity__c(); eo3 = new Event_Oppotunity__c(); eo4 = new Event_Oppotunity__c(); eo5 = new Event_Oppotunity__c();rProduct = new Report__c();
            
            reportOwner = new User();pt1ErrorFlg = false;
            //pt2ErrorFlg = false;
            //pt3ErrorFlg = false;
            //pt4ErrorFlg = false;
            //pt5ErrorFlg = false;
            //pt1ErrorMessage = '';
            //pt2ErrorMessage = '';
            //pt3ErrorMessage = '';
            //pt4ErrorMessage = '';
            //pt5ErrorMessage = '';
            actStartHourText = '';
            actStartMinuteText = '';
            actEndHourText = '';
            actEndMinuteText = '';
            actErrorMessage1 = '';
            actErrorMessage2 = '';
            planStartHourText = '';
            planStartMinuteText = '';
            planEndHourText = '';
            planEndMinuteText = '';
            planErrorMessage1 = '';
            planErrorMessage2 = '';
            planErrorMessage3 = '';
            isDisabledVisitorPlace = true;
        }
    }
    
    /**　報告書ボタン　*/
    /**　新規リードボタン　*/
    /**　新規 保有设备 ボタン　*/
    // TODO 新規時のみsave
    public PageReference openPDNew(){
        //判断是否有权限新建备品借出申请
        
        save();
        return null;
    }
    
    // 新建solution项目需求
    public PageReference openPDNewSol(){
        
        return null;
    }
    //20210603 zh ETAPP与日报联动 start
    public PageReference updateETAPPFlag(){
        if(upsertActIndex != null && upsertActIndex != ''){
            activities.get(Integer.valueOf(upsertActIndex)).act.ETAPPAct__c = true;
        }
        save();
        return null;
    }
    //20210603 zh ETAPP与日报联动 end
    /** 0埋め処理　 */
    public String zeroFill(String str){
        if(str.length() == 2){
            return str;
        }
        else{
            return '0' + str;
        }    
    }
    
    // 2018/11/21 SWAG-B6Q8BS 判断是否需要弹窗更新客户信息 start
    public void CheckAlertInputDep() {
        Alertlines = '';
        IsAlertInputDep = false;
        
        list<ID> DepIDList = new list<ID>();
        for (Integer i = 0; i < activities.size(); i++) {
            Activity a = activities.get(i);
            a.act.IsAlertInputDep__c = false;   
            if (a.act.whatid__c != null && a.act.whatid__c.startsWith('001')) {
                DepIDList.add(a.act.whatid__c);
            }
        }
        if(DepIDList.size() == 0){
            return;
        }
        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++) {
                Activity a = activities[i];
                if (a.act.whatid__c != null && a.act.whatid__c.startsWith('001')) {
                   system.debug('进来了'+a.act.whatid__c);
                    if(DepartMap.get(a.act.whatid__c)!=null && 
                        ANCLMap.get(DepartMap.get(a.act.whatid__c).ParentId) ==null){
                        IsAlertInputDep = true;
                        a.act.IsAlertInputDep__c = true;
                        if(Alertlines.equals('')){
                            Alertlines = ''+ i;
                        }else{
                            Alertlines+= '||' + i;
                        }

                    }
                }
            }
        }
    }
    // 2018/11/21 SWAG-B6Q8BS 判断是否需要弹窗更新客户信息 end
    
    public Pagereference homeBack(){
        return new Pagereference(URL.getSalesforceBaseUrl().toExternalForm() + '/home/home.jsp');
    }
    
    public Pagereference dailyBack(){
        Pagereference re = save();
        if(error){
            return null;
        }
        else{
            return new Pagereference(URL.getSalesforceBaseUrl().toExternalForm() + '/a0A/o');
        }
    }

    private List<Event> getNextEventList(Set<Id> eIdList) {
        return [
            select  Id, NextEventC_ID__c, EventC_ID__c,
                    Subject, StartDateTime, EndDateTime, Main_Visit_Location__c,
                    Location, whatId__c, Activity_Type2__c,
                    Purpose_Type__c,OPDPlan_Flag__c,
                    Related_Opportunity1__c,
                    Related_Opportunity1_ID__c,
                    Related_Service1__c,
                    Related_Service1_ID__c,
                    Description
            from Event where NextEventC_ID__c in :eIdList
        ];
    }
    
    private List<Event__c> sortEventC(List<Event__c> ecList) {
        Boolean needSort = true;
        List<Event__c> rtnList = ecList;
        
        while (needSort) {
            needSort = false;
            
            for (Integer i = 0; i < rtnList.size() - 1; i++) {
                Event__c nowEc = rtnList[i];
                Event__c nextEc = rtnList[i + 1];
                if (nowEc.StartDateTime__c > nextEc.StartDateTime__c) {
                    rtnList.set(i, nextEc);
                    rtnList.set(i + 1, nowEc);
                    needSort = true;
                // 開始時間同じなら、終了時間を比較（念のため）
                } else if (nowEc.StartDateTime__c == nextEc.StartDateTime__c) {
                    if (nowEc.EndDateTime__c > nextEc.EndDateTime__c) {
                        rtnList.set(i, nextEc);
                        rtnList.set(i + 1, nowEc);
                        needSort = true;
                    }
                } else {}
            }
        }
        
        return rtnList;
    }
    private 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,
                                            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;
    }

    // 任务和日报管理 2020-05-15 update by vivek start
    // 取消后保存一遍日报和报告一览。
    public PageReference cancelSave(){
        // 取消必须是作成中才可以取消。
        List<Event__c> cancelSaveList = new List<Event__c>();
        Integer del = Integer.valueOf(delIndex);
        // Activity a = activities.get(del);
        if(report.Status__c == '作成中'){
            for(Integer i = 0 ; i < activities.size(); i++){
                if(i == del){
                    activities[i].act.eventStatus__c = '取消';
                }
                // activities[i].act.ActivityDate__c = report.Reported_Date__c;
                // cancelSaveList.add(activities[i].act);
            }
            // for(Activity actf :activities){
            //     cancelSaveList.add(actf.act);
            // }
            // ControllerUtil.upsEventC(cancelSaveList);
        }
        // PageReference ref = 
        // new Pagereference('/apex/XinDailyReport?id='+
        //     EsetId);
        // ref.setRedirect(true);   
        // return ref;
        return save();
    }
    public PageReference delaysave(){
        // 延期必须是作成中才可以延期。
        List<Event__c> delaySaveList = new List<Event__c>();
        Integer del = Integer.valueOf(delIndex);
        // Activity a = activities.get(del);
        if(report.Status__c == '作成中'){
            //20210624 zh 当延期至时间的日报状态不是草案中时，不能延期 start
            List<Daily_Report__c> delayToReport = [SELECT Id,Status_With_Check__c FROM Daily_Report__c WHERE Reported_Date__c = :activities[del].delayToDate and Reporter__c = :UserInfo.getUserId()];
            if (delayToReport.size() > 0 && delayToReport[0] != null && delayToReport[0].Status_With_Check__c != '草案中') {
                activities[del].act.delayToDate__c.addError('只能延期到草案中的日报。');
                error = true;
                return null;
            }
            //20210624 zh 当延期至时间的日报状态不是草案中时，不能延期 start
            for(Integer i = 0 ; i < activities.size(); i++){
                if(i == del){
                    // 是否可以延期判断
                    // if(activities[i].act.Event_ID__c == null){
                    //     // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '手动添加的日报明细，不支持延期。'));
                    //     activities[i].act.delayToDate__c.addError('手动添加的日报明细，不支持延期，请取消。');
                    //     return null;
                    // }
                    // // 延期对日期的判断。
                    // if(activities[i].delayToDate.year() != report.Reported_Date__c.year() || activities[i].delayToDate.Month() !=  report.Reported_Date__c.Month()){
                    //     // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '只能延期到当月或者下个月。'));
                    //     errorMessage = '只能延期到本月或者下个月。';
                    //     // activities[i].delayToDate.addError('只能延期到本月或者下个月。');
                    //     // eventFlg = false;
                    //     error = true;
                    //     // return null;
                    // }
                    // if(activities[i].delayToDate.year() != report.Reported_Date__c.year() || activities[i].delayToDate.Month() !=  report.Reported_Date__c.Month()+1){
                    //     // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '只能延期到当月或者下个月。'));
                    //     errorMessage = '只能延期到本月或者下个月。';
                    //     // activities[i].delayToDate.addError('只能延期到本月或者下个月。');
                    //     // eventFlg = false;
                    //     error = true;
                    //     // return null;
                    // }

                    activities[i].act.eventStatus__c = '延期';
                }
                // activities[i].act.ActivityDate__c = report.Reported_Date__c;
                // cancelSaveList.add(activities[i].act);
            }
            // for(Activity actf :activities){
            //     cancelSaveList.add(actf.act);
            // }
            // ControllerUtil.upsEventC(cancelSaveList);
        }
        // PageReference ref = 
        // new Pagereference('/apex/XinDailyReport?id='+
        //     EsetId);
        // ref.setRedirect(true);   
        // return ref;
        return save();
    }
    // 任务和日报管理 2020-05-15 update by vivek end

    @TestVisible
    public static void testI() {
        
    }

    
    @TestVisible
    public static void testY() {
    }
}