/** 备品智能化
 * 2023-10-30 Add by dzk 
 * 日历新建事件按钮,VF页面转换为LWC页面
 * 与原新建事件功能一致
 */
public without sharing class lexCreateEventButton {
    // 获取开始日期时间
    @AuraEnabled
    public static Datetime  getNowDateTime(){
        try{
            Datetime nowDate = Datetime.Now().addDays(1);
            return nowDate;
        }
        catch(Exception e){
            System.debug(LoggingLevel.INFO, '*** e: ' + e);
            return null;
        }
    }

    // 获取结束日期时间
    @AuraEnabled
    public static Datetime  getEndDateTime(){
        try{
            Datetime nowDate = Datetime.Now().addDays(1);
            Datetime endDate = nowDate.addMinutes(30);
            return endDate;
        }
        catch(Exception e){
            System.debug(LoggingLevel.INFO, '*** e: ' + e);
            return null;
        }
    }

    @AuraEnabled
    public static String  getUserJobCategory(){
        try{
            User LoginUser = [SELECT Id, Name, Job_Category__c  FROM User WHERE Id = :UserInfo.getUserId()];
            return LoginUser.Job_Category__c;
        }
        catch(Exception e){
            System.debug(LoggingLevel.INFO, '*** e: ' + e);
            return null;
        }
    }

    // 询价填值时,获取询价下的报价行项目信息
    @AuraEnabled
    public static List<ProLine>  getOppQuoteItems(String records,String recordId){
        try{
            List<ProLine> ProLineList = new List<ProLine>();
            List<ProLine> ProLineOldList = new List<ProLine>();
            if(String.isNotBlank(records)) {
                ProLineOldList =(List<ProLine>)System.JSON.deserialize(records, List<ProLine>.class);
            }
            List<ProLine> ProLineNewList = new List<ProLine>();
            Map<String,ProLine> ProLineNewMap = new Map<String,ProLine>();
            for(ProLine pro : ProLineOldList){
                if(pro.QuoteId == null){
                    ProLineNewList.add(pro);
                    ProLineNewMap.put(pro.ProductModel, pro);
                }
            }

            if(String.isNotBlank(recordId)){
                ProLineNewList = null;
                List<Opportunity> opp = [SELECT Id, Estimation_Id__c FROM Opportunity WHERE Id =: recordId];
                List<QuoteLineItem> quoteItemList = [SELECT Id, Quantity, Product2.Name, QuoteId,
                                                            Product2.Key_product_147P__c,Quote.Quote_No__c,
                                                            Product2.ProductCode, Product2.Fixture_Model_No_T__c,
                                                            OppIsLendMark__c, Product2.RentalSubject__c
                                                            FROM QuoteLineItem
                                                            WHERE Product2.RentalSubject__c = true 
                                                            AND QuoteId =: opp[0].Estimation_Id__c
                                                            AND Product2.Fixture_Model_No_F__c != null
                                                            AND Product2.Category5__c != '虚拟'
                                                            AND ((Product2.SFDA_Status__c = '停止' 
                                                                AND Product2.Manual_Entry__c = false 
                                                                AND Product2.Loaner_categoryII__c IN ('台车','监视器','录像设备'))
                                                            OR (Product2.SFDA_Status__c != '停止'  
                                                                OR Product2.Manual_Entry__c = true)) ];
                for(QuoteLineItem quoLine : quoteItemList){
                    if(ProLineNewMap.get(quoLine.Product2.Fixture_Model_No_T__c) != null){
                       ProLineNewMap.get(quoLine.Product2.Fixture_Model_No_T__c).QuoteId = quoLine.QuoteId;
                       ProLineNewMap.get(quoLine.Product2.Fixture_Model_No_T__c).QuoteNo = quoLine.Quote.Quote_No__c;
                    }else{
                        ProLine proNew = new ProLine();
                        proNew.Id = quoLine.Id;
                        proNew.Name = quoLine.Product2.Name;
                        proNew.Quantity = 1;
                        proNew.ProductCode = quoLine.Product2.ProductCode;
                        proNew.ProductModel = quoLine.Product2.Fixture_Model_No_T__c;
                        if(String.isNotBlank(quoLine.Product2.Key_product_147P__c)){
                            proNew.FixtureModel = quoLine.Product2.Key_product_147P__c.substring(3);
                        }
                        proNew.QuoteId = quoLine.QuoteId;
                        proNew.QuoteNo = quoLine.Quote.Quote_No__c;
                        ProLineNewMap.put(proNew.ProductModel, proNew);
                    }
                }
                for (ProLine mapValue : ProLineNewMap.values()) {
                    ProLineList.add(mapValue);
                }
                return ProLineList;
            }else{
                return ProLineNewList;
            }    
        }
        catch(Exception e){
            System.debug(LoggingLevel.INFO, '*** e: ' + e + e.getLineNumber() + '行');
            return null;
        }
    }

    // 初始化事件
    @AuraEnabled(cacheable=true)
    public static EventData initEvent(String eventid, String taskId, String accid, String cid, String oid, String mid, String source){
        try {
            EventData eveData = new EventData();
            Event eve = new Event();
            if (String.isNotBlank(eventid)) {
                eve = [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,Activity_Purpose__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];
                // 新增内容 自定义主题 start
                String subjectPerson = eve.Subject;
                String actpurpose = eve.Activity_Purpose__c;
                if (subjectPerson.indexOf(actpurpose) >= 2) {
                    eve.Subject = subjectPerson.substring(0, subjectPerson.indexOf(actpurpose) - 1);
                } else {
                    eve.Subject = '';
                }
                // 新增内容 自定义主题 end
                if (eve.StartDateTime.date() < Date.today() || (eve.EventStatus__c != '01 分配' && eve.EventStatus__c != '02 接受') 
                    || (eve.StartDateTime.date() ==  Date.today() && eve.EventC_ID__c != null ) ) {
                    //2021-07-28  mzy  SWAG-C4YB9J 事件页面优化 今天的事件 如果已经生成报告一览,则不允许进行取消和延期操作
                    eveData.allDisable = true;
                }
            } 
            // 角色
            String userJob = getUserJobCategory();
            String accountid = accid;
            String oppid = oid;
            String mainid = mid;
            String camid = cid;
            String taskcid = String.isNotBlank(taskId) ? taskId : String.isNotBlank(eve.Task_ID__c) ? eve.Task_ID__c : null;
            // 任务
            if (String.isNotBlank(taskcid)) {
                Task__c 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 = :taskcid];
                eve.Task_ID__c = task.id;
                eve.delayReason__c = task.delayReason__c;
                if(userJob == '销售服务' && ('SLA报告书任务'.equals(task.RecordType.Name) || '点检任务'.equals(task.RecordType.Name))){
                    eveData.isDisActivityPurposeFSE = true;
                    eve.Activity_PurposeFSE__c = '服务合同';
                    eve.Purpose_TypeFSE__c = 'SLA报告书任务'.equals(task.RecordType.Name) ? '合同季报' : '合同点检';
                }
                accountid = task.account__c;
                oppid = task.OpportunityId__c;
                mainid = task.Maintenance_Contract__r.Id;
                if ('OPD'.equals(task.RecordType.Name) && ('被动任务'.equals(task.taskDifferent__c)||'上级分配任务'.equals(task.taskDifferent__c))) {    
                    eve.OPDPlan_Flag__c = true;
                }
            }
            // 来源
            if (String.isNotBlank(source) && source.equals('AccountPCL') && String.isNotBlank(userJob) && !userJob.equals('销售服务')) {
                eve.Activity_PurposeEscFSE__c = '询价推进';
            }
            // 客户
            if (String.isNotBlank(accountid)) {
                //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 from Account where Id = :accountid];
                //20201104 zh SFDC-BUF6KM OPD被动任务 end
                eve.Location = acc.Name;
                eve.whatid__c = acc.Id;
                // this.isDisableDepart = true;//20201104 zh SFDC-BUF6KM OPD被动任务
                if (acc.RecordType.Name.startsWith('診療科')) {
                    eve.Activity_Type2__c = '病院';
                    // 引合
                    if (String.isNotBlank(oppid)) {
                        List<Opportunity> opp = [select Name from Opportunity where Id = :oppid and AccountId = :accountid and StageName in ('引合', '注残', '出荷') and RecordType.DeveloperName = 'Opportunity'];
                        // 念のためマッチするかを判断
                        if (opp.size() > 0) {
                            eve.Related_Opportunity1__c = opp[0].Name;
                            eve.Related_Opportunity1_ID__c = oppid;
                        }
                    }
                    // サビコン
                    if (String.isNotBlank(mainid)) {
                        List<Maintenance_Contract__c> mc = [select Id,Name,Management_Code__c from Maintenance_Contract__c where Id = :mainid and Department__c = :accountid];
                        // 念のためマッチするかを判断
                        if (mc.size() > 0) {
                            //2021-09-30  mzy  点检改善 显示合同名+合同编码  start
                            //this.targetEvent.Related_Service1__c = mc[0].Name;
                            eve.Related_Service1__c = mc[0].Name +' '+mc[0].Management_Code__c;
                            //2021-09-30  mzy  点检改善 显示合同名+合同编码  end
                            eve.Related_Service1_ID__c = mainid;
                            eve.Related_Service1_Code__c = mc[0].Management_Code__c;//20210624 zh 合同编码
                        }
                    }
                    // 販売店
                } else if (acc.RecordType.Name.startsWith('販売店')) {
                    eve.Activity_Type2__c = '販売店';
                }
            }
            // 学会
            else if (String.isNotBlank(camid)) {
                Campaign cam = [select Id, Name from Campaign where Id = :camid];
                eve.Location = cam.Name;
                eve.whatid__c = cam.Id;
                eve.Activity_Type2__c = '社外イベント';
            }

            eveData.eventData = eve;
            return eveData;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }

    // 事件保存
    @AuraEnabled
    public static String  saveEvent(String records,String products){
        Event targetEvent = new Event();
        task__c taskActive = new task__c();
        task__c delayTask = null;
        List<Account> accList = new List<Account>();
        Set<String> departIdSet = new Set<String>();
        Maintenance_Contract__c mc = new Maintenance_Contract__c();
        Map<String, String> accToDepMap = new Map<String, String>();
        Map<String, Account_Number_of_target__c> accToNumTarget = new Map<String, Account_Number_of_target__c>();

        try{
            String taskAccName = '';
            String taskAccType = '';
            String taskType = '';
            Datetime eveStartTime = null;
            Datetime eveEndTime = null;

            User LoginUser = [SELECT Id, Name, Job_Category__c  FROM User WHERE Id = :UserInfo.getUserId()];
            Map<String, Object> eventLineMap = (Map<String, Object>) JSON.deserializeUntyped(records);

            // 从页面读取参数 start
            targetEvent.Id = eventLineMap.get('EventId') != null && eventLineMap.get('EventId') != '' ? String.valueOf(eventLineMap.get('EventId')) : null;
            Boolean eventNew = String.isBlank(targetEvent.Id) ? true : false;
            if (!eventNew) {
                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,Activity_Purpose__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 = :targetEvent.Id];
                eveStartTime = targetEvent.StartDateTime;
                eveEndTime = targetEvent.EndDateTime;
            }
            taskActive.Id = eventLineMap.get('TaskId') != null && eventLineMap.get('TaskId') != '' ? String.valueOf(eventLineMap.get('TaskId')) : null;
            Boolean taskNew = String.isBlank(taskActive.Id) ? true : false;
            if (!taskNew) {
                taskActive = [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 = :taskActive.Id];
            }

            targetEvent.StartDateTime = (Datetime)JSON.deserialize('"' + String.valueOf(eventLineMap.get('StartTime')) + '"', Datetime.class);
            targetEvent.EndDateTime = (Datetime)JSON.deserialize('"' + String.valueOf(eventLineMap.get('EndTime')) + '"', Datetime.class);
            Long startTime = targetEvent.StartDateTime.getTime();
            Long endTime = targetEvent.EndDateTime.getTime();
            targetEvent.DurationInMinutes = Integer.valueOf((endTime - startTime) / 1000 / 60);

            String whatId = eventLineMap.get('AccountId') != null && eventLineMap.get('AccountId') != '' ? String.valueOf(eventLineMap.get('AccountId')) : null;
            String conId = eventLineMap.get('ContactId') != null && eventLineMap.get('ContactId') != '' ? String.valueOf(eventLineMap.get('ContactId')) : null;
            String oppId = eventLineMap.get('OpportunityId') != null && eventLineMap.get('OpportunityId') != '' ? String.valueOf(eventLineMap.get('OpportunityId')) : null;
            String mainConId = eventLineMap.get('ServiceId') != null && eventLineMap.get('ServiceId') != '' ? String.valueOf(eventLineMap.get('ServiceId')) : null;
            String ActivityType2 = eventLineMap.get('ActivityType2') != null && eventLineMap.get('ActivityType2') != '' ? String.valueOf(eventLineMap.get('ActivityType2')) : null;
            String ActivityPurposeFSE = eventLineMap.get('ActivityPurposeFSE') != null && eventLineMap.get('ActivityPurposeFSE') != '' ? String.valueOf(eventLineMap.get('ActivityPurposeFSE')) : null;//拜访目的
            String PurposeTypeFSE = eventLineMap.get('PurposeTypeFSE') != null && eventLineMap.get('PurposeTypeFSE') != '' ? String.valueOf(eventLineMap.get('PurposeTypeFSE')) : null;//活动区分
            String subjectPerson = eventLineMap.get('Subject') != null && eventLineMap.get('Subject') != '' ? String.valueOf(eventLineMap.get('Subject')) : '';
            String isDelayStr = eventLineMap.get('isDelay') != null && eventLineMap.get('isDelay') != '' ? String.valueOf(eventLineMap.get('isDelay')) : '';
            String isBeforeStr = eventLineMap.get('isBefore') != null && eventLineMap.get('isBefore') != '' ? String.valueOf(eventLineMap.get('isBefore')) : '';    //sx  20240228 延期与提前不插入产品中间表 提前标识
            String Infrastructure_Project1 = String.valueOf(eventLineMap.get('ProjectId')); //zzm 20240115 基建项目没有保存值bug修复 
            Boolean isDelay = isDelayStr.equals('true') ? true : false;
            Boolean isBefore = isBeforeStr.equals('true') ? true : false;          //sx  20240228 延期与提前不插入产品中间表 提前标识
            // 从页面读取参数 end
            // event赋值 start
            if (eventNew) {
                targetEvent.OwnerId = Userinfo.getUserId();
                targetEvent.EventStatus__c = '02 接受';
            }
            targetEvent.Activity_Type2__c = ActivityType2;
            targetEvent.Visitor1_ID__c = conId;
            if (LoginUser.Job_Category__c == '销售服务') {
                targetEvent.Activity_PurposeFSE__c = ActivityPurposeFSE;
                targetEvent.Purpose_TypeFSE__c = PurposeTypeFSE;
            } else {
                targetEvent.Activity_PurposeEscFSE__c = ActivityPurposeFSE;
                targetEvent.Purpose_TypeEscFSE__c = PurposeTypeFSE;
            } 
            targetEvent.Activity_Purpose__c = ActivityPurposeFSE;
            targetEvent.Purpose_Type__c = PurposeTypeFSE;
            targetEvent.noOpp_Reason__c = String.valueOf(eventLineMap.get('NoOppReason'));
            if(!String.isBlank(whatId)){
                // 优化获取对象
                Id objId = whatId;
                SObjectType objType = objId.getSObjectType();
                String rcdType = objType != null ? objType.getDescribe().getName() : '';
                // 科室
                if(rcdType.equals('Account')){
                    Account acc = [SELECT Id, Name,RecordType.Name,Parent_RecordType__c FROM Account WHERE Id = :whatId];
                    targetEvent.Location = acc.Name;
                    targetEvent.whatid__c = whatId;
                    
                    accList = 
                        [select id, name, Department_Class__c 
                         from Account 
                         where id = :whatId];
                    for (Account acc1 : accList) {
                        departIdSet.add(acc1.Department_Class__c);
                        accToDepMap.put(acc1.Id, acc1.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;
                        }
                    }
                    if(!String.isBlank(oppId)){
                        targetEvent.Related_Opportunity1_ID__c = oppId;
                        List<Opportunity> opp = [SELECT Id,Name,Competitor__c,
                                                  Close_Forecasted_Date__c,
                                                  Created_Day__c,StageName__c,
                                                  Bid_Date__c,Closing_Bid_Date__c 
                                            FROM Opportunity 
                                            WHERE Id = :oppId 
                                            AND StageName = '引合'
                                        ];
                        if(opp.size() > 0){
                            targetEvent.Related_Opportunity1__c = opp[0].Name;
                        }
                    }
                    if(!String.isBlank(mainConId)){
                        mc = [SELECT Id,Name,Management_Code__c,
                                     RecordType_DeveloperName__c 
                                FROM Maintenance_Contract__c 
                                WHERE Id = :mainConId AND Department__c = :whatId];
                        targetEvent.Related_Service1__c = mc.Name +' '+mc.Management_Code__c;
                        targetEvent.Related_Service1_ID__c = mainConId;
                        targetEvent.Related_Service1_Code__c = mc.Management_Code__c;
                    }
                }
                // <!-- zzm 20240115  事件 基建项目没有保存值bug修复 start-->
                Infrastructure_Project__c InfProobj = new Infrastructure_Project__c();
                if(!String.isBlank(Infrastructure_Project1)){
                    InfProobj = [SELECT Id,Name
                            FROM Infrastructure_Project__c 
                            WHERE Id = :Infrastructure_Project1];
                        targetEvent.Related_Opportunity4__c = InfProobj.Name ;
                        targetEvent.Related_Opportunity4_ID__c = Infrastructure_Project1;
                }
                // <!-- zzm 20240115  事件 基建项目没有保存值bug修复 end-->
                if (rcdType.equals('Campaign')) {
                    Campaign camlist = [SELECT Id, Name FROM Campaign WHERE Id = :whatId];
                    targetEvent.Location = camlist.Name;
                    targetEvent.whatid__c = camlist.Id;
                }
            }

            // 新增内容 自定义主题 start
            targetEvent.Subject = subjectPerson;
            targetEvent.Subject += String.isNotBlank(targetEvent.Subject) && String.isNotBlank(targetEvent.Activity_Purpose__c) ? '-' : '';
            targetEvent.Subject += String.isNotBlank(targetEvent.Activity_Purpose__c) ? targetEvent.Activity_Purpose__c : '';
            targetEvent.Subject += String.isNotBlank(targetEvent.Location) ? '(' + targetEvent.Location + ')' : '';
            // 新增内容 自定义主题 end

            // event赋值 end

            // 任务相关判断
            if (!taskNew && !isDelay) {
                //2021-10-12  mzy  任务管理改善  satrt
                //上级分配任务 和主动任务、被动任务平级  , 判断 是被动任务的地方也要 加上上级分配任务
                //zh 20201218 多年保合同只能延期到任务生成日+30日以内 start
                if (('多年保修任务'.equals(taskActive.RecordType.Name) || 
                    '维修合同任务'.equals(taskActive.RecordType.Name) || 
                    'SLA报告书任务'.equals(taskActive.RecordType.Name)) && 
                    Date.valueOf(targetEvent.StartDateTime) > taskActive.CreateDate__c.addDays(30) && 
                    '被动任务'.equals(taskActive.taskDifferent__c)) {
                    return 'ERROR:接收任务的开始时间必须在任务生成日的30天内。';
                }
                if (confirmCheck(taskActive, targetEvent) && 
                    taskActive.RecordType.Name != '多年保修任务' && 
                    taskActive.RecordType.Name != '维修合同任务'&& 
                    '被动任务'.equals(taskActive.taskDifferent__c) && 
                    taskActive.RecordType.Name != 'SLA报告书任务' && 
                    taskActive.RecordType.Name != '点检任务') {
                //zh 20201218 多年保合同只能延期到任务生成日+30日以内 end
                    return 'ERROR:接收任务的开始时间必须在任务生成日下个月的时间。';
                }
                targetEvent.Task_ID__c = taskActive.Id;
                taskActive.taskStatus__c = '02 接受';
                taskActive.GeneratePlan__c = true; //2021-10-20  mzy  任务管理改善  start
                taskActive.ConfirmDate__c = Date.today();
                taskActive.Activity_Date__c = targetEvent.StartDateTime.date(); //拜访日期 20201105 zh CHAN-BUV2TF
                //20201123 zh 创建主动任务与维修合同关联 start
                if(String.isNotBlank(targetEvent.Related_Service1_ID__c)){
                    taskActive.Maintenance_Contract__c = targetEvent.Related_Service1_ID__c;
                }
                //20201123 zh 创建主动任务与维修合同关联 end
            }
            // 判断是不是延期的任务，开始日期只能选择下个月的日期，并需要返更新任务状态
            //  lightning hql start
            if (!taskNew && isDelay) {
                if (taskActive.taskDifferent__c !=null && 
                    ('被动任务'.equals(taskActive.taskDifferent__c) || 
                    '上级分配任务'.equals(taskActive.taskDifferent__c)) && 
                    ('多年保修任务'.equals(taskActive.RecordType.Name) || 
                    '维修合同任务'.equals(taskActive.RecordType.Name) || 
                    'SLA报告书任务'.equals(taskActive.RecordType.Name)) && 
                    taskActive.CreateDate__c !=null && 
                    (Date.valueOf(targetEvent.StartDateTime) > taskActive.CreateDate__c.addDays(60) || 
                    Date.valueOf(targetEvent.StartDateTime) <= taskActive.CreateDate__c.addDays(30))) {
                    return 'ERROR:延期任务的开始时间必须在任务生成日的31天-60天。';
                }
                //2021-10-12  mzy  任务管理改善  end
                //2021-07-16  mzy  update  CHAN-C4G5DK  任务的未执行判断时间修改 start
                // lightning  hql start 
                if(targetEvent.StartDateTime.Date() > taskActive.Finish_Date__c){
                    // lightning  hql end 
                    return 'ERROR:请将任务延期至 '+String.valueOf(taskActive.Finish_Date__c) +'之前的日期';
                }
                //2021-07-16  mzy  update  CHAN-C4G5DK  任务的未执行判断时间修改 end
    
                taskActive.taskStatus__c = '05 延期';
                taskActive.delayDate__c = Date.today();
                taskActive.delayToDate__c = targetEvent.StartDateTime.date();
                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 = taskActive.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 != targetEvent.whatid__c && !''.equals(targetEvent.whatid__c)){//2022-4-24 yjk 增加非空验证
                    delayTask.account__c = targetEvent.whatid__c; //客户
                }
                System.debug(targetEvent.whatid__c + '======');
                // delayTask.Name = UserInfo.getName()+' 测试任务 '+delayTask.taskStatus__c;
                delayTask.Name = taskActive.Name;
                delayTask.Initial_Task__c = taskActive.Initial_Task__c == null ? taskActive.Id : taskActive.Initial_Task__c; //20210428 zh 初始任务
                if (String.isNotBlank(targetEvent.Related_Opportunity1_ID__c)) {
                    delayTask.OpportunityId__c = 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  = :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(targetEvent.Related_Service1_ID__c)){
                    delayTask.Maintenance_Contract__c = targetEvent.Related_Service1_ID__c;
                }
                delayTask.RecordTypeId = taskActive.RecordTypeId;
                //20201123 zh 创建主动任务与维修合同关联 end
                  //2021-06-16  mzy add 延期时,将维修合同带过去 start
                if(taskActive.Maintenance_Contract__r.Id != null){
                    delayTask.Maintenance_Contract__c = taskActive.Maintenance_Contract__r.Id ;
                }
                if(taskActive.NewMaintenanceReport_Task__c != null){
                   delayTask.NewMaintenanceReport_Task__c = taskActive.NewMaintenanceReport_Task__c;
                }
                // 2021-06-16 mzy add 延期时,将维修合同带过去 end
            }
            // 主动任务，创建一个已接收的任务
            if (taskNew && (targetEvent.Activity_Type2__c == '病院' || 
                targetEvent.Activity_Type2__c == '販売店' || 
                targetEvent.Activity_Type2__c == '社外イベント')) {
                // 主动任务记录类型需确认，先使用默认值创建。
                // 任务记录类型分配
                //20201123 zh 创建主动任务与维修合同关联 start
                Map<String,Maintenance_Contract__c> mainMaps = new Map<String,Maintenance_Contract__c>();
                if (String.isNotBlank(targetEvent.Related_Service1_ID__c)) {
                    List<Maintenance_Contract__c> mainContract = [SELECT Id,Name,RecordType.DeveloperName,Management_Code__c  
                                                            FROM Maintenance_Contract__c 
                                                            WHERE Id = :targetEvent.Related_Service1_ID__c];
                    for(Maintenance_Contract__c main : mainContract){
                        mainMaps.put(main.Id, main);
                    }
                }
                //20201123 zh 创建主动任务与维修合同关联 end
                if (LoginUser.Job_Category__c.equals('销售推广')) {
                    if (targetEvent.Activity_Type2__c == '病院') {
                        // 2021-06-11 mzy sla 注释掉了询价3 因为现在的页面没有给询价3赋值,所以会显示 询价3不等于空字符串而是等于null ,导致后面的判断进不去
                        System.debug('测试询价任务:' +'询价1:' +targetEvent.Related_Opportunity1__c +'---询价2:'+targetEvent.Related_Opportunity2__c);
                        if (targetEvent.Related_Opportunity1__c != '' || targetEvent.Related_Opportunity2__c != '') { 
                            taskType = System.Label.OpportunityFollow; // 询价跟进任务
                        } else if (targetEvent.OPDPlan_Flag__c) {
                            taskType = System.Label.OPD; // OPD任务
                        } else if (!accToNumTarget.isEmpty() && !accToDepMap.isEmpty() && (accToNumTarget.get(accToDepMap.get(targetEvent.whatid__c)).Is_Target_Account_Energy__c == 1 || accToNumTarget.get(accToDepMap.get(targetEvent.whatid__c)).Is_Target_Account__c == 1)) {
                            taskType = System.Label.TargetAccountVisit; // 目标客户拜访任务
                        }  else if (!accToNumTarget.isEmpty() && !accToDepMap.isEmpty() && (accToNumTarget.get(accToDepMap.get(targetEvent.whatid__c)).OCM_Category__c == 'H1' || accToNumTarget.get(accToDepMap.get(targetEvent.whatid__c)).OCM_Category__c == 'H0')) {
                            taskType = System.Label.visitHLevel; // H层拜访任务
                        } else {
                            taskType = System.Label.DailyVisit;// 日程拜访任务
                        }
                    }
                    if (targetEvent.Activity_Type2__c == '販売店') {
                        taskType = System.Label.AgencyVisit; // 经销商支持任务
                    }
                    if (targetEvent.Activity_Type2__c == '社外イベント') {
                        taskType = System.Label.campaignFollow; // 学术会议跟进任务
                    }
                } else {
                    taskType = System.Label.DailyVisit; //日常拜访
                    //20201123 zh 创建主动任务与维修合同关联 start
                    if (String.isNotBlank(targetEvent.Related_Service1_ID__c) && 
                        mainMaps.containsKey(targetEvent.Related_Service1_ID__c) && 
                        mainMaps.get(targetEvent.Related_Service1_ID__c).RecordType.DeveloperName == 'VM_Contract') {
                        taskType = System.Label.VMContract; //多年保修任务
                    }
                    if (String.isNotBlank(targetEvent.Related_Service1_ID__c) && 
                        mainMaps.containsKey(targetEvent.Related_Service1_ID__c) && 
                        (mainMaps.get(targetEvent.Related_Service1_ID__c).RecordType.DeveloperName == 'NewMaintenance_Contract'
                        || mainMaps.get(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(targetEvent.Purpose_TypeFSE__c))){
                    taskType = System.Label.SLA; //SLA任务
                    // 关联服务合同报告书任务
                    if(String.isNotBlank(targetEvent.Related_Service1_ID__c) &&
                        mainMaps.get(targetEvent.Related_Service1_ID__c).RecordType.DeveloperName == 'NewMaintenance_Contract'){
                        List<NewMaintenanceReport_Task__c> tempNMCTList = [SELECT id FROM NewMaintenanceReport_Task__c where NewMaintenance_Contract__c = :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(targetEvent.Purpose_TypeFSE__c))){
                    taskType = System.Label.InspectupTask; //点检任务
                }
                //2021-09-30  mzy  活动区分为 合同点检时，任务记录类型是点检任务 end

                // 名称拼写
                taskAccName = targetEvent.Location;
                System.debug('任务记录类型 :'+taskType);
                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(targetEvent.Related_Service1_ID__c)){
                    taskActive.Maintenance_Contract__c = 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(targetEvent.whatid__c)) {
                    if (targetEvent.whatid__c.startsWith('701')) {
                        taskActive.Campaign__c = targetEvent.whatid__c; //市场活动
                    }
                    if (targetEvent.whatid__c.startsWith('001')) {
                        taskActive.account__c = targetEvent.whatid__c; //客户
                        if (String.isNotBlank(targetEvent.Related_Opportunity1_ID__c)) {
                            taskActive.OpportunityId__c = 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  = :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 (targetEvent.Activity_Type2__c == '病院') {
                    taskAccType = '用户拜访';
                }
                if (targetEvent.Activity_Type2__c == '販売店') {
                    taskAccType = '经销商支持';
                }
                if (targetEvent.Activity_Type2__c == '社外イベント') {
                    taskAccType = '学术会议';
                }
                taskActive.Name = taskAccType + ':' + taskAccName;
            }
            //任务和日报管理开发 update by vivek 2020-04-17 end

            // event和task保存操作 start
            System.debug('事件21212:'+targetEvent);
            if(eventNew){
                insert targetEvent;             
                System.debug('事件Insert:'+targetEvent); 
            }else if(!eventNew && !isDelay){
                update targetEvent;                
                System.debug('事件update:'+targetEvent);
            }
            //任务和日报管理开发 update by vivek 2020-04-17 start
            // 正常接收任务
            if (!taskNew && !isDelay) {
                //2021-05-24 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  update  start
                if (targetEvent.Activity_Type2__c == '病院') {
                    taskAccType = '用户拜访';
                }
                if (targetEvent.Activity_Type2__c == '販売店') {
                    taskAccType = '经销商支持';
                }
                if (targetEvent.Activity_Type2__c == '社外イベント') {
                    taskAccType = '学术会议';
                }
                taskActive.Name =  taskAccType + ':'+targetEvent.Location;
                //2021-05-24 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  update  end
                update taskActive;
            }
            // 延期任务更新任务状态
            if (!taskNew && isDelay) {
                // update task;
                insert delayTask;
                taskActive.delayTask__c = delayTask.Id;
                update taskActive;
                System.debug('delayTask.Id======' + delayTask.Id);
                //2021-05-20 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  update start
                //如果不是OPD类型的话,延期则创建新的事件,原事件改为延期
                if(!targetEvent.OPDPlan_Flag__c && !eventNew){
                    //原事件 : 修改事件状态,勾选是否延期
                    Event oldevent = new Event();
                    oldevent.Id = targetEvent.Id;
                    oldevent.Subject = targetEvent.Subject +'【已延期】';
                    oldevent.EventStatus__c = '05 延期';
                    oldevent.isDelay__c = true;
                    oldevent.delayToDate__c = targetEvent.StartDateTime.Date();
                    StaticParameter.EscapeEventTrigger = true;
                    update oldevent;
                    StaticParameter.EscapeEventTrigger = false;
                    //新事件 : 清除原事件的Id,作为新事件添加
                    targetEvent.Id = null;
                    targetEvent.Task_ID__c = delayTask.Id;
                    targetEvent.delayReason__c = null;
                    insert targetEvent;
                }else{
                    //任务管理器过来的
                    targetEvent.Task_ID__c = delayTask.Id;
                    StaticParameter.EscapeEventTrigger = true;
                    update targetEvent;
                    StaticParameter.EscapeEventTrigger = false;
                }
            }
            //任务和日报管理开发 update by vivek 2020-04-17 end
            //2021-08-19  mzy SWAG-C5784H 【委托】事件无法延期 start 
            if(taskNew && (targetEvent.Activity_Type2__c != '病院' || 
                targetEvent.Activity_Type2__c != '販売店' || 
                targetEvent.Activity_Type2__c != '社外イベント')){
                //活动区分 非 病院 販売店  社外イベント  不会生成任务,只是更新事件的信息
                if(isDelay){
                    //延期:
                    //原事件 : 修改事件状态,勾选是否延期,填写延期至的时间
                    Event oldevent = new Event();
                    oldevent.Id = targetEvent.Id;
                    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();
                    StaticParameter.EscapeEventTrigger = true;
                    update oldevent;
                    StaticParameter.EscapeEventTrigger = false;

                    //新事件 : 清除原事件的Id,作为新事件添加
                    targetEvent.Id = null;
                    targetEvent.delayReason__c = null;
                    insert targetEvent;
                }
            }
            //zzm 20240204 新建事件 公司工作 报错生成了任务bug修复 start
            if (taskNew && taskActive != null && (targetEvent.Activity_Type2__c == '病院' || 
                targetEvent.Activity_Type2__c == '販売店' || 
                targetEvent.Activity_Type2__c == '社外イベント')) {
                //zzm 20240204 新建事件 公司工作 报错生成了任务bug修复 start
                insert taskActive;
                targetEvent.Task_ID__c = taskActive.Id;
                StaticParameter.EscapeEventTrigger = true;
                update targetEvent;
                StaticParameter.EscapeEventTrigger = false;
            }
            // event和task保存操作 end

            // OPD相关 start
            if (Boolean.valueOf(eventLineMap.get('IsOPDPlan'))) {
                StaticParameter.EscapeEventTrigger = true;
                StaticParameter.EscapeTaskcTrigger = true;
                saveOPDPlan(targetEvent, taskActive, delayTask, isDelay, isBefore, products);
                StaticParameter.EscapeEventTrigger = false;
                StaticParameter.EscapeTaskcTrigger = false;
                //2021-04-29 mzy  WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  add   start
                //任务是OPD类型 , 事件 原日期 > 现日期 ,说明提前
                if(eveStartTime != null && eveStartTime.Date() > targetEvent.StartDateTime.Date()){
                    createCancelPostponePlan_Advance(targetEvent);
                }
                //2021-04-29 mzy  WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  add   end     
                //2021-05-20 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  update start
                //如果是OPD类型延期的话
                if(!taskNew && isDelay && !eventNew){
                    createCancelPostponePlan_Delay(taskActive, targetEvent);
                }      
                //2021-05-20 mzy WLIG-BX3DQ5 【委托】Outlook日历和SFDC日历同步  update end
            }
            return targetEvent.Id;
        }
        catch(Exception e){
            String originalString = e.getMessage();
            String extractedContent = 'ERROR:' + originalString.substringBetween('EXCEPTION,', ': [');
            System.debug(LoggingLevel.INFO, '*** e: ' + e  + e.getLineNumber() + '行');
            return extractedContent;
        }
    }

    public static boolean confirmCheck(task__c task, Event targetEvent) {
        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;
    }

    // OPD的延期取消申请 - 提前
    public static void createCancelPostponePlan_Advance(Event targetEvent){
        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;
    }

    // OPD的延期取消申请 - 延期
    public static void createCancelPostponePlan_Delay(task__c taskActive, Event targetEvent){
        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(taskActive.delayReason__c);
        //5.申请类型
        tempCancelPostponePlan.ApplyType__c = '延期';
        tempCancelPostponePlan.isDailyReportDelay__c = true;//2022-4-22 yjk 事件延期odp增加标识，防止循环
        insert tempCancelPostponePlan;
    }

    @AuraEnabled
    public static String  saveLogic(String records,String products){
        try{
            String ErrorMessage = '';
            Map<String, Object> eventLineMap = (Map<String, Object>) JSON.deserializeUntyped(records);
            
            List<ProLine> ProLineList = 
            (List<ProLine>)System.JSON.deserialize(products, List<ProLine>.class);
            Date today = Date.today();
            DateTime startDateTime;
            DateTime endDateTime;
            Date startDate;
            Date endDate;

            // 获得事件id，查找事件
            String eventId = eventLineMap.get('EventId') != null && eventLineMap.get('EventId') != '' ? String.valueOf(eventLineMap.get('EventId')) : null;
            Event targetEvent = null;
            
            if (String.isNotBlank(eventId)) {
                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,Activity_Purpose__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];
            }

            // 获得任务id，查找任务
            String taskId = eventLineMap.get('TaskId') != null && eventLineMap.get('TaskId') != '' ? String.valueOf(eventLineMap.get('TaskId')) : null;
            task__c task = null;
            if (String.isNotBlank(taskId)) {
                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];
            }
           
            if(String.isBlank(String.valueOf(eventLineMap.get('StartTime')))){
                return 'ERROR:请输入开始时间';
            }else{
                startDateTime = (Datetime)JSON.deserialize('"' + String.valueOf(eventLineMap.get('StartTime')) + '"', Datetime.class);
                startDate = startDateTime.Date();
            }
            if(String.isBlank(String.valueOf(eventLineMap.get('EndTime')))){
                return 'ERROR:请输入结束时间' ;
            }else{
                endDateTime = (Datetime)JSON.deserialize('"' + String.valueOf(eventLineMap.get('EndTime')) + '"', Datetime.class);
                endDate = endDateTime.Date();
            }
            // 提前和延期判断

            Boolean isDelay = eventLineMap.get('isDelay') != null && String.valueOf(eventLineMap.get('isDelay')) == 'true' ? true : false;
            Boolean isBefore = eventLineMap.get('isBefore') != null && String.valueOf(eventLineMap.get('isBefore')) == 'true' ? true : false;
            System.debug('===========zzm==========eventLineMap.get isBefore' +eventLineMap.get('isBefore'));
            System.debug('===========zzm==========isBefore' +isBefore);
            // 事件判断
            if (targetEvent != null) {
                // 获得事件的开始结束时间
                Date EventStartDate = targetEvent.StartDateTime.Date();
                Date EventEndDate = targetEvent.EndDateTime.Date();
                Boolean isDateDelay = false;
                Boolean isDateBefore = false;
                // 判断日期延后
                if(((EventStartDate != null && startDate > EventStartDate) || (EventEndDate!=null&&endDate > EventEndDate) || (eventId == null && taskId != null)) && isDelay){
                    isDateDelay = true;
                }
                // 判断日期提前
                if (((EventStartDate != null && startDate <= EventStartDate) || 
                    (EventEndDate!=null&&endDate <= EventEndDate) )) {
                    isDateBefore = true;
                }
                System.debug('===========zzm==========startDate' +startDate);
                System.debug('===========zzm==========EventStartDate' +EventStartDate);
                System.debug('===========zzm==========endDate' +endDate);
                System.debug('===========zzm==========EventEndDate' +EventEndDate);
                System.debug('===========zzm==========isDateBefore' +isDateBefore);
                // 日期没变化时报错
                if(isDelay && !isDateDelay){
                    return '延期必须修改 开始时间 和 结束时间 的日期'; 
                }
                if(isBefore && !isDateBefore){
                    return '提前必须修改 开始时间 和 结束时间 的日期';
                }
            }
            // 任务判断
            //如果是上级分配的任务,则拜访日期不能超过希望完成日
            if(task != null &&'上级分配任务'.equals(task.taskDifferent__c)&&task.HopeCompletionDate__c!=null&&targetEvent.StartDateTime.date()>task.HopeCompletionDate__c&& task.HopeCompletionDate__c > Date.today()){
                return '接收任务时,上级分配的任务拜访日期不能超过希望完成日('+String.valueOf(task.HopeCompletionDate__c)+')';
            }
            //2021-11-26  mzy  任务管理改善  end
            if(task != null && startDate > task.Finish_Date__c){
                return '请填写 开始时间 至 '+String.valueOf(task.Finish_Date__c) +'之前的日期';
            }
            //2021-07-16  mzy  update  CHAN-C4G5DK  任务的未执行判断时间修改 end

            if (task != null && task.Activity_Date__c != null && startDate > task.Activity_Date__c && String.isBlank(targetEvent.delayReason__c)) {
                return '延期请先在事件详情页点击【延期】按钮选择延期理由';
            }
            if (isDelay &&task != null &&task.Activity_Date__c != null && startDate <= task.Activity_Date__c) {
                return '延期日期必须晚于任务拜访日期';
            }
            //lightning修改hql 20231026 start
            
            if (isBefore && task != null && task.Activity_Date__c != null 
                // kk 20231128  提前能不动日期 修改其他数据 start
                //&& startDate >= task.Activity_Date__c
                && startDate > task.Activity_Date__c
                // kk 20231128  提前能不动日期 修改其他数据 start
                ) {
                return '提前日期必须早于任务拜访日期';
            }

            String oppId = String.valueOf(eventLineMap.get('OpportunityId'));
            String ActivityType2 = String.valueOf(eventLineMap.get('ActivityType2'));
            String ActivityPurposeFSE = String.valueOf(eventLineMap.get('ActivityPurposeFSE'));//拜访目的
            if (startDate <= today) {
                return '请输入今天以后的日期';
            }
            if (startDate > today.addDays(60)) {
                return '请输入60天以内的日期';
            }
            if(startDateTime > endDateTime){
                return '结束日期必须大于开始日期';
            }
            if(startDate != endDate){
                return '开始时间 和 结束时间 必须在同一天';
            }
            if((String.isBlank(ActivityType2)
                || String.isBlank(ActivityPurposeFSE))){
                return '请输入必填值';
            }
            System.debug('ActivityType2----------' + ActivityType2);
            if(ActivityType2 == '病院' && String.isBlank(String.valueOf(eventLineMap.get('AccountId')))){
                return '科室不能为空';
            }
            Boolean isOPDPlan = false;
            if(eventLineMap.get('IsOPDPlan') == null){
                isOPDPlan = false;
            }else{
                isOPDPlan = Boolean.valueOf(eventLineMap.get('IsOPDPlan'));
            }
            
            if (isOPDPlan){
                 if (ProLineList.size() == 0) {
                    return '【opd计划】勾选时且关联询价时，计划出借的备品必须填写';
                    // isError = true;
                }
                if(String.isBlank(oppId) && String.isBlank(String.valueOf(eventLineMap.get('NoOppReason')))) {
                    return '【opd计划】勾选时，涉及的询价为空，必须填写无询价申请理由';
                }
                if(String.isNotBlank(oppId)){
                    Opportunity opp = [SELECT Id,Name,StageName FROM Opportunity WHERE Id = :oppId];
                    if(opp.StageName=='敗戦' || opp.StageName=='削除' || opp.StageName=='注残' || opp.StageName=='出荷' || opp.StageName=='完了'){
                        return '涉及的询价状态为：失单、取消、注残、发货、完毕，不允许创建OPD计划';                
                    }
                } 
            }
            return 'Success';
        }
        catch(Exception e){            
            String originalString = e.getMessage();
            String extractedContent = originalString.substringBetween('EXCEPTION,', ': [');
            System.debug(LoggingLevel.INFO, '*** e: ' + e  + e.getLineNumber() + '行');
            return extractedContent;
        }
    }
    
    //20240228 sx 添加参数isBefore
    public static void saveOPDPlan(Event event, task__c task, task__c delayTask, Boolean isDelay, Boolean isBefore, String products) {
        System.debug('saveOPDPlan----event===' + event + 'task===' + task);
        OPDPlan__c opdPlan = new OPDPlan__c();
        opdPlan.OwnerId =  event.OwnerId;
        opdPlan.Activity_Type2__c = event.Activity_Type2__c;
        opdPlan.StartDateTime__c = event.StartDateTime;
        opdPlan.EndDateTime__c = event.StartDateTime.addMinutes(event.DurationInMinutes);
        if(event.OPD_Plan__c == null){
            opdPlan.OPDPlan_ImplementDate__c = event.StartDateTime.date();
        }
        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.Related_Opportunity1__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.NoOpp_Reason__c = null;  
        }else{
            opdPlan.NoOpp_Reason__c = event.noOpp_Reason__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.OPDType__c = '事件';
        opdPlan.RentalReson__c = 'OPD'; 
        opdPlan.Task_ID__c = event.Task_ID__c;

        Boolean opdNew = true;
        if(event.Opd_Plan__c == null){
            insert opdPlan;  
        }else if(event.Opd_Plan__c != null){
            opdPlan.Id = event.Opd_Plan__c;
            if(isDelay){
                //如果是延期的话则OPD关联的任务更新为延期任务
                opdPlan.Task_ID__c = delayTask != null ? delayTask.Id : event.Task_ID__c;
            }
            opdNew = false;
            update opdPlan;
        }

        String quantity = '';
        String quantityNo = '';
        String quantitySys = '';
        RecordType recordType = [SELECT Id,Name FROM RecordType WHERE SobjectType = 'Plan_Rental_Equipment__c' AND Name = '事件'];

        List<Plan_Rental_Equipment__c> planREDeleteList = new List<Plan_Rental_Equipment__c>();
        List<Plan_Rental_Equipment__c> planREInsertList = new List<Plan_Rental_Equipment__c>();
        Map<String,ProLine> ProLineMap = new Map<String,ProLine>();
        Map<String,Plan_Rental_Equipment__c> planREMap = new Map<String,Plan_Rental_Equipment__c>();
        // 旧数据获取
        List<Plan_Rental_Equipment__c> beforePlanREList = [SELECT Id, ProductCode__c FROM Plan_Rental_Equipment__c WHERE Event_ID__c = :event.Id];
        
        List<ProLine> ProLineList = 
            (List<ProLine>)System.JSON.deserialize(products, List<ProLine>.class);
        List<Plan_Rental_Equipment__c> ineuqipments = new List<Plan_Rental_Equipment__c>();
        for(ProLine pro : ProLineList){
            ProLineMap.put(pro.ProductCode, pro);
            Plan_Rental_Equipment__c planRE = new Plan_Rental_Equipment__c();
            planRE.Event_ID__c = event.Id;
            planRE.Quote__c = pro.QuoteId;
            planRE.RecordTypeId = recordType.Id;
            planRE.Name = pro.Name;
            planRE.Rental_Equipment__c = pro.Name;
            planRE.Rental_Quantity__c = String.valueOf(pro.Quantity);
            planRE.OPD_Plan__c = opdPlan.Id;
            planRE.ProductCode__c = pro.ProductCode;
            planRE.MDM_Model_No__c = pro.ProductModel;
            planRE.FixtureModel__c = pro.FixtureModel;
            planRE.Opportunity__c = event.Related_Opportunity1_ID__c;
            ineuqipments.add(planRE);
            if(String.isNotBlank(pro.FixtureModel)){
                quantitySys += pro.FixtureModel + '*' + pro.Quantity + '; ';
            }
            if(pro.QuoteId == null){
                quantity += pro.ProductModel + '*' + pro.Quantity + '; ';
            }else{
                quantityNo += pro.ProductModel + '*' + pro.Quantity + '; ';
            }
        }
        
        for(Plan_Rental_Equipment__c planRE : beforePlanREList){
            planREMap.put(planRE.ProductCode__c, planRE);
        }
        for(Plan_Rental_Equipment__c planRE : beforePlanREList){ 
            if (ProLineMap.get(planRE.ProductCode__c) == null) {
                Plan_Rental_Equipment__c planREDelete = new Plan_Rental_Equipment__c();
                planREDelete.Id = planRE.Id;
                planREDeleteList.add(planREDelete);
            }   
        }
        for(Plan_Rental_Equipment__c proInsert : ineuqipments) {
            if (planREMap.get(proInsert.ProductCode__c) == null) {
                planREInsertList.add(proInsert);
            }
        }
        if (planREDeleteList.size() > 0) {
            delete planREDeleteList;
        }
        System.debug('opdNew==' + opdNew + 'isDelay===' + isDelay + 'isBefore==' + isBefore);
        if (planREInsertList.size() > 0 && opdNew) {        //20240228 sx 只有新建的时候才增加小表数据
            insert planREInsertList;
        }

        opdPlan.PlanProdDetail__c = quantityNo + quantity;
        opdPlan.EquipmentNotFromOpp__c = quantity;
        opdPlan.EquipmentFromOpp__c = quantityNo;
        opdPlan.PlanProdDetailSys__c = quantitySys;
        opdPlan.PlanProdDetailSysT__c = quantitySys.length() > 255 ? quantitySys.substring(0, 255):quantitySys; // 计划出借战略产品文本 add by ljh 20240302
                
        if (opdNew) {
            opdPlan.Status__c = '提交';  
        }

        update opdPlan;

        if(opdNew){
            LexOPDSupplementaryController.newRentalApply(opdPlan.Id);   //20240227 sx 延期申请会不触发新建备品申请单
        }
        

        // 再更新事件
        event.Opd_Plan__c = opdPlan.Id;
        event.PlanProdDetail__c = quantity;
        update event;

        // 更新任务
        if (task != null && !isDelay && task.Opd_Plan__c != opdPlan.Id) {
            task.Opd_Plan__c = opdPlan.Id;
            update task;
        }
        //延期任务
        if (delayTask != null && isDelay && event.Opd_Plan__c != delayTask.Opd_Plan__c) {
            delayTask.Opd_Plan__c = event.Opd_Plan__c;
            update delayTask;
        }
    }

    public class ProLine {
        @AuraEnabled
        public String Id { get; set; } 
        @AuraEnabled
        public Integer Quantity { get; set; } 
        @AuraEnabled
        public String Name { get; set; } 
        @AuraEnabled
        public String QuoteNo { get; set; } 
        @AuraEnabled
        public String QuoteId { get; set; } 
        @AuraEnabled
        public String ProductCode { get; set; }  
        @AuraEnabled
        public String ProductModel { get; set; } 
        @AuraEnabled
        public String FixtureModel { get; set; } 
    } 

    public class EventData {
        @AuraEnabled
        public Event eventData { get; set;}
        @AuraEnabled
        public Boolean allDisable { get; set;}
        @AuraEnabled
        public Boolean isDisActivityPurposeFSE { get; set;}
    }

    public static void runiplus() {
        Integer i = 0;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
        i++;
    }
}