public class RentalApplyCancelController {

    /*--------- private ---------*/
    //private Id objId {get; set;}
    public Id objId {get; set;} //20210602 ljh update 1732
    /*--------- public ---------*/
    public Rental_Apply__c ra {get; set;}
    public String saveStatus {get; set;}
    // 20210823 ljh SFDC-C448KZ 修改到触发器  RentalApplyTriggerHandler cancelRa()
	//20210207 ljh  SWAG-BXVDPJ add start
	// public Map<String,String> cancleMap;
	// public static Integer FIELDMAX = 200;
	//20210207 ljh  SWAG-BXVDPJ add start
    /**
    * @description RentalApplyCancelController   Class的构造函数
    * @param objId 申请书ID
    **/
    public RentalApplyCancelController() {
        this.objId = ApexPages.currentPage().getParameters().get('objId');
        // 20210823 ljh SFDC-C448KZ 修改到触发器  RentalApplyTriggerHandler cancelRa()
		//20210207 ljh  SWAG-BXVDPJ add start
		// cancleMap = new Map<String,String>();
		// SS_Batch_Column_Mapping__c mpdMapping = SS_Batch_Column_Mapping__c.getValues('Rental_Apply_OPD_Cancle');         
		// Map<String,String> opdMap = new Map<String,String>();
		// for (Integer i = 101; i <= FIELDMAX; i++) {
		// 	String lpadI = ('00' + i).right(3);
		// 	String fromColumn = 'From_Column_' + lpadI + '__c';
		// 	String apiStr = String.valueOf(mpdMapping.get(fromColumn));
		// 	if (String.isBlank(apiStr) == false) {
		// 		String ssColumn = 'SS_Column_' + lpadI + '__c';
		// 		String ssApiStr = String.valueOf(mpdMapping.get(ssColumn));
		// 		if(apiStr.split(';').size()>=2){
		// 			if(apiStr.split(';')[1] != null && (apiStr.split(';')[1] == '主动取消'||apiStr.split(';')[1] == '被动取消')){
		// 				cancleMap.put(apiStr.split(';')[0],ssApiStr);
		// 			}					
		// 		}		   
		// 	}
		// }
		//20210207 ljh  SWAG-BXVDPJ add start
    }

