package com.huigou.uasp.builder.jsbutton;

import java.util.ArrayList;
import java.util.List;

import com.google.common.base.CaseFormat;
import com.huigou.uasp.builder.ButtonTypeInter;
import com.huigou.uasp.builder.vo.ButtonAttributeVO;
import com.huigou.uasp.builder.vo.SeleListCustomVO;
import com.huigou.uasp.util.Utils;
import com.huigou.uasp.util.Constant;

public class AddButtonResult implements ButtonTypeInter {
	
	public List<String> processOutResult(StringBuffer sb,ButtonAttributeVO btnAttr){
		List <String> list=new ArrayList<String>();
		//sb.append("//增加方法 ").append(Constant.SYSMBOL_LINE);
		//如果是配置了流程  则通过Ifame打开，发起流程页面
		sb.append(" function addHandler(){");
        sb.append("  if ($('#procId').val()!=\"\") { ");

            sb.append("UICtrl.addTabItem({ ");
			sb.append("	tabid: 'add").append(btnAttr.getEntityName()).append("',");
			sb.append("	text: \"新增"+btnAttr.getFormName()+"\",");
			sb.append("	url: web_app.name+'/dataManage/addDataRecord.job?procId='+$('#procId').val()");
			sb.append("+'&formNo='+$('#formNo').val()");
			sb.append(" });");

          sb.append(" } else { ");

			sb.append("   UICtrl.showAjaxDialog({");
			sb.append("  title:'").append(btnAttr.getFormName()).append("',");
			if (btnAttr.getIsForm() == 1) {  //是表单生成器 则调用统一的添加方法
				sb.append("  url: web_app.name +'/dataManage/addDataRecord.load',");
				sb.append("      param: {id:$('#id').val(),formNo:$('#formNo').val()},");
			} else {  //代码生成器
				sb.append("  url: web_app.name +'/").append(Utils.toLowerCaseFirstOne(btnAttr.getEntityName())).append("/").append("load")
						.append(Utils.toUpperCaseFirstOne(btnAttr.getEntityName())).append("Detail.load',");
				sb.append("      param: {id:$('#id').val()},");
			}
			sb.append("      width: 1000,");
			sb.append("      height:460,");
			sb.append("      init:function(){");
			sb.append("         initAdd").append(Utils.toUpperCaseFirstOne(btnAttr.getEntityName())).append("();");
			sb.append("      },");
			sb.append("     ok: function() { doSave").append(Utils.toUpperCaseFirstOne(btnAttr.getEntityName())).append("(1);},");

			sb.append("     close: onDialogCloseHandler ");
			sb.append(" });");

			sb.append("} ");
			sb.append(" ");
           sb.append(" } ");
		sb.append(Constant.SYSMBOL_LINE);

   		sb.append("function initAdd").append(Utils.toUpperCaseFirstOne(btnAttr.getEntityName())).append("(){ ");
   		//如果存在自定义的 下拉选择框
   		boolean existCustomSelect=false;
   		 for (int i=0;i<btnAttr.getDataSourceType().length;i++){
   			 if (Constant.DATASOURCETYPE_SQL.equals(btnAttr.getDataSourceType()[i])){
   				existCustomSelect=true;
   				 break;
   			 }
   		 }
   		 //dataSouce: [searchName:;type:;id:;displayField:{};conditionField:{};ordeby:]
   	    if  (existCustomSelect){
   	    	//String dataSource="";
   	    	SeleListCustomVO selectCustom=null;
   	    	List <SeleListCustomVO>  customLists= btnAttr.getSelectCustoms();
   	      for (int i=0;i<btnAttr.getDataSourceType().length;i++){  //遍历所有的数据来源
      		if (Constant.DATASOURCETYPE_SQL.equals(btnAttr.getDataSourceType()[i])){  //是集合类型的  自定义检索SQL的　
      		   String  targetField=btnAttr.getFieldEns()[i];
      		   selectCustom=null;
      		   for (int u=0;u<customLists.size();u++){  //遍历所有的检索SQL
      			  if (btnAttr.getIsForm()==1){  //是表单生成器   字段名称变成了field0、field1、field2....
      				  if  (i==customLists.get(u).getTargetNum()){
      					 selectCustom=customLists.get(u);
      					 break;
      				  }
      			  } else { //代码生成器
      	 		     if (targetField.equals(customLists.get(u).getTargetField())){  //字段名称是真实字段名称
      				   selectCustom=customLists.get(u);  
     				   break;
      			     }
      			   }
      		    }  //
 
      		 if (selectCustom!=null){
      		   sb.append(" $('#").append(targetField).append("').searchbox({ ");
      		   sb.append("	type : '").append(selectCustom.getSearchboxType()).append("', ");
      		   sb.append("	name : '").append(selectCustom.getSearchName()).append("', ");
      		  if (btnAttr.getIsForm()==1){  //是表单生成器   增加参数frmType
      			 sb.append("	frmType : '").append(selectCustom.getFormNo()).append("', ");
      		  }
      		   sb.append("	getParam : function() { ");
      		   sb.append("		return { ");   //参数字段 
      		if (selectCustom.getCondiColumns()!=null&&!"".equals(selectCustom.getCondiColumns())){
      			 String []condiCols=selectCustom.getCondiColumns().split(",");
      		    for (int x=0;x<condiCols.length;x++){
      	
      			   sb.append("			").append(condiCols[x]).append(":$('#")
      			     .append(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,condiCols[x]))
      			     .append("').val()"); 
      	
      			  if (x<condiCols.length-1){
      				 sb.append(",");
      			  }
      			 sb.append(" ");
      		    }
      		 }
          	//存在冒号开头的指定变量参数
             if (selectCustom.getParamFields()!=null&&!"".equals(selectCustom.getParamFields())){ 
            	 if (selectCustom.getCondiColumns()!=null&&!"".equals(selectCustom.getCondiColumns())){
            		 sb.append("         ,"); 
            	 }
            	 String []paramFields=selectCustom.getParamFields().split(",");
            	 String []paramSourceFields=new String[paramFields.length];
            	 if (selectCustom.getParamSourceFields()!=null&&!"".equals(selectCustom.getParamSourceFields())){ 
            	    paramSourceFields=selectCustom.getParamSourceFields().split(",");
            	 }
            	 String paramSourceField="";
            	 for (int x=0;x<paramFields.length;x++){
          			 sb.append("			").append(paramFields[x]).append(":$('#");
          		      if (btnAttr.getIsForm()==1){  //是表单生成器   字段名称变成了field0、field1、field2....
          		    	  String []fields=selectCustom.getFieldEns();
          		    	   paramSourceField=paramSourceFields[x]; //默认取来源字段 ，以免是隐藏字段没有找到值
          		    	  for (int y=0;y<fields.length;y++){
          		    		if (fields[y].equals(paramSourceFields[x])){
          		    			paramSourceField="field"+y;
          		    		    break;
          		    		}
          		    	  }
          		      } else {
          		    	 paramSourceField=paramSourceFields[x];
          		      }
          			   if (paramSourceFields.length>x){
          			      sb.append(paramSourceField);
          			    } else {
          			      sb.append(paramFields[x]); 
          			    }
          		      
          			   sb.append("').val()"); 
          			 if (x<paramFields.length-1){
          				 sb.append(",");
          			 }
          			 sb.append(" ");
          		   }
            	 
             }
      		 sb.append("		}; ");
      		 sb.append("	}, ");
             sb.append("		back : { ");
             if (selectCustom.getFieldCodes()!=null&&!"".equals(selectCustom.getFieldCodes())){
            	 String []fieldCodes=selectCustom.getFieldCodes().split(",");
            	 String []backFields=selectCustom.getBackFields().split(",");
            	 String []fieldEns=selectCustom.getFieldEns();  //隐藏字段如何处理?
        		   for (int y=0;y<fieldCodes.length;y++){ 
        			  if  (backFields.length>=y+1&&!"".equals(backFields[y])){//有对应的返回字段
        				  sb.append("			").append(fieldCodes[y]).append(":'#");
        				  if (btnAttr.getIsForm()==1){  //是表单生成器   字段名称变成了field0、field1、field2....
        		    					        					  
        					  sb.append(getMappingFieldEn(fieldEns,backFields[y]));
               					  
        					 // if (backFields[y].equals(getRealFieldEn(fieldEns,targetField))){  //返回给当前字段的值 需要加 _text
        					//	 sb.append("_text");  //不用 旧版本需要  
            		         // }
        				  } else {  //代码生成器
      		                  sb.append(backFields[y]);
      		                // if  (targetField.equals(backFields[y])){  //返回给当前字段的值 需要加 _text
      		            	 //  sb.append("_text");  
      		                // }
        				  }
       		            sb.append("'");
      		         
      		          if (y<backFields.length-1) {
      		        	  sb.append(",");
      		          }
      		           sb.append(" ");
        			  }
      	   		   }
             }
            
             //toServiceCode_text
             
      		 sb.append("		}, ");
      		 sb.append("	onChange : function() { ");
      		// sb.append("		$('#buildingName').val($('#buildingName_text').val()); ");
      		 sb.append("	 } ");
      		 sb.append("	}); ");
      		// sb.append("	} ");
      		// sb.append("  }  ");
      		 }
      		}
   	      }
   	    }
   	    
