package com.rjconsultores.ventaboletos.relatorios.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.rjconsultores.ventaboletos.relatorios.utilitarios.ArrayDataSource;
import com.rjconsultores.ventaboletos.relatorios.utilitarios.Relatorio;
import com.rjconsultores.ventaboletos.utilerias.DateUtil;
import com.rjconsultores.ventaboletos.web.utilerias.NamedParameterStatement;

public class RelatorioReceitaServico extends Relatorio {

	public RelatorioReceitaServico(Map<String, Object> parametros, Connection conexao) throws Exception	{
		super(parametros, conexao);

		this.setCustomDataSource(new ArrayDataSource(this) {

			public void initDados() throws Exception {
				Connection conexao = this.relatorio.getConexao();
				Map<String, Object> parametros = this.relatorio.getParametros();

				String sql = getSql(
						(parametros.get("ORIGEN_ID") != null && parametros.get("ORIGEN_ID") != ""),
						(parametros.get("DESTINO_ID") != null && parametros.get("DESTINO_ID") != ""),
						(parametros.get("CORRIDA_ID") != null && parametros.get("CORRIDA_ID") != ""),
						(parametros.get("CLASESERVICIO_ID") != null && parametros.get("CLASESERVICIO_ID") != ""));

				NamedParameterStatement stmt = new NamedParameterStatement(conexao, sql);

				stmt.setTimestamp("DATA_INICIAL", new Timestamp(DateUtil.inicioFecha((Date) parametros.get("DATA_INICIAL")).getTime()));
				stmt.setTimestamp("DATA_FINAL", new Timestamp(DateUtil.fimFecha((Date) parametros.get("DATA_FINAL")).getTime()));

				if (parametros.get("CORRIDA_ID") != null)
					stmt.setString("CORRIDA_ID", (String) parametros.get("CORRIDA_ID"));

				if (parametros.get("ORIGEN_ID") != null)
					stmt.setInt("ORIGEN_ID", (Integer) parametros.get("ORIGEN_ID"));

				if (parametros.get("DESTINO_ID") != null)
					stmt.setInt("DESTINO_ID", (Integer) parametros.get("DESTINO_ID"));

				if (parametros.get("EMPRESA_ID") != null)
					stmt.setInt("EMPRESA_ID", (Integer) parametros.get("EMPRESA_ID"));
				else
					stmt.setNull("EMPRESA_ID", java.sql.Types.INTEGER);

				if (parametros.get("CLASESERVICIO_ID") != null && (!parametros.get("CLASESERVICIO_ID").equals("")))
					stmt.setInt("CLASESERVICIO_ID", (Integer) parametros.get("CLASESERVICIO_ID"));

				ResultSet rset = stmt.executeQuery();

				while (rset.next()) {

					Map<String, Object> dataResult = new HashMap<String, Object>();

					dataResult.put("data", rset.getDate("data"));
					dataResult.put("servico", rset.getString("servico"));
					dataResult.put("empresa", rset.getString("empresa"));
					dataResult.put("origem", rset.getString("origem"));
					dataResult.put("destino", rset.getString("destino"));
					dataResult.put("classe", rset.getString("classe"));
					dataResult.put("preciobase", rset.getBigDecimal("preciobase"));
					dataResult.put("tarifa", rset.getBigDecimal("tarifa"));
					dataResult.put("tut", rset.getBigDecimal("tut"));
					dataResult.put("pedagio", rset.getBigDecimal("pedagio"));
					dataResult.put("total", rset.getBigDecimal("total"));
					dataResult.put("tipo", rset.getString("tipo"));
					dataResult.put("agencia", rset.getString("agencia"));
					dataResult.put("telefone", rset.getString("telefone"));
					dataResult.put("dataHoraCompra", rset.getTimestamp("dataHoraCompra"));
					dataResult.put("passageiro", !(rset.getString("passageiro") == null) ? rset.getString("passageiro") : "");
					dataResult.put("nrBilhete", !(rset.getString("nrBilhete") == null) ? rset.getString("nrBilhete") : "");
					dataResult.put("tipoServico", !(rset.getString("tipoServico") == null) ? rset.getString("tipoServico") : "");
					dataResult.put("prefixo", !(rset.getString("prefixo") == null) ? rset.getString("prefixo") : "");
					
					this.dados.add(dataResult);
				}

				this.resultSet = rset;
			}
		});
	}

