package com.huigou.uasp.form.controller;
 import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;









import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import com.huigou.cache.SystemCache;
import com.huigou.uasp.annotation.ControllerMapping;
import com.huigou.uasp.annotation.SkipAuth;
import com.huigou.uasp.builder.BuildTypeClass;
import com.huigou.uasp.builder.vo.ParamFormVO;
import com.huigou.uasp.builder.vo.SeleListCustomVO;
import com.huigou.uasp.client.CommonController;
import com.huigou.uasp.form.application.CommonUtilApplication;
import com.huigou.uasp.form.application.SafFormslistApplication;
import com.huigou.uasp.form.domain.model.FormAttribute;
import com.huigou.uasp.form.domain.model.FormButtonVO;
import com.huigou.uasp.form.domain.model.FormSearchSql;
import com.huigou.uasp.form.domain.model.FormTables;
import com.huigou.uasp.form.domain.model.PropertyDefines;
import com.huigou.uasp.form.domain.model.SafFormslist;
import com.huigou.uasp.form.domain.query.FormParameterQueryRequest;
import com.huigou.uasp.form.domain.query.SafFormsQueryRequest;
import com.huigou.uasp.form.model.ResultModel;
import com.huigou.uasp.form.repository.FormAttributeRepository;
import com.huigou.uasp.form.repository.FormSearchSqlRepository;
import com.huigou.uasp.form.repository.FormTablesRepository;
import com.huigou.uasp.form.repository.SafFormslistRepository;
import com.huigou.uasp.meta.domain.model.MetaData;
import com.huigou.uasp.meta.repository.MetaDataRepository;
import com.huigou.uasp.model.application.DbTablesApplication;
import com.huigou.uasp.model.domain.query.DbTablesQueryRequest;
import com.huigou.uasp.model.repository.DbTablesRepository;
import com.huigou.util.SDO;
import com.huigou.util.StringUtil;

import org.springframework.util.StringUtils;
















import com.huigou.uasp.util.Constant;
import com.huigou.uasp.util.Utils;


/**
 * 
 * @author lxh
 * @date 2019年08月16日
 * @return
 * @Description 表单设置的控制类
 */
