public without sharing class RentalApplyFaultReportController{

	public String raId {get; set;}
	public List<Rental_Apply_Equipment_Set_Detail__c> eList { get; set;}
	public Rental_Apply__c raObj { get; set;}
	public List<RetObject> retObject { get; set; }

	public RentalApplyFaultReportController(){
		raId = ApexPages.currentPage().getParameters().get('ra_id');

		if (String.isBlank(this.raId)) {
			throw new ControllerUtil.myException('参数错误：请指定Id。');
		}
	}

	public Pagereference init() {

		retObject = new List<RetObject>();

		raObj = [SELECT Id, Name, OCM_dept_category__c, Hospital__c, Hospital__r.Name, Person_In_Charge__c, Person_In_Charge__r.Name, WorkPlace__c, demo_purpose2__c FROM Rental_Apply__c WHERE Id =: raId];

		//备品借出申请一览明细
		eList = [
			SELECT Id, Name, Rental_Apply__c, Rental_Apply_Equipment_Set__r.Name, Rental_Apply__r.OCM_dept_category__c, Loaner_asset_no__c, AssetName__c,
				Fixture_Model_No__c, SerialNumber_F__c, Inspection_result_after__c, Inspection_result_after_NG__c, SerialNumber__c
			  FROM Rental_Apply_Equipment_Set_Detail__c
			 WHERE Rental_Apply__c = :raId
			   AND Inspection_result_after__c = 'NG'
			   AND Is_Body__c = true
			ORDER BY Id];

		List<Id> eIds = new List<Id>();
		for(Rental_Apply_Equipment_Set_Detail__c e :eList){
			eIds.add(e.Id);
		}


		//查当前明细下有多少故障报告
		// 0 没有报告
		// Id 有 最新一条为草案中
		// 2 有很多条
		List<Rental_Apply_Fault__c> faultReportsList = [SELECT Id ,status__c ,Rental_Apply_Equipment_Set_Detail__c from Rental_Apply_Fault__c where Rental_Apply_Equipment_Set_Detail__c in :eIds Order By CreatedDate DESC];
		Map<Id, List<Rental_Apply_Fault__c>> radetail_rentalApplyFault_Map = new Map<Id, List<Rental_Apply_Fault__c>>();
		
		for(Rental_Apply_Fault__c raf : faultReportsList){
			if(!radetail_rentalApplyFault_Map.containsKey(raf.Rental_Apply_Equipment_Set_Detail__c)){
				List<Rental_Apply_Fault__c> tempList = new List<Rental_Apply_Fault__c>();
				tempList.add(raf);
				radetail_rentalApplyFault_Map.put(raf.Rental_Apply_Equipment_Set_Detail__c, tempList);
			}
		}

		system.debug('radetail_rentalApplyFault_Map==='+radetail_rentalApplyFault_Map);

		for(Rental_Apply_Equipment_Set_Detail__c rae : eList){

			RetObject temp = new RetObject();
			temp.Id = rae.Id;
			temp.Name = rae.Name;
			temp.rae = rae;
			
			if( radetail_rentalApplyFault_Map.containsKey(rae.Id) && radetail_rentalApplyFault_Map.get(rae.Id).size() > 0 ){
					
				temp.flag = radetail_rentalApplyFault_Map.get(rae.Id)[0].Id ;
				
			}else{
				temp.flag = '不存在故障报告单';
			}

			retObject.add(temp);
		}

		return null;
	}

	public class RetObject {
		public String Id { get; set; }
		public String Name { get; set; }

		public Rental_Apply_Equipment_Set_Detail__c rae { get; set; }
		public String flag { get; set; }
	}
}