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

import com.google.common.base.CaseFormat;
import com.huigou.context.Operator;
import com.huigou.context.ThreadLocalUtil;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.exception.ApplicationException;
import com.huigou.uasp.bmp.common.application.BaseApplication;
import com.huigou.uasp.builder.vo.PubDataRecord;
import com.huigou.uasp.data.application.DataRecordApplication;
import com.huigou.uasp.data.domain.query.DataRecordQueryRequest;
import com.huigou.uasp.form.application.CommonUtilApplication;
import com.huigou.uasp.form.domain.model.SafFormslist;
import com.huigou.uasp.form.repository.SafFormslistRepository;
import com.huigou.uasp.model.domain.query.DbTablesQueryRequest;
import com.huigou.uasp.util.ComUtils;
import com.huigou.uasp.util.Constant;
import com.huigou.uasp.util.ReflectionUtil;
import com.huigou.uasp.util.Utils;
import com.huigou.util.ApplicationContextWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;


@Service("dataRecordApplication")
public class DataRecordApplicationImpl extends BaseApplication implements DataRecordApplication { 

	static String QUERY_XML_FILE_PATH = "config/formdesign/dataRecord.xml";

	@Autowired
	private  CommonUtilApplication  commonUtilApplication;

	@Autowired
	private SafFormslistRepository safFormslistRepository;
	
