package com.nms.server.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.nms.server.common.Constants;
import com.nms.server.util.ConnectionOracle;
import com.nms.server.util.DateUtil;
import com.nms.server.util.SQLExecuteTimeoutException;

public class CommonDao extends ConnectionOracle {
	
	public CommonDao() throws SQLException {
		super();
	}
	
	private Logger logger = Logger.getLogger(CommonDao.class);
	/**
	 * 插入数据 封装方法
	 * 
	 * @time Jul 27, 2011-4:00:44 PM
	 * @param tableName
	 *            插入表 表名
	 * @param info
	 *            字段和值集合
	 * @return
	 * @throws Exception
	 */
	public boolean insertObj(String tableName, Map<String, String> info)
			throws SQLExecuteTimeoutException,SQLException {
		StringBuffer values_0 =new StringBuffer();
		StringBuffer infoSQL = new StringBuffer("insert into " + tableName
				+ " ("); // SQL
		StringBuffer values = new StringBuffer(); // values
		// SQL拼写
		Iterator<Entry<String, String>> ite = info.entrySet().iterator();
		ArrayList<String> params = new ArrayList<String>();

		while (ite.hasNext()) {
			Entry<String, String> entry = ite.next();
			//logger.debug(entry.getKey()  +": \""+entry.getValue()+"\"" );
			if (StringUtils.isBlank(entry.getValue()))
				continue; // 跳过无效数据
			infoSQL.append(entry.getKey() + ",");
			params.add(entry.getValue());
			if (DateUtil.isDate(entry.getValue(), Constants.COMMON_DATE_FORMAT)) { // 日期类型
				values.append(" to_date(?,'" + Constants.DB_DATE_FORMAT
								+ "'),");
			} else { // 其他类型
				values.append("?,");
			}
			//--
			if (DateUtil.isDate(entry.getValue(), Constants.COMMON_DATE_FORMAT)) { // 日期类型
				values_0.append(" to_date('"+entry.getValue()+"','" + Constants.DB_DATE_FORMAT
								+ "'),");
			} else { // 其他类型
				values_0.append("'"+entry.getValue()+"',");
			}
		}

		infoSQL = infoSQL.deleteCharAt(infoSQL.length() - 1);
		values = values.deleteCharAt(values.length() - 1);
		values_0 = values_0.deleteCharAt(values_0.length() - 1);
		logger.debug(infoSQL+") values ("+values_0+")");
		infoSQL.append(") values (" + values + ")");
		return this.dbUpdate(infoSQL.toString(), params.toArray());
	}

