public without sharing class OpportunityTrigger {

    public static Boolean isFirst = true;

    public static void lockOpportunityFile(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {

        List<String> targetIds = new List<String>();
        for (Opportunity newOpp : newList) {
            Opportunity oldOpp = oldMap.get(newOpp.Id);
            if (newOpp.Stock_apply_status__c != oldOpp.Stock_apply_status__c &&
                    newOpp.Stock_apply_status__c == '批准' && oldOpp.Stock_apply_status__c == '申请中') {
                targetIds.add(newOpp.Id);
            }
        }

        if (targetIds.size() == 0) Return;

        List<Opportunity_File__c> ofileList = [select id, Is_Locked__c from Opportunity_File__c where Opportunity__c = :targetIds and Is_Locked__c = false];
        for (Opportunity_File__c ofile : ofileList) {
            ofile.Is_Locked__c = true;
        }

        update ofileList;
    }

    //CHAN-AZJ6JS 追溯系统来的询价，取消WIN时，经销商订单自动改到“驳回”
    public static void changeConsumableOrderStatus(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        
        List<String> orderIds = new List<String>();

        for (Opportunity newOpp : newList) {
            // si询价新逻辑 为配置建议决定时间赋值 by vivek start
            if(newOpp.Configuration_Suggestion__c == '无建议' && newOpp.Recommended_Confirmation_Time__c == null){
                newOpp.Recommended_Confirmation_Time__c = Date.today();
            }
            if(newOpp.Configuration_Suggestion__c == '有建议' && newOpp.Configuration_Suggestion_Feedback__c != null && newOpp.Recommended_Confirmation_Time__c == null){
                newOpp.Recommended_Confirmation_Time__c = Date.today();
            }
            // si询价新逻辑 为配置建议决定时间赋值 by vivek end
            Opportunity oldOpp = oldMap.get(newOpp.Id);
            if (newOpp.SAP_Send_OK__c != oldOpp.SAP_Send_OK__c && newOpp.SAP_Send_OK__c == false ) {
                if (String.isNotBlank(newOpp.Estimation_Id__c) && newOpp.Estimation_Id__c.StartsWith('a2K'))newOpp.StageName = '削除';
                if (String.isNotBlank(newOpp.Opportunity_No__c)) orderIds.add(newOpp.Opportunity_No__c);
                //fy DB202312538864 2024.02.20 start
                // //lastbuy  2022/2/9 fy start
                // List<LastbuyProduct__c> upLastbuyObjList = new List<LastbuyProduct__c>();
                // List<LastbuyProduct__c> LastbuyObjList=[select id,LastbuyQuantity__c,InquiryCode__c,ProductName__c,effectiveFLG__c from LastbuyProduct__c where InquiryCode__c= : newOpp.Id];
                // if(LastbuyObjList!=null){
                //     for(LastbuyProduct__c lastbuypr :LastbuyObjList){
                //         lastbuypr.ActualQuantity__c=0;
                //         lastbuypr.effectiveFLG__c=true;
                //         upLastbuyObjList.add(lastbuypr);
                //     }
                // }
                // if(upLastbuyObjList!=null){
                //     upsert upLastbuyObjList;           
                // }
                // //lastbuy  2022/2/9 fy end
                //fy DB202312538864 2024.02.20 end
            }
        }

        if (orderIds.size() == 0) Return;
        ControllerUtil.selectAndupdateOrderSatus(orderIds);

        

        /*List<Consumable_order__c> orderList = [select id, Order_status__c from Consumable_order__c where Name = :orderIds and Order_status__c = '批准' and RecordType.DeveloperName = 'Order'];
        for (Consumable_order__c order : orderList) {
            order.Order_status__c = '驳回';
        }
        update orderList;*/
    }

    // CHAN-AYTCE6  询价页面中的经销商1变更后更新报价中经销商1  2018/5/25 start
    public static void changeQuoteAgency1(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        Map<Id, Opportunity> oppIdMap = new Map<Id, Opportunity>();
        for (Opportunity newOpp : newList) {
            if (!String.isBlank(newOpp.Estimation_No__c) && newOpp.StageName__c != '取消' && newOpp.StageName__c != '失单') {
                Opportunity oldOpp = oldMap.get(newOpp.Id);
                if (
                    (
                        (String.isBlank(oldOpp.Agency1__c) && !String.isBlank(newOpp.Agency1__c))
                        || (!String.isBlank(oldOpp.Agency1__c) && String.isBlank(newOpp.Agency1__c))
                        || oldOpp.Agency1__c != newOpp.Agency1__c
                    )
                    &&
                    (
                        newOpp.Estimation_No__c == oldOpp.Estimation_No__c
                    )
                ) {
                    oppIdMap.put(newOpp.Id, newOpp);
                }
            }
        }
        if (oppIdMap.size() > 0) {
            List<Quote> quList = [Select Id, Agency1__c, Quote_No__c, OpportunityId
                                  from Quote where OpportunityId In: oppIdMap.keySet()];
            if (quList != null && quList.size() > 0) {
                List<Quote> quUpd = new List<Quote>();
                for (Quote q : quList) {
                    Opportunity opp = oppIdMap.get(q.OpportunityId);
                    if (q.Quote_No__c == opp.Estimation_No__c) {
                        q.Agency1__c = opp.Agency1__c;
                        quUpd.add(q);
                    }
                }
                if (quUpd.size() > 0) {
                    update quUpd;
                }
            }
        }
    }
    // CHAN-AYTCE6  询价页面中的经销商1变更后更新报价中经销商1  2018/5/25 end
    
    //  千里马 - 招投标状态更新Batch  mzy  2021-05-13  start
    //  更新招投标上反应询价标识
    public static void UpdateBiddingFlag(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        if (StaticParameter.EscapeOpportunityBefUpdTrigger) {
            return;
        }
        List<Tender_information__c> tenderList = new List<Tender_information__c>();
        Map<String,Tender_information__c> tenderMap = new Map<String,Tender_information__c>();
        // 招标-询价关联修改 需要从link表里确认有哪些信息需要修改
        List<String> oppIds = new List<String>();
        for (Opportunity op : newList) {
            oppIds.add(op.Id);
        }
        List<Tender_Opportunity_Link__c> links = [SELECT Id, Tender_information__c, Tender_information__r.IsReactionOpp__c, Opportunity__c FROM Tender_Opportunity_Link__c WHERE Opportunity__c IN :oppIds AND Tender_information__r.IsReactionOpp__c = false];
        // 由于变为link之后，招标项目字段不再每次绑定时都更新，针对招标-询价关联时修改反映询价标记的修改无法顾及所有
        // 在此处只对win和失单判断做更新
        for(Opportunity op : newList){
            // Tender_information__c temptender = new Tender_information__c();
            //Tender_information__c Oldtemptender = new Tender_information__c();
            Opportunity oldopp = oldMap == null? null : oldMap.get(op.id); 
            if(oldopp != null){

                //判断询价的招标项目  从有到无 -- 从无到有
                // if( op.Bidding_Project_Name_Bid__c != oldopp.Bidding_Project_Name_Bid__c){
                        

                //         if(String.isNotBlank(op.Bidding_Project_Name_Bid__c)){
                //             temptender.id = op.Bidding_Project_Name_Bid__c;                            
                //             temptender.IsReactionOpp__c = true;
                //             tenderMap.put(temptender.id ,temptender );
                            
                //         }
                //         if(String.isNotBlank(oldopp.Bidding_Project_Name_Bid__c)) {
                //             temptender = new Tender_information__c();
                //             temptender.id = oldopp.Bidding_Project_Name_Bid__c;
                //             temptender.IsReactionOpp__c = true;
                //             tenderMap.put(temptender.id ,temptender );
                //         } 
                        
                // }

                // 从不win到win 或 从win到不win 并且 招投标项目不为空
                // if( (op.SAP_Send_OK__c != oldopp.SAP_Send_OK__c )&&String.isNotBlank(op.Bidding_Project_Name_Bid__c) ){
                //     temptender.id = op.Bidding_Project_Name_Bid__c;
                //     temptender.IsReactionOpp__c = true;
                //     tenderMap.put(temptender.id ,temptender );
                // }

                // 从失单到不失单 或  从不失单到失单 并且 招投标项目不为空
                // if( ( (op.StageName__c.equals('失单') && !oldopp.StageName__c.equals('失单'))
                //     ||(!op.StageName__c.equals('失单') && oldopp.StageName__c.equals('失单')) ) &&String.isNotBlank(op.Bidding_Project_Name_Bid__c) ){
                //     temptender.id = op.Bidding_Project_Name_Bid__c;
                //     temptender.IsReactionOpp__c = true;
                //     tenderMap.put(temptender.id ,temptender ); 
                // }
                // 合并判断条件 
                //20220803 you 招标项目增加 取消，中标结果更新确认条件
                if((op.SAP_Send_OK__c != oldopp.SAP_Send_OK__c) || 
                    ((op.StageName__c.equals('失单') && !oldopp.StageName__c.equals('失单')) || 
                    (!op.StageName__c.equals('失单') && oldopp.StageName__c.equals('失单'))) ||
                    ((op.StageName__c.equals('取消') && !oldopp.StageName__c.equals('取消')) || 
                    (!op.StageName__c.equals('取消') && oldopp.StageName__c.equals('取消'))) ||
                    (String.isNotBlank(op.ConfirmationofAward__c) && op.ConfirmationofAward__c!=oldopp.ConfirmationofAward__c)) {
                    for (Tender_Opportunity_Link__c link : links) {
                        if (link.Opportunity__c == op.Id) {
                            Tender_information__c temptender = new Tender_information__c();
                            temptender.Id = link.Tender_information__c;
                            temptender.IsReactionOpp__c = true;
                            tenderMap.put(temptender.id ,temptender); 
                        }
                    }
                }
                //DB202304056706  you 20230406 清空 打标识，重新执行batch
                if(String.isBlank(op.ConfirmationofAward__c) && op.ConfirmationofAward__c!=oldopp.ConfirmationofAward__c){
                   for (Tender_Opportunity_Link__c link : links) {
                        if (link.Opportunity__c == op.Id) {
                            Tender_information__c temptender = new Tender_information__c();
                            temptender.Id = link.Tender_information__c;
                            temptender.IsReactionOpp__c = true;
                            tenderMap.put(temptender.id ,temptender); 
                        }
                    } 
                }
                //20221017  lt SWAG-CHL5XA【FY23询价改善】-统计主机台数 start
                // System.debug('lt123 oly主机'+op.OlyNumberHosts__c);
                // System.debug('lt123 老oly主机'+oldopp.OlyNumberHosts__c);
                // System.debug('lt123 对手主机'+op.RivalHostsNumber__c);
                // System.debug('lt123 老对手主机'+oldopp.RivalHostsNumber__c);

                if(op.OlyNumberHosts__c != oldopp.OlyNumberHosts__c || op.RivalHostsNumber__c != oldopp.RivalHostsNumber__c){
                    for (Tender_Opportunity_Link__c link : links){
                        if (link.Opportunity__c == op.Id){
                            Tender_information__c temptender = new Tender_information__c();
                            temptender.Id = link.Tender_information__c;
                            temptender.IsReactionOpp__c = true;
                            tenderMap.put(temptender.id ,temptender); 
                        }
                    }
                }
                //20221017  lt SWAG-CHL5XA【FY23询价改善】-统计主机台数 end

            // }else {
            //     //新建时判断询价的招标项目是不是从无到有
            //     if(String.isNotBlank(op.Bidding_Project_Name_Bid__c) ){
            //         temptender.id = op.Bidding_Project_Name_Bid__c;
            //         temptender.IsReactionOpp__c = true;
            //         tenderMap.put(temptender.id ,temptender );
            //     }
            }
        }


        System.debug('招标Map:'+tenderMap);
        if(tenderMap.size()>0){
            update tenderMap.values();
        }

    }

    // 千里马 - 招投标状态更新Batch  mzy  2021-05-13  start
    // 招标-询价关联 20210817 start
    public static void changeLastLinkedTender(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        List<Tender_Opportunity_Link__c> new_links = new List<Tender_Opportunity_Link__c>();
        for(Opportunity op : newList){
            // 先判断Bidding_Project_Name_Bid__c是不是空
            if (op.Bidding_Project_Name_Bid__c != null && String.isNotBlank(op.Bidding_Project_Name_Bid__c)) {
                // 不是空的情况下 
                // 新建link
                Tender_Opportunity_Link__c link = new Tender_Opportunity_Link__c();
                link.Tender_information__c = op.Bidding_Project_Name_Bid__c;
                link.Opportunity__c = op.id;
                link.Tender_Opportunity_Uniq__c = String.valueOf(op.Bidding_Project_Name_Bid__c) + String.valueOf(op.id); 
                new_links.add(link);
            }
        }
        if (new_links.size() > 0) {
            insert new_links;
        }
    }
    // 招标-询价关联 20210817 end
     // 阿斯赛多签收单 精琢技术 fy 2021-09-06 start
    //  public static void changeSignedByAsicedo(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
    //     List<Statu_Achievements_DN__c> Statu_Achievements_DN_c = new List<Statu_Achievements_DN__c>();
    //     List<eSignForm__c> eSignForm_c = new List<eSignForm__c>();
    //     for(Opportunity op : newList){
    //         if(op.Is_Corrosion__c==false&&oldMap.get(op.Id).Is_Corrosion__c==true){
    //             List<Statu_Achievements_DN__c> StatuAchievementsDNc =[select Id,Name,Is_Corrosion__c from Statu_Achievements_DN__c where Opportunity__c =:op.Id];
    //             for(Statu_Achievements_DN__c sadc:StatuAchievementsDNc){
    //                 if(sadc.Is_Corrosion__c==true){
    //                     sadc.Is_Corrosion__c=false;
    //                     Statu_Achievements_DN_c.add(sadc);
    //                     system.debug('Statu_Achievements_DN_c ==='+Statu_Achievements_DN_c);
    //                 }
    //                 List<eSignForm__c> eSignFormc =[select Id,Name,Hazardous_Chemicals__c from eSignForm__c where Statu_Achievements_DN__c =:sadc.Id];
    //                 for(eSignForm__c efc:eSignFormc){
    //                     if(efc.Hazardous_Chemicals__c==true){
    //                         efc.Hazardous_Chemicals__c=false;
    //                         eSignForm_c.add(efc);
    //                         system.debug('eSignForm_c ==='+eSignForm_c);
    //                     }
    //                 }
    //             }
    //         }
    //     }
    //     if(Statu_Achievements_DN_c.size()>0){
    //         update Statu_Achievements_DN_c;
    //     }
    //     if(eSignForm_c.size()>0){
    //         update eSignForm_c;
    //     }
    // }
    // 阿斯赛多签收单 精琢技术 fy 2021-09-06 end

    // SWAG-C7P4XB start
    // 更新前操作 判断WIN为TRUE的时候 清除掉"取消WIN原因"
    public static void removeCancelWinReason(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap) {
        for (Opportunity opp : newList) {
            Opportunity old_opp = oldMap.get(opp.Id);
            if (opp.SAP_Send_OK__c == true && old_opp != null && old_opp.SAP_Send_OK__c == false && opp.Reason_Cancel_WIN__c != null) {
                opp.Reason_Cancel_WIN__c = null;
            }
        }
    } 
    // SWAG-C7P4XB end

    //LastBuy 预留产品 lt 20220315 start
    //询价失单或取消时，预留产品的"是否有效"设置为否
    public static void ReservedProFlg(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
        List<Id> oppList = new List<Id>();
        List<LastbuyProduct__c> lbpflgList = new List<LastbuyProduct__c>();

        for (Opportunity lbOpp : newList){
            Opportunity OldLbOpp = oldMap.get(lbOpp.Id);
            if(OldLbOpp.StageName != lbOpp.StageName){
                if(lbOpp.StageName == '敗戦' || lbOpp.StageName == '削除'){
                    oppList.add(lbOpp.Id);
                }
            }
        }

        if(oppList.size() > 0){
            List<LastbuyProduct__c> lbpList = [select id, effectiveFLG__c,InquiryCode__c from LastbuyProduct__c where InquiryCode__c in :oppList];
            if(lbpList.size() > 0){
                for(LastbuyProduct__c lbp : lbpList){
                    if(lbp.effectiveFLG__c == true){ 
                        lbp.effectiveFLG__c = false;
                        lbpflgList.add(lbp);
                    }
                }
            }
        }

        if(lbpflgList.size() > 0){
            update lbpflgList;
        }
    }
    //LastBuy 预留产品 lt 20220315 end

    //DB202311665664  【重要紧急课题】询价中的“项目：招标日”和漏单数修改 start
    public static void lostTenUtil(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
        Set<Id> oppIdSet = new Set<Id>();
        System.debug('20231222-lt------');
        for (Opportunity lbOpp : newList){
            Opportunity OldLbOpp = oldMap.get(lbOpp.Id);
            System.debug('20231222-lt------旧'+OldLbOpp.TenderBeginDate_New__c);
            System.debug('20231222-lt------新'+lbOpp.TenderBeginDate_New__c);
            if(OldLbOpp.TenderBeginDate_New__c != lbOpp.TenderBeginDate_New__c){
                oppIdSet.add(lbOpp.Id);
            }
        }

        if(oppIdSet.Size() > 0){
            TenderUtil.UpdLeakageNum(oppIdSet);
        }
    }
    //DB202311665664  【重要紧急课题】询价中的“项目：招标日”和漏单数修改 end

    //lt 20240118 DB202401275115 紧急：招标项目终止状态的逻辑调整 start
    public static void CountOppNum(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
        List<String> oppList = new List<String>();
        List<String> tenList = new List<String>();
        List<String> ten1List = new List<String>();
        List<Tender_information__c> updtenList = new List<Tender_information__c>();

        for (Opportunity Opp : newList){
            Opportunity OldOpp = oldMap.get(Opp.Id);
            System.debug('lt20240126---Opp.StageName:'+Opp.StageName);
            if(Opp.StageName == '削除' && Opp.StageName != OldOpp.StageName){
                oppList.add(Opp.Id);
                if(Opp.Bidding_Project_Name_Bid__c != null){
                    tenList.add(Opp.Bidding_Project_Name_Bid__c);
                }
            }
        }
        System.debug('lt20240126---oppList:'+oppList);

        if(oppList.Size() > 0 ){
            List<AggregateResult> LinksList = [Select count(id) cnt,Tender_information__c
                                               From Tender_Opportunity_Link__c 
                                               Where Tender_information__c in :tenList 
                                               And Opportunity__r.StageName != '削除'
                                               Group By Tender_information__c];
            Map<String, Integer> sum_map = new Map<String, Integer>();
            System.debug('lt20240126---LinksList:'+LinksList);
            if (LinksList != null && LinksList.size() > 0) {
                for (AggregateResult result : LinksList) {
                    sum_map.put(String.valueOf(result.get('Tender_information__c')), Integer.valueOf(result.get('cnt')));
                }
                System.debug('lt20240126---sum_map:'+sum_map);
            }
            else{
                if(tenList.Size() > 0){
                    List<Tender_information__c> tensList = [Select id,OpportunityNum__c
                                                            From Tender_information__c 
                                                            Where id in :tenList ];

                    if(tensList.Size() > 0){
                        for(Tender_information__c tens : tensList){
                            Tender_information__c ten = new Tender_information__c();
                            ten.Id = tens.Id;
                            ten.OpportunityNum__c = 0;
                            System.debug('lt20240126---ten.OpportunityNum__c---0:'+ten.OpportunityNum__c);
                            updtenList.add(ten);
                        }
                    }
                }
            }
        
            for(String tenId :sum_map.keySet()) {
                Tender_information__c ten = new Tender_information__c();
                ten.Id = tenId;
                ten.OpportunityNum__c = sum_map.get(tenId) != null ? sum_map.get(tenId) : 0;
                System.debug('lt20240126---ten.OpportunityNum__c---1:'+ten.OpportunityNum__c);
                updtenList.add(ten);
            }

            System.debug('lt20240126---updtenList:'+updtenList);
        }

        if(updtenList.Size() > 0){
            update updtenList;
        }
        
    }
    //lt 20240118 DB202401275115 紧急：招标项目终止状态的逻辑调整 end

//SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy start 
// public static void UpdateBidNumber(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
//     List<Id> OpportunityIdList = new List<Id>();
//     Boolean flag = true;
//     for (Opportunity opp : newList) {
//         OpportunityIdList.add(opp.Id);
//         Opportunity oldopp = oldMap == null? null : oldMap.get(opp.Id); 
//         if(oldopp==null){
//             if(opp.NumberOfBids__c!=null||opp.BidWinningNumber__c!=null){
//                 flag = true;
//             }
//         }else{
//             if(opp.NumberOfBids__c!=oldopp.NumberOfBids__c||opp.NumberOfBids__c!=oldopp.NumberOfBids__c){
//                 flag = true;
//             }
//         }
//     }
//     system.debug('newList+++'+newList);
//     system.debug('oldList+++'+oldList);
//     if(flag){
//         List<Tender_Opportunity_Link__c> TenderOpportunityLinkList = [select Tender_information__c from Tender_Opportunity_Link__c where Opportunity__c in:OpportunityIdList];
//         Set<Id> enderOpportunityId = new Set<Id>();
//         if(TenderOpportunityLinkList.size()>0){
//             for (Tender_Opportunity_Link__c TenderOpportunity : TenderOpportunityLinkList) {
//                 enderOpportunityId.add(TenderOpportunity.Tender_information__c);
//             }
//         }
//         system.debug('TenderOpportunityLinkList+++'+TenderOpportunityLinkList);
//         List<Tender_Opportunity_Link__c> TenderOpportunityLinkList2 = [select Tender_information__c,Opportunity__r.NumberOfBids__c,Opportunity__r.BidWinningNumber__c from Tender_Opportunity_Link__c where Tender_information__c in:enderOpportunityId];
//         Map<String,Tender_information__c> TenderinformationMap = new Map<String,Tender_information__c>();
//         system.debug('TenderOpportunityLinkList2+++'+TenderOpportunityLinkList2);
//         if(TenderOpportunityLinkList2.size()>0){
//             for(Tender_Opportunity_Link__c TenderOpportunity2 :TenderOpportunityLinkList2){
//                     if(TenderinformationMap.containsKey(TenderOpportunity2.Tender_information__c)){
//                         Tender_information__c Tender_informationvalue = new Tender_information__c();
//                         Tender_informationvalue = TenderinformationMap.get(TenderOpportunity2.Tender_information__c);
//                         Tender_informationvalue.NumberOfBids__c=Tender_informationvalue.NumberOfBids__c+TenderOpportunity2.Opportunity__r.NumberOfBids__c;
//                         Tender_informationvalue.BidWinningNumber__c=Tender_informationvalue.BidWinningNumber__c+TenderOpportunity2.Opportunity__r.BidWinningNumber__c;
//                         TenderinformationMap.put(TenderOpportunity2.Tender_information__c, Tender_informationvalue);
//                     }else{
//                         Tender_information__c Tender_informationvalue = new Tender_information__c();
//                         Tender_informationvalue.Id=TenderOpportunity2.Tender_information__c;
//                         Tender_informationvalue.NumberOfBids__c=TenderOpportunity2.Opportunity__r.NumberOfBids__c;
//                         Tender_informationvalue.BidWinningNumber__c=TenderOpportunity2.Opportunity__r.BidWinningNumber__c;
//                         TenderinformationMap.put(TenderOpportunity2.Tender_information__c, Tender_informationvalue);
//                     }
//             }
//         }
//         List<Tender_information__c> Tender_informationList = new List<Tender_information__c>();
//         for (Tender_information__c value : TenderinformationMap.values()) {
//             Tender_informationList.add(value);
//         }
//         system.debug('Tender_informationList+++'+Tender_informationList);
//         update Tender_informationList;
//     }
// }
//SWAG-CHL67J 【委托】【FY23询价改善】-询价页面/招标项目增加统计字段 fy end
    //add 询价跟进任务开发 - 3.创建失单任务 sx 20220617 start
    //询价中标结果确认竞争对手中标时实时创建失单任务
    public static void createTaskByOppConfirmationofAward(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){

        if (!isFirst) {
            return;
        }

        Set<Id> oppoIds = new Set<Id>();
        Set<Id> oppIdList = new Set<Id>();//DB202306331086 you 失单任务增加招标项目链接
        Map<Id,String> mapoppid = new Map<Id,String>();
        list<task__c> taskUpdateList = new list<task__c>();
        for(Opportunity op : newList){
            Opportunity oldopp =  oldMap.get(op.Id);
            //询价中标结果确认竞争对手中标时实时创建失单任务 且 询价状态1等于询价
            if (oldopp.ConfirmationofAward__c != '竞争对手中标' && op.ConfirmationofAward__c == '竞争对手中标' && op.StageName__c == '询价' && !op.DirectLossFLG__c){
                oppoIds.add(op.Id);
            }
            //20220929 you  SWAG-CJP7TL 手动更改询价所有人，同步修改任务所有人
            if((String.isNotBlank(op.OwnerId) && op.OwnerId !=oldopp.OwnerId) ||Test.isRunningTest()){
                 mapoppid.put(op.id,op.OwnerId);
            }
            oppIdList.add(op.id);//DB202306331086 you 失单任务增加招标项目链接
        }
        if(mapoppid.size() > 0){
            List<Task__c> taskList = [
                    SELECT Id,OpportunityId__c,taskStatus__c 
                    FROM task__c 
                    WHERE OpportunityId__c in :mapoppid.keySet()
                    AND (RecordType.Name = '中标结果确认' OR RecordType.Name = '失单报告任务')
                    AND taskStatus__c = '02 接受'];
            system.debug(mapoppid.keySet()+'test1-----'+taskList);
            for(Task__c t: taskList){
                if(mapoppid.containsKey(t.OpportunityId__c)){
                   t.Ownerid = mapoppid.get(t.OpportunityId__c);
                   t.assignee__c = mapoppid.get(t.OpportunityId__c);
                   taskUpdateList.add(t);
                }
                           
            }
             if (taskUpdateList != null && taskUpdateList.size() > 0) {
                update taskUpdateList;
            }
        }    

        if (!oppoIds.isEmpty()) {
            // 20221206  DB202211594688 start
            // // 有效失单状态一览
            // List<String> validStatus = new List<String>{'申请中', '提交', '批准'};
            // // 询价失单/取消报告查询 
            // List<Lost_cancel_report__c> lostCancelReportList = [SELECT Id, Opportunity__c from Lost_cancel_report__c WHERE Opportunity__c in :oppoIds and Report_Status__c in: validStatus];
           
            // List<Lost_cancel_report__c> lostCancelReportList1 = [SELECT Id, Opportunity__c,DeveloperName__c from Lost_cancel_report__c WHERE Opportunity__c in :oppoIds and Report_Status__c ='草案'];
            
            // //<询价Id, 失单报告>
            // Map<String, Lost_cancel_report__c> lostCancelReportMap = new Map<String, Lost_cancel_report__c>();
            // for(Lost_cancel_report__c lcr : lostCancelReportList){
            //     if (!lostCancelReportMap.isEmpty() && lostCancelReportMap.containsKey(lcr.Opportunity__c)) {
            //         // no action
            //     } else {
            //         lostCancelReportMap.put(lcr.Opportunity__c, lcr);
            //     }
            // }
             
            //有效失单状态一览
            List<String> validStatus = new List<String>{'申请中', '提交', '批准'};
            List<String> allStatus = new List<String>{'申请中', '提交', '批准','草案'};
            // 询价失单/取消报告查询  
            List<Lost_cancel_report__c> lostCancelReportList = [SELECT Id, Opportunity__c,Report_Status__c,DeveloperName__c  from Lost_cancel_report__c WHERE Opportunity__c in :oppoIds and Report_Status__c in: allStatus];
           
            //<询价Id, 失单报告>
            Map<String, Lost_cancel_report__c> lostCancelReportMap = new Map<String, Lost_cancel_report__c>();
            Map<String, Lost_cancel_report__c> lostCancelReportMap1 = new Map<String, Lost_cancel_report__c>();
            for(Lost_cancel_report__c lcr : lostCancelReportList){
                if(validStatus.contains(lcr.Report_Status__c)){
                    if (!lostCancelReportMap.isEmpty() && lostCancelReportMap.containsKey(lcr.Opportunity__c)) {
                        // no action
                    } else {
                        lostCancelReportMap.put(lcr.Opportunity__c, lcr);
                    }
                }else{
                    // 草案
                    if (!lostCancelReportMap1.isEmpty() && lostCancelReportMap1.containsKey(lcr.Opportunity__c)) {
                    // no action
                    } else {
                        lostCancelReportMap1.put(lcr.Opportunity__c, lcr);
                    }
                } 
            }                
            // 20221206  DB202211594688 start
            List<Task__c> insTaskList = new List<Task__c>();
            
            // 定义需要更新的询价任务
            List<Opportunity> updateOpportunity = new List<Opportunity>();
            
            // 记录类型：失单报告任务
            List<RecordType> recordTypes = [select Id from RecordType where IsActive = true and SobjectType = 'task__c' and DeveloperName = 'LoseListTask'];
            Id loseListTask_TaskId = recordTypes.get(0).Id;
            //String taskName = '';
            //DB202306331086 you 失单任务增加招标项目链接
            List<task__c> taskList = [select id,taskStatus__c,OpportunityId__c,Tender_information_Task__c from task__c where RecordType.Name ='中标结果确认' and OpportunityId__c in :oppIdList];
            Map<String, String> taskMap = new Map<String, String>();
            if(null!= taskList && taskList.size()>0){
              for(task__c ta : taskList){
                 taskMap.put(ta.OpportunityId__c,ta.Tender_information_Task__c);
              }
            }
            for(Opportunity opp : newList) {
                //没有已提交的失单报告
                if(!lostCancelReportMap.containsKey(opp.Id) && oppoIds.contains(opp.Id)) {

                    //创建失单任务提醒
                    Task__c tempTask = new Task__c();
                    tempTask.RecordTypeId = loseListTask_TaskId;
                    tempTask.taskDifferent__c = '被动任务';
                    tempTask.taskStatus__c = '02 接受';       //任务状态2
                    tempTask.assignee__c = opp.OwnerId;    //被分配者
                    tempTask.account__c = opp.AccountId;
                    tempTask.Name = '失单结果确认：' + opp.Opportunity_No__c;
                    tempTask.OwnerId = opp.OwnerId;   //所有人
                    tempTask.OpportunityId__c = opp.Id;
                    tempTask.ConfirmDate__c = Date.today();
                    if(null!= taskMap && taskMap.containsKey(opp.Id)){
                      tempTask.Tender_information_Task__c =taskMap.get(opp.Id); 
                    }else{
                      tempTask.Tender_information_Task__c = opp.Bidding_Project_Name_Bid__c;
                    }
                    
                    insTaskList.add(tempTask);
                    
                    //更新询价  Task_createTime__c  
                    Opportunity uopp  = new Opportunity();
                    uopp.Id = opp.Id;
                    uopp.LostTask_createTime__c  = Date.today();
                    //20221205 you DB202211594688  部分失单派发任务，但是中标结果不赋值
                    
                    if(null!=lostCancelReportMap1.get(opp.Id) && lostCancelReportMap1.get(opp.Id).DeveloperName__c =='PCL_PartLost_report'){
                   
                        uopp.ConfirmationofAward__c = '';
                        uopp.ConfirmationofAward_createTime__c = null;
                        uopp.Is_ConfirmationofAward__c =null;
                    }else{
                        if(oldMap.get(opp.Id).ConfirmationofAward__c != '竞争对手中标' && opp.ConfirmationofAward__c == '竞争对手中标'){
                          uopp.Closing_Bid_Date__c = null;
                        }
                    }
                    updateOpportunity.add(uopp);
                }
            }

            if (!insTaskList.isEmpty()) {
                insert insTaskList;
            }
            if (!updateOpportunity.isEmpty()) {
                update updateOpportunity;
            }
        }
        isFirst = false;
    }
    //add 询价跟进任务开发 - 3.创建失单任务 sx 20220617 end
    //DB202306372336 you start
    public static void UpdateStrategic_department_Opp(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
        Set<Id> oppoIds = new Set<Id>();
        for(Opportunity op : newList){
            Opportunity oldopp =  oldMap.get(op.Id);
            if (oldopp.Department_Class__c != op.Department_Class__c ||Test.isRunningTest()){// || System.label.Strategic_department_Opp.equals('true')
                oppoIds.add(op.Id);
            }
        }
        List<Tender_Opportunity_Link__c> tenderList1 = new List<Tender_Opportunity_Link__c>();
        if (!oppoIds.isEmpty()){
            tenderList1 = [SELECT id, Opportunity__r.Department_Class__r.Department_Class_Label__c,Tender_information__c
                                                      FROM Tender_Opportunity_Link__c 
                                                      WHERE Opportunity__c in :oppoIds];
        }
        List<String> tenids = new List<String>();
        List<Tender_Opportunity_Link__c> tenderList = new List<Tender_Opportunity_Link__c>();
        List<Tender_information__c> UpdateTenders1 = new List<Tender_information__c>();
        if(null!=tenderList1 && tenderList1.size()>0){
          for (Tender_Opportunity_Link__c tender : tenderList1){
              if(!tenids.contains(tender.Tender_information__c)){
                tenids.add(tender.Tender_information__c);
              }
          }
          
          if(tenids.size() > 0){
             tenderList = [SELECT id, Opportunity__r.Department_Class__r.Department_Class_Label__c,Tender_information__c
                                                      FROM Tender_Opportunity_Link__c 
                                                      WHERE Tender_information__c in :tenids order by Tender_information__c];
          } 
          if(tenderList.size() > 0){
            Map<String, Set<String>> updateTenMap = new Map<String, Set<String>>();//招标项目id，战略科室分类
            //String partment_Opp='';

            for (Tender_Opportunity_Link__c tender : tenderList){
                if(String.isNotBlank(tender.Opportunity__r.Department_Class__r.Department_Class_Label__c)){
                    //String ten_Opp =tender.Opportunity__r.Department_Class__r.name.split(' ')[1];
                    //if(tender.Opportunity__r.Department_Class__r.name.split(' ').size() ==3 ){
                    //   ten_Opp =tender.Opportunity__r.Department_Class__r.name.split(' ')[2];
                    //}

                    String ten_Opp =tender.Opportunity__r.Department_Class__r.Department_Class_Label__c;
                    Set<String> temp = new Set<String>();
                    if(ten_Opp.indexOf('其他') == -1){
                        if(updateTenMap.containsKey(tender.Tender_information__c)){
                            temp= updateTenMap.get(tender.Tender_information__c);
                            temp.add(ten_Opp);
                        } else{
                            temp.add(ten_Opp);
                        }
                    }else{//其他归普外
                        if(updateTenMap.containsKey(tender.Tender_information__c)){
                            temp= updateTenMap.get(tender.Tender_information__c);
                            temp.add('普外科');
                        } else{
                            temp.add('普外科');
                        }
                    }
                    updateTenMap.put(tender.Tender_information__c,temp);  
                }
                
            } 
            system.debug('==updateTenMap=='+updateTenMap);    
            if(null!=updateTenMap && updateTenMap.size()>0){
                 for(String ksy :updateTenMap.keySet()){
                    //String partment_Opp=updateTenMap.get(ksy).toString(); 
                    String partment_Opp=String.join(new List<String>(updateTenMap.get(ksy)), ';'); 
                    system.debug('=====partment_Opp='+partment_Opp); 
                    partment_Opp=partment_Opp.replaceAll(',', ';');

                    Tender_information__c tin1 =new Tender_information__c();
                    tin1.id=ksy;
                    tin1.Strategic_department_Opp__c = partment_Opp;
                    UpdateTenders1.add(tin1);
                 }
                }
           }
          }  

        if(UpdateTenders1.size() > 0){
            System.debug('202309191938========');
            StaticParameter.EscapeTenderInformationUpdate =false;//20230918 lt DB202306372336 add
           update UpdateTenders1;
           StaticParameter.EscapeTenderInformationUpdate =true;//20230918 lt DB202306372336 add
        }

    }
    //DB202306372336 you end
    //询价跟进任务开发 
    public static void opportunityTasks(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
        Set<Id> oppoIds = new Set<Id>();
    
        for(Opportunity op : newList){
            Opportunity oldopp =  oldMap.get(op.Id);
            
            //询价中标结果确认竞争对手中标时实时创建失单任务 且 询价状态1等于询价
            if (oldopp.ConfirmationofAward__c != 'OLY中标' && op.ConfirmationofAward__c == 'OLY中标' && op.StageName__c == '询价'){
                oppoIds.add(op.Id);
                //确认中标结果时间 创建任务时间  20220629 sx
                op.ConfirmationofAward_createTime__c = Date.today();
                if(op.Task_createTime__c!=null){
                    
                    //是否按时确认：3个工作日内按时1，不按时0
                    String inttemp = CalendarUtil.getWorkDayNum(String.valueOf(op.Task_createTime__c), String.valueOf(op.ConfirmationofAward_createTime__c));
                    op.Is_ConfirmationofAward__c = Integer.valueOf(inttemp) > 3 ? 0 : 1;   
                }
            }

            //20220628会议新需求  对手中标 7.中标日清空
            if(oldopp.ConfirmationofAward__c != '竞争对手中标' && op.ConfirmationofAward__c == '竞争对手中标'){
                //op.Closing_Bid_Date__c = null; // 20221206 you
                op.ConfirmationofAward_createTime__c = Date.today(); 
                if(op.Task_createTime__c!=null){
                   
                    //是否按时确认：3个工作日内按时1，不按时0
                    String inttemp = CalendarUtil.getWorkDayNum(String.valueOf(op.Task_createTime__c), String.valueOf(op.ConfirmationofAward_createTime__c));
                    op.Is_ConfirmationofAward__c = Integer.valueOf(inttemp) > 3 ? 0 : 1;    
                }              
            }
        }

        if(!oppoIds.isEmpty()){

            // 2022-12-02 ssm DB202211552746 增加流标废标时清空结果记录日的逻辑，需要判断不是流标废标的结果数据才更新中标日
            list<Tender_Opportunity_Link__c> toppLinkList = [Select Id, Opportunity__c, Tender_information__c,Tender_information__r.ResultDate__c,Tender_information__r.InfoType__c 
                                                            FROM Tender_Opportunity_Link__c 
                                                            WHERE Opportunity__c in :oppoIds 
                                                            and Tender_information__r.InfoType__c = '3：结果' 
                                                            and Tender_information__r.subInfoType__c != '3-1：废标公告' 
                                                            and Tender_information__r.subInfoType__c != '3-2：流标公告'];
            Map<String, Tender_Opportunity_Link__c> toopLinkMap = new Map<String, Tender_Opportunity_Link__c>();
            
            for(Tender_Opportunity_Link__c tol : toppLinkList){
                Opportunity oppoTemp = newMap.get(tol.Opportunity__c);
                //询价关联到招标项目才进行操作
                if(oppoTemp.Bidding_Project_Name_Bid__c == tol.Tender_information__c){
                    toopLinkMap.put(tol.Opportunity__c, tol);
                }
                
            }
            
            for (String key : toopLinkMap.keySet()) {
                Opportunity oppoTemp = newMap.get(key);
                //20220628会议新需求  OLY中标 7.中标日（结果记录日）= 招标项目.结果记录日
                oppoTemp.Closing_Bid_Date__c = toopLinkMap.get(key).Tender_information__r.ResultDate__c;
                System.debug('============'+toopLinkMap.get(key).Tender_information__r.ResultDate__c);
                
                //是否按时确认：3个工作日内按时1，不按时0
                //String inttemp = CalendarUtil.getWorkDayNum(String.valueOf(oppoTemp.Task_createTime__c), String.valueOf(oppoTemp.ConfirmationofAward_createTime__c));
                //oppoTemp.Is_ConfirmationofAward__c = Integer.valueOf(inttemp) > 3 ? 0 : 1;    
            }

        }  
       

    }
    //办事处ET/ENG担当共享 you 20240222
    public static void UpdateoppShare(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
        Set<String> oppSapPros = new Set<String>();
        List<OCM_Management_Province__c> mpList = new List<OCM_Management_Province__c>();
        Map<String, OCM_Management_Province__c> mpMap = new Map<String, OCM_Management_Province__c>();
        for (Opportunity newOpp : newList) {
            Opportunity oldOpp = oldMap.get(newOpp.Id);
            system.debug('=='+newOpp.StageName);
            if (newOpp.StageName != oldOpp.StageName && newOpp.StageName == '注残' || Test.isRunningTest()) {
                oppSapPros.add(newOpp.SAP_Province__c); 
            }
        }
        if(null !=oppSapPros && oppSapPros.size()>0){
            mpList = [select id,Province__c,ET_DataWindow__c,ET_BusinessWindow__c,ET_Assistant1__c,ET_Assistant2__c,ENG_DataWindow__c,ENG_BusinessWindow__c,ENG_Assistant1__c,ENG_Assistant2__c from OCM_Management_Province__c where Province__c in: oppSapPros];
            for (OCM_Management_Province__c mp: mpList){
                mpMap.put(mp.Province__c, mp);
            }
            if(null!=mpMap){
                List<OpportunityShare> oppsharlist =new List<OpportunityShare>();
                for (Opportunity nObj : newList) {
                    if (mpMap.containsKey(nObj.SAP_Province__c)) {
                       if(null!=nObj.Opp_order_Type__c && ''!= nObj.Opp_order_Type__c && null!=mpMap.get(nObj.SAP_Province__c)){
                          if(nObj.Opp_order_Type__c=='ET'){
                            if(null!=mpMap.get(nObj.SAP_Province__c).ET_DataWindow__c && !''.equals(mpMap.get(nObj.SAP_Province__c).ET_DataWindow__c) && nObj.Ownerid !=mpMap.get(nObj.SAP_Province__c).ET_DataWindow__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = nObj.Id,
                                UserOrGroupId = mpMap.get(nObj.SAP_Province__c).ET_DataWindow__c,
                                OpportunityAccessLevel = 'read');
                                oppsharlist.add(oppshare);
                            }
                            if(null!=mpMap.get(nObj.SAP_Province__c).ET_BusinessWindow__c && !''.equals(mpMap.get(nObj.SAP_Province__c).ET_BusinessWindow__c) && nObj.Ownerid !=mpMap.get(nObj.SAP_Province__c).ET_BusinessWindow__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = nObj.Id,
                                UserOrGroupId = mpMap.get(nObj.SAP_Province__c).ET_BusinessWindow__c,
                                OpportunityAccessLevel = 'read');
                                oppsharlist.add(oppshare);
                            }
                            if(null!=mpMap.get(nObj.SAP_Province__c).ET_Assistant1__c && !''.equals(mpMap.get(nObj.SAP_Province__c).ET_Assistant1__c) && nObj.Ownerid !=mpMap.get(nObj.SAP_Province__c).ET_Assistant1__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = nObj.Id,
                                UserOrGroupId = mpMap.get(nObj.SAP_Province__c).ET_Assistant1__c,
                                OpportunityAccessLevel = 'read');
                                oppsharlist.add(oppshare);
                            }
                            if(null!=mpMap.get(nObj.SAP_Province__c).ET_Assistant2__c && !''.equals(mpMap.get(nObj.SAP_Province__c).ET_Assistant2__c) && nObj.Ownerid !=mpMap.get(nObj.SAP_Province__c).ET_Assistant2__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = nObj.Id,
                                UserOrGroupId = mpMap.get(nObj.SAP_Province__c).ET_Assistant2__c,
                                OpportunityAccessLevel = 'read');
                                oppsharlist.add(oppshare);
                            }
                            
                          }else{//SP,ENG 
                            if(null!=mpMap.get(nObj.SAP_Province__c).ENG_DataWindow__c && !''.equals(mpMap.get(nObj.SAP_Province__c).ENG_DataWindow__c) && nObj.Ownerid !=mpMap.get(nObj.SAP_Province__c).ENG_DataWindow__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = nObj.Id,
                                UserOrGroupId = mpMap.get(nObj.SAP_Province__c).ENG_DataWindow__c,
                                OpportunityAccessLevel = 'read');
                                oppsharlist.add(oppshare);
                            }
                            if(null!=mpMap.get(nObj.SAP_Province__c).ENG_BusinessWindow__c && !''.equals(mpMap.get(nObj.SAP_Province__c).ENG_BusinessWindow__c) && nObj.Ownerid !=mpMap.get(nObj.SAP_Province__c).ENG_BusinessWindow__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = nObj.Id,
                                UserOrGroupId = mpMap.get(nObj.SAP_Province__c).ENG_BusinessWindow__c,
                                OpportunityAccessLevel = 'read');
                                oppsharlist.add(oppshare);
                            }
                            if(null!=mpMap.get(nObj.SAP_Province__c).ENG_Assistant1__c && !''.equals(mpMap.get(nObj.SAP_Province__c).ENG_Assistant1__c) && nObj.Ownerid !=mpMap.get(nObj.SAP_Province__c).ENG_Assistant1__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = nObj.Id,
                                UserOrGroupId = mpMap.get(nObj.SAP_Province__c).ENG_Assistant1__c,
                                OpportunityAccessLevel = 'read');
                                oppsharlist.add(oppshare);
                            }
                            if(null!=mpMap.get(nObj.SAP_Province__c).ENG_Assistant2__c && !''.equals(mpMap.get(nObj.SAP_Province__c).ENG_Assistant2__c) && nObj.Ownerid !=mpMap.get(nObj.SAP_Province__c).ENG_Assistant2__c){
                                OpportunityShare oppshare = new OpportunityShare(
                                OpportunityId = nObj.Id,
                                UserOrGroupId = mpMap.get(nObj.SAP_Province__c).ENG_Assistant2__c,
                                OpportunityAccessLevel = 'read');
                                oppsharlist.add(oppshare);
                            }
                          }
                       }
                     
                   }
                }    
                if(null!=oppsharlist){
                    insert oppsharlist;
                }
            }
        }  
    }   
    //fy DB202312538864 2024.02.20 start
    // public static Boolean isExecuted = false;
    // public static void lastbuycheck(List<Opportunity> newList, Map<Id, Opportunity> newMap, List<Opportunity> oldList, Map<Id, Opportunity> oldMap){
    //     if (!isExecuted) {
    //         System.debug('isAfterisUpdate');
    //         //产品预留check
    //         List<Opportunity> oppList = new List<Opportunity>();
    //         for (Opportunity local : newList) {
    //             Opportunity old = oldMap.get(local.Id);
    //             if(local.StageName != old.StageName && local.StageName == '削除'&&local.Estimation_Decision__c){
    //                 oppList.add(local);
    //             }
    //             System.debug('local.StageName'+local.StageName);
    //             System.debug('old.StageName'+old.StageName);
    //         }
    //         if(oppList.size()>0){
    //             List<PreProduct_Storage_List__c> PreProductStorageList = new List<PreProduct_Storage_List__c>();
    //             List<PreProduct_Storage__c> UpdatePreProductStorageList =  new List<PreProduct_Storage__c>();
    //             Set<Id> lastProductFLGListId = new Set<Id>();
    //             Set<Id> NewcodeListId = new Set<Id>();
    //             List<OpportunityLineItem> act = new List<OpportunityLineItem>();
    //             List<OpportunityLineItem> act2 = new List<OpportunityLineItem>();
    //             List<Id> localId = new List<Id>();
    //             Map<String,Opportunity> oppmap = new Map<String,Opportunity>();
    //             List<String> SalepartmentSAPList = new List<String>();
    //             List<String> OCMprovincecusList = new List<String>();
    //             for (Opportunity local : oppList) {
    //                 localId.add(local.Id);
    //                 oppmap.put(local.Id,local);
    //                 SalepartmentSAPList.add(local.Salesdepartment_SAP__c);
    //                 OCMprovincecusList.add(local.OCM_man_province_cus__c);
    //             }
    //             act =  [select Id,Quantity,PricebookEntry.Product2Id,PricebookEntry.Product2.LastbuyProductFLG__c,PricebookEntry.Product2.whetherOldCode_PrePro__c,OpportunityId from OpportunityLineItem where OpportunityId in:localId];
    //             act2=act.deepClone();
    //             Map<String,Map<String,OpportunityLineItem>> map2 = new Map<String,Map<String,OpportunityLineItem>>();
    //             //*****合并产品重复的报价行项目****
    //             for(OpportunityLineItem pspsc :act2){
    //                 if(pspsc.PricebookEntry.Product2Id!=null){
    //                     if(map2.containsKey(pspsc.OpportunityId)){
    //                         Map<String,OpportunityLineItem> quoteLine = map2.get(pspsc.OpportunityId);
    //                         if(quoteLine.containsKey(pspsc.PricebookEntry.Product2Id)){
    //                         OpportunityLineItem quoteLine1 = quoteLine.get(pspsc.PricebookEntry.Product2Id);
    //                         quoteLine1.Quantity =quoteLine1.Quantity+pspsc.Quantity;
    //                         quoteLine.put(pspsc.PricebookEntry.Product2Id,quoteLine1);
    //                         }else{
    //                         quoteLine.put(pspsc.PricebookEntry.Product2Id,pspsc);
    //                         }
    //                         map2.put(pspsc.OpportunityId,quoteLine);
    //                     }else{
    //                         Map<String,OpportunityLineItem> quoteLine = new Map<String,OpportunityLineItem>();
    //                         quoteLine.put(pspsc.PricebookEntry.Product2Id,pspsc);
    //                         map2.put(pspsc.OpportunityId,quoteLine);
    //                     }
    //                 }
    //             }
    //             Map<String,Set<Opportunity>> proCorderIdMap = new Map<String,Set<Opportunity>>();
    //             for (Map<String,OpportunityLineItem> value2 : map2.values()) {
    //                 for (OpportunityLineItem value : value2.values()) {
    //                     if(value.PricebookEntry.Product2.whetherOldCode_PrePro__c){
    //                         NewcodeListId.add(value.PricebookEntry.Product2Id);
    //                         if(proCorderIdMap.containsKey(value.PricebookEntry.Product2Id)){
    //                             Set<Opportunity> clastList = proCorderIdMap.get(value.PricebookEntry.Product2Id);
    //                             Opportunity clast = oppmap.get(value.OpportunityId);
    //                             clastList.add(clast);
    //                             proCorderIdMap.put(value.PricebookEntry.Product2Id,clastList);
    //                         }else{
    //                             Set<Opportunity> cnewList = new Set<Opportunity>();
    //                             Opportunity cnew = oppmap.get(value.OpportunityId);
    //                             cnewList.add(cnew);
    //                             proCorderIdMap.put(value.PricebookEntry.Product2Id,cnewList);
    //                         }
    //                     }
    //                     if(value.PricebookEntry.Product2.LastbuyProductFLG__c){
    //                         lastProductFLGListId.add(value.PricebookEntry.Product2Id);
    //                         if(proCorderIdMap.containsKey(value.PricebookEntry.Product2Id)){
    //                             Set<Opportunity> clastList = proCorderIdMap.get(value.PricebookEntry.Product2Id);
    //                             Opportunity clast = oppmap.get(value.OpportunityId);
    //                             clastList.add(clast);
    //                             proCorderIdMap.put(value.PricebookEntry.Product2Id,clastList);
    //                         }else{
    //                             Set<Opportunity> cnewList = new Set<Opportunity>();
    //                             Opportunity cnew = oppmap.get(value.OpportunityId);
    //                             cnewList.add(cnew);
    //                             proCorderIdMap.put(value.PricebookEntry.Product2Id,cnewList);
    //                         }
    //                     }
    //                 }
    //             }
    //             List<Product2> prd2List = new List<Product2>();
    //             Map<String,String> prd2Map = new Map<String,String>();
    //             Map<String,Map<String,PreProduct_Storage__c>> prd2ppsMap = new Map<String,Map<String,PreProduct_Storage__c>>();
    //             // List<PreProduct_Storage__c> ProductStorageList = new List<PreProduct_Storage__c>();
    //             if(NewcodeListId.size() > 0){
    //                 prd2List = [Select Id,Correspond_Code__c From Product2 Where Correspond_Code__c In:NewcodeListId];
    //                 for(Product2 prd2 : prd2List){
    //                     lastProductFLGListId.add(prd2.Id);
    //                     if(!proCorderIdMap.containsKey(prd2.Id)){
    //                         Set<Opportunity> cnewList = proCorderIdMap.get(prd2.Correspond_Code__c);
    //                         proCorderIdMap.put(prd2.Id,cnewList);
    //                     }
    //                     prd2Map.put(prd2.Correspond_Code__c, prd2.Id);
    //                 }
    //             }
    //             //*****合并产品重复的报价****
    //             if(lastProductFLGListId!=null&&lastProductFLGListId.size()!=0){
    //                 // 锁定行前查询数据
    //                 List<PreProduct_Storage__c> lockedPreProductStorage = [SELECT Id,Name,Storage_Number__c,Used_Number__c,Department__c,Province__c,RecordType.Name,Field1__c 
    //                 FROM PreProduct_Storage__c 
    //                 WHERE ifValid__c = true and Field1__c in:lastProductFLGListId
    //                 and ((RecordType.Name = '整机' and Department__c in:SalepartmentSAPList) 
    //                 or (RecordType.Name = '耗材' and Province__c in:OCMprovincecusList) ) FOR UPDATE];
    //                 // 执行需要锁定行的其他操作
    //                 if(lockedPreProductStorage!=null&&lockedPreProductStorage.size()!=0){
    //                     List<Id> preProductStorageIdList = new List<Id>();
    //                     for (PreProduct_Storage__c preProductStorage : lockedPreProductStorage) {
    //                         for(Opportunity corder : proCorderIdMap.get(preProductStorage.Field1__c)){
    //                             if((preProductStorage.RecordType.Name == '整机'
    //                             && corder.Salesdepartment_SAP__c == preProductStorage.Department__c)
    //                             ||(preProductStorage.RecordType.Name == '耗材'
    //                             && corder.OCM_man_province_cus__c == preProductStorage.Province__c) ){
    //                                 if(prd2ppsMap.containsKey(corder.Id)){
    //                                     Map<String,PreProduct_Storage__c> clastmap = prd2ppsMap.get(corder.Id);
    //                                     clastmap.put(preProductStorage.Field1__c,preProductStorage);
    //                                     prd2ppsMap.put(corder.Id,clastmap);
    //                                 }else{
    //                                     Map<String,PreProduct_Storage__c> cnewmap = new Map<String,PreProduct_Storage__c>();
    //                                     cnewmap.put(preProductStorage.Field1__c,preProductStorage);
    //                                     prd2ppsMap.put(corder.Id,cnewmap);
    //                                 }
    //                             }
    //                         }
    //                         preProductStorageIdList.add(preProductStorage.Id);
    //                     }
    //                     List<PreProduct_Storage_List__c> pslList = [select Id,PreProduct_Storage__c,AddReduceNumber__c,Opportunity__c 
    //                                                   from PreProduct_Storage_List__c 
    //                                                   where Opportunity__c in:localId 
    //                                                   and PreProduct_Storage__c in:preProductStorageIdList];
    //                     Map<String,Map<String,Decimal>> fallbackQuantityMap = new Map<String,Map<String,Decimal>>();
    //                     for(PreProduct_Storage_List__c psl :pslList){
    //                         if(fallbackQuantityMap.containsKey(psl.Opportunity__c)){
    //                           Map<String,Decimal> QuantityMap = fallbackQuantityMap.get(psl.Opportunity__c);
    //                           if(QuantityMap.containsKey(psl.PreProduct_Storage__c)){
    //                             Decimal lastsumnum = QuantityMap.get(psl.PreProduct_Storage__c);
    //                             Decimal newsumnum = psl.AddReduceNumber__c+lastsumnum;
    //                             QuantityMap.put(psl.PreProduct_Storage__c,newsumnum);
    //                           }else{
    //                             QuantityMap.put(psl.PreProduct_Storage__c,psl.AddReduceNumber__c);
    //                           }
    //                           fallbackQuantityMap.put(psl.Opportunity__c,QuantityMap);
    //                         }else{
    //                           Map<String,Decimal> QuantityMap = new Map<String,Decimal>();
    //                           QuantityMap.put(psl.PreProduct_Storage__c,psl.AddReduceNumber__c);
    //                           fallbackQuantityMap.put(psl.Opportunity__c,QuantityMap);
    //                         }
    //                     }
    //                     for (String key2 : map2.keySet()) {
    //                         Map<String,OpportunityLineItem> value2 = map2.get(key2);
    //                         Map<String,PreProduct_Storage__c> clastma = prd2ppsMap.get(key2);
    //                         Map<String,Decimal> QuantityMa =  fallbackQuantityMap.get(key2);
    //                         for (OpportunityLineItem value : value2.values()) {
    //                             if(clastma.containsKey(value.PricebookEntry.Product2Id) || value.PricebookEntry.Product2.whetherOldCode_PrePro__c){
    //                                 //有预留的产品
    //                                 PreProduct_Storage__c preProductStorage2 = clastma.get(value.PricebookEntry.Product2Id);
    //                                 //有旧code的产品
    //                                 PreProduct_Storage__c oldcodeps = clastma.get(prd2Map.get(value.PricebookEntry.Product2Id));
    //                                 if(oldcodeps != null){
    //                                   Decimal oldcodenum = QuantityMa.get(oldcodeps.Id);
    //                                   if(oldcodenum<0){
    //                                     oldcodenum = -oldcodenum;
    //                                     PreProduct_Storage_List__c PreProductStorageObj = new PreProduct_Storage_List__c();
    //                                     PreProductStorageObj.PreProduct_Storage__c = oldcodeps.Id;
    //                                     PreProductStorageObj.Modify_Number__c = oldcodenum;
    //                                     PreProductStorageObj.AddReduceNumber__c = oldcodenum;
    //                                     PreProductStorageObj.Modified_Time__c = Datetime.now();
    //                                     PreProductStorageObj.Change_Type__c = '退回';
    //                                     PreProductStorageObj.Opportunity__c = key2;
    //                                     PreProductStorageList.add(PreProductStorageObj);
    //                                   }
    //                                 }
    //                                 if(preProductStorage2 != null){
    //                                   Decimal newnum = QuantityMa.get(preProductStorage2.Id);
    //                                   if(newnum<0){
    //                                     newnum = -newnum;
    //                                     PreProduct_Storage_List__c PreProductStorageObj = new PreProduct_Storage_List__c();
    //                                     PreProductStorageObj.PreProduct_Storage__c = preProductStorage2.Id;
    //                                     PreProductStorageObj.Modify_Number__c = newnum;
    //                                     PreProductStorageObj.AddReduceNumber__c = newnum;
    //                                     PreProductStorageObj.Modified_Time__c = Datetime.now();
    //                                     PreProductStorageObj.Change_Type__c = '退回';
    //                                     PreProductStorageObj.Opportunity__c = key2;
    //                                     PreProductStorageList.add(PreProductStorageObj);
    //                                   }
    //                                 }
    //                             }
    //                         }
    //                     }
    //                 }
    //             }
    //             if(PreProductStorageList.size()>0){
    //                 insert PreProductStorageList;
    //             }
    //             // if(UpdatePreProductStorageList.size()>0){
    //             //     update UpdatePreProductStorageList;
    //             // }
    //         }
    //         isExecuted = true;
    //     }
    // }
    //fy DB202312538864 2024.02.20 end
}