@Controller
@ControllerMapping("safFormslist")
 public class SafFormslistController extends CommonController{ 


@Autowired
private  SafFormslistRepository safFormslistRepository;

@Autowired
private  FormTablesRepository formTablesRepository;

@Autowired
private  FormAttributeRepository formAttributeRepository;

@Autowired
private FormSearchSqlRepository formSearchSqlRepository;


@Autowired
private  CommonUtilApplication  commonUtilApplication; 

@Autowired
private SafFormslistApplication safFormsApplication;

@Autowired
private DbTablesApplication dbTablesApplication;



@Autowired
private  BuildTypeClass buildTypeClass;

@Override
protected String getPagePath(){
	return "/formdesign/forms/";
}

 //跳转到首页
 public String forwardSyfFormsList(){
	 this.putAttribute("uploadPath",SystemCache.getParameter("uploadPath", String.class)+"/source");
	 return forward("syfFormsList");
}
 
//跳转到表单设计页面
/* @SkipAuth
public String forwardEditSafForm(){
	SDO sdo = this.getSDO(); 
	 this.putAttribute("uploadPath",SystemCache.getParameter("uploadPath", String.class)+"/source");
	 String formId=sdo.getString("id");
	 SafFormslist form=(SafFormslist)safFormslistRepository.findOne(formId);
	 
       String tableName=commonUtilApplication.getTablesByFormId(formId,1);
		 tableName=tableName.split(",")[0];  //取第一个主表 
		 //获取表字段元素
	   List<Map<String, Object>> fieldLists=commonUtilApplication.queryFormTableFields(form.getFormNo(),tableName);
        this.putAttribute("fieldLists",JSONObject.toJSON(fieldLists));
        
	    this.putAttribute("form_template",form.getTemplate());
		this.putAttribute("form_name" , form.getFormName());
		this.putAttribute("table_name" , tableName);
		this.putAttribute("formNo" , form.getFormNo());
		this.putAttribute("form_parse" , form.getParse());
		this.putAttribute("form_data" , form.getData());
		this.putAttribute("form_template" , form.getTemplate());
		this.putAttribute("form_html" , form.getHtml());
	
	 return forward("form_edit");
}

//跳转到预览表单页
@SkipAuth
public String previewEditForm(){
	SDO sdo=this.getSDO();
	String formId=sdo.getString("formId");
	String formeditor=sdo.getString("formeditor");
	SafFormslist form = null;
	if(formeditor != null)
		form = SafFormslist.praseTemplate(form,formeditor);
	else if(formId != null && !"".equals(formId)) {
		//form = ueService.findByFormId(formId);
		form=this.safFormslistRepository.findOne(formId);
		
	}
	
	String parse = form.getParse();
	String template = form.getTemplate();
	 Map<String, Object> map =new HashMap<String, Object>();
	map.put("parse", parse);
	map.put("template", template);
	map.put("html", form.getHtml());
	// return forward("form_edit");
	this.putAttribute("parse",parse);
	this.putAttribute("template",template);
	this.putAttribute("html",form.getHtml());
	 return forward("form_edit");
}
 */
 
/**
 * 查询
 * @return 
 */
 public String slicedQuerySyfForms() { 
 	SDO sdo = this.getSDO(); 
   SafFormsQueryRequest queryRequest = sdo.toQueryRequest(SafFormsQueryRequest.class); 
   Map<String, Object> data = this.safFormsApplication.querySyfForms(queryRequest); 
	  return toResult(data);
	 }

 //加载表单编辑页面
public String loadSyfFormsDetail() {
   String id = getSDO().getString("id");
   this.putAttribute("openval",1);
  if (StringUtils.isEmpty(id)) {
	      return forward("syfFormsDetail");
    }else {
    	SafFormslist entity = this.safFormsApplication.loadSyfForms(id);
	      return forward("syfFormsDetail",entity);
   }
}

//加载功能编辑页面
public String loadSyfFormsFunction(){
	 String formId = getSDO().getString("id");
	  if (StringUtils.isEmpty(formId)) {
		      return forward("syfFormsFunction");
	    }else {
	    	SafFormslist entity = this.safFormsApplication.loadSyfForms(formId);
	    	this.putAttribute("formId", entity.getId());
		      return forward("syfFormsFunction",entity);
	   }
	
}


//加载表单配置页面
public String loadSyfFormsSetting(){
	 String formId = getSDO().getString("id");
	  if (StringUtils.isEmpty(formId)) {
		      return forward("syfFormsSetting");
	    }else {
	    	SafFormslist entity = this.safFormsApplication.loadSyfForms(formId);
	    	this.putAttribute("formId", entity.getId());
		      return forward("syfFormsSetting",entity);
	   }
	
}

//加载SearchSQL的自定义数据来源
public String loadDataSourceDetail() {
	   SDO sdo = this.getSDO(); 
	   String id = sdo.getString("id");
	   String formNo=sdo.getString("formNo");
	   List<SafFormslist> formList=this.safFormslistRepository.findByFormNo(formNo);
	   SafFormslist form=formList.get(0);
	  //String targetField=sdo.getString("targetField");
	  // List <FormTables> tableList=formTablesRepository.findByFormId(form.getId());
	 /*  SafFormsQueryRequest queryRequest=new  SafFormsQueryRequest();
	   queryRequest.setFormNo(form.getFormNo());
	   queryRequest.setTableType(0); //查询所有的表
	   List<Map<String, Object>> tableList=this.safFormsApplication.queryExistTables(queryRequest);
	   Map <String, Object>tableMap=new HashMap<String, Object>();
	   for (Map <String, Object>map:tableList){
		  tableMap.put(map.get("tableName").toString(),map.get("name").toString());
	  }*/
	   this.putAttribute("formNo", formNo);
	 // this.putAttribute("tableMap", tableMap);
	  // this.putAttribute("fieldMap", getTableAllFields(form));
	   
	  if (id!=null&&!"".equals(id)) {
		   List <FormSearchSql>list=this.formSearchSqlRepository.findById(id);
		   FormSearchSql entity= list.get(0);
		   this.putAttribute("oldSearchSql",entity.getSearchSql());
	      return forward("dataSourceDetail",entity);
	  }else {
		    // SyfForms entity = this.safFormsApplication.loadSyfForms(id);
	    	FormSearchSql entity=new FormSearchSql();
	    	entity.setFormNo(formNo);
	    	//entity.setTableName(tableName);
	    	//entity.setTargetField(targetField);
	    	this.putAttribute("oldSearchSql","");
		    return forward("dataSourceDetail",entity);
	   }
	}

//加载SearchSQL下一步数据来源
public String loadDataSourceDetailNext() {
	   SDO sdo = this.getSDO(); 
		  String id = sdo.getString("id");
		 // String tableName=sdo.getString("tableName");
		//  String formNo=sdo.getString("formNo");
		//  String targetField=sdo.getString("targetField");
		 //  List <FormSearchSql>list=this.formSearchSqlRepository.searchFormSearchSqlByFormNoAndField(formNo, targetField);
		  String formNo=sdo.getString("formNo");
		   List<SafFormslist> formList=this.safFormslistRepository.findByFormNo(formNo);
		   SafFormslist form=formList.get(0);
		   String tableName=commonUtilApplication.getTablesByFormId(form.getId(),1);
			 tableName=tableName.split(",")[0];  //取第一个主表 
			 
		 // this.putAttribute("fieldMap", getTableAllFields(form));
		   List <FormSearchSql>list=this.formSearchSqlRepository.findById(id);
		   FormSearchSql entity=null;
		  if (list!=null&&list.size()>0) {
			 entity= list.get(0);
			// tableName=entity.getParamSourceTables();
			// entity.setTableName(tableName);
		  }
		  //this.putAttribute("tableName", tableName.toUpperCase());
		return forward("dataSourceDetailNext",entity);
}

//获取表单主表的所有显示字段 
private Map <String, Object> getTableAllFields_(SafFormslist form){
	String tableName=commonUtilApplication.getTablesByFormId(form.getId(),1);
	 tableName=tableName.split(",")[0];  //取第一个主表 
	 
    DbTablesQueryRequest queryRequest=new DbTablesQueryRequest();
    queryRequest.setTableName(tableName.toUpperCase());
    queryRequest.setIsHidden(0);
    Map<String, Object> mapData=dbTablesApplication.querySubDbTableFields(queryRequest);
    @SuppressWarnings("unchecked")
    List<Map<String, Object>> fieldList = (List<Map<String, Object>>) mapData.get("Rows");
    Map <String, Object>fieldMap=new HashMap<String, Object>();
   for (Map <String, Object>map:fieldList){
   	 String fieldCode=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,map.get("fieldCode").toString()); //驼峰法
   	// if (!"formId".equals(fieldCode)&&!"id".equals(fieldCode)&&!"status".equals(fieldCode)){ //去掉formId 、id、status
   	    fieldMap.put(fieldCode,map.get("fieldName").toString());
   }
   return fieldMap;
}


