public without sharing class CancelPostponePlanHandler  extends Oly_TriggerHandler {

    private Map<Id, CancelPostponePlan__c> newMap;
    private Map<Id, CancelPostponePlan__c> oldMap;
    private List<CancelPostponePlan__c> newList;
    private List<CancelPostponePlan__c> oldList;
    //2021/02/07 liying start SWAG-BXVDPJ 
    public static Integer FIELDMAX = 100;
    //2021/02/07 liying end SWAG-BXVDPJ 
    public CancelPostponePlanHandler() {
        this.newMap = (Map<Id, CancelPostponePlan__c>) Trigger.newMap;
        this.oldMap = (Map<Id, CancelPostponePlan__c>) Trigger.oldMap;
        this.newList = (List<CancelPostponePlan__c>) Trigger.new;
        this.oldList = (List<CancelPostponePlan__c>) Trigger.old;
    }

    protected override void afterInsert() {
        ChangeStatus();
    }

    protected override void afterUpdate() {
        ChangeStatus();
    }

    // protected override void afterUpdate() {
    //     CleanOPDLendSort();
    // }
    private void ChangeStatus () {

        List<OPDPlan__c> oPDPlans = new List<OPDPlan__c>();
        // SWAG-BUF6J5 20201111  you start
        Set<Id> opdIdSet = new Set<Id>(); 
        Set<String> cancelIdSet = new Set<String>(); //手动调回审批
        // SWAG-BUF6J5 20201111  you end
        //2021-08-11  mzy   SWAG-C5RAZV  事件——计划 延期 调查  start
        //存放每条OPD对应的取消理由
        Map<String,String> opdCancelReasonMap = new Map<String,String>();
        //2021-08-11  mzy   SWAG-C5RAZV  事件——计划 延期 调查  end

        for (CancelPostponePlan__c cpp : newList) {
            OPDPlan__c opdplan = new OPDPlan__c();

            // if (oldMap.get(cpp.Id).get('Status__c') != cpp.Status__c && cpp.Status__c == '取消成功') {
            if (Trigger.isInsert && cpp.Status__c == '取消成功' ||
                Trigger.isUpdate && oldMap.get(cpp.Id).get('Status__c') != cpp.Status__c && cpp.Status__c == '取消成功') {
                // SWAG-BUF6J5 20201111  you start
                //opdIdSet.add(cpp.CancelOPDPlan__c);
                cancelIdSet.add(cpp.CancelOPDPlan__c);
                // SWAG-BUF6J5 20201111  you end
                opdplan.Id =  cpp.CancelOPDPlan__c;
                opdplan.Status__c = '取消';
                // CHAN-BBACTU LHJ 记录最新延期 Start
                opdplan.OPD_DelayCancel_Last__c = cpp.id;
                // CHAN-BBACTU LHJ 记录最新延期 End
                // ***SWAG-BZCAHL***XHL***20210329***Start*********
                if ('备品不足'.equals(cpp.cancelReasonCombobox__c)) {
                    opdplan.CancelOpdPlan__c = true;    
                }
                // ***SWAG-BZCAHL***XHL***20210329***End*********
                oPDPlans.add(opdplan);

                //2021-08-11  mzy   SWAG-C5RAZV  事件——计划 延期 调查  start
                opdCancelReasonMap.put(opdplan.Id ,cpp.cancelReasonCombobox__c);
                //2021-08-11  mzy   SWAG-C5RAZV  事件——计划 延期 调查  end


            // } else if (oldMap.get(cpp.Id).get('Status__c') != cpp.Status__c && cpp.Status__c == '延期成功') {
            } else if (Trigger.isInsert && cpp.Status__c == '延期成功' ||
                    Trigger.isUpdate && oldMap.get(cpp.Id).get('Status__c') != cpp.Status__c && cpp.Status__c == '延期成功') {
                
                opdplan.Id =  cpp.CancelOPDPlan__c;

                // SWAG-BXDC25 mzy 审批后，更新【OPD计划实施日期temp】  Start
                //opdplan.OPDPlan_ImplementDate__c = cpp.NextPlanDate__c;
                opdplan.OPDPlan_ImplementDate_temp__c = cpp.NextPlanDate__c;
                // SWAG-BXDC25 mzy 审批后，更新【OPD计划实施日期temp】  End           
                // CHAN-BBACTU LHJ 记录最新延期 Start
                opdplan.OPD_DelayCancel_Last__c = cpp.id;
                // CHAN-BBACTU LHJ 记录最新延期 End
                // SWAG-BXW4AH  XHL 2021/2/7 【委托】 OPD计划再申请逻辑设置 Start    
                if (Trigger.isInsert && cpp.cancelReasonCombobox__c == '系统自动延期' ) {
                       //OPD计划已进行 系统自动延期 标记(只在OPD计划取消/延期新增的时候进行标记)
                       opdplan.SystemDelayMark__c = true;
                }
                // SWAG-BXW4AH  XHL 2021/2/7 【委托】 OPD计划再申请逻辑设置 End
                //2022-1-11 yjk 设置是否日报延期
                opdplan.isDailyReportDelay__c = cpp.isDailyReportDelay__c;
                oPDPlans.add(opdplan);
            }
        }
        if (cancelIdSet.size() > 0) {
            List<Approval.ProcessWorkitemRequest> requests = new List<Approval.ProcessWorkitemRequest> ();
            Map<ID,ProcessInstance> piMap = New Map<ID,ProcessInstance>([Select Id from ProcessInstance where TargetObjectId IN :cancelIdSet]);
            system.debug('==cancelIdSet=='+cancelIdSet);
            for(ProcessInstanceWorkItem wi : [Select Id from ProcessInstanceWorkItem where ProcessInstanceId IN :piMap.keySet()]){
                Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                req2.setAction('Removed');
                req2.setWorkitemId(wi.Id);
                requests.add(req2);
            }
            system.debug('==requests.size()=='+requests.size());
            if (requests.size() > 0) {
                Approval.ProcessResult[] processResults = null;
                processResults = Approval.process(requests, true);
                system.debug('==调回opd计划审批得结果=='+processResults);
            }
        }

        if (oPDPlans.size() > 0) {
            update oPDPlans;
        }
        // SWAG-BUF6J5 20201111  you start
        if (cancelIdSet.size() > 0) {//查询opd计划下得所有备品借出申请  更新 状态
            List<Rental_Apply__c> Rentals = new List<Rental_Apply__c>();
            List<Rental_Apply__c> RentalList = [select id,Cancel_Reason__c , Loaner_cancel_request__c,OPDPlan__c from Rental_Apply__c where OPDPlan__c in: cancelIdSet and Status__c <> '取消'];
            Set<String> cancelIdSet1 = new Set<String>(); //手动调回审批
            SS_Batch_Column_Mapping__c mpdMapping = SS_Batch_Column_Mapping__c.getValues('Rental_Apply_OPD_Cancle');
            //2021/02/07 liying SWAG-BXVDPJ start           
            Map<String,String> opdMap = new Map<String,String>();
            for (Integer i = 1; i <= FIELDMAX; i++) {
                String lpadI = ('00' + i).right(3);
                String fromColumn = 'From_Column_' + lpadI + '__c';
                //2021-06-30  mzy  Outlook日历和SFDC日历 开发 update  start  
                if(mpdMapping!=null){
                    //注:这个得判空,否则转字符串会报错
                    String apiStr = String.valueOf(mpdMapping.get(fromColumn));
                    if (String.isBlank(apiStr) == false) {
                        String ssColumn = 'SS_Column_' + lpadI + '__c';
                        String ssApiStr = String.valueOf(mpdMapping.get(ssColumn));
                        opdMap.put(apiStr,ssApiStr);
                        //2021/02/07 liying SWAG-BXVDPJ end      
                    }
                }
                //2021-06-30  mzy  Outlook日历和SFDC日历 开发 update  start

            }
            for (CancelPostponePlan__c cpp : newList) {
                if (RentalList.size() > 0) {
                  for (Rental_Apply__c rtl : RentalList) {
                      if(rtl.OPDPlan__c == cpp.CancelOPDPlan__c && cpp.if_HaveRental_Apply__c == false){
                          cancelIdSet1.add(rtl.id);
                          // 2021/02/07 liying SWAG-BXVDPJ start
                          if(opdMap.containsKey(cpp.cancelReasonCombobox__c)){
                             rtl.Cancel_Reason__c = opdMap.get(cpp.cancelReasonCombobox__c).split(';')[1];
                             rtl.Loaner_cancel_reason__c = opdMap.get(cpp.cancelReasonCombobox__c).split(';')[0];   
                             rtl.Loaner_cancel_request__c = opdMap.get(cpp.cancelReasonCombobox__c).split(';')[0];  
                          }
                          rtl.Status__c = '取消';
                          rtl.if_HaveOPD_Apply__c = true;
                          rtl.if_HaveOPDPlanCan__c = true;//备品借出申请审批调回得时候 状态会变成 “草案中”，打标机是为了防止这样
                          Rentals.add(rtl);
                      }
                        
                  }
                }
            } 
            if (cancelIdSet1.size() > 0) {
            List<Approval.ProcessWorkitemRequest> requests = new List<Approval.ProcessWorkitemRequest> ();
            Map<ID,ProcessInstance> piMap = New Map<ID,ProcessInstance>([Select Id from ProcessInstance where TargetObjectId IN :cancelIdSet1]);
            system.debug('==cancelIdSet1=='+cancelIdSet1);
            for(ProcessInstanceWorkItem wi : [Select Id from ProcessInstanceWorkItem where ProcessInstanceId IN :piMap.keySet()]){
                Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
                req2.setAction('Removed');
                req2.setWorkitemId(wi.Id);
                requests.add(req2);
            }
            system.debug('==requests.size()=='+requests.size());
            if (requests.size() > 0) {
                Approval.ProcessResult[] processResults = null;
                processResults = Approval.process(requests, true);
                system.debug('==调回审批得结果=='+processResults);
            }
        }
             if(Rentals.size()>0){
                   update Rentals;
                } 
        }
        // SWAG-BUF6J5 20201111  you end
        //2021-08-11  mzy   SWAG-C5RAZV  事件——计划 延期 调查  start
        //0.取消
        if(cancelIdSet.size()>0){
           List<Task__c> needCancelTasks = new List<Task__c>();
           List<String> taskIds = new List<String>();
           //查询 OPD所 关联的任务 ,将取消理由和状态赋值
           List<OPDPlan__c>  OPDList = [SELECT Id,Task_ID__c,Task_ID__r.Initial_Task__c,Task_ID__r.taskType__c  FROM OPDPlan__c where Id in : cancelIdSet AND Task_ID__r.taskStatus__c != '04 取消'];
          
           if(OPDList.size()>0){
                for(OPDPlan__c op : OPDList){

                    if(op.Task_ID__c != null){
                        task__c t = new task__c();
                        t.Id = op.Task_ID__c;
                        t.TaskStatus__c = '04 取消';
                        t.cancelDate__c = date.today();
                        t.cancelReasonOther__c = '';
                        String cancelLY = opdCancelReasonMap.get(op.Id);

                        System.debug('取消理由====:'+cancelLY);
                        if('询价跟进'.equals(op.Task_ID__r.taskType__c)){
                            t.cancelReason__c ='其他';
                            t.cancelReasonSelect__c = '其他';
                            t.cancelReasonOther__c = cancelLY ;
                        }else if('医院取消试用'.equals(cancelLY)){
                           t.cancelReason__c = '客户时间变更或冲突';
                           t.cancelReasonSelect__c = '客户事件变更或冲突';
                        }else if('计划调整变更'.equals(cancelLY) || '工作计划修改'.equals(cancelLY)){
                           t.cancelReason__c ='与其他突发事件冲突';
                           t.cancelReasonSelect__c = '与其他突发事件冲突';
                        }else if('问题已解决无需OPD'.equals(cancelLY)){
                           t.cancelReason__c ='问题已解决无需OPD';
                           t.cancelReasonSelect__c = '问题已解决无需OPD';
                        }else if('手术取消'.equals(cancelLY)){
                           t.cancelReason__c ='无合适病例（适合病例流失）OPD取消';
                           t.cancelReasonSelect__c = '无合适病例（适合病例流失）OPD取消';
                        }else if('客户已采购竞品，失单'.equals(cancelLY)){                        
                           t.cancelReason__c ='客户已采购竞品，失单';
                           t.cancelReasonSelect__c = '客户已采购竞品，失单';
                        }else if('计划重复'.equals(cancelLY)){
                           t.cancelReason__c ='计划重复';
                           t.cancelReasonSelect__c = '计划重复'; 
                        }else if('信息填写错误'.equals(cancelLY)){
                            t.cancelReason__c ='信息填写错误';
                            t.cancelReasonSelect__c = '信息填写错误'; 
                        }else if('担当离职'.equals(cancelLY) 
                            || '申请单合并'.equals(cancelLY) || '没完成备品申请'.equals(cancelLY)
                            || '其他'.equals(cancelLY)  || '修理对应'.equals(cancelLY) || '备品不足'.equals(cancelLY)){
                           t.cancelReason__c ='其他';
                           t.cancelReasonSelect__c = '其他';
                           t.cancelReasonOther__c = (cancelLY == '备品不足'?'备品原因':cancelLY );
                        }

                        taskIds.add(t.Id);

                        needCancelTasks.add(t);

                        if(op.Task_ID__r.Initial_Task__c != null){
                           task__c Initial_Task = new task__c();
                           Initial_Task.Id = op.Task_ID__r.Initial_Task__c ;
                           Initial_Task.cancelReason__c =t.cancelReason__c;
                           Initial_Task.cancelReasonSelect__c =t.cancelReasonSelect__c;
                           Initial_Task.cancelReasonOther__c = t.cancelReasonOther__c;
                           needCancelTasks.add(Initial_Task);

                           //taskIds.add(Initial_Task.Id);
                        }
                    }
                    
                }

                if(needCancelTasks.size()>0){
                    update needCancelTasks;
                }
           }

            //查询 任务所对应的事件 ,将取消理由和状态赋值
            if(taskIds.size()>0){
               List<Event> elist = [SELECT ID,Subject,Task_ID__c,EventStatus__c FROM Event WHERE Task_ID__c IN :taskIds];
                if(elist.size()>0){
                    for(Event e : elist){
                       for(Task__c t : needCancelTasks){
                            if(String.ValueOf(e.Task_ID__c).contains(t.Id)){
                                if(!'05 延期'.equals(e.EventStatus__c)){
                                    if(e.Subject!=null&&String.isNotBlank(String.valueOf(e.Subject))&&String.valueOf(e.Subject).indexOf('【已取消】') == -1 ){
                                        e.Subject += '【已取消】';
                                    }else if(e.Subject==null ||String.isBlank(String.valueOf(e.Subject))){
                                        e.Subject  = '【已取消】';
                                    }
                                    e.EventStatus__c = '04 取消';
                                }
                                e.cancelReason__c = t.cancelReason__c;
                                e.cancelReasonSelect__c = t.cancelReasonSelect__c;
                                e.cancelReasonOther__c = t.cancelReasonOther__c;
                            }
                       }
                    }
                    
                    update elist;
               }               
            }

        }

        //2021-08-11  mzy   SWAG-C5RAZV  事件——计划 延期 调查  end
    }

    // private void CleanOPDLendSort(){
    //   List<OPDPlan__c> needCleanOPDLendSort = new List<OPDPlan__c>();
    //   for (CancelPostponePlan__c cpp : newList) {
    //      OPDPlan__c opdplan = new OPDPlan__c();
    //      if (oldMap.get(cpp.Id).get('Status__c') != cpp.Status__c && cpp.Status__c == '延期成功') {
    //              opdplan.Id =  cpp.CancelOPDPlan__c;
    //              opdplan.OPDLendSort__c = null;
    //              needCleanOPDLendSort.add(opdplan);
    //       }
    //   }
    //   if(needCleanOPDLendSort.size()>0){
    //        update needCleanOPDLendSort;
    //   }
    // }
    // 2020-11-04 mzy SWAG-BSC5WP 延期成功后,取消 备品优先度 的值,只保留 备品出借优先度草案中 end
}