/**
 * 经销商有效协议判断
 */
public without sharing class AccountEffectiveContract {
	public static void syncAccountContract(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
		//取得经销商ID SET
    	Set<String> agencySet = new Set<String>();
		if (Trigger.isInsert) {
			for (Account acc : newList) {
				if(acc.RecordTypeId == System.label.effective_1){ //niwu  01210000000QjCN
					agencySet.add(acc.ParentId);
				}
			}
		}else if (Trigger.isDelete) {
			for (Account acc : oldList) {
				if(acc.RecordTypeId == System.label.effective_1){
					agencySet.add(acc.ParentId);
				}
			}
		}else if(Trigger.isUpdate ){
			for (Account acc : newList) {
				if(acc.RecordTypeId == System.label.effective_1 && (acc.Delete_Flag__c != oldMap.get(acc.Id).Delete_Flag__c || acc.ET_SP_Dealer__c != oldMap.get(acc.Id).ET_SP_Dealer__c)){
					agencySet.add(acc.ParentId);
				}
			}
			for (Account acc : oldList) {
				if(acc.RecordTypeId == System.label.effective_1 && (acc.Delete_Flag__c != newMap.get(acc.Id).Delete_Flag__c || acc.ET_SP_Dealer__c != newMap.get(acc.Id).ET_SP_Dealer__c)){
					agencySet.add(acc.ParentId);
				}
			}
		}
		//汇总举要有效契约的经销商数据
		if(agencySet.size() > 0){
			List<Account> accUpList = new List<Account>();
			List<Account> accList = [SELECT Id FROM Account WHERE  Id in :agencySet];
			AggregateResult[] results = [SELECT ParentId,count(Id) cnt
                                         FROM Account
                                         WHERE ParentId in :agencySet
                                         AND ET_SP_Dealer__c = true
                                         AND Is_Active_Formula__c = '有效'
                                         group by ParentId];
            for(Account acc : accList){
            	Boolean existFlg = false;
            	for(AggregateResult ar: results){
            		if(String.valueOf(ar.get('ParentId')) == acc.Id){
            			if(Integer.valueOf(ar.get('cnt')) > 0){
            				existFlg = true;
            				break;
            			}
            		}
            	}
            	Account accinfo = new Account();
            	accinfo.id = acc.Id;
            	accinfo.Agency_With_EffectiveContract__c = existFlg;
            	accUpList.add(accinfo);
            }
            System.debug('accUpList+++++' + accUpList.size()  + accUpList);
            if(accUpList.size() > 0){

            	update accUpList;
            }
		}
	}

	
}