    /**
    * @description RentalApplyCancelController 初始化方法
    **/
    public void init() {
        try{
			if (String.isBlank(this.objId)) {
				throw new ControllerUtil.myException('请设置备品借出申请的Id');
			}
			if (String.isNotBlank(this.objId)) {
				List<Rental_Apply__c> ras = getRas(this.objId);
				if (ras.size() == 0) {
					throw new ControllerUtil.myException('没有检索出备品借出申请');
				}
				this.ra = ras[0];
			}
        }
        catch (Exception e) {
            System.debug(e.getStackTraceString());
            ApexPages.addMessages(e);
            return;
        }
    }
    /**
    * @description 保存取消状态
    **/
    public void saveCancel() {
        Savepoint sp = Database.setSavepoint();
        try {
			// SWAG-BFV6G4 start
			StaticParameter.rentalApplyIsRunning = true;
			// SWAG-BFV6G4 end
			if (String.isBlank(this.ra.Cancel_Reason__c)) {
				throw new ControllerUtil.myException('请输入取消理由');
			}
			//20210207 ljh  SWAG-BXVDPJ update start
			if (String.isBlank(this.ra.Loaner_cancel_reason__c)) {
				throw new ControllerUtil.myException('请输入备品申请取消理由');
			}
			if (String.isBlank(this.ra.Loaner_cancel_request__c) && !String.isBlank(this.ra.Loaner_cancel_reason__c) && this.ra.Loaner_cancel_reason__c == '其他') {
				throw new ControllerUtil.myException('备品申请取消理由是【其他】请输入备品申请取消理由备注');
			}
			//20210207 ljh  SWAG-BXVDPJ update start
			// 20210823 ljh SFDC-C448KZ 修改到触发器  RentalApplyTriggerHandler cancelRa()
			// ----- start
           // SWAG-BUF6J5 20201117  you start
    //       	if((this.ra.Cancel_Reason__c=='被动取消' || this.ra.Cancel_Reason__c=='主动取消')&& !String.isBlank(this.ra.Loaner_cancel_reason__c)){
				// // SWAG-BWSBW3 2021-01-08 add by rentx start
				// Boolean flag = true;
				// // SWAG-BWSBW3 2021-01-08 add by rentx end 
				// List<CancelPostponePlan__c> cppList  = new List<CancelPostponePlan__c>();
				// List<Rental_Apply__c> raList = [SELECT Id,Status__c FROM Rental_Apply__c WHERE Id <> :objId and OPDPlan__c =:this.ra.OPDPlan__c and Status__c <>'取消' limit 1];
				// if(raList.size()==0){
				// 	system.debug('==opd计划状态'+this.ra.OPDPlan__r.Status__c+'opd担当是否离职'+this.ra.OPDPlan__r.StayOrNot__c);
				// 	if(this.ra.OPDPlan__r.Status__c !='取消'){
				// 		CancelPostponePlan__c cpp = new CancelPostponePlan__c();
				// 		cpp.CancelOPDPlan__c=this.ra.OPDPlan__c;//opdList[0].id;
				// 		cpp.RecordTypeId = '01210000000gQyL';
				// 		cpp.Status__c='取消成功';
				// 		//cpp.cancelReasonCombobox__c='备品不足';
				// 		//20210207 ljh  SWAG-BXVDPJ update start
				// 		if (this.ra.OPDPlan__r.OPDType__c == '学会') {
				// 			flag = false;
				// 		}else{	
				// 			cpp.cancelReasonCombobox__c = cancleMap.get(this.ra.Loaner_cancel_reason__c);
				// 		}
				// 		if(this.ra.Cancel_Reason__c=='被动取消'){
				// 			20210207 ljh  SWAG-BXVDPJ update start
				// 		} else {
				// 			//如果担当为 '已离职' 并且OPD计划来源是 '学会' OPD计划不自动取消 ->不进那个handler就可以了  SWAG-BWSBW3 2021-01-08 add by rentx start
				// 			// if (this.ra.OPDPlan__r.StayOrNot__c == '已离职' && this.ra.OPDPlan__r.OPDType__c == '学会') {
				// 			//flag = false;
				// 			//}
				// 			//如果担当为 '已离职' 并且OPD计划来源是 '学会' OPD计划不自动取消 ->不进那个handler就可以了  SWAG-BWSBW3 2021-01-08 add by rentx end
				// 			//update by yc 20210121 start 不管担当是否离职 ，都要排除学会的
				// 			if (this.ra.OPDPlan__r.OPDType__c == '学会') {
				// 				flag = false;
				// 			} 
				// 			//update by yc 20210121 end
				// 			if(this.ra.OPDPlan__r.StayOrNot__c=='已离职'){
				// 				cpp.cancelReasonCombobox__c='担当离职';  
				// 			}else{
				// 				cpp.cancelReasonCombobox__c='取消OPD计划';
				// 			}
				// 		}
				// 		//20210207 ljh  SWAG-BXVDPJ update end
				// 		//System.debug('cpp.cancelReasonCombobox__c'+cpp.cancelReasonCombobox__c);
				// 		cpp.if_HaveRental_Apply__c=true;//打标机是防止循环更新 opd计划
				// 		//SWAG-BWSBW3 2021-01-08 add by rentx start
				// 		if (flag) {
				// 			cppList.add(cpp);
				// 		}
				// 		// cppList.add(cpp);
				// 		//SWAG-BWSBW3 2021-01-08 add by rentx start
				// 	}  
				// }
    //             if(cppList!=null){
    //                 insert cppList;
    //             }
    //       	}
			// ----end
          	// SWAG-BUF6J5 20201117  you end
			/**
			 取消这一部分，备品取消之前先调回审批 （有一个验证规则在限制）
			this.ra.if_HaveOPDPlanCan__c = true;//打标记 为了撤回审批得时候更新状态 为取消
			if(this.ra.Status__c=='申请中'){
				List<Approval.ProcessWorkitemRequest> requests = new List<Approval.ProcessWorkitemRequest> ();
				Map<ID,ProcessInstance> piMap = New Map<ID,ProcessInstance>([Select Id from ProcessInstance where TargetObjectId =:objId]);
				for(ProcessInstanceWorkItem wi : [Select Id from ProcessInstanceWorkItem where ProcessInstanceId IN :piMap.keySet()]){
					Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
					req2.setAction('Removed');
					req2.setWorkitemId(wi.Id);
					requests.add(req2); 

				}

				if (requests.size() > 0) {
					Approval.ProcessResult[] processResults = null;
					processResults = Approval.process(requests, true);
					system.debug('==执行结果=='+processResults);
				}
			}
			**/
			//System.debug('this.ra:'+this.ra);
			//20210207 ljh  SWAG-BXVDPJ update start
			if(this.ra.Loaner_cancel_reason__c != null){
				if(this.ra.Loaner_cancel_reason__c != '其他'){
					this.ra.Loaner_cancel_request__c = this.ra.Loaner_cancel_reason__c;
				}
			}
			//20210207 ljh  SWAG-BXVDPJ update end
			FixtureUtil.withoutUpdate(new Rental_Apply__c[]{this.ra});
			String statusMessage;
			statusMessage = RentalApplyWebService.RentalApplyCancel(objId, false);
			if (statusMessage != '1') {
				throw new ControllerUtil.myException(statusMessage);
			}
			saveStatus = 'ok';
        }
        catch (Exception e) {
            Database.rollback(sp);
            System.debug(e.getStackTraceString());
            ApexPages.addMessages(e);
            saveStatus = 'ng';
            return;
        }
    }

    /**
    * @description 备品借出申请取得
    **/
    private List<Rental_Apply__c> getRas(Id raId) {
       return [SELECT Id,
                      Name,
                      OwnerId,
                      Status__c,
                      RA_Status__c,
                      Cancel_Reason__c,
                      Loaner_cancel_request__c,
					  Loaner_cancel_reason__c,//20210207 ljh  SWAG-BXVDPJ add
                      //add by rentx 2021-01-08
                      OPDPlan__c,
                      OPDPlan__r.Status__c,
                      OPDPlan__r.StayOrNot__c,
                      OPDPlan__r.OPDType__c 
                      //add by rentx 2021-01-08
                      
                 FROM Rental_Apply__c
                WHERE Id = :raId];
    }
}