package com.huigou.uasp.form.application.impl;

import com.google.common.base.CaseFormat;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.uasp.bmp.common.application.BaseApplication;
import com.huigou.uasp.bmp.opm.domain.model.resource.SysFunction;
import com.huigou.uasp.bmp.opm.proxy.SysFunctionApplicationProxy;
import com.huigou.uasp.bmp.opm.repository.org.SysFunctionRepository;
import com.huigou.uasp.builder.BuildTypeClass;
import com.huigou.uasp.builder.filer.BuildPageDetailFile;
import com.huigou.uasp.builder.vo.ParamFormVO;
import com.huigou.uasp.builder.vo.SeleListCustomVO;
import com.huigou.uasp.form.application.CommonUtilApplication;
import com.huigou.uasp.form.application.SafFormslistApplication;
import com.huigou.uasp.form.domain.model.*;
import com.huigou.uasp.form.domain.query.FormParameterQueryRequest;
import com.huigou.uasp.form.domain.query.SafFormsQueryRequest;
import com.huigou.uasp.form.repository.*;
import com.huigou.uasp.meta.domain.model.MetaData;
import com.huigou.uasp.meta.repository.MetaDataRepository;
import com.huigou.uasp.model.application.impl.DbTableService;
import com.huigou.uasp.model.domain.query.DbTablesQueryRequest;
import com.huigou.uasp.util.Constant;
import com.huigou.uasp.util.Utils;
import com.huigou.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.io.File;
import java.util.*;

//import com.huigou.util.CommonUtil;
//import com.huigou.util.SDO;
//import com.huigou.uasp.util.Utils;


@Service("safFormslistApplication")
public class SafFormslistApplicationImpl extends BaseApplication implements SafFormslistApplication { 

 static String QUERY_XML_FILE_PATH = "config/formdesign/safFormslist.xml";
 private String pagePath = "/customform/";
 
@Autowired
private SafFormslistRepository safFormslistRepository;

@Autowired
private SysFunctionRepository   sysFunctionRepository;

@Autowired
private FormTablesRepository  formTablesRepository;

@Autowired
private  FormButtonsRepository formButtonsRepository;

@Autowired
private  FormAttributeRepository formAttributeRepository;

@Autowired
private DbTableService dbTableService;

@Autowired
private MetaDataRepository metaDataRepository;

@Autowired
private FormSearchSqlRepository formSearchSqlRepository;

@Autowired
private SysFunctionApplicationProxy sysFunctionApplication;

@Autowired
private  CommonUtilApplication  commonUtilApplication; 


@Autowired
private  BuildTypeClass buildTypeClass;

@Override
public Map<String, Object> querySyfForms(SafFormsQueryRequest queryRequest) { 
 	 return this.sqlExecutorDao.executeSlicedQuery(getQueryDescriptor(), queryRequest);
}
 
private QueryDescriptor getQueryDescriptor() {
   return this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "querySafFormList");
 } 
 
private QueryDescriptor getQueryDescriptor(String entityName) {
    return this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, entityName);
}

private QueryDescriptor getQueryDescriptor(String filePath,String entityName) {
    return this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, entityName);
}
//查询表单的按钮
@Override
public List<Map<String, Object>> queryformButtonList(SafFormsQueryRequest queryRequest) { 
 	// return this.sqlExecutorDao.executeSlicedQuery( getQueryDescriptor(queryRequest.getTableName(),"formButtonList"), queryRequest);
	String sql = getQueryDescriptor(queryRequest.getTableName(),"formButtonList").getSql();
	return this.sqlExecutorDao.queryToListMap(sql,queryRequest.getId());

}

@Override
public  List<Map<String, Object>> queryDisplayListFields(SafFormsQueryRequest queryRequest){
	String sql = getQueryDescriptor("gridListFields").getSql();
	return this.sqlExecutorDao.queryToListMap(sql,queryRequest.getId());
}

@Override
public List<Map<String, Object>> queryDisplaySearchFields(SafFormsQueryRequest queryRequest){
	String sql = getQueryDescriptor("gridSearchFields").getSql();
	return this.sqlExecutorDao.queryToListMap(sql,queryRequest.getId());
}


//查询表单配置列表数据
@Override
public List<Map<String, Object>> queryFormParameter(FormParameterQueryRequest queryRequest){

	String sql = "";
	if (queryRequest.getParmType()==1){
		sql = getQueryDescriptor("queryFormParameterPrompt").getSql();
	} else if (queryRequest.getParmType()==2){
		sql = getQueryDescriptor("queryFormParameterSearchSQL").getSql();
		return this.sqlExecutorDao.queryToListMap(sql,queryRequest.getFormNo());
	} else if (queryRequest.getParmType()==3){
		sql = getQueryDescriptor("queryFormFunctionOrProcduce").getSql();
		return this.sqlExecutorDao.queryToListMap(sql,"FUNCTION");
		
	} else if (queryRequest.getParmType()==4){
		sql = getQueryDescriptor("queryFormFunctionOrProcduce").getSql();
		return this.sqlExecutorDao.queryToListMap(sql,"PROCEDURE");
	}
	return this.sqlExecutorDao.queryToListMap(sql,queryRequest.getFormNo(),queryRequest.getParmType());
	
}

//查询表单配置函数或过程的 内容
@Override
public Map<String, Object> queryFormFunctionOrProcduceContent(FormParameterQueryRequest queryRequest){

	//String sql =getQueryDescriptor("queryFormFunctionOrProcduceContent").getSql();
	 QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor("queryFormFunctionOrProcduceContent"), queryRequest);
    // queryModel.setPageSize(50);//默认50
    // queryModel.setPageIndex(1);
     String sql=queryModel.getSql();
     
     sql+=" and name='"+queryRequest.getName()+"'";
 	if (queryRequest.getParmType()==3){
 		 sql+=" and  TYPE='FUNCTION' ";
 	} else if (queryRequest.getParmType()==4){
 		 sql+=" and  TYPE='PROCEDURE' ";
 	
 	}
    // sql+=" and c.form_no='"+queryRequest.getFormNo()+"'";
     queryModel.setSql(sql);
     
     Map<String, Object> mapData = this.sqlExecutorDao.executeSlicedQuery(queryModel);
     //@SuppressWarnings("unchecked")
    // List<Map<String, Object>> list = (List<Map<String, Object>>) mapData.get("Rows");
        return mapData;
	//return this.sqlExecutorDao.queryToListMap(sql);
	
}