	 private QueryDescriptor getQueryDescriptor(String queryName) {
	        if ("".equals(queryName)) {
	            queryName = "queryHiddenFieldBySearchSQL";
	        }
	        return this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, queryName);
	    }

	 
	// @Autowired
	//private  SafFormslistApplication safFormslistApplication;

	 @Override
	    /*
	     * 加载单条数据
	     * @see
	     */
	    public PubDataRecord loadDataRecord(DataRecordQueryRequest queryRequest) {
	        Assert.hasText(queryRequest.getId(), Constant.ID_NOT_BLANK);

	      
	        List<Map<String, Object>> lists = this.commonUtilApplication.queryDataRecordSingleFields(queryRequest.getFormId(),queryRequest.getMaiTab().toUpperCase());
	        //MdmMetaData metaData=null;
	        String fields = "";
	        String[] dataTypes = new String[lists.size()];
	        Map<String, Object> map = null;
	        for (int i = 0; i < lists.size(); i++) {
	            map = (Map<String, Object>) lists.get(i);
				if (Constant.NO_ACCESS.equals(map.getOrDefault("defaultOperation",Constant.READ_WRITE).toString())) { //无权访问
					fields += "'' "+map.get("fieldCode").toString();
				} else {
					fields += map.get("fieldCode").toString();
				}
	            dataTypes[i] = map.get("fieldType").toString();
				if (i < lists.size() - 1)
					fields += ",";
	        }

	        PubDataRecord entity = new PubDataRecord();
	        entity.setId(queryRequest.getId());
           //获取隐藏字段
	        DbTablesQueryRequest dbQueryRequest=new DbTablesQueryRequest();
	        dbQueryRequest.setTableName(queryRequest.getMaiTab().toUpperCase());
	        List <String> hiddenFields=commonUtilApplication.queryTableHiddenFields(dbQueryRequest, 0);
	        String hiddenCols=org.apache.commons.lang.StringUtils.join(hiddenFields.toArray(), ",");
	        //查询数据
	        StringBuffer sb = new StringBuffer("");
	        sb.append("select  ").append(fields).append(",").append(hiddenCols);
	        sb.append(" from ");
	        sb.append(queryRequest.getMaiTab());
	        sb.append(" t where 1=1 ");
	        sb.append(" and t.id='").append(queryRequest.getId()).append("'");

	        List<?> dataList = this.generalRepository.queryByNativeSql(sb.toString(), new HashMap<>());
	        Object[] obj = (Object[]) dataList.get(0);

	        Class<?> clz = entity.getClass();
	        Field[] field = clz.getDeclaredFields();
	        //List <Map<String,Object>> hidelist=new ArrayList<Map<String,Object>>();
	        Map <String,Object>hiMap=new HashMap<String,Object>(); 
	        for (int i = 0; i < obj.length-hiddenFields.size(); i++) {

	            if (obj[i] != null) {
	                ReflectionUtil.invokeSet(entity, field[i].getName(), obj[i].toString());
	            }
	        }
	        String []hiddenCol=hiddenCols.split(",");
	        int u=0;
	        for (int j = obj.length-hiddenFields.size(); j<obj.length;j++) {
	         //for (String hiddeField:hiddenFields){
	          if (obj[j] != null) {
	        	hiddenCol[u]=CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,hiddenCol[u]); //转成驼峰法
	        	hiMap.put(hiddenCol[u],obj[j].toString());
	          }
	        	u++;
            }
	        entity.setHiddField(hiMap);
	        return entity;
	    }

	    /*
	     * 新增数据 加载初始化信息  初始化编码等信息
	     * @see
	     */
	    @Override
	    public PubDataRecord loadDataRecordByAdded(DataRecordQueryRequest queryRequest) {
	        PubDataRecord entity = new PubDataRecord();
	        // QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor(""), queryRequest);
	        try {
	            String tableName = queryRequest.getMaiTab();
	            queryRequest.setSubTab(tableName);
	            Map<String, Object> map = new HashMap<String, Object>();

	           /* if (this.queryIsExistTable(queryRequest) == 0) {
	                //mapData.put("error",tableName+Constant.NOT_DATA_DETAIL_TABLE);
	                Assert.isTrue(false, tableName + Constant.NOT_DATA_DETAIL_TABLE);
	                return entity;
	            }*/
	            entity.setFormId(queryRequest.getFormId());      
	            //SafFormsQueryRequest safFormsQueryRequest=new SafFormsQueryRequest();
		       // safFormsQueryRequest.setId(queryRequest.getFormId());
		        //safFormsQueryRequest.setMaiTab(queryRequest.getMaiTab());

	            List<Map<String, Object>> fieldList = commonUtilApplication.queryDataRecordSingleFields(queryRequest.getFormId(),tableName.toUpperCase());
	            //  String fieldCode="";
	            for (int i = 0; i < fieldList.size(); i++) {
	                map = fieldList.get(i);
	                // fieldCode=map.get("fieldCode").toString();
	                if (map.get("codeRuleId") != null && !"".equals(map.get("codeRuleId").toString())) {
	                    Object codeGenerator = ApplicationContextWrapper.getBean("codeGenerator");
	                    Method method = codeGenerator.getClass().getMethod("getNextCode", new Class[]{String.class});
	                    String code = (String) method.invoke(codeGenerator, new Object[]{map.get("codeRuleId").toString()});
	                    ReflectionUtil.invokeSet(entity, "field" + i, code);
	                }
	            }
	        } catch (Exception ex) {
	            throw new IllegalArgumentException(ex.getMessage());
	        }
	        return entity;
	    }
	    
	    
	    @SuppressWarnings("unchecked")
	    @Override
	    public Map<String, Object> queryDataRecord(DataRecordQueryRequest queryRequest) {

	        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor(""), queryRequest);
	        // String exportType = queryModel.getExportType();
	        //String tableName = commonDataService.getTableName(queryRequest.getModelId());
	        //queryRequest.setSubTab(tableName);
	        Map<String, Object> mapData = new HashMap<String, Object>();

	       /* if (this.queryIsExistTable(queryRequest) == 0) {
	            mapData.put("error", tableName + Constant.NOT_DATA_DETAIL_TABLE);
	            return mapData;
	        }*/

	       // SafFormsQueryRequest safFormsQueryRequest=new SafFormsQueryRequest();
	       // safFormsQueryRequest.setId(queryRequest.getFormId());
	       // safFormsQueryRequest.setMaiTab(queryRequest.getMaiTab());
	        
	        List<Map<String, Object>> fieldList = this.commonUtilApplication.queryDataRecordSingleFields(queryRequest.getFormId(),queryRequest.getMaiTab().toUpperCase());
	        String fields = "";

	        if ("all".equals(queryModel.getExportType())) {//导出Excel
	            fields = Utils.getDataFieldsByAlias(fieldList);
	        } else {
	            fields = Utils.getDataFields(fieldList, "fieldCode");
	        }
	        //判断表中是否存在 字段
	        // QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor("allColumnsByTable"), queryRequest);

	        StringBuffer sb = new StringBuffer("");
	        if (!"".equals(fields)) {
	            sb.append("select  id,form_id,");
	            sb.append(fields);
	            sb.append(",'' sequence,status,created_date from ");
	            sb.append(queryRequest.getMaiTab());
	            sb.append(" where 1=1 ");
	            Map <String,Object>map=queryRequest.getSearchContent();
	            if (!map.isEmpty()) {
	                String searchFields = Utils.getSearchDataFields(fieldList);
	                if (!"".equals(searchFields)) {
	                    String[] searchField = searchFields.split(",");
	                    
	                   // sb.append(" and (");
	                    for (int u = 0; u < searchField.length; u++) {
	                      if (map.get("field"+u)!=null&&!"".equals(map.get("field"+u).toString())){
	                         String value=map.get("field"+u).toString();
	                         sb.append(" and ");
	                         sb.append(searchField[u]).append(" like '%").append(value).append("%'");
	                      }
	                    }
	                  //  sb.append(" ) ");
	                 }
	             }

	        } else {
	            sb.append("select t.id,t.classify_id,'' model_id,'' sequence,created_date from mdm_model_record t where 1=2");
	        }
	        if (queryModel.getSortFieldName().startsWith("field")) {  //显示数据时  选定了排序字段
	            //areas,produce_date,age,customer_code,customer
	            String[] field = fields.split(",");
	            String sortField = queryModel.getSortFieldName();
	            queryModel.setSortFieldName(field[Integer.parseInt(sortField.substring(5))]);
	        } else {  //默认排序字段
	        	queryModel.setSortFieldName("created_date");
	        	queryModel.setSortOrder("desc");
	        }
	        queryModel.setSql(sb.toString());
	        if ("all".equals(queryModel.getExportType())) {//导出Excel
	            mapData = this.sqlExecutorDao.executeSlicedQuery(queryModel);
	        } else {
	            mapData = this.sqlExecutorDao.executeSlicedQuery(queryModel);
	            mapData.put("Rows", Utils.dataFieldTransfer(fieldList, (List<Map<String, Object>>) mapData.get("Rows")));
	        }
	        return mapData;
	    }
	    
	    
		//保存主表实体
	    @Override
	    @Transactional
		 public  String saveDataRecord(DataRecordQueryRequest queryRequest,Map<String, Object> datamap){
	    	// List<PubDataRecord> backlist = new ArrayList<PubDataRecord>();
	         PubDataRecord entity = null;
	         String sid="";
	         try {
	        	// SafFormsQueryRequest safFormsQueryRequest=new SafFormsQueryRequest();
	  	 	     // safFormsQueryRequest.setId(queryRequest.getFormId());
	        	 String btntype=queryRequest.getBtntype();
	        	 
	        	
	     	    //查询字段名称
	             List<Map<String, Object>> fieldList = this.commonUtilApplication.queryDataRecordSingleFields(queryRequest.getFormId(),queryRequest.getMaiTab().toUpperCase());
	           //  String columns = Utils.getDataFields(fieldList, "fieldCode");
	            
	           
	             String tableName =queryRequest.getMaiTab();// commonDataService.getTableName(queryRequest.getModelId());

	             //fields=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,fields);//转成下划线
	             //fields= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,fields); //转成驼峰法
	             // Map <String, Object>map=Utils.dataValueTransfer(fieldList,entity);
	             
	             entity = new PubDataRecord();
	             Operator operator = ThreadLocalUtil.getOperator();
	             
	             boolean isAdded = false;
	             
		    	  List <String>hiddenFields=queryRequest.getHiddenField();
		            // StringUtils.trimTrailingCharacter(hiddenField, ",");
		       
		             
	                // String columns = Utils.getDataFields(fieldList, "fieldCode");
	                 if (StringUtils.isEmpty(datamap.get("id"))) { //新增
	                     sid = Utils.createUuid();
	                     isAdded = true;
	                     datamap.put("id", sid);
	                     entity.setId(sid);
	                     //增加写入的隐藏列的默认数据值
	                     if (hiddenFields.contains("created_date")){
	                    	 datamap.put("created_date", "sysdate");
	  	                 }
	  	                 if (hiddenFields.contains("status")){
	  	                	datamap.put("status", 1); 
	  	                 }
	                 } else {
	                	  sid=datamap.get("id").toString();
	                      entity.setId(datamap.get("id").toString());
	                      if (hiddenFields.contains("created_date")){
	                    	//  List <?>rqList=this.generalRepository.queryByNativeSql("select sysdate from dual",new HashMap<String,Object>());
	        	            //  String dbrq=rqList.get(0).toString().substring(0,19);
	                    	  String dbrq=this.commonUtilApplication.queryDBCurrentDate();
	                    	  datamap.put("created_date", dbrq);
		  	              }
	                 }
	                 if (hiddenFields.contains("created_by_id")){
	                	 datamap.put("created_by_id", operator.getPersonMemberId());
	  	              }
	  	              if (hiddenFields.contains("created_by_name")){
	  	            	datamap.put("created_by_name", operator.getPersonMemberName());
	  	              }
	  	              
	  	            datamap.put("form_id", queryRequest.getFormId());
	           
	  	            
	             if ("2".equals(queryRequest.getSaveMode())){  //是存储过程方式  先保存临时表 
	        		 //保存到临时表
	        		  saveRecordTmpTable(isAdded,tableName+"_tmp",datamap);
	        		 
	        		 if (btntype!=null&&"1".equals(btntype)){  //是主表单保存按钮操作 
	        			 //调用存储过程操作 
	        			// Map map=dataList.get(0);
	         			 String backStr=callMainProcedure(tableName,entity.getId());
		            	 if (backStr!=null&&!"".equals(backStr)){
		            		 throw new IllegalArgumentException(backStr);
		            	 }        			 
	           		 }
	        	 } else {
	        		 
	        		 saveRecordEntity(isAdded,datamap,fieldList,queryRequest);
	        		 
	        	 }
	             

	         } catch (Exception ex) {
	             ex.printStackTrace();
	             throw new IllegalArgumentException(ex.getMessage());

	         }
	         return sid; 
		 }
	    
	    //只保存实体 
	    public void saveRecordEntity(boolean isAdded,Map <String, Object>datamap,List<Map<String, Object>> fieldList,DataRecordQueryRequest queryRequest){
	    	 
	    	// List<PubDataRecord> backlist = new ArrayList<PubDataRecord>();
	    	  List<Map<String, Object>> datas = Collections.singletonList(datamap);
	    	  
	    	  String columns = Utils.getDataFields(fieldList, "fieldCode");
	    	  
	    	 // List <String>hiddenFields=queryRequest.getHiddenField();
	            // StringUtils.trimTrailingCharacter(hiddenField, ",");
	         //   String hiddeCols=org.apache.commons.lang.StringUtils.join(hiddenFields.toArray(), ",");
	    	  
	    	   String hiddeCols=org.apache.commons.lang.StringUtils.join(queryRequest.getHiddenField().toArray(), ",");

	    	   String flowCols="status,bill_code,fillin_date,organ_id,organ_name,dept_id,dept_name,position_id,position_name,person_member_id,person_member_name,full_id";

	           //  for (Map<String, Object> map : dataList) {
	               //  isAdded = false;

	  	            
	                 //增加写入的固定列数据值
	                // map.put("service_code", map.get("serviceCode") != null ? map.get("serviceCode").toString() : "mdm");
	            
	                // String fixedCols = ",id,form_id,status,created_date,created_by_id,created_by_name";
	                // datas = new ArrayList<Map<String, Object>>();
	               //  datas.add(datamap);

	                 //生成并执行批量insert方法
	                 //if(datas!=null &&  datas.size()>0){

	               //  for (int i = 0; i < datas.size(); i++) datas.get(i).put("seqVal", String.format("%03d", i));
	                 datamap.put("seqVal", String.format("%03d",0));
	 				/*//排序 java 8新特性，当前使用的Tomcat不支持
	 				List<Map<String,Object>> temp_datas = datas.stream()
	 						.sorted(CommonUtil.CommonMapComparator.getInstance(sortColumn, CommonUtil.CommonMapComparator.INT_TYPE))
	 						.collect(Collectors.toList());
	 				//新序号
	 				Stream.iterate(0,i->i+1).limit(temp_datas.size()).forEach(i-> temp_datas.get(i).put("seqVal", String.format("%03d",i)));
	 				*/
			         if (isAdded) {
	                     String sql = ComUtils.getMultiInsertSqlByList(queryRequest.getMaiTab(), datamap, columns+"," +hiddeCols+","+flowCols);
	                     this.sqlExecutorDao.executeUpdate(sql);
	                 } else {
	                	// hiddenField.remove("id");
	                	 //fixedCols=org.apache.commons.lang.StringUtils.join(hiddenField.toArray(), ",");
	                	// columns+="," +hiddeCols;
	                	 Map <String,Object>hiddMap=null;
	                	  for (String hiddField:queryRequest.getHiddenField()){
	             	            if (!"id".equals(hiddField)&&!"form_id".equals(hiddField)){
	        	        		  columns+=","+hiddField;
	        	        	   
	        	        		 hiddMap=new HashMap<String,Object>();
	        	     	         hiddMap.put("fieldCode",hiddField);
	        	        		 if ("created_date".equals(hiddField)){
	        	        	        hiddMap.put("fieldType","date");
	        	        		 }else {
	        	        	   	    hiddMap.put("fieldType","string");
	        	        		 }
	        	        	     fieldList.add(hiddMap);
	        	               }
	        	        	}
	                	/* Map <String,Object>hiMap=new HashMap<String,Object>();  //前面查询了所有隐藏字段 
	                	 List <String> hiddenList=this.commonUtilApplication.querySearchSQLHiddenFields(queryRequest.getFormNo());
	                	 for (String field:hiddenList){   //可能存在重复的隐藏字段  主表和明细表同时存在
	                		 hiMap=new HashMap<String,Object>();
	                		if (!"id".equals(field)){ //剔除id ，避免表单检索SQL设置返回字段为ID　
	                		   field=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,field);//转成下划线
	                		 if (columns.indexOf(field)<0){
	                		   hiMap.put("fieldCode",field);
	                		   hiMap.put("fieldType","string");
	                		   fieldList.add(hiMap);
	                		   columns+=","+field;
	                		 }
	                		}
	                	 }*/
	
	                     String batchUpdateSql = String.format("update %s set %s where id = ?", queryRequest.getMaiTab(), ComUtils.getMultiUpdateColumnSqlByList(fieldList, columns));
	                     this.sqlExecutorDao.batchUpdate(batchUpdateSql, ComUtils.convertListMapToListObjects(datas, columns + ",id"));
	                 }
	    }
	    
	    
	    //保存临时表 
	    public  void saveRecordTmpTable(boolean isAdded,String tableName,Map<String,Object> map){
	    	
	    		//String itStr = String.format(" into %s(%s) values (%s)", tableName,columns,"%s");
	    		StringBuffer sbdata = new StringBuffer();
	    		//String[] columnNames = columns.split(",");
	    		
	    		//for(Map<String,Object> map : datas){
	    		//	StringBuffer valuesSql = new StringBuffer();
	    			
	    		 for (Map.Entry<String, Object> entry : map.entrySet()) {
	    			 sbdata.append(entry.getKey()).append(":").append(entry.getValue());
 				       //      System.out.println("key= " +  + " and value= "
 					       //             + entry.getValue());
	    			 sbdata.append(";");
 		        }
	    		/*	for(String key : columnNames){
	    			//	String realKey = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, key);
	    				//String realKey = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, key).toUpperCase();
	    				sbdata.append(key).append(":");
	    				String value = MapUtils.getString(map,key,"");
	    				 value=value.replace("'", "''");
	    				 if (value.indexOf(":")>0){
	    				   value=value.replace(":", "<~>");
	    				 }
	    				 if (value.indexOf(";")>0){
	    				   value=value.replace(";", "<^>");
	    				 }
	    				 sbdata.append(value).append(";");
	    				 */
	    				/*if(key.equalsIgnoreCase("id")){
	    					if (map.get("id")!=null&&!"".equals(map.get("id").toString())){
	    					   valuesSql.append(String.format(",'%s'", value));
	    					} else {
	    					   valuesSql.append(",sys_guid()");
	    					}
	    				}else if(key.equalsIgnoreCase("created_date")){
	    					valuesSql.append(",sysdate");
	    				}else if (value.startsWith("to_date(")){ //日期格式值  去掉单引号
	    					valuesSql.append(String.format(",%s", value));
	    				}else{
	    					value=value.replace("'", "''");
	    					valuesSql.append(String.format(",'%s'", value));
	    				}*/
	    		//	}
	    			//intoSql.append(String.format(itStr, valuesSql.substring(1)));
	    		//}
	    	//	String sql = String.format("insert all %s select * from dual", intoSql.toString());
	    	 	 String backStr=sbdata.toString();
	    	 	 backStr=backStr.substring(0,backStr.length()-1);
	    		// Operator operator = ThreadLocalUtil.getOperator();
	    		  StringBuffer sb=new StringBuffer("");
	    		 // String fields="id,data,created_by_id,created_date,dealed,operator_type";
	    		 sb.append(" insert into ").append(tableName).append("(");
	    		 if  (isAdded){//
	    			
	    			 sb=doSaveTmpTable(tableName,map,backStr,1);
	    		   
	    		 }else {
	    			 sb=new StringBuffer("");
	    			 // 先判断数据是否存在
	    			 List<?> dataList = this.generalRepository.queryByNativeSql("select id,dealed from "+tableName+" where id='"+map.get("id").toString()+"'", new HashMap<>());
	    			if (dataList!=null&&dataList.size()>0){
	    				//Object []obj=(Object [])dataList.get(0);
	    				sb.append("update ").append(tableName)
	    				.append(" set data='").append(backStr)
	    				.append("',created_date=sysdate,operator_type=0,dealed=0 where id='")
	    				.append(map.get("id").toString()).append("'");
	    			} else {
	    				sb=doSaveTmpTable(tableName,map,backStr,0);
	    			}

	    		 }
	    		 this.sqlExecutorDao.executeUpdate(sb.toString());
    
	    	
	    }
	    
	    public StringBuffer doSaveTmpTable(String  tableName,Map <String,Object>map,String backStr,int opertorType){
	     	 StringBuffer sb=new StringBuffer("");
	    	 Operator operator = ThreadLocalUtil.getOperator();
	    	 String fields="id,data,created_by_id,created_date,dealed,operator_type";
	    	  sb.append(" insert into ").append(tableName).append("(");
		    if (map.get("parentId")!=null&&!"".equals(map.get("parentId").toString())){ //写入明细表的临时表中
   			   fields="parent_id,"+fields;
   			   sb.append(fields);
   			   sb.append(") values('");
   			   sb.append(map.get("parentId").toString()).append("',");
   		   //  sql="insert into "+tableName+"(id,parent_id,data,created_by_id,created_date,dealed) values('"+map.get("id").toString()+"','"+map.get("parentId").toString()+"','"+backStr+"','"+operator.getPersonMemberId()+"',sysdate,0,1)";
   		    } else {
   			   sb.append(fields);
   			   sb.append(") values(");
   	        }
 			  sb.append("'").append(map.get("id").toString()).append("','")
   			 .append(backStr).append("','")
   			 .append(operator.getPersonMemberId())
   			 .append("',sysdate,0,").append(opertorType).append(")");
 			  return sb;
	    }
	    
	    //如果配置了存储过程方式,调用主表存储过程处理 
	    //过程名称"PROC_表名称"
 	   // 过程参数：主键ID，返回值
	    @Override
	    public String  callMainProcedure(String tableName,String id){
	    	Connection conn = null;
			CallableStatement cs = null;
			String back = "";
		  try {
			  String procName="PROC_"+tableName.toUpperCase();
	    	 conn = this.sqlExecutorDao.getDataSource().getConnection();
			//DatabaseMetaData meta=conn.getMetaData();
			//db_url=meta.getURL();
			conn.setAutoCommit(false);
				cs = conn.prepareCall("{call "+procName+"(?,?)}");
				cs.setString(1,id);
				cs.registerOutParameter(2, oracle.jdbc.OracleTypes.VARCHAR);
				cs.execute();
			  back = cs.getString(2);
			  conn.commit();
		  } catch (Exception ex) {
		        ex.printStackTrace();
		        throw new IllegalArgumentException(ex.getMessage());

		  }
		  return back;
	    }
	    
	    @Override
	    @Transactional
	    //删除实体数据
	    public void deleteDataRecord(DataRecordQueryRequest queryRequest, List<String> ids) {
	        // Assert.hasText(queryRequest.getId(), Constant.ID_NOT_BLANK);
	        String tableName =queryRequest.getMaiTab();
	        //   String tableName=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,queryR
	        // String mainTable=commonDataService.getTableName(queryRequest.getModelId());
	        //  String tableName=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,queryRequest.getSubTab());//转成下划线
	        //fields=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,fields);//转成下划线
	        //fields= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,fields); //转成驼峰法
	        try {
	            StringBuffer sb = null, detailsb = null;
	            //  String id[]=ids.split(",");
	            String []detailTables=queryRequest.getSubTab().split(",");
	            List<Map <String,Object>> dataList =new ArrayList<Map <String,Object>>();
	            for (int u = 0; u < ids.size(); u++) {

	                sb = new StringBuffer();
	                if (!StringUtils.isEmpty(ids.get(u))) { //明细数据id存在
	                    //  map.put("id", detail.getId());
	                    // String batchUpdateSql = String.format("update %s set %s where id = ?", tableName,CommonUtil.getMultiUpdateColumnSqlByList(columns));
	                    sb.append("delete from ").append(tableName).append(" where id='")
	                            .append(ids.get(u)).append("'");

	                	//删除临时表数据  如果是保存存储过程的
	                	 queryRequest.setSubTab(tableName+"_tmp");
	                   if (this.queryIsExistTable(queryRequest) == 1) {//存在临时表的 

	                	  //需要记录到临时表中 ，先判断数据是否存在
	   	                   saveTmpTableDetail(tableName,ids.get(u));
	                  
 	                    } 
	                    queryRequest.setSubTab("");
	                    //遍历明细表
	                    for (int i = 0; i < detailTables.length; i++) {
	        
	                        detailsb = new StringBuffer("");
	                        
	                    	queryRequest.setSubTab(detailTables[i]+"_tmp");
	  	                  if (this.queryIsExistTable(queryRequest) == 1) {//存在临时表的  表示通过存储过程 保存
	  	                		// 先判断数据是否存在，需要记录到临时表中 
	  	              	       String sql="select id,parent_id from "+detailTables[i]+" where parent_id='"+ids.get(u)+"'";
	  	  			           dataList = this.sqlExecutorDao.queryToListMap(sql,null);
	  	  			          if (dataList!=null&&dataList.size()>0){
	  	  			        	 for (int y=0;y<dataList.size();y++){
	  	   	                       saveTmpTableDetail(detailTables[i],dataList.get(y).get("id").toString());
	  	  			        	 }
	  	  			          }

	  	                   } 
	                        
	                          detailsb.append("delete from ").append(detailTables[i]).append(" where parent_id='").append(ids.get(u)).append("'");
	                          this.sqlExecutorDao.executeUpdate(detailsb.toString());

	                    }
	                    this.sqlExecutorDao.executeUpdate(sb.toString());
	                }

	            }
	        } catch (Exception ex) {
	            ex.printStackTrace();
	        }
	    }
	    
	    
	    //判断表是否存在
	    @Override
	    public int queryIsExistTable(DataRecordQueryRequest queryRequest) {

	        String detailTableName = queryRequest.getSubTab();
	        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "currentExistTable");
	        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
	        String sql = queryModel.getSql() + " and t.table_name='" + detailTableName.toUpperCase() + "'";
	        queryModel.setSql(sql);
	        queryModel.setSortFieldName("sequence");
	        Map<String, Object> mapData = this.sqlExecutorDao.executeSlicedQuery(queryModel);
	        //@SuppressWarnings("unchecked")
	        //List<Map<String, Object>> list = (List<Map<String, Object>>) mapData.get("Rows");
	        int total = 0;
	        if (mapData.get("file") != null) { //数据导出
	            total = 1;
	        } else {
	            total = Integer.parseInt(mapData.get("Total").toString());
	        }
	        return total;
	    }
	    
	    
	    @Override
	    public Map<String, Object> queryDataRecordDetail(DataRecordQueryRequest queryRequest) {
	        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor(""), queryRequest);
	        
	       // SafFormsQueryRequest formQueryRequest=new SafFormsQueryRequest();
	        //formQueryRequest.setId(queryRequest.getFormId());
	        //formQueryRequest.setTableName(queryRequest.getSubTab().toUpperCase());
	        List<Map<String, Object>> fieldList =this.commonUtilApplication.queryDataRecordMultsFields(queryRequest.getFormId(),queryRequest.getSubTab().toUpperCase());
	        
	        String detailTableName = queryRequest.getSubTab();

	        String fields = Utils.getDataFields(fieldList, "fieldCode");
	        //获取检索SQL返回的隐藏列
	         String hiddFields=queryRequest.getHiddenField().toString();
	         
	        StringBuffer sb = new StringBuffer("");
	        sb.append("select  id,parent_id,");
	        if (queryRequest.getHiddenField().size()>0){
	          sb.append(hiddFields.substring(1,hiddFields.length()-1)).append(",");
	        }
	        sb.append(fields);
	        sb.append(",'' sequence,status  from ");
	        sb.append(detailTableName);
	        sb.append(" where 1=1 ");
	        if (queryRequest.getId() != null) {
	            sb.append(" and parent_id='").append(queryRequest.getId()).append("'");
	        }
	        if (queryModel.getSortFieldName().startsWith("field")) {  //显示数据时  选定了排序字段
	            String[] field = fields.split(",");
	            queryModel.setSortFieldName(field[Integer.parseInt(queryModel.getSortFieldName().substring(5))]);
	        }
	        queryModel.setSql(sb.toString());
	        Map<String, Object> mapData = this.sqlExecutorDao.executeSlicedQuery(queryModel);
	        mapData.put("Rows", Utils.dataFieldTransfer(fieldList, (List<Map<String, Object>>) mapData.get("Rows")));
	        return mapData;

	    }

	  //保存明细行数据
	  //参数: formId,mid,subtable,List<PubDataRecord>
	  public Map<String, Object> saveRowDataRecordDetail(String formId,String mid,String subTable,List<PubDataRecord> detailData){

		  DataRecordQueryRequest queryRequest =new  DataRecordQueryRequest();//sdo.toQueryRequest(DataRecordQueryRequest.class);

		  SafFormslist form = this.safFormslistRepository.findOne(formId);

		  queryRequest.setId(mid);//主表ID
		  queryRequest.setFormId(formId);
		  queryRequest.setSubTab(subTable);

		  String tableNames=commonUtilApplication.getTablesByFormId(formId,1);
		  String tableName=tableNames.split(",")[0];  //取第一个是主表
		  queryRequest.setMaiTab(tableName);

		  //System.out.println("saveRowDetail================="+detailData.get(0).getField1()+"=pid="+sdo.getString("mid").toString()+"==="+detailData.get(0).getId());
		  // 存在数据字典的 将值字段 转换到保存的字段
		  List<PubDataRecord> newDetailData = new ArrayList<PubDataRecord>();

		  //获取所有隐藏的列
		 // String subTable = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, queryRequest.getSubTab());//转成下划线
		  DbTablesQueryRequest dbqueryRequest = new DbTablesQueryRequest();
		  dbqueryRequest.setTableName(subTable.toUpperCase());
		  List<String> hiddenFieldList = commonUtilApplication.queryTableHiddenFields(dbqueryRequest, 0); //0表示返回带下划线的 字段

		  //获取检索SQL返回的隐藏字段
		  queryRequest.setFormNo(form.getFormNo());
		  queryRequest.setSaveMode(form.getSaveMode());
		  // List <String> hiddenFieldList=getDetailHiddenFields(queryRequest);

		  PubDataRecord entity = null;
		  Map<String, Object> map = null, hiddenMap = null;
		  String field = ""; boolean allEmptyVal = true;
		  for (PubDataRecord pubDataRecord:detailData) {
			  map=Utils.convertBeanToMap(pubDataRecord,"field");;
			  entity = pubDataRecord;

			  //判断所有字段是否都是空值 ，如果是则不保存
			  allEmptyVal = true;
			  for (Map.Entry<String, Object> entry : map.entrySet()) {   //遍历所有数据字段
				  if (entry.getKey().toString().startsWith("field") &&
						  !"".equals(entry.getValue().toString())) {
					  allEmptyVal = false;
					  break;
				  }
			  }
			  if (!allEmptyVal) {

				  hiddenMap = new HashMap<String, Object>();

				  for (Map.Entry<String, Object> entry : map.entrySet()) {   //遍历所有数据字段
					  //  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
					  if (entry.getKey().toString().endsWith("_dictcode")) { ///来源数据字典的字段
						  field = entry.getKey().toString();
						  field = field.substring(0, field.length() - 9);
						  ReflectionUtil.invokeSet(entity, field, entry.getValue());
					  } else {  //查找是否存在隐藏列
						  if (!entry.getKey().toString().startsWith("field")) { //不是以field开头的   注意元数据名称不能以field开头
							  field = entry.getKey().toString();
							  if (entry.getValue() != null && !"".equals(entry.getValue())) {
								  // System.out.println("hiddenField Key = " + entry.getKey() + ", Value = " + entry.getValue());
								  for (String hiddenField : hiddenFieldList) {
									  field = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field);//转成下划线
									  if (field.equals(hiddenField)) {
										  hiddenMap.put(field, entry.getValue());
									  }
								  }
							  }
						  }
					  }
				  }

				  entity.setHiddField(hiddenMap);
				  newDetailData.add(entity);
			  }
		  }
		  //queryRequest  param: mainTab,subtab,formId,id ,savemode  ？？
		  Map<String, Object> data = new HashMap<String, Object>();
		  if (!org.apache.commons.lang.StringUtils.isEmpty(mid)&&newDetailData.size()>0) { //主表ID存在
			  //System.out.println("s-====================="+newDetailData.size()+"=="+newDetailData.get(0).getId());
			  data = this.saveDataRecordDetail(queryRequest, hiddenFieldList, newDetailData);
			  //data.put("result", backStr);
		  }
		  return data;

	  }
	    
	    //保存明细数据
	    @Override
	    @Transactional
		//参数: mainTab,subTab,formId,id,savemode,数据列表
	    public Map<String,Object> saveDataRecordDetail(DataRecordQueryRequest queryRequest,List <String> hiddenFieldList,List<PubDataRecord> detailData) {
	        Assert.hasText(queryRequest.getId(), Constant.ID_NOT_BLANK);
	       // String mainTable = queryRequest.getMaiTab();//commonDataService.getTableName(queryRequest.getFormId());
			String maiTable=queryRequest.getMaiTab();
			if  (queryRequest.getMaiTab().indexOf("_")<0) {  //不存在下划线的
				maiTable = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, queryRequest.getMaiTab());  //转成下划线
			}
			String subTable =queryRequest.getSubTab();
			if  (queryRequest.getSubTab().indexOf("_")<0) {  //不存在下划线的
				subTable = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, queryRequest.getSubTab());//转成下划线
			}
	          String sql = "",backStr="success",backIDs="";
	          Map <String,Object>backmap=new HashMap<String,Object>();
	        try {
	            //查询字段名称
	            queryRequest.setMaiTab(maiTable);  //带下划线 
	            queryRequest.setSubTab(subTable);
	            
	            Operator operator = ThreadLocalUtil.getOperator();
	           // SafFormsQueryRequest formQueryRequest=new SafFormsQueryRequest();
		       // formQueryRequest.setId(queryRequest.getFormId());
		        //formQueryRequest.setTableName(queryRequest.getSubTab().toUpperCase());
	            List<Map<String, Object>> fieldList = this.commonUtilApplication.queryDataRecordMultsFields(queryRequest.getFormId(),queryRequest.getSubTab().toUpperCase());
	            
	            Map<String, Object> map = null;
	            List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
	            String parentId = queryRequest.getId();
	            String columns = Utils.getDataFields(fieldList, "fieldCode");
	  //System.out.println("parentId==============="+queryRequest.getId());
	            //添加隐藏的列（获取第一列的）
	           // Map <String,Object>hiddMap=detailData.get(0).getHiddField();//如果是第一行乌
	        	//for (Map.Entry<String,Object> entry:hiddMap.entrySet()) { 
	            Map <String,Object>hiddMap=new HashMap<String,Object>();
	            for (String hiddenField:hiddenFieldList){
	        	  //if (entry.getValue()!=null&&!"".equals(entry.getValue())){
	              if (!"id".equals(hiddenField)){
	        		  columns+=","+hiddenField;
	        	   
	        		 hiddMap=new HashMap<String,Object>();
	     	         hiddMap.put("fieldCode",hiddenField);
	        		 if ("created_date".equals(hiddenField)){
	        	        hiddMap.put("fieldType","date");
	        		 }else {
	        	   	    hiddMap.put("fieldType","string");
	        		 }
	        	     fieldList.add(hiddMap);
	               }
	        	}
	           // List <?>rqList=this.generalRepository.queryByNativeSql("select sysdate from dual",new HashMap<String,Object>());
	             // String dbrq=rqList.get(0).toString().substring(0,19);
	              String dbrq=this.commonUtilApplication.queryDBCurrentDate();
	              String id ="",back="";
	              boolean isAdded=false;

	            for (PubDataRecord detail : detailData) {
	                map = Utils.dataValueTransfer(fieldList, detail);
                    map.putAll(detail.getHiddField());   //添加隐藏列的值
	                datas = new ArrayList<Map<String, Object>>();
	                 id = Utils.createUuid();

	               if ("2".equals(queryRequest.getSaveMode())){  //是存储过程方式  只将明细数据存入临时表
	 	                //	back=callDetailProcedure(subTable,parentId,id);
	            	        map.put("parentId", parentId);
	            	      
	            	        if (!StringUtils.isEmpty(detail.getId())) { //更新明细
	            	        	isAdded=false;
	            	             map.put("id", detail.getId());
	            	        } else {
	            	        	isAdded=true;
	            	        	map.put("id", id);
	            	        }
	 	                	saveRecordTmpTable(isAdded,subTable+"_tmp",map);
	 		           	 // if (back!=null&&!"".equals(back)){
	 	            	//	 throw new IllegalArgumentException(back);
	 	            	 // }
	 		       } else {
	                   //增加写入的隐藏列的默认数据值
                      if (hiddenFieldList.contains("created_date")){
 	                    map.put("created_date", dbrq);
 	                  }
 	                  if (hiddenFieldList.contains("created_by_id")){
 	                     map.put("created_by_id", operator.getPersonMemberId());
 	                   }
 	                  if (hiddenFieldList.contains("created_by_name")){
 	                    map.put("created_by_name", operator.getPersonMemberName());
 	                  }
 	                  //System.out.println("ss==detail=size======"+detailData.size()+"==="+detail.getId());
					   map.put("parent_id", parentId);
	                 if (!StringUtils.isEmpty(detail.getId())) { //更新明细
	                	id = detail.getId();
	                    map.put("id", detail.getId());
	                    datas.add(map);
	                    sql = String.format("update %s set %s where id = ?", subTable, ComUtils.getMultiUpdateColumnSqlByList(fieldList, columns));
						 //System.out.println("ss==update detail======="+sql);
	                    this.sqlExecutorDao.batchUpdate(sql, ComUtils.convertListMapToListObjects(datas, columns + ",id"));
	                 } else {   //新增明细
	                  //  map.put("parent_id", parentId);
	                    map.put("status", 1);
	                    map.put("id", id);
						 //System.out.println("ss==detail=add======"+parentId);
	                   // datas.add(map);
	                    sql = ComUtils.getMultiInsertSqlByList(subTable, map, columns + ",status,id,parent_id");
						 //System.out.println("ss==detail=add======"+sql);
	                    this.sqlExecutorDao.executeUpdate(sql);
	                 }
					   if (!"".equals(backIDs)){
						   backIDs+=",";
					   }
					   backIDs+=id;
	 		       }
	              
	            }
				backmap.put("backIDs",backIDs);
	        } catch (Exception ex) {
	        	System.out.println("sql:="+sql);backStr="failure："+ex.getMessage();
	        	throw new ApplicationException("保存明细表数据错误：" + ex.getMessage());
	           // ex.printStackTrace();
	        }
			backmap.put("result",backStr);
	        return  backmap;
	    }
	    
		//如果配置了存储过程方式,调用明细表存储过程处理 
	    //过程名称"PROC_表名称"
	    //过程参数：父ID,主键ID，返回值
	    @Override
	    public String callDetailProcedure(String subTable,String parentId,String id){
	    	Connection conn = null;
			CallableStatement cs = null;
			String back = "";
		  try {
			String procName="PROC_"+subTable.toUpperCase();
	    	conn = this.sqlExecutorDao.getDataSource().getConnection();
			//DatabaseMetaData meta=conn.getMetaData();
			//db_url=meta.getURL();
			conn.setAutoCommit(false);
			  cs = conn.prepareCall("{call "+procName+"(?,?,?)}");
				cs.setString(1,parentId);
				cs.setString(2,id);
				cs.registerOutParameter(3, oracle.jdbc.OracleTypes.VARCHAR);
				cs.execute();
			  back = cs.getString(3);
			  conn.commit();
		  } catch (Exception ex) {
			    back=ex.getMessage();
		        ex.printStackTrace();
		        throw new IllegalArgumentException(ex.getMessage());

		  }
		  return back;
	    }
	
	    
	     @Override  
	     //查询明细表中 检索SQL返回的隐藏字段  
	     public List<Map<String, Object>> queryHiddenFieldBySearchSQL(DataRecordQueryRequest queryRequest) {
	         Map<String, Object> mapData = new HashMap<String, Object>();
	         //safFormlist.xml -->queryFormDataRecordFields
	        // SafFormsQueryRequest queryRequest=new SafFormsQueryRequest();
	         QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor("queryHiddenFieldBySearchSQL"), queryRequest);
	         //queryModel.setPageSize(101);//默认100
	      //   queryModel.setPageIndex(1);
	          String sql=queryModel.getSql();
	         //查询单值字段
	        // StringBuffer sb = new StringBuffer("");
	         if  (queryRequest.getSubTab()!=null&&!"".equals(queryRequest.getSubTab())){
	        	 sql+=" and t.table_name='"+CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, queryRequest.getSubTab()).toUpperCase()+"'";
	         }
	         queryModel.setSql(sql);
	         mapData = this.sqlExecutorDao.executeSlicedQuery(queryModel);
	         @SuppressWarnings("unchecked")
	         List<Map<String, Object>> list = (List<Map<String, Object>>) mapData.get("Rows");

	         return list;
	     }
	     
	    @Override
	    @Transactional
	    //删除明细数据
	    public void deleteDataRecordDetail(DataRecordQueryRequest queryRequest, String ids) {
	        Assert.hasText(queryRequest.getId(), Constant.ID_NOT_BLANK);
	        // String mainTable=commonDataService.getTableName(queryRequest.getModelId());
	        String tableName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, queryRequest.getSubTab());//转成下划线
	        //fields=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,fields);//转成下划线
	        //fields= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,fields); //转成驼峰法
	        try {
	            //查询字段名称
	            //  queryRequest.setMaiTab(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,mainTable));
	            //   List <Map<String, Object>>fieldList=this.queryDataRecordMultsFields(queryRequest);
	            // Map <String, Object>map=null;
	            // List<Map<String,Object>> datas =new ArrayList<Map<String,Object>>();
	            // String parentId=queryRequest.getId();
	            StringBuffer sb = null;
	            String id[] = ids.split(",");
	            for (int u = 0; u < id.length; u++) {
	                // map=CommonDataService.dataValueTransfer(fieldList,detail);
	                //  String columns=map.get("columns").toString();
	                // map.remove("columns");
	                sb = new StringBuffer();
	                if (!StringUtils.isEmpty(id[u])) { //明细数据id存在
	                    //  map.put("id", detail.getId());
	                    // String batchUpdateSql = String.format("update %s set %s where id = ?", tableName,CommonUtil.getMultiUpdateColumnSqlByList(columns));
	                	//删除临时表数据  如果是保存存储过程的
	                	queryRequest.setSubTab(tableName+"_tmp");
	                   if (this.queryIsExistTable(queryRequest) == 1) {//如果存在临时表的 
	                	 // sb.append("delete from ").append(tableName+"_tmp").append(" where id='")
                           //.append(id[u]).append("'");
	                	  //需要记录到临时表中 
	                   	  saveTmpTableDetail(tableName,id[u]);
	                   } 
	                    queryRequest.setSubTab(tableName);
	                    sb.append("delete from ").append(tableName).append(" where id='")
	                            .append(id[u]).append("'");
	                   
	                    this.sqlExecutorDao.executeUpdate(sb.toString());
	                }

	            }
	        } catch (Exception ex) {
	            ex.printStackTrace();
	        }


	    }
	    
	    //数据保存到临时表
	    public void saveTmpTableDetail(String tableName,String id){
	    	  String sql="select * from "+tableName+" where id='"+id+"'";//
			  List<Map <String,Object>> dataList = this.sqlExecutorDao.queryToListMap(sql,null);
			if (dataList!=null&&dataList.size()>0){
				//Object []obj=(Object [])dataList.get(0);
				 StringBuffer  sbstr = new StringBuffer();
				Map <String,Object>map=dataList.get(0);
				 for (Map.Entry<String, Object> entry : map.entrySet()) {
					 sbstr.append(entry.getKey()).append(":").append(entry.getValue());
					sbstr.append(";");
		        }
				String backStr=sbstr.toString();
				backStr=backStr.substring(0,backStr.length()-1);
			   this.sqlExecutorDao.executeUpdate(this.doSaveTmpTable(tableName+"_tmp", map, backStr, -1).toString());
			}
       	
	    	
	    }
	    
	    ////改变状态
	    public String changeDataRecordStatus(DataRecordQueryRequest queryRequest) {
	        String backStr = "";
	        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor(""), queryRequest);
	       // String tableName = commonDataService.getTableName(queryRequest.getModelId());
	       // queryRequest.setSubTab(tableName);
	        String tableName=queryRequest.getMaiTab();
	        Map<String, Object> mapData = new HashMap<String, Object>();
	        if (!StringUtils.isEmpty(queryRequest.getId())) {
	            List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
	            mapData.put("id", queryRequest.getId());
	            mapData.put("status", queryRequest.getStatus());
	            datas.add(mapData);
	            String batchUpdateSql = String.format("update " + tableName + " set status=? where id = ?");
	            String columns = "status,id";
	            this.sqlExecutorDao.batchUpdate(batchUpdateSql, ComUtils.convertListMapToListObjects(datas, columns));
	        }
	        return backStr;
	    }

	    ////改变明细表的状态
	    public String changeDataRecordDetailStatus(DataRecordQueryRequest queryRequest) {
	        String backStr = ""; 
	        String tableName=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,queryRequest.getSubTab());
	      //  QueryModel queryModel = this.sqlExecutorDao.getQueryModel(getQueryDescriptor(""), queryRequest);
	        
	      // String tableName=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,queryRequest.getMaiTab());//转成下划线
	     //  String subTable=CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,queryRequest.getSubTab());

	        Map<String, Object> mapData = new HashMap<String, Object>();
	        if (!StringUtils.isEmpty(queryRequest.getId())) {
	            List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
	            mapData.put("id", queryRequest.getId());
	            mapData.put("status", queryRequest.getStatus());
	            datas.add(mapData);
	            String batchUpdateSql = String.format("update " + tableName + " set status=? where id = ?");
	            String columns = "status,id";
	            this.sqlExecutorDao.batchUpdate(batchUpdateSql, ComUtils.convertListMapToListObjects(datas, columns));
	        }
	        return backStr;
	    }

	    //效验函数方法     
	    /*
	     * 函数定义时：注意参数中默认第一个是id,第二个是当前字段的值，后面是其它参数的值
	     * 
	     */
       public  String checkFieldFunction(Map <String,Object> map){
	          Connection conn=null;
	          CallableStatement stmt=null;
	          String backMsg = "";
	      try {
	    	 conn=this.sqlExecutorDao.getDataSource().getConnection();
	   	     String currVal=map.get("currVal").toString();
		     String funcname=map.get("funcname").toString();
		     String []paramfield=null;
		    if (map.get("paramfields")!=null){
				   String paramfields=map.get("paramfields").toString();
				   paramfield=paramfields.split(",");
			}
	         StringBuffer  callFunc=new StringBuffer("");
	         callFunc.append("{?=call ").append(funcname);
	         callFunc.append("(?,?");  //
	         if (paramfield!=null){
	        	 for (int x=0;x<paramfield.length;x++){
	        	   callFunc.append(",?"); 
	        	 }
	         }
	         callFunc.append(")}");
		
	
			stmt = conn.prepareCall(callFunc.toString());

	        stmt.registerOutParameter(1, java.sql.Types.VARCHAR);  
	        stmt.setString(2, map.get("id").toString());
	        stmt.setString(3, currVal);  
	       for (int x=0;x<paramfield.length;x++){
	    	   stmt.setString(x+4, map.get(paramfield[x]).toString());    //需要判断不同数据类型  还是都作为string
	       }
	       // stmt.setString(2, key);
	          stmt.executeUpdate();  
	        // int retCode = stmt.getInt(1);  
	          backMsg = stmt.getString(1)!=null?stmt.getString(1):"";  
	          
		} catch (Exception e) {
			backMsg=e.getMessage();
			e.printStackTrace();
		}  finally {
			try {
				stmt.close();
			   if  (conn!=null)
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
          return backMsg;
     }
}
