public without sharing class BeforeUpsertReportHandler extends Oly_TriggerHandler {
    /**
    SWAG-BVW8CW 20201207 you create
    **/
    private Map<Id, Report__c> newMap;
    private Map<Id, Report__c> oldMap;
    private List<Report__c> newList;
    private List<Report__c> oldList;
    public BeforeUpsertReportHandler() {
        this.newMap = (Map<Id, Report__c>) Trigger.newMap;
        this.oldMap = (Map<Id, Report__c>) Trigger.oldMap;
        this.newList = (List<Report__c>) Trigger.new;
        this.oldList = (List<Report__c>) Trigger.old;
    }

    protected override void beforeInsert() {
        InsertReport();
        InsertReportConsume();
    }

    protected override void beforeUpdate() {
        InsertReport();
        InsertReportConsume();

    }
    private void InsertReport() {
        Integer buffer = Integer.valueOf(System.Label.report_oldDate_update);//为了刷新prod上的老数据
        Set<Id> rentalIdSet = new Set<Id>();//备品借出申请id 做询价用
        Set<Id> opdplanIdSet = new Set<Id>();//OPD计划id
        Set<Id> rentalproIdSet = new Set<Id>();//备品借出申请id 做产品1，2，3，4，5赋值用
        for (Report__c re : newList) {
            /** 从opd报告书得按钮带值
            //有备品从备品带，无备品从opd计划上带 询价
            if (re.Loaner_request_no1__c != null && (Trigger.isInsert || (Trigger.isUpdate && (oldMap.get(re.id).Loaner_request_no1__c != re.Loaner_request_no1__c))) ) {
                rentalIdSet.add(re.Loaner_request_no1__c);
            } else if (re.Loaner_request_no1__c == null && (Trigger.isInsert || (Trigger.isUpdate && (oldMap.get(re.id).Report_OPDPlan__c != re.Report_OPDPlan__c))) && re.Report_OPDPlan__c != null) {
                opdplanIdSet.add(re.Report_OPDPlan__c);
            }
            **/
            if( re.Purpose1__c=='OPD' && re.Loaner_request_no1__c != null && (Trigger.isInsert || (Trigger.isUpdate && (oldMap.get(re.id).Loaner_request_no1__c != re.Loaner_request_no1__c || oldMap.get(re.id).Purpose1__c != re.Purpose1__c || buffer==1)))){
                rentalproIdSet.add(re.Loaner_request_no1__c);
            } 
            //20210106 BWZ6M8 you start
             if(Trigger.isUpdate && oldMap.get(re.id).Status__c != re.Status__c && re.Status__c=='申請中' && oldMap.get(re.id).Status__c=='草案中' && re.Purpose1__c=='OPD'&& re.RecordTypeId == '01210000000RLTiAAO'&& re.Loaner_request_no1__c == null){
               re.Loaner_request_no1__c.addError('当目的1为OPD时：借出备品申请单号必须填写。');
            }
            //20210106 BWZ6M8 you end
        }
        /**
        //备品带询价
        if (rentalIdSet.size() > 0) {
            Map<string, string> rentalapplyMap = new Map<string, string>();
            List<Rental_Apply__c> rList = [select id, Follow_UP_Opp__c from Rental_Apply__c where id in:rentalIdSet and demo_purpose2__c = '试用（有询价）' and Follow_UP_Opp__c <> null];
            if (null != rList && rList.size() > 0) {
                for (Rental_Apply__c ra : rList) {
                    rentalapplyMap.put(ra.id, ra.Follow_UP_Opp__c);
                }
            }
            system.debug('==rentalapplyMap==' + rentalapplyMap);
            
            for (Report__c re : newList) {
                re.Opportunity1__c = null;
                re.Opportunity_Situation__c = '引合無';
                
                if (rentalapplyMap.containsKey(re.Loaner_request_no1__c)) {
                    re.Opportunity1__c = rentalapplyMap.get(re.Loaner_request_no1__c);
                    re.Opportunity_Situation__c = '跟进询价'; 
                }
             
            }
        }
        **/
        //借出备品配套一览  根据：备品配套明细型号 到产品：备品配套明细型号 比对，随机拿产品名字放过来
        //SWAG-C4U43T 20210713 you 改成 otcode去比对
        //1.重点产品主机/镜子最优先,2.主机/镜子（不要台车）,3.其他产品
        System.debug('rentalproIdSet'+rentalproIdSet);
    
        if (rentalproIdSet.size() > 0) {
            Set<String> raesdmodelSet = new Set<String>();//备品配套明细型号
            Map<String, String>  raesdmodelMap = new Map<String, String>();
            List<Rental_Apply_Equipment_Set__c> raesList = [select id, OtCode__c, Rental_Apply__c from Rental_Apply_Equipment_Set__c where Rental_Apply__c in:rentalproIdSet and RAES_Status__c !='取消'];
            if (null != raesList && raesList.size() > 0) {
                for (Rental_Apply_Equipment_Set__c raes : raesList) {
                    raesdmodelSet.add(raes.OtCode__c);
                    String key =  raes.Rental_Apply__c + '|' + raes.OtCode__c;
                    raesdmodelMap.put(key, raes.OtCode__c);
                }

            }
            system.debug('==raesdmodelMap==' + raesdmodelMap);
            String Key_ProductLabel = System.Label.Key_ProductLabel;//重点产品
            List<String> zhlistAll = new List<String>();
            if (raesdmodelMap.size() > 0) {
                List<Product2> prodList = [select id, ProductCode,Key_product_147P__c,Category3__c from Product2 where ProductCode != '' And ProductCode in:raesdmodelSet and IsActive =true]; //产品
                if (null != prodList && prodList.size() > 0) {
                    List<String> zdidList = new List<String>();//重点产品
                    List<String> fzdidList = new List<String>();//非重点产品
                    List<String> qtidList = new List<String>();//非重点产品
                    for (Product2 pro : prodList) {
                        String mapkey = '';
                        if(String.isNotBlank(pro.Key_product_147P__c) && Key_ProductLabel.contains(pro.Key_product_147P__c)){
                            mapkey = pro.ProductCode +'_'+ pro.id;
                            zdidList.add(mapkey);  
                        } else if(String.isNotBlank(pro.Category3__c) && (pro.Category3__c.contains('主机') || pro.Category3__c.contains('镜'))){
                            mapkey = pro.ProductCode +'_'+ pro.id;
                            fzdidList.add(mapkey);
                        } else{
                            mapkey = pro.ProductCode +'_'+ pro.id;
                            qtidList.add(mapkey);
                        }
                        
                    }
                    if(null!=zdidList && zdidList.size()>0){
                       zhlistAll.addAll(zdidList);
                    }
                    if(null!=fzdidList && fzdidList.size()>0){
                       zhlistAll.addAll(fzdidList);
                    }
                    if(null!=qtidList && qtidList.size()>0){
                       zhlistAll.addAll(qtidList);
                    }
                }
            }
            system.debug('zheli'+zhlistAll);
             for (Report__c re : newList) {
                
                re.Product1__c = null;
                re.Product2__c = null;
                re.Product3__c = null;
                re.Product4__c = null;
                re.Product5__c = null;
                
                if (zhlistAll != null && zhlistAll.size() > 0) {
                    Integer num = 1;
                    for (String modelNo : zhlistAll) {
                        String[] pdcode = modelNo.split('_');
                        String key = re.Loaner_request_no1__c + '|'+ pdcode[0];

                        String stringid = pdcode[1];
                        system.debug('==外key==' + key);
                        if (raesdmodelMap.containsKey(key)) {
                            system.debug('==内key==' + key);
                            if (num == 1) {
                                re.Product1__c = stringid;
                            } else if (num == 2) {
                                re.Product2__c = stringid;
                            } else if (num == 3) {
                                re.Product3__c = stringid;
                            } else if (num == 4) {
                                re.Product4__c = stringid;
                            } else if (num == 5) {
                                re.Product5__c = stringid;
                            }
                            num += 1;
                        }

                    }
                }
            }
        }   
        /**
        //opd计划带询价
        if (opdplanIdSet.size() > 0) {
            Map<string, string> opdplanMap = new Map<string, string>();
            List<OPDPlan__c> opdplanist = [select id, Related_Opportunity1_ID__c from OPDPlan__c where id in:opdplanIdSet and Related_Opportunity1_ID__c <> null];
            if (opdplanist.size() > 0) {
                for (OPDPlan__c op : opdplanist) {
                    opdplanMap.put(op.id, op.Related_Opportunity1_ID__c);
                }
            }
            for (Report__c re : newList) {
                re.Opportunity1__c = null;
                re.Opportunity_Situation__c = '引合無';
                if (opdplanMap.containsKey(re.Report_OPDPlan__c)) {
                    re.Opportunity1__c = opdplanMap.get(re.Report_OPDPlan__c);
                    re.Opportunity_Situation__c = '跟进询价';
                }

            }
        }
        **/
    }


//2021/01/28 liying start 耗材申请借出

 private void InsertReportConsume() {
        Set<Id> consumeIdSet = new Set<Id>();//耗材借出申请id 做询价用
        Set<Id> consumeproIdSet = new Set<Id>();//耗材借出申请id 做产品1，2，3，4，5赋值用
        for (Report__c re : newList) {
           
            if( (re.Purpose1__c=='SIS-ET' || re.Purpose1__c=='SIS-ENG耗材' )&& re.Consum_Apply__c != null && (Trigger.isInsert || (Trigger.isUpdate && (oldMap.get(re.id).Consum_Apply__c != re.Consum_Apply__c || oldMap.get(re.id).Purpose1__c != re.Purpose1__c)))){
                consumeproIdSet.add(re.Consum_Apply__c);
            } 
        }
        //耗材备品配套一览  根据：备品配套明细型号 到产品：备品配套明细型号 比对，随机拿产品名字放过来
        if (consumeproIdSet.size() > 0) {
            Set<String> raesdmodelSet = new Set<String>();//备品配套明细型号
            Map<String, String>  raesdmodelMap = new Map<String, String>();
            List<Consum_Apply_Equipment_Set__c> raesList = [select id, Model_No__c, Consum_Apply__c from Consum_Apply_Equipment_Set__c where Consum_Apply__c in:consumeproIdSet];
            if (null != raesList && raesList.size() > 0) {
                for (Consum_Apply_Equipment_Set__c raes : raesList) {
                    raesdmodelSet.add(raes.Model_No__c);
                    String key =  raes.Consum_Apply__c + '|' + raes.Model_No__c;
                    raesdmodelMap.put(key, raes.Model_No__c);
                }
            }
            system.debug('==raesdmodelMap==' + raesdmodelMap);
            Map<String, String> prodIdMap = new Map<String, String>();
            if (raesdmodelMap.size() > 0) {
                
                List<Product2> prodList = [select id, Fixture_Model_No_F__c from Product2 where Fixture_Model_No_F__c != '' And Fixture_Model_No_F__c in:raesdmodelSet and IsActive =true]; //产品
                if (null != prodList && prodList.size() > 0) {
                    for (Product2 pro : prodList) {
                        prodIdMap.put(pro.Fixture_Model_No_F__c, pro.id );
                    }
                }
            }
             for (Report__c re : newList) {
                
                re.Product1__c = null;
                re.Product2__c = null;
                re.Product3__c = null;
                re.Product4__c = null;
                re.Product5__c = null;
                
                system.debug('==prodIdMap==' + prodIdMap);
                if (prodIdMap != null && prodIdMap.size() > 0) {
                        Integer num = 1;
                        for (String modelNo : prodIdMap.keySet()) {

                            String key = re.Consum_Apply__c + '|'+ modelNo;
                            String stringid = prodIdMap.get(modelNo);
                            system.debug('==外key==' + key);
                            if (raesdmodelMap.containsKey(key)) {
                                system.debug('==内key==' + key);
                                if (num == 1) {
                                    re.Product1__c = stringid;
                                } else if (num == 2) {
                                    re.Product2__c = stringid;
                                } else if (num == 3) {
                                    re.Product3__c = stringid;
                                } else if (num == 4) {
                                    re.Product4__c = stringid;
                                } else if (num == 5) {
                                    re.Product5__c = stringid;
                                }
                                num += 1;
                            }

                        }
                    }
            	}
       		 }      
   		 }
//2021/01/28 liying end
}