package com.rjconsultores.ventaboletos.relatorios.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.rjconsultores.ventaboletos.entidad.Marca;
import com.rjconsultores.ventaboletos.relatorios.utilitarios.ArrayDataSource;
import com.rjconsultores.ventaboletos.relatorios.utilitarios.Relatorio;
import com.rjconsultores.ventaboletos.service.SegVKMService;
import com.rjconsultores.ventaboletos.web.utilerias.NamedParameterStatement;

public class RelatorioTabelaPreco extends Relatorio {
	private static final String ORGAO_CONCEDENTE = "ORGAO_CONCEDENTE_ID";
	private boolean isLayoutArtesp;
	private SegVKMService segVKM;

	public RelatorioTabelaPreco(final Map<String, Object> parametros, Connection conexao, SegVKMService segVKMService) throws Exception {
		super(parametros, conexao);

		this.segVKM = segVKMService;
		this.isLayoutArtesp = (Boolean) parametros.get("isLayoutArtesp");

		this.setCustomDataSource(new ArrayDataSource(this) {

			@Override
			public void initDados() throws Exception {
				Connection conexao = this.relatorio.getConexao();
				NamedParameterStatement stmt = new NamedParameterStatement(conexao, getSql());
				ResultSet rset = stmt.executeQuery();
				
				setReportImages();
				
				String series = segVKM.seriePorEmpresa((Integer) parametros.get("EMPRESA_ID"));
				while (rset.next()) {
					Map<String, Object> dataResult = new HashMap<String, Object>();

					if (isLayoutArtesp) {
						dataResult.put("seguroOpcional",
								segVKM.buscarSeguroPorKm(rset.getLong("kmReal"),
										series, (Integer) parametros.get(ORGAO_CONCEDENTE)));
					}

					dataResult.put("cveorigem", rset.getString("cveorigem"));
					dataResult.put("cvedestino", rset.getString("cvedestino"));
					dataResult.put("origem", rset.getString("origem"));
					dataResult.put("destino", rset.getString("destino"));
					dataResult.put("aliasorigem", rset.getString("aliasorigem"));
					dataResult.put("aliasdestino", rset.getString("aliasdestino"));
					dataResult.put("origemid", rset.getString("origemid"));
					dataResult.put("destinoid", rset.getString("destinoid"));
					dataResult.put("tarifa", rset.getBigDecimal("tarifa"));
					dataResult.put("tarifaoriginal", rset.getBigDecimal("tarifaoriginal"));
					dataResult.put("pedagio", rset.getBigDecimal("pedagio"));
					dataResult.put("taxaEmbarque", rset.getBigDecimal("taxaEmbarque"));
					dataResult.put("outros", rset.getBigDecimal("outros"));
					dataResult.put("tipoClasse", rset.getString("tipoClasse"));
					dataResult.put("empresa", rset.getString("empresa"));
					
					dataResult.put("seguro", rset.getBigDecimal("seguro"));
					dataResult.put("linha", rset.getString("linha"));
					dataResult.put("prefixo", rset.getString("prefixo"));
					dataResult.put("dataVigenciaInicial", rset.getDate("dataVigenciaInicial"));
					dataResult.put("dataVigenciaFinal", rset.getDate("dataVigenciaFinal"));
					dataResult.put("idLinha", rset.getInt("idLinha"));
					dataResult.put("idVigencia", rset.getInt("idVigencia"));
					dataResult.put("kmreal", rset.getString("kmReal"));
					dataResult.put("orgao", rset.getString("orgao"));
					
					this.dados.add(dataResult);
				}

				this.resultSet = rset;
			}
		});
	}

	protected void setReportImages() throws IOException {
		BufferedImage empresaLogo = null;
		Marca marca = (Marca) parametros.get("MARCA");
		if (marca != null && marca.getLogotipomarca() != null) {
			empresaLogo = ImageIO.read(new ByteArrayInputStream(marca.getLogotipomarca()));
		}
		BufferedImage artespLogo = ImageIO.read(getClass().getResource(getBaseDir() + "/imagens/artesp.png"));

		parametros.put("artesp_logo", artespLogo);
		parametros.put("empresa_logo", empresaLogo);
		
	}

	@Override
	protected void processaParametros() throws Exception {
	}