   /*	
    	 	 
  	  $('#buildingName').searchbox({
		type : 'oa',
		name : 'buildingInfo',
		getParam : function() {
			return {
				villageId:$('#villageId').val()  //sql语句 定义了  以：参数
			};
		},
		back : {
			id : '#buildingId',
			buildingName : '#buildingName_text'
			
		},
		onChange : function() {
			$('#buildingName').val($('#buildingName_text').val());
		}
	});
   	 */
   	    	 
   	   
   		if (btnAttr.getExistAttachment()==1){
   		  sb.append("   var _attbizid=$(\"#attbizid\").val();");
   		  sb.append("   $('#").append(Utils.toLowerCaseFirstOne(btnAttr.getEntityName())).append("List').fileList({bizId:_attbizid}); //�����ؼ���ʼ��");
   		}
   		//sb.append(" $("#projectName").attr("readonly",true);
   	    sb.append("	} ");
   	    sb.append(" ");
   	    
   	 //   sb.append(" //保存方法 ;");
		sb.append(Constant.SYSMBOL_LINE);
		sb.append("function doSave").append(Utils.toUpperCaseFirstOne(btnAttr.getEntityName())).append("(grid){");
		sb.append(" var _self = this;");
		sb.append("   var id = getId();");
		
		if (btnAttr.getIsForm()==1){  //是表单生成器 则调用统一的添加方法
	       sb.append("  var url= '/dataManage/saveDataRecord.ajax';");
	       sb.append("  if (grid==1) { url+='?btntype=1';  } ");
	       sb.append("  $('#submitForm').ajaxSubmit({");   //发起流程 必须固定表单名称为submitForm
		} else {
		   sb.append("   var url = '/").append(Utils.toLowerCaseFirstOne(btnAttr.getEntityName()))
		    .append("/save").append(Utils.toUpperCaseFirstOne(btnAttr.getEntityName())).append(".ajax';");
		  // sb.append("  $('#").append(Utils.toLowerCaseFirstOne(btnAttr.getEntityName())).append("Form').ajaxSubmit({");
			sb.append("  $('#submitForm').ajaxSubmit({");
		}
		
