package com.anji.xwl.pojo;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;

import com.wb.util.DbUtil;
import com.wb.util.StringUtil;
import com.wb.util.WebUtil;

public class DBTool {

	public DBTool(Connection conns)
	{
		conn=conns;
		
	}

	private Connection conn=null;
	
	public String getInsertSql(String tableName)
	{
		String sql = null;

		sql = "select getInsertSql('"+tableName+"') from dual";
		String insertSql = "";
		ResultSet rs = null;
	
		Statement stmt = null;
		try {
			
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			if(rs.next())
			{
				insertSql = rs.getString(1);
			}
			stmt.close();
			
		} catch (SQLException e) {
			
			e.printStackTrace();
		}finally{
			try {
				rs.close();
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
		return insertSql;
	}
	public String getUpdateSql(String tableName)
	{
		String sql = null;

		sql = "select getUpdateSql('"+tableName+"') from dual";
		String insertSql = "";
		ResultSet rs = null;
	
		Statement stmt = null;
		try {
			
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			if(rs.next())
			{
				insertSql = rs.getString(1);
			}
			stmt.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				rs.close();
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
		return insertSql;
	}
	public String getSelectSql(String tableName)
	{
		String sql = null;

		sql = "select getSelectSql('"+tableName+"') from dual";
		String insertSql = "";
		ResultSet rs = null;
	
		Statement stmt = null;
		try {
		
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			if(rs.next())
			{
				insertSql = rs.getString(1);
			}
			stmt.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				rs.close();
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
		return insertSql;
	}
	/**
	 * 
	 * @param 表名
	 * @param 查询字段  null就行
	 * @return 返回该表信息
	 */
	public Table getTable(String  tableName,String searchcolumn)
	{
		String sql = null;

		sql="select  *  from  wb_Table  where TABLE_NAME='"+tableName+"'   order by  orderno";
		ResultSet rs = null;
		Statement stmt = null;
		Table table = new Table();
		table.setTableName(tableName);
		TableColumn column = null;
		Connection connection=null;
		List<TableColumn> columnList = new ArrayList<TableColumn>();
		try {
			connection=DbUtil.getConnection();
			stmt = connection.createStatement();
			rs = stmt.executeQuery(sql);
			table .setColumnList(bindDataToDTO(rs,new TableColumn()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			try {
				rs.close();
				stmt.close();
				connection.close();
				//conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
		return table;
	}
	public static void main(String[] args)
	{

		try {
			String[] sqls = buildSQLs("java:comp/env/jdbc/wb_mysql", "WB_MISC", false, 1, null, null, null, null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 
	 * @param rs  数据rs集合
	 * @param dto 实体bean
	 * @return  list 对象实体bean
	 * @throws Exception
	 */
	 public static List<TableColumn> bindDataToDTO(ResultSet rs, TableColumn dto) throws Exception {  
		  
	        //取得Method方法   
	        Method[] methods = dto.getClass().getMethods();  
	        List<TableColumn> list =new ArrayList<TableColumn>();
	        //取得ResultSet的列名   
	        ResultSetMetaData rsmd = rs.getMetaData();   
	        int columnsCount = rsmd.getColumnCount();   
	        String[] columnNames = new String[columnsCount];   
	        for (int i = 0; i < columnsCount; i++) {   
	            columnNames[i] = rsmd.getColumnLabel(i + 1);   
	        }  
	  
	        //遍历ResultSet   
	        while (rs.next()) {   
	            //反射, 从ResultSet绑定到JavaBean  
	        	
	        	 TableColumn column=new TableColumn();
	            for (int i = 0; i < columnNames.length; i++) {   
	                //取得Set方法   
	            	 Object value = rs.getObject(columnNames[i]);
	            	 if (value==null)
	            		 continue;
	                String setMethodName = "set" + columnNames[i];   
	                //遍历Method   
	                for (int j = 0; j < methods.length; j++) {  
	                	
	                    if (methods[j].getName().equalsIgnoreCase(setMethodName)) {   
	                        setMethodName = methods[j].getName();   
		                	System.out.println(setMethodName+"=============="+methods[j].getName());

	                       
	  
	                        //实行Set方法   
	                        try {   
	                            //JavaBean内部属性和ResultSet中一致时候   
	                            Method setMethod = column.getClass().getMethod(   
	                                    setMethodName, value.getClass());   
	                            setMethod.invoke(column, value);   
	                        } catch (Exception e) {   
	                            //JavaBean内部属性和ResultSet中不一致时候，使用String来输入值。   
	                            Method setMethod = column.getClass().getMethod(   
	                                    setMethodName, String.class);   
	                            setMethod.invoke(column, value.toString());   
	                        }  
	                        
	                        
	                    }   
	                }   
	            }  
	            list.add(column);
	        }  
	  
	        return list;   
	    }  
	 
	 /**
	  * 
	  * @param jndi
	  * @param tableName
	  * @param ignoreBlob
	  * @param scriptType
	  * @param request
	  * @param fields
	  * @param whereFields
	  * @param fieldsMap
	  * @return 动态生成 insert update和 delete语句
	  * @throws Exception
	  */
	 public static String[] buildSQLs(String jndi, String tableName,
				boolean ignoreBlob, int scriptType, HttpServletRequest request,
				JSONObject fields, JSONObject whereFields, JSONObject fieldsMap)
				throws Exception {
			String[] sqls = new String[4];
			Connection conn = null;
			PreparedStatement st = null;
			ResultSet rs = null;
			ResultSet rm = null;
			ResultSetMetaData meta;
			StringBuilder selectFields = new StringBuilder();
			StringBuilder insertFields = new StringBuilder();
			StringBuilder insertParams = new StringBuilder();
			StringBuilder condition = new StringBuilder();
			StringBuilder updateParams = new StringBuilder();
			String fieldName, fieldValueName, param, typeName, mapName;
			int i, j, type;
	
		
		
			boolean isFirstSelect = true, isFirstUpdate = true, isFirstCondi = true;
			boolean required, readOnly, isText, isBlob, isFloat, hasRequest = request != null;

			try {

					conn = DbUtil.getConnection( jndi);
				rm=conn.getMetaData().getPrimaryKeys(null,null,tableName);
				String  fileId="";
				if(rm.next())
					fileId=rm.getString(4);
					condition.append(fileId+"={?"+fileId+"?}");
					
				st = conn.prepareStatement("select * from " + tableName
						+ " where 1=0");
				rs = st.executeQuery();
				meta = rs.getMetaData();
				j = meta.getColumnCount() + 1;
				for (i = 1; i < j; i++) {
					type = meta.getColumnType(i);
					typeName = DbUtil.getTypeName(type);
					isText = DbUtil.isTextField(type) || meta.getPrecision(i) > 10000;
					isBlob = DbUtil.isBlobField(type);
					isFloat = DbUtil.maybeFloatField(type) && meta.getScale(i) > 0;
					required = meta.isNullable(i) == ResultSetMetaData.columnNoNulls;
					readOnly = meta.isReadOnly(i);
					fieldName = meta.getColumnLabel(i);
					fieldName = DbUtil.getFieldName(fieldName);
					fieldValueName = fieldName;
					fieldName = StringUtil.quoteIf(fieldName);
					if (fieldsMap != null) {
						mapName = fieldsMap.optString(fieldValueName, null);
						if (mapName != null)
							fieldValueName = mapName;
					}
					// $fieldName!=1表示忽略对blob空字段的处理，通常在修改记录时未更改blob即忽略处理。
					if (isBlob
							&& hasRequest
							&& StringUtil.isEmpty(WebUtil.fetch(request,
									fieldValueName))
							&& !"1".equals(WebUtil.fetch(request, "$"
									+ fieldValueName)))
						continue;
					if (fields == null
							&& (!ignoreBlob || !isBlob)
							|| (fields != null && (fields.has(fieldValueName) || fields
									.has("$" + fieldValueName)))) {
						if (isFirstSelect)
							isFirstSelect = false;
						else {
							selectFields.append(',');
						}
						selectFields.append(fieldName);
						if (!readOnly) {
							if (isFirstUpdate)
								isFirstUpdate = false;
							else {
								insertFields.append(',');
								insertParams.append(',');
								updateParams.append(',');
							}
							switch (scriptType) {
								case 1:
									if (typeName == null)
										param = StringUtil.concat("{?", fieldValueName,
												"?}");
									else
										param = StringUtil.concat("{?", typeName, ".",
												fieldValueName, "?}");
									break;
							case 2:
								param = StringUtil.concat("{#", fieldValueName,
										"#}");
								break;
							default:
								param = fieldValueName;
							}
							insertFields.append(fieldName);
							insertParams.append(param);
							updateParams.append(fieldName);
							updateParams.append('=');
							updateParams.append(param);
						}
					}
				
				}
				sqls[0] = StringUtil.concat("insert into ", tableName, " (",
						insertFields.toString(), ") values (", insertParams
								.toString(), ")");
				sqls[1] = StringUtil.concat("update ", tableName, " set ",
						updateParams.toString(), " where ", condition.toString());
				sqls[2] = StringUtil.concat("delete from ", tableName, " where ",
						condition.toString());
				sqls[3] = StringUtil.concat("select ", selectFields.toString(),
						" from ", tableName, " where ", condition.toString());
			} finally {
				DbUtil.close(rs);
				DbUtil.close(st);
				if (request == null)
					DbUtil.close(conn); // request!=null共享连接且自动释放
			}
			return sqls;
		}

}
