public class RepairRenewalController {
	public String raId { get; private set; }
	public Rental_Apply__c raObj { get; set; } 
	public List<Rental_Apply_Equipment_Set__c> raesList { get; set; } 

	public void init() {
		this.raId = ApexPages.currentPage().getParameters().get('raid');
		//备品借出申请
		raObj = [SELECT Id, Person_In_Charge__c, Person_In_Charge__r.name, Routine_Check_Status__c, Routine_Check_Day__c, Repair__c, Account__c, Routine_Check_Person__c
				FROM Rental_Apply__c 
				WHERE Id =: raId];
		raObj.Routine_Check_Day__c = Date.today();
		raObj.Routine_Check_Person__c = raObj.Person_In_Charge__r.name;
		raObj.Repair__c = null;
		if (String.isBlank(raObj.Routine_Check_Status__c)) {
			raObj.Routine_Check_Status__c = 'OK';
		}

		//备品借出一览
		raesList = [SELECT Id, Loaner_categoryI_F__c, Loaner_categoryII_F__c FROM Rental_Apply_Equipment_Set__c WHERE Rental_Apply__c =: raObj.Id AND Cancel_Select__c = false];
	}

	public PageReference doRenewal() {
		if (raObj.Routine_Check_Status__c != 'OK' && raObj.Routine_Check_Status__c != 'NG') {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '点检状态没有选择，不能续借'));
			return null;
		}
		if (raObj.Routine_Check_Status__c == 'NG') {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '点检状态NG时，不能续借，请按最新预定归还日操作回寄'));
			return null;
		}
		if (String.isBlank(raObj.Repair__c)) {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '没有选择修理单，不能续借'));
			return null;
		}

		Repair__c repairObj = [
				SELECT Id, Status1__c, Account__c, Delivered_Product__r.Fixture_Model_No_F__c, FSE_ApplyForRepair_time__c, Repair_Final_Inspection_Date__c, Repair_Shipped_Date__c,
						EquipmentGuaranteeFlg_Asset__c, NewProductGuaranteeObject__c, Delivered_Product__r.Product2.Asset_Model_No__c, Number_of_EffectiveContract__c
				FROM Repair__c WHERE Id =: raObj.Repair__c];
		if (repairObj == null) {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '不存在所选择的修理单，请确认'));
			return null;
		}

		// 也就是续借所选择的修理单的医院具体科室与原备品申请单的医院具体科室应该是一致的
		if (repairObj.Account__c != raObj.Account__c) {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '非同一科室，不能续借'));
			return null;
		}

		List<Fixture_Set__c> fsList = [SELECT Loaner_categoryI__c, Loaner_categoryII__c FROM Fixture_Set__c WHERE Fixture_Set_Body_Model_No__c =: repairObj.Delivered_Product__r.Fixture_Model_No_F__c AND Loaner_categoryI__c IN ('硬性内镜', '软性内镜')];
		if (fsList.isEmpty()) {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '非同一系列产品，不能续借'));
			return null;
		}

		Boolean isEqualsCategory = false;
		for (Rental_Apply_Equipment_Set__c raes : raesList) {
			if (raes.Loaner_categoryI_F__c == fsList[0].Loaner_categoryI__c && raes.Loaner_categoryII_F__c == fsList[0].Loaner_categoryII__c) {
				isEqualsCategory = true;
				break;
			}
		}
		// 基于备品类型Ⅰ的基础上备品类型II相同的产品可以申请续借，即客户的新修理型号与原申请单的备品配套明细型号比对，若不满足，提示【非同一系列产品，不能续借】
		if (!isEqualsCategory) {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '非同一系列产品，不能续借'));
			return null;
		}

		// 未申请修理(FSE修理申请日=空)，提示【未申请修理（FSE修理申请日为空），不能续借】
		if (repairObj.FSE_ApplyForRepair_time__c == null) {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '未申请修理（FSE修理申请日为空），不能续借'));
			return null;
		}

		// 新修理的最终检测日≠空，提示【修理单已生成【最终检测日】，不能续借】
		if (repairObj.Repair_Final_Inspection_Date__c != null) {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '修理单已生成【最终检测日】，不能续借'));
			return null;
		}

		// 新修理的状态1 = 0.删除/ 0.取消，提示【修理单已取消、删除，不能续借】
		if (repairObj.Status1__c == '0.删除' || repairObj.Status1__c == '0.取消') {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '修理单已取消、删除，不能续借'));
			return null;
		}

		// 新修理的RC修理品返送日≠空，提示【修理单已生成【RC修理品返送日】，不能续借】
		if (repairObj.Repair_Shipped_Date__c != null) {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '修理单已生成【RC修理品返送日】，不能续借'));
			return null;
		}

		// 回寄默认申请单不存在
		List<FixtureDeliverySlip__c> fdsList = [SELECT Id FROM FixtureDeliverySlip__c WHERE Name = 'RepairRenewal_Ship_Dummy'];
		if (fdsList.isEmpty()) {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '系统默认发货备品运输单不存在，请确认'));
			return null;
		}

		// 回寄默认申请单不存在
		List<FixtureDeliverySlip__c> fdsReturnList = [SELECT Id FROM FixtureDeliverySlip__c WHERE Name = 'RepairRenewal_Return_Dummy'];
		if (fdsReturnList.isEmpty()) {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '系统默认回寄备品运输单不存在，请确认'));
			return null;
		}

		Date today = Date.today();
		DateTime now = System.now();
		String fieldsNames = '';
		for (Schema.SObjectField sObjectField : Schema.getGlobalDescribe().get('Rental_Apply__c').getDescribe().fields.getMap().values()) {
		     fieldsNames += sObjectField.getDescribe().getName() + ',';
		}

		fieldsNames = fieldsNames.removeEnd(',');

		Rental_Apply__c raObjTemp = Database.query(
		      'SELECT ' + fieldsNames + ' FROM Rental_Apply__c Where Id =: raId'
		);

		Rental_Apply__c raCloneObj = raObjTemp.clone(true);
		raCloneObj.Repair__c = raObj.Repair__c;
		raCloneObj.Id = null;
		raCloneObj.Name = null;
		raCloneObj.AWS_Data_Id__c = raObjTemp.AWS_Data_Id__c + 'X';
		// 旧借出申请
		raCloneObj.Old_Rental_Apply__c = null;
		// 续借次数
		raCloneObj.Renewal_Num__c = 0;
		// 补充申请创建
		raCloneObj.SupplementCreated__c = false;
		// 点检状态
		raCloneObj.Routine_Check_Status__c = 'OK';
		// 点检日期
		raCloneObj.Routine_Check_Day__c = today;
		// 点检人 
		raCloneObj.Routine_Check_Person__c = Userinfo.getName();
		// 申请理由
		raCloneObj.Demo_purpose_text__c = '续借';
		// 希望到货日
		raCloneObj.Request_shipping_day__c = today;
		// 医院收到确认完了
		raCloneObj.HP_received_Confirmed__c = false;
		// 用户装机日
		raCloneObj.HP_received_sign_day__c = null;
		// 备品签收单上传记录
		raCloneObj.HP_received_sign_rich__c = null;
		// 医院收到备品签字(文本)
		raCloneObj.HP_received_sign_text__c = null;
		// 备品中心确认
		raCloneObj.AssetManageConfirm__c = false;
		// 上传签收单日期
		raCloneObj.HP_received_sign_NewDate__c = null;
		// 到货签收确认日
		raCloneObj.Rental_Received_Day__c = null;
		// 发货运输单 dummy运输单 a2q6D000000DAqnQAG
		raCloneObj.DeliverySlip__c = fdsList[0].Id;
		// 备品中心出库日(第10个工作日)
		raCloneObj.Bollow_Date_Add_10_WD__c = null;
		// 备品中心出库日(第7个工作日)
		raCloneObj.Bollow_Date_Add_7_WD__c = null;
		// 延期最新步骤批准时间
		raCloneObj.Extension_NewStep_AppTime__c = null;
		// 延期状态
		raCloneObj.ExtensionStatus__c = null;
		// 延期申请时间(最初)
		raCloneObj.ExtensionApplicationTime_Initial__c = null;
		// 延期申请时间(最终)
		raCloneObj.ExtensionApplicationTime_Final__c = null;
		// 延期成功次数
		raCloneObj.ExtensionSuccessTimes__c = null;
		// 延期天数
		raCloneObj.ExtensionDays__c = null;
		// 延期内容
		raCloneObj.ExtensionContent__c = null;
		// 延期入口
		raCloneObj.Extension_Parent_Entrance__c = null;
		// 延期批准时间(最初)
		raCloneObj.ExtensionApprovalTime_Initial__c = null;
		// 延期批准时间(最终)
		raCloneObj.ExtensionApprovalTime_Final__c = null;
		// 延期截止日期
		raCloneObj.Extension_Deadline__c = null;
		// 延期类型
		raCloneObj.Extension_Type__c = null;
		// 是否需要删除延期信息
		raCloneObj.Is_Delete_Extension__c = false;
		// 批量延期申请单
		raCloneObj.Extension_List_RentalApply__c = null;
		// 批量延期申请单id
		raCloneObj.Extension_Much_ID__c = null;
		// 已批量延期申请单
		raCloneObj.History_Extension_List_RentalApply__c = null;
		// 已批量延期申请单id
		raCloneObj.History_Extension_Much_ID__c = null;
		// 维修代品下延期的是否违规
		raCloneObj.DPC_Flag_For_WXDP__c = false;
		// 排队备品预计出库时间
		raCloneObj.QueueShippmentDate__c = null;
		// 新修理
		raCloneObj.NewRepair__c = null;
		// 新修理RC修理品返送日
		raCloneObj.NewRepair_Repair_Shipped_Date__c = null;
		// 新修理单号
		raCloneObj.NewRepairNo__c = null;
		// QIS_RC修理品返送日
		raCloneObj.QIS_Repair_Shipped_Date__c = null;
		// RC未定到期延时
		raCloneObj.RcUnexpectExpiryDelay__c = null;
		// 申请时间
		raCloneObj.Request_demo_time__c = now;
		// 批准时间(申请提交时间)
		raCloneObj.Request_approval_time__c = now;
		// 备品首次分配时间
		raCloneObj.Request_answer_time__c = now;
		// 申请受理时间(回答时间)
		raCloneObj.Application_accept_time__c = null;
		// 应答沟通
		raCloneObj.Response__c = null;
		// 实时应答沟通
		raCloneObj.ResponseNew__c = null;
		// 修理最终检测日
		raCloneObj.Repair_Final_Inspection_Date__c = null;
		// QIS修理
		raCloneObj.QISRepair__c = null;
		// 再修理
		raCloneObj.Re_repair__c = null;
		// 源申请单
		raCloneObj.Root_Rental_Apply__c = null;

		// 使用目的2根据修理单来自动选择是保修用户或者市场多年保修
		if (raCloneObj.demo_purpose2__c == '保修用户' && !Purpose2Check1(repairObj)) {
			if (Purpose2Check2(repairObj)) {
				raCloneObj.demo_purpose2__c = '市场多年保修';
			} else {
				ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '修理单要求是市场多年保或保修用户'));
				return null;
			}
		} else if(raCloneObj.demo_purpose2__c == '市场多年保修' && !Purpose2Check2(repairObj)){
			if (Purpose2Check1(repairObj)) {
				raCloneObj.demo_purpose2__c = '保修用户';
			} else {
				ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, '修理单要求是市场多年保或保修用户'));
				return null;
			}
		}

		Savepoint sp = Database.setSavepoint();
		try {
			Oly_TriggerHandler.bypass('RentalApplyShareHandler');
			Oly_TriggerHandler.bypass('RentalHpDeptUpdHandler');
			FixtureUtil.isRepairRenewal = true;
			insert raCloneObj;

			// 因为申请单Name的赋值规则，所以旧借出申请要单独更新
			Rental_Apply__c raTemp = [SELECT Id, Name, Old_Rental_Apply__c FROM Rental_Apply__c WHERE Id =: raCloneObj.Id];
			//更新后设置旧借出申请信息
			raTemp.Old_Rental_Apply__c = raObj.Id;
			update raTemp;

			// 一览Clone
			String fieldsNames1 = '';
			for (Schema.SObjectField sObjectField : Schema.getGlobalDescribe().get('Rental_Apply_Equipment_Set__c').getDescribe().fields.getMap().values()) {
			     fieldsNames1 += sObjectField.getDescribe().getName() + ',';
			}
			fieldsNames1 = fieldsNames1.removeEnd(',');
			List<Rental_Apply_Equipment_Set__c> raesList = Database.query(
			      'SELECT ' + fieldsNames1 + ' FROM Rental_Apply_Equipment_Set__c Where Rental_Apply__c =: raId and Cancel_Select__c = false order by Id'
			);

			List<Rental_Apply_Equipment_Set__c> raesCloneList = new List<Rental_Apply_Equipment_Set__c>();
			List<Id> ids = new List<Id>();
			for (Rental_Apply_Equipment_Set__c raesObj : raesList) {
				ids.add(raesObj.Id);
				Rental_Apply_Equipment_Set__c raesCloneObj = raesObj.clone(true);
				raesCloneObj.Rental_Apply__c = raCloneObj.Id;
				raesCloneObj.Id = null;
				raesCloneObj.UniqueKey__c = null;
				// 现场签收时间
				raesCloneObj.Loaner_received_time__c = now;
				// 备品预计出货日
				raesCloneObj.Rental_Start_Date__c = today;
				// 备品预计回收日
				raesCloneObj.Rental_End_Date__c = today.addDays(30);
				// 收货确认状态(文本)
				raesCloneObj.Received_Confirm_Status_Text__c = '申请者已收货';
				// 现场收到确认结果
				raesCloneObj.Received_Confirm__c = 'OK';
				// 备品中心出库日(第10个工作日)
				raesCloneObj.Bollow_Date_Add_10_WD__c = null;
				// 备品中心出库日(第7个工作日)
				raesCloneObj.Bollow_Date_Add_7_WD__c = null;
				// 排队备品回寄日
				raesCloneObj.Asset_return_Day__c = null;
				// 排队备品欠品OK时间
				raesCloneObj.Lost_item_check_OK__c = null;
				// 排队备品检测OK时间
				raesCloneObj.Inspection_result_after_OK__c = null;
				// 排队备品预计出库时间Sys
				raesCloneObj.QueueShippmentDate__c = null;
				// 排队备品预计明细
				raesCloneObj.QueueDetail__c = null;
				// 再延长申请日期
				raesCloneObj.Re_Delay_Apply_Date__c = null;
				// 再申请的原备品
				raesCloneObj.Zsq_Rental_Apply__c = null;
				// 再申请的原备品一览
				raesCloneObj.zsqybpyl__c = null;
				// Canceled
				raesCloneObj.Canceled__c = null;
				// 原借出备品配套明细数
				raesCloneObj.Old_RetalFSetDetail_Cnt__c = null;
				// 新借出备品配套一览
				raesCloneObj.New_Rental_Apply_Equipment__c = null;
				// 延期时间
				raesCloneObj.Extend_Date__c = null;
				// 条件延期_21天
				raesCloneObj.Condition_X21_Days__c = null;
				// 条件延期_7天
				raesCloneObj.Condition_Seven_Days__c = null;
				// 条件延期_最新预定归还日
				raesCloneObj.Condition_Final_Reply_Days__c = null;
				// 日期延期_最新预定归还日
				raesCloneObj.Delay_Final_Reply_Days__c = null;
				// 排队(Sys)
				raesCloneObj.Pai_Dui_Jia__c = null;
				// 手动排队
				raesCloneObj.Manual_Queue__c = false;
				// NG重新分配
				raesCloneObj.NG_Select_Again__c = false;
				// 代替品重新分配（Text）
				raesCloneObj.Substitute_Select_Again_text__c = false;
				// 到货NG重新分配（Text）
				raesCloneObj.Received_NG_ReAssign_Text__c = false;
				// 代替品
				raesCloneObj.Substitute_flag__c = false;
				// 代替品不可
				raesCloneObj.Irreplaceable_flag__c = false;
				raesCloneList.add(raesCloneObj);
			}
			insert raesCloneList;

			// 一览明细Clone
			String fieldsNames2 = '';
			for (Schema.SObjectField sObjectField : Schema.getGlobalDescribe().get('Rental_Apply_Equipment_Set_Detail__c').getDescribe().fields.getMap().values()) {
			     fieldsNames2 += sObjectField.getDescribe().getName() + ',';
			}
			fieldsNames2 = fieldsNames2.removeEnd(',');
			List<Rental_Apply_Equipment_Set_Detail__c> raesdList = Database.query(
			      'SELECT ' + fieldsNames2 + ' FROM Rental_Apply_Equipment_Set_Detail__c Where Rental_Apply__c =: raId and Cancel_Select__c = false order by Rental_Apply_Equipment_Set__c'
			);

			List<Rental_Apply_Equipment_Set_Detail__c> raesdCloneList = new List<Rental_Apply_Equipment_Set_Detail__c>();
			Id idTemp = null;
			Integer indexNum = 0;
			for (Rental_Apply_Equipment_Set_Detail__c raesdObj : raesdList) {
				if (idTemp == null) idTemp = raesList[0].Id;
				Rental_Apply_Equipment_Set_Detail__c raesdCloneObj = raesdObj.clone(true);
				raesdCloneObj.Id = null;
				raesdCloneObj.UniqueKey__c = null;
				raesdCloneObj.Rental_Apply__c = raCloneObj.Id;
				if (idTemp != raesdObj.Rental_Apply_Equipment_Set__c) {
					indexNum ++;
					raesdCloneObj.Rental_Apply_Equipment_Set__c = raesCloneList[indexNum].Id;
					idTemp = raesList[indexNum].Id;
				} else {
					raesdCloneObj.Rental_Apply_Equipment_Set__c = raesCloneList[indexNum].Id;
				}
				// 分配时间
				raesdCloneObj.Select_Time__c  = now;
				// 出库指示时间(Sys)
				raesdCloneObj.Shipment_request_time2__c = now;
				// 下架时间(Sys)
				raesdCloneObj.StockDown_time__c = now;
				// 发货前-检测完毕时间(Sys)
				raesdCloneObj.Pre_inspection_time__c = now;
				// 发货运输单 dummy运输单
				raesdCloneObj.DeliverySlip__c = fdsList[0].Id;
				// 发货运输单(Text)
				raesdCloneObj.DeliverySlip_Text__c = fdsList[0].Id;
				// 备品中心出库时间
				raesdCloneObj.Shippment_loaner_time__c = now;
				// 修理
				raesdCloneObj.Repair__c = null;
				// 修理完毕（无修理单）
				raesdCloneObj.Repair_Finished__c = false;
				// 修理状态(文本)
				raesdCloneObj.Repair_Status_Text__c = null;
				// 待修理(Sys)
				raesdCloneObj.Dai_Xiu_Li_Jia__c = null;
				// 提交申请到备品出库时长  
				// TODO 如果之后 批准时间(申请提交时间)和 出库时间的赋值逻辑发生变化，设置的逻辑需要参照EquipmentSetShippmentReceived3Controller来设置
				raesdCloneObj.ApplyToShipmentWorkTime__c = 0;
				// 更新排队预计（文本）
				raesdCloneObj.UQueueShippmentDateText__c = null;
				// 被重新分配的借出备品配套一览明细
				raesdCloneObj.Canceled__c = null;
				// 被重新分配的Id
				raesdCloneObj.Canceled_Id__c = null;
				// 申请插队
				raesdCloneObj.Allow_Adjust_Queue_Flag__c = false;
				// 已插队
				raesdCloneObj.IsAdjust__c = false;
				// 排队日(首次)
				raesdCloneObj.Queue_Day_Text__c = null;
				// 排队时间(首次)
				raesdCloneObj.Queue_Time_Text__c = null;
				// 排队日
				raesdCloneObj.Queue_Day__c = null;
				// 排队No
				raesdCloneObj.Queue_Number__c = null;
				// 排队备注
				raesdCloneObj.Queue_Conment__c = null;
				// 排队时间
				raesdCloneObj.Queue_Time__c = null;
				// 下一次借用预计出库时间
				raesdCloneObj.NextShippmentDate__c = null;
				raesdCloneList.add(raesdCloneObj);
			}
			insert raesdCloneList;

			Map<Id, Id> assMap = new Map<Id, Id>();
			List<Rental_Apply_Equipment_Set__c> raesUpdList = new List<Rental_Apply_Equipment_Set__c>();
			List<Rental_Apply_Equipment_Set_Detail__c> raesdAssetList = [SELECT Id, Asset__c, Rental_Apply_Equipment_Set__c, Rental_Apply_Equipment_Set__r.Final_reply_day__c FROM Rental_Apply_Equipment_Set_Detail__c WHERE Cancel_Select__c = false and Is_Body__c = true and Rental_Apply__c =: raCloneObj.Id order by Rental_Apply_Equipment_Set__c];
			for (Rental_Apply_Equipment_Set_Detail__c raesdTemp : raesdAssetList) {
				assMap.put(raesdTemp.Asset__c, raesdTemp.Id);
				// 第一条备品配套明细的值需要回更新到一览上
				Rental_Apply_Equipment_Set__c raesTemp = new Rental_Apply_Equipment_Set__c();
				raesTemp.Id = raesdTemp.Rental_Apply_Equipment_Set__c;
				raesTemp.First_RAESD__c = raesdTemp.Id;
				// 最终借出备品回收期限(文本)
				raesTemp.Final_reply_day_text__c = raesdTemp.Rental_Apply_Equipment_Set__r.Final_reply_day__c;
				raesUpdList.add(raesTemp);
			}
			update raesUpdList;

			List<Asset> assList = new List<Asset>();
			// 原申请单一览明细
			for (Rental_Apply_Equipment_Set_Detail__c raesdObj : raesdList) {
				// 明细单未完成Text
				raesdObj.Detail_Not_Finish_Text__c = false;
				// 回寄后状态(文本)
				raesdObj.Return_Status_Text__c = '已回库';
				// 回寄运输单  dummy回寄单 a2q6D000000D8hcQAC
				raesdObj.Return_DeliverySlip__c = fdsReturnList[0].Id;
				// 回寄运输单(Text)
				raesdObj.Return_DeliverySlip_Text__c = raesdObj.Return_DeliverySlip__c;
				// 回寄时间(Sys)
				raesdObj.Asset_return_time__c = now;
				// 回收后-检测结果（最初）(Sys)
				raesdObj.Inspection_result_after__c = 'OK';
				// 欠品确认结果（最初）
				raesdObj.Check_lost_Item__c = 'OK';
				// 欠品确认者（最初）
				raesdObj.Lost_item_check_staff__c = raesdObj.Inspection_staff__c;
				// 回库确认者
				raesdObj.Return_wh_chenk_staff__c = raesdObj.StockDown_staff__c;
				// 回收后-检测人员（最初）
				raesdObj.Inspection_staff_After__c = raesdObj.Inspection_staff__c;
				// 欠品确认时间（最初）
				raesdObj.Lost_item_check_time__c = now;
				// 回库确认完毕时间
				raesdObj.Arrival_wh_time__c = now;
				// 消毒人员
				raesdObj.CDS_staff__c = raesdObj.Inspection_staff__c;
				// 回库确认
				raesdObj.Arrival_in_wh__c = true;
				// CDS完毕
				raesdObj.CDS_complete__c = true;
				// 回收后-检测完毕时间（最初）(Sys)
				raesdObj.After_Inspection_time__c = now;
				// CDS完毕时间
				raesdObj.CDS_complete_time__c = now;

				// 更新关联的保有设备
				if (raesdObj.Is_Body__c) {
					Asset ass = new Asset();
					ass.Id = raesdObj.Asset__c;
					// 上次备品申请借出明细历史
					ass.Pre_Reserve_RAES_Detail__c = raesdObj.Id;
					if (!assMap.isEmpty() && assMap.containsKey(raesdObj.Asset__c)) {
						// 最新备品申请借出明细
						ass.Last_Reserve_RAES_Detail__c = assMap.get(raesdObj.Asset__c);
					}
					assList.add(ass);
				}
			}

			update raesdList;
			update assList;

			// 原申请单一览
			for (Rental_Apply_Equipment_Set__c raesObj : raesList) {
				// 回寄时间
				raesObj.Asset_return_time__c = now;
			}
			update raesList;

			// 原申请单
			// 续借次数
			raObjTemp.Renewal_Num__c = 1;
			// 备品借出状态(Text)
			raObjTemp.RA_Status_Text__c = '完了';
			update raObjTemp;

			Oly_TriggerHandler.clearBypass('RentalApplyShareHandler');
			Oly_TriggerHandler.clearBypass('RentalHpDeptUpdHandler');

			PageReference ret = new PageReference('/' + raTemp.Id);
			return ret;
		} catch (Exception ex) {
			ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
			//ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getDmlMessage(0)));
			// rollback entire transaction
			Database.RollBack(sp);
			return null;
		}
	}

	// 保修用户Check
	public Boolean Purpose2Check1(Repair__c repairObj) {
		//保修用户满足下面3条中的任何一个即可：
		// 1、有无维修合同对象(SFDC)=无 And 无偿区别标志=2: 服务多年保修 And  修理设备的产品型号（MDM） = LTF-190-10-3D,LTF-S190-5,CYF-VHA,CYF-VA2,CYF-5A,LTF-S190-10,OER-AW,URF-V,URF-V2,URF-P6
		if(repairObj.Number_of_EffectiveContract__c == '无' 
			&& repairObj.NewProductGuaranteeObject__c == '2: 服务多年保修'
			&& (repairObj.Delivered_Product__r.Product2.Asset_Model_No__c == 'LTF-190-10-3D'
				|| repairObj.Delivered_Product__r.Product2.Asset_Model_No__c == 'LTF-S190-5'
				|| repairObj.Delivered_Product__r.Product2.Asset_Model_No__c == 'CYF-VHA'
				|| repairObj.Delivered_Product__r.Product2.Asset_Model_No__c == 'CYF-VA2'
				|| repairObj.Delivered_Product__r.Product2.Asset_Model_No__c == 'CYF-5A'
				|| repairObj.Delivered_Product__r.Product2.Asset_Model_No__c == 'LTF-S190-10'
				|| repairObj.Delivered_Product__r.Product2.Asset_Model_No__c == 'OER-AW'
				|| repairObj.Delivered_Product__r.Product2.Asset_Model_No__c == 'URF-V'
				|| repairObj.Delivered_Product__r.Product2.Asset_Model_No__c == 'URF-V2'
				|| repairObj.Delivered_Product__r.Product2.Asset_Model_No__c == 'URF-P6')
		){
			return true;
		}
		// 2、有无维修合同对象(SFDC)=有 And 无偿区别标志≠8: 市场多年保修
		else if (repairObj.Number_of_EffectiveContract__c == '有' 
			&& repairObj.NewProductGuaranteeObject__c != '8: 市场多年保修'){
			return true;
		}
		// 3、新合同备品确保提供（修理上的备品确保提供对象）=true
		else if (repairObj.EquipmentGuaranteeFlg_Asset__c) {
			return true;
		}

		return false;
	}

	// 市场多年保修Check
	public Boolean Purpose2Check2(Repair__c repairObj) {
		//市场多年保修用户需满足：新合同备品确保提供=false AND  无偿区别标志=8: 市场多年保修
		if(repairObj.EquipmentGuaranteeFlg_Asset__c == false && repairObj.NewProductGuaranteeObject__c == '8: 市场多年保修'){
			return true;
		}
		return false;
	}
}