//保存自定义检索SQL明细
public String saveSelectCustom(){
	 SDO sdo = this.getSDO();
	 String type=sdo.getString("type");
	 FormSearchSql  entity = (FormSearchSql) sdo.toObject(FormSearchSql.class);
	 if (!"".equals(sdo.getString("paramSourceTables_text"))&&
			 !(sdo.getString("paramSourceTables_text").equals(sdo.getString("paramSourceTables")))){
		entity.setParamSourceTables(sdo.getString("paramSourceTables_text"));
	 }
	  String sql=entity.getSearchSql().toLowerCase().trim();
	  Map<String, Object> data = new HashMap<String, Object>(); 
	try{
	 if ("1".equals(type)&&"1".equals(sdo.getString("changed"))){  //保存sql语句 页面
	   String fields=sql.split("from")[0];
	  //t.id,t.unit_name,t.unit_type
	  fields=fields.substring(6,fields.length());
	  String realField="",fieldWidths="",fieldTypes="",paramFields="";
	  String []field=null;
	  String fieldCodes="";
	  field=fields.split(",");
	  if (fields.indexOf(".")>0){
		  for (int i=0;i<field.length;i++){
			  realField=field[i].split("\\.")[1];
			  field[i]=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,realField);
		  }
       }
	    for (int i=0;i<field.length;i++){
		   fieldCodes+=field[i].trim();
		   fieldWidths+="100";
		  if ("id".equals(fieldCodes)||fieldCodes.endsWith("id")){//id或以id结尾的 隐藏
			  fieldTypes+="1";
		  } else {
		      fieldTypes+="0";
		  }
		  if (i<field.length-1){
			  fieldCodes+=",";
			  fieldWidths+=",";
			  fieldTypes+=",";
		  }
	    }
	    //判断是否存在 以冒号开头的指定参数
	    if (sql.indexOf(":")>0){
	    	String []params=sql.split(":");
	    	 for (int k=1;k<params.length;k++){
	    		 if  (params[k].indexOf(")")>0){ //后面有括号
	    			 paramFields+=params[k].split(")")[0]; 
	    		 }else {
	    			 paramFields+=params[k].split(" ")[0];  // 注意写SQL时：参数后面还有 添加空格
	    		 }
	    		// paramSourceFields+="";
	    		 if (k<params.length-1){
	    			 paramFields+=",";
	    			// paramSourceFields+=",";
	    		 }
	    	}
	    }
	   entity.setFieldNames(fieldCodes);
	   entity.setFieldCodes(fieldCodes);
	   entity.setFieldTypes(fieldTypes);
	   entity.setCreatedDate(new Date());
	   if (entity.getFieldWidths()==null){
	     entity.setFieldWidths(fieldWidths);
	   }
	  // entity.setBackFields(fieldCodes);
	   entity.setParamFields(paramFields);
	 //  entity.setParamSourceFields(paramSourceFields);
	   if (entity.getCondiColumns()!=null&&!"".equals(entity.getCondiColumns())){
	      String []condiColumns=entity.getCondiColumns().split(",");
	      String condiTypes="";
	      for (int w=0;w<condiColumns.length;w++){
	    	  condiTypes+="java.lang.String";
	    	  if (w<condiColumns.length-1){
	    		 condiTypes+=",";
	 	     }
	      }
	      String condiNames=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,entity.getCondiColumns());
	      entity.setCondiNames(condiNames);
	      entity.setCondiTypes(condiTypes);
	   }
	   
	   //保存当前字段的数据来源类型
	  // SafFormslist forms=this.safFormslistRepository.findByTableName(entity.getTableName()).get(0);
	   List <SafFormslist>formList=this.safFormslistRepository.findByFormNo(entity.getFormNo());
	 //  FormTables  formTables=formTablesRepository.findByTableName(entity.getTableName()).get(0);
	   SafFormslist forms=null;
	   if  (formList!=null&&formList.size()>0){
	       forms=formList.get(0);
	   } else {
		   throw new RuntimeException(String.format("表单编号“%s”不存在！", entity.getFormNo()));
	   }
	   //查找表单定义属性
	  /* List<FormAttribute> formAttriList=formAttributeRepository.findByFormId(forms.getId());
	   
	   String []fieldEns=new String[formAttriList.size()];
	   String []dataSourceTypes=new String[formAttriList.size()];
	   FormAttribute formAttribute=null;
	   for  (int x=0;x<formAttriList.size();x++){
		   formAttribute=formAttriList.get(x);
		   dataSourceTypes[x]=formAttribute.getDataSourceType()!=null?formAttribute.getDataSourceType().toString():"";
	   }
	  // String []fieldEns=forms.getShowfieldsEn().split(",");
	   String []tempSourceTypes=new String[formAttriList.size()];
	  // String []dataSourceTypes=forms.getDataSourceType().split(",");

	   for (int f=0;f<tempSourceTypes.length;f++){
		   tempSourceTypes[f]="";
		   if (dataSourceTypes.length>f){
		      tempSourceTypes[f]=dataSourceTypes[f];
		   }
	   }
	   for (int c=0;c<fieldEns.length;c++){
		   if (entity.getTargetField().equals(fieldEns[c])){
			   tempSourceTypes[c]="2";
			   break;
		   }
	   }
	   String dataSourceType="";
	   for (int f=0;f<tempSourceTypes.length;f++){
		   dataSourceType+=tempSourceTypes[f];
		   if (f<tempSourceTypes.length-1){
			   dataSourceType+=",";
  		   }
	   }*/
	   //forms.setDataSourceType(dataSourceType);  //需要修改    保存到FormAttribute  ????  
	  // this.safFormslistRepository.save(forms);
	  }
	 if (!"".equals(sdo.getString("id"))){
	    StringBuffer sb=getXml(entity);
	    entity.setContent(sb.toString());
	    
	    //放入缓存中 SystemCache
		  String key=entity.getFormNo()+".searchbox."+entity.getSearchName();
		  SystemCache.removeOther(key);
		  SystemCache.putOther(key, (Serializable)sb.toString());
	 }
	  this.formSearchSqlRepository.save(entity);
	  data.put("id", entity.getId());
	  
   } catch (Exception e) {
	  e.printStackTrace();
   }
	
	  return toResult(data);
	 
}