@Override
public SafFormslist  loadSyfForms(String id) {
  Assert.hasText(id, Constant.ID_NOT_BLANK); 
	 return this.safFormslistRepository.findOne(id);
}
 
 @Transactional
 @Override
public void deleteSyfFormsByIds(List<String> ids) {
   List<SafFormslist> list = this.safFormslistRepository.findAll(ids); 
   
   for (String formId:ids){
      //删除关联属性
      this.formAttributeRepository.deleteFormAttribute(formId);
      //删除关联表
      this.formTablesRepository.deleteFormTables(formId);
      //删除按钮
      this.formButtonsRepository.deleteFormButtons(formId);
   }
   
   this.safFormslistRepository.delete(list);
  }
 
 
 @Override
  public List<Map<String, Object>> queryTableProperty(SafFormsQueryRequest queryRequest) {
		String sql = null;
		sql = getQueryDescriptor(queryRequest.getTableName(),"tableProperty").getSql();
		return this.sqlExecutorDao.queryToListMap(sql,queryRequest.getTableName(),queryRequest.getTableName(),queryRequest.getId());
	}
 
  //保存或更新表单
   @Override
   @Transactional
   public  String saveOrUpdateForm(SafFormslist form){
	    
	    String backStr="";
	     String formId=form.getId();
	     this.safFormslistRepository.saveAndFlush(form);
	     
	     //删除表单属性
	     this.formAttributeRepository.deleteFormAttribute(formId);
	     //保存表单属性
	     List <FormAttribute>faList=form.getFormAttributeList();
	     MetaData metaData=null; int u=0;
	     for (FormAttribute formAttr:faList){
	    	 formAttr.setId(Utils.createUuid());
	    	 formAttr.setFormId(formId);
	    	 formAttr.setStatus(1);
	    	 formAttr.setSequence(u);
	    	 //查询元数据ID
	    	 metaData=this.metaDataRepository.findByFieldCode(formAttr.getAttrCode());
	    	 formAttr.setMetaId(metaData.getId());
	    	 formAttributeRepository.save(formAttr);
	    	 u++;
	     }
	     
	     //保存表单检索SQL  绑定到编辑的字段上
	     List <FormSearchSql>searchSqlList=form.getFormSearchSqlList();
	     FormSearchSql newFormSearchSql=null;
	     //MetaData metaData=null; int u=0;
	     for (FormSearchSql frmSearchSql:searchSqlList){
	    	 List <FormSearchSql>list=formSearchSqlRepository.searchSqlByFormNoAndSearchName(frmSearchSql.getFormNo(),frmSearchSql.getSearchName());
	    	 if (list!=null&&list.size()>0){
	    		 newFormSearchSql=list.get(0);
	    		 newFormSearchSql.setTargetField(frmSearchSql.getTargetField());
	       		 formSearchSqlRepository.save(newFormSearchSql);
	    	 }
	     }
	   return backStr;
 }
 
 
	//保存属性
	@Override
	@Transactional
	public synchronized String saveTableFieldAttributeList_old(String id,String tableName,List<PropertyDefines> plist) {

		// String sql="";
		//if (!"3".equals(nodeType)){ //项目基本属性以及阶段的基本属性 需要重新查询 taskPropertyClassId
			/* sql="select t.id,t.pm_id from PM_PROPERTYCLASS_LIST t where t.pm_id='"+id+"' and t.property_classid='1'";
			 Object[] obj=null;
			List<?> pmlist=this.generalRepository.queryByNativeSql(sql,new HashMap<String, Object>());
			if (pmlist!=null&&pmlist.size()>0){
		       obj=(Object[])pmlist.get(0);
		      String  taskPropertyClassId= obj[0].toString();
		   
			} else { //插入一条数据 PM_PROPERTYCLASS_LIST
				Propertyclass  propertyclass=new Propertyclass();
				//String uuid=CommonUtil.createUuid();
				//taskPropertyClassId=uuid;
				propertyclass.setId(null);
				//propertyclass.setPmId(nodeId);
				propertyclass.setPropertyClassid("1");
				propertyclass.setPropertyClassname("基本属性");
				//propertyclass = propertyclassRepository.save(propertyclass);
				//taskPropertyClassId=propertyclass.getId();
			}
		*/
		
		//保存前判断 是否本次是否删除了一些属性,需要先删除掉
		 //  sql="SELECT T.ID, T.TASKPROPERTY_CLASSID FROM PM_SHOWFIELD_LIST  T WHERE T.PM_Id='"+id+"' AND T.TASKPROPERTY_CLASSID='"+id+"'";
		 //  List<?> oldlist=this.generalRepository.queryByNativeSql(sql,new HashMap<String, Object>());
		  //  Object[] obj=null;
		  //  boolean isExists=false;
		
	        //判断进度管理明细 表是否存在记录 ，先删除
	     //  sql="SELECT T.ID, T.TASKPROPERTY_CLASSID FROM PM_SHOWFIELD_DETAIL  T WHERE T.PM_Id='"+id+"' AND T.TASKPROPERTY_CLASSID='"+id+"'";
		//   List<?> oldlistDetail=this.generalRepository.queryByNativeSql(sql,new HashMap<String, Object>());
		 // if (oldlistDetail!=null&&oldlistDetail.size()>0){
     	//  Map  <String,Object>params = new HashMap<String,Object>(1);
   	   //  params.put("propertyId", taskPropertyClassId);
	       //   this.generalRepository.update("delete from ShowfieldDetail where taskpropertyClassid=:propertyId", params);
		//  }
	           
		
	     if (plist!=null&&plist.size()>0){
	    	 
	    	 SafFormslist syfForms=safFormslistRepository.findOne(id);
	    	 
	    	 assembleData(plist,syfForms);
	
	    	// syfForms.setId(CommonUtil.createGUID());
			//showfieldList.setPmId(nodeId);
	  	    //showfieldList.setTaskpropertyClassid(taskPropertyClassId);
	    	// if (syfForms.getDataSourceType().indexOf("2")>-1){
	    	 //删除可能配置过数据来源为集合（自定义来源的）
	    		 String []sourceTypes=null;//syfForms.getDataSourceType().split(",");
	    		 String []fieldEns=null;//syfForms.getShowfieldsEn().split(",");
	    		 //??????????????????
	    		 List <FormSearchSql> list=formSearchSqlRepository.searchSqlByFormNo(tableName);
	    		if (list!=null&&list.size()>0){
	    			FormSearchSql syfSelectCustom=null;
	    		  for (int i=0;i<list.size();i++){
	    			  syfSelectCustom=list.get(i);
	    		   for (int j=0;j<fieldEns.length;j++){
	    			   if (fieldEns[j].equals(syfSelectCustom.getTargetField())){
	    				  if (!Constant.DATASOURCETYPE_SQL.equals(sourceTypes[j])){
	    					  formSearchSqlRepository.deleteSearchSqlByTableField(tableName,fieldEns[j]);
	   	    			  }
	    				   break;
	    			   }
	    		   }
	    		 }
	    	  }
	    	 
	    	 syfForms = safFormslistRepository.save(syfForms);
	    	 
		    return syfForms.getId();
	     } else {
	    	return "";
	     }
		
	}
	
	//保存按钮
		@Override
		@Transactional
		public  String saveFormButtonLists(String formId,String tableName,List<FormButtonVO> blist) {
			//String btnNames="",btnValues="";
			FormButtons formButtons=null;
			//先删除按钮
			formButtonsRepository.deleteFormButtons(formId);
			for (int i=0;i<blist.size();i++) { 
				//btnNames+=blist.get(i).getButtonName();
				//btnValues+=blist.get(i).getButtonValue();
				formButtons=new FormButtons();
				formButtons.setId(Utils.createUuid());
				formButtons.setFormId(formId);
				formButtons.setButtonKey(blist.get(i).getButtonValue());
				formButtons.setButtonName(blist.get(i).getButtonName());
				formButtons.setButtonType(1);
				formButtons.setStatus(1);
				formButtons.setSequence(i+1);
				formButtons.setButtonMethodName(blist.get(i).getButtonValue());
				formButtonsRepository.save(formButtons);
			}
			// SafFormslist syfForms=safFormslistRepository.findOne(id);
			// syfForms.setFormbuttonsName(btnNames);
			// syfForms.setFormbuttonsMethodName(btnValues);
			// formButtonsRepository.save(arg0);
			 
			return formId;	
		}
	
		//保存自定义按钮
		@Override
		@Transactional
		public String saveCustomButton(String formId,String btnName,String btnValue){
			List <FormButtons>list=formButtonsRepository.findByFormId(formId);
			int zs=1;
			if (list!=null&&list.size()>0){
				zs=list.size()+1;
			}
			FormButtons formButtons=new FormButtons();	
			formButtons.setId(Utils.createUuid());
			formButtons.setFormId(formId);
			formButtons.setButtonKey(btnValue);
			formButtons.setButtonName(btnName);
			formButtons.setButtonMethodName(btnValue);
			formButtons.setButtonType(2);
			formButtons.setStatus(1);
			formButtons.setSequence(zs);
			formButtonsRepository.save(formButtons);
			return formId;	
		 }
		 
		//删除自定义按钮
			@Override
			@Transactional
		public String deleteCustomButton(String formId,String btnName,String btnValue){
		   this.formButtonsRepository.deleteFormButtonsByKey(formId,btnValue);
			return formId;		
	   }
		    
	@Override
	@Transactional
	//删除表单设置信息
	public void deleteFormSettings(String type,List<String> ids) {
		
		   if ("easysearch".equals(type)) {
		        List<FormSearchSql> list = this.formSearchSqlRepository.findAll(ids); 
			   this.formSearchSqlRepository.delete(list);
		   }
			
	  }
		 
	//保存列表显示字段
	   @Override
  	  @Transactional
	  public  String saveDisplayListFields(String formId,List<FormAttribute> blist){
		  
		   //将显示字段 都关闭
		   this.formAttributeRepository.updateDisplayListing(0, formId);
		   FormAttribute formAttribute=null;
			for (int i=0;i<blist.size();i++) { 
				formAttribute=blist.get(i);
				formAttribute=formAttributeRepository.findOne(formAttribute.getId());
				formAttribute.setDisplayListing(1);
				formAttributeRepository.save(formAttribute);
			}
		   return formId;
	   }
	   
	   //保存查询条件字段
	   @Override
    	@Transactional
	  public  String saveSearchFields(String formId,List<FormAttribute> blist){
		   //将默认查询条件字段 都关闭
		   this.formAttributeRepository.updateSearchField(0, formId);
		   FormAttribute formAttribute=null;
			for (int i=0;i<blist.size();i++) { 
				formAttribute=blist.get(i);
				formAttribute=formAttributeRepository.findOne(formAttribute.getId());
				formAttribute.setSearchField(1);
				formAttributeRepository.save(formAttribute);
			}
		   return formId;
		   
	   }
		    
		
	public SafFormslist  assembleData(List<PropertyDefines> lists,SafFormslist  syfForms){
		lists.sort(Comparator.naturalOrder());
		//SyfForms showfieldList = new SyfForms();
		
		StringBuffer showfieldsEn = new StringBuffer();//存放显示字段英文名称
		StringBuffer showfieldsCh = new StringBuffer();//存放显示字段中文名称
		StringBuffer mustinputField = new StringBuffer();//存放必输字段名称
		StringBuffer listdisplayField = new StringBuffer();//存放列表显示字段
		StringBuffer listdisplayFieldName = new StringBuffer();//存放列表显示字段名称
		StringBuffer fieldTag = new StringBuffer();//存放控件类型
		StringBuffer validatorType = new StringBuffer();//存放数据类型
		StringBuffer dataSourceType = new StringBuffer();//存放数据来源类型
		StringBuffer dataSource = new StringBuffer();//存放数据来源名称
		StringBuffer sequence = new StringBuffer();//存放字段显示顺序
		StringBuffer showfieldsType=new StringBuffer();//存放字段真实类型 
		StringBuffer listdisplayFieldType=new StringBuffer();//列表显示字段类型 
		StringBuffer showfieldsLengths=new StringBuffer();//显示字段长度
		StringBuffer listdisplaySearchFields=new StringBuffer();//是否是列表查询字段  
		
		int i=0;
		for (PropertyDefines list : lists) {  //前面没有设置值  添加,  ??????顺序
			//拼装显示字段英文名称
			if(StringUtil.isNotBlank(list.getColumnName())){
				//String columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, list.getColumnName());
				String columnName =list.getColumnName();
				showfieldsEn.append(columnName);
				showfieldsEn.append(",");
			}
			//拼装显示字段中文名称
			if(StringUtil.isNotBlank(list.getComments())){
				showfieldsCh.append(list.getComments().replaceAll(",",""));
				showfieldsCh.append(",");
			}
			//拼装显示字段必输 信息
			if(StringUtil.isNotBlank(list.getYesorno())){
				mustinputField.append(list.getYesorno());				
			}else {
				mustinputField.append("0");
			}
			mustinputField.append(",");
			
			//拼装列表显示字段 信息
			if(StringUtil.isNotBlank(list.getListdisplayField())){
				if ("1".equals(list.getListdisplayField())){  //是列表显示的字段 
				  listdisplayField.append(list.getColumnName());
				  listdisplayField.append(",");
				  
				  listdisplayFieldName.append(list.getComments());
				  listdisplayFieldName.append(",");
				  
				  listdisplayFieldType.append(list.getDataType());
				  listdisplayFieldType.append(",");
				}			
			}
			
			
			
			//拼装是否列表的查询字段
			if(StringUtil.isNotBlank(list.getListdisplaySearchField())){
				listdisplaySearchFields.append(list.getListdisplaySearchField());				
			}else {
				listdisplaySearchFields.append("0");
			}
			listdisplaySearchFields.append(",");
					
			//拼装控件类型
			if(StringUtil.isNotBlank(list.getXmControlType())){
				fieldTag.append(list.getXmControlType());
			}else {
				fieldTag.append("input"); //默认值
			}
			fieldTag.append(",");
			
			//拼装数据类型
			if(StringUtil.isNotBlank(list.getValidatorType())){
				validatorType.append(list.getValidatorType());
			}
			validatorType.append(",");
			
			//拼装数据来源类型
			if(StringUtil.isNotBlank(list.getDataSourceType())){
				dataSourceType.append(list.getDataSourceType());
			}
			dataSourceType.append(",");
			//拼装数据来源名称
			// 集合格式   " A1;B1;C1", Json 格式 ： [{};{}]
			if(StringUtil.isNotBlank(list.getDataSource())){
				dataSource.append(list.getDataSource().replaceAll(",",""));
			}
			dataSource.append(",");
			
			//拼装顺序号
			i++;
			if(StringUtil.isNotBlank(list.getSequence())){
				sequence.append(list.getSequence());
			}else {
				sequence.append(i);
			}
			sequence.append(",");
			//拼装字段真实类型
			if(StringUtil.isNotBlank(list.getDataType())){
				showfieldsType.append(list.getDataType());
				showfieldsType.append(",");
			}
			// 拼装字段长度 
			if(StringUtil.isNotBlank(list.getDataLength())){
			  showfieldsLengths.append(list.getDataLength());
			  showfieldsLengths.append(",");
			}
			
		}
	/*	//保存并去掉最后一个多余的逗号
		if(StringUtil.isNotBlank(showfieldsEn.toString())){
			syfForms.setShowfieldsEn(showfieldsEn.toString().substring(0, showfieldsEn.length()-1));
		}
		if(StringUtil.isNotBlank(showfieldsCh.toString())){
			syfForms.setShowfieldsCh(showfieldsCh.toString().substring(0, showfieldsCh.length()-1));
		}
		if(StringUtil.isNotBlank(mustinputField.toString())){
			syfForms.setMustinputField(mustinputField.toString().substring(0, mustinputField.length()-1));
		}
				
		if(StringUtil.isNotBlank(listdisplayField.toString())){
			syfForms.setListdisplayField(listdisplayField.toString().substring(0, listdisplayField.length()-1));
		}else {
			syfForms.setListdisplayField("");
		}
		if(StringUtil.isNotBlank(listdisplayFieldName.toString())){
			syfForms.setListdisplayFieldname(listdisplayFieldName.toString().substring(0, listdisplayFieldName.length()-1));
		} else {
			syfForms.setListdisplayFieldname("");
		}
		
		if(StringUtil.isNotBlank(listdisplayFieldType.toString())){
			syfForms.setListdisplayFieldType(listdisplayFieldType.toString().substring(0, listdisplayFieldType.length()-1));
		} else {
			syfForms.setListdisplayFieldType("");
		}
		if(StringUtil.isNotBlank(fieldTag.toString())){
			syfForms.setFieldTag(fieldTag.toString().substring(0, fieldTag.length()-1));
		}
		
		if(StringUtil.isNotBlank(validatorType.toString())){
			syfForms.setValidatorType(validatorType.toString());
		}
		
		if(StringUtil.isNotBlank(dataSourceType.toString())){
			syfForms.setDataSourceType(dataSourceType.toString());
		}
		
		if(StringUtil.isNotBlank(dataSource.toString())){
			syfForms.setDataSource(dataSource.toString());
		}
		
		if(StringUtil.isNotBlank(showfieldsType.toString())){
			syfForms.setShowfieldsType(showfieldsType.toString().substring(0, showfieldsType.length()-1));
		}
		
	
		
		if(StringUtil.isNotBlank(showfieldsLengths.toString())){
			syfForms.setShowfieldsLengths(showfieldsLengths.toString().substring(0, showfieldsLengths.length()-1));
		}
				
		if(StringUtil.isNotBlank(sequence.toString())){
			syfForms.setSequence(sequence.toString().substring(0, sequence.length()-1));
		}
		if(StringUtil.isNotBlank(listdisplaySearchFields.toString())){
			syfForms.setListdisplaySearchField(listdisplaySearchFields.toString().substring(0, listdisplaySearchFields.length()-1));
		}
		*/
		
		return syfForms;
	}
	
	
	//查询待选择的数据模型
	@Override
	public Map<String, Object>  queryAlternativeTableLists(SafFormsQueryRequest queryRequest){
		QueryDescriptor queryDescriptor = getQueryDescriptor("alternativeTableData");
		Map<String, Object> map = this.sqlExecutorDao.executeSlicedQuery(queryDescriptor,queryRequest);
		return  map;
	}

 // 查询已经选择的数据模型 
	@Override
	public  List<Map<String, Object>> querySelectedTableLists(SafFormsQueryRequest queryRequest) {
		String sql= getQueryDescriptor("selectedTableData").getSql();
		List<Map<String, Object>> data = this.sqlExecutorDao.queryToListMap(sql, queryRequest.getId());
		return data;
		
	}
	
	 //保存表单
	@Override
	public  String saveSafForms(SafFormslist safFormslist,List <Object>plist){
		Map <String,Object>map=null;
		SafFormslist safForms=null;
		String backStr="";
 	   //判断是否存在主表单
		boolean existMainTable=false;
		 for (int i=0;i<plist.size();i++) {
			map=(Map<String,Object>)plist.get(i);
 		   // String tableType=map.get("tableType").toString();
 		    if ("1".equals(map.get("tableType").toString())){
 		    	existMainTable=true;
 		    	break;
 		    }
		 }
		 if (!existMainTable){
			throw new IllegalArgumentException("表单编号"+safFormslist.getFormNo()+"：没有设置主表！");
		 }
		//判断是否是修改
		if (safFormslist.getId()!=null&&!"".equals(safFormslist.getId())){
			safForms=safFormslistRepository.findOne(safFormslist.getId());
			safForms.setFormNo(safFormslist.getFormNo());
			safForms.setFormName(safFormslist.getFormName());
			safForms.setSaveMode(safFormslist.getSaveMode());
		    List <FormTables>tableLists=this.formTablesRepository.findByFormId(safFormslist.getId());
		    for (FormTables table:tableLists){
		       this.formTablesRepository.delete(table);
		    }
		} else {  //新增
			safForms=new SafFormslist();
			List <SafFormslist>dblist=this.safFormslistRepository.findByFormNo(safFormslist.getFormNo());
		    if (dblist!=null&&dblist.size()>0){	
			   backStr="表单编号已经存在！";
			   throw new IllegalArgumentException("表单编号"+safFormslist.getFormNo()+"已经存在！");
		    }
		    safForms.setFormNo(safFormslist.getFormNo());
		    safForms.setFormName(safFormslist.getFormName());
		    safForms.setPackageName(safFormslist.getFormNo());
		    safForms.setFormPath(safFormslist.getFormNo());
		    safForms.setSaveMode(safFormslist.getSaveMode());
		    
		   if (safFormslist.getPagedatailCols()!=null){
			   safForms.setPagedatailCols(safFormslist.getLabelCols());
		   } else {
			   safForms.setPagedatailCols(Integer.parseInt(Constant.PAGEDETAIL_COLS));
		   }
		   if (safFormslist.getLabelCols()!=null){
			   safForms.setLabelCols(safFormslist.getLabelCols());
		   } else {
			   safForms.setLabelCols(Integer.parseInt(Constant.LABEL_COLS));
		   }
		   if (safFormslist.getFieldCols()!=null){
			   safForms.setFieldCols(safFormslist.getFieldCols());
		   } else {
			   safForms.setFieldCols(Integer.parseInt(Constant.FIELD_COLS));
		   }
		   if (safFormslist.getTextareaRows()!=null){
			   safForms.setTextareaRows(safFormslist.getTextareaRows());
		   } else {
			   safForms.setTextareaRows(Integer.parseInt(Constant.TEXTAREA_ROWS));
		   }
		   if (safFormslist.getExistAttachment()!=null){
			   safForms.setExistAttachment(safFormslist.getExistAttachment());
		   } else {
			   safForms.setExistAttachment(0);
		   }
	  
		   // safForms.setName(queryRequest.getName());
		}
		    safForms=this.safFormslistRepository.saveAndFlush(safForms);
		    FormTables formTables=null;
         //保存表信息 
		for (int i=0;i<plist.size();i++) {
			map=(Map<String,Object>)plist.get(i);
			String tableId=map.get("id").toString();
			//String fieldName=map.get("fieldName").toString();
			String tableName=map.get("tableName").toString();
			String tableType=map.get("tableType").toString();
			
			formTables=new FormTables();
			
			formTables.setId(Utils.createUuid());
			formTables.setTableId(tableId);
			formTables.setFormId(safForms.getId());
			formTables.setTableName(tableName);
			formTables.setTableType(Integer.parseInt(tableType));
			
			//tablesMeta.setFieldCode(fieldCode);
			//tablesMeta.setNums(Integer.parseInt(map.get("nums").toString()));
			 formTables.setStatus(1);
			this.formTablesRepository.save(formTables);
			
		//	queryRequest.setTableName(tableName);
		   // QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor("dbTablesByName"),queryRequest);
			//map=this.sqlExecutorDao.executeQuery(queryModel);
	
		}
		return backStr;
		
	}
	
	
	 //生成菜单信息
	@Override
	public  Map<String, Object> produceMenuList(SafFormsQueryRequest queryRequest){
		Map <String,Object>map=new HashMap<String,Object>();
		
		SafFormslist  formList=this.safFormslistRepository.findOne(queryRequest.getId());
		
		String url="/menuManage/forwardPageList.do?formNo="+formList.getFormNo();
		
		SysFunction  parentSysFunction =sysFunctionRepository.findByCode("customMenu");
		
		SysFunction  function =sysFunctionRepository.findByCode(formList.getFormNo());
		if (function==null){
			map.put("backStr","");
		  SysFunction  sysFunction=new SysFunction();
		  String id=Utils.createUuid();
		  sysFunction.setId(id);
		  sysFunction.setCode(formList.getFormNo());
		  sysFunction.setName(formList.getFormName());
		  sysFunction.setUrl(url);
		  sysFunction.setParentId(parentSysFunction.getId());
		  sysFunction.setNodeKindId("fun");
		  sysFunction.setIcon("fa-file");
		  sysFunction.setFullId(parentSysFunction.getFullId()+"/"+id);
		  sysFunction.setFullName(parentSysFunction.getFullName()+"/"+formList.getFormName());
		  sysFunction.setStatus(1);
		  sysFunction=sysFunctionRepository.saveAndFlush(sysFunction);
	
		  //构建权限
		  sysFunctionApplication .buildPermission(sysFunction.getFullId());
		  
		}else {
			map.put("backStr", Constant.MENU_CODE_EXIST);
		}
		return map;
	}


	 /*
     * 生成表单的页面文件
     * queryRequest:需要参数formNo
     */
    public String needGenerateFile(String  formNo) {
    	String backStr="";
        String webPath = this.getClass().getClassLoader().getResource("/").getPath();
        webPath = webPath.substring(1, webPath.length() - 16);
        webPath += pagePath;
        File file=new File(webPath);
        if (!file.exists()){
        	file.mkdir();
        }
        SafFormslist  safFormslist=this.safFormslistRepository.findByFormNo(formNo).get(0);
        webPath+=safFormslist.getFormNo();
        file=new File(webPath);
        if (!file.exists()){
        	file.mkdir();
        }
        String tableName=commonUtilApplication.getTablesByFormId(safFormslist.getId(),1);
		 tableName=tableName.split(",")[0];  //取第一个主表 
		// queryRequest.setTableName(tableName.toUpperCase());
		SafFormsQueryRequest queryRequest=new SafFormsQueryRequest();
		queryRequest.setId(safFormslist.getId());
		queryRequest.setTableName(tableName.toUpperCase());
		queryRequest.setFormNo(formNo);

        String pageName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,tableName); //转驼峰法
        String filePathName = webPath + "/" + pageName + ".jsp";
        file = new File(filePathName);

    	// 重新发布 需要删除已经生成的页面文件
		if (file.exists()) {
    	  file.delete();
    	}
    	   
        if (!file.exists()) {
            List <String>hiddenField=new ArrayList<String>(); //默认隐藏字段
          // hiddenField.add("id");
          // hiddenField.add("formId");
           //System.out.println("safFormslist.getPublished()==="+safFormslist.getPublished());
			//主表添加流程所需要的字段
			if (safFormslist.getPublished()==null||(safFormslist.getPublished()!=null&&safFormslist.getPublished()==0)) {
				dbTableService.addProcessFields(tableName);
			}
            ParamFormVO paraForm = this.getFieldAttributes(queryRequest);
            
            DbTablesQueryRequest dbqueryRequest=new DbTablesQueryRequest();    
            dbqueryRequest.setTableName(tableName.toUpperCase());
            hiddenField=commonUtilApplication.queryTableHiddenFields(dbqueryRequest,1);
          
            paraForm.setIsform(1);
            paraForm.setTableName(tableName);//主表名称 
            paraForm.setFormPath(webPath);
			paraForm.setUploadPath("");  //页面文件 直接生成在运行目录 
            paraForm.setSrcPath(pagePath); 
        /*   if (paraForm.getHiddenFields()!=null&&paraForm.getHiddenFields().size()>0){
        	   List <String>tmpHidden=paraForm.getHiddenFields();
        	   tmpHidden.addAll(hiddenField);
           	   paraForm.setHiddenFields(tmpHidden);
           } else {
               paraForm.setHiddenFields(hiddenField);
           }
           */
            paraForm.setHiddenFields(hiddenField);
            
            paraForm.setFormName(safFormslist.getFormName());
            
            //查询页面配置的按钮
            List <FormButtons>buttonLists=this.formButtonsRepository.findByFormId(safFormslist.getId());
            if  (buttonLists!=null&&buttonLists.size()>0){
              String []btnNames=new String[buttonLists.size()];
              String []btnMethodNames=new String[buttonLists.size()];
              FormButtons formButtons=null;
               for (int y=0;y<buttonLists.size();y++){
            	  formButtons=buttonLists.get(y);
               	  btnNames[y]=formButtons.getButtonName();
            	  btnMethodNames[y]=formButtons.getButtonMethodName();
                }
               paraForm.setBtnNames(btnNames);
               paraForm.setBtnMethodNames(btnMethodNames);
            }
            // 查询当前表单是否挂流程

            try {
				StringBuffer sb = new StringBuffer("");
                BuildPageDetailFile buildPageDetailFile = new BuildPageDetailFile();
                sb = buildPageDetailFile.generateContents(paraForm,tableName);
                buildPageDetailFile.generateFile(filePathName, sb);
                
                Thread.sleep(1000);
                buildTypeClass.getBuildClass(Constant.BUILD_PAGELIST).generateFile(paraForm,null);
                
                Thread.sleep(1000);
    	        buildTypeClass.getBuildClass(Constant.BUILD_PAGEJS).generateFile(paraForm,null);
    	        
                Thread.sleep(1000);

				if (safFormslist.getPublished()==null||(safFormslist.getPublished()!=null&&safFormslist.getPublished()==0)) {
					safFormslist.setPublished(1);
					this.safFormslistRepository.saveAndFlush(safFormslist);
				}
            } catch (Exception e) {
				backStr=e.getMessage();
                e.printStackTrace();
            }
        }
		return backStr;
    }
    
    
    /**
     * 拼装数据对象属性
     *
     * @param queryRequest: formId、formNo 、tableName
     * @return
     */
    public ParamFormVO getFieldAttributes(SafFormsQueryRequest queryRequest) {
         //获取主表字段 进行拼装 
        List<Map<String, Object>> singleList = commonUtilApplication.queryDataRecordSingleFields(queryRequest.getId(),queryRequest.getTableName());
        ParamFormVO paraForms = Utils.composeAttributes(singleList, "", "", null);
    	
         //拼装检索SQL到参数中　
        List <FormSearchSql> customlists=formSearchSqlRepository.searchSqlByFormNo(queryRequest.getFormNo());
	       List <SeleListCustomVO> listCustoms=new  ArrayList<SeleListCustomVO>();
	       SeleListCustomVO customVO=null;Map <String, Object>map=null;
	       String []fieldEns=new String[singleList.size()];
	       //String []allFieldEns=new String[singleList.size()];
	       List<String> hiddenFields=new ArrayList<String>();
	       String backFields="",paramSourceFields="";
	       for (int i=0;i<customlists.size();i++){
	    	   customVO=new SeleListCustomVO();
	    	   Utils.CopyBean(customlists.get(i),customVO);
	    	   singleList = commonUtilApplication.queryDataRecordSingleFields(queryRequest.getId(),customVO.getTableName());
	    	   fieldEns=new String[singleList.size()];
	          // allFieldEns=new String[singleList.size()];
	           
	           //增加参数来源的字段顺序号
	           addParamFieldNum(queryRequest.getId(),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);
	    	  }
	    	  for (int j=0;j<singleList.size();j++){
	    		   map=singleList.get(j);
	    		   fieldEns[j]=map.get("fieldCode").toString();
	    	  }   //？？？？？     ====================？？？？  遍历两次？？
	    	  
	     	   for (int j=0;j<singleList.size();j++){ 
	    		   map=singleList.get(j);
	    		   //fieldEns[j]=map.get("fieldCode").toString();  //真实字段名称
	    		 if (customVO.getTargetField()!=null&&customVO.getTargetField().equals(map.get("fieldCode").toString())){
	    			customVO.setTargetNum(j);  //目标字段顺序号
	    			break;
	    		  }
	    	   }
	     	   
	    	   customVO.setFieldEns(fieldEns);  //关联字段的真实字段名称 
	    	 //  customVO.setAllFieldEns(allFieldEns); //所有字段的真实名称 
	    	   hiddenFields.addAll(Utils.getHiddenFields(customVO));
	      	   listCustoms.add(customVO);
	       }
	       paraForms.setSelectCustoms(listCustoms);
           paraForms.setHiddenFields(hiddenFields);
		   paraForms.setFormPath(queryRequest.getFormNo());
           
        //判断是否存在明细表
       /* List<Map<String, Object>> multsList =new  ArrayList<Map<String, Object>>();
        String mainTableName=queryRequest.getTableName().toLowerCase();//获取主表
        queryRequest.setTableType(2);
        multsList=this.queryExistTables(queryRequest);
        if (multsList != null && multsList.size() > 0) {//多值则产生明细表
            ParamFormVO paramVO = new ParamFormVO();
        	List<String> hiddenField=new ArrayList<String>();
        	hiddenField.add("id");
        	hiddenField.add("parentId");
            List<ParamFormVO> details = new ArrayList<ParamFormVO>();
           // Map<String, Object> map =null;
            List<Map<String, Object>> list=null;
            for (int i = 0; i < multsList.size(); i++) {
                 map = (Map<String, Object>) multsList.get(i);
             //    queryRequest.setAttrId(map.get("id").toString());  05.18.2020 lxh close
                queryRequest.setTableName(map.get("tableName").toString());
               list = this.commonUtilApplication.queryDataRecordMultsFields(queryRequest.getId(),map.get("tableName").toString());
                paramVO = Utils.composeAttributes(list, map.get("tableName").toString(), map.get("name").toString(), hiddenField);
                paramVO.setDisplayFieldnames(paramVO.getFieldChs());
                paramVO.setDisplayFields(paramVO.getFieldEns());
                paramVO.setDisplayFieldTypes(paramVO.getValidatorTypes());
                paramVO.setSrcPath(pagePath);
                paramVO.setSelectCustoms(listCustoms);
                paramVO.setIsform(1);  //是表单生成器 
                paramVO.setFormPath(queryRequest.getFormNo());
                paramVO.setMainTableName(mainTableName);
                details.add(paramVO);
            }
            paraForms.setDetails(details);
        }
        */
		 return getDetailTables(queryRequest,paraForms);
         //return paraForms;
    }

    //判断是否存在明细表的情况
	//queryRequest.getFormNo()
	//参数： id：formId,formNo,tableName
	@Override
    public  ParamFormVO getDetailTables(SafFormsQueryRequest queryRequest,ParamFormVO paraForms){
		//判断是否存在明细表
		List<Map<String, Object>> multsList =new  ArrayList<Map<String, Object>>();
		String mainTableName=queryRequest.getTableName().toLowerCase();//获取主表
		//queryRequest.setFormNo(formNo);
		queryRequest.setTableType(2);
		queryRequest.setTableName(mainTableName);
		multsList=this.queryExistTables(queryRequest);
		if (multsList != null && multsList.size() > 0) {//多值则产生明细表
			ParamFormVO paramVO = new ParamFormVO();
			List<String> hiddenField=new ArrayList<String>();
			hiddenField.add("id");
			hiddenField.add("parentId");
			List<ParamFormVO> details = new ArrayList<ParamFormVO>();
			Map<String, Object> map =null;
			List<Map<String, Object>> list=null;
			for (int i = 0; i < multsList.size(); i++) {
				map = (Map<String, Object>) multsList.get(i);
				//    queryRequest.setAttrId(map.get("id").toString());  05.18.2020 lxh close
				queryRequest.setTableName(map.get("tableName").toString());
				list = this.commonUtilApplication.queryDataRecordMultsFields(queryRequest.getId(),map.get("tableName").toString());
				paramVO = Utils.composeAttributes(list, map.get("tableName").toString(), map.get("name").toString(), hiddenField);
				paramVO.setDisplayFieldnames(paramVO.getFieldChs());
				paramVO.setDisplayFields(paramVO.getFieldEns());
				paramVO.setDisplayFieldTypes(paramVO.getValidatorTypes());
				paramVO.setSrcPath(pagePath);
				paramVO.setSelectCustoms(paraForms.getSelectCustoms());
				paramVO.setIsform(1);  //是表单生成器
				paramVO.setFormPath(queryRequest.getFormNo());
				paramVO.setMainTableName(mainTableName);
				details.add(paramVO);
			}
			paraForms.setDetails(details);
		}
		return paraForms;
	}

    //检索SQL获取参数字段顺序号   //当前表 　  参数来源表目前只能支持一个主表、一个明细表 
    public SeleListCustomVO  addParamFieldNum(String formId,SeleListCustomVO customVO){
    	 
       if (customVO.getParamFields()!=null&&!"".equals(customVO.getParamFields())) {  //存在参数 
    	  //customVO.getTableName()   customVO.getParamSourceTables() 
    	  String []tables=customVO.getParamSourceTables().split(",");
    	
    	  List<Map<String, Object>> singleList = commonUtilApplication.queryDataRecordSingleFields(formId,customVO.getTableName());
    	  List<Map<String, Object>> otherList =null;
    	   if (tables.length>1){  //SMS_ORDER,SMS_ORDER_DETAIL
    		  String otherTable=tables[0];
    		  if (customVO.getTableName().equals(tables[0])){
    			  otherTable=tables[1];
    		  }
    	     otherList = commonUtilApplication.queryDataRecordSingleFields(formId,otherTable);
    	   } 
    	      String []paraSourceField=customVO.getParamSourceFields().split(",");
    	      Map <String, Object>map=null;
    	      int []paramSourceNums=new int[paraSourceField.length];
    	      boolean isFound=false;
    	   for (int d=0;d<paraSourceField.length;d++) {
    	    
    	       for (int r=0;r<singleList.size();r++){
	    		   map=singleList.get(r);
	    		   if (paraSourceField[d].equals(map.get("fieldCode").toString())){
	    			   paramSourceNums[d]=r;
	    			   isFound=true;
	    			   break;
	    		   }
    	       }
    	       if  (!isFound){ //没有找到  再遍历另外一个表
    	    	   for (int r=0;r<otherList.size();r++){
    	    		   map=otherList.get(r);
    	    		   if (paraSourceField[d].equals(map.get("fieldCode").toString())){
    	    			   paramSourceNums[d]=r;
    	    			   isFound=true;
    	    			   break;
    	    		   }
        	       }
    	       }
     	   }
    	   customVO.setParamSourceNums(paramSourceNums);
      }
    	 return customVO;
    }
    
    //增加返回字段的参数 顺序号 
  /*  public SeleListCustomVO addBackFieldNums(SeleListCustomVO customVO, List<Map<String, Object>> singleList) {
    	   Map <String, Object>map=null;
    	 if (customVO.getBackFields()!=null){

   		  String []bakcFields=customVO.getBackFields().split(",");
   		  String []fieldTypes=customVO.getFieldTypes().split(",");
   		  int   []backFieldNums=new int[bakcFields.length];
   		  for (int y=0;y<bakcFields.length;){
   			  if (!"1".equals(fieldTypes[y])){  //隐藏字段
   				 for (int j=0;j<singleList.size();j++){
   		    	  map=singleList.get(j);
   		    	  if  (bakcFields[y].equals(map.get("fieldCode").toString())){
   		    		  backFieldNums[y]=j;
   		    		   break; 
   		    	  }
   			     }
   				  
   			 }
   		  }
   		  customVO.setBackFieldNums(backFieldNums);
   		  
   	     String backFields=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,customVO.getBackFields()); //转成驼峰法
   	     customVO.setBackFields(backFields);
   	     
   	    }
    	  return customVO;
    }
    */
    /*
     * 查询模型包含的单值字段(non-Javadoc)
     * @see 字段个数默认最大100
     */
   // @Override
   /* public List<Map<String, Object>> queryDataRecordSingleFields_ff(SafFormsQueryRequest queryRequest) {
        Map<String, Object> mapData = new HashMap<String, Object>();
        //safFormlist.xml -->queryFormDataRecordFields
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor("queryFormDataRecordFields"), queryRequest);
        queryModel.setPageSize(101);//默认100
        queryModel.setPageIndex(1);
        String sql=queryModel.getSql();

        // if (queryRequest.getDisplayListing()==1){ //只查询列表显示字段   05.18.2020 lxh close
        //	sb.append(" and a.display_listing=").append(queryRequest.getDisplayListing());
        // } 
          sql+=" and a.form_id='"+queryRequest.getId()+"'";
          sql+=" order by a.sequence ";
        queryModel.setSortFieldName("sequence");
        queryModel.setSql(sql);
        if ("all".equals(queryModel.getExportType())) {//导出Excel
            queryModel.setExportType(null);
        }
        mapData = this.sqlExecutorDao.executeSlicedQuery(queryModel);
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> list = (List<Map<String, Object>>) mapData.get("Rows");
        return list;
    }*/
    
    
    //*查询是否存在明细表的属性
    @Override
    public List<Map<String, Object>> queryExistTables(SafFormsQueryRequest queryRequest) {
        Map<String, Object> mapData = new HashMap<String, Object>();
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor("queryFormExistTables"), queryRequest);
        queryModel.setPageSize(101);//默认100
        queryModel.setPageIndex(1);
        String sql=queryModel.getSql();
        if (queryRequest.getTableType()!=0){
        	 sql+=" and a.table_type="+queryRequest.getTableType();
        }
        sql+=" and c.form_no='"+queryRequest.getFormNo()+"'";
        queryModel.setSql(sql);
        
        mapData = this.sqlExecutorDao.executeSlicedQuery(queryModel);
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> list = (List<Map<String, Object>>) mapData.get("Rows");
        return list;
    }
    
    
   
    
   
}
