public without sharing class BidAnnounceTrigger {
    // Bid_AnnouncementのId
    public static Set<Id> Bid_Ids = new Set<Id>();
    
    public static void checkConfirmStatus(List<Bid_Announcement__c> newList, List<Bid_Announcement__c> oldList, Map<Id, Bid_Announcement__c> newMap, Map<Id, Bid_Announcement__c> oldMap) {
        List<String> oppIds = new List<String>();
        for (Bid_Announcement__c ba : newList) {
            // 二重実行禁止
            if (Bid_Ids.contains(ba.Id)) continue;
            
            if (ba.Status__c == '处理完毕') {
                oppIds.add(ba.Opportunity_name__c);
                
                Bid_Ids.add(ba.Id);
            }
        }
        
        if (oppIds.size() > 0) {
            Map<String, String> oppEstiMap = new Map<String, String>();
            for (Opportunity opp : [select Id, Estimation_Id__c from Opportunity where Id in :oppIds]) {
                oppEstiMap.put(opp.Id, opp.Estimation_Id__c);
            }
            // 报价-中标相互link
            Map<String, String> falseMap = new Map<String, String>();
            for (Bid_Announcement__c ba : newList) {
                if (String.isBlank(oppEstiMap.get(ba.Opportunity_name__c))) {
                    ba.addError('询价还没有报价，无法同意中标通知书');
                } else {
                    ba.Quote__c = oppEstiMap.get(ba.Opportunity_name__c);
                    falseMap.put(oppEstiMap.get(ba.Opportunity_name__c), ba.Id);
                }
            }
            
            if (falseMap.keySet().size() > 0) {
                List<Quote> falseQuotes = new List<Quote>();
                for (Quote q : [select Id from Quote where Id in :falseMap.keySet()]) {
                    q.BidAnnounce__c = falseMap.get(q.Id);
                    falseQuotes.add(q);
                }
                update falseQuotes;
            }
        }
    }
    
    public static void clearBidQuoteLink(List<Bid_Announcement__c> newList, List<Bid_Announcement__c> oldList, Map<Id, Bid_Announcement__c> newMap, Map<Id, Bid_Announcement__c> oldMap) {
        List<String> quoteIds = new List<String>();
        for (Bid_Announcement__c ba : newList) {
            // 二重実行禁止
            if (Bid_Ids.contains(ba.Id)) continue;
            
            Bid_Announcement__c oldBa = oldMap.get(ba.Id);
            if (oldBa.Status__c == '处理完毕' && ba.Status__c == '草案中') {
                quoteIds.add(ba.Quote__c);
                ba.Quote__c = null;
                
                Bid_Ids.add(ba.Id);
            }
        }
        
        if (quoteIds.size() > 0) {
            List<Quote> updQuotes = new List<Quote>();
            for (Quote q : [select Id from Quote where Id in :quoteIds]) {
                q.BidAnnounce__c = null;
                updQuotes.add(q);
            }
            update updQuotes;
        }
    }
}