package com.ejie.p06b.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.ejie.p06b.datatype.logic.P06BInformeDEC;
import com.ejie.p06b.datatype.logic.P06BInformeOtroDEC;
import com.ejie.p06b.datatype.model.P06B48T00Datatype;
import com.ejie.p06b.general.P06BConstantes;
import com.ejie.p06b.general.P06BTablas;
import com.ejie.p06b.log.P06BLog;
import com.ejie.p06b.util.bd.P06BServidorConexionesBD;

/**
 * Fecha de creación: (26/01/2012)
 */
public class P06B48T00DAO {
	
	static private P06B48T00DAO instance = null;

	public static P06B48T00DAO getInstance() {
	     if (instance == null) {
	          synchronized (P06B48T00DAO.class) {
	          		if (instance == null) {
	                     instance = new P06B48T00DAO();
	                }
	          }
	     }
	     return instance;
	}
	
	
	/**
    * Obtiene un registro de la BD a partir de la clave primaria
    * @param numExp.
    *            parte de la clave primaria
    * @param ejer.
    *            parte de la clave primaria
    * @return un objeto P06B48T00Datatype o null si no se encuentra nada.
	* @throws Exception
    */
	public P06B48T00Datatype select(String ejer, String numExp) throws Exception{
		P06BLog.send(2,this, "Inicio P06B48T00DAO-select");
		P06B48T00Datatype result = null;
		PreparedStatement lstm  = null;
        ResultSet lrst  = null;
        String sql = SELECT_BY_PK;
        Connection lconConexion = P06BServidorConexionesBD.getConexionConsultas();
        try {
        	lstm = lconConexion.prepareStatement(sql);
        	lstm.setString(1,ejer.toUpperCase());
        	lstm.setString(2,numExp.toUpperCase());
        	lrst = lstm.executeQuery();
	        if (lrst.next()) {
	        	result = new P06B48T00Datatype();
	        	
	        	result.setEjercicio(lrst.getString(P06BTablas.P06B_P06B48_EJERCICIO));
	        	result.setNumExp(lrst.getString(P06BTablas.P06B_P06B48_NUMEXP));
	        	
			    result.setValorAnadComis(lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_COMIS)==null?"":lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_COMIS));
			    result.setValorAnadSubv(lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_SUBV)==null?"":lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_SUBV));
			    result.setValorAnadOtrosIng(lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_OTROSING)==null?"":lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_OTROSING));
			    result.setValorAnadCompras(lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_COMPRAS)==null?"":lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_COMPRAS));
			    result.setValorAnadServExt(lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_SERVEXT)==null?"":lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_SERVEXT));
			    result.setValorAnadOtrosTrib(lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_OTROSTRIB)==null?"":lrst.getString(P06BTablas.P06B_P06B48_VALORANAD_OTROSTRIB));
			    result.setInverBruta(lrst.getString(P06BTablas.P06B_P06B48_INVERBRUTA)==null?"":lrst.getString(P06BTablas.P06B_P06B48_INVERBRUTA));
	        }
	        P06BLog.send(2,this, "Fin P06B48T00DAO-select");
	    } catch (SQLException e) {
	    	P06BLog.send(2,this, "error: " +e.getMessage());
        	try {
        		if(lrst!=null)
        			lrst.close();
        	}catch (Exception rse) {}
	        try {
	        	if(lstm!=null)
	        		lstm.close();
	        }catch (Exception sse) {}
	        try {
	        	if(lconConexion!=null)
	        		lconConexion.close();
	        }catch (Exception cse) {}
	        //Propago la excepción
	        throw e;
	    }catch (Exception e2) {	 
        	P06BLog.send(2,this, "error: " +e2.getMessage());
        	try {
        		if(lrst!=null)
        			lrst.close();
        	}catch (Exception rse) {}
	        try {
	        	if(lstm!=null)
	        		lstm.close();
	        }catch (Exception sse) {}
	        try {
	        	if(lconConexion!=null)
	        		lconConexion.close();
	        }catch (Exception cse) {}
	        //Propago la excepción
	        throw e2;
	    }finally {
	    	try {
        		if(lrst!=null)
        			lrst.close();
        	}catch (Exception rse) {}
	        try {
	        	if(lstm!=null)
	        		lstm.close();
	        }catch (Exception sse) {}
	        try {
	        	if(lconConexion!=null)
	        		lconConexion.close();
	        }catch (Exception cse) {}
	    }
		return result;
	}

	
	/**
    * Obtiene los datos para el informe resumen de la DEC asociados al ejercicio indicado
    * @param ejerDEC.
    *            ejercicio de la DEC
    * @param objInformeDEC.
    *            objeto donde actualizar los datos obtenidos en la select
	* @throws Exception
    */
	public void selectInvBrutaValAnadInformeDEC(String ejerDEC, P06BInformeDEC objInformeDEC, String tipoMed) throws Exception{
		P06BLog.send(2,this, "Inicio P06B48T00DAO-selectInvBrutaValAnadInformeDEC");
		PreparedStatement lstm  = null;
        ResultSet lrst  = null;
        String sql = SELECT_INVBRUTAVALANAD_INFORMEDEC;
        
        //Dependiendo del tipo hacer una select u otra. Corredores: F, J, RF, RJ. Vinculados: AF, AJ. Operadores banca: OV.
        if(P06BConstantes.P06B_CORR.equals(tipoMed)){
        	sql += " AND " + " (" + P06BTablas.P06B_P06B48_NUMEXP + " like '"+P06BConstantes.P06B_CORREDORES_TIPOPER_JURIDICA+"-%' or " + P06BTablas.P06B_P06B48_NUMEXP + " like '"+P06BConstantes.P06B_CORREDORES_TIPOPER_FISICA+"-%' or " + P06BTablas.P06B_P06B48_NUMEXP + " like '"+P06BConstantes.P06B_REASEGUROS_JURIDICA+"-%' or " + P06BTablas.P06B_P06B48_NUMEXP + " like '"+P06BConstantes.P06B_REASEGUROS_FISICA+"-%')";
    	}else if(P06BConstantes.P06B_VINC.equals(tipoMed)){
    		sql += " AND " + " (" + P06BTablas.P06B_P06B48_NUMEXP + " like '"+P06BConstantes.P06B_AGENTEVINCULADO_FISICA+"-%' or " + P06BTablas.P06B_P06B48_NUMEXP + " like '"+P06BConstantes.P06B_AGENTEVINCULADO_JURIDICA+"-%')";
    	}else if(P06BConstantes.P06B_OBS.equals(tipoMed)){
    		sql += " AND " + " (" + P06BTablas.P06B_P06B48_NUMEXP + " like '"+P06BConstantes.P06B_OPERADORBANCA_VINCULADO+"-%' or " + P06BTablas.P06B_P06B48_NUMEXP + " like '"+P06BConstantes.P06B_OPERADORBANCA_EXCLUSIVO+"-%')";
    	}
        
        Connection lconConexion = P06BServidorConexionesBD.getConexionConsultas();
        try {
        	lstm = lconConexion.prepareStatement(sql);
        	lstm.setString(1,ejerDEC.toUpperCase());
        	lrst = lstm.executeQuery();
        	
	        if (lrst.next()) {
	        	if(P06BConstantes.P06B_CORR.equals(tipoMed)){
	        		objInformeDEC.setValAnadCorrM3(lrst.getDouble("VALOR_ANAD"));
		        	objInformeDEC.setInvBrutaCorrM3(lrst.getDouble("INVERSION_BRUTA"));
	        	}else if(P06BConstantes.P06B_VINC.equals(tipoMed)){
	        		objInformeDEC.setValAnadVincM3(lrst.getDouble("VALOR_ANAD"));
		        	objInformeDEC.setInvBrutaVincM3(lrst.getDouble("INVERSION_BRUTA"));
	        	}else if(P06BConstantes.P06B_OBS.equals(tipoMed)){
	        		objInformeDEC.setValAnadObsM3(lrst.getDouble("VALOR_ANAD"));
		        	objInformeDEC.setInvBrutaObsM3(lrst.getDouble("INVERSION_BRUTA"));
	        	}
	        }
	        P06BLog.send(2,this, "Fin P06B48T00DAO-selectInvBrutaValAnadInformeDEC");
	    } catch (SQLException e) {
	    	P06BLog.send(2,this, "error: " +e.getMessage());
        	try {
        		if(lrst!=null)
        			lrst.close();
        	}catch (Exception rse) {}
	        try {
	        	if(lstm!=null)
	        		lstm.close();
	        }catch (Exception sse) {}
	        try {
	        	if(lconConexion!=null)
	        		lconConexion.close();
	        }catch (Exception cse) {}
	        //Propago la excepción
	        throw e;
	    }catch (Exception e2) {	 
        	P06BLog.send(2,this, "error: " +e2.getMessage());
        	try {
        		if(lrst!=null)
        			lrst.close();
        	}catch (Exception rse) {}
	        try {
	        	if(lstm!=null)
	        		lstm.close();
	        }catch (Exception sse) {}
	        try {
	        	if(lconConexion!=null)
	        		lconConexion.close();
	        }catch (Exception cse) {}
	        //Propago la excepción
	        throw e2;
	    }finally {
	    	try {
        		if(lrst!=null)
        			lrst.close();
        	}catch (Exception rse) {}
	        try {
	        	if(lstm!=null)
	        		lstm.close();
	        }catch (Exception sse) {}
	        try {
	        	if(lconConexion!=null)
	        		lconConexion.close();
	        }catch (Exception cse) {}
	    }
	}
	
	/**
	    * Obtiene los datos para el informe resumen de la DEC asociados al ejercicio indicado
	    * @param ejerDEC.
	    *            ejercicio de la DEC
	    * @param objInformeOtroDEC.
	    *            objeto donde actualizar los datos obtenidos en la select
		* @throws Exception
	    */
		public void selectDatosInformeOtroDEC(String ejerDEC, P06BInformeOtroDEC objInformeOtroDEC) throws Exception{
			P06BLog.send(2,this, "Inicio P06B48T00DAO-selectDatosInformeOtroDEC");
			PreparedStatement lstm  = null;
	        ResultSet lrst  = null;
	        String sql = SELECT_DATOS_INFORMEOTRODEC;
	        String sTipoMediador;
	    	ArrayList<String> al_MediadorCodigo = new ArrayList<String>(); 
	    	ArrayList<Double> al_MediadorComision = new ArrayList<Double>();
	    	
	        
	        Connection lconConexion = P06BServidorConexionesBD.getConexionConsultas();
	        try {
	        	lstm = lconConexion.prepareStatement(sql);
	        	lstm.setString(1,ejerDEC.toUpperCase());
	        	lrst = lstm.executeQuery();
	        	
		        while (lrst.next()) {

		        	al_MediadorCodigo.add(lrst.getString("TC"));
		        	al_MediadorComision.add(lrst.getDouble("D1"));
		        }
		        objInformeOtroDEC.setAl_MediadorCodigo(al_MediadorCodigo);
		        objInformeOtroDEC.setAl_MediadorComision(al_MediadorComision);
		        P06BLog.send(2,this, "Fin P06B48T00DAO-selectDatosInformeOtroDEC");
		    } catch (SQLException e) {
		    	P06BLog.send(2,this, "error: " +e.getMessage());
	        	try {
	        		if(lrst!=null)
	        			lrst.close();
	        	}catch (Exception rse) {}
		        try {
		        	if(lstm!=null)
		        		lstm.close();
		        }catch (Exception sse) {}
		        try {
		        	if(lconConexion!=null)
		        		lconConexion.close();
		        }catch (Exception cse) {}
		        //Propago la excepción
		        throw e;
		    }catch (Exception e2) {	 
	        	P06BLog.send(2,this, "error: " +e2.getMessage());
	        	try {
	        		if(lrst!=null)
	        			lrst.close();
	        	}catch (Exception rse) {}
		        try {
		        	if(lstm!=null)
		        		lstm.close();
		        }catch (Exception sse) {}
		        try {
		        	if(lconConexion!=null)
		        		lconConexion.close();
		        }catch (Exception cse) {}
		        //Propago la excepción
		        throw e2;
		    }finally {
		    	try {
	        		if(lrst!=null)
	        			lrst.close();
	        	}catch (Exception rse) {}
		        try {
		        	if(lstm!=null)
		        		lstm.close();
		        }catch (Exception sse) {}
		        try {
		        	if(lconConexion!=null)
		        		lconConexion.close();
		        }catch (Exception cse) {}
		    }
		}
			
		
	private static String SELECT_BY_PK =
		"SELECT " +	
		P06BTablas.P06B_P06B48_EJERCICIO + ", " + 
		P06BTablas.P06B_P06B48_NUMEXP + ", " + 
		P06BTablas.P06B_P06B48_VALORANAD_COMIS + ", " + 
		P06BTablas.P06B_P06B48_VALORANAD_SUBV + ", " + 
		P06BTablas.P06B_P06B48_VALORANAD_OTROSING + ", " + 
		P06BTablas.P06B_P06B48_VALORANAD_COMPRAS + ", " + 
		P06BTablas.P06B_P06B48_VALORANAD_SERVEXT + ", " + 
		P06BTablas.P06B_P06B48_VALORANAD_OTROSTRIB + ", " + 
		P06BTablas.P06B_P06B48_INVERBRUTA +
				
		" FROM "+ P06BTablas.P06B_P06B48T00_TABLA +
		" WHERE " + P06BTablas.P06B_P06B48_EJERCICIO + " = ? and " + P06BTablas.P06B_P06B48_NUMEXP + " = ?";

	private static String SELECT_INVBRUTAVALANAD_INFORMEDEC =
		"SELECT (sum(nvl("+P06BTablas.P06B_P06B48_VALORANAD_COMIS+",0)) + sum(nvl("+P06BTablas.P06B_P06B48_VALORANAD_SUBV+",0)) + sum(nvl("+P06BTablas.P06B_P06B48_VALORANAD_OTROSING+",0)) - sum(nvl("+P06BTablas.P06B_P06B48_VALORANAD_COMPRAS+",0)) - sum(nvl("+P06BTablas.P06B_P06B48_VALORANAD_SERVEXT+",0)) - sum(nvl("+P06BTablas.P06B_P06B48_VALORANAD_OTROSTRIB+",0))) as VALOR_ANAD,"+
		" sum(nvl("+P06BTablas.P06B_P06B48_INVERBRUTA+",0)) as INVERSION_BRUTA"+
		" FROM "+ P06BTablas.P06B_P06B48T00_TABLA +
		" WHERE " + P06BTablas.P06B_P06B48_EJERCICIO + " = ?";
	
    private static String SELECT_DATOS_INFORMEOTRODEC =
		"SELECT SUBSTR(" + P06BTablas.P06B_P06B48_NUMEXP + ", 0, INSTR(" + P06BTablas.P06B_P06B48_NUMEXP + ", '-')-1) as TC, SUM(NVL(" +
		P06BTablas.P06B_P06B48_VALORANAD_COMIS + ",0)) as D1 FROM " +
		P06BTablas.P06B_P06B48T00_TABLA + " WHERE " + P06BTablas.P06B_P06B48_EJERCICIO + " = ? GROUP BY SUBSTR(" + P06BTablas.P06B_P06B48_NUMEXP + ", 0, INSTR(" + P06BTablas.P06B_P06B48_NUMEXP + ", '-')-1)" +
		" ORDER BY SUBSTR(" + P06BTablas.P06B_P06B48_NUMEXP + ", 0, INSTR(" + P06BTablas.P06B_P06B48_NUMEXP + ", '-')-1)";
	
//    private static String SELECT_DATOS_INFORMEOTRODEC =
//		"SELECT " + P06BTablas.P06B_P06B48_NUMEXP + " as TC, SUM(NVL(" +
//		P06BTablas.P06B_P06B48_VALORANAD_COMIS + ",0)) as D1 FROM " +
//		P06BTablas.P06B_P06B48T00_TABLA + 
//		" WHERE " + P06BTablas.P06B_P06B48_EJERCICIO + " = ?" + 
//		" GROUP BY " + P06BTablas.P06B_P06B48_NUMEXP + 
//		" ORDER BY " + P06BTablas.P06B_P06B48_NUMEXP;
	
}
