package com.szpg.db.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.apache.log4j.Logger;

import com.szpg.db.dao.PgHSDao;
import com.szpg.db.data.PgSH;
import com.szpg.db.util.ConnectionManager;
import com.szpg.util.NumberFormat;

public class PgHSDaoImpl implements PgHSDao {
	
	private final Logger logger = Logger.getLogger(this.getClass().getName());

	@Override
	public List<PgSH> findAllPblz() {
		Connection conn = null;
		
		String queryStr = "SELECT ID, SH, LOGTIME, PGDEVICEID FROM PG_SH";
		try {
			conn = ConnectionManager.getConnectionFromC3P0();
			conn.setAutoCommit(false);
			
			QueryRunner runner = new QueryRunner();
			List<Object[]> tempList = (List<Object[]>) runner.query(conn, queryStr, new ArrayListHandler());
			
			if (null != tempList && tempList.isEmpty() == false) {
				logger.debug("查询所有硫化氢监测值成功[" + tempList.size() + "]");
				
				List<PgSH> list = new ArrayList<PgSH>();
				for (int i = 0; i < tempList.size(); i++) {
					PgSH sh = new PgSH();
					Object[] item = tempList.get(i);
					
					sh.setId(((Number) item[0]).intValue());
					sh.setSh(Float.parseFloat((String) item[1]));
					sh.setPgdeviceid(((Number) item[3]).intValue());
					
					long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[2]).toJdbc()).getTime();
					Calendar cal = Calendar.getInstance();
					cal.setTimeInMillis(tmValue);
					sh.setLogtime(cal.getTime());
					sh.setUptime(cal.getTime());
					
					list.add(sh);
				}
				return list;
			}
			else 
				return null;
		} catch (Exception ex) {
			logger.error("查询所有硫化氢监测值异常", ex);
		} finally {
			try {
				DbUtils.commitAndClose(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public PgSH findPblzById(Integer id) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, SH, LOGTIME, PGDEVICEID FROM PG_SH WHERE ID = ?";
		Object[] param = new Object[1];
		param[0] = id;
		try {
			conn = ConnectionManager.getConnectionFromC3P0();
			conn.setAutoCommit(false);
			
			QueryRunner runner = new QueryRunner();
			List<Object[]> tempList = (List<Object[]>) runner.query(conn, queryStr, new ArrayListHandler(), param);
			
			if (null != tempList && tempList.size() == 1) {
				PgSH sh = new PgSH();
				Object[] item = tempList.get(0);
				
				sh.setId(((Number) item[0]).intValue());
				sh.setSh(Float.parseFloat((String) item[1]));
				sh.setPgdeviceid(((Number) item[3]).intValue());
				
				long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[2]).toJdbc()).getTime();
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(tmValue);
				sh.setLogtime(cal.getTime());
				sh.setUptime(cal.getTime());
				
				logger.debug("根据ID查询硫化氢监测值成功" + sh + "]");
				
				return sh;
			}
			else 
				return null;
		} catch (Exception ex) {
			logger.error("根据ID查询硫化氢监测值异常", ex);
		} finally {
			try {
				DbUtils.commitAndClose(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	@Override
	public PgSH findLatestPblzByDevice(Integer deviceid) {
		Connection conn = null;

		String queryStr = "SELECT A.* FROM " +
				"(SELECT ID, SH, LOGTIME, PGDEVICEID FROM PG_SH WHERE PGDEVICEID = ? ORDER BY LOGTIME DESC) A " +
				"WHERE ROWNUM <= 1";
		Object[] param = new Object[1];
		param[0] = deviceid;
		try {
			conn = ConnectionManager.getConnectionFromC3P0();
			conn.setAutoCommit(false);
			
			QueryRunner runner = new QueryRunner();
			List<Object[]> tempList = (List<Object[]>) runner.query(conn, queryStr, new ArrayListHandler(), param);
			
			if (null != tempList && tempList.isEmpty() == false) {
				PgSH sh = new PgSH();
				Object[] item = tempList.get(0);
				
				sh.setId(((Number) item[0]).intValue());
				sh.setSh(Float.parseFloat((String) item[1]));
				sh.setPgdeviceid(((Number) item[3]).intValue());
				
				long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[2]).toJdbc()).getTime();
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(tmValue);
				sh.setLogtime(cal.getTime());
				sh.setUptime(cal.getTime());
				
				logger.debug("根据设备ID查询最新的硫化氢监测值成功" + sh + "]");
				
				return sh;
			}
			else 
				return null;
		} catch (Exception ex) {
			logger.error("根据设备ID查询最新的硫化氢监测值异常", ex);
		} finally {
			try {
				DbUtils.commitAndClose(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public List<PgSH> findPblzByDevice(Integer deviceid) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, SH, LOGTIME, PGDEVICEID FROM PG_SH WHERE PGDEVICEID = ?";
		Object[] param = new Object[1];
		param[0] = deviceid;
		try {
			conn = ConnectionManager.getConnectionFromC3P0();
			conn.setAutoCommit(false);
			
			QueryRunner runner = new QueryRunner();
			List<Object[]> tempList = (List<Object[]>) runner.query(conn, queryStr, new ArrayListHandler());
			
			if (null != tempList && tempList.isEmpty() == false) {
				logger.debug("根据设备ID查询硫化氢监测值成功[" + tempList.size() + "]");
				
				List<PgSH> list = new ArrayList<PgSH>();
				for (int i = 0; i < tempList.size(); i++) {
					PgSH sh = new PgSH();
					Object[] item = tempList.get(i);
					
					sh.setId(((Number) item[0]).intValue());
					sh.setSh(Float.parseFloat((String) item[1]));
					sh.setPgdeviceid(((Number) item[3]).intValue());
					
					long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[2]).toJdbc()).getTime();
					Calendar cal = Calendar.getInstance();
					cal.setTimeInMillis(tmValue);
					sh.setLogtime(cal.getTime());
					sh.setUptime(cal.getTime());
					
					list.add(sh);
				}
				return list;
			}
			else 
				return null;
		} catch (Exception ex) {
			logger.error("根据设备ID查询硫化氢监测值异常", ex);
		} finally {
			try {
				DbUtils.commitAndClose(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public List<PgSH> findPblzByDeviceAndTm(Integer deviceid, String start, String end) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, SH, LOGTIME, PGDEVICEID FROM PG_SH WHERE PGDEVICEID = ? AND LOGTIME >= TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS') AND LOGTIME <= TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS')";
		Object[] params = new Object[3];
		params[0] = deviceid;
		params[1] = start;
		params[2] = end;
		try {
			conn = ConnectionManager.getConnectionFromC3P0();
			conn.setAutoCommit(false);
			
			QueryRunner runner = new QueryRunner();
			List<Object[]> tempList = (List<Object[]>) runner.query(conn, queryStr, new ArrayListHandler());
			
			if (null != tempList && tempList.isEmpty() == false) {
				logger.debug("根据设备ID和时间查询硫化氢监测值成功[" + tempList.size() + "]");
				
				List<PgSH> list = new ArrayList<PgSH>();
				for (int i = 0; i < tempList.size(); i++) {
					PgSH sh = new PgSH();
					Object[] item = tempList.get(i);
					
					sh.setId(((Number) item[0]).intValue());
					sh.setSh(Float.parseFloat((String) item[1]));
					sh.setPgdeviceid(((Number) item[3]).intValue());
					
					long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[2]).toJdbc()).getTime();
					Calendar cal = Calendar.getInstance();
					cal.setTimeInMillis(tmValue);
					sh.setLogtime(cal.getTime());
					sh.setUptime(cal.getTime());
					
					list.add(sh);
				}
				return list;
			}
			else 
				return null;
		} catch (Exception ex) {
			logger.error("根据设备ID和时间查询硫化氢监测值异常", ex);
		} finally {
			try {
				DbUtils.commitAndClose(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	@Override
	public double findLastValueByDevice(Integer deviceid) {
		Connection conn = null;
		
		String sql = "SELECT SH FROM (SELECT * FROM PG_SH WHERE PGDEVICEID = ? ORDER BY ID DESC) WHERE ROWNUM = 1";
		Object[] param = new Object[1];
		param[0] = deviceid;
		try {
			conn = ConnectionManager.getConnectionFromC3P0();
			conn.setAutoCommit(false);
			
			QueryRunner runner = new QueryRunner();
			double value = NumberFormat.parseDouble((String) runner.query(conn, sql, new ScalarHandler<String>(1), param), "0.00");
			return value;
		} catch (Exception ex) {
			logger.error("根据设备查询最近的硫化氢浓度值异常", ex);
		} finally {
			try {
				DbUtils.commitAndClose(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return 0.0;
	}

	@Override
	public int addPblzRecord(PgSH sh) {
		return addPblzRecord(sh.getSh(), sh.getTmStr(), sh.getPgdeviceid());
	}

	@Override
	public int addPblzRecord(float value, String tm, int deviceid) {
		Connection conn = null;
		
		String insertStr = "INSERT INTO PG_SH " + 
						   "(SH, LOGTIME, UPTIME, PGDEVICEID) " + 
						   "VALUES (?, TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), ?)";
		Object[] params = new Object[4];
		params[0] = NumberFormat.format(value, "0.00");
		params[1] = tm;
		params[2] = tm;
		params[3] = deviceid;
		
		try {
			conn = ConnectionManager.getConnectionFromC3P0();
			conn.setAutoCommit(false);
			
			QueryRunner runner = new QueryRunner();
			int count = runner.update(conn, insertStr, params);
			
			if (count > 0) 
				logger.debug("插入硫化氢监测值成功[tm=" + tm + ", value=" + value + ", deviceid=" + deviceid + "]");
			else 
				logger.error("插入硫化氢监测值失败！");
			
			return count;
		} catch (Exception ex) {
			logger.error("插入硫化氢监测值异常", ex);
		} finally {
			try {
				DbUtils.commitAndClose(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

}
