public class SimpleEventRegisterController {

    private static final String HOSPITAL_STRING = '病院';
    private static final String AGENCY_STRING = '販売店';
    private static final String CAMPAIGN_STRING = '社外イベント';
    private static final String DEP_TYPE = '診療科';
    private static final String AGY_TYPE = '販売店';

    public boolean isHospital { get; set; }
    public boolean isAgent { get; set; }
    public boolean isTraining { get; set; }
    public boolean isCampaign { get; set; }
    public boolean isNone { get; set; }
    public boolean isDisable { get; set; } //20200827 禁止修改访问场所 zh
    public boolean isShowService {get; set;} //20200922 SWAG-BS6BYA 推广人员禁止选择维修合同 zh
    public boolean isDisService {get; set;} //20201221 接收任务禁止修改维修合同 zh
    public boolean isDisPlanProd {get; set;} 
    public boolean allDisable {get; set;} //20210522 zh WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步
    //2021-06-09 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 start
    //所有类型的事件编辑时都不允许改 科室 和拜访区分
    public boolean isDisActivityCategory {get; set;}
    //2021-06-09 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 end
    //2021-06-17 mzy  任务类型是SLA  被动任务 拜访目的不能修改 
    public boolean isDisActivityPurposeFSE {get; set;}
    public boolean isDisActivityPurposeEscFSE {get; set;}
    //2021-06-17 mzy 任务类型是SLA  被动任务 拜访目的不能修改     
    //2021-08-10  mzy  update  SWAG-C5R6GW   询价任务新增字段  start
    //延期时不可以更新询价
    public boolean isOppSelect {get;set;}
    //2021-08-10  mzy  update  SWAG-C5R6GW   询价任务新增字段  end
    //20201104 SFDC-BUF6KM opd被动任务显示战略科室 zh start
    public boolean isDisableDepart {get; set;} 
    public boolean isShowDepartment {get; set;} 
    public String DepartmentName { get; set; } 
    public boolean isOpdDisable { get; set; } 
    public List<Account> accounts;
    //20201104 SFDC-BUF6KM opd被动任务显示战略科室 zh end

    public Event targetEvent { get; set; }

    public User LoginUser {get; set;}
    private String retURL = null;
    private String evt4 = null;
    private String evt13 = null;
    private String newURL = null;

    private String aid = null;
    private String cid = null;
    private String oid = null;
    private String mid = null;

    // 任务和日报管理开发 update by vivek 2020-04-13 start
    private String taskId = null;
    private String isDelay = null;
    //lightning修改hql 20231026 start
    private String isDelayURL = null;
    private String isBefore = null;
    //lightning修改hql 20231026 end
    public task__c task;
    public task__c taskActive;
    public task__c delayTask;
    public List<task__c> taskList = new List<task__c>();
    // 任务和日报管理开发 update by vivek 2020-04-13 start

    public List<Rental_Equipment__c> prods {get;set;}
    public Map<String,String> planProducts {get;set;}

    // CHAN-B9M9KA start
    private string source;
    // CHAN-B9M9KA end

    //20210324 zh WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 start
    private String eventId = null;
    public Boolean isEdit {get; set;}
    //20210324 zh WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 end

    //2021-04-27  mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  add  start
    private Datetime EventStartDate;
    private Integer EventDurationInMinutes;
    //2021-04-27  mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  add  end
    //2021-07-28  mzy SWAG-C4YB9J  事件页面优化  add start
    private DateTime EventEndDate;
    private String opdId = null;
    //2021-07-28  mzySWAG-C4YB9J  事件页面优化  add  end
    //2021-04-28  mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  add  start
    private Event delayEvent;
    //2021-04-28  mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  add  end
    //2021-12-06  mzy SWAG-C9ADM5 【委托】 [询价任务]主动任务创建时点相关信息没有保存  start
    private Boolean isSaveAndNew;
    //2021-12-06  mzy SWAG-C9ADM5 【委托】 [询价任务]主动任务创建时点相关信息没有保存  end

    //2021-10-20  mzy  任务管理改善   start
    private Boolean IsGeneratePlan;  //是否生成计划
    //2021-10-20  mzy  任务管理改善   end


    //deloitee-zhj 20231204 PIPL还原
    //Add By Li Jun 20220224 for PIPL start
    // public String idVisitor1PI{set;get;}
    // public String idVisitor2PI{set;get;}
    // public String staticResource {get; set;}
    // public String contactAWSIds{set;get;}
    //Add By Li Jun 20220224 for PIPL end
    // DB202312088802 hql 20231214 添加自定义主题 start
    public String subjectPerson{set;get;}
    // DB202312088802 hql 20231214 添加自定义主题 end
    
    public SimpleEventRegisterController(ApexPages.StandardController controller) {
        this.isHospital = true;
        this.isAgent = false;
        this.isCampaign = false;
        this.isNone = false;
        this.isDisable = false;
        this.isShowService = true; //20200922 SWAG-BS6BYA 推广人员禁止选择维修合同 zh
        //20201104 SFDC-BUF6KM opd被动任务显示战略科室 zh start
        this.isDisableDepart = false;
        this.isShowDepartment = false; 
        this.DepartmentName = ''; 
        this.isOpdDisable = false;
        this.accounts = new List<Account>();
        //20201104 SFDC-BUF6KM opd被动任务显示战略科室 zh end
        this.isDisService = false; //20201221 接收任务禁止修改维修合同 zh
        //2021-06-09 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 start
        //所有类型的事件编辑时都不允许改 科室 和拜访目的
        this.isDisActivityCategory = false;
        //2021-06-09 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 end
        //2021-06-17 mzy  任务类型是SLA 被动任务  拜访目的不能修改 
        this.isDisActivityPurposeFSE = false;
        this.isDisActivityPurposeEscFSE = false;
        //2021-06-17 mzy 任务类型是SLA  被动任务 拜访目的不能修改

        //2021-08-10  mzy  update  SWAG-C5R6GW   询价任务新增字段  start
        //延期时不可以更新询价
        this.isOppSelect = false;
        //2021-08-10  mzy  update  SWAG-C5R6GW   询价任务新增字段  end
        //2021-12-06  mzy SWAG-C9ADM5 【委托】 [询价任务]主动任务创建时点相关信息没有保存  start
        this.isSaveAndNew = false;
        //2021-12-06  mzy S WAG-C9ADM5 【委托】 [询价任务]主动任务创建时点相关信息没有保存  end

        //2021-10-20  mzy 任务管理改善  start
        this.IsGeneratePlan = true;
        //2021-10-20  mzy  任务管理改善  end

        this.targetEvent = new Event();
        this.targetEvent.OwnerId = Userinfo.getUserId();
        this.targetEvent.StartDateTime = Datetime.Now().addDays(1);
        //lightning修改hql 20231026 start
        this.targetEvent.EndDateTime = Datetime.Now().addDays(1).addMinutes(30);
        //lightning修改hql 20231026 end
        //this.targetEvent.StartDateTime = Datetime.Now().addDays(0);
        //2021-07-28  mzy SWAG-C4YB9J  事件页面优化  add start
        //this.targetEvent.DurationInMinutes = 60;
        //2021-07-28  mzy SWAG-C4YB9J  事件页面优化  add end
        this.targetEvent.Activity_Type2__c = HOSPITAL_STRING;
        this.targetEvent.OPDPlan_Flag__c = false;
        this.targetEvent.EventStatus__c = '02 接受';
        retURL = ApexPages.currentPage().getParameters().get('retURL');
        evt4 = ApexPages.currentPage().getParameters().get('evt4');
        evt13 = ApexPages.currentPage().getParameters().get('evt13');
        //newURL = '/apex/SimpleEventRegister?retURL=' + (retURL == null ? '' : EncodingUtil.urlEncode(retURL, 'UTF-8')) + '' + (evt4 == null ? '' : '&evt4=' + evt4) + '' + (evt13 == null ? '' : '&evt13=' + evt13);
        this.planProducts = new Map<String,String>(); // 20200907 zh
        System.debug('-----:retURL=' + retURL);
        System.debug('-----:evt4=' + evt4);
        System.debug('-----:evt13=' + evt13);

        if (evt4 != null && evt13 != null) {
            // この結果はGMTになる
            Datetime inputDatetime = Datetime.parse(evt4 + ' ' + evt13);
            System.debug('-----:inputDateTime=' + inputDatetime);
            this.targetEvent.StartDateTime = inputDatetime;
        } else if (evt4 != null) {
            Datetime inputDatetime = Datetime.parse(evt4 + ' 00:00');
            System.debug('-----:inputDatetime=' + inputDatetime);
            this.targetEvent.StartDateTime = inputDatetime;
        }
//deloitte-zhj 20231204 PIPL还原
        //Add by Li Jun 20220303 for PIPL Start
        // PIHelper.PIIntegration piIntegration = PIHelper.getPIIntegrationInfo('Contact');
        // staticResource = JSON.serialize(piIntegration);
        // system.debug('static resource:'+JSON.serialize(staticResource));
        //Add by Li Jun 20220303 for PIPL End
    }