	@Override
	protected void processaParametros() throws Exception {
	}

	private String getSql(boolean origemSelected, boolean destinoSelected, boolean servicoSelected, boolean claseServicioSelected) {
		StringBuilder sql = new StringBuilder();

		sql.append("SELECT b.feccorrida   AS data, ");
		sql.append("b.corrida_id 		  AS servico, ");
		sql.append("mar.descmarca 		  AS empresa, ");
		sql.append("origem.cveparada      AS Origem, ");
		sql.append("destino.cveparada 	  AS Destino, ");
		sql.append("cl_ser.descclase      AS Classe, ");
		sql.append("COALESCE(b.preciobase,0) AS preciobase, ");
		sql.append("COALESCE(b.preciopagado,0) 	      AS tarifa, ");
		sql.append("COALESCE(b.importetaxaembarque,0) AS tut, ");
		sql.append("COALESCE(b.importepedagio,0) 	  AS pedagio, ");
		sql.append("(COALESCE(b.preciopagado,0) + COALESCE(b.importetaxaembarque,0) + COALESCE(b.importepedagio,0) ) AS total, ");
		sql.append("cat.desccategoria 	  AS tipo, ");
		sql.append("p.nombpuntoventa 	  AS agencia, ");
		sql.append("b.fechorventa 		  AS dataHoraCompra, ");
		sql.append("b.nombpasajero 		  AS passageiro, ");
		sql.append("b.desctelefono 		  AS telefone, ");
		sql.append("b.NUMFOLIOSISTEMA 	  AS nrBilhete, ");
		
		sql.append("       CASE ");
		sql.append("           WHEN c.tiposervicio_id = 1 THEN 'O' ");
		sql.append("           WHEN c.tiposervicio_id = 2 THEN 'E' ");
		sql.append("           ELSE ''                        ");
		sql.append("       END AS tipoServico,");
		sql.append("       r.prefixo ");                           
		
		sql.append("FROM BOLETO b ");
		
		sql.append(" left join corrida c on (b.corrida_id = c.corrida_id and b.feccorrida = c.feccorrida)");
		sql.append(" left join ruta r on (b.ruta_id = r.ruta_id and r.activo = 1) ");
		
		sql.append("INNER JOIN marca   	 	      mar ON b.marca_id              = mar.marca_id ");
		sql.append("INNER JOIN clase_servicio  cl_ser ON cl_ser.claseservicio_id = b.claseservicio_id ");
		sql.append("LEFT JOIN PARADA 		  levante ON levante.parada_id       = b.levante_id ");
		sql.append("LEFT OUTER JOIN PUNTO_VENTA 	p ON b.puntoventa_id         = p.puntoventa_id ");
		sql.append("LEFT OUTER JOIN PARADA 	   parada ON p.PARADA_ID             = parada.PARADA_ID, ");
		sql.append("PARADA origem, ");
		sql.append("PARADA destino, ");
		sql.append("CATEGORIA cat ");
		sql.append("WHERE b.activo = 1 ");
		sql.append("AND b.feccorrida BETWEEN :DATA_INICIAL AND :DATA_FINAL ");
		sql.append("AND b.origen_id = origem.parada_id ");
		sql.append("AND b.destino_id = destino.parada_id ");
		
		if (origemSelected) {
			sql.append("AND b.origen_id = (:ORIGEN_ID) ");
		}
		if (destinoSelected) {
			sql.append("AND b.destino_id = (:DESTINO_ID) ");
		}
		if (servicoSelected) {
			sql.append("AND b.corrida_id= :CORRIDA_ID ");
		}
		if (claseServicioSelected) {
			sql.append(" AND cl_ser.CLASESERVICIO_ID  =  :CLASESERVICIO_ID ");
		}
		sql.append("AND b.categoria_id=cat.categoria_id ");
		sql.append("AND b.motivocancelacion_id IS NULL ");
		sql.append("AND mar.EMPRESA_ID =  :EMPRESA_ID ");

		return sql.toString();
	}

}