	/**
	 * 插入数据 封装方法
	 * 
	 * @time Jul 27, 2011-4:00:44 PM
	 * @param tableName
	 *            插入表 表名
	 * @param info
	 *            字段和值集合
	 * @return
	 * @throws Exception
	 */
	public boolean insertObjByBatch(String tableName, List<Map<String, String>> infoList)
			throws SQLExecuteTimeoutException,SQLException {
		if(infoList!=null && infoList.size()>0){
			List<String> sqList = new LinkedList<String>();
			for(Map<String, String> info : infoList){
				StringBuffer values_0 =new StringBuffer();
				StringBuffer infoSQL = new StringBuffer("insert into " + tableName
						+ " ("); // SQL
				// SQL拼写
				Iterator<Entry<String, String>> ite = info.entrySet().iterator();
				ArrayList<String> params = new ArrayList<String>();
				
				while (ite.hasNext()) {
					Entry<String, String> entry = ite.next();
					//logger.debug(entry.getKey()  +": \""+entry.getValue()+"\"" );
					if (StringUtils.isBlank(entry.getValue()))
						continue; // 跳过无效数据
					infoSQL.append(entry.getKey() + ",");
					params.add(entry.getValue());
					
					//--
					if (DateUtil.isDate(entry.getValue(), Constants.COMMON_DATE_FORMAT)) { // 日期类型
						values_0
						.append(" to_date('"+entry.getValue()+"','" + Constants.DB_DATE_FORMAT
								+ "'),");
					} else { // 其他类型
						values_0.append("'"+entry.getValue()+"',");
					}
				}
				
				infoSQL = infoSQL.deleteCharAt(infoSQL.length() - 1);
				values_0 = values_0.deleteCharAt(values_0.length() - 1);
				logger.debug(infoSQL+") values ("+values_0+")");
				infoSQL.append(") values (" + values_0 + ")");
				sqList.add(infoSQL.toString());
			}
			return this.dbUpdateByBatch(sqList);
		}else{
			return true;
		}
	}
	
	
	/**
	 * 插入数据 封装方法
	 * 
	 * @time Jul 27, 2011-4:00:44 PM
	 * @param tableName
	 *            插入表 表名
	 * @param info
	 *            字段和值集合
	 * @return
	 * @throws Exception
	 */
	/*public boolean insertSimpleObjByBatch(String tableName,List<Map<String, String>> infoList)
			throws SQLExecuteTimeoutException,SQLException {
		
		//固定 字段名
		List<Object> columnList = null;
		//固定 sql
		StringBuffer infoSQL = new StringBuffer("insert into " + tableName
				+ " ("); // SQL
		StringBuffer values = new StringBuffer(); // values
		if(infoList!=null && infoList.size()>0){
			Map<String, String> map  =   infoList.get(0);
			
			columnList = Arrays.asList(map.keySet().toArray());
			
			for(Object obj : columnList){
				
				if(obj == null){
					continue;
				}
				
				String key = obj.toString();
				String value = map.get(key);
				
				logger.debug(key  +": \""+value+"\"" );
				infoSQL.append(key + ",");
				
				if (DateUtil.isDate(value, Constants.COMMON_DATE_FORMAT)) { // 日期类型
					values
					.append(" to_date(?,'" + Constants.DB_DATE_FORMAT
							+ "'),");
				} else { // 其他类型
					values.append("?,");
				}
			}
			infoSQL = infoSQL.deleteCharAt(infoSQL.length() - 1);
			values = values.deleteCharAt(values.length() - 1);
			infoSQL.append(") values (" + values + ")");
		}
		
		
		//整理值
		if(infoList!=null && infoList.size()>0){
			List<String[]> paramsList = new LinkedList<String[]>();
			
			for(Map<String, String> info : infoList){
				
				for(Object obj : columnList){
					if(obj == null){
						continue;
					}
					
					ArrayList<String> params = new ArrayList<String>();
					String value = info.get(obj);
					if(StringUtils.isBlank(value)){
						params.add("");
					}else{
						params.add(info.get(obj));
					}
					System.out.println(""+Arrays.toString(params.toArray(new String[0])));
					paramsList.add(params.toArray(new String[0]));
				}

			}
			return this.dbUpdateByBatch(infoSQL.toString(),paramsList);
		}else{
			return true;
		}
	}*/
	
	/**
	 * 查询数据 封装方法
	 * 
	 * @time Jul 27, 2011-4:08:38 PM
	 * @param attributes
	 * @param fields{
	 * 
	 * @param tableName
	 * @param info
	 * @return
	 * @throws Exception
	 */
	/*private ArrayList<Map<String, String>> selectObjs(ArrayList<String> fields,
			String tableName, Map<String, String> info) throws Exception {
		StringBuffer seachInfoSQL = new StringBuffer(); // 查询SQL
		if (fields == null || fields.size() == 0) { // 全部字段查询
			seachInfoSQL.append("select * from " + tableName + " where 1=1 ");
		} else { // 指定字段查询
			seachInfoSQL.append("select ");
			for (String attribute : fields) {
				seachInfoSQL.append(attribute + ",");
			}
			seachInfoSQL.deleteCharAt(seachInfoSQL.length() - 1);
			seachInfoSQL.append(" from " + tableName + " where 1=1 ");
		}
		// SQL拼写
		Iterator<Entry<String, String>> ite = info.entrySet().iterator();
		ArrayList<String> params = new ArrayList<String>();

		while (ite.hasNext()) {
			Entry<String, String> entry = ite.next();
			if (StringUtils.isEmpty(entry.getValue()))
				continue;
			params.add(entry.getValue());
			if (Common.isDate(entry.getValue(), Constants.COMMON_DATE_FORMAT)) {
				seachInfoSQL.append(" and to_char(" + entry.getKey() + ",'"
						+ Constants.DB_DATE_FORMAT + "') = ?");
			} else {
				seachInfoSQL.append(" and " + entry.getKey() + "=?");
			}
		}
		return this.dbSelect(seachInfoSQL.toString(), fields, params.toArray());
	}*/
}