    public void init() {
        System.debug('进Init方法');
        //getplanProductMap();// 20200907 zh 计划出借备品    2021-05-26 移到init方法末尾,否则数据显示不出来  mzy
        aid = ApexPages.currentPage().getParameters().get('accid');
        cid = ApexPages.currentPage().getParameters().get('cid');
        oid = ApexPages.currentPage().getParameters().get('oid');
        mid = ApexPages.currentPage().getParameters().get('mid');

        // 任务和日报管理开发 update by vivek 2020-04-13 start
        taskId = ApexPages.currentPage().getParameters().get('taskId');
        isDelay = ApexPages.currentPage().getParameters().get('isDelay');

        //2021-08-10  mzy  update  SWAG-C5R6GW   询价任务新增字段  start
        //延期时不可以更新询价
        if('true'.equals(isDelay)){
            this.isOppSelect = true;
        }
        //2021-08-10  mzy  update  SWAG-C5R6GW   询价任务新增字段  end

        //20210324 zh WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 start
        eventId = ApexPages.currentPage().getParameters().get('id');
        if (eventId != null) {
            targetEvent = [SELECT Id,OwnerId,StartDateTime,Purpose_TypeEscFSE__c,IsRecurrence,Activity_PurposeFSE__c,Purpose_TypeFSE__c,
                            Related_Opportunity1_ID__c,Related_Opportunity1__c,Related_Opportunity2_ID__c,Related_Opportunity2__c,
                            Related_Opportunity3_ID__c,Related_Opportunity3__c,Related_Opportunity4_ID__c,Related_Opportunity4__c,
                            Related_Opportunity5_ID__c,Related_Opportunity5__c,Related_Service1_ID__c,Related_Service1__c,Related_Service1_Code__c, 
                            DurationInMinutes,Activity_Type2__c,OPDPlan_Flag__c,Activity_PurposeEscFSE__c,noOpp_Reason__c,Location,
                            whatid__c,Subject,Visitor1__c,Visitor2__c,Visitor3__c,Visitor4__c,Visitor5__c,PlanProdDetail__c,
                            Visitor1_ID__c,Visitor2_ID__c,Visitor3_ID__c,Visitor4_ID__c,Visitor5_ID__c,Task_ID__c,delayReason__c,
                            //2021-04-25  mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 add  start
                            Opd_Plan__c,EventStatus__c,
                            //2021-04-25  mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  add  end
                            // 2021-07-28   mzy 今天的事件 如果已经生成报告一览,则不允许进行取消和延期操作  start
                            EventC_ID__c,
                            // 2021-07-28   mzy 今天的事件 如果已经生成报告一览,则不允许进行取消和延期操作  end
                            //2021-07-28  mzy SWAG-C4YB9J  事件页面优化  add
                            EndDateTime 
                            //2021-07-28  mzy SWAG-C4YB9J  事件页面优化  add
                            FROM Event WHERE Id = :eventId];
            taskId = targetEvent.Task_ID__c;
            this.subjectPerson = targetEvent.Subject;// DB202312088802 zzm 20231228 添加自定义主题 
            //2021-04-27  mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  add  start
            EventStartDate = targetEvent.StartDateTime;
            EventDurationInMinutes = targetEvent.DurationInMinutes;
            //2021-04-27  mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  add  end
            //2021-07-28  mzy SWAG-C4YB9J  事件页面优化  add
            EventEndDate = targetEvent.EndDateTime;
            if(targetEvent.Opd_Plan__c != null){
               opdId = targetEvent.Opd_Plan__c;
            }
            //2021-07-28  mzy SWAG-C4YB9J  事件页面优化  add
            //2021-07-28  mzy SWAG-C4YB9J 事件页面优化 今天的事件 如果已经生成报告一览,则不允许进行取消和延期操作 start
            //if (targetEvent.StartDateTime.date() <= Date.today() || (targetEvent.EventStatus__c != '01 分配' && targetEvent.EventStatus__c != '02 接受')) {
            if (targetEvent.StartDateTime.date() < Date.today() || (targetEvent.EventStatus__c != '01 分配' && targetEvent.EventStatus__c != '02 接受') 
                || (targetEvent.StartDateTime.date() ==  Date.today() && targetEvent.EventC_ID__c != null ) ) {
            //2021-07-28  mzy  SWAG-C4YB9J 事件页面优化 今天的事件 如果已经生成报告一览,则不允许进行取消和延期操作 end
                allDisable = true;
            }
//deloitte-zhj 20231204 PIPL还原
            //Add By Li Jun for PIPL 20220303 Start
            // List<String> conAWSIds = new List<String>();
            // Set<String> contactIdsForReport = new Set<String>();
            // List<String> visitorList = new List<String>{'Visitor1_ID__c','Visitor2_ID__c','Visitor3_ID__c','Visitor4_ID__c','Visitor5_ID__c'};
            // for(String visitorValue:visitorList){
                //     if(String.isNotEmpty((String)targetEvent.get(visitorValue))&&String.isNotBlank((String)targetEvent.get(visitorValue))){
                    //         contactIdsForReport.add((String)targetEvent.get(visitorValue));
                //     }
            // }
            // 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 20220303 End
        }
        //20210324 zh WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 end
        if (targetEvent.OPDPlan_Flag__c) {
            this.isDisable = true;
            this.isDisableDepart = true;
            this.isDisPlanProd = true;
            this.isOpdDisable = true;
        }
        //2021-06-09 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 start
        //所有类型的事件编辑时都不允许改 科室 和拜访区分
        if(eventId != null || isDelay =='true' || taskId != null){
            this.isDisableDepart = true;
            this.isDisActivityCategory = true;
        }
        //2021-03-09 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 end
        if (taskId != null) {
            task = [select id, name,RecordTypeId,RecordType.Name,CreateDate__c,Activity_Date__c,
                    CreatedDate, isDelay__c, delayToDate__c, 
                    taskDifferent__c, delayTask__c,Initial_Task__c, 
                    //2021-07-16  mzy  update  任务的未执行判断时间修改最终期限
                    Finish_Date__c,
                    //2021-07-16  mzy  update  任务的未执行判断时间修改最终期限
                    //2021-06-15  mzy update 
                    delayReason__c,Opd_Plan__c,NewMaintenanceReport_Task__c,
                    //2021-06-15 mzy update
                    //2021-11-26  mzy  任务管理改善  start
                    HopeCompletionDate__c,
                    //2021-11-26  mzy  任务管理改善  end
                    taskStatus__c, account__c ,OpportunityId__c , Maintenance_Contract__c, Maintenance_Contract__r.Id 
                    from task__c where id = :taskId];
            // 2021-06-15 mzy update
            System.debug('任务的延期理由:'+task.delayReason__c);
            // 2021-07-30 mzy SWAG-C5DAX8  start
            if(task.delayReason__c!=null&&eventId == null){
                targetEvent.delayReason__c = task.delayReason__c;
            }      
            // 2021-07-30 mzy  SWAG-C5DAX8 end
            System.debug('事件的延期理由:'+targetevent.delayReason__c);
            // 2021-06-15  mzy update  
            aid = task.account__c;
            oid = task.OpportunityId__c;
            mid = task.Maintenance_Contract__r.Id; //20201204 zh 给跟进的维修合同赋值
            //this.isDisable = true;
            if (!String.isBlank(mid)) {
                this.isDisService = true; //20201221 接收任务禁止修改维修合同 zh
            }
            //2021-10-12  mzy  任务管理改善  satrt
            //上级分配任务 和主动任务、被动任务平级  , 判断 是被动任务的地方也要 加上上级分配任务
            /*if ('被动任务'.equals(task.taskDifferent__c)) {
                this.isDisable = true;
                this.isDisableDepart = true;
                this.isDisActivityCategory = true;
            }
            if ('OPD'.equals(task.RecordType.Name) && !'被动任务'.equals(task.taskDifferent__c)) {
                this.isDisPlanProd = true;
            }*/
            if ('被动任务'.equals(task.taskDifferent__c)||'上级分配任务'.equals((task.taskDifferent__c))) {
                this.isDisable = true;
                this.isDisableDepart = true;
                this.isDisActivityCategory = true;
            }
            if ('OPD'.equals(task.RecordType.Name) && !'被动任务'.equals(task.taskDifferent__c)
            &&!'上级分配任务'.equals((task.taskDifferent__c)) ) {
                this.isDisPlanProd = true;
            }
            //2021-10-12  mzy 任务管理改善   end

        }
        // 任务和日报管理开发 update by vivek 2020-04-13 end

        LoginUser = [Select Id, Name, Post__c, Employee_No__c, Department, Job_Category__c, Category4__c, Category6__c, ManagerId, Manager.Email From User Where Id = :UserInfo.getUserId()];
        //20200922 SWAG-BS6BYA 推广人员禁止选择维修合同 zh start
        if (LoginUser.Job_Category__c.equals('销售推广')) {
            this.isShowService = false;
        }
        //20200922 SWAG-BS6BYA 推广人员禁止选择维修合同 zh end
        // CHAN-B9M9KA start
        source = ApexPages.currentPage().getParameters().get('source');
        if (source != null && source.equals('AccountPCL') && LoginUser.Job_Category__c != null && !LoginUser.Job_Category__c.equals('销售服务')) {
            targetEvent.Activity_PurposeEscFSE__c = '询价推进';
        }
        // CHAN-B9M9KA end

        //2021-06-17 mzy  任务类型是SLA 被动任务 拜访目的不能修改 
        if(taskId!=null && 'SLA报告书任务'.equals(task.RecordType.Name)){
            if(LoginUser.Job_Category__c == '销售服务'){
                this.isDisActivityPurposeFSE = true;
                this.targetEvent.Activity_PurposeFSE__c = '服务合同';
                this.targetEvent.Purpose_TypeFSE__c = '合同季报';
            }
        }
        //2021-06-17 mzy 任务类型是SLA 被动任务 拜访目的不能修改
        //2021-09-30 mzy  任务类型是点检 被动任务 拜访目的不能修改 
        if(taskId!=null && '点检任务'.equals(task.RecordType.Name) ){
            if(LoginUser.Job_Category__c == '销售服务'){
                this.isDisActivityPurposeFSE = true;
                this.targetEvent.Activity_PurposeFSE__c = '服务合同';
                this.targetEvent.Purpose_TypeFSE__c = '合同点检';
            }
        }
        //2021-09-30 mzy  任务类型是点检 被动任务 拜访目的不能修改 
        // 顧客Job_Category__c
        if (!String.isBlank(aid)) {

            //20201104 zh SFDC-BUF6KM OPD被动任务 start
            // Account acc = [select Id, RecordType.Name, Name, Parent_RecordType__c from Account where Id = :aid];
            Account acc = [select Id, RecordType.Name, Name, Parent_RecordType__c,(select id,Name from ChildAccounts) from Account where Id = :aid];
            this.accounts = acc.ChildAccounts;
            //20201104 zh SFDC-BUF6KM OPD被动任务 end
            this.targetEvent.Location = acc.Name;
            this.targetEvent.whatid__c = acc.Id;
            // this.isDisableDepart = true;//20201104 zh SFDC-BUF6KM OPD被动任务

            // 診療科
            if (acc.RecordType.Name.startsWith(DEP_TYPE)) {
                this.targetEvent.Activity_Type2__c = HOSPITAL_STRING;
                this.isHospital = true;
                this.isAgent = false;
                this.isCampaign = false;
                this.isNone = false;
                // 引合
                if (!String.isBlank(oid)) {
                    List<Opportunity> opp = [select Name from Opportunity where Id = :oid and AccountId = :aid and StageName in ('引合', '注残', '出荷') and RecordTypeId =:System.label.register_1]; //deloitte-zhj 20231221 hardcode改造  niwu- -012C600000003JS
                    // 念のためマッチするかを判断
                    if (opp.size() > 0) {
                        this.targetEvent.Related_Opportunity1__c = opp[0].Name;
                        this.targetEvent.Related_Opportunity1_ID__c = oid;
                    }
                }
                // サビコン
                if (!String.isBlank(mid)) {
                    List<Maintenance_Contract__c> mc = [select Id,Name,Management_Code__c from Maintenance_Contract__c where Id = :mid and Department__c = :aid];
                    // 念のためマッチするかを判断
                    if (mc.size() > 0) {
                        //2021-09-30  mzy  点检改善 显示合同名+合同编码  start
                        //this.targetEvent.Related_Service1__c = mc[0].Name;
                        this.targetEvent.Related_Service1__c = mc[0].Name +' '+mc[0].Management_Code__c;
                        //2021-09-30  mzy  点检改善 显示合同名+合同编码  end
                        this.targetEvent.Related_Service1_ID__c = mid;
                        this.targetEvent.Related_Service1_Code__c = mc[0].Management_Code__c;//20210624 zh 合同编码
                    }
                }
                // 販売店
            } else if (acc.RecordType.Name.startsWith(AGY_TYPE)) {
                this.targetEvent.Activity_Type2__c = AGENCY_STRING;
                this.isHospital = false;
                this.isAgent = true;
                this.isCampaign = false;
                this.isNone = false;
            } else {}

            //2021-10-12  mzy  任务管理改善  satrt
            //上级分配任务 和主动任务、被动任务平级  , 判断 是被动任务的地方也要 加上上级分配任务
            //20201104 zh SFDC-BUF6KM OPD被动任务 start
            //if (task != null && 'OPD'.equals(task.RecordType.Name) && '被动任务'.equals(task.taskDifferent__c)) {
            if (task != null && 'OPD'.equals(task.RecordType.Name) && ('被动任务'.equals(task.taskDifferent__c)||'上级分配任务'.equals(task.taskDifferent__c))) {    
            //2021-10-12  mzy  任务管理改善  end
                this.targetEvent.OPDPlan_Flag__c = true;
                this.isOpdDisable = true;
                //lightning修改hql 20231026 start
                //客户是战略科室
                if (HOSPITAL_STRING.equals(acc.Parent_RecordType__c) || System.Test.isrunningTest()) {
                //lightning修改hql 20231026 end
                    this.targetEvent.Location = '';
                    this.targetEvent.whatid__c = '';
                    this.isShowDepartment = true;
                    this.DepartmentName = acc.Name;
                    this.isDisableDepart = false;
                }
            }
            //20201104 zh SFDC-BUF6KM OPD被动任务 end
            // Campaign
        } else if (!String.isBlank(cid)) {
            Campaign cam = [select Id, Name from Campaign where Id = :cid];

            this.targetEvent.Location = cam.Name;
            this.targetEvent.whatid__c = cam.Id;
            this.targetEvent.Activity_Type2__c = CAMPAIGN_STRING;
            this.isHospital = false;
            this.isAgent = false;
            this.isCampaign = true;
            this.isNone = false;
        } else {}


        getplanProductMap();// 20210526 mzy update WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步
    }

    // 20200907 zh 计划出借备品 start
    public void getplanProductMap(){
        this.prods = [SELECT Name FROM Rental_Equipment__c ORDER BY Serial_Number__c ASC NULLS FIRST];
         /*
        if (String.isNotBlank(this.targetEvent.PlanProdDetail__c)) {
            String[] prodvals = this.targetEvent.PlanProdDetail__c.split(';');
            System.debug('事件字段值:'+targetEvent.PlanProdDetail__c+'\r\n分号切割 :'+prodvals +'\r\nprods :'+prods);
            for(Rental_Equipment__c prod : prods){
                for (String val : prodvals) {
                    if (prod.Name.equals(val.split('\\*')[0])){
                        planProducts.put(prod.Name, val.split('\\*')[1]);
                    }else {
                        planProducts.put(prod.Name, '');
                    }
                }
                
            }
        }else {
            for(Rental_Equipment__c prod : prods){
                planProducts.put(prod.Name, '');
            }
        }*/
        // 2021-04-23  mzy  update WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  start  每次获取到需要的备品后就跳出循环
        if(String.IsNotBlank(this.targetEvent.PlanProdDetail__c)){
            String[] prodvals = this.targetEvent.PlanProdDetail__c.split(';');
            for(Rental_Equipment__c prod :prods){
                for(String val : prodvals){
                    if(prod.Name.equals(val.trim().split('\\*')[0])){
                        planProducts.put(prod.Name,val.trim().split('\\*')[1]);
                        break;
                    }else {
                        planProducts.put(prod.Name, '');
                    }
                }
            }
        }else {
            for(Rental_Equipment__c prod : prods){
                planProducts.put(prod.Name, '');
            }
        }
        // 2021-04-23 mzy  update WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  end  每次获取到需要的备品后就跳出循环

    }
    // 20200907 zh 计划出借备品 end

    public void visitToHospital() {
        System.debug('-----:訪問区分=' + this.targetEvent.Activity_Type2__c);
        this.isHospital = true;
        this.isAgent = false;
        this.isTraining = false;
        this.isCampaign = false;
        this.isNone = false;
        this.resetReference();
    }

    public void visitToAgent() {
        System.debug('-----:訪問区分=' + this.targetEvent.Activity_Type2__c);
        this.isHospital = false;
        this.isAgent = true;
        this.isTraining = false;
        this.isCampaign = false;
        this.isNone = false;
        this.resetReference();
    }

    public void visitToTraining() {
        System.debug('-----:訪問区分=' + this.targetEvent.Activity_Type2__c);
        this.isHospital = false;
        this.isAgent = false;
        this.isTraining = true;
        this.isCampaign = false;
        this.isNone = false;
        this.resetReference();
    }

    public void visitToCampaign() {
        System.debug('-----:訪問区分=' + this.targetEvent.Activity_Type2__c);
        this.isHospital = false;
        this.isAgent = false;
        this.isTraining = false;
        this.isCampaign = true;
        this.isNone = false;
        this.resetReference();
    }

