public without sharing class OpportunityTriggerHandler {

    public static void updateStageLimit(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
        system.debug('=====updateStageLimit');
        
        //只有管理员和通过点击状态按钮才能更新询价状态
        Opportunity old = null;
        // String profileId = UserInfo.getProfileId().substring(0, 15);
        //新的获取人员简档ID
        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
        //if (newList[0].RecordTypeId != System.Label.SSBD_Replacement && profileId != System.Label.SystemAdmin && profileId != System.Label.SystemAdmin2 && profileId != System.Label.SystemAdmin_GPI && StaticParameter.StageProgressBarUpdate == false) {
        if (newList[0].RecordTypeId != System.Label.SSBD_Replacement 
            && new_profileId != System.Label.SystemAdmin && new_profileId != System.Label.SystemAdmin2 && new_profileId != System.Label.SystemAdmin_GPI
            && StaticParameter.StageProgressBarUpdate == false) {
            for (Opportunity opp : newList) {
                if (Trigger.isUpdate) {
                    old = oldMap.get(opp.Id);
                }
                if (Trigger.isInsert && opp.StageName != 'Prospect Created') {
                    opp.StageName.addError('新建询价时，询价状态只能为Prospect Created。');
                }
                if (Trigger.isUpdate && opp.StageName != old.StageName) {
                    opp.StageName.addError('不能直接编辑更新询价状态。');
                }
            }
        }   
    }
    
    public static void autoSet(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        system.debug('=====autoSet');
        
        for (Opportunity opp : newList) {
            //close以外的时候，预定下单日自动拷贝到结束日期
            if (opp.StageName != 'Closed Won' && opp.StageName != 'Closed Lost' && opp.StageName != 'Closed Cancel') {
                if (opp.ExpectedOrderDate__c != null) {
                    opp.CloseDate = opp.ExpectedOrderDate__c;
                } else {
                    opp.CloseDate = opp.NewInquiryDate__c == null ? Date.today().addMonths(6) : opp.NewInquiryDate__c.addMonths(6);
                }
            }
            if (opp.ProductSegmentCompetitor__c != opp.ProductSegment__c) {
                opp.ProductSegmentCompetitor__c = opp.ProductSegment__c;
            }
            if (opp.DealerNameF__c != opp.DealerNameText__c) {
                opp.DealerNameText__c = opp.DealerNameF__c;
            }

            Opportunity oldOpp = oldMap == null ? new Opportunity() : oldMap.get(opp.Id);
system.debug('=====' + opp.IE_Discount_Special__c      + '|' + oldOpp.IE_Discount_Special__c);
system.debug('=====' + opp.IE_Custom_Price__c          + '|' + oldOpp.IE_Custom_Price__c);
system.debug('=====' + opp.IE_local_cost__c            + '|' + oldOpp.IE_local_cost__c);
system.debug('=====' + opp.IE_Subtotal__c              + '|' + oldOpp.IE_Subtotal__c);
system.debug('=====' + opp.IE_ShippingHandling__c      + '|' + oldOpp.IE_ShippingHandling__c);
system.debug('=====' + opp.IE_Payment_terms__c         + '|' + oldOpp.IE_Payment_terms__c);
            String item_text = opp.OpportunityLineItem_text__c;
            item_text = item_text == null ? '' : item_text.replace('\r', '').replace('\n', '');
            String item_text2 = oldOpp.OpportunityLineItem_text__c;
            item_text2 = item_text2 == null ? '' : item_text2.replace('\r', '').replace('\n', '');

            String item_textot = opp.OpportunityLineItemOT_text__c;
            item_textot = item_textot == null ? '' : item_textot.replace('\r', '').replace('\n', '');
            String item_textot2 = oldOpp.OpportunityLineItemOT_text__c;
            item_textot2 = item_textot2 == null ? '' : item_textot2.replace('\r', '').replace('\n', '');
system.debug('=====' + item_text);
system.debug('=====' + item_text2);
            boolean changed = opp.IE_Discount_Special__c      != oldOpp.IE_Discount_Special__c      ||
                              //opp.OpportunityLineItem_text__c != oldOpp.OpportunityLineItem_text__c ||
                              item_textot.equals(item_textot2)    == false                              ||
                              //item_text.equals(item_text2)    == false                              ||                            
                              opp.IE_Custom_Price__c          != oldOpp.IE_Custom_Price__c          ||
                              opp.IE_local_cost__c            != oldOpp.IE_local_cost__c            ||
                              opp.IE_Subtotal__c              != oldOpp.IE_Subtotal__c              ||
                              opp.IE_ShippingHandling__c      != oldOpp.IE_ShippingHandling__c      ||
                              opp.IE_Payment_terms__c         != oldOpp.IE_Payment_terms__c;
            if (changed && OrderDivisionController.OrderDivision == false) {
                opp.SpecialPriceApproveStatus__c = 'Draft';
                //opp.test1__c = '1111';
                system.debug('@@@@@@autoSet');
                System.debug(item_textot+'@@@@@@@@@@@@@@@@'+ item_textot2);
                System.debug(item_textot.equals(item_textot2) );
            }
        }
    }
    
    public static void setIsNew(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        system.debug('=====setIsNew');
        
        for (Opportunity newOpp : newList) {
            //王鹏伟新加开始 新建询价时检查代理商
            String customerIds = System.label.CreateOppCustom;
            if(String.isNotBlank(customerIds) && !StaticParameter.StageProgressBarUpdate){
                List<String> customerIds_list = customerIds.split(',');
                if(customerIds_list!=null && customerIds_list.size()!=0 && newOpp.DealerId__c != null){
                    Boolean is_have = customerIds_list.contains(newOpp.DealerId__c.substring(0,15));
                    if(is_have){
                        newOpp.addError('代理商不允许新建询价！');
                    }
                }
            }
            if(newOpp.DealerSelectOwner__c != null){
                newOpp.OwnerId = newOpp.DealerSelectOwner__c;
            }
            //王鹏伟新加结束 新建询价时检查代理商
            if (UserInfo.getUserType() == 'PowerPartner' && newOpp.ProductSegment__c != 'BS' && newOpp.ProductSegment__c != 'IE' && newOpp.ProductSegment__c != 'RVI' && newOpp.RecordTypeId != System.Label.RT_SSBD_Service && newOpp.RecordTypeId != System.Label.SSBD_Replacement && StaticParameter.StageProgressBarUpdate == false) {
                newOpp.IsNew__c = true;
                // 外贸送达方默认为外贸公司
                if (newOpp.Trade_Type_D__c == 'Tax Exemption') {
                    newOpp.SpecialDeliveryAddress_D__c = newOpp.ForeignTradeCompany_D__c;
                }
            } else {
                //newOpp.Amount_D__c = newOpp.Amount;
                //newOpp.TotalOpportunityQuantity_D__c = newOpp.TotalOpportunityQuantity;
                newOpp.LeadSource_D__c = newOpp.LeadSource;
                //newOpp.CloseDate_D__c = newOpp.CloseDate;
                //newOpp.StageName_D__c = newOpp.StageName;
                newOpp.Budget_Amount_D__c = newOpp.BudgetAmount__c;
                newOpp.Cancel_Reason_Text_D__c = newOpp.CancelReasonText__c;
                newOpp.Competitor_Company_D__c = newOpp.CompetitorCompany__c;
                newOpp.Cancel_Reason_D__c = newOpp.CancelReason__c;
                newOpp.Competitor_Product_D__c = newOpp.Competitor_Product__c;
                newOpp.Competitor_Product2_D__c = newOpp.Competitor_Product2__c;
                newOpp.Competitor_Product3_D__c = newOpp.Competitor_Product3__c;
                newOpp.Competitor_Product4_D__c = newOpp.Competitor_Product4__c;
                newOpp.Competitor_Product5_D__c = newOpp.Competitor_Product5__c;
                newOpp.Competitor_Product6_D__c = newOpp.Competitor_Product6__c;
                newOpp.Competitor_Product7_D__c = newOpp.Competitor_Product7__c;
                newOpp.Competitor_Product8_D__c = newOpp.Competitor_Product8__c;
                newOpp.Competitor_Product_Code_D__c = newOpp.CompetitorProductCode__c;
                newOpp.Competitor_Product_Code2_D__c = newOpp.CompetitorProductCode2__c;
                newOpp.Competitor_Product_Code3_D__c = newOpp.CompetitorProductCode3__c;
                newOpp.Competitor_Product_Code4_D__c = newOpp.CompetitorProductCode4__c;
                newOpp.Competitor_Product_Code5_D__c = newOpp.CompetitorProductCode5__c;
                newOpp.Competitor_Product_Code6_D__c = newOpp.CompetitorProductCode6__c;
                newOpp.Competitor_Product_Code7_D__c = newOpp.CompetitorProductCode7__c;
                newOpp.Competitor_Product_Code8_D__c = newOpp.CompetitorProductCode8__c;
                newOpp.Dealer_Sales_Staff_Name_D__c = newOpp.DealerSalesStaffName__c;
                newOpp.Dealer_Service_D__c = newOpp.DealerService__c;
                // PIPL Update 20220420 By Chen Yanan Start
                newOpp.Dealer_Sales_Staff_Name_D_Encrypted__c = newOpp.DealerSalesStaffName_Encrypted__c;
                newOpp.Dealer_Service_D_Encrypted__c = newOpp.DealerService_Encrypted__c;
                // PIPL Update 20220420 By Chen Yanan End
                newOpp.Expected_Delivery_Date_D__c = newOpp.ExpectedDeliveryDate__c;
                newOpp.Expected_Order_Date_D__c = newOpp.ExpectedOrderDate__c;
                newOpp.Inquiry_Result_D__c = newOpp.InquiryResult__c;
                newOpp.Inquiry_Result_Cancel_D__c = newOpp.InquiryResultCancel__c;
                newOpp.Inquiry_Result_Lost_D__c = newOpp.InquiryResultLost__c;
                newOpp.Inquiry_Result_Order_D__c = newOpp.InquiryResultOrder__c;
                newOpp.Lost_Amount_D__c = newOpp.LostAmount__c;
                newOpp.Lost_Competitor_Product_D__c = newOpp.LostCompetitorProduct__c;
                newOpp.LostReasonText_D__c = newOpp.LostReasonText__c;
                newOpp.LostReason_D__c = newOpp.Lostreason__c;
                newOpp.New_Inquiry_Date_D__c = newOpp.NewInquiryDate__c;
                newOpp.Phase1Date_D__c = newOpp.Phase1Date__c;
                newOpp.Phase2Date_D__c = newOpp.Phase2Date__c;
                newOpp.Phase3Date_D__c = newOpp.Phase3Date__c;
                newOpp.Sales_Channel_D__c = newOpp.SalesChannel__c;
                newOpp.Sub_Dealer_D__c = newOpp.SubDealer__c;
                newOpp.Trade_Type_D__c = newOpp.TradeType__c;
                newOpp.Machine_Parts_D__c = newOpp.Machine_Parts__c;
                // 外贸送达方默认为外贸公司
                if (newOpp.Trade_Type_D__c == 'Tax Exemption') {
                    newOpp.SpecialDeliveryAddress__c = newOpp.ForeignTradeCompany__c;
                }
                newOpp.SpecialDeliveryAddress_D__c = newOpp.SpecialDeliveryAddress__c;
                newOpp.ForeignTradeCompany_D__c = newOpp.ForeignTradeCompany__c;
                newOpp.SpecialDeliveryContact_D__c = newOpp.SpecialDeliveryContact__c;
                if (UserInfo.getUserType() != 'PowerPartner') {
                    newOpp.DealerSelectOwner__c = newOpp.OwnerId;
                }
                Boolean specialDealer =  StaticParameter.specialDealerMap1.containsKey(newOpp.DealerId__c);
                Boolean control = newOpp.IS_Control__c;
                System.debug(newOpp.IS_Control__c);
                /*if(control == true){
                    newOpp.OwnerId = newOpp.DealerSelectOwner__c;
                }*/
                //newOpp.CrossCooperativeProject__c 跨区销售标记
                if(specialDealer == false && control == false && newOpp.CrossCooperativeProject__c != true){
                    newOpp.ApprovalStatus_D__c = 'Pass';
                }
            }
        }
    }
    
    public static void setPriceBook(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        system.debug('=====setPriceBook');
        
        Map<String, String> pricebookMap1 = new Map<String, String>();
        Map<String, String> pricebookMap2 = new Map<String, String>();
        Boolean needUpdate = false;

        for (Opportunity opp : newList) {
            
            Opportunity old = oldMap == null ? new Opportunity() : oldMap.get(opp.Id);
            system.debug('opp____'+opp.Pricebook2Id);
            system.debug('old____'+old.Pricebook2Id);
            if (trigger.isInsert || opp.Pricebook2Id != old.Pricebook2Id || opp.ProductSegment__c != old.ProductSegment__c ||
                opp.TradeType__c != old.TradeType__c || opp.Trade_Type_D__c != old.Trade_Type_D__c ||
                opp.SalesChannel__c != old.SalesChannel__c || opp.Sales_Channel_D__c != old.Sales_Channel_D__c ||
                opp.Machine_Parts__c != old.Machine_Parts__c || opp.Machine_Parts_D__c != old.Machine_Parts_D__c || opp.needUpdate__c == true) {

               needUpdate = true;
               system.debug('<---needUpdate--->'+ needUpdate);
            } else {
                continue;
            }
        }

        if(needUpdate){
            List<PriceBook2> pbeList = [select id, Name, ProductSegment__c, TradeType__c, SalesChannel__c, MachineParts__c from PriceBook2 where IsStandard = false];
            for (PriceBook2 pbe : pbeList) {
                pricebookMap1.put(pbe.ProductSegment__c + '-' + pbe.TradeType__c + '-' + pbe.SalesChannel__c + '-' + pbe.MachineParts__c, pbe.Id);
                pricebookMap2.put(pbe.Name, pbe.Id);
            }
    system.debug('=====pricebookMap1:' + pricebookMap1);
    system.debug('=====pricebookMap2:' + pricebookMap2);

            List<String> accIds = new List<String>();
            for (Opportunity opp : newList) {
                accIds.add(opp.AccountId);
            }
            List<Account> accList = [select Id, ProductSegmentF__c from Account where Id = :accIds];
            Map<String, String> acc2psMap = new Map<String, String>();
            for (Account acc : accList) {
                acc2psMap.put(acc.Id, acc.ProductSegmentF__c);
            }
    system.debug('=====acc2psMap:' + acc2psMap);
            for (Opportunity opp : newList) {
                Opportunity old = oldMap == null ? new Opportunity() : oldMap.get(opp.Id);
                if (trigger.isInsert || opp.Pricebook2Id != old.Pricebook2Id || opp.ProductSegment__c != old.ProductSegment__c ||
                    opp.TradeType__c != old.TradeType__c || opp.Trade_Type_D__c != old.Trade_Type_D__c ||
                    opp.SalesChannel__c != old.SalesChannel__c || opp.Sales_Channel_D__c != old.Sales_Channel_D__c ||
                    opp.Machine_Parts__c != old.Machine_Parts__c || opp.Machine_Parts_D__c != old.Machine_Parts_D__c || opp.needUpdate__c == true) {
                    // 是处理对象
                } else {
    system.debug('=====continue');
                    continue;
                }
                if (opp.ProductSegment__c != acc2psMap.get(opp.AccountId)) {
                    opp.ProductSegment__c = acc2psMap.get(opp.AccountId);
                }
    system.debug('=====ProductSegmentF__c:' + opp.AccountId + '|' + acc2psMap.get(opp.AccountId));
                String pbid = '';
                if (acc2psMap.get(opp.AccountId) == 'NDT' || acc2psMap.get(opp.AccountId) == 'ANI') {
                    /*String key = opp.ProductSegment__c;
                    pbid = pricebookMap2.get(key);*/
                    String key = opp.ProductSegment__c + '-' + opp.TradeType__c + '-' + opp.SalesChannel__c + '-' + opp.Machine_Parts__c;
                    if (opp.TradeType__c == null || opp.SalesChannel__c == null || opp.Machine_Parts__c == null) {
                        key = opp.ProductSegment__c + '-' + opp.Trade_Type_D__c + '-' + opp.Sales_Channel_D__c + '-' + opp.Machine_Parts_D__c;
                    }
                    pbid = pricebookMap1.get(key);
    system.debug('=====key:' + key);
                } else if (acc2psMap.get(opp.AccountId) == 'BS' || acc2psMap.get(opp.AccountId) == 'IE' || acc2psMap.get(opp.AccountId) == 'RVI') {
                    String key = opp.ProductSegment__c + '-' + opp.TradeType__c + '-' + opp.SalesChannel__c + '-' + opp.Machine_Parts__c;
                    system.debug('=====key-BS-IE-key1:' + key);
                    if (opp.TradeType__c == null || opp.SalesChannel__c == null || opp.Machine_Parts__c == null) {
                        key = opp.ProductSegment__c + '-' + opp.Trade_Type_D__c + '-' + opp.Sales_Channel_D__c + '-' + opp.Machine_Parts_D__c;
                    }
                    pbid = pricebookMap1.get(key);
    system.debug('=====key-BS-IE-key2:' + key);
                }
    system.debug('=====pbid:' + pbid);
    system.debug('=====Pricebook2Id:' + opp.Pricebook2Id);
                if (opp.Pricebook2Id != pbid) {
                    if (opp.ProductCount__c > 0 && opp.needUpdate__c == false) {
                        //新的获取人员简档ID
                        String new_profileId = calendarUtil.getMemberProfileID(UserInfo.getUserId().subString(0,15));
                        // String profileId = UserInfo.getProfileId().subString(0,15);
                        if (new_profileId.substring(0, 15) != System.Label.SystemAdmin && new_profileId.substring(0, 15) != System.Label.SystemAdmin2) {
                            opp.addError('询价中有产品时，不能更改价格手册和决定价格手册的项目。');
                        }
                    } else{
                        opp.Pricebook2Id = pbid;
                        opp.needUpdate__c = false;
                        system.debug('!!!!'+opp);
                    }
                }
                opp.needUpdate__c = false;
            }
        }
    }
    
    public static void updateForDealer(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        system.debug('=====updateForDealer');
        
        for (Opportunity newOpp : newList) {
            Opportunity oldOpp = oldMap.get(newOpp.Id);

            //newOpp.Amount_D__c != oldOpp.Amount_D__c;
            //newOpp.TotalOpportunityQuantity_D__c != oldOpp.TotalOpportunityQuantity_D__c;
            if (newOpp.LeadSource_D__c != oldOpp.LeadSource_D__c || 
            //newOpp.CloseDate_D__c != oldOpp.CloseDate_D__c;
            //newOpp.StageName_D__c != oldOpp.StageName_D__c;
                newOpp.AmountD__c != oldOpp.AmountD__c && (newOpp.ProductSegment__c != 'BS' && newOpp.ProductSegment__c != 'IE' && newOpp.ProductSegment__c != 'RVI' && newOpp.RecordTypeId != System.Label.RT_SSBD_Service ) || 
                newOpp.Budget_Amount_D__c != oldOpp.Budget_Amount_D__c || 
                newOpp.Cancel_Reason_Text_D__c != oldOpp.Cancel_Reason_Text_D__c || 
                newOpp.Cancel_Reason_D__c != oldOpp.Cancel_Reason_D__c || 
                newOpp.Competitor_Company_D__c != oldOpp.Competitor_Company_D__c || 
                newOpp.Competitor_Product_D__c != oldOpp.Competitor_Product_D__c || 
                newOpp.Competitor_Product2_D__c != oldOpp.Competitor_Product2_D__c || 
                newOpp.Competitor_Product3_D__c != oldOpp.Competitor_Product3_D__c || 
                newOpp.Competitor_Product4_D__c != oldOpp.Competitor_Product4_D__c || 
                newOpp.Competitor_Product5_D__c != oldOpp.Competitor_Product5_D__c || 
                newOpp.Competitor_Product6_D__c != oldOpp.Competitor_Product6_D__c || 
                newOpp.Competitor_Product7_D__c != oldOpp.Competitor_Product7_D__c || 
                newOpp.Competitor_Product8_D__c != oldOpp.Competitor_Product8_D__c || 
                newOpp.Competitor_Product_Code_D__c != oldOpp.Competitor_Product_Code_D__c || 
                newOpp.Competitor_Product_Code2_D__c != oldOpp.Competitor_Product_Code2_D__c || 
                newOpp.Competitor_Product_Code3_D__c != oldOpp.Competitor_Product_Code3_D__c || 
                newOpp.Competitor_Product_Code4_D__c != oldOpp.Competitor_Product_Code4_D__c || 
                newOpp.Competitor_Product_Code5_D__c != oldOpp.Competitor_Product_Code5_D__c || 
                newOpp.Competitor_Product_Code6_D__c != oldOpp.Competitor_Product_Code6_D__c || 
                newOpp.Competitor_Product_Code7_D__c != oldOpp.Competitor_Product_Code7_D__c || 
                newOpp.Competitor_Product_Code8_D__c != oldOpp.Competitor_Product_Code8_D__c || 
                newOpp.Dealer_Sales_Staff_Name_D__c != oldOpp.Dealer_Sales_Staff_Name_D__c || 
                newOpp.Dealer_Service_D__c != oldOpp.Dealer_Service_D__c || 
                newOpp.Expected_Delivery_Date_D__c != oldOpp.Expected_Delivery_Date_D__c || 
                newOpp.Expected_Order_Date_D__c != oldOpp.Expected_Order_Date_D__c || 
                newOpp.Inquiry_Result_D__c != oldOpp.Inquiry_Result_D__c || 
                newOpp.Inquiry_Result_Cancel_D__c != oldOpp.Inquiry_Result_Cancel_D__c || 
                newOpp.Inquiry_Result_Lost_D__c != oldOpp.Inquiry_Result_Lost_D__c || 
                newOpp.Inquiry_Result_Order_D__c != oldOpp.Inquiry_Result_Order_D__c || 
                newOpp.Lost_Amount_D__c != oldOpp.Lost_Amount_D__c || 
                newOpp.Lost_Competitor_Product_D__c != oldOpp.Lost_Competitor_Product_D__c || 
                newOpp.LostReasonText_D__c != oldOpp.LostReasonText_D__c || 
                newOpp.LostReason_D__c != oldOpp.Lostreason_D__c || 
                newOpp.New_Inquiry_Date_D__c != oldOpp.New_Inquiry_Date_D__c || 
                newOpp.Phase1Date_D__c != oldOpp.Phase1Date_D__c || 
                newOpp.Phase2Date_D__c != oldOpp.Phase2Date_D__c || 
                newOpp.Phase3Date_D__c != oldOpp.Phase3Date_D__c || 
                newOpp.Sales_Channel_D__c != oldOpp.Sales_Channel_D__c || 
                newOpp.Sub_Dealer_D__c != oldOpp.Sub_Dealer_D__c || 
                newOpp.Trade_Type_D__c != oldOpp.Trade_Type_D__c || 
                newOpp.Machine_Parts_D__c != oldOpp.Machine_Parts_D__c ||
                newOpp.SpecialDeliveryAddress_D__c != oldOpp.SpecialDeliveryAddress_D__c ||
                newOpp.ForeignTradeCompany_D__c != oldOpp.ForeignTradeCompany_D__c ||
                newOpp.SpecialDeliveryContact_D__c != oldOpp.SpecialDeliveryContact_D__c ||
                newOpp.DealerSelectOwner__c != oldOpp.DealerSelectOwner__c) {
                if (UserInfo.getUserType() == 'PowerPartner' && newOpp.ProductSegment__c != 'BS' && newOpp.ProductSegment__c != 'IE' && newOpp.ProductSegment__c != 'RVI'  && newOpp.RecordTypeId != System.Label.RT_SSBD_Service && newOpp.RecordTypeId != System.Label.SSBD_Replacement && OrderDivisionController.OrderDivision == false) {
                    newOpp.ApprovalStatus_D__c = 'Draft';
                    if(newOpp.ProductSegment__c == 'NDT' || newOpp.ProductSegment__c == 'ANI'){
                      newOpp.IsNew__c = true;
                    }
                    if (newOpp.Trade_Type_D__c == 'Tax Exemption' && newOpp.ForeignTradeCompany_D__c != oldOpp.ForeignTradeCompany_D__c) {
                        newOpp.SpecialDeliveryAddress_D__c = newOpp.ForeignTradeCompany_D__c;
                    }
                }
            }
            
                //newOpp.Amount_D__c = newOpp.Amount;
                //newOpp.TotalOpportunityQuantity_D__c = newOpp.TotalOpportunityQuantity;
            if (newOpp.LeadSource != oldOpp.LeadSource) {
                newOpp.LeadSource_D__c = newOpp.LeadSource;
            }
                //newOpp.CloseDate_D__c = newOpp.CloseDate;
                //newOpp.StageName_D__c = newOpp.StageName;
            if (newOpp.BudgetAmount__c != oldOpp.BudgetAmount__c) {
                newOpp.Budget_Amount_D__c = newOpp.BudgetAmount__c;
            }
            if (newOpp.CancelReasonText__c != oldOpp.CancelReasonText__c) {
                newOpp.Cancel_Reason_Text_D__c = newOpp.CancelReasonText__c;
            }
            if (newOpp.CancelReason__c != oldOpp.CancelReason__c) {
                newOpp.Cancel_Reason_D__c = newOpp.CancelReason__c;
            }
            if (newOpp.CompetitorCompany__c != oldOpp.CompetitorCompany__c) {
                newOpp.Competitor_Company_D__c = newOpp.CompetitorCompany__c;
            }
            if (newOpp.Competitor_Product__c != oldOpp.Competitor_Product__c) {
                newOpp.Competitor_Product_D__c = newOpp.Competitor_Product__c;
            }
            if (newOpp.Competitor_Product2__c != oldOpp.Competitor_Product2__c) {
                newOpp.Competitor_Product2_D__c = newOpp.Competitor_Product2__c;
            }
            if (newOpp.Competitor_Product3__c != oldOpp.Competitor_Product3__c) {
                newOpp.Competitor_Product3_D__c = newOpp.Competitor_Product3__c;
            }
            if (newOpp.Competitor_Product4__c != oldOpp.Competitor_Product4__c) {
                newOpp.Competitor_Product4_D__c = newOpp.Competitor_Product4__c;
            }
            if (newOpp.Competitor_Product5__c != oldOpp.Competitor_Product5__c) {
                newOpp.Competitor_Product5_D__c = newOpp.Competitor_Product5__c;
            }
            if (newOpp.Competitor_Product6__c != oldOpp.Competitor_Product6__c) {
                newOpp.Competitor_Product6_D__c = newOpp.Competitor_Product6__c;
            }
            if (newOpp.Competitor_Product7__c != oldOpp.Competitor_Product7__c) {
                newOpp.Competitor_Product7_D__c = newOpp.Competitor_Product7__c;
            }
            if (newOpp.Competitor_Product8__c != oldOpp.Competitor_Product8__c) {
                newOpp.Competitor_Product8_D__c = newOpp.Competitor_Product8__c;
            }
            if (newOpp.CompetitorProductCode__c != oldOpp.CompetitorProductCode__c) {
                newOpp.Competitor_Product_Code_D__c = newOpp.CompetitorProductCode__c;
            }
            if (newOpp.CompetitorProductCode2__c != oldOpp.CompetitorProductCode2__c) {
                newOpp.Competitor_Product_Code2_D__c = newOpp.CompetitorProductCode2__c;
            }
            if (newOpp.CompetitorProductCode3__c != oldOpp.CompetitorProductCode3__c) {
                newOpp.Competitor_Product_Code3_D__c = newOpp.CompetitorProductCode3__c;
            }
            if (newOpp.CompetitorProductCode4__c != oldOpp.CompetitorProductCode4__c) {
                newOpp.Competitor_Product_Code4_D__c = newOpp.CompetitorProductCode4__c;
            }
            if (newOpp.CompetitorProductCode5__c != oldOpp.CompetitorProductCode5__c) {
                newOpp.Competitor_Product_Code5_D__c = newOpp.CompetitorProductCode5__c;
            }
            if (newOpp.CompetitorProductCode6__c != oldOpp.CompetitorProductCode6__c) {
                newOpp.Competitor_Product_Code6_D__c = newOpp.CompetitorProductCode6__c;
            }
            if (newOpp.CompetitorProductCode7__c != oldOpp.CompetitorProductCode7__c) {
                newOpp.Competitor_Product_Code7_D__c = newOpp.CompetitorProductCode7__c;
            }
            if (newOpp.CompetitorProductCode8__c != oldOpp.CompetitorProductCode8__c) {
                newOpp.Competitor_Product_Code8_D__c = newOpp.CompetitorProductCode8__c;
            }
            if (newOpp.DealerSalesStaffName__c != oldOpp.DealerSalesStaffName__c) {
                newOpp.Dealer_Sales_Staff_Name_D__c = newOpp.DealerSalesStaffName__c;
                // PIPL Update 20220420 By Chen Yanan Start
                newOpp.Dealer_Sales_Staff_Name_D_Encrypted__c = newOpp.DealerSalesStaffName_Encrypted__c;
                // PIPL Update 20220420 By Chen Yanan End
            }
            if (newOpp.DealerService__c != oldOpp.DealerService__c) {
                newOpp.Dealer_Service_D__c = newOpp.DealerService__c;
                // PIPL Update 20220420 By Chen Yanan Start
                newOpp.Dealer_Service_D_Encrypted__c = newOpp.DealerService_Encrypted__c;
                // PIPL Update 20220420 By Chen Yanan End
            }
            if (newOpp.ExpectedDeliveryDate__c != oldOpp.ExpectedDeliveryDate__c) {
                newOpp.Expected_Delivery_Date_D__c = newOpp.ExpectedDeliveryDate__c;
            }
            if (newOpp.ExpectedOrderDate__c != oldOpp.ExpectedOrderDate__c) {
                newOpp.Expected_Order_Date_D__c = newOpp.ExpectedOrderDate__c;
            }
            if (newOpp.InquiryResult__c != oldOpp.InquiryResult__c) {
                newOpp.Inquiry_Result_D__c = newOpp.InquiryResult__c;
            }
            if (newOpp.InquiryResultCancel__c != oldOpp.InquiryResultCancel__c) {
                newOpp.Inquiry_Result_Cancel_D__c = newOpp.InquiryResultCancel__c;
            }
            if (newOpp.InquiryResultLost__c != oldOpp.InquiryResultLost__c) {
                newOpp.Inquiry_Result_Lost_D__c = newOpp.InquiryResultLost__c;
            }
            if (newOpp.InquiryResultOrder__c != oldOpp.InquiryResultOrder__c) {
                newOpp.Inquiry_Result_Order_D__c = newOpp.InquiryResultOrder__c;
            }
            if (newOpp.LostAmount__c != oldOpp.LostAmount__c) {
                newOpp.Lost_Amount_D__c = newOpp.LostAmount__c;
            }
            if (newOpp.LostCompetitorProduct__c != oldOpp.LostCompetitorProduct__c) {
                newOpp.Lost_Competitor_Product_D__c = newOpp.LostCompetitorProduct__c;
            }
            if (newOpp.LostReasonText__c != oldOpp.LostReasonText__c) {
                newOpp.LostReasonText_D__c = newOpp.LostReasonText__c;
            }
            if (newOpp.Lostreason__c != oldOpp.Lostreason__c) {
                newOpp.LostReason_D__c = newOpp.Lostreason__c;
            }
            if (newOpp.NewInquiryDate__c != oldOpp.NewInquiryDate__c) {
                newOpp.New_Inquiry_Date_D__c = newOpp.NewInquiryDate__c;
            }
            if (newOpp.Phase1Date__c != oldOpp.Phase1Date__c) {
                newOpp.Phase1Date_D__c = newOpp.Phase1Date__c;
            }
            if (newOpp.Phase2Date__c != oldOpp.Phase2Date__c) {
                newOpp.Phase2Date_D__c = newOpp.Phase2Date__c;
            }
            if (newOpp.Phase3Date__c != oldOpp.Phase3Date__c) {
                newOpp.Phase3Date_D__c = newOpp.Phase3Date__c;
            }
            if (newOpp.SalesChannel__c != oldOpp.SalesChannel__c) {
                newOpp.Sales_Channel_D__c = newOpp.SalesChannel__c;
            }
            if (newOpp.SubDealer__c != oldOpp.SubDealer__c) {
                newOpp.Sub_Dealer_D__c = newOpp.SubDealer__c;
            }
            if (newOpp.TradeType__c != oldOpp.TradeType__c) {
                newOpp.Trade_Type_D__c = newOpp.TradeType__c;
            }
             if (newOpp.Machine_Parts__c != oldOpp.Machine_Parts__c) {
                newOpp.Machine_Parts_D__c = newOpp.Machine_Parts__c;
            }
            if (newOpp.SpecialDeliveryAddress__c != oldOpp.SpecialDeliveryAddress__c) {
                newOpp.SpecialDeliveryAddress_D__c = newOpp.SpecialDeliveryAddress__c;
            }
            if (newOpp.ForeignTradeCompany__c != oldOpp.ForeignTradeCompany__c) {
                newOpp.ForeignTradeCompany_D__c = newOpp.ForeignTradeCompany__c;
                // 外贸送达方默认为外贸公司
                if (newOpp.Trade_Type_D__c == 'Tax Exemption') {
                    newOpp.SpecialDeliveryAddress__c = newOpp.ForeignTradeCompany__c;
                    newOpp.SpecialDeliveryAddress_D__c = newOpp.SpecialDeliveryAddress__c;
                }
            }
            if (newOpp.SpecialDeliveryContact__c != oldOpp.SpecialDeliveryContact__c) {
                newOpp.SpecialDeliveryContact_D__c = newOpp.SpecialDeliveryContact__c;
            }
            if (newOpp.OwnerId != oldOpp.OwnerId) {
                newOpp.DealerSelectOwner__c = newOpp.OwnerId;
            }
        }
    }
    
    public static void dealerOpportunityApproval(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        system.debug('=====dealerOpportunityApproval');
        
        for (Opportunity newOpp : newList) {
            Opportunity oldOpp = oldMap.get(newOpp.Id);
            
            if (newOpp.ApprovalStatus_D__c != oldOpp.ApprovalStatus_D__c) {
                if (newOpp.ApprovalStatus_D__c == 'Pass') {
                    // 批准过程肯定是一条一条批准的，所以这里再循环中写了select文
                    List<Account> accList = [select Id, IsNew__c, AccountStatus__c from Account where Id = :newOpp.AccountId];
                    if (accList.size() > 0) {
                        Account acc = accList[0];
                        if (acc.IsNew__c == true || acc.AccountStatus__c == 'Cancel') {
                            newOpp.addError('客户无效或未通过审批，不能批准当前询价。');
                        }
                    }
                    //List<OpportunityContactRole> ocrList = [select Id, OpportunityId, Contact.isNew__c, Contact.ContactStatus__c from OpportunityContactRole where OpportunityId = :newOpp.Id];
                    //for (OpportunityContactRole ocr : ocrList) {
                    //    if (ocr.Contact.isNew__c == true || ocr.Contact.ContactStatus__c == 'Cancel') {
                    //        newOpp.addError('联系人无效或未通过审批，不能批准当前询价。');
                    //    }
                    //}
                    //newOpp.Amount = newOpp.Amount_D__c;
                    //newOpp.TotalOpportunityQuantity = newOpp.TotalOpportunityQuantity_D__c;
                    newOpp.LeadSource = newOpp.LeadSource_D__c;
                    //newOpp.CloseDate = newOpp.CloseDate_D__c;
                    //newOpp.StageName = newOpp.StageName_D__c;
                    newOpp.BudgetAmount__c = newOpp.Budget_Amount_D__c;
                    newOpp.CancelReasonText__c = newOpp.Cancel_Reason_Text_D__c;
                    newOpp.CancelReason__c = newOpp.Cancel_reason_D__c;
                    newOpp.CompetitorCompany__c = newOpp.Competitor_Company_D__c;
                    newOpp.Competitor_Product__c = newOpp.Competitor_Product_D__c;
                    newOpp.Competitor_Product2__c = newOpp.Competitor_Product2_D__c;
                    newOpp.Competitor_Product3__c = newOpp.Competitor_Product3_D__c;
                    newOpp.Competitor_Product4__c = newOpp.Competitor_Product4_D__c;
                    newOpp.Competitor_Product5__c = newOpp.Competitor_Product5_D__c;
                    newOpp.Competitor_Product6__c = newOpp.Competitor_Product6_D__c;
                    newOpp.Competitor_Product7__c = newOpp.Competitor_Product7_D__c;
                    newOpp.Competitor_Product8__c = newOpp.Competitor_Product8_D__c;
                    newOpp.CompetitorProductCode__c = newOpp.Competitor_Product_Code_D__c;
                    newOpp.CompetitorProductCode2__c = newOpp.Competitor_Product_Code2_D__c;
                    newOpp.CompetitorProductCode3__c = newOpp.Competitor_Product_Code3_D__c;
                    newOpp.CompetitorProductCode4__c = newOpp.Competitor_Product_Code4_D__c;
                    newOpp.CompetitorProductCode5__c = newOpp.Competitor_Product_Code5_D__c;
                    newOpp.CompetitorProductCode6__c = newOpp.Competitor_Product_Code6_D__c;
                    newOpp.CompetitorProductCode7__c = newOpp.Competitor_Product_Code7_D__c;
                    newOpp.CompetitorProductCode8__c = newOpp.Competitor_Product_Code8_D__c;
                    newOpp.DealerSalesStaffName__c = newOpp.Dealer_Sales_Staff_Name_D__c;
                    newOpp.DealerService__c = newOpp.Dealer_Service_D__c;
                    // PIPL Update 20220420 By Chen Yanan Start
                    newOpp.DealerSalesStaffName_Encrypted__c = newOpp.Dealer_Sales_Staff_Name_D_Encrypted__c;
                    newOpp.DealerService_Encrypted__c = newOpp.Dealer_Service_D_Encrypted__c;
                    // PIPL Update 20220420 By Chen Yanan End
                    newOpp.ExpectedDeliveryDate__c = newOpp.Expected_delivery_date_D__c;
                    newOpp.ExpectedOrderDate__c = newOpp.Expected_Order_Date_D__c;
                    newOpp.InquiryResult__c = newOpp.Inquiry_result_D__c;
                    newOpp.InquiryResultCancel__c = newOpp.Inquiry_result_cancel_D__c;
                    newOpp.InquiryResultLost__c = newOpp.Inquiry_result_lost_D__c;
                    newOpp.InquiryResultOrder__c = newOpp.Inquiry_result_order_D__c;
                    newOpp.LostAmount__c = newOpp.Lost_amount_D__c;
                    newOpp.LostCompetitorProduct__c = newOpp.Lost_competitor_product_D__c;
                    newOpp.LostReasonText__c = newOpp.LostReasonText_D__c;
                    newOpp.LostReason__c = newOpp.Lostreason_D__c;
                    newOpp.NewInquiryDate__c = newOpp.New_Inquiry_Date_D__c;
                    newOpp.Phase1Date__c = newOpp.Phase1Date_D__c;
                    newOpp.Phase2Date__c = newOpp.Phase2Date_D__c;
                    newOpp.Phase3Date__c = newOpp.Phase3Date_D__c;
                    newOpp.SalesChannel__c = newOpp.Sales_Channel_D__c;
                    newOpp.SubDealer__c = newOpp.Sub_Dealer_D__c;
                    newOpp.TradeType__c = newOpp.Trade_Type_D__c;
                    newOpp.Machine_Parts__c = newOpp.Machine_Parts_D__c;
                    newOpp.SpecialDeliveryAddress__c = newOpp.SpecialDeliveryAddress_D__c;
                    newOpp.ForeignTradeCompany__c = newOpp.ForeignTradeCompany_D__c;
                    newOpp.SpecialDeliveryContact__c = newOpp.SpecialDeliveryContact_D__c;
                    if (newOpp.IsNew__c = true) {
                        newOpp.IsNew__c = false;
                    }
                    
                    newOpp.OwnerId = newOpp.DealerSelectOwner__c;
                    
                    if (newOpp.Inquiry_result_order_D__c != null) {
                        newOpp.StageName = 'Closed Won';
                    } else if (newOpp.Inquiry_result_lost_D__c != null) {
                        newOpp.StageName = 'Closed Lost';
                    } else if (newOpp.Inquiry_result_cancel_D__c != null) {
                        newOpp.StageName = 'Closed Cancel';
                    } else if (newOpp.Phase3Date_D__c != null) {
                        newOpp.StageName = 'Phase3';
                    } else if (newOpp.Phase2Date_D__c != null) {
                        newOpp.StageName = 'Phase2';
                    } else if (newOpp.Phase1Date_D__c != null) {
                        newOpp.StageName = 'Phase1';
                    } else {
                        newOpp.StageName = 'Prospect Created';
                    }
                }
                Boolean specialDealer =  StaticParameter.specialDealerMap1.containsKey(newOpp.DealerId__c);
            
                if (newOpp.ApprovalStatus_D__c == 'Reject' && newOpp.IsNew__c == false && specialDealer == false) {
                    //newOpp.Amount_D__c = newOpp.Amount;
                    //newOpp.TotalOpportunityQuantity_D__c = newOpp.TotalOpportunityQuantity;
                    newOpp.LeadSource_D__c = newOpp.LeadSource;
                    //newOpp.CloseDate_D__c = newOpp.CloseDate;
                    //newOpp.StageName_D__c = newOpp.StageName;
                    newOpp.Budget_Amount_D__c = newOpp.BudgetAmount__c;
                    newOpp.Cancel_Reason_Text_D__c = newOpp.CancelReasonText__c;
                    newOpp.Cancel_Reason_D__c = newOpp.CancelReason__c;
                    newOpp.Competitor_Company_D__c = newOpp.CompetitorCompany__c;
                    newOpp.Competitor_Product_D__c = newOpp.Competitor_Product__c;
                    newOpp.Competitor_Product2_D__c = newOpp.Competitor_Product2__c;
                    newOpp.Competitor_Product3_D__c = newOpp.Competitor_Product3__c;
                    newOpp.Competitor_Product4_D__c = newOpp.Competitor_Product4__c;
                    newOpp.Competitor_Product5_D__c = newOpp.Competitor_Product5__c;
                    newOpp.Competitor_Product6_D__c = newOpp.Competitor_Product6__c;
                    newOpp.Competitor_Product7_D__c = newOpp.Competitor_Product7__c;
                    newOpp.Competitor_Product8_D__c = newOpp.Competitor_Product8__c;
                    newOpp.Competitor_Product_Code_D__c = newOpp.CompetitorProductCode__c;
                    newOpp.Competitor_Product_Code2_D__c = newOpp.CompetitorProductCode2__c;
                    newOpp.Competitor_Product_Code3_D__c = newOpp.CompetitorProductCode3__c;
                    newOpp.Competitor_Product_Code4_D__c = newOpp.CompetitorProductCode4__c;
                    newOpp.Competitor_Product_Code5_D__c = newOpp.CompetitorProductCode5__c;
                    newOpp.Competitor_Product_Code6_D__c = newOpp.CompetitorProductCode6__c;
                    newOpp.Competitor_Product_Code7_D__c = newOpp.CompetitorProductCode7__c;
                    newOpp.Competitor_Product_Code8_D__c = newOpp.CompetitorProductCode8__c;
                    newOpp.Dealer_Sales_Staff_Name_D__c = newOpp.DealerSalesStaffName__c;
                    newOpp.Dealer_Service_D__c = newOpp.DealerService__c;
                    // PIPL Update 20220420 By Chen Yanan Start
                    newOpp.Dealer_Sales_Staff_Name_D_Encrypted__c = newOpp.DealerSalesStaffName_Encrypted__c;
                    newOpp.Dealer_Service_D_Encrypted__c = newOpp.DealerService_Encrypted__c;
                    // PIPL Update 20220420 By Chen Yanan End
                    newOpp.Expected_Delivery_Date_D__c = newOpp.ExpectedDeliveryDate__c;
                    newOpp.Expected_Order_Date_D__c = newOpp.ExpectedOrderDate__c;
                    newOpp.Inquiry_Result_D__c = newOpp.InquiryResult__c;
                    newOpp.Inquiry_Result_Cancel_D__c = newOpp.InquiryResultCancel__c;
                    newOpp.Inquiry_Result_Lost_D__c = newOpp.InquiryResultLost__c;
                    newOpp.Inquiry_Result_Order_D__c = newOpp.InquiryResultOrder__c;
                    newOpp.Lost_Amount_D__c = newOpp.LostAmount__c;
                    newOpp.Lost_Competitor_Product_D__c = newOpp.LostCompetitorProduct__c;
                    newOpp.LostReasonText_D__c = newOpp.LostReasonText__c;
                    newOpp.LostReason_D__c = newOpp.Lostreason__c;
                    newOpp.New_Inquiry_Date_D__c = newOpp.NewInquiryDate__c;
                    newOpp.Phase1Date_D__c = newOpp.Phase1Date__c;
                    newOpp.Phase2Date_D__c = newOpp.Phase2Date__c;
                    newOpp.Phase3Date_D__c = newOpp.Phase3Date__c;
                    newOpp.Sales_Channel_D__c = newOpp.SalesChannel__c;
                    newOpp.Sub_Dealer_D__c = newOpp.SubDealer__c;
                    newOpp.Trade_Type_D__c = newOpp.TradeType__c;
                    newOpp.Machine_Parts_D__c = newOpp.Machine_Parts__c;
                    newOpp.SpecialDeliveryAddress_D__c = newOpp.SpecialDeliveryAddress__c;
                    newOpp.ForeignTradeCompany_D__c = newOpp.ForeignTradeCompany__c;
                    newOpp.SpecialDeliveryContact_D__c = newOpp.SpecialDeliveryContact__c;
                    newOpp.DealerSelectOwner__c = newOpp.OwnerId;
                }
                //21.6.4 WLIG-C3LA3U 【委托】SSBG-LS特殊代理商中誉询价被驳回后自动取消
                String IdList = System.label.zhongyuID;
                if(IdList != null && newOpp.DealerId__c != null){
                    if (newOpp.ApprovalStatus_D__c == 'Reject' && IdList.contains(newOpp.DealerId__c.substring(0,15))){
                        newOpp.StageName = 'Closed Cancel';
                        newOpp.Cancel_Fail_Approve__c = 'Pass';
                        newOpp.Cancel_reason_D__c = 'Other';
                        newOpp.Cancel_Reason_Text_D__c = '其他';
                        newOpp.CancelReasonText__c = '其他';
                        newOpp.CancelReason__c = 'Other';
                    }
                }
            }
        }
    }
    
    public static void dealerOpportunityApproval2(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
       
        List<String> oppIdList = new List<String>();
        
        system.debug('=====dealerOpportunityApproval2');
        //List<String> passOppList = new List<String>();
        //List<String> rejectOppList = new List<String>();
        for (Opportunity newOpp : newList) {
            Opportunity oldOpp = oldMap.get(newOpp.Id);
            if (newOpp.ApprovalStatus_D__c != oldOpp.ApprovalStatus_D__c) {
                if (newOpp.ApprovalStatus_D__c == 'Pass') {
                    //passOppList.add(newOpp.Id);
                    oppIdList.add(newOpp.Id);
                }
                if (newOpp.ApprovalStatus_D__c == 'Reject' && newOpp.IsNew__c == false) {
                    //rejectOppList.add(newOpp.Id);
                }
            }
        }
        if (oppIdList.size() > 0) {
            List<OpportunityShare> osList = [select Id, OpportunityId, UserOrGroupId, OpportunityAccessLevel, RowCause from OpportunityShare where OpportunityId = :oppIdList and RowCause = 'Team' and OpportunityAccessLevel = 'Read'];
            for (OpportunityShare os : osList) {
                os.OpportunityAccessLevel = 'Edit';
            }
            if (osList.size() > 0) {
                update osList;
            }
        }
        
/*        List<OpportunityLineItem> updList = new List<OpportunityLineItem>();
        List<OpportunityLineItem> delList = new List<OpportunityLineItem>();
        if (passOppList.size() > 0) {
            List<OpportunityLineItem> oliList = [select id,Quantity,UnitPrice,Description,QuantityD__c,UnitPriceD__c,DescriptionD__c,IsNew__c,IsDelete__c from OpportunityLineItem where OpportunityId in :passOppList];
            for (OpportunityLineItem oli : oliList) {
                if (oli.IsDelete__c) {
                    delList.add(oli);
                } else {
                    oli.Quantity = oli.QuantityD__c;
                    oli.UnitPrice = oli.UnitPriceD__c;
                    oli.Description = oli.DescriptionD__c;
                    if (oli.IsNew__c == true) {
                        oli.IsNew__c = false;
                    }
                    updList.add(oli);
                }
            }
        }
        if (rejectOppList.size() > 0) {
            List<OpportunityLineItem> oliList = [select id,Quantity,UnitPrice,Description,QuantityD__c,UnitPriceD__c,DescriptionD__c,IsNew__c,IsDelete__c from OpportunityLineItem where OpportunityId in :rejectOppList];
            for (OpportunityLineItem oli : oliList) {
                if (oli.IsNew__c == false) {
                    oli.QuantityD__c = oli.Quantity;
                    oli.UnitPriceD__c = oli.UnitPrice;
                    oli.DescriptionD__c = oli.Description;
                    if (oli.IsDelete__c == true) {
                        oli.IsDelete__c = false;
                    }
                    updList.add(oli);
                } else {
                    delList.add(oli);
                }
            }
        }
        
        if (updList.size() > 0) {
            update updList;
        }
        if (delList.size() > 0) {
            delete delList;
        }*/
    }
    
    public static void setDealerGroup(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        List<String> groupIdList = new List<String>();
        List<String> oppIdList = new List<String>();
        
        List<String> specialDealerList = new List<String>();
        for (Opportunity newOpp : newList) {
            oppIdList.add(newOpp.Id);
            String dealerId = newOpp.Dealer__c;
            String groupId = StaticParameter.dealerGroupMap.get(dealerId == null ? '' : dealerId.substring(0, 15));
            Boolean flag = StaticParameter.specialDealerList.contains(dealerId == null ? '' : dealerId.substring(0, 15));
            if(flag){
                specialDealerList.add(newOpp.Id);
            }
            if (groupId == null || groupId.length() == 0) {
                continue;
            }
            groupIdList.add(groupId);
        }
        List<GroupMember> gmList = [select id, groupId, userOrGroupId from GroupMember where groupId = :groupIdList];
        
        List<OpportunityTeamMember> insertList = new list<OpportunityTeamMember>();

        for (Opportunity newOpp : newList) {
            if(newOpp.RecordTypeId != '0120l000000eXDu'){
                String dealerId = newOpp.Dealer__c;
                String groupId = StaticParameter.dealerGroupMap.get(dealerId == null ? '' : dealerId.substring(0, 15));
                if(specialDealerList.contains(newOpp.Id)){
                    OpportunityTeamMember otm = new OpportunityTeamMember();
                    otm.opportunityId = newOpp.Id;
                    otm.userId = newOpp.CreatedById;
                    otm.teamMemberRole = 'Sales Manager';
                    insertList.add(otm);
                    continue;
                }
                if (groupId == null || groupId.length() == 0) {
                    continue;
                }
                for (GroupMember gm : gmList) {
                    if (gm.groupId == groupId) {
                        OpportunityTeamMember otm = new OpportunityTeamMember();
                        otm.opportunityId = newOpp.Id;
                        otm.userId = gm.userOrGroupId;
                        otm.teamMemberRole = 'Sales Manager';
                        insertList.add(otm);
                    }
                }
            }
        }
        if (insertList.size() > 0) {
            insert insertList;
        }
        
        List<OpportunityShare> osList = new List<OpportunityShare>();
        osList = [select Id, OpportunityId, UserOrGroupId, OpportunityAccessLevel, RowCause from OpportunityShare where OpportunityId = :oppIdList and RowCause = 'Team'];
        for (OpportunityShare os : osList) {
            os.OpportunityAccessLevel = 'Edit';
        }
        if (osList.size() > 0) {
            update osList;
        }
    }

// Added by wangshuo for Opportunity BusinessDepOwner check

  public static void setReceiver(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap)
   {
        if (StaticParameter.OpportunityTriggerHandler_setReceiver) {
            return;
        }
        
        List<String> ownerIdList = new List<String>();
        Map<String,String> opportunityToOwner = new Map<String,String>();

        For (Opportunity opp: newList) {
            ownerIdList.add(opp.DealerSelectOwner__c);
            opportunityToOwner.put(opp.Id, opp.DealerSelectOwner__c);
        }

        Map<Id, User> copyUserMap = new Map<Id, User>([SELECT Id, Name,BS_AsistGenManger__c, BusinessDepOwner_Tax__c,BusinessDepOwner_WithoutTax__c,SalesWindow__c,Department__c,SalesManager__c FROM User 
            WHERE Id IN :ownerIdList ]);

           for (Opportunity opp: newList)
           {  User u = copyUserMap.get(OpportunityToOwner.get(opp.Id));
                if (u != null && ( u.BusinessDepOwner_Tax__c != null || u.BusinessDepOwner_WithoutTax__c != null ))
                 {
                    opp.BusinessDepOwnerWithoutTax__c = u.BusinessDepOwner_WithoutTax__c == null ? u.Id : u.BusinessDepOwner_WithoutTax__c;
                    opp.BusinessDepOwnerTax__c = u.BusinessDepOwner_Tax__c == null ? u.Id : u.BusinessDepOwner_Tax__c;
                }
                //王鹏伟新加 特价审批流程调整 开始
                if(u!=null && (u.SalesWindow__c != null || u.Department__c !=null)){
                    opp.IESalesManage__c = u.SalesManager__c != null ? u.SalesManager__c : u.Id;
                    opp.IESalesManageWindow__c  = u.SalesWindow__c != null ? u.SalesWindow__c : u.Id;
                    opp.DepartmentPrincipal__c = u.Department__c != null ? u.Department__c : u.Id;
                }
                //结束
                //跨区销售添加副部长
                if(u != null && u.BS_AsistGenManger__c != null){
                    opp.AsistGenManger__c = u.BS_AsistGenManger__c;
                }
            }  
            StaticParameter.OpportunityTriggerHandler_setReceiver = true;     
        }

    public static void setTextField(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
         
        List<String> targetList = new List<String>();
        Map<Id,Id> manager = new Map<Id,Id>();
        Map<Id,Id> association = new Map<Id,Id>();
        List<Id> oldId = new List<Id>();
        Map<Id,Id> nullList = new Map<Id,Id>();
        for (Opportunity newOpp : newList) {
            Opportunity oldOpp = oldMap.get(newOpp.Id);
            // if (newOpp.DealerSelectOwner__c != null){
            // WLIG-BVP4L2 触发101 修改了上面的判断条件，改为下面的判断依据，同时加上了if (userid.size() > 0)
            if((newOpp.DealerSelectOwner__c != null && newOpp.DealerSelectOwner__c != oldOpp.DealerSelectOwner__c) || newOpp.Manager__c  == null ){
                manager.put(newOpp.DealerSelectOwner__c , oldOpp.Id);
            }
            //用于关联询价
            if(newOpp.Have_Computer__c == false && newOpp.Association_Opportunity__c != null && newOpp.Association_Opportunity__c != oldOpp.Association_Opportunity__c && StaticParameter.OppCanChangeOpp == false){
                newOpp.addError('请在包含电脑的询价中选择主机询价。');
                
            }else if(newOpp.Have_Computer__c == true && newOpp.Association_Opportunity__c == null){
                newOpp.addError('请选择关联询价。');
            }else if(newOpp.CanChangeOpp__c == false && newOpp.Association_Opportunity__c != oldOpp.Association_Opportunity__c){
                newOpp.addError('合同已经提交审批或已经批准，不能修改关联询价');
            }else if(StaticParameter.OppChangeopp == false){
                if(newOpp.Association_Opportunity__c != null && newOpp.Association_Opportunity__c != oldOpp.Association_Opportunity__c){
                    association.put(newOpp.Association_Opportunity__c, newOpp.Id);
                    if(oldOpp.Association_Opportunity__c != null){
                        oldId.add(oldOpp.Association_Opportunity__c);
                    }
                }else if(newOpp.Association_Opportunity__c == null && oldOpp.Association_Opportunity__c != null){
                    nullList.put(oldOpp.Association_Opportunity__c,oldOpp.Id);
                }

            }
            if (oldOpp.SyncedQuoteId == null && newOpp.SyncedQuoteId == null) {
                targetList.add(newOpp.Id);
            }
             if(newOpp.OppShipping__c == null && newOpp.OppIntake__c != null){
                newOpp.OppShipping__c = newOpp.OppIntake__c.addDays(90);
                //Date.addDays(Integer days)
            }

            //王鹏伟 记录非定时任务更新询价的最后更新时间以及更新用户
            if(UserInfo.getUserId().substring(0,15) != '00528000004ooQW' && UserInfo.getUserId().substring(0,15) != '00528000006hJeB' ){
                newOpp.OppUpdateDateTime__c = Datetime.now();
                newOpp.OppUpdateUser__c = UserInfo.getUserId();
                if(newOpp.ProductSegment__c != 'NDT' && newOpp.ProductSegment__c != 'ANI'){
                    newOpp.IsUpdate__c = true;
                    newOpp.OppUpdateDate__c = Date.today();
                    newOpp.ThreeMonths__c = false;
                    newOpp.SixMonths__c = false;
                    newOpp.NineMonths__c = false;
                    newOpp.OneYear__c = false;
                }
            }
        }
        List<Opportunity> updateList = new List<Opportunity>();
        List<Order> updateOrdList = new List<Order>();
        if(association.size() > 0){

            for(Id ass : association.keySet()){
                Opportunity opp = new Opportunity();
                opp.Id =ass; 
                opp.Association_Opportunity__c = association.get(ass);
                updateList.add(opp);
            }
            for(Id id : oldId){
                Opportunity opp = new Opportunity();
                opp.Id = id;
                opp.Association_Opportunity__c = null;
                updateList.add(opp);
            }
            List<Id> ordIdList = new List<Id>();
            ordIdList.addAll(association.keySet());
            ordIdList.addAll(oldId);

            List<Order> ordList = new List<Order>();
            ordList = [select id,opportunityId from Order where opportunityId in : ordIdList and Status__c = 'Active'];
            Map<Id,Id> ord_oppMap = new Map<Id,Id>();
            List<Id> oldOrd = new List<Id>();
            if(ordList.size() >0){
                for(Order o : ordList){
                    if(association.keySet().contains(o.OpportunityId)){
                        if (newMap.get(association.get(o.OpportunityId)).OrderId__c != null) {
                            Order ordnew = new Order();
                            ordnew.Id = newMap.get(association.get(o.OpportunityId)).OrderId__c;
                            ordnew.Association_Order__c = o.Id;
                            order ordold = new Order();
                            ordold.Id = o.Id;
                            ordold.Association_Order__c = newMap.get(association.get(o.OpportunityId)).OrderId__c;
                            updateOrdList.add(ordnew);
                            updateOrdList.add(ordold);
                        }
                    }
                    if(oldId.contains(o.OpportunityId)){
                        Order ordnull = new Order();
                        ordnull.Id = o.Id;
                        ordnull.Association_Order__c = null;
                        updateOrdList.add(ordnull);
                    }
                }
            }
        }
        if(nullList.size() > 0 ){

            for(Id id : nullList.keySet()){
                Opportunity opp = new Opportunity();
                opp.Id = id;
                opp.Association_Opportunity__c = null;
                updateList.add(opp);
            }
            List<Order> ordList = [select id,opportunityId from Order where opportunityId in : nullList.keySet() and Status__c = 'Active'];
            if(ordList.size() > 0){
                for (Order o : ordList) {
                    if(nullList.keySet().contains(o.OpportunityId)){
                        if (newMap.get(nullList.get(o.OpportunityId)).OrderId__c != null) {
                            Order ord1 = new Order();
                            ord1.Id = newMap.get(nullList.get(o.OpportunityId)).OrderId__c;
                            ord1.Association_Order__c = null;
                            Order ord2 = new Order();
                            ord2.Id = o.Id;
                            ord2.Association_Order__c = null;
                            updateOrdList.add(ord1);
                            updateOrdList.add(ord2);
                        }
                    }
                }
            }
        }
        StaticParameter.OppChangeopp = true;
        StaticParameter.OppCanChangeOpp = true;
        StaticParameter.temp = true;
        if(updateList.size() > 0){
            // StaticParameter.OppChangeopp = true;
            // StaticParameter.OppCanChangeOpp = true;
            update updateList;
        }
        if(updateOrdList.size() > 0){
           //  StaticParameter.temp = true;
            update updateOrdList;
        }
        List<User> userList = new List<User>();
        Set<Id> userid = new Set<Id>();
        userid.addAll(manager.keySet());
        system.debug(manager);
        if (userid.size() > 0) {
            userList = [select id,SalesManager__c,BS_AsistGenManger__c from User where id in :userid];
            system.debug(userList);
            if(userList.size() > 0){
                for(User use : userList){

                    Id accid = manager.get(use.Id);
                    system.debug(accid);
                    system.debug(newMap);
                    newMap.get(accid).Manager__c = use.BS_AsistGenManger__c == null ? use.SalesManager__c : use.BS_AsistGenManger__c;

                }
            }
        }
        
        if(targetList.size() > 0){
            List<OpportunityLineItem> oliList = [select Id, Name, ProductCode, ECCode__c, Quantity, OpportunityId, Opportunity.Amount,ProductName__c from OpportunityLineItem where OpportunityId = :targetList order by OpportunityId, Id];
            Map<String, String> itemMap = new Map<String, String>();
            Map<String, Decimal> amountMap = new Map<String, Decimal>();
            Map<String, String> otitemMap = new Map<String, String>();
            //王鹏伟新加listitemMap 询价的产品配置清单（产品名称、U8 CODE、UPC CODE、数量）询价跟进
            Map<String, String> listitemMap = new Map<String,String>();
            for (OpportunityLineItem oli : oliList) {
                if (itemMap.containsKey(oli.OpportunityId) == false) {
                    itemMap.put(oli.OpportunityId, oli.ECCode__c + '|' + oli.Quantity);
                    otitemMap.put(oli.OpportunityId, oli.ProductCode + '|' + oli.Quantity);
                    listitemMap.put(oli.OpportunityId,oli.ProductName__c+'|'+ oli.ProductCode + '|' + oli.ECCode__c + '|' + oli.Quantity);
                    amountMap.put(oli.OpportunityId, oli.Opportunity.Amount);
                } else {
                    String tmp = itemMap.get(oli.OpportunityId);
                    String tmp1 = otitemMap.get(oli.OpportunityId);
                    String tmp2 = listitemMap.get(oli.OpportunityId);
                    itemMap.put(oli.OpportunityId, tmp + ',\r\n' + oli.ECCode__c + '|' + oli.Quantity);
                    otitemMap.put(oli.OpportunityId, tmp1 + ',\r\n' + oli.ProductCode + '|' + oli.Quantity);
                    listitemMap.put(oli.OpportunityId, tmp2 + ',\r\n' + oli.ProductName__c+'|'+ oli.ProductCode + '|' + oli.ECCode__c + '|' + oli.Quantity);
                }
            }


            for (Opportunity newOpp : newList) {
                Opportunity oldOpp = oldMap.get(newOpp.Id);
                if (oldOpp.SyncedQuoteId == null && newOpp.SyncedQuoteId == null) {
                    newOpp.OpportunityLineItem_text__c = itemMap.get(newOpp.Id);
                    newopp.OpportunityAmount_text__c = amountMap.get(newOpp.Id);
                    newopp.OpportunityLineItemOT_text__c = otitemMap.get(newOpp.Id);
                    newopp.OpportunityLineItemLIST_text__c = listitemMap.get(newOpp.Id);
                }
            }
        }

        // IE特价申请状态重置
        for (Opportunity newOpp : newList) {
            Opportunity oldOpp = oldMap.get(newOpp.Id);
            if ((newOpp.ProductSegment__c == 'IE' || newOpp.ProductSegment__c == 'RVI'|| newOpp.ProductSegment__c == 'NDT'|| newOpp.ProductSegment__c == 'ANI') && OrderDivisionController.OrderDivision == false) {
                if (newOpp.IE_Discount_Special__c != oldOpp.IE_Discount_Special__c ||
                    //newOpp.OpportunityLineItem_text__c != oldOpp.OpportunityLineItem_text__c ||
                    newOpp.OpportunityLineItemOT_text__c != oldOpp.OpportunityLineItemOT_text__c ||
                    newOpp.IE_Custom_Price__c != oldOpp.IE_Custom_Price__c ||
                    newOpp.IE_local_cost__c != oldOpp.IE_local_cost__c ||
                    newOpp.IE_Subtotal__c != oldOpp.IE_Subtotal__c ||
                    newOpp.IE_ShippingHandling__c != oldOpp.IE_ShippingHandling__c ||
                    newOpp.IE_Payment_terms__c != oldOpp.IE_Payment_terms__c) {
                    newOpp.SpecialPriceApproveStatus__c = 'Draft';
                    //newOpp.test1__c = '2222';
                    newOpp.IE_need_business_approve__c = false;
                    System.debug(newOpp.OpportunityLineItemOT_text__c +'@@@@@@@@@@@@@@@@@@'+ oldOpp.OpportunityLineItemOT_text__c);
                    System.debug( newOpp.OpportunityLineItemOT_text__c != oldOpp.OpportunityLineItemOT_text__c);
                    system.debug('@@@@@IE特价申请状态重置');
                }
            }
            //王鹏伟 新加，询价是否更新打勾，记录更新时间 开始 询价跟进
            if((newOpp.Visit_Notes__c != oldOpp.Visit_Notes__c || 
                newOpp.StageName != oldOpp.StageName || 
                newOpp.OpportunityLineItemLIST_text__c != oldOpp.OpportunityLineItemLIST_text__c) && 
                (newOpp.ProductSegment__c == 'NDT' || newOpp.ProductSegment__c == 'ANI')){

                newOpp.IsUpdate__c = true;
                newOpp.OppUpdateDate__c = Date.today();
                newOpp.ThreeMonths__c = false;
                newOpp.SixMonths__c = false;
            }
            //王鹏伟 新加，询价是否更新打勾，记录更新时间 结束
        }
    }


    public static void setOrderFields(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        System.debug('Opportunity1 StaticParameter.OpportunityTriggerIsUpdate:'+StaticParameter.OpportunityTriggerIsUpdate);
        if(StaticParameter.OpportunityTriggerIsUpdate || StaticParameter.StageProgressBarUpdate){
            System.debug('Opportunity2 StaticParameter.OpportunityTriggerIsUpdate:'+StaticParameter.OpportunityTriggerIsUpdate);
            StaticParameter.OpportunityTriggerIsUpdate = false;
            
            return;
        }
        List<String> targetList = new List<String>();
        List<String> targetList2 = new List<String>();
        List<String> targetList3 = new List<String>();
        String targetList4 = '';
        String quoId = '';
        Map<String, boolean> changedMap = new Map<String, boolean>();
        for (Opportunity opp : newList) {   
            Opportunity oldOpp = oldMap.get(opp.Id);
            if ((opp.ProductSegment__c == 'IE' || opp.ProductSegment__c == 'RVI'|| opp.ProductSegment__c == 'NDT'|| opp.ProductSegment__c == 'ANI') && opp.StageName != 'Closed Cancel' && opp.StageName != 'Closed Lost') {
                targetList.add(opp.Id);
                String item_text = opp.OpportunityLineItem_text__c;
                String item_textot = opp.OpportunityLineItemOT_text__c;

                item_text = item_text == null ? '' : item_text.replace('\r', '').replace('\n', '');
                item_textot = item_textot == null ? '' : item_textot.replace('\r', '').replace('\n', '');

                String item_text2 = oldOpp.OpportunityLineItem_text__c;
                String item_textot2 = oldOpp.OpportunityLineItemOT_text__c;
                
                item_text2 = item_text2 == null ? '' : item_text2.replace('\r', '').replace('\n', '');
                item_textot2 = item_textot2 == null ? '' : item_textot2.replace('\r', '').replace('\n', '');
                
                boolean changed = opp.IE_Discount_Special__c      != oldOpp.IE_Discount_Special__c      ||
                                  //item_text                       != item_text2                         ||
                                  item_textot                     != item_textot2                         ||     
                                  opp.IE_Custom_Price__c          != oldOpp.IE_Custom_Price__c          ||
                                  opp.IE_local_cost__c            != oldOpp.IE_local_cost__c            ||
                                  opp.IE_Subtotal__c              != oldOpp.IE_Subtotal__c              ||
                                  opp.IE_ShippingHandling__c      != oldOpp.IE_ShippingHandling__c      ||
                                  opp.IE_Payment_terms__c         != oldOpp.IE_Payment_terms__c;
                changedMap.put(opp.Id, oldOpp.SpecialPriceApproveStatus__c == 'Pass' && changed);
            }
            if (opp.OwnerId != oldOpp.OwnerId) {
                targetList2.add(opp.Id);
            }
            //开始 王鹏伟添加代码 询价贸易管理客户分类变更时，合同贸易管理客户分类同步变更 
            if(opp.customerType__c != oldOpp.customerType__c){
                StaticParameter.OrderTriggerIsUpdate = true;
                if(!targetList2.contains(opp.Id)){
                    targetList2.add(opp.Id);
                }
            }
            //结束 王鹏伟添加代码 询价贸易管理客户分类变更时，合同贸易管理客户分类同步变更 
            //添加日期:2019-1-3日
            //添加原因:在询价的同步报价修改时,将同步报价的付款方式赋值到合同中.        
            if(opp.Quote_PaymentTerms__c != oldOpp.Quote_PaymentTerms__c && opp.Quote_PaymentTerms__c != null){
                targetList3.add(opp.Id);
            }
            system.debug('%%%%%%%%%%%'+opp.Dealer__c);
            if((opp.SyncedQuoteId != oldOpp.SyncedQuoteId || oldOpp.SyncedQuoteId == null) && (opp.Dealer__c != '0012800001HoORb' && opp.Dealer__c != '0012800001HoPY4' && opp.Dealer__c != '0012800001HoPaz')){
               system.debug('@@@111');
               quoId = opp.SyncedQuoteId; 
            }
            if(opp.ProductSegment__c == 'BS' && opp.StageName == 'Phase3' && opp.Is_Decided__c == true && oldOpp.Is_Decided__c == false){
                system.debug(opp.SyncedQuoteId);
                targetlist4=opp.SyncedQuoteId;
            }

        }

        if (targetList.size() > 0) {
            List<Order> odrList = [select id, OpportunityId,ForeignTradeCompany_D__c,TradeType__c,ProductSegment__c from Order where OpportunityId = :targetList and Status__c = 'Active'];
            for (Order odr : odrList) {
                Opportunity opp = newMap.get(odr.OpportunityId);

                odr.Discount_D__c = opp.Quote_Discount__c;
                odr.Olympus_Price_BeforeDiscount_D__c = opp.Quote_Subtotal__c;
                odr.PaymentCondition_D__c = opp.Quote_PaymentTerms_Text__c;
                Decimal warranty = opp.Quote_Warranty__c;
                odr.SpecialWarranty_D__c = warranty == null ? '' : warranty.format();
                odr.CustomerContractPriceD__c = opp.Quote_CustomPrice__c == null ? 0 : opp.Quote_CustomPrice__c;
                odr.Shipment_Term_D__c = opp.Quote_ShipmentTerm__c;
                odr.Shipment_Term2_D__c = opp.Quote_ShipmentTerm2__c;
                Decimal totalPrice = opp.Quote_TotalPrice__c;
                if(opp.ProductSegment__c != 'NDT' && opp.ProductSegment__c != 'ANI'){
                    odr.OlympusContractPricesD__c = totalPrice.setScale(0, System.RoundingMode.HALF_UP);
                }else{
                    odr.OlympusContractPricesD__c = totalPrice;
                    odr.WarrantyD__c = warranty == null ? '' : warranty.format();
                }
                //odr.OlympusContractPrices__c = odr.OlympusContractPricesD__c;
                odr.Cost_D__c = opp.IE_local_cost__c;
                if (changedMap.get(odr.OpportunityId)) {
                    odr.Status__c = 'Inactive';
                }
            }
            
            System.debug('odrList------'+odrList);
            if (odrList.size() > 0) update odrList;
        }
        if (targetList2.size() > 0) {
            //王鹏伟询价贸易管理类型变更，合同同步变更  添加SQL搜索字段TradeMagCategory__c
            List<Order> odrList = [select id, OpportunityId,TradeMagCategory__c from Order where OpportunityId = :targetList2];
            for (Order odr : odrList) {
                Opportunity opp = newMap.get(odr.OpportunityId);
                //王鹏伟询价贸易管理类型变更，合同同步变更  新加一行
                odr.TradeMagCategory__c = opp.customerType__c;
                // 跨区域销售，合同共享异常。因此注释 20210906 XHL  Start
                // odr.OwnerId = opp.OwnerId;
                // 跨区域销售，合同共享异常。因此注释 20210906 XHL  End
            }

            if (odrList.size() > 0) update odrList;
        }
        //添加日期:2019-1-3日
        //添加原因:在询价的同步报价修改时,将同步报价的付款方式赋值到合同中.
        if(targetList3.size() > 0 ){
            List<Order> odrList = [select id,OpportunityId from Order WHERE OpportunityId in :targetList3];
            if(odrList.size() > 0){
                for(Order odr : odrList){
                    Opportunity opp = newMap.get(odr.OpportunityId);

                    odr.PaymentTerms__c = opp.Quote_PaymentTerms__c;
                }
                update odrList;
            }
        }

        if(quoID != null && quoId.length() > 0){
            List<QuoteLineItem> qliList = [select id,DontSingleProduct__c from QuoteLineItem where QuoteId = :quoId];
            String temp = '';
            for(QuoteLineItem qli : qliList){
                if(qli.DontSingleProduct__c != '1'){
                    temp+=(' '+qli.DontSingleProduct__c);
                }
            }
            Quote quo = new Quote();
            quo.id = quoId;
            quo.DontSingleProductCode__c = temp;

            if(temp.length() >0) update quo;
        }

        if(targetList4 != null && targetlist4 != '' ){
            List<QuoteLineItem> quoLIList = [select Id, QuoteId, Description, Quantity, PricebookEntryId, UnitPrice from QuoteLineItem where QuoteId = :targetlist4];
            List<Order> ordList = [select Id from Order where QuoteId = :targetlist4 and Contract_Status__c = 'Active'];
            if(ordList.size() > 0){
                Order ord = ordList[0];
                String orderId = ord.Id;
                List<OrderItem> oiList = [select Id from OrderItem where OrderId = :orderId];
                List<OrderItem> insList = new List<OrderItem>();
                for (QuoteLineItem qli : quoLIList) {
                    OrderItem oi = new OrderItem();
                    oi.Description = qli.Description;
                    oi.Quantity = qli.Quantity;
                    oi.PricebookEntryId = qli.PricebookEntryId;
                    oi.UnitPrice = qli.UnitPrice;
                    oi.OrderId = orderId;
                    oi.QuoteLineItemId = qli.Id;
                    insList.add(oi);
                }
                system.debug('111');
                if (oiList.size() > 0) delete oiList;
                if (insList.size() > 0) insert insList;
            }
        }   
    }


    public static void check(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        
        String id = newList[0].id;
        List<OpportunityLineItem> oliList = [select id,Product2.If_Exempt_Product__c,Product2.If_Radiation_Product__c from OpportunityLineItem where opportunityId = :id];
        Boolean hasA = false;
        if(newList[0].ProductSegment__c == 'ANI' ||newList[0].ProductSegment__c == 'NDT'){
            for(OpportunityLineItem oli : oliList){
                if(oli.Product2.If_Exempt_Product__c == false && oli.Product2.If_Radiation_Product__c == true){
                    hasA = true;
                }
            }
            if(hasA == true){
                String str =  LicenseCheckUtil.LicenseCheck1(newList[0].DealerId__c);
            newList[0].check__c =str;
          
            }
        } 
        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++; 
    }

     public static String checkoly(){
        return LicenseCheckUtil.LicenseCheckOly();
     }
}