global class AgencyIntelligenceExpireBatch implements Database.Batchable<sObject> {
	
	String query;
	
	global AgencyIntelligenceExpireBatch() {
		
	}
	
	global Database.QueryLocator start(Database.BatchableContext BC) {
		query = 'select Id, Agency1__r.Id, Agency1__r.Ban_On_Use_Date__c, Agency1__r.Business_Paper_Expiration_Date__c, ';
		query += 'Agency1__r.Tax_Practice_Expiration_Date__c, Agency1__r.Medical_Equipment_Expiration_Date__c, ';
		query += 'Sales_assistant_name_text__c, Manager_name_text__c from Opportunity where StageName__c =\'询价\' ';
		query += 'and From_Today_Num__c >= 0 and From_Today_Num__c <= 60 and Agency1__c <> null';

		return Database.getQueryLocator(query);
	}

   	global void execute(Database.BatchableContext BC, List<sObject> scope) {
		List<Opportunity> oppList = new List<Opportunity>();
		List<Opportunity> updOppList = new List<Opportunity>();
		oppList = scope;
		for (Opportunity opp : oppList) {
			// 经销商1的 禁用日期和三证中有任何一个日期在未来30天到期 的系统发邮件提醒邮件给营业助理和询价所有人的经理
			if ((opp.Agency1__r.Ban_On_Use_Date__c != null && opp.Agency1__r.Ban_On_Use_Date__c <= Date.today().addDays(30))
				|| (opp.Agency1__r.Business_Paper_Expiration_Date__c != null && opp.Agency1__r.Business_Paper_Expiration_Date__c <= Date.today().addDays(30))
				|| (opp.Agency1__r.Tax_Practice_Expiration_Date__c != null && opp.Agency1__r.Tax_Practice_Expiration_Date__c <= Date.today().addDays(30))
				|| (opp.Agency1__r.Medical_Equipment_Expiration_Date__c != null && opp.Agency1__r.Medical_Equipment_Expiration_Date__c <= Date.today().addDays(30))
				) {
				opp.Agency_Intelligence_Expire_Remind_Flag__c = 10;
				updOppList.add(opp);
			}
		}
		if (updOppList.size() > 0) {
			update updOppList;
		}
	}
	
	global void finish(Database.BatchableContext BC) {
		
	}
	
}