    public void visitToNone() {
        this.isHospital = false;
        this.isAgent = false;
        this.isTraining = false;
        this.isCampaign = false;
        this.isNone = true;
        this.resetReference();
    }

    private void resetReference() {
        this.targetEvent.Location = '';
        this.targetEvent.Visitor1__c = '';
        this.targetEvent.Visitor2__c = '';
        this.targetEvent.Visitor3__c = '';
        this.targetEvent.Visitor4__c = '';
        this.targetEvent.Visitor5__c = '';
        this.targetEvent.Visitor1_ID__c = '';
        this.targetEvent.Visitor2_ID__c = '';
        this.targetEvent.Visitor3_ID__c = '';
        this.targetEvent.Visitor4_ID__c = '';
        this.targetEvent.Visitor5_ID__c = '';
        this.targetEvent.whatid__c = '';
        this.targetEvent.Related_Opportunity1__c = '';
        this.targetEvent.Related_Opportunity1_ID__c = '';
        this.targetEvent.Related_Opportunity2__c = '';
        this.targetEvent.Related_Opportunity2_ID__c = '';
        this.targetEvent.Related_Opportunity3__c = '';
        this.targetEvent.Related_Opportunity3_ID__c = '';
        this.targetEvent.Related_Opportunity4__c = '';
        this.targetEvent.Related_Opportunity4_ID__c = '';
        this.targetEvent.Related_Opportunity5__c = '';
        this.targetEvent.Related_Opportunity5_ID__c = '';
        this.targetEvent.Related_Service1__c = '';
        this.targetEvent.Related_Service1_ID__c = '';
    }

