//create by tcm 2021-11-15	batch版累计汇总（条件）
global class UpdateAssetReturnTimeBatch implements Database.Batchable<sObject>, Database.Stateful {
	public List<String> tempIds;
	public String history;// 20211129 ljh add start
	global UpdateAssetReturnTimeBatch(List<String> tempId) {
		this.tempIds = tempId;
	}
	global UpdateAssetReturnTimeBatch() {
		this.tempIds = new List<String>();
		this.History = '';
	}
	// 20211129 ljh add start
	global UpdateAssetReturnTimeBatch(String type) {
		this.history = type;
	}
	// 20211129 ljh add start
	global Database.QueryLocator start(Database.BatchableContext bc) {
		// 20211129 ljh add start
		Date mdDay = Date.newInstance(2020, 04, 01);
		Date st = mdDay.toStartOfWeek();
		Datetime laststart = Datetime.newInstance(st.year(), st.month(), st.day(), 8, 0, 0);
		// 20211129 ljh add end
		String sql ='select id FROM Rental_Apply__c ';
		// 20211129 ljh add start
		sql += 'where Asset_return_time_OK__c = null and Asset_return_time__c != null and Asset_return_time_OK_Flag__c = false';
		sql += ' AND CreatedDate >= :laststart ';
		// 20211129 ljh add end
		if (tempIds != null && tempIds.size() > 0) {
			sql += 'and  Id in :tempIds ';
		}
		return Database.getQueryLocator(sql);
	}

	global void execute(Database.BatchableContext BC, list<Rental_Apply__c> raList) {
		List<String> raIdList=new List<String>();
		for (Rental_Apply__c ra : raList) {
			raIdList.add(ra.Id);
		}
		List<AggregateResult> raesList=[select Rental_Apply__c,MIN(Asset_return_time__c) art FROM Rental_Apply_Equipment_Set__c WHERE Rental_Apply__c in :raIdList and Received_Confirm__c!=null AND Received_Confirm__c!='NG' AND Asset_return_time__c !=NULL group by Rental_Apply__c];

		List<Rental_Apply__c> racList=new List<Rental_Apply__c>();
		for (AggregateResult raes : raesList) {
			Rental_Apply__c ra=new Rental_Apply__c();
			ra.Id=(Id)raes.get('Rental_Apply__c');
			ra.Asset_return_time_OK__c=(Datetime)raes.get('art');
			ra.Asset_return_time_OK_Flag__c = true; // 20211129 ljh add 
			racList.add(ra);
		}
		update racList;
	}

	global void finish(Database.BatchableContext BC) {
		// 20220113 ljh add 排队对应关系系列 start
		if(!System.Test.isRunningTest()){
			database.executebatch(new RentalQueueShippmentDate0Batch(),50);
		}
		// 20220113 ljh add 排队对应关系系列 end
	}
}