package com.cftech.sys.security;

import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.util.Arrays;


public class AttrValidateUtil {
	/**
	 * 检测请求参数是否为空(填入无需校验的属性名称)
	 * true:不为空
	 * false：至少有一个校验参数为空
	 * */
	public static boolean myValidateNotUtil(Object obj,String...notValidateAttrName){
		Class<? extends Object> objclass=obj.getClass();
	       Field[] fs = objclass.getDeclaredFields();
	       String[] baseType = {"byte","short","int","long","char","boolean","float","double"};
 	       for(int i = 0 ; i < fs.length; i++){  
	           Field f = fs[i];  
	           f.setAccessible(true);
	           String attrName = f.getName();
	           if(Arrays.asList(notValidateAttrName).indexOf(attrName) == -1){
	        	   String type = f.getType().toString();
	        	   Object val = null;
				try {
					val = f.get(obj);
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}
	        	   if(type.endsWith("String") && val != null && StringUtils.isBlank(val.toString())){
	        		   return false;
	        	   }else if(Arrays.asList(baseType).indexOf(type) == -1 && val == null){
	        		  return false;
	        	   }
	           }else{
	        	   continue;
	           }
	       }  
 	      return true;  
	}
	
	/**
	 * 检测请求参数是否为空(填入要校验的属性名称)
	 * true:不为空
	 * false：至少有一个校验参数为空
	 * */
	public static boolean myValidateUtil(Object obj,String...validateAttrName){
		Class<? extends Object> objclass=obj.getClass();
	       Field[] fs = objclass.getDeclaredFields();
	       String[] baseType = {"byte","short","int","long","char","boolean","float","double"};
 	       for(int i = 0 ; i < fs.length; i++){  
	           Field f = fs[i];  
	           f.setAccessible(true);
	           String attrName = f.getName();
	           if(Arrays.asList(validateAttrName).indexOf(attrName) != -1){
	        	   String type = f.getType().toString();
	        	   Object val = null;
				try {
					val = f.get(obj);
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}
	        	   if(type.endsWith("String") && val != null && StringUtils.isBlank(val.toString())){
	        		   return false;
	        	   }else if(Arrays.asList(baseType).indexOf(type) == -1 && val == null){
	        		  return false;
	        	   }
	           }else{
	        	   continue;
	           }
	       }  
 	      return true;  
	}
}
