global class SpareIsLoanBatch implements Database.Batchable<sObject> {
	//----SWAG-B624XU-----XHL--------20181101-------------------
	//该Batch 运行后会 修改 Opportunity(询价) 和 Rental_Apply__c(备品借出申请)
	
	List<String> oppIdListBatch;

	Boolean IsNeedExecute = false; // 2021-06-07  mzy  WLIG-BYHD79  SFDC环境batch合并调查  是否符合执行条件

	Integer daysBefore = 2; // 2023-01-05 ssm 报告太多了，需要增加限制

	//默认执行为无参
	global SpareIsLoanBatch() {
		
	}
	// 备品借出申请Rental_Apply__c 中 Follow_UP_Opp__c 询价ID
	global SpareIsLoanBatch(List<String> oppIdList) {
		this.oppIdListBatch = oppIdList;
	}
  
	//2021-06-07 mzy   WLIG-BYHD79  SFDC环境batch合并调查   start
	global SpareIsLoanBatch(Boolean needExecute) {
		this.IsNeedExecute = needExecute; 
	}
	// 2021-06-07  mzy  WLIG-BYHD79  SFDC环境batch合并调查   end

	// 2023-01-05 ssm 为报告增加限制，处理历史数据 start
	global SpareIsLoanBatch(Integer days) {
		this.daysBefore = days;
	}
	// 2023-01-05 ssm 为报告增加限制，处理历史数据 end

	global Database.QueryLocator start(Database.BatchableContext BC) {
		if (oppIdListBatch == null || oppIdListBatch.size() == 0 ) {
			// 查询 跟进询价1 不为 空的 备品借出申请
			return  Database.getQueryLocator(
				[SELECT Id,Follow_UP_Opp__c,Follow_UP_Opp__r.Spare_Application_Singular__c,Follow_UP_Opp__r.Estimation_Decision__c,Follow_UP_Opp__r.EffectiveRentalApply__c   
			FROM Rental_Apply__c WHERE Follow_UP_Opp__c != null ]);
		} else {
			return  Database.getQueryLocator(
				[SELECT Id,Follow_UP_Opp__c,Follow_UP_Opp__r.Spare_Application_Singular__c,Follow_UP_Opp__r.EffectiveRentalApply__c,Follow_UP_Opp__r.Estimation_Decision__c   
			FROM Rental_Apply__c WHERE Follow_UP_Opp__c In :oppIdListBatch ]);
		}
			
	}

   	global void execute(Database.BatchableContext BC, List<Rental_Apply__c> raList) {

		//询价所用
		Map<String,Decimal>  countMap = new Map<String,Decimal>(); 
		Map<String,Integer>  resultsMap = new Map<String,Integer>();
		List<String> rA_statusList = new List<String>();
		Map<String,Opportunity> updateOpportunityMap = new Map<String,Opportunity>();
		Map<String,Decimal> selectQuantityMap = new Map<String,Decimal>();
		//备品借出申请所用
		List<Rental_Apply__c> racList = new List<Rental_Apply__c>();
		Map<String,Decimal>  racCountMap = new Map<String,Decimal>();
		Map<String,Integer>  racResultsMap = new Map<String,Integer>();

		rA_statusList.add('已出库');rA_statusList.add('医院已装机确认');rA_statusList.add('已回寄');
		rA_statusList.add('欠品中');rA_statusList.add('申请者已收货');rA_statusList.add('已回收');
		rA_statusList.add('完了');
		//A集合 跟进询价1 不为 空的 备品借出申请
		for(Rental_Apply__c ra: raList){
			String oppId = ra.Follow_UP_Opp__c;
			Decimal singular = ra.Follow_UP_Opp__r.Spare_Application_Singular__c;
			Decimal effectiveRentalApply = ra.Follow_UP_Opp__r.EffectiveRentalApply__c;
			countMap.put(oppId,singular);
			selectQuantityMap.put(oppId,effectiveRentalApply);
		}
		//B集合 使用目的2 不是 已购待货 并且 状态是 出库及以后状态的 备品借出申请
		AggregateResult[]  results = [select Follow_UP_Opp__c,count(Id) cnt
		 		from Rental_Apply__c
				where Follow_UP_Opp__c In :countMap.keySet() AND RA_Status__c In :rA_statusList AND demo_purpose2__c != '已购待货'  group by Follow_UP_Opp__c];
		// SWAG-BVA5V8	XHL 2020-12-14 Add AND demo_purpose2__c != '已购待货'
		for(AggregateResult ar :results){
			resultsMap.put(String.valueOf(ar.get('Follow_UP_Opp__c')), Integer.valueOf(ar.get('cnt')));
		}
		Opportunity  opp = null;
		//B集合是A集合的子集
		for (String ids :countMap.keySet()) {
			
			if (resultsMap.containsKey(ids)) {
				// A 集合的值 在B集合中
				// 询价 找到符合要求的备品借出申请
				if (countMap.get(ids) == null) {
					// 询价 备品申请单数 的值 为空
					opp = new Opportunity();
					opp.Spare_Application_Singular__c = resultsMap.get(ids);
					opp.Id = ids;
					updateOpportunityMap.put(ids,opp);
				} else if(countMap.get(ids) != resultsMap.get(ids)) {
					// 询价 备品申请单数 有值，但是新值不等于旧值 
					opp = new Opportunity();
					opp.Spare_Application_Singular__c = resultsMap.get(ids);
					opp.Id = ids;
					updateOpportunityMap.put(ids,opp);
				}

			} else {
				// A 集合的值 不在B集合中 
				// 询价 没有找到符合要求的备品借出申请
				if (countMap.get(ids) == null) {
					// 询价 备品申请单数 的值 为空 置零
					opp = new Opportunity();
					opp.Spare_Application_Singular__c = 0;
					opp.Id = ids;
					updateOpportunityMap.put(ids,opp);
				} else if (countMap.get(ids)>0) {
					// 询价 备品申请单数 的值 不为为空 置零
					opp = new Opportunity();
					opp.Id = ids;
					opp.Spare_Application_Singular__c = 0;
					updateOpportunityMap.put(ids,opp);
				}
				
			}
			
		}

		if (selectQuantityMap != null && selectQuantityMap.size() > 0) {

			// 查找 借出备品配套一览 获取 备品配套明细型号	
			List<Rental_Apply_Equipment_Set__c> getRAESList = [SELECT Id,Name,Rental_Apply__c,First_RAESD_Model_No_F__c,Rental_Apply__r.Follow_UP_Opp__c,Rental_Apply__r.Demo_purpose1__c,Rental_Apply__r.demo_purpose2__c,Bollow_Date__c FROM  Rental_Apply_Equipment_Set__c WHERE Rental_Apply__r.Demo_purpose1__c = '产品试用' AND (Rental_Apply__r.demo_purpose2__c = '试用（有询价）' OR Rental_Apply__r.demo_purpose2__c = '试用（无询价）') AND Rental_Apply__r.Bollow_Date__c != null AND Rental_Apply__r.Follow_UP_Opp__c IN: selectQuantityMap.keySet() order by Rental_Apply__r.Follow_UP_Opp__c ];
			// 将每个询价下  借出备品配套一览 的 备品配套明细型号 放进集合
			Map<String,List<String>> model_NoMap  = new Map<String,List<String>>();
			for(Rental_Apply_Equipment_Set__c raes :getRAESList){
				String opportunityId = raes.Rental_Apply__r.Follow_UP_Opp__c;
				List<String> model_NoList = new List<String>();

				if (model_NoMap.containsKey(opportunityId)) {
					model_NoList = model_NoMap.get(opportunityId);
				}
				model_NoList.add(raes.First_RAESD_Model_No_F__c);
				model_NoMap.put(opportunityId,model_NoList);

			}
			// 查找 询价产品 获取 OCSM内部产品型号(略称)
			List<OpportunityLineItem> getOpportunityLineItemList = [Select Id, Asset_Model_No__c, OCM_internal_product_name__c,OpportunityId From OpportunityLineItem where OpportunityId In:selectQuantityMap.keySet() order by OpportunityId];
			Map<String,Decimal>  effectiveRental_ApplyMap  = new  Map<String,Decimal>();

			if (getOpportunityLineItemList.size() >0) {
				for(OpportunityLineItem oli:getOpportunityLineItemList)	{
					String opportunityId = oli.OpportunityId;
					if (model_NoMap.containsKey(opportunityId)) {
						
						for (String model_No :model_NoMap.get(opportunityId)){

							if (oli.Asset_Model_No__c.equals(model_No) && !effectiveRental_ApplyMap.containsKey(opportunityId)) {
								// 备品申请单一览中的主机型号与产品的型号相同
								effectiveRental_ApplyMap.put(opportunityId,1);
							}
						}

					} else {
						// 询价 下 备品借出申请 无 借出备品配套一览
						effectiveRental_ApplyMap.put(opportunityId,0);
					}
				}	
			}
			
		
			for (String oppId:selectQuantityMap.keySet()){

				opp = new Opportunity();
				opp.Id = oppId;
				if (updateOpportunityMap.containsKey(oppId)) {
					opp = updateOpportunityMap.get(oppId);
				}
				if (!effectiveRental_ApplyMap.containsKey(oppId)) {
					if (selectQuantityMap.get(oppId) != 0) {
						// 备品申请单一览中的主机型号与产品的型号不相同，或者 询价下 无询价产品，有效备品申请 置0。
						opp.EffectiveRentalApply__c = 0;
						updateOpportunityMap.put(oppId,opp);
					}
					
				} else  {
					if (effectiveRental_ApplyMap.get(oppId) != selectQuantityMap.get(oppId)) {
						opp.EffectiveRentalApply__c = effectiveRental_ApplyMap.get(oppId);
						updateOpportunityMap.put(oppId,opp);
					}
				}
			}
		}
		
		// 2023-01-05 ssm 增加限制，报告要审批通过的，最后更新日在2天内的
		// 为处理历史数据，设置成可以调整的样子
		Datetime start_at = this.daysBefore != null && this.daysBefore > 0 ? Datetime.now().addDays(0 - this.daysBefore) : Datetime.now().addDays(-2);
		List<Report__c> raLists = [Select Id,Loaner_request_no1__c,Loaner_request_no1__r.OPDAmount__c 
			from Report__c where Loaner_request_no1__c != null and Status__c = '批准' and LastModifiedDate >= :start_at];
		
		for (Report__c ra: raLists) {

			racCountMap.put(ra.Loaner_request_no1__c,ra.Loaner_request_no1__r.OPDAmount__c);
			
		}
		results = [select Loaner_request_no1__c,count(Id) cnt  from  Report__c where Loaner_request_no1__c In :racCountMap.keySet() and Status__c = '批准' group by Loaner_request_no1__c];
		system.debug('results'+results);
		for (AggregateResult ar :results) {
			racResultsMap.put(String.valueOf(ar.get('Loaner_request_no1__c')), Integer.valueOf(ar.get('cnt')));
		}
		Rental_Apply__c rac = null;
		for (String ids :racCountMap.keySet()) {
			if (racResultsMap.containsKey(ids)) {
				if (racCountMap.get(ids) == null) {
					rac = new Rental_Apply__c();
					rac.OPDAmount__c = racResultsMap.get(ids);
					rac.Id = ids;
					racList.add(rac);
				} else if(racCountMap.get(ids) != racResultsMap.get(ids)) {
					rac = new Rental_Apply__c();
					rac.OPDAmount__c = racResultsMap.get(ids);
					rac.Id = ids;
					racList.add(rac);
				}

			} else {

				if (racCountMap.get(ids) == null) {
					rac = new Rental_Apply__c();
					rac.OPDAmount__c = 0;
					rac.Id = ids;
					racList.add(rac);
				} else if (racCountMap.get(ids)>0) {
					rac = new Rental_Apply__c();
					rac.Id = ids;
					rac.OPDAmount__c = 0;
					racList.add(rac);
				}
				
			}
			
		}
		if (racList.size()>0) {
			update racList;
		}
		// if (oppList.size()>0) {
		// 	update oppList;
		// }
		if (updateOpportunityMap != null && updateOpportunityMap.size() > 0) {
			update updateOpportunityMap.values();
		}
	}
	
	global void finish(Database.BatchableContext BC) {

		
      //2021-07-13  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
        //if(!Test.isRunningTest() &&IsNeedExecute==true){
          //batch里调用下一个batch时，希望跟原有的Schedule里面传的条数保持一致
        //   Id execBTId = Database.executebatch(new SubAuthorizedBatch(true),10);
        //}
        if(!Test.isRunningTest() &&IsNeedExecute==true){
          //batch里调用下一个batch时，希望跟原有的Schedule里面传的条数保持一致
           Id execBTId = Database.executebatch(new CreateOpportunityTaskBatch(true),20);
        }
      //2021-07-13  mzy  WLIG-BYHD79  SFDC环境batch合并调查 end
	}
	
}