    public Boolean saveLogic() {

        Boolean isError = false;

        System.debug('-----:this.targetEvent.StartDateTime=' + this.targetEvent.StartDateTime);
        //System.debug('-----:this.targetEvent.endDateTime=' + this.targetEvent.endDateTime);
        System.debug('-----:訪問区分=' + this.targetEvent.Activity_Type2__c);
        System.debug('-----:訪問目的=' + this.targetEvent.Activity_PurposeFSE__c+'----'+this.targetEvent.Activity_PurposeEscFSE__c);
        System.debug('-----:活动区分=' + this.targetEvent.Purpose_TypeFSE__c + '----'+this.targetEvent.Purpose_TypeEscFSE__c);
        System.debug('-----:Location=' + this.targetEvent.Location);
        System.debug('-----:引合=' + this.targetEvent.Related_Opportunity1__c);
        System.debug('-----:サービス=' + this.targetEvent.Related_Service1__c);
        System.debug('-----:IsRecurrence=' + this.targetEvent.IsRecurrence);


        this.targetEvent.IsAllDayEvent = false;
        //2021-08-19  mzy update  SWAG-C5R6GW   询价任务新增字段  start
        System.debug('页面事件Id:'+eventId +'---事件Id:'+this.targetEvent.Id+'----逻辑结果:'+(eventId == null));
        if (eventId == null && this.targetEvent.Id == null) {
            this.targetEvent.IsRecurrence = false;
        }
        //2021-08-19  mzy update  SWAG-C5R6GW   询价任务新增字段  end
        // 行動簡易登録画面空登録するときだけに立つフラグ
        this.targetEvent.isScheduled__c = true;


        if (LoginUser.Job_Category__c == '销售服务' && this.targetEvent.Purpose_TypeFSE__c != null) {
            this.targetEvent.Purpose_Type__c = this.targetEvent.Purpose_TypeFSE__c;
        } else if (LoginUser.Job_Category__c != '销售服务' && this.targetEvent.Purpose_TypeEscFSE__c != null) {
            this.targetEvent.Purpose_Type__c = this.targetEvent.Purpose_TypeEscFSE__c;
        } else {
            this.targetEvent.Purpose_Type__c = null;
        }

        if (LoginUser.Job_Category__c == '销售服务' && this.targetEvent.Activity_PurposeFSE__c != null) {
            this.targetEvent.Activity_Purpose__c = this.targetEvent.Activity_PurposeFSE__c;
        } else if (LoginUser.Job_Category__c != '销售服务' && this.targetEvent.Activity_PurposeEscFSE__c != null) {
            this.targetEvent.Activity_Purpose__c = this.targetEvent.Activity_PurposeEscFSE__c;
        } else {
            this.targetEvent.Activity_Purpose__c = null;
        }

        // 目的(计划)が入力されているか？
//System.debug('-----:' + this.targetEvent.Subject);
        // if (this.targetEvent.Subject == null || this.targetEvent.Subject.length() == 0) { // DB202312088802 zzm 20231228 添加自定义主题 
            //this.targetEvent.addError('请输入目的(计划)');
            //isError = true;
            if (this.targetEvent.Location !=null && this.targetEvent.Location !='') {
                // DB202312088802 hql 20231214 添加自定义主题 start
                if (this.subjectPerson!=null && String.isNotBlank(this.subjectPerson)) {
                    this.targetEvent.Subject = this.subjectPerson;
                    if (this.targetEvent.Activity_Purpose__c !=null && this.subjectPerson.indexOf(this.targetEvent.Activity_Purpose__c) == -1) {
                        this.targetEvent.Subject += '-'+this.targetEvent.Activity_Purpose__c;
                    }
                    if (this.targetEvent.Location !=null && this.subjectPerson.indexOf(this.targetEvent.Location) == -1) {
                        this.targetEvent.Subject += '('+this.targetEvent.Location+')';
                    }
                }else{
                     this.targetEvent.Subject = this.targetEvent.Activity_Purpose__c+'('+this.targetEvent.Location+')';
                 } 
                 // DB202312088802 hql 20231214 添加自定义主题 end
            }else{
                this.targetEvent.Subject = this.targetEvent.Activity_Purpose__c;
            }
            
        // } // DB202312088802 zzm 20231228 添加自定义主题 
        // 日付は明日以降か？
        Date today = Date.today();
        Date startDate = this.targetEvent.StartDateTime.Date();
        //startDate <= today
        if (startDate <= today) {
           this.targetEvent.StartDateTime.addError('请输入今天以后的日期');
           isError = true;
        }
         
        //20210120 SWAG-BX7F9W you start
        if (startDate > today.addDays(60)) {
            this.targetEvent.StartDateTime.addError('请输入60天以内的日期');
            isError = true;
        }
        //20210120 SWAG-BX7F9W you end

        //2021-07-22  mzy  add OPD类型事件非正常延期
        /*if('true'.equals(isDelay)&&startDate<= EventStartDate.Date()){
            this.targetEvent.StartDateTime.addError('只能延期到原事件之后的日期');
            isError = true;
        }*/
        //2021-07-22  mzy  add OPD类型事件非正常延期


        //2021-07-28     SWAG-C4YB9J  事件页面优化 计算持续时间   mzy  start
        System.debug('开始日期:'+this.targetEvent.StartDateTime +'---结束日期:'+this.targetEvent.EndDateTime);
        Long startTime = this.targetEvent.StartDateTime.getTime();
        Long endTime = this.targetEvent.EndDateTime.getTime();
        if(startTime > endTime){
            this.targetEvent.EndDateTime.addError('结束日期必须大于开始日期');
            isError = true;
        }
        //Long milliseconds = endTime - startTime;
        //Long seconds = milliseconds / 1000;
        //Long minutes = seconds / 60;
        //System.debug('minutes :'+ minutes +'--'+Integer.valueOf(minutes)+'--'+Integer.valueOf((endTime - startTime) / 1000 / 60));
        this.targetEvent.DurationInMinutes = Integer.valueOf((endTime - startTime) / 1000 / 60);
        //2021-07-28     SWAG-C4YB9J  事件页面优化 计算持续时间   mzy  end
        //2021-08-04  mzy  SWAG-C4YB9J  事件页面优化
        String isRelayDelay = ApexPages.currentPage().getParameters().get('isDelay');
        if(isRelayDelay == 'true'&& isDelay == 'false'){
            this.targetEvent.StartDateTime.addError('延期必须修改 开始时间 和 结束时间 的日期');
            isError = true;
        }
        //lightning修改hql 20231026 start
        if(isBefore == 'false' ){
            this.targetEvent.StartDateTime.addError('提前必须修改 开始时间 和 结束时间 的日期');
            isError = true;
        }
        //lightning修改hql 20231026 end

        //2021-08-04  mzy  SWAG-C4YB9J  事件页面优化  

        //2021-07-16  mzy  update  CHAN-C4G5DK  任务的未执行判断时间修改 start
        //20210414 zh WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 start
        //if (task != null && startDate > task.CreateDate__c.addDays(60)) {
        //    this.targetEvent.StartDateTime.addError('请输入任务生成日60天以内的日期');
        //    isError = true;
        //}
        
        //2021-11-26  mzy  任务管理改善  start
        //如果是上级分配的任务,则拜访日期不能超过希望完成日
        if(task != null &&'上级分配任务'.equals(task.taskDifferent__c)&&task.HopeCompletionDate__c!=null&&targetEvent.StartDateTime.date()>task.HopeCompletionDate__c&& task.HopeCompletionDate__c > Date.today()){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '接收任务时,上级分配的任务拜访日期不能超过希望完成日('+String.valueOf(task.HopeCompletionDate__c)+')'));
            isError = true;
        }
        //2021-11-26  mzy  任务管理改善  end
        if(task != null && startDate > task.Finish_Date__c){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '请填写 开始时间 至 '+String.valueOf(task.Finish_Date__c) +'之前的日期'));
            isError = true;
        }
        //2021-07-16  mzy  update  CHAN-C4G5DK  任务的未执行判断时间修改 end

        if (task != null && task.Activity_Date__c != null && startDate > task.Activity_Date__c && String.isBlank(this.targetEvent.delayReason__c)) {
            this.targetEvent.StartDateTime.addError('延期请先在事件详情页点击【延期】按钮选择延期理由');
            isError = true;
        }
        if ('true'.equals(isDelay) &&task != null &&task.Activity_Date__c != null && startDate <= task.Activity_Date__c) {
            this.targetEvent.StartDateTime.addError('延期日期必须晚于任务拜访日期');
            isError = true; 
        }
        //lightning修改hql 20231026 start
        
        if ('true'.equals(isBefore) &&task != null &&task.Activity_Date__c != null 
            // kk 20231128  提前能不动日期 修改其他数据 start
            //&& startDate >= task.Activity_Date__c
            && startDate > task.Activity_Date__c
            // kk 20231128  提前能不动日期 修改其他数据 start
            ) {
            this.targetEvent.StartDateTime.addError('提前日期必须早于任务拜访日期');
            isError = true; 
        }
        
        //lightning修改hql 20231026 end
        //20210414 zh WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 end
        
        //2021-08-04   mzy  SWAG-C4YB9J  事件页面的优化  start
        // 24hチェック
        //if (this.targetEvent.DurationInMinutes > 24 * 60) {
        //    this.targetEvent.DurationInMinutes.addError('活动时间不能超过24小时');
        //    isError = true;
        //}
        //开始时间  和 结束时间 必须在同一天
        if(this.targetEvent.StartDateTime.Date() != this.targetEvent.EndDateTime.Date()){
            this.targetEvent.EndDateTime.addError('开始时间 和 结束时间 必须在同一天');
            isError = true;
        }
        //2021-08-04  mzy  SWAG-C4YB9J  事件页面的优化  end

        //SWAG-BA65JL 2019/03/22   XHL UpdateStart
        if (this.targetEvent.Activity_Type2__c == '病院' && String.isBlank( this.targetEvent.Location)) {
            this.targetEvent.Location.addError('科室不能为空');
            isError = true;
        }
        //SWAG-BA65JL 2019/03/22   XHL UpdateEnd
        //SWAG-BS6BYA zhaohui start
        List<Rental_Equipment__c> tempList = new List<Rental_Equipment__c>();
        for(Rental_Equipment__c prod : prods){
            if (!'0'.equals(planProducts.get(prod.Name)) && String.isNotBlank(planProducts.get(prod.Name))) {
                tempList.add(prod);
            }
        }
        if (this.targetEvent.OPDPlan_Flag__c==true ){
            if (tempList.size() <= 0) {
                this.targetEvent.addError('【opd计划】勾选时，计划出借的备品必须填写');
                isError = true;
            }
            if (String.isBlank(this.targetEvent.Related_Opportunity1__c) && String.isBlank(this.targetEvent.Related_Opportunity2__c) && String.isBlank(this.targetEvent.noOpp_Reason__c)) {
                this.targetEvent.addError('【opd计划】勾选时，涉及的询价为空，必须填写无询价申请理由');
                isError = true;
            }
            //20201127 you SFDC-BVQC8H start
            String related_Opp1 =this.targetEvent.Related_Opportunity1_ID__c;
            String related_Opp2 =this.targetEvent.Related_Opportunity2_ID__c;
            String oppsql='select StageName,id FROM Opportunity where';
            String oppsql2='select StageName,id FROM Opportunity where';
            system.debug('related_Opp1==='+related_Opp1);
            if (String.isNotBlank(related_Opp1) ) {
                 oppsql += ' id= \'' + related_Opp1 + '\'';//\'' + related_Opp1 + '\'';
                 List<Opportunity> opplist =Database.query(oppsql);
                 system.debug('询价list==='+opplist.size());
                 if(null!=opplist && opplist.size()>0){
                      String oppstagename1 =opplist[0].StageName;
                      system.debug('询价list==='+oppstagename1);
                      if(oppstagename1=='敗戦' || oppstagename1=='削除' || oppstagename1=='注残' || oppstagename1=='出荷' || oppstagename1=='完了'){
                          this.targetEvent.addError('涉及的询价1状态为：失单、取消、注残、发货、完毕，不允许创建OPD计划');
                          isError = true;
                      }
                 }  
            }
            if (String.isNotBlank(related_Opp2) ) {
                 oppsql2 += ' id= \'' + related_Opp2 + '\'';
                 List<Opportunity> opplist =Database.query(oppsql2);
                 if(null!=opplist && opplist.size()>0){
                      String oppstagename2 =opplist[0].StageName;
                      if(oppstagename2=='敗戦' || oppstagename2=='削除' || oppstagename2=='注残' || oppstagename2=='出荷' || oppstagename2=='完了'){
                          this.targetEvent.addError('涉及的询价2状态为：失单、取消、注残、发货、完毕，不允许创建OPD计划');
                          isError = true;
                      }
                 }  
            }
            
            //20201127 you SFDC-BVQC8H end
        }
        //SWAG-BS6BYA zhaohui end
        //20201104 SFDC-BUF6KM zh start
        if (this.isShowDepartment == true) {
            Boolean isDepart = true;
            for (Account acc2 : accounts ) {
                if (this.targetEvent.whatid__c.equals( acc2.Id) ) {
                    isDepart = false;
                    break;
                }
                
            }
            if (isDepart) {
                this.targetEvent.Location.addError('必须填写战略科室下的普通科室');
                isError = true;
            }
        }
        //20201104 SFDC-BUF6KM zh start
        
        //2021-06-21 mzy sla 如果拜访目的选择了服务合同  活动区分为必填
        if (('服务合同'.equals(String.valueOf(this.targetEvent.Activity_PurposeFSE__c))&& this.targetEvent.Purpose_TypeFSE__c == null) 
              || ('服务合同'.equals(String.valueOf(this.targetEvent.Activity_PurposeEscFSE__c))&& this.targetEvent.Purpose_TypeEscFSE__c == null) ){
            this.targetEvent.addError('拜访目的选择了[服务合同],活动区分必填');
            isError = true;
        }
        //2021-06-21 mzy sla 如果拜访目的选择了服务合同   活动区分为必填

        
        //2021-11-01 mzy  <系统反馈出现问题>【请协助】日报无法提交申请  start
        //2021-06-11 mzy sla 如果拜访目的选择了服务合同  涉及的维修合同必填
        if (('服务合同'.equals(String.valueOf(this.targetEvent.Activity_PurposeFSE__c)) 
             || ('服务合同'.equals(String.valueOf(this.targetEvent.Activity_PurposeEscFSE__c)))) &&this.targetEvent.Related_Service1__c == ''){
            this.targetEvent.addError('拜访目的选择了[服务合同],涉及的维修合同必填');
            isError = true;
        }
        //2021-06-11 mzy sla 如果拜访目的选择了服务合同   涉及的维修合同必填

        //由原有的选择【服务合同】涉及的维修合同必填，变为三级分类里的【合同季报】为必填，【合同点检】可填可不填。
        //if ('合同季报'.equals(String.valueOf(this.targetEvent.Purpose_TypeFSE__c))&&(this.targetEvent.Related_Service1_ID__c == ''||String.isBlank(String.valueOf(this.targetEvent.Related_Service1_ID__c))) ){
        //    this.targetEvent.addError('活动区分选择了[合同季报],涉及的维修合同必填');
        //    isError = true;
        //}
        //2021-11-01 mzy   <系统反馈出现问题>【请协助】日报无法提交申请  end

        //2021-06-25 mzy  OPD任务时,更改日期时检查 ,OPD下的备品是否有出库或做已出库指示的,如果有则提示  start
        if(taskId!=null&&'OPD'.equals(task.RecordType.Name) && startDate != task.Activity_Date__c ){
            if(task.Opd_Plan__c != null){                
                String rtn = OpdPlanWebService.changeTrade(task.Opd_Plan__c);
                if(!'OK'.equals(rtn)){
                    this.targetEvent.addError(rtn);
                    isError = true;
                }
            }
        }
        //2021-06-25 mzy  OPD任务时更改日期时检查 ,OPD下的备品是否有出库或做已出库指示的,如果有则提示  end

        return isError;
    }

    public PageReference save() {

        //2021-07-29  mzy SWAG-C4YB9J  事件页面优化 update   start
        //开始日 和 结束日
        Date startDate = this.targetEvent.StartDateTime.Date();
        Date endDate = this.targetEvent.EndDateTime.Date();
        // 日期发生变化 则判定为  延期
        //lightning修改hql 20231026 start
         System.debug('isDelay1 值:'+isDelay);
         System.debug('startDate 值:'+startDate);
         isDelayURL = ApexPages.currentPage().getParameters().get('isDelay');
         
         Boolean isDelayYAN;
         if (isDelayURL=='true') {
             isDelayYAN = true;
         }else{
            isDelayYAN = false;
         }
         // System.debug('EventStartDate.Date 值:'+EventStartDate.Date());
        //System.debug('StartDate:['+startDate+'] EventStartDate:['+EventStartDate+'] endDate:['+endDate+'] EventEndDate:['+EventEndDate+']');
        if (isDelayYAN) {
                // if((EventStartDate != null && startDate > EventStartDate.Date())|| (EventEndDate!=null&&endDate > EventEndDate.Date()) || (eventId == null && taskId!=null && isDelay== 'true')){
            if(((EventStartDate != null && startDate > EventStartDate.Date())|| (EventEndDate!=null&&endDate > EventEndDate.Date()) || (eventId == null && taskId!=null )) && isDelayURL== 'true'){
                isDelay = 'true';
            }else {            
            // 日期没发生变化 则判定为  编辑           
                isDelay = 'false';
            }
        }else{
            //lightning修改hql 20231026 end
        //lightning修改hql 20231026 start
        // 日期发生变化 则判定为  提前
        //  kk 20231128 修改提前验证  <= 或>=  start
            if (((EventStartDate != null && startDate <= EventStartDate.Date())
                || (EventEndDate!=null&&endDate <= EventEndDate.Date())
                ||(EventStartDate != null && startDate > EventStartDate.Date())
                || (EventEndDate!=null&&endDate > EventEndDate.Date()))) {
                isBefore = 'true';
            }else{
                if (EventStartDate != null ) {
                    isBefore = 'false';
                }
                
            }
            //  kk 20231128 修改提前验证  <= 或>=  start
        System.debug('isBefore 值:'+isBefore);
        System.debug('EventStartDate 值:'+EventStartDate+'');
        }
        
        
        //lightning修改hql 20231026 end
        //2021-07-29  mzy SWAG-C4YB9J  事件页面优化  update    end


        Boolean isError = this.saveLogic();

        // 有エラー
        if (isError == true) {
            return null;
        }

        System.debug('开始时间:'+this.targetEvent.StartDateTime);

        Savepoint sp = Database.setSavepoint(); //20201028 SWAG-BS6BYA zh


        //任务和日报管理开发 update by vivek 2020-04-17 start
        // 正常接收任务
        System.debug('========:' + taskId + '========' + isDelay);
        if (taskId != null && isDelay != 'true') {
            //2021-10-12  mzy  任务管理改善  satrt
            //上级分配任务 和主动任务、被动任务平级  , 判断 是被动任务的地方也要 加上上级分配任务
            //zh 20201218 多年保合同只能延期到任务生成日+30日以内 start
            
            if (('多年保修任务'.equals(task.RecordType.Name) || '维修合同任务'.equals(task.RecordType.Name) || 'SLA报告书任务'.equals(task.RecordType.Name))
            && Date.valueOf(this.targetEvent.StartDateTime) > task.CreateDate__c.addDays(30) && '被动任务'.equals(task.taskDifferent__c)) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '接收任务的开始时间必须在任务生成日的30天内。'));
                return null;
            }
            // if (confirmCheck() ) {
            if (confirmCheck()  && task.RecordType.Name != '多年保修任务' && task.RecordType.Name != '维修合同任务'&& '被动任务'.equals(task.taskDifferent__c) && task.RecordType.Name != 'SLA报告书任务' && task.RecordType.Name != '点检任务') {
            //zh 20201218 多年保合同只能延期到任务生成日+30日以内 end
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '接收任务的开始时间必须在任务生成日下个月的时间。'));
                return null;
            }
            /*
            if (('多年保修任务'.equals(task.RecordType.Name) || '维修合同任务'.equals(task.RecordType.Name) || 'SLA报告书任务'.equals(task.RecordType.Name))
            && Date.valueOf(this.targetEvent.StartDateTime) > task.CreateDate__c.addDays(30) && ('被动任务'.equals(task.taskDifferent__c)||'上级分配任务'.equals(task.taskDifferent__c) )) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '接收任务的开始时间必须在任务生成日的30天内。'));
                return null;
            }
            // if (confirmCheck() ) {
            if (confirmCheck()  && task.RecordType.Name != '多年保修任务' && task.RecordType.Name != '维修合同任务'&& ('被动任务'.equals(task.taskDifferent__c)||'上级分配任务'.equals(task.taskDifferent__c) ) && task.RecordType.Name != 'SLA报告书任务' && task.RecordType.Name != '点检任务') {
            //zh 20201218 多年保合同只能延期到任务生成日+30日以内 end
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '接收任务的开始时间必须在任务生成日下个月的时间。'));
                return null;
            }*/
            //2021-10-12 mzy 任务管理改善 增加 上级分配任务 的判断 end
            targetEvent.Task_ID__c = taskId;
            task.taskStatus__c = '02 接受';
            task.GeneratePlan__c = true; //2021-10-20  mzy  任务管理改善  start
            task.ConfirmDate__c = Date.today();
            task.Activity_Date__c = targetEvent.StartDateTime.date(); //拜访日期 20201105 zh CHAN-BUV2TF
            //20201123 zh 创建主动任务与维修合同关联 start
            if(String.isNotBlank(this.targetEvent.Related_Service1_ID__c)){
                task.Maintenance_Contract__c = this.targetEvent.Related_Service1_ID__c;
            }
            //20201123 zh 创建主动任务与维修合同关联 end
        }

        // 判断是不是延期的任务，开始日期只能选择下个月的日期，并需要返更新任务状态
        //  lightning hql start
        if ((taskId != null && isDelay == 'true')) {
        //  lightning hql end
            // 判断开始日期。
            // List<task__c> taskList = new List<task__c>();
            //2021-10-12  mzy  任务管理改善  satrt
            //上级分配任务 和主动任务、被动任务平级  , 判断 是被动任务的地方也要 加上上级分配任务
            //zh 20201218 多年保合同只能延期到任务生成日+60日以内 start
            /*if ('被动任务'.equals(task.taskDifferent__c) && ('多年保修任务'.equals(task.RecordType.Name) || '维修合同任务'.equals(task.RecordType.Name) || 'SLA报告书任务'.equals(task.RecordType.Name))
                && (Date.valueOf(this.targetEvent.StartDateTime) > task.CreateDate__c.addDays(60) || Date.valueOf(this.targetEvent.StartDateTime) <= task.CreateDate__c.addDays(30))) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '延期任务的开始时间必须在任务生成日的31天-60天。'));
                return null;
            }*/
            if ( task !=null && task.taskDifferent__c !=null && ('被动任务'.equals(task.taskDifferent__c)||'上级分配任务'.equals(task.taskDifferent__c)) && ('多年保修任务'.equals(task.RecordType.Name) || '维修合同任务'.equals(task.RecordType.Name) || 'SLA报告书任务'.equals(task.RecordType.Name))
                && task.CreateDate__c !=null &&(Date.valueOf(this.targetEvent.StartDateTime) > task.CreateDate__c.addDays(60) || Date.valueOf(this.targetEvent.StartDateTime) <= task.CreateDate__c.addDays(30))) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '延期任务的开始时间必须在任务生成日的31天-60天。'));
                return null;
            }
            //2021-10-12  mzy  任务管理改善  end
            //2021-07-16  mzy  update  CHAN-C4G5DK  任务的未执行判断时间修改 start
            // lightning  hql start 
            if(task !=null && this.targetEvent.StartDateTime.Date() > task.Finish_Date__c){
                // lightning  hql end 
               /*if('被动任务'.equals(task.taskDifferent__c)&&('询价跟进'.equals(task.RecordType.Name)||'OPD'.equals(task.RecordType.Name) )){
                          ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '询价/OPD被动任务允许延期至任务创建日期的下下个月的最后一天'));
                          return null;
                  }else {
                         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '延期任务允许延期至任务创建日期的下下个月的最后一天'));
                         return null;
              }*/
                  ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '请将任务延期至 '+String.valueOf(task.Finish_Date__c) +'之前的日期'));
                 return null;
            }
            //2021-07-16  mzy  update  CHAN-C4G5DK  任务的未执行判断时间修改 end
            // if (delayCheck() ) {
            // if (delayCheck() && task.RecordType.Name != '多年保修任务' && task.RecordType.Name != '维修合同任务' && '被动任务'.equals(task.taskDifferent__c)) {
            // //zh 20201218 多年保合同只能延期到任务生成日+60日以内 end
            //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '延期任务的开始时间必须在任务生成日下下个月的时间。'));
            //     return null;
            // }
            //2021-07-02  mzy  CHAN-C4G5DK  任务的未执行判断时间修改   start
            //修改OPD任务和询价任务的延期限制，目前只针对被动任务，先修改事件页面的逻辑，如果是询价/OPD任务，允许延期至被动任务创建日期的下下个月的最后一天。
            //1.延期 2.询价/OPD任务 3.被动任务 4.允许延期至被动任务创建日期的下下个月的最后一天
            //if('被动任务'.equals(task.taskDifferent__c)&&('OPD'.equals(task.RecordType.Name)||'询价跟进'.equals(task.RecordType.Name))&&delayCheckOPDorOPP()){
            //    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '询价/OPD被动任务允许延期至任务创建日期的下下个月的最后一天'));
            //    return null;
            //}      

            //被动任务除 询价/OPD任务 以外,还走以下逻辑
            //if(Date.valueOf(this.targetEvent.StartDateTime) > task.CreateDate__c.addDays(60)){
            //if(Date.valueOf(this.targetEvent.StartDateTime) > task.CreateDate__c.addDays(60)
            //   &&
            //   ( ('被动任务'.equals(task.taskDifferent__c)
            //   && (!'OPD'.equals(task.RecordType.Name)&&!'询价跟进'.equals(task.RecordType.Name))) || '主动任务'.equals(task.taskDifferent__c))){
            //    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '延期日期不能超过任务生成日+60天'));
            //    return null;
            //}
            //if(Date.valueOf(this.targetEvent.StartDateTime) > task.CreateDate__c.addDays(60)){
            //     ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,  '延期日期不能超过任务生成日+60天'));
            //     return null;
            //}
            //2021-07-02  mzy  CHAN-C4G5DK  任务的未执行判断时间修改   end

            task.taskStatus__c = '05 延期';
            // task.isDelay__c = true;
            // task.Name = UserInfo.getName()+' 测试任务 '+task.taskStatus__c;
            task.delayDate__c = Date.today();
            task.delayToDate__c = targetEvent.StartDateTime.date();
            // taskList.add(task);
            delayTask = new task__c();
            delayTask.taskStatus__c = '02 接受'; // 状态
            delayTask.assignee__c = UserInfo.getUserId(); //被分配者
            // delayTask.taskDifferent__c = task.taskDifferent__c;
            // 延期就是主动任务
            delayTask.taskDifferent__c = '主动任务';
            delayTask.delayTaskDelay__c = true;
            delayTask.delayTaskP__c = task.Id;
            delayTask.GeneratePlan__c = true; //2021-10-20  mzy  任务管理改善  start
            delayTask.ConfirmDate__c = Date.today(); //接受时间
            delayTask.Activity_Date__c = targetEvent.StartDateTime.date(); //拜访日期 20201105 zh CHAN-BUV2TF
            if(null != this.targetEvent.whatid__c && !''.equals(this.targetEvent.whatid__c)){//2022-4-24 yjk 增加非空验证
                delayTask.account__c = this.targetEvent.whatid__c; //客户
            }
            System.debug(this.targetEvent.whatid__c + '======');
            // delayTask.Name = UserInfo.getName()+' 测试任务 '+delayTask.taskStatus__c;
            delayTask.Name = task.Name;
            delayTask.Initial_Task__c = task.Initial_Task__c == null ? task.Id : task.Initial_Task__c; //20210428 zh 初始任务
            if (String.isNotBlank(this.targetEvent.Related_Opportunity1_ID__c)) {
                delayTask.OpportunityId__c = this.targetEvent.Related_Opportunity1_ID__c;//询价
                //2021-08-13  mzy  update  SWAG-C5R6GW   询价任务新增字段  start
                //如果页面选择询价了,则将询价的以下字段赋值给任务                        
                //询价等级（分配）：记录分配时点的询价等级
                //预测OCSM签约日（分配）：记录分配时点的预测签约日
                //询价状态 (分配) : 记录分配时点的询价状态
                //询价创建日 (分配) : 记录分配时点的询价创建日
                //询价招标日 (分配) : 记录分配时点的询价招标日
                //询价中标日 (分配) : 记录分配时点的询价中标日
                Opportunity op = [SELECT Id,Competitor__c,Close_Forecasted_Date__c,Created_Day__c,StageName__c,
                                 Bid_Date__c,Closing_Bid_Date__c FROM Opportunity WHERE Id  = :this.targetEvent.Related_Opportunity1_ID__c];
                if(op!=null){
                    delayTask.OppCompetitorDbt__c = op.Competitor__c;
                    delayTask.CloseForecastedDateDbt__c = op.Close_Forecasted_Date__c;
                    delayTask.OpportunityStatusDbt__c = op.StageName__c;
                    delayTask.OppCreateDateDbt__c =op.Created_Day__c;
                    delayTask.Bid_DateDbt__c =op.Bid_Date__c;
                    delayTask.Closing_Bid_DateDbt__c =op.Closing_Bid_Date__c;
                }
                //2021-08-13  mzy  update  SWAG-C5R6GW   询价任务新增字段  end
            }
            //20201123 zh 创建主动任务与维修合同关联 start
            if(String.isNotBlank(this.targetEvent.Related_Service1_ID__c)){
                delayTask.Maintenance_Contract__c = this.targetEvent.Related_Service1_ID__c;
            }
            delayTask.RecordTypeId = task.RecordTypeId;
            //20201123 zh 创建主动任务与维修合同关联 end
              //2021-06-16  mzy add 延期时,将维修合同带过去 start
            if(task.Maintenance_Contract__r.Id != null){
                delayTask.Maintenance_Contract__c = task.Maintenance_Contract__r.Id ;
            }
            if(task.NewMaintenanceReport_Task__c != null){
               delayTask.NewMaintenanceReport_Task__c = task.NewMaintenanceReport_Task__c;
            }
            // 2021-06-16 mzy add 延期时,将维修合同带过去 end
            // taskList.add(delayTask);
        }

        // 主动任务，创建一个已接收的任务
        if (taskId == null && (this.targetEvent.Activity_Type2__c == '病院' 
                               || this.targetEvent.Activity_Type2__c == '販売店' 
                               || this.targetEvent.Activity_Type2__c == '社外イベント')) {
            // 主动任务记录类型需确认，先使用默认值创建。
            String taskType = '';
            String taskAccType = '';
            String taskAccName = '';
            // 任务记录类型分配
            Set<String> departIdSet = new Set<String>();
            Map<String, String> accToDepMap = new Map<String, String>();
            Map<String, Account_Number_of_target__c> accToNumTarget = new Map<String, Account_Number_of_target__c>();
            List<Account> accList = 
                [select id, name, Department_Class__c 
                 from Account 
                 where id = :this.targetEvent.whatid__c];
            for (Account acc : accList) {
                departIdSet.add(acc.Department_Class__c);
                accToDepMap.put(acc.Id, acc.Department_Class__c);
            }
            List<Account> accDepList = 
                [select id, name, 
                 (select id, OCM_Period__c, 
                  Is_Target_Account_Energy__c, 
                  Is_Target_Account__c, OCM_Category__c 
                  from Account_target_acc__r 
                  order by OCM_Period__c desc limit 1) 
                 from Account where id = :departIdSet];
            for (Account accdep : accDepList) {
                for (Account_Number_of_target__c accnum : accdep.Account_target_acc__r) {
                    accToNumTarget.put(accdep.Id, accnum);
                    break;
                }
            }
            //20201123 zh 创建主动任务与维修合同关联 start
            Map<String,Maintenance_Contract__c> mainMaps = new Map<String,Maintenance_Contract__c>();
            if (String.isNotBlank(this.targetEvent.Related_Service1_ID__c)) {
                List<Maintenance_Contract__c> mainContract = [SELECT Id,Name,RecordType.DeveloperName,Management_Code__c  
                                                                FROM Maintenance_Contract__c 
                                                                WHERE Id = :this.targetEvent.Related_Service1_ID__c];
                for(Maintenance_Contract__c main : mainContract){
                    mainMaps.put(main.Id, main);
                    this.targetEvent.Related_Service1_Code__c = main.Management_Code__c;
                }
                
            }

            //20201123 zh 创建主动任务与维修合同关联 end
            if (LoginUser.Job_Category__c.equals('销售推广')) {
                if (this.targetEvent.Activity_Type2__c == '病院') {
                    
                   // 2021-06-11 mzy sla 注释掉了询价3 因为现在的页面没有给询价3赋值,所以会显示 询价3不等于空字符串而是等于null ,导致后面的判断进不去
                   // if (this.targetEvent.Related_Opportunity1__c != '' || this.targetEvent.Related_Opportunity2__c != '' || this.targetEvent.Related_Opportunity3__c != '') {
                    System.debug('测试询价任务:' +'询价1:' +this.targetEvent.Related_Opportunity1__c +'---询价2:'+this.targetEvent.Related_Opportunity2__c);
                    if (this.targetEvent.Related_Opportunity1__c != '' || this.targetEvent.Related_Opportunity2__c != '') { 
                        taskType = System.Label.OpportunityFollow; // 询价跟进任务
                    } else if (this.targetEvent.OPDPlan_Flag__c) {
                        taskType = System.Label.OPD; // OPD任务
                    } else if (!accToNumTarget.isEmpty() && !accToDepMap.isEmpty() && (accToNumTarget.get(accToDepMap.get(this.targetEvent.whatid__c)).Is_Target_Account_Energy__c == 1 || accToNumTarget.get(accToDepMap.get(this.targetEvent.whatid__c)).Is_Target_Account__c == 1)) {
                         taskType = System.Label.TargetAccountVisit; // 目标客户拜访任务
                    }  else if (!accToNumTarget.isEmpty() && !accToDepMap.isEmpty() && (accToNumTarget.get(accToDepMap.get(this.targetEvent.whatid__c)).OCM_Category__c == 'H1' || accToNumTarget.get(accToDepMap.get(this.targetEvent.whatid__c)).OCM_Category__c == 'H0')) {
                         taskType = System.Label.visitHLevel; // H层拜访任务
                    } else {
                        taskType = System.Label.DailyVisit;// 日程拜访任务
                    }
                }
                if (this.targetEvent.Activity_Type2__c == '販売店') {
                    taskType = System.Label.AgencyVisit; // 经销商支持任务
                }
                if (this.targetEvent.Activity_Type2__c == '社外イベント') {
                    taskType = System.Label.campaignFollow; // 学术会议跟进任务
                }
            } else {
                taskType = System.Label.DailyVisit; //日常拜访
                //20201123 zh 创建主动任务与维修合同关联 start
                if (String.isNotBlank(this.targetEvent.Related_Service1_ID__c) && 
                    mainMaps.containsKey(this.targetEvent.Related_Service1_ID__c) && 
                    mainMaps.get(this.targetEvent.Related_Service1_ID__c).RecordType.DeveloperName == 'VM_Contract') {
                    taskType = System.Label.VMContract; //多年保修任务
                }
                if (String.isNotBlank(this.targetEvent.Related_Service1_ID__c) && 
                    mainMaps.containsKey(this.targetEvent.Related_Service1_ID__c) && 
                    (mainMaps.get(this.targetEvent.Related_Service1_ID__c).RecordType.DeveloperName == 'NewMaintenance_Contract'
                        || mainMaps.get(this.targetEvent.Related_Service1_ID__c).RecordType.DeveloperName == 'Maintenance_Contract')) {
                    taskType = System.Label.MaintenanceTask; //维修合同任务(消费率预警)
                }
                //20201123 zh 创建主动任务与维修合同关联 end
            }

            //2021-06-21 mzy  sla 活动区分为 合同季报时，任务记录类型是SLA  查询当前季度的服务合同报告书任务 start
            //发放任务的时间 应该用的是 及时率统计期间,目前用的是 发放期间
            NewMaintenanceReport_Task__c tempNMCT ;
            if ('合同季报'.equals(String.valueOf(this.targetEvent.Purpose_TypeFSE__c))){
                taskType = System.Label.SLA; //SLA任务

                // 关联服务合同报告书任务
                if(String.isNotBlank(this.targetEvent.Related_Service1_ID__c) &&
                    mainMaps.get(this.targetEvent.Related_Service1_ID__c).RecordType.DeveloperName == 'NewMaintenance_Contract'){
                    //List<NewMaintenanceReport_Task__c> tempNMCTList = [SELECT id FROM NewMaintenanceReport_Task__c where NewMaintenance_Contract__c =:this.targetEvent.Related_Service1_ID__c 
                    //           and TimelyRateStartDate__c <= :Date.today() and TimelyRateEndDate__c >= :Date.today()];
                    List<NewMaintenanceReport_Task__c> tempNMCTList = [SELECT id FROM NewMaintenanceReport_Task__c where NewMaintenance_Contract__c =:this.targetEvent.Related_Service1_ID__c 
                               and Distribution_Start_Date__c <= :Date.today() and Distribution_End_Date__c >= :Date.today()];
                    if(tempNMCTList.size()>0){
                        tempNMCT = tempNMCTList.get(0);
                    }
                }
            }
            //2021-06-21 mzy  sla 活动区分为 合同季报时，任务记录类型是SLA  查询当前季度的服务合同报告书任务 end

            //2021-09-30  mzy  活动区分为 合同点检时，任务记录类型是点检任务 start
            if('合同点检'.equals(String.valueOf(this.targetEvent.Purpose_TypeFSE__c))){
                taskType = System.Label.InspectupTask; //点检任务
            }
            //2021-09-30  mzy  活动区分为 合同点检时，任务记录类型是点检任务 end

            // 名称拼写
            if (String.isNotBlank(this.targetEvent.whatid__c)) {
                if (this.targetEvent.whatid__c.startsWith('001')) {
                    List<Account> acclsit = [select id, name from Account where id = :this.targetEvent.whatid__c];
                    if (acclsit.size() > 0 ) {
                        taskAccName = acclsit[0].name;
                    }
                    
                }
                if (this.targetEvent.whatid__c.startsWith('701')) {
                    List<Campaign> camlist = [select id, name from Campaign where id = :this.targetEvent.whatid__c];
                    if (camlist.size() > 0 ) {
                        taskAccName = camlist[0].name;
                    }
                    
                }
            }
            System.debug('任务记录类型 :'+taskType);
            taskActive = new task__c();
            taskActive.taskStatus__c = '02 接受'; // 状态
            taskActive.assignee__c = UserInfo.getUserId(); //被分配者
            taskActive.taskDifferent__c = '主动任务';
            taskActive.ConfirmDate__c = Date.today(); //接受时间
            taskActive.GeneratePlan__c = true; //2021-10-20  mzy  任务管理改善  start
            taskActive.Activity_Date__c = targetEvent.StartDateTime.date(); //拜访日期 20201105 zh CHAN-BUV2TF
            taskActive.RecordTypeId = taskType;
            //20201123 zh 创建主动任务与维修合同关联 start
            if(String.isNotBlank(this.targetEvent.Related_Service1_ID__c)){
                taskActive.Maintenance_Contract__c = this.targetEvent.Related_Service1_ID__c;
            }
            //20201123 zh 创建主动任务与维修合同关联 end
            //2021-06-17 mzy add  关联服务合同报告书任务 start
            if(tempNMCT !=null){
               taskActive.NewMaintenanceReport_Task__c =  tempNMCT.Id;
            }
            //2021-06-17 mzy add 关联服务合同报告书任务 end
            if (String.isNotBlank(this.targetEvent.whatid__c)) {
                if (this.targetEvent.whatid__c.startsWith('701')) {
                    taskActive.Campaign__c = this.targetEvent.whatid__c; //市场活动
                }
                if (this.targetEvent.whatid__c.startsWith('001')) {
                    taskActive.account__c = this.targetEvent.whatid__c; //客户
                    if (String.isNotBlank(this.targetEvent.Related_Opportunity1_ID__c)) {
                        taskActive.OpportunityId__c = this.targetEvent.Related_Opportunity1_ID__c;//询价

                        //2021-08-10  mzy  update  SWAG-C5R6GW   询价任务新增字段  start
                        //如果页面选择询价了,则将询价的以下字段赋值给任务                        
                        //询价等级（分配）：记录分配时点的询价等级
                        //预测OCSM签约日（分配）：记录分配时点的预测签约日
                        //询价状态 (分配) : 记录分配时点的询价状态
                        //询价创建日 (分配) : 记录分配时点的询价创建日
                        //询价招标日 (分配) : 记录分配时点的询价招标日
                        //询价中标日 (分配) : 记录分配时点的询价中标日
                        Opportunity op = [SELECT Id,Competitor__c,Close_Forecasted_Date__c,Created_Day__c,StageName__c,
                                         Bid_Date__c,Closing_Bid_Date__c FROM Opportunity WHERE Id  = :this.targetEvent.Related_Opportunity1_ID__c];
                        if(op!=null){
                            taskActive.OppCompetitorDbt__c = op.Competitor__c;
                            taskActive.CloseForecastedDateDbt__c = op.Close_Forecasted_Date__c;
                            taskActive.OpportunityStatusDbt__c = op.StageName__c;
                            taskActive.OppCreateDateDbt__c =op.Created_Day__c;
                            taskActive.Bid_DateDbt__c =op.Bid_Date__c;
                            taskActive.Closing_Bid_DateDbt__c =op.Closing_Bid_Date__c;
                        }
                        //2021-08-10  mzy  update  SWAG-C5R6GW   询价任务新增字段  end
                    }
                }
            }
            if (this.targetEvent.Activity_Type2__c == '病院') {
                taskAccType = '用户拜访';
            }
            if (this.targetEvent.Activity_Type2__c == '販売店') {
                taskAccType = '经销商支持';
            }
            if (this.targetEvent.Activity_Type2__c == '社外イベント') {
                taskAccType = '学术会议';
            }
            //System.debug(this.targetEvent.whatid__c + '======');
            taskActive.Name = taskAccType + ':' + taskAccName;
        }
        //任务和日报管理开发 update by vivek 2020-04-17 end



        // 行動作成
        try {
            // insert targetEvent;
            System.debug('事件21212:'+targetEvent);
            if(eventId == null){
                insert targetEvent;                  
                System.debug('事件Insert:'+targetEvent); 
            }else if(eventId != null && isDelay != 'true'){
                update targetEvent;                
                System.debug('事件update:'+targetEvent);
            }
            //任务和日报管理开发 update by vivek 2020-04-17 start
            // 正常接收任务
            if (taskId != null && isDelay != 'true') {
                //2021-05-24 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  update  start
                task.account__c = targetEvent.whatid__c;
                String taskAccType  = '';
                if (this.targetEvent.Activity_Type2__c == '病院') {
                    taskAccType = '用户拜访';
                }
                if (this.targetEvent.Activity_Type2__c == '販売店') {
                    taskAccType = '经销商支持';
                }
                if (this.targetEvent.Activity_Type2__c == '社外イベント') {
                    taskAccType = '学术会议';
                }
                task.Name =  taskAccType + ':'+targetEvent.Location;
                //2021-05-24 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  update  end
                update task;
            }
            // 延期任务更新任务状态
            if (taskId != null &&  isDelay == 'true') {
                // update task;
                insert delayTask;
                task.delayTask__c = delayTask.Id;
                update task;
                System.debug('delayTask.Id======' + delayTask.Id);
                //targetEvent.Task_ID__c = delayTask.Id;
                //2021-05-20 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  update start
                //如果不是OPD类型的话,延期则创建新的事件,原事件改为延期
                if(!targetEvent.OPDPlan_Flag__c&&eventId != null){
                    //原事件 : 修改事件状态,勾选是否延期
                    Event oldevent = new Event();
                    oldevent.Id = eventId;
                    oldevent.Subject = targetEvent.Subject +'【已延期】';
                    oldevent.EventStatus__c = '05 延期';
                    oldevent.isDelay__c = true;
                    oldevent.delayToDate__c = targetEvent.StartDateTime.Date();
                    update oldevent;
                    //新事件 : 清除原事件的Id,作为新事件添加
                    targetEvent.Id = null;
                    targetEvent.Task_ID__c = delayTask.Id;
                    targetEvent.delayReason__c = null;
                    insert targetEvent;
                }else{
                    //任务管理器过来的
                    targetEvent.Task_ID__c = delayTask.Id;
                    update targetEvent;
                }
                
            }
            if (taskId == null && taskActive != null) {
                insert taskActive;
                targetEvent.Task_ID__c = taskActive.Id;
                update targetEvent;
            }
            if(string.isNotBlank(targetEvent.Task_ID__c) &&
                Date.valueOf(targetEvent.StartDateTime).month() ==
                Date.today().month()
               ){
                // database.executeBatch(new EventToEventDetailsBatch(targetEvent.id),1);
            }
            //任务和日报管理开发 update by vivek 2020-04-17 end
        } catch (DmlException ex) {
            ApexPages.addMessages(ex);
            return null;
        }

        //2021-08-19  mzy SWAG-C5784H 【委托】事件无法延期 start 
        if(taskId == null&&(this.targetEvent.Activity_Type2__c != '病院' 
                               || this.targetEvent.Activity_Type2__c != '販売店' 
                               || this.targetEvent.Activity_Type2__c != '社外イベント')){
        //活动区分 非 病院 販売店  社外イベント  不会生成任务,只是更新事件的信息
            if(isDelay == 'true'){
                //延期:
                //原事件 : 修改事件状态,勾选是否延期,填写延期至的时间
                Event oldevent = new Event();
                oldevent.Id = eventId;
                String subjectName = targetEvent.Subject;
                if(String.isNotBlank(subjectName)&&subjectName.contains('【')){
                   oldevent.Subject = subjectName.split('【')[0] + '【已延期】';
                }else {
                   oldevent.Subject = subjectName +'【已延期】';
                }
                oldevent.EventStatus__c = '05 延期';
                oldevent.isDelay__c = true;
                oldevent.delayToDate__c = targetEvent.StartDateTime.Date();
                update oldevent;

                //新事件 : 
                //新事件 : 清除原事件的Id,作为新事件添加
                targetEvent.Id = null;
                targetEvent.delayReason__c = null;
                insert targetEvent;
            }else {
                //编辑/提前:
                update targetEvent;
            }

        }
        //2021-08-19  mzy SWAG-C5784H 【委托】事件无法延期 end

        // LZHU-BHVCWW 活动计划与目标客户管理的报表 20200103  by vivek srart
        // if (this.targetEvent.Activity_Type2__c == '病院' || this.targetEvent.Activity_Type2__c == '販売店' || this.targetEvent.Activity_Type2__c == '社外イベント') {
        //     System.debug('this.targetEvent.Id' + this.targetEvent.Id);
        //     System.debug('this.targetEvent.OwnerId' + this.targetEvent.OwnerId);
        //     List<Event> calenderList = ControllerUtil.eventSelectById(this.targetEvent.Id);
        //     System.debug('calenderList[0].ActivityDate' + calenderList[0].ActivityDate + 'calenderList[0].OwnerId' + calenderList[0].OwnerId);
        //     List<Daily_Report__c> 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 from Daily_Report__c where Reported_Date__c = :calenderList[0].ActivityDate and OwnerId = :calenderList[0].OwnerId ];
        //     System.debug('========-' + reportlist == null + '===' + reportlist.size());
        //     if (reportlist.size() <= 0) {
        //         System.debug('========+' + reportlist);
        //         Date reportDate = calenderList[0].ActivityDate;
        //         Daily_Report__c report = new Daily_Report__c();
        //         report.Reporter__c = calenderList[0].OwnerId;
        //         report.Status__c = '作成中';
        //         report.Daily_Report_Data_Type__c = '通常';
        //         report.Reported_Date__c = reportDate;
        //         report.Working_Time_From__c =
        //             Datetime.newInstance(reportDate.year(),
        //                                  reportDate.month(),
        //                                  reportDate.day(), 8, 45, 0);
        //         report.Working_Time_To__c =
        //             Datetime.newInstance(reportDate.year(),
        //                                  reportDate.month(),
        //                                  reportDate.day(),
        //                                  17, 30, 0);
        //         report.OwnerId = calenderList[0].OwnerId;
        //         insert report;
        //         reportlist.add(report);
        //     }


        //     if (reportlist.size() > 0) {
        //         Daily_Report__c report = new Daily_Report__c();
        //         report = reportlist[0];
        //         Date d = report.Reported_Date__c;
        //         List<Event__c> ecNewList = new List<Event__c>();
        //         // 作成中の場合のみ、Event→EventCへ作成
        //         if (report.Status__c == '作成中') {
        //             // List<Event> calenderList = ControllerUtil.eventSelectById(this.targetEvent.Id);
        //             // calenderList.add(this.targetEvent);
        //             // 次回の活動予定を取得
        //             List<String> nextEcIds = new List<String>();
        //             for (Event e : calenderList) {
        //                 if (this.targetEvent.NextEventC_ID__c != null) nextEcIds.add(this.targetEvent.NextEventC_ID__c);
        //             }
        //             Map<String, Event__c> nextEcMap = new Map<String, Event__c>();
        //             if (nextEcIds.size() > 0) {
        //                 List<Event__c> nextEcList = ControllerUtil.getNextEventCList(nextEcIds);
        //                 for (Event__c ec : nextEcList) {
        //                     nextEcMap.put(ec.Id, ec);
        //                 }
        //             }

        //             for (Event e : calenderList) {
        //                 if (!String.isBlank(this.targetEvent.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;
        //                     }
        //                     Event__c ec = new Event__c(
        //                         Subject__c = e.Subject,
        //                         StartDateTime__c = e.StartDateTime,
        //                         DurationInMinutes__c = e.DurationInMinutes,
        //                         EndDateTime__c = e.StartDateTime.addMinutes(e.DurationInMinutes),
        //                         ActivityDate__c = d,
        //                         BeforeActivityDate__c = e.BeforeActivityDate__c,
        //                         ActivityDateTime__c = e.StartDateTime,
        //                         Main_Visit_Location__c = e.Main_Visit_Location__c,
        //                         Activity_Type2__c = e.Activity_Type2__c,
        //                         Purpose_Type__c = e.Purpose_Type__c,
        //                         Related_Opportunity1__c = e.Related_Opportunity1__c,
        //                         OPDPlan_Flag__c = e.OPDPlan_Flag__c,
        //                         Related_Opportunity1_ID__c = e.Related_Opportunity1_ID__c,
        //                         Related_Opportunity2__c = e.Related_Opportunity2__c,
        //                         Related_Opportunity2_ID__c = e.Related_Opportunity2_ID__c,
        //                         Related_Opportunity3__c = e.Related_Opportunity3__c,
        //                         Related_Opportunity3_ID__c = e.Related_Opportunity3_ID__c,
        //                         Related_Opportunity4__c = e.Related_Opportunity4__c,
        //                         Related_Opportunity4_ID__c = e.Related_Opportunity4_ID__c,
        //                         Related_Opportunity5__c = e.Related_Opportunity5__c,
        //                         Related_Opportunity5_ID__c = e.Related_Opportunity5_ID__c,
        //                         Related_Service1__c = e.Related_Service1__c,
        //                         Related_Service1_ID__c = e.Related_Service1_ID__c,
        //                         Visitor1__c = e.Visitor1__c,
        //                         Visitor2__c = e.Visitor2__c,
        //                         Visitor3__c = e.Visitor3__c,
        //                         Visitor4__c = e.Visitor4__c,
        //                         Visitor5__c = e.Visitor5__c,
        //                         Visitor1_ID__c = e.Visitor1_ID__c,
        //                         Visitor2_ID__c = e.Visitor2_ID__c,
        //                         Visitor3_ID__c = e.Visitor3_ID__c,
        //                         Visitor4_ID__c = e.Visitor4_ID__c,
        //                         Visitor5_ID__c = e.Visitor5_ID__c,
        //                         Visitor_Place_Free__c = visitorPlaceFree,
        //                         Location__c = location,
        //                         whatid__c = whatid,
        //                         Daily_Report__c = report.Id,
        //                         Event_ID__c = e.Id,
        //                         IsScheduled__c = e.IsScheduled__c,
        //                         AppCdId__c = e.AppCdId__c,
        //                         SyncCreatedDate__c = e.SyncCreatedDate__c,
        //                         Activity_Purpose__c = e.Activity_Purpose__c,
        //                         Activity_PurposeFSE__c = e.Activity_PurposeFSE__c,
        //                         Activity_PurposeEscFSE__c = e.Activity_PurposeEscFSE__c,
        //                         Purpose_TypeFSE__c = e.Purpose_TypeFSE__c,
        //                         Purpose_TypeEscFSE__c = e.Purpose_TypeEscFSE__c
        //                     );
        //                     if (e.IsScheduled__c) {
        //                         ec.IsScheduled_StartDateTime__c = ec.StartDateTime__c;
        //                         ec.IsScheduled_EndDateTime__c = ec.EndDateTime__c;
        //                         ec.IsScheduled_Location__c = e.Location;
        //                         ec.IsScheduled_Subject__c = ec.Subject__c;
        //                     }
        //                     if (e.whatid__c != null && e.whatid__c.startsWith('001')) {
        //                         // 訪問場所はAccountの場合
        //                         ec.Account_ID__c = e.whatid__c;
        //                         ec.Campaign_ID__c = null;
        //                     } else if (e.whatid__c != null && e.whatid__c.startsWith('701')) {
        //                         // 訪問場所はCampaignの場合
        //                         ec.Account_ID__c = null;
        //                         ec.Campaign_ID__c = e.whatid__c;
        //                     } else {
        //                         ec.Account_ID__c = null;
        //                         ec.Campaign_ID__c = null;
        //                     }
        //                     if (e.NextEventC_ID__c != null && nextEcMap.containsKey(e.NextEventC_ID__c)) {
        //                         Event__c nextEc = nextEcMap.get(e.NextEventC_ID__c);
        //                         ec.Visitor1__c = nextEc.Visitor1__c;
        //                         ec.Visitor2__c = nextEc.Visitor2__c;
        //                         ec.Visitor3__c = nextEc.Visitor3__c;
        //                         ec.Visitor4__c = nextEc.Visitor4__c;
        //                         ec.Visitor5__c = nextEc.Visitor5__c;
        //                         ec.Visitor1_ID__c = nextEc.Visitor1_ID__c;
        //                         ec.Visitor2_ID__c = nextEc.Visitor2_ID__c;
        //                         ec.Visitor3_ID__c = nextEc.Visitor3_ID__c;
        //                         ec.Visitor4_ID__c = nextEc.Visitor4_ID__c;
        //                         ec.Visitor5_ID__c = nextEc.Visitor5_ID__c;
        //                         ec.Purpose_Type2__c = nextEc.Purpose_Type2__c;
        //                         ec.Purpose_Type3__c = nextEc.Purpose_Type3__c;
        //                         ec.Purpose_Type4__c = nextEc.Purpose_Type4__c;
        //                         ec.Purpose_Type5__c = nextEc.Purpose_Type5__c;
        //                         ec.Related_Opportunity2__c = nextEc.Related_Opportunity2__c;
        //                         ec.Related_Opportunity3__c = nextEc.Related_Opportunity3__c;
        //                         ec.Related_Opportunity4__c = nextEc.Related_Opportunity4__c;
        //                         ec.Related_Opportunity5__c = nextEc.Related_Opportunity5__c;
        //                         ec.Related_Opportunity2_ID__c = nextEc.Related_Opportunity2_ID__c;
        //                         ec.Related_Opportunity3_ID__c = nextEc.Related_Opportunity3_ID__c;
        //                         ec.Related_Opportunity4_ID__c = nextEc.Related_Opportunity4_ID__c;
        //                         ec.Related_Opportunity5_ID__c = nextEc.Related_Opportunity5_ID__c;
        //                         ec.Related_Service2__c = nextEc.Related_Service2__c;
        //                         ec.Related_Service2_ID__c = nextEc.Related_Service2_ID__c;
        //                         ec.Purpose__c = ec.Subject__c;
        //                     }
        //                     ecNewList.add(ec);
        //                 }
        //             }
        //         }
        //         System.debug('ecNewList======++++++' + ecNewList);
        //         insert ecNewList;
        //     }
        // }

        // LZHU-BHVCWW 活动计划与目标客户管理的报表 20200103  by vivek end

        //SWAG-BA65JL 2019/03/22   XHL UpdateStart
        
        try {
            if (targetEvent.OPDPlan_Flag__c == true) {
                saveOPDPlan(targetEvent);
                //2021-04-29 mzy  WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  add   start
                 //任务是OPD类型 , 事件 原日期 > 现日期 ,说明提前
                 if(EventStartDate!= null &&EventStartDate.Date() > targetEvent.StartDateTime.Date() ){
                    createCancelPostponePlan_Advance();
                }
                //2021-04-29 mzy  WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  add   end     
                 //2021-05-20 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  update start
                //如果是OPD类型延期的话
                if(taskId !=null&&isDelay=='true'&&eventId != null){
                    Event oldevent = new Event();
                    oldevent.Id = eventId;                    
                    oldevent.isDelay__c = true;
                    oldevent.EventStatus__c = '05 延期';
                    oldevent.StartDateTime = EventStartDate;
                    // oldevent.EndDateTime = EventStartDate.addMinutes(EventDurationInMinutes);                    
                    oldevent.delayToDate__c = targetEvent.StartDateTime.Date();                     
                    oldevent.task_Id__c = taskId;
                    update oldevent;
                    createCancelPostponePlan_Delay();
                    oldevent = new Event();
                    oldevent.Id = eventId;                                 
                    oldevent.Subject = targetEvent.Subject +'【已延期】';
                    update oldevent;
                }      
                //2021-05-20 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  update end
            }
        } catch (DmlException ex) {
            System.debug('dmlex===='+ex);
            ApexPages.addMessages(ex);
            Database.rollback(sp); //20201028 SWAG-BS6BYA zh
            this.targetEvent.Id = eventId;// 20210819 zh SWAG-C5R6GW 询价任务新增字段
            return null;
        } 
        //SWAG-BA65JL 2019/03/22   XHL UpdateEnd
        
        //2021-12-06 mzy SWAG-C9ADM5 【委托】 [询价任务]主动任务创建时点相关信息没有保存  start
        PageReference ret = null;
        //如果IsSaveAndNew == true 则说明是 保存并新建 
        if(this.isSaveAndNew){
            //  + '' + (evt4 == null ? '' : '&evt4=' + evt4 + (evt13 == null ? '' : '&evt13=' + evt13));
            Datetime newStart = this.targetEvent.StartDateTime.addMinutes(this.targetEvent.DurationInMinutes);
            System.debug('-----:newStart=' + newStart + ',   ← GMT?');
            String newEvt4 = newStart.Year() + '/' + newStart.Month() + '/' + newStart.Day();
            System.debug('-----:newEvt4=' + newEvt4 + ',   ← GMT?');
            String newEvt13 = newStart.Hour() + ':' + newStart.minute();
            newURL = '/apex/SimpleEventRegister?retURL=' + (retURL == null ? '' : EncodingUtil.urlEncode(retURL, 'UTF-8')) + '&evt4=' + newEvt4 + '&evt13=' + newEvt13;
    
            newURL += (String.isBlank(aid) ? '' : '&accid=' + aid)
                    + (String.isBlank(cid) ? '' : '&cid=' + cid)
                    + (String.isBlank(oid) ? '' : '&oid=' + oid)
                    + (String.isBlank(mid) ? '' : '&mid=' + mid);
    
            ret = new PageReference(newURL);
            //点击完 保存并新建 按钮恢复初始值
            this.isSaveAndNew = false;
        }else {
            //2021-07-28     SWAG-C4YB9J  事件页面优化 保存事件后跳转到当前事件页面,不跳转主页   mzy  start
            //点击保存后不跳转到主页，跳转到本条事件的详情页
            //PageReference ret = new PageReference(retURL == null ? '/' : retURL);
            String eventURL = ''+this.targetEvent.id;
            if(opdId != null){
                //说明是OPD事件延期,则重新查找新事件
                Event e = [select id from event where Opd_Plan__c = :opdId];
                eventURL =''+e.Id;
            }
            retURL = null;
            ret = new PageReference(retURL == null ? '/'+eventURL : retURL);
            //2021-07-28     SWAG-C4YB9J  事件页面优化  保存事件后跳转到当前事件页面,不跳转主页  mzy  end
        }
        ret.setRedirect(true);
        //2021-12-06 mzy SWAG-C9ADM5 【委托】 [询价任务]主动任务创建时点相关信息没有保存  end
        return ret;
    }
    // 任务和日报管理开发 update by vivek 2020-04-13 end
    public PageReference saveAndNew() {
        //2021-12-06 mzy SWAG-C9ADM5 【委托】 [询价任务]主动任务创建时点相关信息没有保存  start
        this.isSaveAndNew = true;
        PageReference ret = save();
        return ret;
        //2021-12-06 mzy SWAG-C9ADM5 【委托】 [询价任务]主动任务创建时点相关信息没有保存  end
    }

    // 任务和日报管理开发 update by vivek 2020-04-13 start
    public boolean confirmCheck() {
        Date Next1Month = Date.valueOf(task.CreatedDate.addMonths(1));
        Date firstDayNext1Month = Date.newInstance(Next1Month.year(), Next1Month.Month(), 1);
        Date Next2Month = Date.valueOf(task.CreatedDate.addMonths(2));
        Date firstDayNext2Month = Date.newInstance(Next2Month.year(), Next2Month.Month(), 1);
        Date targetDate = Date.valueof(targetEvent.StartDateTime);
        boolean tempResult = true;
        if (targetDate >= firstDayNext1Month && targetDate < firstDayNext2Month) {
            tempResult = false;
        }
        return tempResult;

    }
    // 任务和日报管理开发 update by vivek 2020-04-13 start
    // 假设任务生成日是在6月19日
    // 如果是6月26号至6月30号之间延期的，那这个任务需要延期在下下月， 即 8月1日 至 8月31日， 7月末跑Batch时，添加到日报一览明细
    //如果是7月1日至7月31日延期，那这个任务需要延期在下月，即 8月1日 至 8月31日，7月末跑Batch时，添加到日报一览明细
    //7月31号之后不可以操作延期
    public boolean delayCheck() {
        Date Next2Month = Date.valueOf(task.CreatedDate.addMonths(2));
        Date firstDayNext2Month = Date.newInstance(Next2Month.year(), Next2Month.Month(), 1);
        Date Next3Month = Date.valueOf(task.CreatedDate.addMonths(3));
        Date firstDayNext3Month = Date.newInstance(Next3Month.year(), Next3Month.Month(), 1);
        Date targetDate = Date.valueof(targetEvent.StartDateTime);
        boolean tempResult = true;
        if (targetDate >= firstDayNext2Month &&  targetDate < firstDayNext3Month && Date.today() < firstDayNext2Month) {
            tempResult = false;
        }
        return tempResult;

    }

    
    //SWAG-BA65JL 2019/03/22   XHL AddStart
    public Void saveOPDPlan(Event event) {
        //新建维护时
    //20201028 SWAG-BS6BYA zh start
      //   Savepoint sp = Database.setSavepoint();
      // try { 
    //20201028 SWAG-BS6BYA zh end
        OPDPlan__c opdPlan = new OPDPlan__c();
        opdPlan.OwnerId      =  event.OwnerId;
        opdPlan.Activity_Type2__c      =  event.Activity_Type2__c;
        opdPlan.Visitor1__c      =  event.Visitor1__c;
        opdPlan.Visitor2__c      =  event.Visitor2__c;
        opdPlan.Visitor3__c      =  event.Visitor3__c;
        opdPlan.Visitor4__c      =  event.Visitor4__c;
        opdPlan.Visitor5__c      =  event.Visitor5__c;

        opdPlan.StartDateTime__c      =  event.StartDateTime;
        opdPlan.EndDateTime__c      =  event.StartDateTime.addMinutes(event.DurationInMinutes);
        //2021-5-14  mzy 只有新建OPD时这样赋值时间,现在延期通过opd延期取消对象进行更新时间
        if(event.OPD_Plan__c == null){
            opdPlan.OPDPlan_ImplementDate__c = event.StartDateTime.date();
        }
        //2021-5-14  mzy 只有新建OPD时这样赋值时间,现在延期通过opd延期取消对象进行更新时间
        if (event.Activity_Type2__c == '病院' && String.isNotBlank(event.whatid__c)) {
            opdPlan.Account_Laboratory__c      =  event.whatid__c;
        } else if (event.Activity_Type2__c == '販売店' && String.isNotBlank(event.whatid__c)) {
            opdPlan.Account_Dealer__c      =  event.whatid__c;
        } else if (event.Activity_Type2__c == '社内活動' && String.isNotBlank(event.whatid__c)) {
            opdPlan.Account_Laboratory__c      =  event.whatid__c;
        } else if (event.Activity_Type2__c == '社外イベント' && String.isNotBlank(event.whatid__c)) {
            opdPlan.Campaign__c      =  event.whatid__c;
        }
        if (String.isNotBlank(event.Visitor1_ID__c)) {
            opdPlan.Visitor1_ID__c      =  event.Visitor1_ID__c;
        }
        if (String.isNotBlank(event.Visitor2_ID__c)) {
            opdPlan.Visitor2_ID__c      =  event.Visitor2_ID__c;
        }
        if (String.isNotBlank(event.Visitor3_ID__c)) {
            opdPlan.Visitor3_ID__c      =  event.Visitor3_ID__c;
        }
        if (String.isNotBlank(event.Visitor4_ID__c)) {
            opdPlan.Visitor4_ID__c      =  event.Visitor4_ID__c;
        }
        if (String.isNotBlank(event.Visitor5_ID__c)) {
            opdPlan.Visitor5_ID__c      =  event.Visitor5_ID__c;
        }
        if (String.isNotBlank(event.Visitor1_ID__c)) {
            opdPlan.Visitor1_ID__c      =  event.Visitor1_ID__c;
        }

        opdPlan.Related_Opportunity1__c      =  event.Related_Opportunity1__c;
        if (String.isNotBlank(event.Related_Opportunity1_ID__c)) {
            opdPlan.Related_Opportunity1_ID__c      =  event.Related_Opportunity1_ID__c;
        }

        opdPlan.Related_Opportunity2__c      =  event.Related_Opportunity2__c;
        if (String.isNotBlank(event.Related_Opportunity2_ID__c)) {
            opdPlan.Related_Opportunity2_ID__c      =  event.Related_Opportunity2_ID__c;
        }

        opdPlan.Related_Opportunity3__c      =  event.Related_Opportunity3__c;
        if (String.isNotBlank(event.Related_Opportunity3_ID__c)) {
            opdPlan.Related_Opportunity3_ID__c      =  event.Related_Opportunity3_ID__c;
        }

        opdPlan.Related_Opportunity4__c      =  event.Related_Opportunity4__c;
        if (String.isNotBlank(event.Related_Opportunity4_ID__c)) {
            opdPlan.Related_Opportunity4_ID__c      =  event.Related_Opportunity4_ID__c;
        }

        opdPlan.Related_Opportunity5__c      =  event.Related_Opportunity5__c;
        if (String.isNotBlank(event.Related_Opportunity5_ID__c)) {
            opdPlan.Related_Opportunity5_ID__c      =  event.Related_Opportunity5_ID__c;
        }

        opdPlan.Related_Service1__c      =  event.Related_Service1__c;
        if (String.isNotBlank(event.Related_Service1_ID__c)) {
            opdPlan.Related_Service1_ID__c      =  event.Related_Service1_ID__c;
        }
        opdPlan.Activity_PurposeFSE__c      =  event.Activity_PurposeFSE__c;
        opdPlan.Purpose__c      =  event.Subject;
        opdPlan.Purpose_TypeFSE__c      =  event.Purpose_TypeFSE__c;
        opdPlan.Purpose_Type__c      =  event.Purpose_Type__c;
        opdPlan.Activity_Purpose__c      =  event.Activity_Purpose__c;
        opdPlan.NoOpp_Reason__c = event.noOpp_Reason__c; //20201009 zh 无询价申请理由带值 SWAG-BS6BYA 
        opdPlan.OPDType__c = '事件';//20201021 zh OPD计划类型为事件 SWAG-BS6BYA 
        opdPlan.RentalReson__c = 'OPD'; //2021-04-22 mzy SWAG-C2A5YU 由事件创建的OPD计划系统自动默认出借目的为OPD
        //2020-09-23  mzy SWAG-BSC5WP 生成OPD计划改为 提交 状态 update   start
        // opdPlan.Status__c = '计划中';
        // opdPlan.Status__c = '提交'; //2020-10-21 zhaohui 
        //2020-09-23  mzy SWAG-BSC5WP 生成OPD计划改为 提交 状态  update   end
        System.debug('opdPlan20190313___' + opdPlan);
        System.debug('event20190325___' + event);
        //20210118 SWAG-BX7F9W you start
        opdPlan.Task_ID__c= event.Task_ID__c;
        //20210118 SWAG-BX7F9W you end
         //2021-05-24 mzy update start
        if(event.Opd_Plan__c == null){
            insert opdPlan;  
        }else if(event.Opd_Plan__c != null){
            opdPlan.Id = event.Opd_Plan__c;
            if(isDelay == 'true'){
                //如果是延期的话则OPD关联的任务更新为延期任务
                opdPlan.Task_ID__c= delayTask.Id;
            }

            update opdPlan;
        }
        //2021-05-24 mzy update end  
        //2020-09-23 mzy SWAG-BSC5WP 审批后 OPD计划的状态由  提交 改为 计划中 start
        // Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
        // req1.setObjectId(opdPlan.id); 
        // Approval.ProcessResult submitResult = Approval.process(req1);
        //2020-09-23 mzy SWAG-BSC5WP 审批后 OPD计划的状态由  提交 改为 计划中 end
        //20200907 zh 创建计划出借备品 start
        String quantity = '';
        RecordType recordType = [SELECT Id,Name FROM RecordType WHERE SobjectType = 'Plan_Rental_Equipment__c' AND Name = '事件'];
        List<Plan_Rental_Equipment__c> ineuqipments = new List<Plan_Rental_Equipment__c>();
        for(Rental_Equipment__c prod : prods){
            if (!'0'.equals(planProducts.get(prod.Name)) && String.isNotBlank(planProducts.get(prod.Name))) {
                Plan_Rental_Equipment__c planeuqipment = new Plan_Rental_Equipment__c();
                planeuqipment.Event_ID__c = event.Id;
                planeuqipment.RecordTypeId = recordType.Id;
                planeuqipment.Name = prod.Name;
                planeuqipment.Rental_Equipment__c = prod.Name;
                planeuqipment.Rental_Quantity__c = planProducts.get(prod.Name);
                planeuqipment.OPD_Plan__c = opdPlan.Id;
                ineuqipments.add(planeuqipment);
                quantity += prod.Name + '*' + planProducts.get(prod.Name) + '; ';
            }
        }
        System.debug('ineuqipments----'+ineuqipments);
        if (ineuqipments.size()>0 && isDelay != 'true') {
            insert ineuqipments;
        }
        if(isDelay != 'true'){

            opdPlan.PlanProdDetail__c = quantity;
            //2021-05-24  mzy  正在审批的就不再次进入审批流   WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 update  start
            if(event.OPD_Plan__c == null){
            opdPlan.Status__c = '提交'; //2020-10-26 zhaohui 
            }
            //2021-05-24  mzy  正在审批的就不再次进入审批流   WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 update  end
            System.debug('opd status---' + opdPlan.Status__c);
            update opdPlan;
        }
        //20200907 zh 创建计划出借备品 end
        targetEvent.Opd_Plan__c = opdPlan.Id;
        targetEvent.PlanProdDetail__c = quantity;
        update targetEvent;
       //20210118 SWAG-BX7F9W you start
       //正常接受任务
        if (taskId != null && isDelay != 'true') {
          task.Opd_Plan__c = opdPlan.Id;
          update task;
        }
        //延期任务
        if (taskId != null && isDelay == 'true') {
            delayTask.Opd_Plan__c = targetEvent.Opd_Plan__c;
            update delayTask;
            //targetEvent.Task_ID__c = taskId;
            //update targetEvent;
        }
        //主动任务
        if (taskId == null) {
          taskActive.Opd_Plan__c = opdPlan.Id;
          update taskActive;
        }
       //20210118 SWAG-BX7F9W you end
    //20201028 SWAG-BS6BYA zh start
     // }catch (DmlException e) {
     //    System.debug('DmlException---' + e);
     //        ApexPages.addmessages(e);
     //        Database.rollback(sp);
     //  }
    //20201028 SWAG-BS6BYA zh end
    }
    //SWAG-BA65JL 2019/03/22   XHL AddEnd
    //2021-04-25  mzy  WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 add  start
    //构建 延期 对象
    @TestVisible
    private void createCancelPostponePlan_Delay(){
        System.debug('创建opd计划取消延期对象 YQ start ');
        //延期记录类型
        Id recodeTypeId = Schema.SObjectType.CancelPostponePlan__c.getRecordTypeInfosByDeveloperName().get('PostponeType').getRecordTypeId();
        
        //创建opd计划取消延期对象
        CancelPostponePlan__c tempCancelPostponePlan = new  CancelPostponePlan__c();
        //0.OPD计划
        tempCancelPostponePlan.CancelOPDPlan__c = targetEvent.Opd_Plan__c;
        //1.延期状态
        tempCancelPostponePlan.Status__c = '延期成功';
        //2.记录类型
        tempCancelPostponePlan.RecordTypeId = recodeTypeId;
        //3.延期时间
        tempCancelPostponePlan.NextPlanDate__c = targetEvent.StartDateTime.date();
        //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);
                }
            }
        }
        tempCancelPostponePlan.cancelReasonCombobox__c = TaskAndOPDMapping.get(task.delayReason__c);
        // if('客户时间变更或冲突'.equals(targetEvent.delayReason__c)){
        //   tempCancelPostponePlan.cancelReasonCombobox__c = '医院试用改期';
        // }else if('与其他突发事件冲突'.equals(targetEvent.delayReason__c)){
        //   tempCancelPostponePlan.cancelReasonCombobox__c = '工作计划变化';  
        // }else if('备品未到'.equals(targetEvent.delayReason__c)){
        //   tempCancelPostponePlan.cancelReasonCombobox__c = '备品到货推迟';  
        // }else if('无合适病例(适合病例流失)OPD延期'.equals(targetEvent.delayReason__c)){
        //   tempCancelPostponePlan.cancelReasonCombobox__c = '手术改期';  
        // }else if('日期填写错误'.equals(targetEvent.delayReason__c)){
        //   tempCancelPostponePlan.cancelReasonCombobox__c = '日期填写错误';  
        // }else if('医院设备不到位'.equals(targetEvent.delayReason__c)){
        //   tempCancelPostponePlan.cancelReasonCombobox__c = '医院设备不到位';  
        // }else if('其他'.equals(targetEvent.delayReason__c)){
        //   tempCancelPostponePlan.cancelReasonCombobox__c = '其他';  
        // }
        //2021-11-02  mzy  任务管理改善开发计划  end
        //5.申请类型
        tempCancelPostponePlan.ApplyType__c = '延期';
        tempCancelPostponePlan.isDailyReportDelay__c = true;//2022-4-22 yjk 事件延期odp增加标识，防止循环
        insert tempCancelPostponePlan;

    }
    //构建 提前 对象
    @TestVisible
    private void createCancelPostponePlan_Advance(){
        System.debug('创建opd计划取消延期对象 TQ start ');
        //取消记录类型
        Id recodeTypeId = Schema.SObjectType.CancelPostponePlan__c.getRecordTypeInfosByDeveloperName().get('PostponeType').getRecordTypeId();
        //创建opd计划取消延期对象
        CancelPostponePlan__c tempCancelPostponePlan = new  CancelPostponePlan__c();
        //0.OPD计划
        tempCancelPostponePlan.CancelOPDPlan__c = targetEvent.Opd_Plan__c;
        //1.延期状态
        tempCancelPostponePlan.Status__c = '延期成功';
        //2.记录类型
        tempCancelPostponePlan.RecordTypeId = recodeTypeId;
        //3.延期时间
        tempCancelPostponePlan.NextPlanDate__c = targetEvent.StartDateTime.date();
        //4.延期理由
        tempCancelPostponePlan.cancelReasonCombobox__c = '工作计划变化';
        //5.申请类型
        tempCancelPostponePlan.ApplyType__c = '提前';

        insert tempCancelPostponePlan;

    }
    //2021-04-25  mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步 add  end

    // lightning ssm 20231027 start
    public PageReference doCancel(){
        String uiThemeDisplayed = UserInfo.getUiThemeDisplayed();
        String returnto = String.isNotBlank(aid) ? aid : 'lightning/o/Event/home?0.source=alohaHeader';
        PageReference pageRef = new PageReference('/' + returnto);

        if(uiThemeDisplayed=='Theme4d'){ // Lightning Theme Value
            aura.redirect(pageRef);
        }

        if(uiThemeDisplayed=='Theme2' || uiThemeDisplayed=='Theme3'){ // Classic Theme Value
            pageRef.setRedirect(true);
        }
        return pageRef;
    }
    // lightning ssm 20231027 end
}