package com.huigou.uasp.builder.filer;

//import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.CaseFormat;
//import com.huigou.cache.SystemCache;
import com.huigou.uasp.builder.BuildFilerInter;
import com.huigou.uasp.builder.ButtonTypeInter;
import com.huigou.uasp.builder.jsbutton.AddButtonResult;
import com.huigou.uasp.builder.jsbutton.CustomButtonResult;
import com.huigou.uasp.builder.jsbutton.DeleteButtonResult;
import com.huigou.uasp.builder.jsbutton.DeleteRowButtonResult;
import com.huigou.uasp.builder.jsbutton.DisableButtonResult;
import com.huigou.uasp.builder.jsbutton.DisableButtonRowResult;
import com.huigou.uasp.builder.jsbutton.EnableButtonResult;
import com.huigou.uasp.builder.jsbutton.EnableButtonRowResult;
import com.huigou.uasp.builder.jsbutton.ExportExcelButtonResult;
import com.huigou.uasp.builder.jsbutton.SaveRowButtonResult;
import com.huigou.uasp.builder.jsbutton.UpdateButtonResult;
import com.huigou.uasp.builder.jsbutton.ViewButtonResult;
import com.huigou.uasp.builder.vo.ButtonAttributeVO;
import com.huigou.uasp.builder.vo.ParamFormVO;
import com.huigou.uasp.builder.vo.SeleListCustomVO;
import com.huigou.uasp.util.Utils;
import com.huigou.uasp.util.Constant;

@Service("buildPageJSFile")
public class BuildPageJSFile implements BuildFilerInter {
		
	private boolean allowEdit=false; //列表允许编辑
	private boolean doubleClick=true; //列表允许行双击
	private boolean allowNewLine=true; //代码允许换行
   @Override
	public String generateFile(ParamFormVO paraForm,List<Map<String, Object>> fieldList)  throws Exception{
		//  StringBuffer sb=new StringBuffer("");

		  String entityName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraForm.getTableName());
		  String fileName=entityName; //首字母小写
		  entityName=Utils.toUpperCaseFirstOne(entityName); //首字母大写
		  
