package com.huigou.uasp.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.*;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;


//import org.apache.commons.collections.MapUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import com.huigou.cache.DictUtil;
import com.huigou.uasp.builder.vo.ParamFormVO;
import com.huigou.uasp.builder.vo.PubDataRecord;
import com.huigou.uasp.builder.vo.SeleListCustomVO;


public class Utils {
	
	 private static String cols="3";//每行显示的标签个数
	 private static String labelCols="2"; //标签名称占列数
	 private static String fieldCols="2"; //标签值占列数
	 private static String textAreaRows="3"; //textArea占行数
	 
     //fields=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,fields);//转成下划线
     //fields= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,fields); //转成驼峰法
	 
		public static String createUuid() {
			UUID u = UUID.randomUUID();
			return u.toString().replace("-", "").toUpperCase();
		}
		
	//对象属性复制
		/*
		 * lxh
		 */
			 public static void CopyBean(Object source, Object dest) {  
				 try{  
				       //获取属性  
				       BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), java.lang.Object.class);  
				       PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();  
				          
				        BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(), java.lang.Object.class);  
				         PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();  
				          
				       
				            for(int i=0;i<sourceProperty.length;i++){  
				                  
				                 for(int j=0;j<destProperty.length;j++){  
				                      
				                    if(sourceProperty[i].getName().equals(destProperty[j].getName())){  
				                        destProperty[j].getWriteMethod().invoke(dest, sourceProperty[i].getReadMethod().invoke(source));  
				                         break;                    
				                    }  
				                }  
				            }  
				        }catch(Exception e){  
				        	//logger.error("属性复制失败:"+e.getMessage());
				        	e.printStackTrace();
				        }  
			  }  
		
	//首字母转大写
 	public  static String toUpperCaseFirstOne(String s){
 		if ("".equals(s)){
 			return s;
 		}
		if(Character.isUpperCase(s.charAt(0)))
		    return s;
		  else
		    return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
		}
 	
 	//首字母转小写
 	 public  static String toLowerCaseFirstOne(String s){
 		   if ("".equals(s)){
 		      return s;
 		   } 
 			if(Character.isLowerCase(s.charAt(0)))
 			    return s;
 			  else
 			    return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
 			}
	
 	   /*
      * 生成java文件
      * parameter：
      *            fileName：  完整文件名，包括路径
      *            code ：java代码  
      */
 	public static String generateJava(String fileName,StringBuffer code){
 		
 		PrintWriter pw = null;
 		FileInputStream fis = null;
 		InputStreamReader isr = null;
 		BufferedReader br=null;
 		String filein = code.toString() + "\r\n";
         String temp="";
         String backStr = "";
         
 		try {
 			// 文件路径
 			File file = new File(fileName);
 			if (file.exists()){
 				file.delete();
 			}
 			file.createNewFile();
 			
 			// 将文件读入输入流
 			fis = new FileInputStream(file);
 			isr = new InputStreamReader(fis);
 			br = new BufferedReader(isr);
 			StringBuffer buf = new StringBuffer();
  
 			// 保存该文件原有的内容
 			for (int j = 1; (temp = br.readLine()) != null; j++) {
 				buf = buf.append(temp);
 				// System.getProperty("line.separator")
 				// 行与行之间的分隔符 相当于“\n”
 				buf = buf.append(System.getProperty("line.separator"));
 			}
 			buf.append(filein);
 			pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8")));
 			pw.write(buf.toString().toCharArray());
 			pw.flush();
 			
 		} catch (Exception e1) {
 			 backStr=e1.getMessage();
 			 e1.printStackTrace();;
 		} finally{
 			try {
 				br.close();
 			} catch (IOException e) {
 				 backStr=e.getMessage();
 				e.printStackTrace();
 			}
 			pw.close();
 		}
 		return backStr;	
 	}
 	/*
 	 *  生成Class文件
 	 *  packName：(形如：class/com/pm )
 	 *  */
 	  public static String generateClass(String packName,String clsName){
 			/*  成功生成class对象*/
 		  String backStr="";
 		  String path =packName;
 				  // getClass().getResource("/").getPath();  //运行路径classes
 			System.out.println("generateClass path==="+path);
 		  String libPath=path.substring(1,path.length()-8)+"lib";
 			File file = new File(path+packName+"/"+clsName+".class");
 		  if (file.exists()){
 		     file.delete();
 		  }
 		  String byi="javac -g  -encoding UTF-8 "+path+packName+"/"+clsName+".java"
  			+" -classpath "+libPath+"/*";
  			System.out.println("编译文件==="+path+packName+"/"+clsName+".java");
  			Process process=null;
 			try {
 				process = Runtime.getRuntime().exec(byi);
 			
  			InputStream errorStream = process.getErrorStream();
  			InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
  			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  			String line = null;
  			while ((line=bufferedReader.readLine()) != null){
  				System.out.println(line);
  			}
  			int exitVal = process.waitFor();
  			// System.out.println("Process exitValue: " + exitVal);
 			 if (exitVal!=0){
 			      System.out.println("编译java文件失败！");
 		     }
 			} catch (Exception e) {
 				backStr=e.getMessage();
 				e.printStackTrace();
 			}
 			return backStr;
 	  }
 	  
 	  
 	 /*
 	  *数据字段属性转换
 	  *param:字段列表，实体对象 
 	  *displayType:1、 如果是数据字典则显示名称  2、返回数据字典真实值
 	  */
 	
 	public  static List <Map<String, Object>> dataFieldTransfer(List <Map<String, Object>>fieldList,List<Map<String,Object>> oldRows){

 	    List <Map<String, Object>>newRows=new ArrayList<Map<String, Object>>();
 	    String fieldCode="",fieldVal="",displayVal="";
 	     Map <String, Object>mapField=null;
 		for (int i=0;i<oldRows.size();i++){
 			Map <String, Object>mapRow=oldRows.get(i);
 		   for (int j=0;j<fieldList.size();j++){
 				mapField=(Map<String, Object>)fieldList.get(j);
 				fieldCode=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,mapField.get("fieldCode").toString());//转成驼峰法
 				fieldVal=mapRow.get(fieldCode).toString();	
 				mapRow.remove(fieldCode);
 		
 				if (mapField.get("dictCode")!=null&&!"".equals(mapField.get("dictCode"))){  //来源数据字典的 
 					displayVal=DictUtil.getDictionaryDetailText(mapField.get("dictCode").toString(),fieldVal);
 					mapRow.put("field"+j,displayVal);
 					mapRow.put("field"+j+"_dictcode",fieldVal);
 				} else if (Constant.CHECKBOX_TAG.equals(mapField.get("fieldTag"))
 						||Constant.RADIOS_TAG.equals(mapField.get("fieldTag"))){
 					fieldVal=getDataSourceValue(mapField,fieldVal);
 					mapRow.put("field"+j,fieldVal);
 				} else {
 				   mapRow.put("field"+j,fieldVal);
 				}

 		   }
 		   newRows.add(mapRow);
 		}
 		return newRows;
 	}
 	
 	//获取checkbox  radio组件的显示值 
 	public  static String getDataSourceValue(Map <String, Object> map,String fieldVal){
 		  String []fval=fieldVal.split(",");
		  String fvals="",displayVal="";
 		if (Constant.DATASOURCETYPE_DICT.equals(map.get("dataSourceType"))){ //数据字典
				for (int u=0;u<fval.length;u++){
					displayVal=DictUtil.getDictionaryDetailText(map.get("dataSource").toString(),fval[u]);
					if (!"".equals(fvals)){
					   fvals+=",";
					}
				  fvals+=displayVal;
				}
		} else 	if (Constant.DATASOURCETYPE_FIX.equals(map.get("dataSourceType"))){  //自定义数据
	
			 Map <String,Object>mapval = (Map<String,Object>) JSON.parse(map.get("dataSource").toString());
			 for (int u=0;u<fval.length;u++){
				  displayVal=mapval.get(fval[u]).toString();
			    if (!"".equals(fvals)){
				   fvals+=",";
				}
			    fvals+=displayVal;
			}
		}
 		return fvals;
 	}
 	
 	/**
 	 * 数据值对象转换
 	 * param:字段、实体对象
 	 * */
 	public static Map<String, Object> dataValueTransfer(List <Map<String, Object>>fieldList,PubDataRecord entity){
 	    // Class<?> clz = entity.getClass();
 	     Map <String, Object>map=new HashMap<String, Object>();
 	     Map<String, Object> mapfield=new HashMap<String, Object>();
 	   try {
 	     //Field[] field = clz.getDeclaredFields();
  	    // String columns="",
 		 String vals="";
  	     Object obj=null;
  	     
 	    for (int i = 0; i < fieldList.size(); i++) {
 		
 	   	    mapfield=(Map<String, Object>)fieldList.get(i);
 	       // mapfield.get("fieldCode").toString();
 	  	   //  columns+=mapfield.get("fieldCode").toString();
    	   //if (i<fieldList.size()-1)
 			//  columns+=";";  //因转成json时 使用的逗号，故此处把逗号变成;
 	    	
 	        obj=ReflectionUtil.invokeGet(entity,"field"+Integer.toString(i));
 	    
 	       if (obj!=null&&!"".equals(obj.toString())){
 	    	  vals=obj.toString();
 	    	  //如果是新增  而且字段是日期格式 则值增加to_date
 	 	      if (StringUtils.isEmpty(entity.getId())&&"date".equals(mapfield.get("fieldType").toString())){   
 	 	    	 vals="to_date('"+vals+"','yyyy-mm-dd')";
 	 	      } else if ("date".equals(mapfield.get("fieldType").toString())){
 	 	    	 vals=vals.substring(0,10);
 	 	      }
 			  map.put(mapfield.get("fieldCode").toString(),vals);
 	      }
 	    }
 	     // map.put("columns",columns);
 	    }catch(Exception ex){
 	    	ex.printStackTrace();
 	    }
 	   return map;
 	}
 	
 	//获取字段名称 、显示名称等 
 	//fieldStyle 从List中的返回的字段
 	public static String getDataFields(List <Map<String, Object>>fieldList,String fieldStyle){
 		 String fields="";
 		 Map<String, Object> mapData=new HashMap<String, Object>();
 		for (int i=0;i<fieldList.size();i++){
 			mapData=(Map<String, Object>)fieldList.get(i);
 			fields+=mapData.get(fieldStyle).toString();
 			if (i<fieldList.size()-1)
 				fields+=",";
 		}
 		return fields;
 	}
 	

 	//获取字段 添加别名的 
 	 	public static String getDataFieldsByAlias(List <Map<String, Object>>fieldList){
 	 		 String fields="";
 	 		 Map<String, Object> mapData=new HashMap<String, Object>();
 	 		for (int i=0;i<fieldList.size();i++){
 	 			mapData=(Map<String, Object>)fieldList.get(i);
 	 			fields+=mapData.get("fieldCode").toString()+" field"+Integer.toString(i);
 	 			if (i<fieldList.size()-1)
 	 				fields+=",";
 	 		}
 	 		return fields;
 	 	}
 	
 	  //获取字段名称 、显示名称等 
 	 	//fieldStyle 从List中的返回的字段
 	 	public static String getDataFieldsByMult(List <Map<String, Object>>fieldList){
 	 			  String fields="",multFields="";
		 		  Map<String, Object> mapData=new HashMap<String, Object>();
		 		for (int i=0;i<fieldList.size();i++){
		 			mapData=(Map<String, Object>)fieldList.get(i);
		 		   if ("0".equals(mapData.get("multiValue").toString())){
		 			 fields+=mapData.get("fieldCode").toString();
		 		   } else {
		 			 multFields+=mapData.get("attrCode").toString()+":";
		 			 multFields+=mapData.get("fieldCode").toString();
		 		   }
		 		   if (!"".equals(fields)&&!fields.endsWith(",")){
		 			  fields+=",";
		 		   }
		 		   if (!"".equals(multFields)&&!fields.endsWith(",")){
		 			  multFields+=",";
		 		   }
		 		 }
		 	    if (!"".equals(fields)){
		 		  fields=fields.substring(0,fields.length()-1);
		 		}
		 	    if (!"".equals(multFields)) {
		 		  multFields=multFields.substring(0,multFields.length()-1);
		 	    }
 	 		return fields+";"+multFields;
 	 	}
 	 	
 	//获取查询条件的字段 
 	public static String getSearchDataFields(List <Map<String, Object>>fieldList){
 		 String searchField="";
 		 Map<String, Object> mapData=new HashMap<String, Object>();
 		for (int i=0;i<fieldList.size();i++){
 			mapData=(Map<String, Object>)fieldList.get(i);
 		 if (mapData.get("searchField")!=null&&"1".equals(mapData.get("searchField").toString())){
 			 searchField+=mapData.get("fieldCode").toString();
 			if (i<fieldList.size()-1)
 				searchField+=",";
 		 }
 		}
 		return searchField;
 	}
 	


 	
 	//组合字段的相关属性
 	 public static ParamFormVO  composeAttributes(List <Map<String, Object>> srclist,String tableName,String tableDesc,List <String>hiddenFields){
 		 
 			String []fieldEns=new String[srclist.size()];
 			String []fieldChs=new String[srclist.size()];
 			String []realFieldEns=new String[srclist.size()];
 			String []fieldTags=new String[srclist.size()];
 			String []fieldTypes=new String[srclist.size()];
 			
 			String []mustinputFields=new String[srclist.size()];
 		
 		    String []validatorTypes=new String[srclist.size()];
 		    String []dataSourceTypes=new String[srclist.size()];
 		    String []dataSources=new String[srclist.size()];
 		    String []codeRuleIds=new String[srclist.size()];
 		    
 		    String []maxLengths=new String[srclist.size()];
 		    String []defaultOperations=new String[srclist.size()];
 		    
 		    String []cssStyles=new String[srclist.size()];
 		    String []checkFunctions=new String[srclist.size()];
 		    String []jsFunctions=new String[srclist.size()];
			    //
 		    String []searchFields=new String[srclist.size()];
 		    
 		    String displayFieldStr="",displayFieldNameStr="",displayFieldTypeStr="";
 		    Map<String, Object> map=null;
 		    
 		 for (int i=0;i<srclist.size();i++){
 			
 				 map=(Map<String, Object>)srclist.get(i);
 				fieldEns[i]=map.get("fieldCode").toString();
             realFieldEns[i]=fieldEns[i];
 				fieldEns[i]="field"+i;
 				fieldChs[i]=map.get("fieldName").toString();
 				if (map.get("fieldDecimal")!=null&&!"".equals(map.get("fieldDecimal").toString())
 						&&Integer.parseInt(map.get("fieldDecimal").toString())>0){
 					fieldTypes[i]=map.get("fieldType").toString()+"2"; //金额类型 类型用number2表示
 				}else {
 				    fieldTypes[i]=map.get("fieldType").toString();
 				}
 				
 				fieldTags[i]=map.get("fieldTag").toString();
 				mustinputFields[i]=map.get("mustInput").toString();
 				validatorTypes[i]=map.get("dataFormat").toString();
 				
 				//showfieldsLengths[i]=map.get("fieldLength").toString();
 				codeRuleIds[i]=map.get("codeRuleId").toString();
 				
 				maxLengths[i]=(map.get("maxLength")!=null&&!"".equals(map.get("maxLength").toString()))?map.get("maxLength").toString():map.get("fieldLength").toString();

			    defaultOperations[i]=(map.get("defaultOperation")!=null&&!"".equals(map.get("defaultOperation").toString()))?map.get("defaultOperation").toString():"readwrite";
 				
 				cssStyles[i]=map.get("cssStyle")!=null?map.get("cssStyle").toString():"";
 				checkFunctions[i]=map.get("checkFunction")!=null?map.get("checkFunction").toString():"";
 				jsFunctions[i]=map.get("jsFunction")!=null?map.get("jsFunction").toString():"";
 	 				
 			  if (map.get("dataSourceType")!=null&&!"".equals(map.get("dataSourceType").toString())){
 				   dataSourceTypes[i]=map.get("dataSourceType").toString();
 				   dataSources[i]=map.get("dataSource").toString();
 				if (map.get("dictCode")!=null&&!"".equals(map.get("dictCode").toString())){  //配置了数据字典的  优先使用字典
 				   dataSourceTypes[i]=Constant.DATASOURCETYPE_DICT;
 				   dataSources[i]=map.get("dictCode").toString();
 				 }
 				 // if (!"select".equals(fieldTags[i])){ //配置数据来源的 必须是下拉选择框  
  				//	 fieldTags[i]="select";
  				//  }
 			  }
 				//查询字段及列表字段 
 				searchFields[i]=map.get("searchField").toString();
 				if ("1".equals(map.get("displayListing").toString())){
 					if (!"".equals(displayFieldStr)){
 						displayFieldStr+=",";
 						displayFieldNameStr+=",";
 						displayFieldTypeStr+=",";
 					}
 					displayFieldStr+=fieldEns[i];
 				    displayFieldNameStr+=fieldChs[i];
 				    displayFieldTypeStr+=fieldTypes[i];
 				}
 			}
 		 
 		
 			ParamFormVO paraForm=new ParamFormVO();
 			paraForm.setTableName(tableName);
 			paraForm.setFormName(tableDesc);
 			paraForm.setFieldEns(fieldEns);
 			paraForm.setFieldChs(fieldChs);
 			paraForm.setFieldTags(fieldTags);
 			paraForm.setRealFieldEns(realFieldEns);
 			
 			paraForm.setCssStyle(cssStyles);  //样式
 			paraForm.setCheckFunction(checkFunctions);  //DB效验函数
 			paraForm.setJsFunction(jsFunctions);  //JS效验函数 
 			paraForm.setFieldsLengths(maxLengths);
 			paraForm.setDefaultOperation(defaultOperations);
 			
 			paraForm.setCodeRuleId(codeRuleIds);  //编码规则
 			
 			paraForm.setExistAttachment(0);
 			paraForm.setPagedatailCols(cols);
 			paraForm.setLabelCols(Integer.parseInt(labelCols)); //标签名称占列数
 			paraForm.setFieldCols(Integer.parseInt(fieldCols)); //标签值占列数
 			paraForm.setTextAreaRows(Integer.parseInt(textAreaRows)); //textArea占行数
 			
 			paraForm.setDataSources(dataSources);
 			paraForm.setDataSourceTypes(dataSourceTypes);
 			
 			paraForm.setMustinputFields(mustinputFields);
 
 			paraForm.setValidatorTypes(validatorTypes);
 			 
 			paraForm.setHiddenFields(hiddenFields);
 			
 			//主页查询字段  列表字段 
 			paraForm.setSearchFields(searchFields);
 			paraForm.setDisplayFields(displayFieldStr.split(","));
 			paraForm.setDisplayFieldnames(displayFieldNameStr.split(","));
 			paraForm.setDisplayFieldTypes(displayFieldTypeStr.split(","));
 			
 		   return paraForm;
 	   }
 	  
 	  //生成文件
 	  public static String generateFile(String fileName,StringBuffer sb){
 		PrintWriter pw = null;
 		String filein = sb.toString() + "\r\n";
 		String backStr = "";

 		try {
 			// 文件路径
 			File file = new File(fileName);
 			if (file.exists()) {
 				file.delete();
 			}
 			file.createNewFile();

 			StringBuffer buf = new StringBuffer();
 			buf.append(filein);

 			pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8")));
 			pw.write(buf.toString().toCharArray());
 			pw.flush();

 		} catch (Exception e1) {
 	
 			backStr=e1.getMessage();
 			e1.printStackTrace();
 			
 		} finally {
 	
 			pw.close();
 		}
 		return backStr;
 	  }
 	  
 //*****************************formBuilder**************************
 	 public static String[] maches(String str , String regex) {
 		
 		Pattern p = Pattern.compile(regex);
 		Matcher m = p.matcher(str);
 		List<String> list = new ArrayList<String>();
 		
 		while(m.find()) {
 			 list.add(m.group());
 			 
 		}
 		
 		 
 		
 		return list.toArray(new String[0]);
 	}
 	
 	public static JSONObject parseInputAttrs(String str) {
 		
 		 String preg_attr ="(\\w+)=\"(.*?)\"" ;
 		 
 		 List<String[]> list = machesGroup(str, preg_attr);
 		 JSONObject object = new JSONObject();
 		 for(String[] ss : list) {
 			 object.put(ss[0], ss[1]);
 		 }
 		return object ;
 	}
 	
 	public static <T> T parseInputAttrsT(String str , Class<T> t) {
 		 JSONObject object = parseInputAttrs(str);
 		// JSON json=JSON.toJSONString(str);
 		 return JSON.parseObject(object.toJSONString(),t);
 		// return object.toJavaObject(object, t);
 				 //object.toJavaObject(t);
 		 
 	}

 	public static List<String[]> machesGroup(String str , String regex) {
 		
 		Pattern p = Pattern.compile(regex);
 		Matcher m = p.matcher(str);
 		List<String[]> list = new ArrayList<String[]>();
 		
 		while(m.find()) {
 			
 			int cnt = m.groupCount();
 			String[] ss = new String[cnt];
 			for(int i = 0 ; i< cnt ; i++) {
 				ss[i] = (m.group(i + 1));
 			}
 			
 			list.add(ss);
 		}
 		
 		 
 		
 		return list ;
 	}
 	
 	  
    //获取检索SQL中定义的隐藏字段
    public static List<String>  getHiddenFields(SeleListCustomVO customVo){
    	List<String> hiddenField=new ArrayList<String>();
     if (customVo.getBackFields()!=null){
    	String []backField=customVo.getBackFields().split(",");
    	String []fieldType=customVo.getFieldTypes().split(",");

    	Stream.iterate(0, i -> i + 1).limit(backField.length)
				 .filter(index->"1".equals(fieldType[index])) //1表示隐藏
				 .forEach(index -> {hiddenField.add(backField[index]);
				 });
    	/*for (int u=0;u<backField.length;u++){
     		if ("1".equals(fieldType[u])){  //1表示隐藏 
     			hiddenField.add(backField[u]);
     		}
    	}*/
     }
    	return hiddenField;
    }
    
 	 
    
    //组装主表单字段效验事件 
  	public static void composeMainFormCheckFunction(ParamFormVO paraForm,StringBuffer sb){
  		String []chkFuncions=paraForm.getCheckFunction();
  		String []jsFuncions=paraForm.getJsFunction();
  		String []fields=paraForm.getDisplayFields();
  		String []realFields=paraForm.getRealFieldEns();
  	   sb.append(" function bindEvent(){ ").append(Constant.SYSMBOL_LINE);
  	      //DB 函数
		 for (int u=0;u<chkFuncions.length;u++){
  		   if (!"".equals(chkFuncions[u])){
  			   sb.append("    $('#");
//			   if (paraForm.getIsform() == 0) {  //是代码生成器 获取真实字段名称
//				   sb.append(realFields[u]);
//			   } else {
//				   sb.append(fields[u]);
//			   }
			   sb.append(getRealField(paraForm.getIsform(),realFields[u],fields[u]));
  			   sb.append("').on('mouseout',checkFunc_").append(u).append("); ");
  			   sb.append("	  $('#");
			  // if (paraForm.getIsform() == 0) {  //是代码生成器 获取真实字段名称
				//   sb.append(realFields[u]);
			 //  } else {
				//   sb.append(fields[u]);
			  // }
			   sb.append(getRealField(paraForm.getIsform(),realFields[u],fields[u]));
  			   sb.append("').bind('blur',checkFunc_").append(u).append("); ");
  		   }
  		 }
  		 //JS函数 
  		 for (int x=0;x<jsFuncions.length;x++){
   		   if (!"".equals(jsFuncions[x])&&("".equals(chkFuncions[x]))){
   			   sb.append("    $('#");
			   //if (paraForm.getIsform() == 0) {  //是代码生成器 获取真实字段名称
				//   sb.append(realFields[x]);
			  // } else {
			//sb.append(fields[x]);
			  // }
			   sb.append(getRealField(paraForm.getIsform(),realFields[x],fields[x]));
			   sb.append("').on('mouseout',jsFunc_").append(x).append("); ");
   			   sb.append("	  $('#");
			   //if (paraForm.getIsform() == 0) {  //是代码生成器 获取真实字段名称
				//   sb.append(realFields[x]);
			   //}else {
   			   //   sb.append(fields[x]);
			   //}
			   sb.append(getRealField(paraForm.getIsform(),realFields[x],fields[x]));
			   sb.append("').bind('blur',jsFunc_").append(x).append("); ");
   		   }
   		 }
  		  sb.append(" } ").append(Constant.SYSMBOL_LINE);
  		  sb.append("");
  		
  		 for (int u=0;u<chkFuncions.length;u++){
  		    if (!"".equals(chkFuncions[u])){
  		       sb.append(" function  checkFunc_").append(u).append("(){ ").append(Constant.SYSMBOL_LINE);
  			    //JS函数 存在
   	  		    if (!"".equals(jsFuncions[u])){
   	  			  sb.append(" jsFunc_").append(u).append("();").append(Constant.SYSMBOL_LINE);
   	   		   }
  		        checkMainFormMethod(chkFuncions[u],paraForm,u,sb);
  			 }
  		  }
  		 
  		 // JS函数 
  		 String jsfunction="";
  		 for (int u=0;u<jsFuncions.length;u++){
  		   if (!"".equals(jsFuncions[u])){
  			   //字段替换 将 #name 替换成  #field...
  			 jsfunction=jsFuncions[u];
  			// jsfunction=jsfunction.replaceAll("#"+realFields[u],"#"+fields[u]);
  			 sb.append(" function  jsFunc_").append(u).append("(){ ").append(Constant.SYSMBOL_LINE);
  			 for (int x=0;x<realFields.length;x++){  //遍历所有主表字段 
  				jsfunction=jsfunction.replaceAll("#"+realFields[x],"#"+fields[x]);
  			 }
  			 sb.append(jsfunction).append(Constant.SYSMBOL_LINE);
  			 sb.append(" } ").append(Constant.SYSMBOL_LINE);
  		   }
  		 }
  		 
  	}
  	
  	 //组装明细列表字段效验事件 
  	public static void composeDetailCheckFunction(ParamFormVO paraForm,String []mainTableFields,StringBuffer sb) throws Exception {
  		String []chkFuncions=paraForm.getCheckFunction();
  		String []jsFuncions=paraForm.getJsFunction();
   		String []fields=paraForm.getDisplayFields();
  		String []realFields=paraForm.getRealFieldEns();
  		 sb.append("   function bindEvent(grid){ ");
 		 String gridName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraForm.getTableName())+"GridManager";
 		 //DB函数
  		for (int u=0;u<chkFuncions.length;u++){
  		   if (!"".equals(chkFuncions[u])){
  			   
              sb.append("	var datas=grid.record; var cols = grid.column;");
              
              sb.append(" if (cols.name ==\"");
			  // if (paraForm.getIsform()==0) {  //是代码生成器 获取真实字段名称
				//   sb.append(realFields[u]);
			   //} else {
				//   sb.append(fields[u]);
			  // }
			   sb.append(getRealField(paraForm.getIsform(),realFields[u],fields[u]));
               sb.append("\") { ");
               
              checkDetailMethod(gridName,chkFuncions[u],paraForm,mainTableFields,u,sb);
              
              sb.append("  	 }  ");
  		  }
  		}
  		 // JS函数   如果存在主表字段的 以#开头的   明细表  
  		  String jsfunction="";
 		 for (int u=0;u<jsFuncions.length;u++){
 		   if (!"".equals(jsFuncions[u])){
 			   //字段替换 将 #name 替换成  #field...
 			 jsfunction=jsFuncions[u];
 			 //jsfunction.indexOf("#[");
 			// jsfunction=jsfunction.replaceAll("#"+realFields[u],"#"+fields[u]);
			 if (paraForm.getIsform() == 1) {  //是表单生成器 才替换
				 for (int x = 0; x < mainTableFields.length; x++) {  //遍历所有主表字段
					 jsfunction = jsfunction.replaceAll("#" + mainTableFields[x], "#field" + x);
				 }

				 //明细表字段的获取 grid.record.开头的
				 for (int x = 0; x < realFields.length; x++) {  //遍历所有明细表字段
					 if (jsfunction.indexOf("grid.record." + realFields[x]) > -1) {
						 jsfunction = jsfunction.replace("grid.record." + realFields[x], "grid.record." + fields[x]);
					 }
					 //存在替换 .updateCell('field2'
					 if (jsfunction.indexOf(".updateCell('" + realFields[x] + "'") > -1) {
						 jsfunction = jsfunction.replace(".updateCell('" + realFields[x] + "'", ".updateCell('" + fields[x] + "'");
					 }
					 //存在  grid.column.name=='key') 替换 field...
					 if (jsfunction.indexOf("grid.column.name=='" + realFields[x] + "'") > -1) {
						 jsfunction = jsfunction.replace("grid.column.name=='" + realFields[x] + "'", "grid.column.name=='" + fields[x] + "'");
					 }
				 }
			 }
 			 sb.append(jsfunction).append(Constant.SYSMBOL_LINE);
 			   
 		   }
 		 }
  		
  		
  	   sb.append("  	 }  ");
  	}
 
	 //效验主表单的方法定义  
  	 /* 效验函数(函数名称、参数字段、返回字段以冒号分隔,参数字段和返回字段以逗号）
  	  */
   	public static void checkMainFormMethod(String chkFuncions,ParamFormVO paraForm,int u,StringBuffer sb){
  		
  	    	 String []fields=paraForm.getDisplayFields(); //转换后的字段
  		     String []realfields=paraForm.getRealFieldEns();
  		     String []checkfuncs=chkFuncions.split(":");
			 String []paraFields=null;
			 String []backFields=null;
			 if (checkfuncs.length>1) { //存在参数字段 
			   paraFields=checkfuncs[1].split(",");
			 }
			 if (checkfuncs.length>2) { //存在返回字段 
			   backFields=checkfuncs[2].split(",");
			 }
  			 sb.append("    var currVal=$('#");
		    /*if (paraForm.getIsform()==0) {  //是代码生成器 获取真实字段名称
		    	sb.append(realfields[u]);
		     } else {
			    sb.append(fields[u]);
		    // }*/
		     sb.append(getRealField(paraForm.getIsform(),realfields[u],fields[u]));
			 sb.append("').val();").append(Constant.SYSMBOL_LINE);
  			 sb.append("    var url=web_app.name + '/dataManage/checkFieldFunction.ajax?funcname=").append(checkfuncs[0]);
		    if (checkfuncs.length>1) { //存在参数字段 
		       sb.append("&paramfield=").append(checkfuncs[1]);
		    }
		    sb.append("';\r\n");
		    sb.append("    Public.ajax(url ,{id:$(\"#id\").val(),currVal:currVal");
		    
		   if (paraFields!=null){  //存在参数字段 
			   String resField="";
			   for (String pfield:paraFields){   /// 如果是明细表 中的字段效验 ，来源可以是主表 或明细表 
				   for (int x=0;x<realfields.length;x++){
				     if (realfields[x].equals(pfield)){
						/* if (paraForm.getIsform() == 0) {  //是代码生成器 获取真实字段名称
							 resField=realfields[x];
						 }else {
							 resField = "field" + x;
						 }*/
						 resField=getRealField(paraForm.getIsform(),realfields[x],"field" + x);
				    	 break;
				     }
				   }
			     sb.append(",").append(pfield).append(":$('#").append(resField).append("').val()");
			   }
		   }
		   sb.append("  },").append(Constant.SYSMBOL_LINE);
		   
		   sb.append("   function (data) { ").append(Constant.SYSMBOL_LINE);
		   sb.append("     if (data.flag==0){ //表示效验没有通过  ").append(Constant.SYSMBOL_LINE);
		   sb.append("           Public.tip(data.result);");
		   sb.append("          $('#");
		  /*if (paraForm.getIsform()==0) {  //是代码生成器 获取真实字段名称
			sb.append(realfields[u]);
		  } else {
			sb.append(fields[u]);
		  } */
		   sb.append(getRealField(paraForm.getIsform(),realfields[u],fields[u]));
		   sb.append("').val(\"\");");
		   
		   if (backFields!=null){  //存在返回字段
			   sb.append(" 	    } else {  ").append(Constant.SYSMBOL_LINE);
			   sb.append("    var results=data.result.split(\",\");");
			  
			  // for(var i=0;i<res.length;i++){    
			    //   sum+=parseInt(scores[i].split(":")[1])       
			   //  }
			   String resField="";
			   for (int y=0;y<backFields.length;y++) {
			       for (int x = 0; x < realfields.length; x++) {
					   if (realfields[x].equals(backFields[y])) {
						   /*if (paraForm.getIsform() == 0) {  //是代码生成器 获取真实字段名称
							   resField = realfields[x];
						   }else {
							   resField = "field" + x;
						   }*/
						   resField=getRealField(paraForm.getIsform(),realfields[x],"field"+x);
						   break;
					   }
				    }

				   sb.append("  if  (results.length>").append(y).append("){");
				   sb.append("      $('#").append(resField).append("').val(results[").append(y).append("])");
				   sb.append("  } ");
			   }
			   sb.append(" 	    }  ").append(Constant.SYSMBOL_LINE);
		   } else {
		       sb.append(" 	    } ").append(Constant.SYSMBOL_LINE);
		   }
		   
		   sb.append("   }); ").append(Constant.SYSMBOL_LINE);
		   sb.append(" } ").append(Constant.SYSMBOL_LINE);
		   sb.append("");
  	}
	
  	
  	//效验明细列表的方法定义
	// 函数 固定传入 当前主表ID  当前值?
	//DB效验函数或过程(函数名称冒号后面是参数字段和返回字段,参数字段逗号分隔, 参数字段和返回字段中有主表字段使用[]括起来
  	public static void checkDetailMethod(String gridName,String chkFuncions,ParamFormVO paraForm,String []mainTableFields,int u,StringBuffer sb) throws Exception{
  		
  		    String []fields=paraForm.getDisplayFields();
		    String []realfields=paraForm.getRealFieldEns();
  		    String []paraFields=null;
  			String []backFields=null;
		    String []checkfuncs=chkFuncions.split(":");
			if (checkfuncs.length>1) { //存在参数字段 
			   paraFields=checkfuncs[1].split(",");
			}
			 if (checkfuncs.length>2) { //存在返回字段 
			   backFields=checkfuncs[2].split(",");
			 }
			
  			 sb.append("    var currVal=datas.");
		    /*paraForm.getIsform() == 0) {  //是代码生成器 获取真实字段名称
			    sb.append(realfields[u]);
		     }else {
			    sb.append(fields[u]);
		     }*/
		    sb.append(getRealField(paraForm.getIsform(),realfields[u],fields[u]));
			 sb.append("; ").append(Constant.SYSMBOL_LINE);
  		
		 sb.append("    var url=web_app.name + '/dataManage/checkFieldFunction.ajax?funcname=").append(checkfuncs[0]);
		    if (checkfuncs.length>1) { //存在参数字段 
		      sb.append("&paramfield=").append(checkfuncs[1]);
		    }
		    sb.append("';").append(Constant.SYSMBOL_LINE);
		  	sb.append("    Public.ajax(url ,{id:datas.id,currVal:currVal");

		   if (paraFields!=null){
			    String resField="";
			   for (String pfield:paraFields){

					resField = getToLineFields(paraForm.getIsform(),mainTableFields, realfields, pfield);

				   if (!"".equals(resField)) {  //如果定义的参数字段没有找到
					   sb.append(",").append(pfield).append(":datas.").append(resField).append("");
				   }
			   }
		   }
		   sb.append("  }, ").append(Constant.SYSMBOL_LINE);
		   
		   sb.append("   function (data) { ").append(Constant.SYSMBOL_LINE);
		   sb.append("     if (data.flag==0){ //表示效验没有通过  ").append(Constant.SYSMBOL_LINE);
		   sb.append("           Public.tip(data.result);");
		  
		   sb.append("          $('#");
		   if (paraForm.getIsform() == 0) {  //是代码生成器 获取真实字段名称
			  sb.append(realfields[u]);
		   } else {
		      sb.append(fields[u]);
		   }
		   sb.append("').val(\"\");");
		   sb.append(gridName).append(".updateCell('");
		   if (paraForm.getIsform() == 0) {  //是代码生成器 获取真实字段名称
			  sb.append(realfields[u]);
		   } else {
			   sb.append(fields[u]);
		   }
		    sb.append("','',datas);");
		   
		   // smsOrderDetailGridManager.updateCell('field2', '', datas);
		   
		   
		   if (backFields!=null){  //存在返回字段
			   sb.append(" 	    } else {  ").append(Constant.SYSMBOL_LINE);
			   sb.append("        var results=data.result.split(\",\");");
			  
			  // for(var i=0;i<res.length;i++){    
			    //   sum+=parseInt(scores[i].split(":")[1])       
			   //  }
			   //String resField="";
			   for (int y=0;y<backFields.length;y++){
				  /* for (int x=0;x<realfields.length;x++){
					     if (realfields[x].equals(backFields[y])){
					    	 resField="field"+x;
					    	 break;
					     }
					 }*/
				   sb.append("  if  (results.length>").append(y).append("){");
				  // sb.append("      $('#").append(resField).append("').val(results[").append(y).append("])");
				   if (backFields[y].startsWith("[")&&backFields[y].endsWith("]")){  //是主表中字段
					   sb.append("    $('#");
					  // if (paraForm.getIsform() == 0) {  //是代码生成器 获取真实字段名称
					//	   sb.append(backFields[y]);
					  // } else {
					   sb.append(getToLineFields(paraForm.getIsform(),mainTableFields,realfields,backFields[y]));
					 //  }
					   sb.append("').val(results[").append(y).append("])");
				   } else {

				     sb.append(gridName).append(".updateCell('");
					//   if (paraForm.getIsform() == 0) {  //是代码生成器 获取真实字段名称
					//	   sb.append(backFields[y]);
					 //  } else {
					 sb.append(getToLineFields(paraForm.getIsform(),mainTableFields, realfields, backFields[y]));
					 //  }
				     sb.append("',results[").append(y).append("],datas);");
				   }
		
				   sb.append("  } ");
			   }
			   sb.append(" 	    } ").append(Constant.SYSMBOL_LINE);
		   } else {
		       sb.append(" 	    } ").append(Constant.SYSMBOL_LINE);
		   }
		 
		  // sb.append(" 	    }  \r\n");
		   sb.append("   });").append(Constant.SYSMBOL_LINE);
		   sb.append("");
  	}
   //根据表单类型  获取真实字段或映射字段 ,真实字段转成驼峰法
	//formType=0 代码生成器   1为表单生成器
	public static String  getRealField(int formType,String realField,String tfield){
   		String backField=tfield;
		if (formType == 0) {  //是代码生成器 获取真实字段名称
			backField=realField;
			if (realField.indexOf("_")>0) {
				backField = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, realField); //转成驼峰法
			}
		}
		return  backField;
	}
  	
  	//获取转换后的字段名称 ，注意带下划线的 真实字段转成驼峰法
	// realfields是驼峰发的字段  pfield 是真实字段 带下划线
  	public static String  getToLineFields(int  formType,String []mainTableFields,String []realfields,String pfield) throws Exception {
  		   String resultField="";
  		  if (pfield.startsWith("[")&&pfield.endsWith("]")){  //是主表中字段
			   pfield=pfield.substring(1,pfield.length()-1);
			   for (int x=0;x<mainTableFields.length;x++){
				     if (mainTableFields[x].equals(pfield)){
				     	if  (formType==0) { //代码生成器
							resultField=pfield;
							if (pfield.indexOf("_")>0) {
								resultField = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, pfield); //转成驼峰法
							}
						} else {
							resultField = "field" + x;
						}
				    	 break;
				     }
				}
		   } else {  //明细表中的字段
			  if (pfield.indexOf("_")>0) {
				  pfield = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, pfield); //转成驼峰法
			  }
		     for (int x=0;x<realfields.length;x++){
		        if (realfields[x].equals(pfield)){
				  if  (formType==0) { //代码生成器
					  resultField=pfield;
				  }else {
					  resultField = "field" + x;
				  }
		    	 break;
		      }
		     }
		   }
		if ("".equals(resultField)){
			System.out.println("生成明细表字段效验函数出错！在表中没有找到对应字段："+pfield);
		}
  		return resultField;
  	}

    //Bean 转 Map   指定属性名称以keyname开头的
	public static Map<String, Object> convertBeanToMap(Object obj,String keyname) {
		if (obj == null) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				// 过滤class属性
				if (!key.equals("class")&&key.startsWith(keyname)) {
					// 得到property对应的getter方法
					Method getter = property.getReadMethod();
					Object value = getter.invoke(obj);
					if(null==value){
						map.put(key,"");
					}else{
						map.put(key,value);
					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
}