	private String getSql() {
		StringBuilder sql = new StringBuilder();

		if (isLayoutArtesp) {
			sql.append("SELECT dados.* FROM (");
		}
		
		sql.append(" SELECT DISTINCT ");
		sql.append("       po.cveparada                        as cveorigem, ");
		sql.append("       pd.cveparada                        as cvedestino, ");
	    sql.append("       po.DESCPARADA                       as origem, ");
		sql.append("       pd.DESCPARADA                       as destino, ");
		sql.append("       pos.DESCPARADA                      as aliasorigem, ");
		sql.append("       pds.DESCPARADA                      as aliasdestino, ");
		sql.append("       po.parada_id                        as origemid, ");
		sql.append("       pd.parada_id                        as destinoid, ");
		sql.append("       COALESCE(t.precio,0)                as tarifa, ");
		sql.append("       coalesce(t.preciooriginal, 0)       AS tarifaoriginal, ");
		sql.append("       COALESCE(t.IMPORTEPEDAGIO, 0)       as pedagio, ");
		sql.append("       COALESCE(t.IMPORTETAXAEMBARQUE, 0)  as taxaEmbarque, ");
		sql.append("       COALESCE(t.IMPORTESEGURO, 0)        as seguro, ");
		sql.append("       COALESCE(t.IMPORTEOUTROS, 0)        as outros, ");
		sql.append("       cs.DESCCLASE                        as tipoClasse, ");
		sql.append("       r.DESCRUTA                          as linha, ");
		sql.append("       r.prefixo                           as prefixo, ");
		sql.append("       e.NOMBEMPRESA                       as empresa, ");
		sql.append("       vt.FECINICIOVIGENCIA                as dataVigenciaInicial, ");
		sql.append("       vt.FECFINVIGENCIA                   as dataVigenciaFinal, ");
		sql.append("       vt.VIGENCIATARIFA_ID                as idVigencia, ");
		sql.append("       r.RUTA_ID                           as idLinha, ");
		sql.append("       tr.CANTKMREAL                       as kmReal, ");
		sql.append("       o.descorgao                         as orgao ");
		sql.append(" FROM TARIFA t ");
		sql.append(" INNER JOIN PARADA           po ON t.ORIGEN_ID           = po.PARADA_ID ");
		sql.append(" INNER JOIN PARADA           pd ON t.DESTINO_ID          = pd.PARADA_ID ");
		sql.append(" INNER JOIN CLASE_SERVICIO   cs ON cs.CLASESERVICIO_ID   = t.CLASESERVICIO_ID ");
		sql.append(" INNER JOIN RUTA             r ON r.RUTA_ID              = t.RUTA_ID ");
		sql.append(" INNER JOIN MARCA            m ON m.MARCA_ID             = t.MARCA_ID ");
		sql.append(" INNER JOIN EMPRESA          e ON e.EMPRESA_ID           = m.EMPRESA_ID ");
		sql.append(" INNER JOIN VIGENCIA_TARIFA  vt ON vt.VIGENCIATARIFA_ID  = t.VIGENCIATARIFA_ID ");
		sql.append(" INNER JOIN RUTA_COMBINACION rc ON rc.RUTA_ID            = r.RUTA_ID ");
		sql.append(" INNER JOIN TRAMO            tr ON tr.TRAMO_ID           = rc.TRAMO_ID ");
		sql.append(" INNER JOIN ORGAO_CONCEDENTE o ON o.ORGAOCONCEDENTE_ID   = r.ORGAOCONCEDENTE_ID ");
		
		sql.append(" LEFT JOIN alias_servico     s ON s.ORIGEN_ID = t.ORIGEN_ID ");
		sql.append("                               AND s.DESTINO_ID = t.DESTINO_ID ");
		sql.append("                               AND s.RUTA_ID = r.RUTA_ID ");
		sql.append("                               AND s.activo = 1 ");
		sql.append(" LEFT JOIN parada           pos ON POS.PARADA_ID = S.ALIASORIGEN_ID "); 
		sql.append(" LEFT JOIN parada           pds ON PDS.PARADA_ID = S.ALIASDESTINO_ID  ");
		
		sql.append("WHERE rc.INDVENTA = 1 ");
		sql.append("AND rc.ACTIVO = 1 ");
		sql.append("AND tr.ACTIVO = 1 ");
		
		if (isLayoutArtesp) {
			sql.append(" AND rc.indexibetabela = 1 ");
		}
		
		sql.append(" AND tr.ORIGEN_ID = t.ORIGEN_ID ");
		sql.append(" AND tr.DESTINO_ID = t.DESTINO_ID ");
		sql.append(" AND vt.VIGENCIATARIFA_ID = " + parametros.get("VIGENCIA_ID"));
		sql.append(" AND e.empresa_id = " + parametros.get("EMPRESA_ID"));

		String linhas = (String) parametros.get("LINHAS_ID");
		if (linhas != null && !linhas.isEmpty()) {
			sql.append(" AND r.RUTA_ID IN (" + linhas + ")");
		}

		if (parametros.get(ORGAO_CONCEDENTE) != null) {
			sql.append(" AND  r.ORGAOCONCEDENTE_ID = " + parametros.get(ORGAO_CONCEDENTE));
		}

		if (parametros.get("origemId") != null) {
			sql.append(" AND tr.ORIGEN_ID= " + parametros.get("origemId"));
		}

		if (parametros.get("destinoId") != null) {
			sql.append(" AND tr.DESTINO_ID= " + parametros.get("destinoId"));
		}

		sql.append(" ORDER BY r.DESCRUTA, vt.FECINICIOVIGENCIA");

		if (isLayoutArtesp) {
			sql.append(") dados ORDER BY origem,destino");
		}

		return sql.toString();
	}

	@Override
	public String getNome() {
		if (isLayoutArtesp) {
			return "RelatorioTabelaPrecoArtesp";
		}
		return this.getClass().getSimpleName();
	}
}