//拼装XML
private StringBuffer getXml(FormSearchSql  entity){
	   StringBuffer sb=new StringBuffer("");
	  sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
	  	.append("<easy-search-mappings>")
	  	.append("<easy-search name=\"").append(entity.getSearchName()).append("\" desc=\"")
	  	.append(entity.getSearchDesc()).append("\">")
	  	.append("<sql>")
	  	.append(entity.getSearchSql())
	  	.append("</sql>");
		 String []fieldCode=entity.getFieldCodes().split(",");
		 String []fieldType=entity.getFieldTypes().split(",");
		 String []fieldName=entity.getFieldNames().split(",");
		 String []fieldWidth=entity.getFieldWidths().split(",");
		 for (int u=0;u<fieldCode.length;u++){
			 if ("1".equals(fieldType[u])){ //1表示隐藏
				sb.append("<field name=\"").append(fieldCode[u]).append("\" code=\"")
				.append(fieldCode[u]).append("\" type=\"hidden\" />");
			 } else {
			    sb.append("<field name=\"").append(fieldName[u]).append("\" code=\"")
			    .append(fieldCode[u]).append("\" width=\"").append(fieldWidth[u]).append("\" />");
			 }
		 }
	  //	sb.append("<field name=\"id\" code=\"id\" type=\"hidden\" />")
	  //	.append("<field name=\"单位名称\" code=\"unitName\" width=\"140\" />")
	  //	.append("<field name=\"单位类别\" code=\"unitType\" width=\"120\" />")
	  if (entity.getCondiColumns()!=null&&!"".equals(entity.getCondiColumns())){
		 String []condiCol=entity.getCondiColumns().split(",");
		 String []condiType=entity.getCondiTypes().split(",");
		 String []condiSymb=entity.getCondiSymbols().split(",");
		 String []condiAlias=entity.getCondiAlias().split(",");
		 
		 for (int u=0;u<condiCol.length;u++){
			sb.append("<condition column=\"").append(condiCol[u])
			.append("\" name=\"").append(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,condiCol[u]))
			.append("\" type=\"").append(condiType[u]).append("\" symbol=\"").append(condiSymb[u])
			.append("\" alias=\"").append(condiAlias[u]).append("\"/>");
			
			//project_id\" name=\"projectId\" type=\"java.lang.String\" symbol=\"=\" alias=\"t\"/>") 
		 }
	  //	sb.append("<condition column=\"project_id\" name=\"projectId\" type=\"java.lang.String\" symbol=\"=\" alias=\"t\"/>")
	  }
	  	sb.append("<orderby>").append(entity.getOrderby()).append("</orderby>");
	  	sb.append("</easy-search>").append(" </easy-search-mappings>");
	  	return sb;
	
}

//删除表单相关配置信息
public String deleteFormSettings() {
		SDO sdo = this.getSDO();
		String type=sdo.getString("type");
		//String id=sdo.getString("id");
		//SyfForms  entity = (SyfForms) sdo.toObject(SyfForms.class);
		//SafFormslist forms=this.safFormslistRepository.findOne(sdo.getString("id"));
		List <String> list=getSDO().getIds();
		this.safFormsApplication.deleteFormSettings(type, list);
		// this.safFormsApplication.deleteCustomButton(sdo.getString("id"), btnName, btnValue);
		
	
		 return success(sdo.getString("id"));
	}

//表单的属性
public String forwardTableProperty(){
	SDO sdo = this.getSDO();
	//ProjectTemplate template=this.projectTemplateRepository.findOne(sdo.getString("nodeId"));
	return forward("tableProperty",sdo);
}

//{Total=3, page=1, Rows=[{showfieldsEn=formNo,formName,packageName,formPath,
	//	tableName,showfieldsEn,showfieldsCh,mustinputField,showfieldsType,fieldTag,dataSourceType, 
	//	,formNo=project, dataSourceTypeTextView=无,数据字典,数据字典,数据字典,数据字典,数据字典,数据字典,数据字典, 
	//	dataSource=,projectType,,,,,,,, dataSourceType=1,3,3,3,3,3,3,3,}]}


//查询表单按钮列表 
public String slicedQueryFormButton() { 
 	SDO sdo = this.getSDO(); 
    SafFormsQueryRequest queryRequest = sdo.toQueryRequest(SafFormsQueryRequest.class); 
    List<Map<String, Object>> data=safFormsApplication.queryformButtonList(queryRequest);
   //   Map pageMap=(Map<String, Object>)((List)map.get("Rows")).get(0);
     // pageMap.get("");
 	//  return toResult(map);
    return packGridDataAndResult(data);
}

//查询Grid列表显示字段和查询字段列表
/*
 * parm: type:list/search
 */
