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.log4j.Logger;

import com.szpg.db.dao.PgSbDao;
import com.szpg.db.data.PgSbRt;
import com.szpg.db.data.PgSbStat;
import com.szpg.db.util.ConnectionManager;

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

	@Override
	public PgSbRt findLatestRtByDevice(Integer deviceid) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, LOGTIME, PGDEVICEID, RUNSECOND1, RUNSECOND2, RUNHOUR1, RUNHOUR2 FROM PG_SB_RT WHERE PGDEVICEID = ? ORDER BY LOGTIME DESC";
		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) {
				PgSbRt rt = new PgSbRt();
				Object[] item = tempList.get(0);
				
				rt.setId(((Number) item[0]).intValue());
				rt.setPgdeviceid(((Number) item[2]).intValue());
				
				long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[1]).toJdbc()).getTime();
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(tmValue);
				rt.setLogtime(cal.getTime());
				rt.setUptime(cal.getTime());
				
				rt.setRunsecond1(Integer.parseInt((String) item[3]));
				rt.setRunsecond2(Integer.parseInt((String) item[4]));
				rt.setRunhour1(Integer.parseInt((String) item[5]));
				rt.setRunhour2(Integer.parseInt((String) item[6]));
				
				logger.debug("根据ID查询水泵最新运行时长成功" + rt + "]");
				
				return rt;
			}
			else 
				return null;
		} catch (Exception ex) {
			logger.error("根据设备ID查询水泵最新运行时长异常", ex);
		} finally {
			try {
				DbUtils.commitAndClose(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public int addRtRecord(PgSbRt sbrt) {
		return addRtRecord(sbrt.getRunsecond1(), sbrt.getRunsecond2(), sbrt.getRunhour1(), sbrt.getRunhour2(), sbrt.getTmStr(), sbrt.getPgdeviceid());
	}

	@Override
	public int addRtRecord(int second1, int hour1, String tm, int deviceid) {
		Connection conn = null;
		
		String insertStr = "INSERT INTO PG_SB_RT " + 
						   "(RUNSECOND1, RUNHOUR1, LOGTIME, UPTIME, PGDEVICEID) " + 
						   "VALUES (?, ?, TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), ?)";
		Object[] params = new Object[5];
		params[0] = second1;
		params[1] = hour1;
		params[2] = tm;
		params[3] = tm;
		params[4] = 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 + ", second1=" + second1 + ", hour1=" + hour1 + ", 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;
	}
	
	@Override
	public int addRtRecord(int second1, int hour1, int second2, int hour2, String tm, int deviceid) {
		Connection conn = null;
		
		String insertStr = "INSERT INTO PG_SB_RT " + 
						   "(RUNSECOND1, RUNSECOND2, RUNHOUR1, RUNHOUR2, LOGTIME, UPTIME, PGDEVICEID) " + 
						   "VALUES (?, ?, ?, ?, TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), ?)";
		Object[] params = new Object[7];
		params[0] = second1;
		params[1] = second2;
		params[2] = hour1;
		params[3] = hour2;
		params[4] = tm;
		params[5] = tm;
		params[6] = 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 + ", second=" + second1 + "/" + second2 + ", hour=" + hour1 + "/" + hour2 + ", 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;
	}

	@Override
	public List<PgSbStat> findAllStat() {
		Connection conn = null;
		
		String queryStr = "SELECT ID, LOGTIME, PGDEVICEID, RUN1, RUN2, FLT1, FLT2 FROM PG_SB_STAT";
		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<PgSbStat> list = new ArrayList<PgSbStat>();
				for (int i = 0; i < tempList.size(); i++) {
					PgSbStat stat = new PgSbStat();
					Object[] item = tempList.get(i);
					
					stat.setId(((Number) item[0]).intValue());
					stat.setPgdeviceid(((Number) item[2]).intValue());
					
					long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[1]).toJdbc()).getTime();
					Calendar cal = Calendar.getInstance();
					cal.setTimeInMillis(tmValue);
					stat.setLogtime(cal.getTime());
					stat.setUptime(cal.getTime());
					
					stat.setRun1(Boolean.parseBoolean((String) item[3]));
					stat.setRun2(Boolean.parseBoolean((String) item[4]));
					stat.setFlt1(Boolean.parseBoolean((String) item[5]));
					stat.setFlt2(Boolean.parseBoolean((String) item[6]));
					
					list.add(stat);
				}
				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 PgSbStat findStatById(Integer id) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, LOGTIME, PGDEVICEID, RUN1, RUN2, FLT1, FLT2 FROM PG_SB_STAT 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) {
				PgSbStat stat = new PgSbStat();
				Object[] item = tempList.get(0);
				
				stat.setId(((Number) item[0]).intValue());
				stat.setPgdeviceid(((Number) item[2]).intValue());
				
				long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[1]).toJdbc()).getTime();
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(tmValue);
				stat.setLogtime(cal.getTime());
				stat.setUptime(cal.getTime());
				
				stat.setRun1(Boolean.parseBoolean((String) item[3]));
				stat.setRun2(Boolean.parseBoolean((String) item[4]));
				stat.setFlt1(Boolean.parseBoolean((String) item[5]));
				stat.setFlt2(Boolean.parseBoolean((String) item[6]));
				
				logger.debug("根据ID查询水泵运行状态成功" + stat + "]");
				
				return stat;
			}
			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<PgSbStat> findStatByDevice(Integer deviceid) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, LOGTIME, PGDEVICEID, RUN1, RUN2, FLT1, FLT2 FROM PG_SB_STAT 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<PgSbStat> list = new ArrayList<PgSbStat>();
				for (int i = 0; i < tempList.size(); i++) {
					PgSbStat stat = new PgSbStat();
					Object[] item = tempList.get(i);
					
					stat.setId(((Number) item[0]).intValue());
					stat.setPgdeviceid(((Number) item[2]).intValue());
					
					long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[1]).toJdbc()).getTime();
					Calendar cal = Calendar.getInstance();
					cal.setTimeInMillis(tmValue);
					stat.setLogtime(cal.getTime());
					stat.setUptime(cal.getTime());
					
					stat.setRun1(Boolean.parseBoolean((String) item[3]));
					stat.setRun2(Boolean.parseBoolean((String) item[4]));
					stat.setFlt1(Boolean.parseBoolean((String) item[5]));
					stat.setFlt2(Boolean.parseBoolean((String) item[6]));
					
					list.add(stat);
				}
				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<PgSbStat> findStatByDeviceAndTm(Integer deviceid, String start, String end) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, LOGTIME, PGDEVICEID, RUN1, RUN2, FLT1, FLT2 FROM PG_SB_STAT 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<PgSbStat> list = new ArrayList<PgSbStat>();
				for (int i = 0; i < tempList.size(); i++) {
					PgSbStat stat = new PgSbStat();
					Object[] item = tempList.get(i);
					
					stat.setId(((Number) item[0]).intValue());
					stat.setPgdeviceid(((Number) item[2]).intValue());
					
					long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[1]).toJdbc()).getTime();
					Calendar cal = Calendar.getInstance();
					cal.setTimeInMillis(tmValue);
					stat.setLogtime(cal.getTime());
					stat.setUptime(cal.getTime());
					
					stat.setRun1(Boolean.parseBoolean((String) item[3]));
					stat.setRun2(Boolean.parseBoolean((String) item[4]));
					stat.setFlt1(Boolean.parseBoolean((String) item[5]));
					stat.setFlt2(Boolean.parseBoolean((String) item[6]));
					
					list.add(stat);
				}
				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 PgSbStat findLatestStatByDevice(Integer deviceid) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, LOGTIME, PGDEVICEID, RUN1, RUN2, FLT1, FLT2 FROM PG_SB_STAT WHERE PGDEVICEID = ? ORDER BY LOGTIME DESC";
		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) {
				PgSbStat stat = new PgSbStat();
				Object[] item = tempList.get(0);
				
				stat.setId(((Number) item[0]).intValue());
				stat.setPgdeviceid(((Number) item[2]).intValue());
				
				long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[1]).toJdbc()).getTime();
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(tmValue);
				stat.setLogtime(cal.getTime());
				stat.setUptime(cal.getTime());
				
				stat.setRun1(Boolean.parseBoolean((String) item[3]));
				stat.setRun2(Boolean.parseBoolean((String) item[4]));
				stat.setFlt1(Boolean.parseBoolean((String) item[5]));
				stat.setFlt2(Boolean.parseBoolean((String) item[6]));
				
				logger.debug("根据ID查询水泵最新运行状态成功" + stat + "]");
				
				return stat;
			}
			else 
				return null;
		} catch (Exception ex) {
			logger.error("根据设备ID查询水泵最新运行状态异常", ex);
		} finally {
			try {
				DbUtils.commitAndClose(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	public int addStatRecord(PgSbStat sbstat) {
		Connection conn = null;
		
		String insertStr = "INSERT INTO PG_SB_STAT " + 
						   "(RUN1, RUN2, FLT1, FLT2, LOGTIME, UPTIME, PGDEVICEID) " + 
						   "VALUES (?, ?, ?, ?, TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), ?)";
		Object[] params = new Object[7];
		params[0] = sbstat.getRun1();
		params[1] = sbstat.getRun2();
		params[2] = sbstat.getFlt1();
		params[3] = sbstat.getFlt2();
		params[4] = sbstat.getTmStr();
		params[5] = sbstat.getTmStr();
		params[6] = sbstat.getPgdeviceid();
		
		try {
			conn = ConnectionManager.getConnectionFromC3P0();
			conn.setAutoCommit(false);
			
			QueryRunner runner = new QueryRunner();
			int count = runner.update(conn, insertStr, params);
			
			if (count > 0) 
				logger.debug("插入水泵运行状态成功" + sbstat);
			else 
				logger.error("插入水泵运行状态失败！");
			
			return count;
		} catch (Exception ex) {
			logger.error("插入水泵运行状态异常", ex);
		} finally {
			try {
				DbUtils.commitAndClose(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	@Override
	public int addStatRecord(boolean run1, boolean flt1, String tm, int deviceid) {
		Connection conn = null;
		
		String insertStr = "INSERT INTO PG_SB_STAT " + 
						   "(RUN1, FLT1, LOGTIME, UPTIME, PGDEVICEID) " + 
						   "VALUES (?, ?, TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), ?)";
		Object[] params = new Object[5];
		params[0] = run1;
		params[1] = flt1;
		params[2] = tm;
		params[3] = tm;
		params[4] = 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 + ", run1=" + run1 + ", flt1=" + flt1 + ", 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;
	}
	
	@Override
	public int addStatRecord(boolean run1, boolean run2, boolean flt1, boolean flt2, String tm, int deviceid) {
		Connection conn = null;
		
		String insertStr = "INSERT INTO PG_SB_STAT " + 
						   "(RUN1, RUN2, FLT1, FLT2, LOGTIME, UPTIME, PGDEVICEID) " + 
						   "VALUES (?, ?, ?, ?, TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), ?)";
		Object[] params = new Object[7];
		params[0] = run1;
		params[1] = run2;
		params[2] = flt1;
		params[3] = flt2;
		params[4] = tm;
		params[5] = tm;
		params[6] = 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 + ", run=" + run1 + "/" + run2 + ", flt=" + flt1 + "/" + flt2 + ", 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;
	}

}