		  StringBuffer  sb=generateContents(paraForm,entityName,null,false,"");
	      String filePathName=paraForm.getUploadPath()+"/"+paraForm.getFormPath()+"/"+fileName+"List.js";
       	  return Utils.generateFile(filePathName,sb);
	}

	/*
	 * mainTableName :主表     isDetail:是否生成明细页面的js
	 */
	public StringBuffer generateContents(ParamFormVO paraForm,String mainTableName,String []mainTableFields,boolean isDetail,String queryUrl){
		// String srcPath=paraForm.getUploadPath()+"/source";
		  StringBuffer sb=new StringBuffer("");

		  String entityName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraForm.getTableName());
		  String fileName=entityName; //首字母小写
	
			 
		  sb.append(" var ").append(fileName).append("GridManager = null, refreshFlag = false;");
		  sb.append(" $(document).ready( function () {");
		  sb.append("    initUI();");
		  sb.append("    init").append(Utils.toUpperCaseFirstOne(entityName)).append("ListGrid();");
		  
		 // if (!isDetail){ //是主表单的 JS   不是明细页面的js   
		 //    sb.append("    bindEvent();");
		  //}
		  
		 /* sb.append("  if (isAudit==\"1\"){");
		  sb.append(" 	  $('#toolbar_menuinsertRowHandler').hide();");
		  sb.append(" 	  $('#toolbar_menudeleteRowHandler').hide();");
		  sb.append(" 	  $('#toolbar_menusaveRowHandler').hide();");
		  sb.append(" 	  $('#toolbar_menuenableRowHandler').hide();");
		  sb.append(" 	  $('#toolbar_menudisableRowHandler').hide();");
		  sb.append("    }");
		  */   //主数据审核 加的
		  
		  
		  sb.append("  });");
		  sb.append(" ");
		  sb.append(Constant.SYSMBOL_LINE);

		  sb.append("function initUI() {");
	      sb.append("    UICtrl.initDefaultLayout();");
		  sb.append(" }");
		  sb.append("");
		  sb.append(Constant.SYSMBOL_LINE);

		  //组装Grid表格
		  sb.append("function init").append(Utils.toUpperCaseFirstOne(entityName)).append("ListGrid() { ");
		  sb.append("  var toolbarOptions =[];");
		  
		  if (paraForm.getBtnMethodNames()!=null){ //存在工具栏按钮
			  composeDisplayButton(paraForm,queryUrl,sb);
		  }
		  sb.append("");
		  sb.append(Constant.SYSMBOL_LINE);

		  sb.append("  ").append(fileName).append("GridManager = UICtrl.grid('#")
		    .append(fileName).append("Grid', {");
		  sb.append(Constant.SYSMBOL_LINE);

		  //组装显示的列表
	      composeDisplayColumns(paraForm,queryUrl,sb);

	      sb.append("       dataAction: 'server',");// pmProjectInfo/slicedQueryPmProjectInfo
	      
	   if (paraForm.getIsform()==1){  //是表单生成器
		   if (isDetail){ //是明细页面的js
			 queryUrl="'/dataManage/slicedQueryDataRecordDetail.ajax'";
		     sb.append(" parms: {formId:$(\"#formId\").val()");
		     sb.append(",maiTab:'").append(mainTableName).append("'");
		     sb.append(",subTab:'").append(paraForm.getTableName()).append("'");
		     sb.append(",id:").append("$(\"#id\").val()");
		     sb.append("},");
		   }else {  //是主表页面的JS 
			   queryUrl="'/dataManage/slicedQueryFormData.ajax'";  
			   sb.append(" parms: {formNo:$(\"#formNo\").val()");
			   sb.append("},");
		   }
	   } else {         //是代码生成器 
		     entityName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,mainTableName);
	         queryUrl="'/"+entityName+"/slicedQuery"+entityName+".ajax'";
		    if (isDetail){ //如果是编辑页面的明细列表  queryUrl增加参数 
			   queryUrl+="&formId='+"+"$(\"#formId\").val()";
			   queryUrl+="+'&id='+"+"$(\"#id\").val()";
		    }else {
		       entityName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,mainTableName);
		       queryUrl="'/"+fileName+"/slicedQuery"+entityName+".ajax'";
		       sb.append(" parms: {formNo:$(\"#formNo\").val()");
		    }
		   
	   }
	 
		sb.append("       url: web_app.name + ").append(queryUrl).append(",");
	
	   if (paraForm.getBtnMethodNames()!=null){ //存在工具栏按钮
		  sb.append("       toolbar: toolbarOptions,");
	   }
		sb.append("       width: '99.8%',");
		sb.append("       height: '100%',");
		sb.append("       heightDiff: -4,");
		sb.append("       sortName: 'sequence',");
		sb.append("       sortOrder: 'asc',");
		sb.append("       checkbox: true,");
		sb.append("       usePager:true,");
	
		sb.append("       rownumbers: false,");
		sb.append("       enabledEdit: ").append(Boolean.toString(allowEdit)).append(",");
		sb.append("       fixedCellHeight: true,");
		sb.append("       selectRowButtonOnly:true");
		
	   if (isDetail){  //是明细页面的js  需要进行编辑
	      sb.append("     ,onAfterEdit:bindEvent");
	      sb.append("     ,autoAddRowByKeydown:true"); //允许自动增加编辑行 
	      sb.append("     ,onAfterAddRow:function(rows){ var id = getId(); if (id!=''){ saveRow").append(Utils.toUpperCaseFirstOne(entityName)).append("(\"\"); }  }");
	    }
		
		sb.append("       ,onSuccess:function(data){ ");
		sb.append("         if (data.error){ Public.tip(data.error);} }");
						
	   if (doubleClick){ //双击事件 
		 sb.append("       ,onDblClickRow: function(data, rowindex, rowobj) ");
		 sb.append("       { ");
		 sb.append("	         doShowUpdateDialog(data.id);");
		 sb.append("       }");
		}
	 	sb.append("    });");
		sb.append("    UICtrl.setSearchAreaToggle(").append(fileName).append("GridManager);");
		sb.append(" 	}");
		sb.append(Constant.SYSMBOL_LINE);
		
		if (isDetail){ //是明细页面的js   添加明细字段效验的处理
		    try {
                Utils.composeDetailCheckFunction(paraForm, mainTableFields, sb);
            }catch(Exception ex){
		        ex.printStackTrace();
            }
	    }
	
		sb.append(Constant.SYSMBOL_LINE);
		sb.append(" function reload").append(Utils.toUpperCaseFirstOne(fileName)).append("Grid() {")
		  .append("     var params = $(\"#queryMainForm\").formToJSON();")
		  .append("     UICtrl.gridSearch(").append(fileName).append("GridManager, params);")
		  .append("	}");
		sb.append(Constant.SYSMBOL_LINE);

		//生成getId方法
		sb.append("function getId() {");
		sb.append("	    return $(\"#id\").val() || \"\";");
		sb.append("	}");
		sb.append(Constant.SYSMBOL_LINE);
		//生成setId方法
		sb.append("function setId(value)  { ");
		sb.append(" 	$(\"#id\").val(value);");
		// 为文件上传控件绑定业务id
		// $('#fileList').fileList({bizId: leaveId});
		sb.append("   } ");

		sb.append(Constant.SYSMBOL_LINE);

		
		//生成工具栏按钮的执行方法
		 if (paraForm.getBtnMethodNames()!=null){  
		   	     ButtonTypeInter outResults=null;
		   	     ButtonAttributeVO btnAttr=null;
				 btnAttr=new ButtonAttributeVO();
				 
				 btnAttr.setIsForm(paraForm.getIsform());
			 	 btnAttr.setFormName(paraForm.getFormName());
			 	 String parentEntityName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,mainTableName);
			 	 btnAttr.setParentEntityName(parentEntityName); 
			 	 btnAttr.setEntityName(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraForm.getTableName()));
			   //  btnAttr.setProcDefinition(paraForm.getProcDefinition());
			    //  List <String>list=new ArrayList<String>();
		    for (int i=0;i<paraForm.getBtnMethodNames().length;i++){
				     btnAttr.setButtonName(paraForm.getBtnNames()[i]);
				     btnAttr.setButtonMethoedName(paraForm.getBtnMethodNames()[i]);
				     btnAttr.setExistAttachment(paraForm.getExistAttachment());
				     btnAttr.setDataSourceType(paraForm.getDataSourceTypes());
				     btnAttr.setDataSource(paraForm.getDataSources());
				     btnAttr.setFieldEns(paraForm.getFieldEns());
				     btnAttr.setSelectCustoms(paraForm.getSelectCustoms());
				     
				    outResults=this.getPageButtonType(paraForm.getBtnMethodNames()[i]);
					outResults.processOutResult(sb,btnAttr);
			}
		 }

	  //sb.append("//查询方法;").append(Constant.SYSMBOL_LINE);
		sb.append("function query(obj) {");
	    sb.append("  var param = $(obj).formToJSON();");
		sb.append("  UICtrl.gridSearch(").append(fileName).append("GridManager, param);");
		sb.append("}");
		sb.append(Constant.SYSMBOL_LINE);
		
		//sb.append("//重置表单;").append(Constant.SYSMBOL_LINE);;
		sb.append("function resetForm(obj) {");
		sb.append("  $(obj).formClean();");
		sb.append("}");
		sb.append(Constant.SYSMBOL_LINE);
		
		//关闭窗口
		sb.append(" function onDialogCloseHandler() { ");
		sb.append("    if (refreshFlag) {");
		sb.append("        reload").append(Utils.toUpperCaseFirstOne(fileName)).append("Grid();");
		sb.append("        refreshFlag = false;");
		sb.append("    } ");
		sb.append("} ");
		
		String result=sb.toString();
		if (allowNewLine){
			result=result.replace("{","{"+Constant.SYSMBOL_LINE);
			result=result.replace("}","}"+Constant.SYSMBOL_LINE);
			result=result.replace(";",";"+Constant.SYSMBOL_LINE);
			result=result.replace("={"+Constant.SYSMBOL_LINE,"={"); //去掉换行符
			result=result.replace("}"+Constant.SYSMBOL_LINE+";"+Constant.SYSMBOL_LINE,"};"+Constant.SYSMBOL_LINE);
			result=result.replace("{"+Constant.SYSMBOL_LINE+"display:","{display:"); //列表显示去掉换行符

		}
	   return new StringBuffer(result);

	}
	
	//组装显示的列 
	public void composeDisplayColumns(ParamFormVO paraForm,String queryUrl,StringBuffer sb){
		// String fileName=entityName; //首字母小写
		String []fieldEns=paraForm.getFieldEns();
		if (paraForm.getIsform()==0){ //代码生成器
			fieldEns=paraForm.getRealFieldEns();
			String tfstr="";
			for (int u=0;u<fieldEns.length;u++) {
				tfstr= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, fieldEns[u]); //转驼峰法
				fieldEns[u]=tfstr;
			}
		}

		 String []dataSourceTypes=paraForm.getDataSourceTypes();
		 String []dataSources=paraForm.getDataSources();
		 
		 String []displayField=paraForm.getDisplayFields();
		if (paraForm.getIsform()==0){ //代码生成器
			displayField=paraForm.getRealFieldEns();
		}
		 String []displayFieldname=paraForm.getDisplayFieldnames();
	     String []displayFieldType=paraForm.getDisplayFieldTypes();
	     String []mustInput=paraForm.getMustinputFields();
	     List <SeleListCustomVO> customSqlList=paraForm.getSelectCustoms();
	     
	     String  []maxLengths=paraForm.getFieldsLengths();
	     String  []defaultOperations=paraForm.getDefaultOperation();
	     
		  sb.append("      columns: [");
		  double percents=0.00;
		  if  (displayField.length>0){
		    percents=98/displayField.length;  //每列占宽度百分比
		  }
		  List <String> hideCols=new ArrayList<String>();
		  hideCols.add("id");
		  
		   String dataSourceType="",dataSource="",tagType="input";
			  //entityName= mdmDataMaterialaSupply
		   //String queryParams="?tableName="+paraForm.getTableName();
	    for (int i=0;i<displayField.length;i++){
	       	if (i>displayField.length-2){
	    		percents=percents-1;
	    	}
	   	   for (int j=0;j<fieldEns.length;j++) {
			 if (displayField[i].equals(fieldEns[j])){
				// chName=fieldchs[j];
				  tagType=paraForm.getFieldTags()[j];
				 if (dataSourceTypes.length>j){
				    dataSourceType=dataSourceTypes[j]; 
				 }
				 if (dataSources.length>j){
				    dataSource=dataSources[j];
				 }
				 break;
			 }
	   	   }
			sb.append("     {display:\""+displayFieldname[i]+"\",name:\"");
			
			 if (paraForm.getIsform()==1){  //是表单生成器
				 sb.append(displayField[i]).append("\"");
				 
			 } else {  //直接生成代码的 
			   if ("select".equals(tagType)){  //数据来源为数据字典的下拉框
				
				 if (allowEdit){ 
				    sb.append(displayField[i]).append("\"");
		    	  } else { //不能编辑的
					    if (dataSource!=null&&!"".equals(dataSource)){
						     sb.append(dataSource);
						 }else {
							 sb.append(displayField[i]);
						 }
						 sb.append("TextView\""); 
					  
				  }
		       } else { 
		    	 sb.append(displayField[i]).append("\"");
		       }
			 }
			 sb.append(",width:\""+percents+"%\",minWidth:\"60\"");
			 
	       	if ("date".equalsIgnoreCase(displayFieldType[i])){
	       		sb.append(",align:\"left\",type:\"date\"");
	       	 	if (allowEdit){
	       	 	  sb.append(",editor:{type:'date',mask:'date',");
	       	 	  if ("1".equals(mustInput[i])){
	       	 	     sb.append("required:true");
	       	 	  } else {
	       	 		 sb.append("required:false");
	       	 	  }
	       	 	  sb.append("}");
	       	 	}
	       	} else if ("number".equalsIgnoreCase(displayFieldType[i])){
	       		if ("select".equals(tagType)){
	       			sb.append(",align:\"right\",type:\"string\"");
	       		} else {
	       		    sb.append(",align:\"right\",type:\"money\"");
	       		}
	       		if (allowEdit){
	       		  sb.append(",editor:{type:'text',mask : '9999999999.99',");
	      	 	  if ("1".equals(mustInput[i])){
		       	 	     sb.append("required:true");
		       	   } else {
		       	 		 sb.append("required:false");
		       	   }
		       	  sb.append("}");
	       		}
	    	} else {
	    		 sb.append(",align:\"left\",type:\"string\"");
	    		if (allowEdit){
	    			 if (Constant.SELECT_TAG.equals(tagType)){  //数据来源为数据字典的下拉框
	    				 allowNewLine=false; //此处不允许换行了   因为js引号转义
	    				
	    			    sb.append(",editor: {");
	    			    if ("1".equals(mustInput[i])){
				       	   sb.append("required:true,");
				       	 } else {
				       	   sb.append("required:false,");
				       	 }
	    			  if (Constant.DATASOURCETYPE_DICT.equals(dataSourceType)){
	    				  hideCols.add(displayField[i]+"_dictcode");
	  		            sb.append(" type: \"dynamic\",")
	  		             .append("    getEditor: function (row) {")
   		                 .append("    var _fieldCode = \"return {type:'select',data:{ type:'saf',name:'selectDictValueByCode',getParam:function(){ return { code:'").append(dataSource).append("' } ; },\";")
			             .append("  _fieldCode+=\"back:{name:\\\"").append(displayField[i]).append("\\\",value:\\\"").append(displayField[i]).append("_dictcode\\\" } } } \";")
	    			   
	  		             .append("        _fieldCode = (new Function(_fieldCode))();")
	  		             .append("         return _fieldCode;");
	  		           sb.append("      }");
	  				   sb.append(" } ");
	    			  } else  if (Constant.DATASOURCETYPE_SQL.equals(dataSourceType)){  //自定义ＳＱＬ　
	    				  //需要找到检索SQL的参数条件、返回值 字段
	    				 // String []condiCols=null;
	    				  String []backFields=null;
	    				  String []fieldTypes=null;
	    				  String []fieldCodes=null;
	    				  String []paramFields=null,paramSourceFields=null,allFieldEns=null;
	    				  for (SeleListCustomVO customSqlVO:customSqlList){
	    					  if (dataSource.equals(customSqlVO.getSearchName())){
	    						 hideCols.addAll(Utils.getHiddenFields(customSqlVO));
	    						 fieldTypes=customSqlVO.getFieldTypes().split(",");
	    						 backFields=customSqlVO.getBackFields().split(",");
	    						 fieldCodes=customSqlVO.getFieldCodes().split(",");
	    						 allFieldEns=customSqlVO.getFieldEns();
	    						 paramFields=customSqlVO.getParamFields()!=null?customSqlVO.getParamFields().split(","):new String[0];
	    						 paramSourceFields=customSqlVO.getParamSourceFields()!=null?customSqlVO.getParamSourceFields().split(","):new String[0];
	    						// condiCols=customSqlVO.getCondiColumns()!=null?customSqlVO.getCondiColumns().split(","):new String[0];
	    						 break;
	    					  }
	    				  }
	    				  sb.append(" type: \"dynamic\",")
		  		             .append("    getEditor: function (row) {")
	   		                 .append("    var _fieldCode = \"return {type:'select',data:{ type:'saf',name:'")
	   		                 .append(dataSource).append("',frmType:'").append(paraForm.getFormPath()).append("',getParam:function(){ return { ");
	   		                 //.append(" code:'").append(dataSource).append("'")
	    				     for ( int t=0;t<paramFields.length;t++){
	    				    	// getDisplayField(fieldEns,displayField,paramSourceFields[t])//根据真实字段获取转换后的显示字段
	    				    	 //if (paraForm.getIsform()==1){  //是表单生成器   如果是生成代码 ？？？
	    				    	sb.append(paramFields[t]).append(":'\"+row.").append( getDisplayField(allFieldEns,displayField,paramSourceFields[t])).append("+\"'");
	    				    	if (t<paramFields.length-1){
	    				    		sb.append(",");
	    				    	}
	    				     }
	   		                 sb.append(" } ; },\";")
				             //.append("  _fieldCode+=\"back:{name:\\\"").append(displayField[i]).append("\\\",value:\\\"").append(displayField[i]).append("_dictcode\\\" } } } \";")
	   		                 .append("  _fieldCode+=\"back:{");
		    			    for ( int r=0;r<backFields.length;r++){
		    			    	if ("1".equals(fieldTypes[r])){  //隐藏字段
		    			    		sb.append(fieldCodes[r]).append(":\\\"").append(backFields[r]).append("\\\"");
		    			    		//sb.append("name:\\\"").append(backFields[r]).append("\\\",value:\\\"").append(backFields[r]).append("\\\"");
		    			    	} else {  //如果是多个返回字段 displayField[i] -->displayField[r] 07.03
		    			    		sb.append(fieldCodes[r]).append(":\\\"").append(getDisplayField(allFieldEns,displayField,backFields[r])).append("\\\"");
		    			    	   // sb.append("name:\\\"").append(backFields[r]).append("\\\",value:\\\"").append(displayField[i]).append("\\\"");
		    			    	}
		    			    	if (r<backFields.length-1){
	    				    	   sb.append(",");
	    				    	}
		    			    }
	   		                 sb.append(" } } } \";");
		  		             sb.append("        _fieldCode = (new Function(_fieldCode))();")
		  		             .append("         return _fieldCode;");
		  		           sb.append("      }");
		  				   sb.append(" } ");
	    			  }
	  				   
	    			 } else {  //普通输入框
	    			   if (Constant.READ_WRITE.equals(defaultOperations[i])){ //允许编辑的
	    		           sb.append(",editor:{type: 'text',maxLength:'").append(maxLengths[i]).append("',");
	    		          if ("1".equals(mustInput[i])){
			       	 	     sb.append("required:true");
			       	      } else {
			       	 		 sb.append("required:false");
			       	       }
			       	      sb.append("}");
	    			    } else {  //不允许编辑  改变显示的颜色
	    			    	sb.append(",render:function(row) { var html =\"<span style='color:blue'>\"+row.").append(displayField[i])
	    			    	.append("+\"</span>\"; return html;}");
	    			    }
	    			 }
	    	    }
	    	}
	    	sb.append("},");
			sb.append(Constant.SYSMBOL_LINE);
	   }
	    sb.append("     {display: '状态', name: 'status', width: 50, minWidth: 40, align:\"left\",")
          .append("render: function (item) { ")
				.append("  if ($('#procId').val()!=\"\") { ");
		       if (allowEdit){
				   sb.append("	return UICtrl.getStatusInfo(item.status); ");
				 } else {
				   sb.append("  return UICtrl.getApproveStatusInfo(item.status); ");
			   }
				sb.append("  } else { ")
				.append("    return UICtrl.getStatusInfo(item.status);} } }");
	    if (hideCols.size()>0){
	    	 sb.append(",");
	    }
	    for (int u=0;u<hideCols.size();u++) {
		  sb.append("   {display:\"\", name:\"").append(hideCols.get(u)).append("\",hide:true}");
		  if (u<hideCols.size()-1){
			  sb.append(",");
		  }
	    }
		sb.append("],");
		sb.append(Constant.SYSMBOL_LINE);
	}
	
	
	
	//组装显示的按钮 
	public void composeDisplayButton(ParamFormVO paraForm,String queryUrl,StringBuffer sb){
		if (paraForm.getBtnMethodNames().length>0&&!"".equals(paraForm.getBtnMethodNames()[0])){
			   String entityName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraForm.getTableName());
			  // String fileName=entityName; //首字母小写
		    sb.append("  toolbarOptions = UICtrl.getDefaultToolbarOptions({");
		     String mainEntityName="";
		   if (paraForm.getMainTableName()!=null){
		     mainEntityName=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,paraForm.getMainTableName());
		   }
		   for (int i=0;i<paraForm.getBtnMethodNames().length;i++){
			 if (paraForm.getBtnMethodNames()[i].indexOf("_custom")>0){ //自定义按钮
			  sb.append("    ").append(paraForm.getBtnMethodNames()[i]).append("Handler:{  id: '").append(paraForm.getBtnMethodNames()[i]).append(i)
			    .append("',text: '").append(paraForm.getBtnNames()[i])
			    .append("',img: 'fa-user', click: ").append(paraForm.getBtnMethodNames()[i]).append("Handler}");
			 } else { //系统默认按钮类型
				   //添加行按钮
				 if ("addRow".equals(paraForm.getBtnMethodNames()[i]) ){
					 allowEdit=true;
					 doubleClick=false;
					 
					 sb.append("addRowHandler:{")
					 .append("id:'insertRowHandler',")
					 .append("img:'fa-plus',")
				     .append("text:'添加行',")
					 .append("click:function(){ ")
					 .append("doSave").append(Utils.toUpperCaseFirstOne(mainEntityName)).append("(\"")
					 .append(entityName).append("GridManager\");")
					
					 .append("}")
					 .append("}");
					 
				 } else  if ("deleteRow".equals(paraForm.getBtnMethodNames()[i]) ){

						 sb.append("    deleteRowHandler:{")
						 .append("id:'deleteRowHandler',")
						 .append("img:'fa-trash',")
					     .append("text:'删除行',")
						 .append("click:function(){")
						 .append("").append(paraForm.getBtnMethodNames()[i]).append(Utils.toUpperCaseFirstOne(entityName)).append("();")
						 .append("}")
						 .append("}");
				/* } else  if ("saveRow".equals(paraForm.getBtnMethodNames()[i]) ){
					 sb.append("     saveRowHandler:{")
					 .append("id:'saveRowHandler',")
					 .append("img:'fa-save',")
				     .append("text:'保存行',")
					 .append("click:function(){")
					 .append("").append(paraForm.getBtnMethodNames()[i]).append(Utils.toUpperCaseFirstOne(entityName)).append("(\"\");")
					 .append("}")
					 .append("}");  */
				 } else  if ("enableRow".equals(paraForm.getBtnMethodNames()[i]) ){
					 sb.append("     enableRowHandler:{")
					 .append("id:'enableRowHandler',")
					 .append("img:'fa-thumbs-o-up',")
				     .append("text:'启用行',")
					 .append("click:function(){")
					 .append("").append(paraForm.getBtnMethodNames()[i]).append(Utils.toUpperCaseFirstOne(entityName)).append("();")
					 .append("}")
					 .append("}");
				 } else  if ("disableRow".equals(paraForm.getBtnMethodNames()[i]) ){
					 sb.append("     disableRowHandler:{")
					 .append("id:'disableRowHandler',")
					 .append("img:'fa-thumbs-down',")
				     .append("text:'禁用行',")
					 .append("click:function(){")
					 .append("").append(paraForm.getBtnMethodNames()[i]).append(Utils.toUpperCaseFirstOne(entityName)).append("();")
					 .append("}")
					 .append("}");
				 } else  if ("saveRow".equals(paraForm.getBtnMethodNames()[i]) ){
				 	//在下面根据是否存在流程 添加
				 } else {   //主表 默认的按钮类型
		            sb.append("").append(paraForm.getBtnMethodNames()[i]).append("Handler:")
		             .append(paraForm.getBtnMethodNames()[i]).append("Handler");
				 }
			 }
		   
		     if (i<paraForm.getBtnMethodNames().length-1){
		        sb.append(",");
		     }
		      sb.append("");
		   } //ended for
		     sb.append("   });");
			   //如果是明细表 需要增加
			for (int i=0;i<paraForm.getBtnMethodNames().length;i++) {
				if ("saveRow".equals(paraForm.getBtnMethodNames()[i])) {

					sb.append("  if ($('#procId').val()==\"\") {");  //增加是否配置流程
					sb.append("  toolbarOptions.items[toolbarOptions.items.length] =  {id:'saveRowHandler',img:'fa-save',text:'保存行',click:function(){ ")
							.append("saveRow").append(Utils.toUpperCaseFirstOne(entityName)).append("(\"\");}};");
					sb.append(" }");
				}
			}

			}
	
	}
	
	//获取真实字段的显示字段名称  field0、field1、field2....
	// 明细表的 fieldEns//已经是field0...??? 
  public String  getDisplayField(String []fieldEns,String []displayFields,String fieldName){
	  String displayField=fieldName;
	  for (int j=0;j<fieldEns.length;j++) {
			 if (fieldName.equals(fieldEns[j])){
				 displayField=displayFields[j];
				 break;
			 }
	   	   }
	  return displayField;
	  
  }
	
	  //**获取页面按钮类型
	  public  ButtonTypeInter getPageButtonType(String condition){
		    ButtonTypeInter inter=null;
	      switch(condition)
		   { 
		     case Constant.ADD_BUTTON:
			   inter=new AddButtonResult();
			   break;
		 
		     case Constant.UPDATE_BUTTON:  
			   inter=new UpdateButtonResult();
			   break;		
				   
		     case Constant.DELETE_BUTTON:  
			   inter=new DeleteButtonResult();
			   break;		
				   
		     case Constant.VIEW_BUTTON: 
			   inter=new ViewButtonResult();
			   break;		
			   
		     case Constant.DISABLE_BUTTON: 
				   inter=new DisableButtonResult();
				   break;		
			
		     case Constant.ENABLE_BUTTON: 
				   inter=new EnableButtonResult();
				   break;		
		     case Constant.EXPORTEXCEL_BUTTON: 
				   inter=new ExportExcelButtonResult();
				   break;
				   
		     case Constant.DISABLE_BUTTON_ROW: 
				   inter=new DisableButtonRowResult();
				   break;		
			
		     case Constant.ENABLE_BUTTON_ROW: 
				   inter=new EnableButtonRowResult();
				   break;	
				   
		     case Constant.SAVE_BUTTON_ROW:  
				   inter=new SaveRowButtonResult();
				   break;	
		     case Constant.DELETE_BUTTON_ROW:  
				   inter=new DeleteRowButtonResult();
				   break;	
		   //  case Utils.CUSTOM_BUTTON: 
			//	   inter=new CustomButtonResult();
			//	   break;		
		      default:
		    	  inter=new CustomButtonResult();
		    	  break;
		   }
		  return inter;
	  }


}
