/**
20201106 you
SWAG-BSC5WP
可能存在的问题 3月份创建的 opd计划是 4月份这时候还没有目标客户，所以没值
以实施日期 为标准 计算当财年 \上财年 的 目标客户
opd计划上 字段 “是否营业目标客户”来源（1/0）：：---计划出借备品信息字段 上显示 借出得哪个产品  就去对应得  对象“目标客户”（当年）上匹配对应得字段
（目标客户：）如果有 则显示1 ，没有显示0
                “是否有询价 ”    同上      去目标客户上  找 询价数：  如果有值就显示1 否则显示0
                “是否已有设备”   同上      去目标客户上  找 保有设备数：  如果有值就显示1 否则显示0
                “本期OPD次数”        同上     去目标客户上  找 opd数  累计相加
                出借次数
                是否产品OPD目标客户   看opd对象
**/
public without sharing class OPDPlanHandler extends Oly_TriggerHandler {
    /**
     *   Enum representing each of before/after CRUD events on Sobjects
     */
    private Map<Id, OPDPlan__c> newMap;
    private Map<Id, OPDPlan__c> oldMap;
    private List<OPDPlan__c> newList;
    private List<OPDPlan__c> oldList;

    public OPDPlanHandler() {
        this.newMap = (Map<Id, OPDPlan__c>) Trigger.newMap;
        this.oldMap = (Map<Id, OPDPlan__c>) Trigger.oldMap;
        this.newList = (List<OPDPlan__c>) Trigger.new;
        this.oldList = (List<OPDPlan__c>) Trigger.old;
    }

    protected override void afterUpdate() {
        //计划延期后，在延期日新规日报时间
        newEventIns();
        //计划取消后，删除日报
        //cancelEventApply();

        //2021-9-16 yjk 当opd计划完成时，更新任务和事件完成
        updateTaskAndEvent();

    }
    protected override void beforeUpdate() {

        // 20201022  mzy SFDC-BUF6LN    add
        //新建时,OPD状态为提交时,OPD无报告申请时  给推广经理赋值
        updateMng();
        // 20201022  mzy SFDC-BUF6LN    end
        //start SWAG-BSC5WP 20201106 you
        NewOppPlan();
        updateOppPlan();
        //end SWAG-BSC5WP 20201106 you
    }
    //start SWAG-BSC5WP 20201106 you
    protected override void afterInsert() {
       //start SWAG-BSC5WP 20201106 you
        NewOppPlan();
        //end SWAG-BSC5WP 20201106 you
        
    }

    // ***SWAG-BZCAHL***XHL***20210331***START*********
    protected override void beforeInsert() {
       
        beforeOpdPlan();
    }

    private void beforeOpdPlan() {
        //  OPD计划点击"再申请"按钮 创建生成的新OPD计划 的 再申请 复选框 赋值 
        List<String> originalOpdPlanIdList = new List<String>();
        Map<String,OPDPlan__c> originalOpdPlanIdMap = new Map<String,OPDPlan__c>();

        List<String> originalOpdPlanApplicationIdList = new List<String>();
        Map<String,OPDPlan__c> originalOpdPlanApplicationIdMap = new Map<String,OPDPlan__c>();

        for (OPDPlan__c nObj : newList) {
            if (String.isNotBlank(nObj.OriginalOpdPlan__c) && String.isNotBlank(nObj.OriginalOpdPlanApplication__c)) {
                // 报错
                nObj.OriginalOpdPlan__c.addError('原OPD计划(再申请) 与 原OPD计划(补充申请) 只能一个有值');
            }
            if (String.isNotBlank(nObj.OriginalOpdPlan__c)) {
                originalOpdPlanIdList.add(nObj.OriginalOpdPlan__c);
            }
            if (String.isNotBlank(nObj.OriginalOpdPlanApplication__c)) {
                originalOpdPlanApplicationIdList.add(nObj.OriginalOpdPlanApplication__c);
            }
            //20210422 ljh add SWAG-BZK68V start
            if (String.isNotBlank(nObj.OriginalOpdPlanRental__c)) {
                originalOpdPlanApplicationIdList.add(nObj.OriginalOpdPlanRental__c);
            }
            //20210422 ljh add SWAG-BZK68V end

        }
        system.debug('originalOpdPlanApplicationIdList:'+originalOpdPlanApplicationIdList.size());
        //根据模型出借配套 更新 模型出借产品 精琢技术 wql 2021/04/13 start
        updateModelLending(newList);
        //根据模型出借配套 更新 模型出借产品 精琢技术 wql 2021/04/13 end
        // OPD计划 补充申请
        system.debug('originalOpdPlanApplicationIdList:'+originalOpdPlanApplicationIdList.size());
        if (originalOpdPlanApplicationIdList.size() > 0) {

            // 获取 原OPD计划(补充申请) 的值，验证必填字段规则
            List<OPDPlan__c> getOPDPlanList = [SELECT Id,Name,
                    OwnerId, //所有人
                    Status__c, //状态
                    OPDPlan_ImplementDate__c, //OPD计划实施日期
                    OPDPlan_ImplementDate_temp__c, // OPD计划实施日期(Temp)
                    Activity_Type2__c, //拜访区分
                    Account_Laboratory__c, //科室
                    OPDPlan_Report__c, //报告书
                    Campaign__c, //学会
                    Related_Opportunity1_ID__c, //跟进询价ID1
                    Related_Opportunity2_ID__c, //跟进询价ID2
                    NoOpp_Reason__c,//无询价申请理由
                    OPDType__c, //OPD计划来源
                    SalesManager__c, //推广经理
                    SalesManager_Txt__c,
                    PlanProdDetail__c,
                    DelayCancel_Reason__c,
                    Rental_Apply2__c,
                    RentalReson__c, //出借目的
                    noReportStatus__c, //无报告状态
                    ModelLendingProduct__c, //模型出借产品
                    CorrespondingRepairNo__c, //对应修理维修NO
                    AttachmentCertificate__c, //附件证明
                    AdditionalSupport__c //原OPD计划（追加配套用）
                      FROM OPDPlan__c WHERE Id IN:originalOpdPlanApplicationIdList]; 
            system.debug('getOPDPlanList:'+getOPDPlanList.size());
            String opdplanNameSql = '';
            String soql = 'Select Id,Name From OPDPlan__c where Id != \'\'';
            for(OPDPlan__c opdplan:getOPDPlanList){
                originalOpdPlanApplicationIdMap.put(opdplan.Id, opdplan); 

                String opdplanName = opdplan.Name.indexOf('-') >= 0 ? opdplan.Name.split('-')[0]+'%':opdplan.Name+'%';

                if (String.isNotBlank(opdplanNameSql)) {
                    opdplanNameSql +=  ' OR Name Like \'' + opdplanName +'\'';
                } else {
                    opdplanNameSql = ' AND ( Name Like \'' + opdplanName +'\'';
                }
            }
            system.debug('opdplanNameSql:'+opdplanNameSql);
            Map<String,Integer> opdplanQuantityMap = new Map<String,Integer>(); 
            if (String.isNotBlank(opdplanNameSql)) {
                soql += opdplanNameSql + ' )';
                List<OPDPlan__c> getOPDPlanList01 = Database.query(soql); 
                for (OPDPlan__c opdplan :getOPDPlanList01) {
                    String opdplanName = opdplan.Name.indexOf('-') >= 0 ? opdplan.Name.split('-')[0]:opdplan.Name;
                    Integer quantity = 1;
                    if (opdplanQuantityMap.containsKey(opdplanName)) {
                        quantity = opdplanQuantityMap.get(opdplanName) + 1;
                    }
                    opdplanQuantityMap.put(opdplanName,quantity);
                }   
            }

            for (OPDPlan__c nObj : newList) {
                //20210422 ljh update SWAG-BZK68V  start
                //String opdPlanId = nObj.OriginalOpdPlanApplication__c;
                String opdPlanId = nObj.OriginalOpdPlanApplication__c;
                String opdPlanIdR = nObj.OriginalOpdPlanRental__c;
                //if (String.isNotBlank(opdPlanId)) {
                if (String.isNotBlank(opdPlanId)||String.isNotBlank(opdPlanIdR) ) {
                    if (originalOpdPlanApplicationIdMap.containsKey(opdPlanId) || originalOpdPlanApplicationIdMap.containsKey(opdPlanIdR)) {
                        OPDPlan__c originalOpdPlanApplication = originalOpdPlanApplicationIdMap.get(opdPlanId);
                        //20210422 ljh update SWAG-BZK68V start
                        if(originalOpdPlanApplication == null){
                            originalOpdPlanApplication = originalOpdPlanApplicationIdMap.get(opdPlanIdR);
                        }
                        //20210422 ljh update SWAG-BZK68V end
                        // 验证
                        //20210422 ljh update SWAG-BZK68V 
                        //if (!nObj.RentalSplit__c) {
                        if (String.isBlank(nObj.OriginalOpdPlanRental__c)) {
                            
                            nobj.SkipValidationRulesAndWorkflows__c = true;//跳过验证规则或工作流
                            nObj.supplementaryApplication__c = true;
                            nobj.originalOpdRentalApply__c = originalOpdPlanApplication.Rental_Apply2__c;
                            if (nObj.Account_Laboratory__c != originalOpdPlanApplication.Account_Laboratory__c) {
                                nObj.Account_Laboratory__c.addError('补充申请的OPD计划,不可修改科室的值');

                            }  
                            if ((String.isNotBlank(nObj.RentalReson__c) && !'追加配套'.equals(nObj.RentalReson__c)) || nObj.OPDPlan_ImplementDate__c != originalOpdPlanApplication.OPDPlan_ImplementDate__c) {
                                nObj.addError('出借目的必须是追加配套，且不可修改OPD计划实施日期');
                            }
                            if (originalOpdPlanApplication.Status__c != '计划中') {
                                nObj.OriginalOpdPlanApplication__c.addError('只有OPD计划状态为计划中，才能进行补充申请');
                            }
                        } 
                        // else {
                        //    nObj.PlanProdDetail__c = originalOpdPlanApplication.PlanProdDetail__c; 
                        // }
                        
                        nObj.SalesManager__c = originalOpdPlanApplication.SalesManager__c;
                        nobj.SalesManager_Txt__c = originalOpdPlanApplication.SalesManager_Txt__c;
                        nObj.Campaign__c  =  originalOpdPlanApplication.Campaign__c;
                        String opdplanName = originalOpdPlanApplication.Name;
                        if (opdplanName.indexOf('-') >=0) {
                            opdplanName = opdplanName.split('-')[0];
                        }
                        nObj.Name = opdplanName + '-' + opdplanQuantityMap.get(opdplanName);
                        system.debug('nObj---->'+nObj);
                    }   
                } 
            }   
        }

        // OPD计划 再申请
        if (originalOpdPlanIdList.size() > 0) {
           List<OPDPlan__c> getOPDPlanList = [SELECT Id,Name,PlanProdDetail__c,Campaign__c,Account_Laboratory__c,Status__c,DelayCancel_Reason__c,RentalApplyId__c,RentalApplyName__c,Rental_Apply2__r.Id,Rental_Apply2__r.Name from OPDPlan__c WHERE Id IN:originalOpdPlanIdList];
            for(OPDPlan__c opdplan:getOPDPlanList){
                originalOpdPlanIdMap.put(opdplan.Id, opdplan); 
            }

            for (OPDPlan__c nObj : newList) {
                String opdPlanId = nObj.OriginalOpdPlan__c;
                if (String.isNotBlank(opdPlanId)) {
                    if (originalOpdPlanIdMap.containsKey(opdPlanId)) {
                        
                        nObj.PlanProdDetail__c = originalOpdPlanIdMap.get(opdPlanId).PlanProdDetail__c;
                        nObj.Campaign__c  =  originalOpdPlanIdMap.get(opdPlanId).Campaign__c;
                        nObj.RentalApplyId__c = originalOpdPlanIdMap.get(opdPlanId).Rental_Apply2__r.Id;
                        nObj.RentalApplyName__c = originalOpdPlanIdMap.get(opdPlanId).Rental_Apply2__r.Name;
                        
                        if (nObj.Account_Laboratory__c != originalOpdPlanIdMap.get(opdPlanId).Account_Laboratory__c) {
                            nObj.Account_Laboratory__c.addError('再申请的OPD计划,不可修改科室的值');

                        }
                        //2021-06-28  mzy  update  备品不足 对应的API名为  无备品
                        //if (originalOpdPlanIdMap.get(opdPlanId).Status__c != '取消' || originalOpdPlanIdMap.get(opdPlanId).DelayCancel_Reason__c != '备品不足' ) {
                        if (originalOpdPlanIdMap.get(opdPlanId).Status__c != '取消' || (originalOpdPlanIdMap.get(opdPlanId).DelayCancel_Reason__c != '无备品' && originalOpdPlanIdMap.get(opdPlanId).DelayCancel_Reason__c != '备品不足')) {
                        //if (originalOpdPlanIdMap.get(opdPlanId).Status__c != '取消' || originalOpdPlanIdMap.get(opdPlanId).DelayCancel_Reason__c != '无备品') {
                            nObj.OriginalOpdPlan__c.addError('只有OPD计划状态为取消，并且延期取消理由为备品不足才可再申请');
                        }
                    }
                    
                    nObj.Reapply__c = true;
                    
                }
            
            }
        }
    }
    // ***SWAG-BZCAHL***XHL***20210331***END*********
    //end SWAG-BSC5WP 20201106 you
    private void newEventIns() {
        Set<Id> oSetIdSet = new Set<Id>();
        Map<Id,OPDPlan__c> opdMap = new Map<Id,OPDPlan__c>();
        for (OPDPlan__c nObj : newList) {
            OPDPlan__c oObj = oldMap.get(nObj.Id);
            if (oObj.OPDPlan_ImplementDate__c != null && nObj.OPDPlan_ImplementDate__c != null
                  //  && oObj.OPDPlan_ImplementDate__c < nObj.OPDPlan_ImplementDate__c) {
                && oObj.OPDPlan_ImplementDate__c !=  nObj.OPDPlan_ImplementDate__c ) {
                oSetIdSet.add(oObj.Id);
                opdMap.put(oObj.Id,oObj);
            }
        }
        system.debug('oSetIdSet+++++' + oSetIdSet);
        List<Event> eventList = new List<Event>();
        List<Event> eveCloneList = new List<Event>();
        List<Task__c> taskList = new List<Task__c>();
        if (oSetIdSet.size() > 0) {
            eventList = [select Id, StartDateTime, DurationInMinutes, EventStatus__c,Task_ID__c,
                         OPDPlan_Flag__c, Location, whatid__c, Related_Opportunity1_ID__c,
                         Activity_Type2__c, Related_Opportunity1__c, Purpose_Type__c,
                         Related_Service1__c, Related_Service1_ID__c, Activity_Purpose__c,
                         Purpose_TypeFSE__c, Purpose_TypeEscFSE__c, Activity_PurposeFSE__c,
                         Activity_PurposeEscFSE__c, Opd_Plan__c, Opd_Plan_ImplementDate__c,
                         //2021-08-13  mzy   SWAG-C5RAZV  事件——计划 延期 调查  start
                         delayReason__c,
                         //2021-08-13  mzy   SWAG-C5RAZV  事件——计划 延期 调查  end
                         Subject from Event where Opd_Plan__c in: oSetIdSet];
        }

        if (eventList.size() > 0) {
            list<Id> dailyReportOPDIdList = new list<Id>();
            //Map<String,String> tskOpdMap = new Map<String,String>();
            //Map<String,event> tskeventMap = new Map<String,event>();
            for (Event evn : eventList) {
                System.debug('new时间:'+newMap.get(evn.Opd_Plan__c).OPDPlan_ImplementDate__c +'旧时间'+OldMap.get(evn.Opd_Plan__c).OPDPlan_ImplementDate__c);
                if(newMap.get(evn.Opd_Plan__c).OPDPlan_ImplementDate__c < OldMap.get(evn.Opd_Plan__c).OPDPlan_ImplementDate__c){
                    //提前
                    Datetime startD = evn.StartDateTime;
                    Date startDateTime = Date.newInstance(startD.year(), startD.month(), startD.day());
                    Integer betweenDay = startDateTime.daysBetween(evn.Opd_Plan_ImplementDate__c);
                    evn.StartDateTime = evn.StartDateTime.addDays(betweenDay);

                    Task__c tempTask = new Task__c();
                    tempTask.Id = newMap.get(evn.Opd_Plan__c).Task_ID__c;
                    temptask.Activity_Date__c = newMap.get(evn.Opd_Plan__c).OPDPlan_ImplementDate__c;
                    taskList.add(tempTask);
                }else{
                    if(!(newMap.get(opdMap.get(evn.Opd_Plan__c).id)).isDailyReportDelay__c){
                        //延期
                        Event eveClone = evn.clone();
                        Datetime startD = eveClone.StartDateTime;
                        Date startDateTime = Date.newInstance(startD.year(), startD.month(), startD.day());
                        Integer betweenDay = startDateTime.daysBetween(evn.Opd_Plan_ImplementDate__c);
                        eveClone.StartDateTime = eveClone.StartDateTime.addDays(betweenDay);
                        eveClone.delayReason__c = null;
                        //20210527 zh 任务框架修改 start
                        eveClone.EventStatus__c = '02 接受';
                        if (opdMap.containsKey(evn.Opd_Plan__c)) {
                        eveClone.Task_ID__c = opdMap.get(evn.Opd_Plan__c).Task_ID__c;
                        eveClone.PlanProdDetail__c = opdMap.get(evn.Opd_Plan__c).PlanProdDetail__c;
                        }
                        //20210527 zh 任务框架修改 end

                        //2021-08-13  mzy   SWAG-C5RAZV  事件——计划 延期 调查  start
                        if(newMap.get(evn.Opd_Plan__c).DelayCancel_Reason__c!=null && evn.delayReason__c == null){
                            String DelayReason =  newMap.get(evn.Opd_Plan__c).DelayCancel_Reason__c;
                            System.debug('延期理由:'+DelayReason);
                            if('医院试用改期'.equals(DelayReason)){
                                evn.delayReason__c = '客户时间变更或冲突';
                                evn.delayReasonSelect__c = '客户时间变更或冲突';
                            }else if('工作计划变化'.equals(DelayReason)){
                                evn.delayReason__c = '与其他突发事件冲突';
                                evn.delayReasonSelect__c = '与其他突发事件冲突';
                            }else if('备品到货推迟'.equals(DelayReason)){
                                evn.delayReason__c = '备品未到';
                                evn.delayReasonSelect__c = '备品未到';
                            }else if('手术改期'.equals(DelayReason)){
                                evn.delayReason__c = '无合适病例(适合病例流失)OPD延期';
                                evn.delayReasonSelect__c = '无合适病例(适合病例流失)OPD延期';
                            }else if('日期填写错误'.equals(DelayReason)){
                                evn.delayReason__c = '日期填写错误';
                                evn.delayReasonSelect__c = '日期填写错误';
                            }else if('医院设备不到位'.equals(DelayReason)){
                                evn.delayReason__c = '医院设备不到位';
                                evn.delayReasonSelect__c = '医院设备不到位';
                            }else if('其他'.equals(DelayReason)){
                                evn.delayReason__c = '其他';
                                evn.delayReasonSelect__c = '其他';
                            }else if('系统自动延期'.equals(DelayReason)){
                                evn.delayReason__c = '其他';
                                evn.delayReasonSelect__c = '其他';
                                evn.delayReasonOther__c = DelayReason;
                            }
                            evn.delayToDate__c = newMap.get(evn.Opd_Plan__c).OPDPlan_ImplementDate__c;
                        }
                        evn.isDelay__c = true;
                        //2021-08-13  mzy   SWAG-C5RAZV  事件——计划 延期 调查  end
                        
                        evn.OPDPlan_Flag__c = false;                    
                        //2021-066-25 mzy OPD延期 
                        if(evn.task_ID__c == eveClone.Task_ID__c){
                            String subjectName = evn.Subject;
                            if(String.isNotBlank(subjectName)&&subjectName.contains('【')){
                                evn.Subject = subjectName.split('【')[0] + '【已延期】';
                            }else {
                                evn.Subject = subjectName +'【已延期】';
                            }
                            evn.task_ID__c = null; 
                            evn.EventStatus__c = '05 延期';
                            Task__c tempTask = new Task__c();
                            tempTask.Id = newMap.get(evn.Opd_Plan__c).Task_ID__c;
                            temptask.Activity_Date__c = newMap.get(evn.Opd_Plan__c).OPDPlan_ImplementDate__c;
                            taskList.add(tempTask);
                        }
                        evn.Opd_Plan__c = null;
                        //2021-066-25 mzy OPD延期 
                        //2022-1-7 yjk opd延期新建事件
                        if(eveClone.Subject!=null&&String.isNotBlank(eveClone.Subject)){
                            eveClone.Subject = eveClone.Subject.Split('【')[0]; 
                        }
                        eveCloneList.add(eveClone);
                    }else{
                        dailyReportOPDIdList.add(evn.Opd_Plan__c);
                        //tskOpdMap.put(opdMap.get(evn.Opd_Plan__c).Task_ID__c,evn.Opd_Plan__c);
                    }
                }
                
            }
            if(dailyReportOPDIdList.size() > 0){
                List<OPDPlan__c> opdList = [select id,Task_ID__c,Task_ID__r.delayTask__c from OPDPlan__c where id in :dailyReportOPDIdList];
                for(OPDPlan__c opdPlan : opdList){
                    opdPlan.Task_ID__c = opdPlan.Task_ID__r.delayTask__c;
                }
                update opdList;
            }

            //system.debug('eveCloneList+++++' + eveCloneList);
            //system.debug('eventList+++++' + eventList);
            update eventList;
            insert eveCloneList;
            update taskList;
        }
    }


    private void updateMng() {

        Boolean userFlg = false;

        for (OPDPlan__c n : newList) {
            if ((String.isNotBlank(n.Status__c) && n.Status__c.equals('提交')
                    && (String.isBlank(oldMap.get(n.Id).Status__c) || oldMap.get(n.Id).Status__c.equals('草案中')))) {

                // 设置是否取User的FLG
                userFlg = True;
            }
            //2022-01-05  mzy  无报告申请报错  start
            if((String.isNotBlank(n.noReportStatus__c) && n.noReportStatus__c.equals('提交')
            && (String.isBlank(oldMap.get(n.Id).noReportStatus__c) || oldMap.get(n.Id).noReportStatus__c.equals('已保存')))){
                // 设置是否取User的FLG
                userFlg = True;
            }
            //2021-01-05  mzy  无报告申请报错  end
        }
        // 取得User审批人
        List<User> uList = new List<User>();
        if (userFlg) {
            uList = [select Id, SalesManager__c, SalesManager__r.Name from user where SalesManager__r.IsActive = true And id = :UserInfo.getUserId()];
        }

        // 设置审批人
        for (OPDPlan__c n : newList) {
            if ((String.isNotBlank(n.Status__c) && n.Status__c.equals('提交')
                    && (String.isBlank(oldMap.get(n.Id).Status__c) || oldMap.get(n.Id).Status__c.equals('草案中')))                  
                || ((String.isNotBlank(n.noReportStatus__c) && n.noReportStatus__c.equals('提交')
                && (String.isBlank(oldMap.get(n.Id).noReportStatus__c) || oldMap.get(n.Id).noReportStatus__c.equals('已保存'))))) {
                
                if (uList.size() > 0) {
                    String MId = uList[0].SalesManager__c;
                    if (String.isBlank(MId)) {
                        n.addError('经理无效，请联系管理员。');
                    } else {
                        n.SalesManager__c = MId;
                        // SWAG-BZNBKZ 审批人文本化 LHJ Start
                        n.SalesManager_Txt__c = uList[0].SalesManager__r.Name;
                        // SWAG-BZNBKZ 审批人文本化 LHJ End
                    }
                }else {
                    n.addError('经理无效/离职，请联系管理员。');
                }
            }else 
            //推广经理发生变化赋值文本字段
            if(oldMap.get(n.Id).SalesManager__c != n.SalesManager__c){
                //推广经理 等于空
                if(String.isBlank(n.SalesManager__c)){
                    n.SalesManager_Txt__c = '';
                }else {
                    List<User> tempUList = new List<User>();
                    tempUList = [select Id, Name from user where IsActive = true And id = :n.SalesManager__c];
                    if(tempUList.size() > 0){
                        n.SalesManager_Txt__c = tempUList[0].Name;
                    }else {
                        n.addError('经理无效/离职，请联系管理员。');
                    }
                }
                
            }
        }
    }

    private void NewOppPlan() {
        //opd创建时把符合条件的目标客户带过来

        //将OPD计划的战略科室id放到List 当做客户-目标客户的检索条件
        Map<string, string> accsMap = new Map<string, string>();
        // 将OPD计划的战略科室id作为key ，本财年作为value 用于下面判断
        Map<string, string> opdMap = new Map<string, string>();
        List<OPDPlan__c> opdPlanList  = new List<OPDPlan__c>();
        //上一财年
        Map<string, string> opdLastMap = new Map<string, string>();
        map<id, OPDPlan__c> opplansmap = new map<id, OPDPlan__c>();
        //set<String> OpdTargetAcc = new set<String>(); //opp计划上的本财年的目标客户
       // set<String> OpdTargetLastAcc = new set<String>(); //opp计划上的上财年的目标客户
        Map<id, String> OpdTargetAcc = new Map<id, String>();
        Map<id, String> OpdTargetLastAcc = new Map<id,String>();
        Integer buffer = Integer.valueOf(System.Label.opd_oldDate_update);//为了刷新prod上的老数据
        Map<String,String> reapplyopdMap = new Map<String,String>();
        Map<String,String> sApplicationopdMap = new Map<String,String>();
        for (OPDPlan__c t : newList) {
            // Trigger.new[0].addError('=t.OCM_category_ID__c=='+t.OCM_category_ID__c); 
            if (Trigger.isInsert || (Trigger.isUpdate && (oldMap.get(t.id).Account_Laboratory__c != t.Account_Laboratory__c || buffer==1))) {
                if (t.OCM_category_ID__c  != null && t.OPDPlan_ImplementDate__c != null) {
                    accsMap.put(t.OCM_category_ID__c, t.Id);
                    Date dateToday = t.OPDPlan_ImplementDate__c;
                    // Date yesterday = dateToday.addDays(-1);
                    Integer year = dateToday.year();
                    Integer month = dateToday.month();
                    if (month < 4) {
                        year -= 1;
                    }
                    // String ocmYear = year + '年度';  本财年
                    String annual = year - 1867 + 'P';
                    opdMap.put(t.OCM_category_ID__c, annual);
                    //上财年
                    String annual1 = year - 1868 + 'P';
                    opdLastMap.put(t.OCM_category_ID__c, annual1);
                }
            }

            if (Trigger.isInsert && String.isNotBlank(t.OriginalOpdPlan__c)) {
                
                reapplyopdMap.put(t.OriginalOpdPlan__c, t.Id);
                               
            }
            //20210422 ljh update SWAG-BZK68V 
            //if (Trigger.isInsert && String.isNotBlank(t.OriginalOpdPlanApplication__c) && t.RentalSplit__c ) {
            if (Trigger.isInsert && String.isNotBlank(t.OriginalOpdPlanRental__c)) {  
                sApplicationopdMap.put(t.OriginalOpdPlanRental__c, t.Id);               
            }
        }
        // ***SWAG-BZCAHL***XHL***20210331***START*********
        // 原OPD计划下的 计划出借备品 和 附件
        if (reapplyopdMap != null && reapplyopdMap.size() > 0) {
            insertCloneData(reapplyopdMap);
        }
        // ***SWAG-BZCAHL***XHL***20210331***END*********

        // ***SWAG-BZK68V***XHL***20210420***START*********
        // 备品拆单 携带 原OPD计划下的 计划出借备品 和 附件
        if (sApplicationopdMap != null && sApplicationopdMap.size() >0) {
            insertCloneData(sApplicationopdMap);
        }
        // ***SWAG-BZK68V***XHL***20210420***END*********
        //检索OPD计划的战略科室的所有客户-目标客户
        // 20210624 SQL优化 Start
        //if (accsMap != null) {
        if (accsMap.size() > 0) {
        // 20210624 SQL优化 End
            List<Account_Number_of_target__c> anotList = [select Id, OCM_Period__c, Submit_Customer_target_new__c, Account__c
                    from Account_Number_of_target__c
                    where Account__c IN :accsMap.keySet()];
            for (OPDPlan__c t : newList) {
                OPDPlan__c opdplan = new OPDPlan__c();
                for (Account_Number_of_target__c an : anotList) {
                    //判断是否为同一战略科室
                    String subStr = an.Account__c;
                    //Trigger.new[0].addError(subStr.SubString(0,15)+'==='+t.OCM_category_ID__c);
                    if (subStr.SubString(0, 15) == t.OCM_category_ID__c) {

                        //判断本年度财年是否相同     当期的客户-目标客户

                        opdplan.Id = accsMap.get(subStr.SubString(0, 15));
                        if (opdMap.get(subStr.SubString(0, 15)) == an.OCM_Period__c) {
                            if (Trigger.isInsert) {
                                opdplan.OPD_Customers_Target__c = an.Id;
                                opdPlanList.add(opdplan);
                            }
                            if (Trigger.isUpdate && (oldMap.get(t.id).Account_Laboratory__c != t.Account_Laboratory__c || buffer==1)) {
                                t.OPD_Customers_Target__c = an.Id;
                            }
                            if(t.OPDType__c=='学会'){
                              OpdTargetAcc.put(t.id,an.Id+''); //本财年
                            }
                

                        }
                        system.debug('上财年' + opdLastMap.get(subStr.SubString(0, 15)) + '==' + an.OCM_Period__c);
                        //判断上年度财年是否相同   上期的客户-目标客户
                        if (opdLastMap.get(subStr.SubString(0, 15)) == an.OCM_Period__c) {
                            if (Trigger.isInsert) {
                                opdplan.OPD_Customers_Target_Last__c = an.Id;
                                opdPlanList.add(opdplan);
                            }
                            if (Trigger.isUpdate && (oldMap.get(t.id).Account_Laboratory__c != t.Account_Laboratory__c || buffer==1)) {
                                t.OPD_Customers_Target_Last__c = an.Id;
                            }
                            if(t.OPDType__c=='学会'){
                             OpdTargetLastAcc.put(t.id,an.Id+'');//上财年  dcListMap.keySet()  dcListMap.values()
                             }
                        }
                       
                    }
                }
            }
        }
        system.debug('==opdPlanList==' + opdPlanList);
        if(opdPlanList!=null){
            opplansmap.putall(opdPlanList);
        }
        if (Trigger.isInsert && opplansmap.size() > 0) {
            update opplansmap.values();
        }
        if (!OpdTargetAcc.isEmpty() || !OpdTargetLastAcc.isEmpty()){
            upsertOppPlan(OpdTargetAcc,OpdTargetLastAcc);
        }
        //Trigger.new[0].addError('==anotList =='+anotList+'更新的数据：'+opdPlanList);
        //更新OPD计划对象上的客户-目标客户的查找字段
        // if (Trigger.isInsert &&opdPlanList.size() > 0) update opdPlanList;
    }
    // 创建 克隆数据
    private void insertCloneData(Map<String,String> reapplyopdMap){
        // 查找原OPD计划下 计划出借备品
        List<Plan_Rental_Equipment__c> getPREList = [select Id,Name,Event_ID__c,OPD_Plan__c,Campaign__c,Rental_Quantity__c,Rental_Equipment__c from Plan_Rental_Equipment__c WHERE OPD_Plan__c  In:reapplyopdMap.keySet()];
            if (getPREList.size() > 0) {
                List<Plan_Rental_Equipment__c> insertCloneList = new List<Plan_Rental_Equipment__c>();
                for (Plan_Rental_Equipment__c pre:getPREList){
                    Plan_Rental_Equipment__c preClone = new Plan_Rental_Equipment__c();
                    preClone = pre.clone();
                    preClone.Id = null;
                    preClone.Event_ID__c = null;
                    preClone.Campaign__c = null; 
                    preClone.OPD_Plan__c = reapplyopdMap.get(pre.OPD_Plan__c);
                    insertCloneList.add(preClone);

                }

                if (insertCloneList.size() > 0) {
                    insert insertCloneList;
                }
            }
            List<Attachment> getAttachmentList = [SELECT Id, Body, Name, ParentId
                                        FROM Attachment
                                        WHERE ParentId In:reapplyopdMap.keySet()];
            List<Attachment> insertAttachmentCloneList = new List<Attachment>();
            if (getAttachmentList.size() > 0 ) {
                for(Attachment att :getAttachmentList){
                    Attachment attClone = new Attachment();
                    attClone = att.clone();
                    attClone.Id = null;
                    attClone.Body = att.Body;
                    attClone.Name = att.Name;
                    attClone.ParentId = reapplyopdMap.get(att.ParentId);
                    insertAttachmentCloneList.add(attClone);
                }

                if (insertAttachmentCloneList.size() > 0) {
                    insert insertAttachmentCloneList;
                }
            }
    }

    private void updateOppPlan() {
        
        //set<String> OpdTargetAcc = new set<String>(); //opp计划上的本财年的目标客户
        //set<String> OpdTargetLastAcc = new set<String>(); //opp计划上的上财年的目标客户
        Map<id, String> OpdTargetAcc = new Map<id, String>();
        Map<id, String> OpdTargetLastAcc = new Map<id, String>();
        Integer buffer = Integer.valueOf(System.Label.opd_oldDate_update);//为了刷新prod上的老数据
        //存放模型出借配套的id
        List<OPDPlan__c>  opdModelLendList = new  List<OPDPlan__c> ();
        for (OPDPlan__c t : newList) {

            if (Trigger.isUpdate && (oldMap.get(t.id).Status__c != t.Status__c && t.Status__c == '审批中' || buffer==1)) { 
               // OpdTargetAcc.add(t.OPD_Customers_Target__c); //本财年
               // OpdTargetLastAcc.add(t.OPD_Customers_Target_Last__c);//上财年
                OpdTargetAcc.put(t.id,t.OPD_Customers_Target__c);
                OpdTargetLastAcc.put(t.id,t.OPD_Customers_Target_Last__c);
            }

            if (Trigger.isUpdate && oldMap.get(t.id).Name != t.Name && !t.NoNSupplementaryApplication__c) {
                t.Name = oldMap.get(t.id).Name;
            }
            t.NoNSupplementaryApplication__c = false;

            //更新 模型出借产品 精琢技术 wql 2021/04/13 start
            if(Trigger.isUpdate && (oldMap.get(t.id).ModelLending__c != t.ModelLending__c)){
                opdModelLendList.add(t);
            }
            // SWAG-BUF6J5 20201112 you
            // SWAG-BXW4AH  XHL 20210312 因OPD计划 系统自动延期  后 会清空 备品出借优先度与排序日期
            // 因此 注掉 Start
            
            // if(Trigger.isUpdate && oldMap.get(t.id).OPDPlan_ImplementDate__c!= t.OPDPlan_ImplementDate__c){
            //     Date olddate=oldMap.get(t.id).OPDPlan_ImplementDate__c;
            //     Date newdate=t.OPDPlan_ImplementDate__c;
            //     System.debug('尝试反引用空对象 : '+ olddate +'*****'+newdate +'(((((' + t);
            //     if((null==olddate && newdate!=null )|| (olddate.month() != newdate.month())){
            //        Integer a;
            //        t.OPDLendSort__c=a;
            //        t.SortDate__c = null;
            //     }
            // }
            
            // SWAG-BXW4AH  XHL 20210312 因OPD计划 系统自动延期  后 会清空 备品出借优先度与排序日期
            // 因此 注掉 End
            
        }
        if(opdModelLendList.size()>0){
            updateModelLending(opdModelLendList);
        }
        
        if (!OpdTargetAcc.isEmpty() || !OpdTargetLastAcc.isEmpty()) {
            upsertOppPlan(OpdTargetAcc,OpdTargetLastAcc);
        }
    }

    //2021-9-16 yjk 当opd任务完成时，将对应的任务和事件也完成 ----start-----
    private void updateTaskAndEvent(){
        
        List<Id> taskIdList = new List<Id>();
        for (OPDPlan__c opdP: newList) {
            if('完毕'.equals(opdP.Status__c) && !'完毕'.equals(oldMap.get(opdP.Id).Status__c)&&opdP.Task_ID__c != null){
                taskIdList.add(opdP.Task_ID__c);
            }
        }
        if(taskIdList == null || taskIdList.size() == 0 ){
            return;
        }
        //2022-1-5 yjk opd任务的才能完成
        List<Id> tskupdIdList = new List<Id>();
        List<Task__c> taskList = [select id,taskStatus__c from task__c where NeedActivity__c = false and id in :taskIdList];
        for(Task__c tsk : taskList){
            tskupdIdList.add(tsk.id);
            tsk.taskStatus__c = '03 完成';
        }
        if(taskList != null && taskList.size()>0){
           update taskList; 
        }
        
        List<Event> eventList = [select id,EventStatus__c from event where Task_ID__c in :tskupdIdList];
        for(Event evt : eventList){
            evt.EventStatus__c = '03 完成';
        }
        if(eventList != null &&eventList.size()>0){
            update eventList;            
        }
    }
    //2021-9-16 yjk 当opd任务完成时，将对应的任务和事件也完成 ----end-----

    private void upsertOppPlan(Map<id, String> OpdTargetAcc,Map<id, String> OpdTargetLastAcc){
            List<OPDPlan__c> opdPlanList  = new List<OPDPlan__c>();
            map<id, OPDPlan__c> opplansmap = new map<id, OPDPlan__c>();
            set<String> OpdPlanDetail = new set<String>(); //计划出借备品信息.
            Integer FIELDMAX = 200;
            //去mapping表中找到名字为targetKeyProduct的一条数据
            SS_Batch_Column_Mapping__c mpdMapping = SS_Batch_Column_Mapping__c.getValues('targetKeyProduct');

            //对应目标客户中的一系列 opd对象   用来判断“是否产品OPD目标客户”
            List<String> column = new List<String>();
            Map<String, List<String>> tempImportantProduct = new Map<String, List<String>>();
            //对应目标客户中的一系列 目标客户字段  用来判断“是否营业目标客户”
            List<String> columnSalesTar = new List<String>();
            Map<String, List<String>> tempImportantSalesTar = new Map<String, List<String>>();
            //对应目标客户中的一系列 询价数  用来判断“是否有询价”
            List<String> columnOppCnt = new List<String>();
            Map<String, String> tempImportantOppCnt = new Map<String, String>();
            //对应目标客户中的一系列 设备数  用来判断“是否已有设备”
            List<String> columnAsset = new List<String>();
            Map<String, String> tempImportantAsset = new Map<String, String>();
            //对应目标客户中的一系列 OPD数（今年）  用来计算本期OPD次数
            List<String> columnOPDAmount = new List<String>();
            Map<String, String> tempImportantOPDAmount = new Map<String, String>();
            //对应目标客户中的一系列 借出次数  用来统计借出次数
            List<String> columnRental = new List<String>();
            Map<String, String> tempImportantRental = new Map<String, String>();

            for (Integer i = 1; i <= FIELDMAX; i++) {
                String lpadI = ('00' + i).right(3);
                String fromColumn = 'From_Column_' + lpadI + '__c';//假设执行此时 值是 From_Column_115__c
                String apiStr = String.valueOf(mpdMapping.get(fromColumn)); //取字段fromColumn上存储的数据为Rental_Cnt_USG400__c

                if (String.isBlank(apiStr) == false) {
                    String ssColumn = 'SS_Column_' + lpadI + '__c';//SS_Column_115__c
                    String ssApiStr = String.valueOf(mpdMapping.get(ssColumn));//取得是 字段SS_Column_115__c 上的存储的数据 USG-400
                    //Trigger.new[0].addError('=apiStr=='+apiStr+'==ssColumn =='+ssColumn+'==ssApiStr =='+ssApiStr );
                    //打印的值 Rental_Cnt_USG400__c==ssColumn ==SS_Column_115__c==ssApiStr ==USG-400

                    if (i < 101) { //opd对象
                        column.add(apiStr);
                        List<String> ssApiStrList = new List<String>(ssApiStr.Split(','));
                        tempImportantProduct.put(apiStr, ssApiStrList);
                    }
                    if (i >= 118 && i < 127) { //目标客户
                        columnSalesTar.add(apiStr);
                        List<String> ssApiStrList1 = new List<String>(ssApiStr.Split(','));
                        tempImportantSalesTar.put(apiStr, ssApiStrList1);

                    }
                    if (i >= 129 && i < 144) { //询价数 1，0
                        columnOppCnt.add(apiStr);
                        tempImportantOppCnt.put(apiStr, ssApiStr);

                    }
                    if (i >= 146 && i < 161) { //设备数 1，0
                        columnAsset.add(apiStr);
                        tempImportantAsset.put(apiStr, ssApiStr);

                    }

                    if (i >= 163 && i < 178) { //OPD数  本期/上期  累计数
                        columnOPDAmount.add(apiStr);
                        tempImportantOPDAmount.put(apiStr, ssApiStr);

                    }
                    if (i >= 101 && i < 116) { //出借次数  累计数
                        columnRental.add(apiStr);
                        tempImportantRental.put(apiStr, ssApiStr);

                    }

                }
            }

            // Trigger.new[0].addError('=columnAsset='+columnAsset+'--columnOppCnt--'+columnOppCnt+'--columnSalesTar--'+columnSalesTar+'--column--'+column);

            // Trigger.new[0].addError('=column=='+column+'==tempImportantProduct=='+tempImportantProduct );
            Map<id, Account_Number_of_target__c> acctarList = new Map<id, Account_Number_of_target__c>([select id, OPD_CV290__c, OPD_EUME2__c, OPD_290Miro__c, OPD_GFUCT260__c, OPD_OTVS300S400__c, OPD_CV170__c, OPD_190Main__c, OPD_ENG__c, OPD_TB__c,
                    Sales_target_CV290__c,
                    Sales_target_290Miro__c,
                    Sales_target_EUME2__c,
                    Sales_target_GFUCT260__c,
                    Sales_target_OTVS300S400__c,
                    Sales_target_CV170__c,
                    Sales_target_190Main__c,
                    Sales_target_ENG__c,
                    Sales_target_TB__c,
                    Opp_cnt_290MiroBF__c,
                    Opp_cnt_290MiroGI__c,
                    Opp_cnt_290MiroGI_CF__c,
                    Opp_cnt_290MiroGI_Plus__c,
                    Opp_cnt_CV170__c,
                    Opp_cnt_CV190__c,
                    Opp_cnt_CV290__c,
                    Opp_cnt_ESG400__c,
                    Opp_cnt_EUME2__c,
                    Opp_cnt_GFUCT260__c,
                    Opp_cnt_OTVS190__c,
                    Opp_cnt_OTVS300__c,
                    Opp_cnt_OTVS400__c,
                    Opp_cnt_TB__c,
                    Opp_cnt_USG400__c,
                    Opp_cnt_190Main__c,
                    Asset_Cnt_290MiroBF__c,
                    Asset_Cnt_290MiroGI__c,
                    Asset_Cnt_290MiroGI_CF__c,
                    Asset_Cnt_290MiroGI_Plus__c,
                    Asset_Cnt_CV170__c,
                    Asset_Cnt_CV190__c,
                    Asset_Cnt_CV290__c,
                    Asset_Cnt_ESG400__c,
                    Asset_Cnt_EUME2__c,
                    Asset_Cnt_GFUCT260__c,
                    Asset_Cnt_OTVS190__c,
                    Asset_Cnt_OTVS300__c,
                    Asset_Cnt_OTVS400__c,
                    Asset_Cnt_TB__c,
                    Asset_Cnt_USG400__c,
                    Asset_Cnt_190Main__c,
                    OPD_amount_290MiroBF__c,
                    OPD_amount_290MiroGI__c,
                    OPD_amount_290MiroGI_CF__c,
                    OPD_amount_290MiroGI_Plus__c,
                    OPD_amount_CV170__c,
                    OPD_amount_CV190__c,
                    OPD_amount_CV290__c,
                    OPD_amount_ESG400__c,
                    OPD_amount_EUME2__c,
                    OPD_amount_GFUCT260__c,
                    OPD_amount_OTVS190__c,
                    OPD_amount_OTVS300__c,
                    OPD_amount_OTVS400__c,
                    OPD_amount_TB__c,
                    OPD_amount_USG400__c,
                    OPD_amount_190Main__c,
                    Rental_Cnt_290MiroBF__c,
                    Rental_Cnt_290MiroGI__c,
                    Rental_Cnt_290MiroGI_CF__c,
                    Rental_Cnt_290MiroGI_Plus__c,
                    Rental_Cnt_CV170__c,
                    Rental_Cnt_CV190__c,
                    Rental_Cnt_CV290__c,
                    Rental_Cnt_ESG400__c,
                    Rental_Cnt_EUME2__c,
                    Rental_Cnt_GFUCT260__c,
                    Rental_Cnt_OTVS190__c,
                    Rental_Cnt_OTVS300__c,
                    Rental_Cnt_OTVS400__c,
                    Rental_Cnt_TB__c,
                    Rental_Cnt_USG400__c,
                    Rental_Cnt_190Main__c

                    from Account_Number_of_target__c
                    where id in :OpdTargetAcc.values()]);//查询目标客户 本财年的 
            Map<id, Account_Number_of_target__c> acctarlastList = new Map<id, Account_Number_of_target__c>([select id,
                    OPD_amount_290MiroBF__c,
                    OPD_amount_290MiroGI__c,
                    OPD_amount_290MiroGI_CF__c,
                    OPD_amount_290MiroGI_Plus__c,
                    OPD_amount_CV170__c,
                    OPD_amount_CV190__c,
                    OPD_amount_CV290__c,
                    OPD_amount_ESG400__c,
                    OPD_amount_EUME2__c,
                    OPD_amount_GFUCT260__c,
                    OPD_amount_OTVS190__c,
                    OPD_amount_OTVS300__c,
                    OPD_amount_OTVS400__c,
                    OPD_amount_TB__c,
                    OPD_amount_USG400__c,
                    OPD_amount_190Main__c
                    from Account_Number_of_target__c
                    where id = :OpdTargetLastAcc.values()]);//查询目标客户 上财年的
            system.debug('==上财年' + acctarlastList);
            for (OPDPlan__c t : newList) {
                if(Trigger.isUpdate){
                    Integer intes;
                    t.if_OPDTarget__c = intes;
                    t.if_HaveSalestarget__c = intes;
                    t.if_HaveOpportunity__c = intes;
                    t.if_HaveEquipment__c = intes;

                    t.Cnt_OPD_ThisYear__c = 0;
                    t.Cnt_OPD_LastYear__c = 0;
                    t.Cnt_Rentals__c = 0;
                }
               String opdct = OpdTargetAcc.get(t.id);
               String opdla = OpdTargetLastAcc.get(t.id);

                if (acctarList.containskey(opdct) || acctarlastList.containskey(opdla)) { // ||
                    if(t.PlanProdDetail__c!=null){
                        String ppd = t.PlanProdDetail__c;//不能去掉所有空格，因为有一个特殊得（OTV-S400 4K主机）.replaceAll(' ', ''); //GI-290镜子*3; GI-290镜子CF*1; OTV-S400 4K主机*3; OTV-S190*2; TB*8
                        String[] strs = ppd.split(';');//(GI-290镜子*3, GI-290镜子CF*1, OTV-S400 4K主机*3, OTV-S190*2, TB*8)
                        for (Integer i = 0; i < strs.size(); i++) { 
                           OpdPlanDetail.add(strs[i].split('\\*')[0].trim());//{ GI-290镜子CF, OTV-S190, OTV-S400 4K主机, TB, GI-290镜子}
                        }
                    }
                    
                    system.debug('上财年是否有符合条件得数据==' + acctarlastList.containskey(opdla));
                    //Trigger.new[0].addError('==tempImportantProduct=='+tempImportantProduct+'==OpdPlanDetail=='+OpdPlanDetail);
                    Decimal bqopdsum = 0;//计算 本期OPD次数
                    Decimal cntrensum = 0;//计算 出借次数
                    Decimal bqopdlastsum = 0;//计算 上期OPD次数
                    //20210701 SWAG-C4A4RJ you  为了不重复累计数据
                    Integer cv_190_In=0; //出街次数
                    Boolean cv_190_flag =false;//出借次数判断
                    Integer this_cv_190_In=0; //今年opd计划数
                    Boolean this_cv_190_flag =false;//今年opd计划数判断
                    Integer last_cv_190_In=0; //去年opd计划数
                    Boolean last_cv_190_flag =false;//去年opd计划数判断
                    OPDPlan__c opdplan = new OPDPlan__c();
                    for (String opd : OpdPlanDetail) {
                        opdplan.id = t.id;
                        if(acctarList !=null){
                        if (column != null) {
                            for (Integer i = 0; i < column.size(); i++) { //是否产品OPD目标客户
                                List<String>  titleAccout = tempImportantProduct.get(column[i]);
                                system.debug(titleAccout + '===opd===' + opd);
                                if (titleAccout.contains(opd)) {
                                    // system.debug(column[i] + '==anotList ==' + acctarList.get(opdct).get(column[i]) + '====' + acctarList.get(opdct).get(column[i]));
                                    //Trigger.new[0].addError(column[i]+'==anotList =='+acctarList.get(opdct).get(column[i]));
                                    if (acctarList.get(opdct).get(column[i]) != null && acctarList.get(opdct).get(column[i]) != 0) {

                                        
                                        if (Trigger.isInsert && t.OPDType__c=='学会') {
                                            opdplan.if_OPDTarget__c = 1;
                                            opdPlanList.add(opdplan);
                                        }else{
                                            t.if_OPDTarget__c = 1;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                        if (acctarList.containskey(opdct)) {
                            if (columnSalesTar != null) {
                                for (Integer i = 0; i < columnSalesTar.size(); i++) { //是否有营业目标客户
                                    List<String>  titleAccout1 = tempImportantSalesTar.get(columnSalesTar[i]);
                                    if (titleAccout1.contains(opd)) {
                                        system.debug(columnSalesTar[i] + '==是否有营业目标客户==' + acctarList.get(opdct).get(columnSalesTar[i]));
                                        if (acctarList.get(opdct).get(columnSalesTar[i]) != null && acctarList.get(opdct).get(columnSalesTar[i]) != 0) {
                                            
                                            if (Trigger.isInsert && t.OPDType__c=='学会') {
                                                opdplan.if_HaveSalestarget__c = 1;
                                                opdPlanList.add(opdplan);
                                             }else{
                                                t.if_HaveSalestarget__c = 1;
                                             }
                                            break;
                                        }
                                    }
                                }
                            }
                            if (columnOppCnt != null) {
                                for (Integer i = 0; i < columnOppCnt.size(); i++) { //是否有询价数
                                    String  titleAccout2 = tempImportantOppCnt.get(columnOppCnt[i]);
                                    if (opd.indexOf(titleAccout2) != -1) {
                                        if (acctarList.get(opdct).get(columnOppCnt[i]) != null && acctarList.get(opdct).get(columnOppCnt[i]) != 0) {
                                            
                                            if (Trigger.isInsert && t.OPDType__c=='学会') {
                                                opdplan.if_HaveOpportunity__c = 1;
                                                opdPlanList.add(opdplan);
                                             }else{
                                                t.if_HaveOpportunity__c = 1;
                                             }
                                            break;
                                        }
                                    }
                                }
                            }
                            if (columnAsset != null) {
                                for (Integer i = 0; i < columnAsset.size(); i++) { //是否已有设备
                                    String  titleAccout3 = tempImportantAsset.get(columnAsset[i]);
                                    if (opd.indexOf(titleAccout3) != -1) {
                                        system.debug('==opd==' + opd + '==titleAccout3==' + titleAccout3 + '==columnAsset[i]==' + columnAsset[i]);
                                        system.debug('==' + opdct + '==opd==' + acctarList.get(opdct).get(columnAsset[i]));
                                        if (acctarList.get(opdct).get(columnAsset[i]) != null && acctarList.get(opdct).get(columnAsset[i]) != 0) {
                                            
                                            if (Trigger.isInsert && t.OPDType__c=='学会') {
                                                opdplan.if_HaveEquipment__c = 1;
                                                opdPlanList.add(opdplan);
                                             }else{
                                                t.if_HaveEquipment__c = 1;
                                             }
                                            break;
                                        }
                                    }
                                }
                            }

                            if (columnRental != null) {//目标客户上得api字段
                                
                                for (Integer i = 0; i < columnRental.size(); i++) { //出借次数
                                    String  titleAccout4 = tempImportantRental.get(columnRental[i]); //取出来得是CV-190或者是OTV-S190
                                    if (opd == titleAccout4) {
                                        system.debug('出借次数' + opd + '==titleAccout4==' + titleAccout4 + '==columnRental[i]==' + columnRental[i]);
                                        if (acctarList.get(opdct).get(columnRental[i]) != null && acctarList.get(opdct).get(columnRental[i]) != 0) {
                                            Decimal aa = acctarList.get(opdct).get(columnRental[i]) == null ? 0 : Decimal.valueOf(String.valueOf(acctarList.get(opdct).get(columnRental[i])));
                                            system.debug('===出借次数' + aa);
                                            //20210701 SWAG-C4A4RJ you  为了不重复累计数据
                                            if(opd=='CV-190' || opd=='OTV-S190'){
                                               cv_190_In ++;
                                               cv_190_flag = true;
                                            }else{
                                                cv_190_flag = false;
                                            }
                                            system.debug('zheli=='+cv_190_In+'==false=='+cv_190_flag);
                                            if(cv_190_In < 2 || !cv_190_flag){
                                                cntrensum += aa;
                                            }

                                        }
                                    }
                                }
                                
                                if (Trigger.isInsert && t.OPDType__c=='学会') {
                                    opdplan.Cnt_Rentals__c = cntrensum;
                                    opdPlanList.add(opdplan);
                                }else{
                                    t.Cnt_Rentals__c = cntrensum;
                                }
                            }
                        }
                        }
                        if (columnOPDAmount != null) {

                            for (Integer i = 0; i < columnOPDAmount.size(); i++) { //本期OPD次数
                                String  titleAccout5 = tempImportantOPDAmount.get(columnOPDAmount[i]);
                                if (opd == titleAccout5) {
                                    if(acctarList !=null){
                                        if (acctarList.containskey(opdct) && acctarList.get(opdct).get(columnOPDAmount[i]) != null && acctarList.get(opdct).get(columnOPDAmount[i]) != 0) {
                                            system.debug('=columnOPDAmount[i]==' + columnOPDAmount[i] + '=本期OPD次数=' + acctarList.get(opdct).get(columnOPDAmount[i]));
                                            Decimal aa = acctarList.get(opdct).get(columnOPDAmount[i]) == null ? 0 : Decimal.valueOf(String.valueOf(acctarList.get(opdct).get(columnOPDAmount[i])));
                                            system.debug('===aa' + aa); 
                                             //20210701 SWAG-C4A4RJ you  为了不重复累计数据
                                            if(opd=='CV-190' || opd=='OTV-S190'){
                                               this_cv_190_In ++;
                                               this_cv_190_flag = true;
                                            }else{
                                                this_cv_190_flag = false;
                                            }
                                            if(this_cv_190_In < 2 || !this_cv_190_flag){
                                                bqopdsum += aa;
                                            }
                                        }
                                    }
                                    if(acctarlastList !=null){
                                        if (acctarlastList.containskey(opdla) && acctarlastList.get(opdla).get(columnOPDAmount[i]) != null && acctarlastList.get(opdla).get(columnOPDAmount[i]) != 0) {
                                            system.debug('=columnOPDAmount[i]==' + columnOPDAmount[i] + '=上期OPD次数=' + acctarlastList.get(opdla).get(columnOPDAmount[i]));
                                            Decimal bb = acctarlastList.get(opdla).get(columnOPDAmount[i]) == null ? 0 : Decimal.valueOf(String.valueOf(acctarlastList.get(opdla).get(columnOPDAmount[i])));
                                            system.debug('===bb' + bb);
                                            
                                             //20210701 SWAG-C4A4RJ you  为了不重复累计数据
                                            if(opd=='CV-190' || opd=='OTV-S190'){
                                               last_cv_190_In ++;
                                               last_cv_190_flag = true;
                                            }else{
                                                last_cv_190_flag = false;
                                            }
                                            if(last_cv_190_In < 2 || !last_cv_190_flag){
                                                bqopdlastsum += bb;
                                            }
                                        }
                                    }


                                }
                            }
                            
                            if (Trigger.isInsert && t.OPDType__c=='学会') {
                                    opdplan.Cnt_OPD_ThisYear__c = bqopdsum;
                                    opdplan.Cnt_OPD_LastYear__c = bqopdlastsum;
                                    opdPlanList.add(opdplan);
                                }else{
                                    t.Cnt_OPD_ThisYear__c = bqopdsum;
                                    t.Cnt_OPD_LastYear__c = bqopdlastsum;
                                }
                        } //

                    }



                }
            }

        system.debug('=来源直接是学会得=opdPlanList==' + opdPlanList);
        opplansmap.putall(opdPlanList);
        if (Trigger.isInsert && opplansmap.size() > 0) {
            update opplansmap.values();
        }

    }
    //更新 模型出借产品  精琢技术 wql 2021/04/13 start
    private void updateModelLending(List<OPDPlan__c> oplanList){

        Map<Id,Id> ModelLendMap = new Map<Id,Id> ();
        //查询 模型出借配套表 获取模型出借产品
        List<ModelLendingProduct__c>  ModelLendList= [select id,Name,Product__c,productName__c,ModelAndProductName__c from ModelLendingProduct__c ];
        //将所有的数据都检索处理 目前<100条  未来再考虑传参缩小数据范围
        if(ModelLendList.size()>0){
            for(ModelLendingProduct__c ml :ModelLendList){
                ModelLendMap.put(ml.id,ml.Product__c);
            }
            
        }
        //①新增 ②更新 同步赋值即可
        if(oplanList.size() >0){
            for(OPDPlan__c opd :oplanList){
                    if(opd.ModelLending__c == null){
                        opd.ModelLendingProduct__c = null;
                    }else{
                        opd.ModelLendingProduct__c = ModelLendMap.get(opd.ModelLending__c);
                    }
            }
        }
        


    }

}