public String slicedQueryGridFields(){
	SDO sdo = this.getSDO(); 
    SafFormsQueryRequest queryRequest = sdo.toQueryRequest(SafFormsQueryRequest.class); 
    List<Map<String, Object>> data=null;
    if ("list".equals(sdo.getString("type"))){
    	 data=safFormsApplication.queryDisplayListFields(queryRequest);
    } else{
    	 data=safFormsApplication.queryDisplaySearchFields(queryRequest);
    }
    return packGridDataAndResult(data);
}



/**
 * 查询表单配置数据列表 
 */
public String slicedQueryFormParameter(){
	SDO sdo = this.getSDO(); 
	FormParameterQueryRequest queryRequest = sdo.toQueryRequest(FormParameterQueryRequest.class); 
    List<Map<String, Object>> data=null;
   	 data=safFormsApplication.queryFormParameter(queryRequest);

    return packGridDataAndResult(data);
}

//加载函数或过程内容页面
public String loadFunctionOrProcduceContent() {
 String id = getSDO().getString("id");
 String name = getSDO().getString("name");
 this.putAttribute("name", name);
 return forward("viewProcduceContent");
}

/**
 * 查询表单配置函数或过程的内容 
 */
public String slicedQueryFormFunctionOrProcduceContent(){
	SDO sdo = this.getSDO(); 
	FormParameterQueryRequest queryRequest = sdo.toQueryRequest(FormParameterQueryRequest.class); 
    Map<String, Object> data =safFormsApplication.queryFormFunctionOrProcduceContent(queryRequest);
   	 return toResult(data);
    // return packGridDataAndResult(data);
    //return success(sb.toString());
}

/**
 * 查询表的基本属性
 */
