package com.szpg.db.dao.impl;

import com.szpg.db.dao.PgPowerDao;
import com.szpg.db.data.PgPower;
import com.szpg.db.util.ConnectionManager;
import com.szpg.util.NumberFormat;
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 java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

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

	@Override
	public List<PgPower> findAllPower() {
		Connection conn = null;
		
		String queryStr = "SELECT ID, AU, BU, CU, AI, BI, CI, LOGTIME, PGDEVICEID FROM PG_POWER";
		try {
			conn = ConnectionManager.getConnectionFromC3P0();
			conn.setAutoCommit(false);
			
			QueryRunner runner = new QueryRunner();
			List<Object[]> powerList = (List<Object[]>) runner.query(conn, queryStr, new ArrayListHandler());
			
			if (null != powerList && powerList.isEmpty() == false) {
				logger.debug("查询所有电力参数监测值成功[" + powerList.size() + "]");
				
				List<PgPower> list = new ArrayList<PgPower>();
				for (int i = 0; i < powerList.size(); i++) {
					PgPower power = new PgPower();
					Object[] item = powerList.get(i);
					
					power.setId(((Number) item[0]).intValue());
					power.setAu(Float.parseFloat((String) item[1]));
					power.setBu(Float.parseFloat((String) item[2]));
					power.setCu(Float.parseFloat((String) item[3]));
					power.setAi(Float.parseFloat((String) item[4]));
					power.setBi(Float.parseFloat((String) item[5]));
					power.setCi(Float.parseFloat((String) item[6]));
					power.setPgdeviceid(((Number) item[8]).intValue());
					
					long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[7]).toJdbc()).getTime();
					Calendar cal = Calendar.getInstance();
					cal.setTimeInMillis(tmValue);
					power.setLogtime(cal.getTime());
					power.setUptime(cal.getTime());
					
					list.add(power);
				}
				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 PgPower findPowerById(Integer id) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, AU, BU, CU, AI, BI, CI, LOGTIME, PGDEVICEID FROM PG_POWER 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) {
				PgPower power = new PgPower();
				Object[] item = tempList.get(0);

				power.setId(((Number) item[0]).intValue());
				power.setAu(Float.parseFloat((String) item[1]));
				power.setBu(Float.parseFloat((String) item[2]));
				power.setCu(Float.parseFloat((String) item[3]));
				power.setAi(Float.parseFloat((String) item[4]));
				power.setBi(Float.parseFloat((String) item[5]));
				power.setCi(Float.parseFloat((String) item[6]));
				power.setPgdeviceid(((Number) item[8]).intValue());

				long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[7]).toJdbc()).getTime();
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(tmValue);
				power.setLogtime(cal.getTime());
				power.setUptime(cal.getTime());
				
				logger.debug("根据ID查询电力监测值成功" + power);
				
				return power;
			}
			else 
				return null;
		} catch (Exception ex) {
			logger.error("根据ID查询电力监测值异常", ex);
		} finally {
			try {
				DbUtils.commitAndClose(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	@Override
	public PgPower findLatestPowerByDevice(Integer deviceid) {
		Connection conn = null;

		String queryStr = "SELECT A.* FROM " +
				"(SELECT ID, AU, BU, CU, AI, BI, CI, LOGTIME, PGDEVICEID FROM PG_POWER 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) {
				PgPower power = new PgPower();
				Object[] item = tempList.get(0);

				power.setId(((Number) item[0]).intValue());
				power.setAu(Float.parseFloat((String) item[1]));
				power.setBu(Float.parseFloat((String) item[2]));
				power.setCu(Float.parseFloat((String) item[3]));
				power.setAi(Float.parseFloat((String) item[4]));
				power.setBi(Float.parseFloat((String) item[5]));
				power.setCi(Float.parseFloat((String) item[6]));
				power.setPgdeviceid(((Number) item[8]).intValue());

				long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[7]).toJdbc()).getTime();
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(tmValue);
				power.setLogtime(cal.getTime());
				power.setUptime(cal.getTime());
				
				logger.debug("根据设备ID查询最新的电力监测值成功" + power);
				
				return power;
			}
			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<PgPower> findPowerByDevice(Integer deviceid) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, AU, BU, CU, AI, BI, CI, LOGTIME, PGDEVICEID FROM PG_POWER 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<PgPower> list = new ArrayList<PgPower>();
				for (int i = 0; i < tempList.size(); i++) {
					PgPower power = new PgPower();
					Object[] item = tempList.get(i);

					power.setId(((Number) item[0]).intValue());
					power.setAu(Float.parseFloat((String) item[1]));
					power.setBu(Float.parseFloat((String) item[2]));
					power.setCu(Float.parseFloat((String) item[3]));
					power.setAi(Float.parseFloat((String) item[4]));
					power.setBi(Float.parseFloat((String) item[5]));
					power.setCi(Float.parseFloat((String) item[6]));
					power.setPgdeviceid(((Number) item[8]).intValue());

					long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[7]).toJdbc()).getTime();
					Calendar cal = Calendar.getInstance();
					cal.setTimeInMillis(tmValue);
					power.setLogtime(cal.getTime());
					power.setUptime(cal.getTime());
					
					list.add(power);
				}
				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<PgPower> finPowerByDeviceAndTm(Integer deviceid, String start, String end) {
		Connection conn = null;
		
		String queryStr = "SELECT ID, AU, BU, CU, AI, BI, CI, LOGTIME, PGDEVICEID FROM PG_POWER 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<PgPower> list = new ArrayList<PgPower>();
				for (int i = 0; i < tempList.size(); i++) {
					PgPower power = new PgPower();
					Object[] item = tempList.get(i);

					power.setId(((Number) item[0]).intValue());
					power.setAu(Float.parseFloat((String) item[1]));
					power.setBu(Float.parseFloat((String) item[2]));
					power.setCu(Float.parseFloat((String) item[3]));
					power.setAi(Float.parseFloat((String) item[4]));
					power.setBi(Float.parseFloat((String) item[5]));
					power.setCi(Float.parseFloat((String) item[6]));
					power.setPgdeviceid(((Number) item[8]).intValue());

					long tmValue = ((java.sql.Timestamp) ((oracle.sql.TIMESTAMP) item[7]).toJdbc()).getTime();
					Calendar cal = Calendar.getInstance();
					cal.setTimeInMillis(tmValue);
					power.setLogtime(cal.getTime());
					power.setUptime(cal.getTime());
					
					list.add(power);
				}
				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 int addPowerRecord(PgPower power) {
		return addPowerRecord(power.getAu(), power.getBu(), power.getCu(), power.getAi(), power.getBi(), power.getCi(), power.getTmStr(), power.getPgdeviceid());
	}

	@Override
	public int addPowerRecord(float au, float bu, float cu, float ai, float bi, float ci, String tm, int deviceid) {
		Connection conn = null;
		
		String insertStr = "INSERT INTO PG_POWER " +
						   "(AU, BU, CU, AI, BI, CI, LOGTIME, UPTIME, PGDEVICEID) " +
						   "VALUES (?, ?, ?, ?, ?, ?, TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS'), ?)";
		Object[] params = new Object[9];
		params[0] = NumberFormat.format(au, "0.00");
		params[1] = NumberFormat.format(bu, "0.00");
		params[2] = NumberFormat.format(cu, "0.00");
		params[3] = NumberFormat.format(ai, "0.00");
		params[4] = NumberFormat.format(bi, "0.00");
		params[5] = NumberFormat.format(ci, "0.00");
		params[6] = tm;
		params[7] = tm;
		params[8] = 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 + ", temp=" + au + ", ai=" + ai + ", 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;
	}

}