		sb.append("       url: web_app.name +url,");
		sb.append("       success: function (data) {");
		
		sb.append("           $(\"#id\").val(data);");
		sb.append("           if (grid&&grid!=\"\") {UICtrl.addGridRow(eval(grid),{id:data }  );}");
		sb.append("      	  reload").append(Utils.toUpperCaseFirstOne(btnAttr.getEntityName())).append("Grid();");
	    sb.append("       	  refreshFlag = true;");
		sb.append("           _self.close();");
		sb.append("      }");
		sb.append("   });");

		sb.append(" }");
	    sb.append("	");
		sb.append(Constant.SYSMBOL_LINE);

		  list.add(sb.toString());
		 // list.add(Integer.toString(fieldAttributes.getCurrCols()));
		return list;
	}

	//获取真实的字段名
	private String getRealFieldEn(String []fieldEns,String targetField){
		    String sequence=targetField.substring(5);
		    String fieldEn=targetField;
		   for (int x=0;x<fieldEns.length;x++){
			   if (x==Integer.parseInt(sequence)){
				   fieldEn=fieldEns[x];
				   break;
			   }
		   }
		   return fieldEn;
		
	}
	
	 //获取映射的字段名称  field0、field1、field2...........
		private String getMappingFieldEn(String []fieldEns,String realfield){
			    String fieldEn=realfield;
			   for (int x=0;x<fieldEns.length;x++){
				   if (realfield.equals(fieldEns[x])){
					   fieldEn="field"+x;
					   break;
				   }
			   }
			   return fieldEn;
			
		}
}
