global class InsReToMaintenanceBatch implements Database.Batchable { String query; public List MtcUpdate{get;set;} public List SelallInsReport {get;set;} //维修合同和所属检点书Map public Map> InsMtcMap {get;set;} global InsReToMaintenanceBatch() { SelallInsReport = new List(); InsMtcMap = new Map>(); MtcUpdate = new List(); } global Database.QueryLocator start(Database.BatchableContext BC) { query = 'select id,name,PA_Contrant_Cnt__c,PB_Contrant_Cnt__c from Maintenance_Contract__c ' + ' where Status__c = \'契約\' '; //query = ''; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List scope) { List MainIdlist = new List(); Date TodayYMD = Date.today(); MtcUpdate = scope; for (Maintenance_Contract__c mc : MtcUpdate) { MainIdlist.add(mc.id); } SelallInsReport = [select id,name,Inspection_Date__c,Contract__c from Inspection_Report__c where Contract__c in :MainIdlist]; //数据清零 for(Maintenance_Contract__c Mc : MtcUpdate){ Mc.PA_Contrant_Cnt__c = null; Mc.PB_Contrant_Cnt__c = null; } for(Inspection_Report__c iRc : SelallInsReport){ if(InsMtcMap.containsKey(iRc.Contract__c)){ continue; }else{ List NullList = New List(); InsMtcMap.put(iRc.Contract__c, NullList); } } system.debug('InsMtcMap::::::'+InsMtcMap); for(Inspection_Report__c iR : SelallInsReport){ if(InsMtcMap.containsKey(iR.Contract__c)){ //区分是不是今年 if(TodayYMD.month()>3&&((iR.Inspection_Date__c.year()==TodayYMD.year()&&iR.Inspection_Date__c.month()>3)|| (iR.Inspection_Date__c.year()==(TodayYMD.year()+1)&&iR.Inspection_Date__c.month()<4))|| (TodayYMD.month()<3&&((iR.Inspection_Date__c.year()==TodayYMD.year()&&iR.Inspection_Date__c.month()<4)|| (iR.Inspection_Date__c.year()==(TodayYMD.year()-1)&&iR.Inspection_Date__c.month()>3))) ){ //区分上半年下半年 if(iR.Inspection_Date__c.month()>3&&iR.Inspection_Date__c.month()<10){ List AddListInt = new List(); AddListInt = InsMtcMap.get(iR.Contract__c); AddListInt.add(0); InsMtcMap.put(iR.Contract__c,AddListInt); }else{ List AddListInt = new List(); AddListInt = InsMtcMap.get(iR.Contract__c); AddListInt.add(1); InsMtcMap.put(iR.Contract__c,AddListInt); } }else{ //不是今年的忽略不计 continue; } } } system.debug('InsMtcMap::::::'+InsMtcMap); List UpdateList = new List(); Map AddOrNot = new Map(); for(Maintenance_Contract__c Mc : MtcUpdate){ Integer PA = 0; //上半年计数 Integer PB = 0; //下半年计数 if(AddOrNot.containsKey(Mc.id)){ continue; }else{ if(InsMtcMap.containsKey(Mc.id)){ List ResultCnt = InsMtcMap.get(Mc.id); for(Integer i : ResultCnt){ if(i == 0){ PA=PA+1; }else{ PB=PB+1; } } } Mc.PA_Contrant_Cnt__c = PA; Mc.PB_Contrant_Cnt__c = PB; //UpdateList.add(Mc); AddOrNot.put(Mc.id, Mc.id); } } system.debug('MtcUpdate::::::'+MtcUpdate); if(MtcUpdate.size()>0){ update MtcUpdate; } } global void finish(Database.BatchableContext BC) { } }