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.PgJgDao;
import com.szpg.db.data.PgJgStat;
import com.szpg.db.util.ConnectionManager;

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

	@Override
	public List<PgJgStat> findAllStat() {
		Connection conn = null;
		
		String queryStr = "SELECT ID, LOGTIME, PGDEVICEID, JGOPEN, JGLOCK FROM PG_JG_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<PgJgStat> list = new ArrayList<PgJgStat>();
				for (int i = 0; i < tempList.size(); i++) {
					PgJgStat stat = new PgJgStat();
					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.setJgopen(Boolean.parseBoolean((String) item[3]));
					stat.setJglock(Boolean.parseBoolean((String) item[4]));
					
					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 PgJgStat findStatById(Integer id) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, LOGTIME, PGDEVICEID, JGOPEN, JGLOCK FROM PG_JG_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) {
				PgJgStat stat = new PgJgStat();
				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.setJgopen(Boolean.parseBoolean((String) item[3]));
				stat.setJglock(Boolean.parseBoolean((String) item[4]));
				
				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<PgJgStat> findStatByDevice(Integer deviceid) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, LOGTIME, PGDEVICEID, JGOPEN, JGLOCK FROM PG_JG_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<PgJgStat> list = new ArrayList<PgJgStat>();
				for (int i = 0; i < tempList.size(); i++) {
					PgJgStat stat = new PgJgStat();
					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.setJgopen(Boolean.parseBoolean((String) item[3]));
					stat.setJglock(Boolean.parseBoolean((String) item[4]));
					
					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<PgJgStat> findStatByDeviceAndTm(Integer deviceid, String start, String end) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, LOGTIME, PGDEVICEID, JGOPEN, JGLOCK FROM PG_JG_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<PgJgStat> list = new ArrayList<PgJgStat>();
				for (int i = 0; i < tempList.size(); i++) {
					PgJgStat stat = new PgJgStat();
					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.setJgopen(Boolean.parseBoolean((String) item[3]));
					stat.setJglock(Boolean.parseBoolean((String) item[4]));
					
					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 PgJgStat findLatestStatByDevice(Integer deviceid) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, LOGTIME, PGDEVICEID, JGOPEN, JGLOCK FROM PG_JG_STAT WHERE PGDEVICEID = ? ORDER BY LOGTIME DESC";
		Object[] param = new Object[1];
		param[0] = deviceid;
		try {
			QueryRunner runner = new QueryRunner();
			List<Object[]> tempList = (List<Object[]>) runner.query(conn, queryStr, new ArrayListHandler());
			
			if (null != tempList && tempList.isEmpty() == false) {
				PgJgStat stat = new PgJgStat();
				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.setJgopen(Boolean.parseBoolean((String) item[3]));
				stat.setJglock(Boolean.parseBoolean((String) item[4]));
				
				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 addSbjzRecord(PgJgStat jgstat) {
		return addSbjzRecord(jgstat.getJgopen(), jgstat.getJglock(), jgstat.getTmStr(), jgstat.getPgdeviceid());
	}

	@Override
	public int addSbjzRecord(boolean open, boolean lock, String tm, int deviceid) {
		Connection conn = null;
		
		String insertStr = "INSERT INTO PG_JG_STAT " + 
						   "(JGOPEN, JGLOCK, 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] = open;
		params[1] = lock;
		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 + ", open=" + open + ", lock=" + lock + ", 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;
	}

}