public String queryTableProperty(){
	SDO sdo = this.getSDO();
	try {
		SafFormsQueryRequest queryRequest = sdo.toQueryRequest(SafFormsQueryRequest.class);
		List<Map<String, Object>> data = this.safFormsApplication.queryTableProperty(queryRequest);
		return packGridDataAndResult(data);
	} catch (Exception e) {
		return error(e);
	}
}

 //保存表单基本显示属性
 public String saveSafForms() {
     SDO sdo = getSDO();
   SafFormslist  entity = sdo.toObject(SafFormslist.class);
   List <Object> plist=sdo.getList("detailData1");
  // this.syfFormsRepository.save(entity);
   this.safFormsApplication.saveSafForms(entity, plist);
   return success();
}

 
 
 /**
	 * 保存表的字段编辑属性
	 * @return
	 */
	public String saveTableFieldAttributeList_old(){  //??
		SDO sdo = this.getSDO();
		//String nodeId = sdo.getString("nodeId"); //pmId
		String tableName=sdo.getString("tableName");
		String id=sdo.getString("id");
		List<PropertyDefines> plist=sdo.getList("detailData1", PropertyDefines.class);
		//  String id ="";
		if (plist!=null&&plist.size()>0){
		   id = this.safFormsApplication.saveTableFieldAttributeList_old(id,tableName,plist);
		}
		return success(id);
	}
	
	/*
	 * 保存表单的按钮列表 
	 */
	public String saveFormButtonLists(){
		
		SDO sdo = this.getSDO();
		//String nodeId = sdo.getString("nodeId"); //pmId
		String tableName=sdo.getString("tableName");
		String formId=sdo.getString("formId");
		List<FormButtonVO> plist=sdo.getList("detailData1", FormButtonVO.class);
		  String id ="";
		if (plist!=null&&plist.size()>0){
		   id = this.safFormsApplication.saveFormButtonLists(formId,tableName,plist);
		}
		return success(id);
	}
	
	/*
	 * 保存列表显示字段 
	 */
	public String saveDisplayFields(){
		
		SDO sdo = this.getSDO();
		//String nodeId = sdo.getString("nodeId"); //pmId
		//String tableName=sdo.getString("tableName");
		String formId=sdo.getString("formId");
		List<FormAttribute> plist=sdo.getList("detailData1", FormAttribute.class);
		  String id ="";
		if (plist!=null&&plist.size()>0){
		   id = this.safFormsApplication.saveDisplayListFields(formId,plist);
		}
		return success(id);
	}
	
	/*
	 * 保存列表查询条件字段
	 */
	public String saveSearchFields(){
		
		SDO sdo = this.getSDO();
		//String nodeId = sdo.getString("nodeId"); //pmId
		String tableName=sdo.getString("tableName");
		String formId=sdo.getString("formId");
		List<FormAttribute> plist=sdo.getList("detailData1", FormAttribute.class);
		  String id ="";
		if (plist!=null&&plist.size()>0){
		   id = this.safFormsApplication.saveSearchFields(formId,plist);
		}
		return success(id);
	}
	
	//保存自定义的按钮
	public String saveCustomButton(){
		SDO sdo = this.getSDO();
		String btnName=sdo.getString("buttonName");
		String btnValue=sdo.getString("buttonValue");
		//SyfForms  entity = (SyfForms) sdo.toObject(SyfForms.class);
		//SafFormslist forms=this.safFormslistRepository.findOne(sdo.getString("id"));
	    this.safFormsApplication.saveCustomButton(sdo.getString("id"), btnName, btnValue);
	
	//	btnValue=forms.getFormbuttonsMethodName()+","+btnValue;
		//btnName=forms.getFormbuttonsName()+","+btnName;
	//	forms.setFormbuttonsMethodName(btnValue);
		//forms.setFormbuttonsName(btnName);
	//	this.safFormslistRepository.save(forms);
		return success(sdo.getString("id"));
	}
	

	 //删除自定义按钮方法
	public String deleteCustomButton() {
		SDO sdo = this.getSDO();
		String btnName=sdo.getString("buttonName");
		String btnValue=sdo.getString("buttonValue");
		//SyfForms  entity = (SyfForms) sdo.toObject(SyfForms.class);
		//SafFormslist forms=this.safFormslistRepository.findOne(sdo.getString("id"));
		
		 this.safFormsApplication.deleteCustomButton(sdo.getString("id"), btnName, btnValue);
		
		//String oldBtnValue=forms.getFormbuttonsMethodName()+",";
	//	String oldBtnName=forms.getFormbuttonsName()+",";
		//oldBtnValue=oldBtnValue.replaceAll(btnValue+",", ""); //去掉自定义按钮
		//oldBtnName=oldBtnName.replaceAll(btnName+",",""); 
		
		//oldBtnValue=oldBtnValue.substring(0,oldBtnValue.length()-1);
		//oldBtnName=oldBtnName.substring(0,oldBtnName.length()-1);
		
		//forms.setFormbuttonsMethodName(oldBtnValue);
		//forms.setFormbuttonsName(oldBtnName);
		
		//this.safFormslistRepository.save(forms);
		 return success(sdo.getString("id"));
	}
	
	//进入自定义按钮页面
	public String  loadCustomButtonDetail(){
		 return forward("customButtonDetail");
	}
	
   //删除
   public String deleteSyfForms() {
    this.safFormsApplication.deleteSyfFormsByIds(getSDO().getIds());
	  return success();
   }

   /*
	 * 根据表生成的所有代码
	 */
	public String  produceSourceCode(){
		SDO sdo = getSDO();
		String id=sdo.getString("id");
		String tableName=sdo.getString("tableName");
		tableName=tableName.split(",")[0];  //取第一个主表的 名称
		DbTablesQueryRequest queryRequest = sdo.toQueryRequest(DbTablesQueryRequest.class);
		SafFormslist form=this.safFormslistRepository.findOne(id);
		queryRequest.setTableName(tableName);
		//查询数据库表的列   根据数据库字段    要支持多种类型数据库   需要修改 ？？？？
		 // dbtables.xml-->dbTables_columns
		//List<Map<String, Object>> fieldList=this.dbTablesApplication.queryDbTableColumns(queryRequest); //旧的查询列字段方法
		List<Map<String, Object>> singleList = commonUtilApplication.queryDataRecordSingleFields(queryRequest.getId(),queryRequest.getTableName());
		String backStr="1";
		
	    //tableName
	    SafFormsQueryRequest formQueryRequest=sdo.toQueryRequest(SafFormsQueryRequest.class);;
	     formQueryRequest.setTableName(tableName);
	     
	     //查询表单的字段属性    safFormslist.xml-->syfForms 
	     Map<String, Object> map=safFormsApplication.querySyfForms(formQueryRequest);
	     
	     // Map <String, Object>pageMap=formList.get(0);
	     Map <String, Object>pageMap=(Map<String, Object>)((List)map.get("Rows")).get(0);
		//Map<String, Object> pageMap=(Map<String, Object>)map.get("Rows");
	    String packageName=pageMap.get("packageName").toString();
	    String formPath= pageMap.get("formPath").toString();
	     tableName=tableName.toLowerCase();
	     pageMap.put("tableName",tableName);
	     ParamFormVO paraForm=null;
	     
	    try {  
	      /* List <FormSearchSql> customlists=formSearchSqlRepository.searchSqlByFormNo(form.getFormNo());
	       List <SeleListCustomVO> listNew=new  ArrayList<SeleListCustomVO>();
	       SeleListCustomVO customVO=null;
	       String backFields="",paramSourceFields="";
	       for (int i=0;i<customlists.size();i++){
	    	   customVO=new SeleListCustomVO();
	    	   Utils.CopyBean(customlists.get(i),customVO);
	    	   if (customVO.getBackFields()!=null){
	    	     backFields=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,customVO.getBackFields()); //转成驼峰法
	    	     customVO.setBackFields(backFields);
	    	   }
	    	   if (customVO.getParamSourceFields()!=null){
	    	     paramSourceFields=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,customVO.getParamSourceFields()); //转成驼峰法
	       	     customVO.setParamSourceFields(paramSourceFields);
	    	   }
	    	   listNew.add(customVO);
	       }
	       pageMap.put("selectCustcoms", listNew);
	       */
	      //组装参数对象
		   //paraForm=this.getParamFormVO(pageMap); //旧的方法 作废
			//paraForm = Utils.omposeAttributes(singleList, "", "", null);
			paraForm=safFormsApplication.getFieldAttributes(formQueryRequest);
			pageMap.put("tableName",tableName);
			this.addParamByParamForm(paraForm,pageMap);
			/*paraForm.setIsform(0);
			paraForm.setUploadPath(SystemCache.getParameter("uploadPath", String.class)+"/source");
			paraForm.setPackageName(pageMap.get("packageName").toString());
			paraForm.setTableName(tableName);
			paraForm.setFormPath(pageMap.get("formPath").toString());
			paraForm.setFormName(pageMap.get("formName").toString());
			paraForm.setBtnNames(pageMap.get("formbuttonsName").toString().split(","));
			paraForm.setBtnMethodNames(pageMap.get("formbuttonsMethodName").toString().split(","));
           */
           //获取当前的明细列表配置信息
		  // this.safFormsApplication.getDetailTables(formQueryRequest,paraForm);

	      File file=null;
	      String paths[]=packageName.split("\\.");
	      //String path = this.getClass().getResource("/").getPath();
	      String srcPath =paraForm.getUploadPath();
	      file=new File(srcPath);
			if (!file.exists()){
			  file.mkdir();
			}
	      //建立源码路径
	      for (int i=0;i<paths.length;i++){
	    	   file=new File(srcPath+"/"+paths[i]);
  			  if (!file.exists()){
  				  file.mkdir();
  			  }
  			srcPath+="/"+paths[i];
	      }
	       paraForm.setSrcPath(srcPath);
	    //   CompileUtil cputil=new CompileUtil();
	     //  BuildFilerInter bfile=null;
		//生成实体domain、Query 
	      if (singleList.size()>0){  //
	    	  backStr=buildTypeClass.getBuildClass(Constant.BUILD_ENTITY).generateFile(paraForm,singleList);
			  backStr=buildTypeClass.getBuildClass(Constant.BUILD_QUERYREQUEST).generateFile(paraForm,null);
			  backStr=buildTypeClass.getBuildClass(Constant.BUILD_REPOSITORY).generateFile(paraForm,null);
			  backStr=buildTypeClass.getBuildClass(Constant.BUILD_APPLICATION).generateFile(paraForm,null);
			  backStr=buildTypeClass.getBuildClass(Constant.BUILD_APPLICATION).generateFile(paraForm,null);
			  backStr=buildTypeClass.getBuildClass(Constant.BUILD_CONTROLLER).generateFile(paraForm,null);

			  if (paraForm.getDetails().size()>0) {  //存在明细表
				  List<ParamFormVO> pFormDetails = paraForm.getDetails();
				  for (ParamFormVO pFormDetailVO : pFormDetails) {

					  pageMap.put("formbuttonsName",new String[]{"新增行","删除行","保存行"});  //明细页面默认按钮
					  pageMap.put("formbuttonsMethodName",new String[]{"addRow","deleteRow","saveRow"});
					  addParamByParamForm(pFormDetailVO, pageMap);

					  singleList = commonUtilApplication.queryDataRecordSingleFields(queryRequest.getId(), pFormDetailVO.getTableName());
					  backStr=buildTypeClass.getBuildClass(Constant.BUILD_ENTITY).generateFile(pFormDetailVO, singleList);
					  backStr=buildTypeClass.getBuildClass(Constant.BUILD_QUERYREQUEST).generateFile(pFormDetailVO,null);
					  backStr=buildTypeClass.getBuildClass(Constant.BUILD_REPOSITORY).generateFile(pFormDetailVO,null);
					  backStr=buildTypeClass.getBuildClass(Constant.BUILD_APPLICATION).generateFile(pFormDetailVO,null);
					  backStr=buildTypeClass.getBuildClass(Constant.BUILD_APPLICATION).generateFile(pFormDetailVO,null);
					  backStr=buildTypeClass.getBuildClass(Constant.BUILD_CONTROLLER).generateFile(pFormDetailVO,null);
				  }
			  }
		  }


		//生成页面文件
	      String filePaths[]=formPath.split("/");
	      srcPath = paraForm.getUploadPath();

	      for (int i=0;i<filePaths.length;i++){
	    	   file=new File(srcPath+"/"+filePaths[i]);
 			  if (!file.exists()){
 				  file.mkdir();
 			  }
 			srcPath+="/"+filePaths[i];
	      }
	      //查询页面表单元素
	        
	        paraForm.setSrcPath(srcPath);
	       	backStr=buildTypeClass.getBuildClass(Constant.BUILD_PAGELIST).generateFile(paraForm,null);
		    backStr=buildTypeClass.getBuildClass(Constant.BUILD_PAGEDETAIL).generateFile(paraForm,null);
            backStr=buildTypeClass.getBuildClass(Constant.BUILD_PAGEJS).generateFile(paraForm,null);
		    backStr=buildTypeClass.getBuildClass(Constant.BUILD_XML).generateFile(paraForm,null);
		   
	       } catch (Exception e) {
				e.printStackTrace();
		   }
	      System.out.println("===========Sucess Complete GenerateCode!!!==========");
		
	      return toResult(backStr);
	}
	//生成代码 添加默认参数
	public void addParamByParamForm(ParamFormVO paramFormVO,Map <String,Object>pageMap){

		paramFormVO.setIsform(0);
		paramFormVO.setUploadPath(SystemCache.getParameter("uploadPath", String.class)+"/source");
		paramFormVO.setPackageName(pageMap.get("packageName").toString());
		paramFormVO.setTableName(pageMap.get("tableName").toString());
		paramFormVO.setFormPath(pageMap.get("formPath").toString());
		paramFormVO.setFormName(pageMap.get("formName").toString());
		paramFormVO.setBtnNames(pageMap.get("formbuttonsName").toString().split(","));
		paramFormVO.setBtnMethodNames(pageMap.get("formbuttonsMethodName").toString().split(","));

	}
	/*
	 * 表单发布 （生成页面文件）
	 */
	public  String producePageFile(){
		String backStr="";
		SDO sdo =this.getSDO();
	   String tableName=sdo.getString("tableName");  //主表名称
	   SafFormsQueryRequest formQueryRequest=sdo.toQueryRequest(SafFormsQueryRequest.class);;
	  // String pageName=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,tableName);
	   //formQueryRequest.setTableName(tableName);
        backStr=safFormsApplication.needGenerateFile(formQueryRequest.getFormNo());
        Map <String,Object>map=new HashMap<String,Object>();
        map.put("result",backStr);
	    return toResult(map);
	}
	
	//代码生成器-->组装参数对象    旧的方法 作废
	public ParamFormVO getParamFormVO(Map <String, Object>pageMap){
		ParamFormVO paraForm = new ParamFormVO();
		try {
		 paraForm.setIsform(0);
	 	 paraForm.setUploadPath(SystemCache.getParameter("uploadPath", String.class)+"/source");
	 	 
		 paraForm.setTableName(pageMap.get("tableName").toString());
		 paraForm.setPackageName(pageMap.get("packageName").toString());
		 paraForm.setFormPath(pageMap.get("formPath").toString());
		 paraForm.setFormName(pageMap.get("formName").toString());

		 paraForm.setFieldEns(pageMap.get("showfieldsEn").toString().split(","));
		 paraForm.setFieldChs(pageMap.get("showfieldsCh").toString().split(","));
	 	 paraForm.setValidatorTypes(pageMap.get("validatorType").toString().split(","));

		paraForm.setFieldTags(pageMap.get("fieldTag").toString().split(","));
		paraForm.setDataSourceTypes(pageMap.get("dataSourceType").toString().split(","));
		paraForm.setDataSources(pageMap.get("dataSource").toString().split(";"));
		paraForm.setMustinputFields(pageMap.get("mustinputField").toString().split(","));

		paraForm.setFieldsLengths(pageMap.get("showfieldsLengths").toString().split(","));

		paraForm.setBtnNames(pageMap.get("formbuttonsName").toString().split(","));
		paraForm.setBtnMethodNames(pageMap.get("formbuttonsMethodName").toString().split(","));

		paraForm.setDisplayFields(pageMap.get("listdisplayField").toString().split(","));
		paraForm.setDisplayFieldnames(pageMap.get("listdisplayFieldname").toString().split(","));
		paraForm.setDisplayFieldTypes(pageMap.get("listdisplayFieldType").toString().split(","));
		paraForm.setSearchFields(pageMap.get("listdisplaySearchField").toString().split(","));

		paraForm.setCssStyle(pageMap.get("cssStyle").toString().split(","));
		paraForm.setCheckFunction(pageMap.get("checkFunction").toString().split(","));
		paraForm.setDefaultOperation(pageMap.get("defaultOperation").toString().split(","));

		paraForm.setPagedatailCols(!"".equals(pageMap.get("pagedatailCols")) ? pageMap
				.get("pagedatailCols").toString() : Constant.PAGEDETAIL_COLS);
		paraForm.setLabelCols(Integer.parseInt(pageMap.get("labelCols").toString()));
		paraForm.setFieldCols(Integer.parseInt(pageMap.get("fieldCols").toString()));
		paraForm.setTextAreaRows(Integer.parseInt(pageMap.get("textareaRows").toString()));
		paraForm.setExistAttachment(Integer.parseInt(pageMap.get("existAttachment").toString()));
		if  (pageMap.get("selectCustcoms")!=null){
		    paraForm.setSelectCustoms((List <SeleListCustomVO>)pageMap.get("selectCustcoms"));
		  
		} else {
			paraForm.setSelectCustoms(null);
		}
		List <String> hiddenList=new ArrayList<String>();
		 hiddenList.add("id");
		paraForm.setHiddenFields(hiddenList);
		if ("1".equals(pageMap.get("existAttachment").toString())){
			 hiddenList.add("attbizid");
			paraForm.setHiddenFields(hiddenList);
		}

		}catch (Exception ex){
			ex.printStackTrace();
		}
		return paraForm;
	}
	
		
		  /**
	     * 分页查询待选择的数据模型列表
	     * @return
	     */
		public String queryAlternativeTableLists() {
			SDO sdo = getSDO();
			SafFormsQueryRequest queryRequest = sdo.toQueryRequest(SafFormsQueryRequest.class);
			Map<String, Object> data = this.safFormsApplication.queryAlternativeTableLists(queryRequest);
			//return toResult(data);
			return this.toResult(data);
		}
		
		/**
		 * 查询已经选择的数据模型 
		 * @return
		 */
		public String querySelectedTableLists(){
			SDO sdo = this.getSDO();
			SafFormsQueryRequest queryRequest = sdo.toQueryRequest(SafFormsQueryRequest.class);
			List<Map<String, Object>> data = this.safFormsApplication.querySelectedTableLists(queryRequest);
			return packGridDataAndResult(data);
		}
		/**
		 * 生成菜单基本信息                 
		 * @return
		 */
		public String produceMenuList(){
			SDO sdo = getSDO();
			SafFormsQueryRequest queryRequest = sdo.toQueryRequest(SafFormsQueryRequest.class);
			Map<String, Object> data =this.safFormsApplication.produceMenuList(queryRequest);

			return this.toResult(data);
		}
		
		/**
		 * 判断表单编号是否重复
		 * @return
		 */
		public String  getExistFormNo(){
			SDO sdo=this.getSDO();
			String id=sdo.getString("id");
		    Map<String, Object> map =new HashMap<String, Object>();
		       map.put("flag","0");
		       List<SafFormslist>  list=this.safFormslistRepository.findByFormNo(sdo.getString("formNo"));
		    if (list!=null&&list.size()>0){
		        if (StringUtil.isNotBlank(id)){
		        	SafFormslist safFormslist=list.get(0);
		        	if (!id.equals(safFormslist.getId())){
		        		map.put("flag","1");
		        	} 
		        } else {
		    	   map.put("flag","1");  
		        }
		    }
			return toResult(map);
		}
	
}

