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"));
				// else
				// stmt.setNull("CLASESERVICIO_ID", java.sql.Types.INTEGER);

				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("dataHoraCompra", rset.getTimestamp("dataHoraCompra"));
					dataResult.put("passageiro", !(rset.getString("passageiro") == null) ? rset.getString("passageiro") : "");
					dataResult.put("nrBilhete", !(rset.getString("nrBilhete") == null) ? rset.getString("nrBilhete") : "");

					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 cj.feccorrida as data, ");
		sql.append(" cj.corrida_id as servico,   ");
		sql.append(" mar.descmarca as empresa ,  ");
		sql.append(" pOrig.cveparada as Origem,  ");
		sql.append(" pDest.cveparada as Destino,  ");
		sql.append(" cl_ser.descclase as Classe, ");
		sql.append("  cj.preciobase as preciobase, ");
		sql.append("  cj.preciopagado as tarifa, ");
		sql.append("  cj.importetaxaembarque as tut, ");
		sql.append("  cj.importepedagio as pedagio, ");
		sql.append("  (cj.preciopagado + cj.importetaxaembarque + cj.importepedagio ) as total, ");
		sql.append("  cat.desccategoria as tipo, ");
		sql.append("  pv.nombpuntoventa as agencia, ");
		sql.append("  cj.fechorventa as dataHoraCompra, ");
		sql.append("  cj.nombpasajero as passageiro,    ");
		sql.append("  cj.NUMFOLIOSISTEMA as nrBilhete  ");

		sql.append("  from caja cj  ");
		sql.append("  inner join marca mar on mar.marca_id = cj.marca_id  ");
		sql.append("  inner join parada pOrig on pOrig.parada_id = cj.origen_id  ");
		sql.append("  inner join parada pDest on pDest.parada_id = cj.destino_id  ");
		sql.append("  inner join clase_servicio cl_ser on cl_ser.claseservicio_id = cj.claseservicio_id  ");
		sql.append("  inner join categoria cat on cj.categoria_id = cat.categoria_id  ");
		sql.append("  inner join punto_venta pv on cj.puntoventa_id = pv.puntoventa_id  ");

		sql.append(" where cj.feccorrida >= :DATA_INICIAL ");
		sql.append(" and cj.feccorrida <= :DATA_FINAL ");

		if (servicoSelected) {
			sql.append(" and cj.corrida_id  IN (:CORRIDA_ID) ");
		}
		if (origemSelected) {
			sql.append(" and pOrig.PARADA_ID IN (:ORIGEN_ID) ");
		}
		if (destinoSelected) {
			sql.append(" and pDest.PARADA_ID IN (:DESTINO_ID) ");
		}

		sql.append(" and mar.EMPRESA_ID =  :EMPRESA_ID ");
		if (claseServicioSelected) {
			sql.append(" and cj.CLASESERVICIO_ID =  :CLASESERVICIO_ID ");
		}
		sql.append(" order by cj.feccorrida, cj.corrida_id ");

		return sql.toString();
	}

}
