public without sharing class OpportunityTrigger {

    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);
                //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
            }
        }

        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 ); 
                // }
                // 合并判断条件
                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('失单')))) {
                    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); 
                        }
                    }
                }

            // }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

}