package com.rjconsultores.ventaboletos.relatorios.impl;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.rjconsultores.ventaboletos.entidad.Empresa;
import com.rjconsultores.ventaboletos.entidad.Estado;
import com.rjconsultores.ventaboletos.entidad.TipoPuntoVenta;
import com.rjconsultores.ventaboletos.relatorios.utilitarios.DataSource;
import com.rjconsultores.ventaboletos.relatorios.utilitarios.Relatorio;
import com.rjconsultores.ventaboletos.utilerias.DateUtil;
import com.rjconsultores.ventaboletos.utilerias.exportacao.bpe.xml.BPeUtil;
import com.rjconsultores.ventaboletos.utilerias.fiscal.vo.FinanceiroSintetico;
import com.rjconsultores.ventaboletos.web.utilerias.NamedParameterStatement;

import br.inf.portalfiscal.bpe.TBPe;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class RelatorioFinanceiroSintetico extends Relatorio {

	private static Logger log = LogManager.getLogger(RelatorioFinanceiroSintetico.class);
	List<FinanceiroSintetico> listdata = null;

	@SuppressWarnings("unchecked")
	public RelatorioFinanceiroSintetico(final Map<String, Object> parametros, Connection conexao) throws Exception {
		super(parametros, conexao);

		this.setCustomDataSource(new DataSource(this) {
			@Override
			public void initDados() throws Exception {
				try {
					Date inicio = (Date) parametros.get("inicio");
					Date fim = (Date) parametros.get("fim");
					Empresa empresa = (Empresa) parametros.get("empresa");
					TipoPuntoVenta tipoPuntoVenta = (TipoPuntoVenta) parametros.get("tipoPuntoVenta");
					boolean isBpe = (Boolean) parametros.get("isBpe");

					List<Estado> estados = (List<Estado>) parametros.get("estados");
					String ufs = null;
					for (Estado estado : estados) {
						if (ufs == null)
							ufs = estado.getEstadoId().toString();
						else
							ufs = ufs + "," + estado.getEstadoId().toString();
					}

					String pdvs = (String) parametros.get("agencias");

					String sql = getSql(ufs, pdvs, tipoPuntoVenta == null ? -1 : tipoPuntoVenta.getTipoptovtaId().intValue(), isBpe);

					NamedParameterStatement stmt = new NamedParameterStatement(getConexao(), sql);
					stmt.setInt("EMPRESA_ID", empresa.getEmpresaId());
					stmt.setTimestamp("DATE_INICIO", new java.sql.Timestamp(DateUtil.inicioFecha(inicio).getTime()));
					stmt.setTimestamp("DATE_FIM", new java.sql.Timestamp(DateUtil.fimFecha(fim).getTime()));

					listdata = new ArrayList<FinanceiroSintetico>();
					ResultSet rset = stmt.executeQuery();
					while (rset.next()) {

						String xmlRec = null;
						String xmlDev = null;
						if (isBpe) {
							String xml_bpe_rec = rset.getNString("xml_bpe_rec");
							String xml_bpe_rec_2 = rset.getNString("xml_bpe_rec_2");
							String xml_bpe_rec_3 = rset.getNString("xml_bpe_rec_3");
							xmlRec = StringUtils.join(new String[] { xml_bpe_rec, xml_bpe_rec_2, xml_bpe_rec_3 });

							String xml_bpe_dev = rset.getNString("xml_bpe_dev");
							String xml_bpe_dev_2 = rset.getNString("xml_bpe_dev_2");
							String xml_bpe_dev_3 = rset.getNString("xml_bpe_dev_3");
							xmlDev = StringUtils.join(new String[] { xml_bpe_dev, xml_bpe_dev_2, xml_bpe_dev_3 });
						}

						BigDecimal valorContabilRec = BigDecimal.ZERO;
						BigDecimal valorContabilDev = BigDecimal.ZERO;
						if (isBpe) {
							
							TBPe tbpeRec = null;
							TBPe tbpeDev = null;
							if (StringUtils.isNotBlank(xmlRec))
								tbpeRec = BPeUtil.convertXmlToBpe(xmlRec);

							if (StringUtils.isNotBlank(xmlDev))
								tbpeDev = BPeUtil.convertXmlToBpe(xmlDev);

							if (StringUtils.isNotBlank(xmlRec)) {
								if (tbpeRec.getInfBPe().getInfValorBPe() != null) {
									String vPgto = tbpeRec.getInfBPe().getInfValorBPe().getVPgto();
									valorContabilRec = new BigDecimal(vPgto == null ? "0.0" : vPgto);
								}
							}

							if (StringUtils.isNotBlank(xmlDev)) {
								if (tbpeDev.getInfBPe().getInfValorBPe() != null) {
									String vPgto = tbpeDev.getInfBPe().getInfValorBPe().getVPgto();
									valorContabilDev = new BigDecimal(vPgto == null ? "0.0" : vPgto);
								}
							}
						}

						FinanceiroSintetico fs = new FinanceiroSintetico();
						fs.setUf(getString(rset, new String[] { "uf", "estadoOrigem_rec", "estadoOrigem_dev" }));
						fs.setCodigoAgencia(getString(rset, new String[] { "codigo", "codigo_rec", "codigo_dev" }));

						fs.setGapVenda(getBigDecimal(rset, "receita_gap"));
						fs.setGapImpressa(getBigDecimal(rset, "entrega_gap"));

						BigDecimal receita_rdi_bpr = valorContabilRec == null ? getBigDecimal(rset, "receita_rdi_bpr") : valorContabilRec;
						fs.setReceitaBPR(receita_rdi_bpr);

						BigDecimal totalVendaPassagens = fs.getReceitaBPR().add(fs.getGapVenda());
						totalVendaPassagens = totalVendaPassagens.subtract(fs.getGapImpressa());
						fs.setTotalVendaPassagens(totalVendaPassagens);

						fs.setReceitaEb(getBigDecimal(rset, "receita_eb"));
						fs.setMultaComp(getBigDecimal(rset, "receita_multa"));
						fs.setDifTrocaOCD(getBigDecimal(rset, "receita_dif_troca_ocd"));
						fs.setDifTarifaMaior(getBigDecimal(rset, "receita_dif_dif_tarifa_maior"));

						BigDecimal totalOutrasReceitas = fs.getReceitaEb().add(fs.getMultaComp()).add(fs.getDifTrocaOCD()).add(fs.getDifTarifaMaior());
						fs.setTotalOutrasReceitas(totalOutrasReceitas);

						BigDecimal taxaEmbarque = getBigDecimal(rset, "taxaEmbarque");
						taxaEmbarque = taxaEmbarque.add(getBigDecimal(rset, "taxaEmbarque_ee"));
						fs.setTxEmb(taxaEmbarque);

						fs.setPedagio(getBigDecimal(rset, "pedagio"));
						fs.setSegFacult(getBigDecimal(rset, "segurofac"));
						fs.setTxConveniencia(getBigDecimal(rset, "txconveniencia_ee"));

						BigDecimal totalTerceiros = fs.getTxEmb().add(fs.getPedagio()).add(fs.getSegFacult().add(fs.getTxConveniencia()));
						fs.setTotalTerceiros(totalTerceiros);

						BigDecimal receitaBruta = totalVendaPassagens.add(totalOutrasReceitas).add(totalTerceiros);
						fs.setReceitaBruta(receitaBruta);

						BigDecimal receita_cancel_rdi_bpr = valorContabilDev == null ? getBigDecimal(rset, "receita_cancel_rdi_bpr") : valorContabilDev;
						fs.setDevolBPR(receita_cancel_rdi_bpr);

						fs.setDevolGAP(getBigDecimal(rset, "receita_devol_gap"));
						fs.setDevolOCD(getBigDecimal(rset, "receita_ocd_dev"));
						BigDecimal totalDevolucao = fs.getDevolBPR().add(fs.getDevolGAP()).add(fs.getDevolOCD());

						BigDecimal receitaLiquida = receitaBruta.subtract(totalDevolucao);
						fs.setReceitaLiquida(receitaLiquida);

						fs.setDespesas(getBigDecimal(rset, "despesas"));
						fs.setPgOCD(getBigDecimal(rset, "receita_ocd_pg"));
						fs.setDifTarifaMenor(getBigDecimal(rset, "receita_dif_dif_tarifa_menor"));

						BigDecimal cartaoCredito = getBigDecimal(rset, "cartao_credito");
						cartaoCredito = cartaoCredito.add(getBigDecimal(rset, "cartao_credito_ee"));
						fs.setCartaoCredito(cartaoCredito);

						BigDecimal cartaoDebito = getBigDecimal(rset, "cartao_debito");
						cartaoDebito = cartaoDebito.add(getBigDecimal(rset, "cartao_debito_ee"));
						fs.setCartaoDebito(cartaoDebito);

						BigDecimal boleto = getBigDecimal(rset, "boleto_bnc");
						boleto = boleto.add(getBigDecimal(rset, "boleto_bnc_ee"));
						fs.setBoletoBancario(boleto);

						BigDecimal totalDetalhamento = fs.getDespesas().add(fs.getPgOCD()).add(fs.getDifTarifaMenor())
								.add(fs.getCartaoCredito()).add(fs.getCartaoDebito()).add(fs.getBoletoBancario());
						fs.setTotalDetalhamento(totalDetalhamento);

						BigDecimal saldo = totalDetalhamento.subtract(receitaLiquida);
						fs.setSaldo(saldo);

						listdata.add(fs);
					}

					if (!getConexao().isClosed())
						getConexao().close();

					Collections.sort(listdata);

				} catch (SQLException e) {
					log.error("", e);
				}
			}

		});

		this.setCollectionDataSource(new JRBeanCollectionDataSource(listdata));
	}

	static public String getString(ResultSet rs, String... strColName) throws SQLException {
		String nValue = null;
		String[] array = strColName;
		for (int i = 0; i < array.length; i++) {
			if (StringUtils.isNotBlank(rs.getString(array[i]))) {
				nValue = rs.getString(array[i]);
				return nValue;
			}
		}
		return nValue;
	}

	static public BigDecimal getBigDecimal(ResultSet rs, String strColName) throws SQLException {
		BigDecimal nValue = rs.getBigDecimal(strColName);
		return rs.wasNull() ? BigDecimal.ZERO : nValue;
	}

	@Override
	protected void processaParametros() throws Exception {
	}

	private String getSql(String ufs, String pdvs, Integer tipoptovtaId, boolean isBpe) {

		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT * ");
		sql.append(" FROM ");
		sql.append("    (SELECT cdv.estadoOrigem AS uf, ");
		sql.append("      cdv.estadoId, ");
		sql.append("      cdv.codigo, ");
		sql.append("      cdv.puntoventaId, ");
		sql.append("      cdv.empresaId, ");
		sql.append("      SUM( CASE WHEN (cdv.indreimpresion = 0 ) THEN (CASE WHEN motivocancelacion_id IS NULL THEN 1 ELSE -1 END * cdv.pedagio) ELSE 0 END) AS pedagio, ");
		sql.append("      SUM( CASE WHEN (cdv.indreimpresion = 0 ) THEN (CASE WHEN motivocancelacion_id IS NULL THEN 1 ELSE -1 END * cdv.taxaEmbarque) ELSE 0 END) AS taxaEmbarque, ");
		sql.append("      SUM( CASE WHEN (cdv.indreimpresion = 0 AND cdv.motivocancelacion_id IS NULL) THEN cdv.valorpago ELSE 0 END) AS receita_bpr, ");
		sql.append("      SUM( CASE WHEN (cdv.indreimpresion = 0 AND cdv.tipoventa_id IN (5,12,18,49) AND motivocancelacion_id IS NULL ) THEN ( cdv.tarifa+cdv.taxaEmbarque+cdv.pedagio+cdv.seguro+cdv.outros) ELSE 0 END) AS receita_gap, ");
		sql.append("      SUM( CASE WHEN (cdv.indreimpresion = 1 AND cdv.indstatusboleto = 'E' ) THEN (CASE WHEN motivocancelacion_id IS NULL THEN 1 ELSE -1 END * (cdv.tarifa+cdv.taxaEmbarque+cdv.pedagio+cdv.seguro+cdv.outros)) ELSE 0 END) AS entrega_gap, ");
		sql.append("      SUM( (SELECT sum(CASE WHEN cdv.MOTIVOCANCELACION_ID IS NULL THEN 1 ELSE -1 END * cfp.importe) FROM caja_formapago cfp WHERE cfp.caja_id = cdv.cajaid AND cfp.activo = 1 AND cfp.FORMAPAGO_ID IN (2,31,38) AND cdv.indreimpresion = 0 AND cdv.indstatusoperacion = 'F' AND cdv.tipoventa_id <> 6) ) AS cartao_credito, ");
		sql.append("      SUM( (SELECT sum(CASE WHEN cdv.MOTIVOCANCELACION_ID IS NULL THEN 1 ELSE -1 END * cfp.importe) FROM caja_formapago cfp WHERE cfp.caja_id = cdv.cajaid AND cfp.activo = 1 AND cfp.FORMAPAGO_ID IN (3) AND cdv.indreimpresion = 0 AND cdv.indstatusoperacion = 'F' AND cdv.tipoventa_id <> 6) ) AS cartao_debito, ");
		sql.append("      SUM( (SELECT sum(CASE WHEN cdv.MOTIVOCANCELACION_ID IS NULL THEN 1 ELSE -1 END * cfp.importe) FROM caja_formapago cfp WHERE cfp.caja_id = cdv.cajaid AND cfp.activo = 1 AND cfp.FORMAPAGO_ID IN (1) AND cdv.indreimpresion = 0 AND cdv.indstatusoperacion = 'F' AND cdv.tipoventa_id <> 6) ) AS boleto_bnc ");
		sql.append("    FROM ");
		sql.append("    ( SELECT DISTINCT c.caja_id AS cajaid, ");
		sql.append("      e.empresa_id AS empresaId, ");
		sql.append("      pv.puntoventa_id AS puntoventaId, ");
		sql.append("      pv.numpuntoventa AS codigo, ");
		sql.append("      eo.estado_id AS estadoId, ");
		sql.append("      eo.cveestado AS estadoOrigem, ");
		sql.append("      c.indstatusboleto, ");
		sql.append("      c.indreimpresion, ");
		sql.append("      c.indcancelacion, ");
		sql.append("      c.numfoliosistema, ");
		sql.append("      COALESCE(c.preciopagado, 0) AS valorpago, ");
		sql.append("      COALESCE(c.preciobase, 0) AS precobase, ");
		sql.append("      COALESCE(c.preciopagado, 0) AS tarifa, ");
		sql.append("      COALESCE(c.importetaxaembarque, 0) AS taxaEmbarque, ");
		sql.append("      COALESCE(c.importepedagio, 0) AS pedagio, ");
		sql.append("      COALESCE(c.importeseguro, 0) AS seguro, ");
		sql.append("      COALESCE(c.importeoutros, 0) AS outros, ");
		sql.append("      (SELECT MIN(formapago_id) FROM caja_formapago cfp WHERE cfp.caja_id = c.caja_id AND cfp.activo = 1 ) AS formapago_id , ");
		sql.append("      c.motivocancelacion_id AS motivocancelacion_id, ");
		sql.append("      c.tipoventa_id AS tipoventa_id, ");
		sql.append("      c.indstatusoperacion ");
		sql.append("      FROM CONTA_CORRENTE_PTOVTA ccp ");
		sql.append("      INNER JOIN marca ma ON ma.empresa_id = ccp.EMPRESA_ID ");
		sql.append("      INNER JOIN CAJA c ON c.FECCORTE = ccp.FECCORTE ");
		sql.append("      			AND c.TURNO_ID = ccp.TURNO_ID AND c.PUNTOVENTA_ID = ccp.PUNTOVENTA_ID ");
		sql.append("      			AND c.marca_id = ma.marca_id AND c.USUARIO_ID = ccp.USUARIO_ID ");
		sql.append("      INNER JOIN empresa e ON e.empresa_id = c.empresacorrida_id ");
		sql.append("      JOIN punto_venta pv ON pv.puntoventa_id = c.puntoventa_id ");
		sql.append("      JOIN parada po ON po.parada_id = pv.parada_id ");
		sql.append("      JOIN ciudad co ON co.ciudad_id = po.ciudad_id ");
		sql.append("      JOIN estado eo ON eo.estado_id = co.estado_id ");
		sql.append("      WHERE c.activo = 1 AND po.activo = 1 AND co.activo = 1 AND eo.activo = 1 ");
		sql.append("      AND ccp.feccorte >= :DATE_INICIO ");
		sql.append("      AND ccp.feccorte <= :DATE_FIM ");
		sql.append("      AND ccp.empresa_id = :EMPRESA_ID  ");

		sql.append(ufs == null ? "" : " and eo.estado_id in ( " + ufs + " )  ");
		sql.append(pdvs == null ? "" : "and ccp.puntoventa_id in ( " + pdvs + " ) ");
		sql.append(tipoptovtaId == -1 ? "" : "and pv.tipoptovta_id = " + tipoptovtaId);

		sql.append("    ) cdv ");
		sql.append("    GROUP BY cdv.estadoOrigem, ");
		sql.append("      cdv.estadoId, ");
		sql.append("      cdv.codigo, ");
		sql.append("      cdv.puntoventaId, ");
		sql.append("      cdv.empresaId ");
		sql.append("  ) agrc ");
		sql.append(" LEFT JOIN ");
		sql.append("  (SELECT cdc.estadoOrigem AS uf, ");
		sql.append("    cdc.estadoId, ");
		sql.append("    cdc.codigo, ");
		sql.append("    cdc.puntoventaId, ");
		sql.append("    cdc.empresaId, ");
		sql.append("    SUM( CASE WHEN (cdc.indstatusboleto IN ('C', 'T') AND cdc.motivocancelacion_id IN (32,10,37)) THEN cdc.valorpago ELSE 0 END) AS receita_devol_bpr, ");
		sql.append("    SUM( CASE WHEN (cdc.indstatusboleto IN ('C', 'T') AND cdc.motivocancelacion_id IN (31)) THEN cdc.valorpago ELSE 0 END) AS receita_cancel_bpr, ");
		sql.append("    SUM( CASE WHEN ( (cdc.indstatusboleto = 'C' AND cdc.motivocancelacion_id IN (31,32,10,37) OR (cdc.indstatusboleto = 'T' AND cdc.motivocancelacion_id IS NULL )) AND cdc.numfoliosistema IS NULL AND cdc.tipoventa_id IN (5,12,18,49)) THEN cdc.valorpago ELSE 0 END) AS receita_devol_gap, ");
		sql.append("    SUM( CASE WHEN (trunc(cdc.fecinc) = trunc(cdc.feccorte)) THEN cdc.valor_ocd ELSE 0 END) AS receita_ocd_dev,  ");
		sql.append(" SUM( CASE WHEN (cdc.fecpago is not null and cdc.fecpago between :DATE_INICIO and :DATE_FIM) THEN cdc.valor_ocd ELSE 0 END) AS receita_ocd_pg ");
		sql.append("    FROM ");
		sql.append("    ( SELECT DISTINCT c.caja_id AS cajaid, ");
		sql.append("      e.empresa_id AS empresaId, ");
		sql.append("      pv.puntoventa_id AS puntoventaId, ");
		sql.append("      pv.numpuntoventa AS codigo, ");
		sql.append("      eo.estado_id AS estadoId, ");
		sql.append("      eo.cveestado AS estadoOrigem, ");
		sql.append("      c.indstatusboleto, ");
		sql.append("      c.indreimpresion, ");
		sql.append("      c.indcancelacion, ");
		sql.append("      c.numfoliosistema, ");
		sql.append("      COALESCE(cfp.importe, 0) AS valorpago, ");
		sql.append("      COALESCE(c.preciobase, 0) AS precobase, ");
		sql.append("      COALESCE(c.preciopagado, 0) AS tarifa, ");
		sql.append("      COALESCE(c.importetaxaembarque, 0) AS taxaEmbarque, ");
		sql.append("      COALESCE(c.importepedagio, 0) AS pedagio, ");
		sql.append("      COALESCE(c.importeseguro, 0) AS seguro, ");
		sql.append("      COALESCE(c.importeoutros, 0) AS outros, ");
		sql.append("      cfp.formapago_id, ");
		sql.append("      c.motivocancelacion_id AS motivocancelacion_id, ");
		sql.append("      c.tipoventa_id AS tipoventa_id, ");
		sql.append("      c.indstatusoperacion, ");

		sql.append("      c.feccorte, ");
		sql.append("      ocd.fecinc, ");
		sql.append("      ocd.fecpago, ");
		sql.append("      ocd.valor_pagar as valor_ocd ");

		sql.append("      FROM caja c ");
		sql.append("      INNER JOIN caja_formapago cfp ON cfp.caja_id = c.caja_id ");
		sql.append("      INNER JOIN forma_pago fp ON cfp.formapago_id = fp.formapago_id ");
		sql.append("      INNER JOIN marca m ON m.marca_id = c.marca_id AND m.activo = 1 ");
		sql.append("      INNER JOIN empresa e ON e.empresa_id = m.empresa_id ");
		sql.append("      INNER JOIN punto_venta pv ON pv.puntoventa_id = c.puntoventa_id ");
		sql.append("      JOIN parada po ON po.parada_id = pv.parada_id ");
		sql.append("      JOIN ciudad co ON co.ciudad_id = po.ciudad_id ");
		sql.append("      JOIN estado eo ON eo.estado_id = co.estado_id ");
		sql.append("      LEFT JOIN ocd ocd on ocd.boleto_id = c.transacao_id ");
		sql.append("      WHERE (c.motivocancelacion_id IN (31,32,10,37,99,36) ");
		sql.append("      OR c.motivocancelacion_id IS NULL) ");
		sql.append("      AND c.feccorte >= :DATE_INICIO ");
		sql.append("      AND c.feccorte <= :DATE_FIM ");
		sql.append("      AND c.empresacorrida_id = :EMPRESA_ID  ");

		sql.append(ufs == null ? "" : " and eo.estado_id in ( " + ufs + " )  ");
		sql.append(pdvs == null ? "" : "and pv.puntoventa_id in ( " + pdvs + " ) ");
		sql.append(tipoptovtaId == -1 ? "" : "and pv.tipoptovta_id = " + tipoptovtaId);

		sql.append("      AND c.categoria_id NOT IN ");
		sql.append("      (SELECT valorconstante FROM constante WHERE nombconstante = 'GRATUIDADE_CRIANCA' ) ");
		sql.append("     ) cdc ");
		sql.append("     GROUP BY cdc.estadoOrigem, ");
		sql.append("      cdc.estadoId, ");
		sql.append("      cdc.codigo, ");
		sql.append("      cdc.puntoventaId, ");
		sql.append("      cdc.empresaId ");
		sql.append("  ) canc ON agrc.empresaId = canc.empresaId ");
		sql.append("   AND agrc.puntoventaId = canc.puntoventaId ");
		sql.append("   AND agrc.estadoId = canc.estadoId ");
		sql.append(" LEFT JOIN ");
		sql.append("  (SELECT ee.empresa_id AS empresaId, ");
		sql.append("    cd.puntoventa_id AS puntoventaId, ");
		sql.append("    eo.estado_id AS estadoId, ");
		sql.append("    SUM( CASE WHEN ee.tipoeventoextra_id = 2 AND tee.indtipo = 1 THEN cdp.importe ELSE 0 END) AS taxaembarque_ee, ");
		sql.append("    SUM( CASE WHEN ee.tipoeventoextra_id = 25 AND tee.indtipo = 1 THEN cdp.importe ELSE 0 END) AS segurofac, ");
		sql.append("    SUM( CASE WHEN ee.tipoeventoextra_id = 82 AND tee.indtipo = 1 THEN cdp.importe ELSE 0 END) AS receita_eb, ");
		sql.append("    SUM( CASE WHEN ee.tipoeventoextra_id = 61 AND tee.indtipo = 1 THEN cdp.importe ELSE 0 END) AS txconveniencia_ee, ");
		sql.append("    SUM( CASE WHEN ee.tipoeventoextra_id IN (41) AND tee.indtipo = 1 THEN cdp.importe ELSE 0 END) AS receita_multa, ");
		sql.append("    SUM( CASE WHEN ee.tipoeventoextra_id IN (103,99978,99999) AND tee.indtipo = 1 THEN cdp.importe ELSE 0 END) AS receita_dif_troca_ocd, ");
		sql.append("    SUM( CASE WHEN ee.tipoeventoextra_id IN (43) AND tee.indtipo = 1 THEN cdp.importe ELSE 0 END) AS receita_dif_dif_tarifa_maior, ");
		sql.append("    SUM( CASE WHEN ee.tipoeventoextra_id IN (44) AND tee.indtipo = 0 THEN cdp.importe ELSE 0 END) AS receita_dif_dif_tarifa_menor, ");
		sql.append("    SUM( CASE WHEN ee.tipoeventoextra_id NOT IN (44) AND tee.indtipo = 0 THEN cdp.importe ELSE 0 END) AS despesas, ");
		sql.append("    SUM( CASE WHEN (cdp.formapago_id IN (2,31,38) AND e.indtipo = 1) THEN cdp.importe ELSE 0 END) AS cartao_credito_ee, ");
		sql.append("    SUM( CASE WHEN (cdp.formapago_id IN (3) AND e.indtipo = 1) THEN cdp.importe ELSE 0 END) AS cartao_debito_ee, ");
		sql.append("    SUM( CASE WHEN (cdp.formapago_id IN (1) AND e.indtipo = 1) THEN cdp.importe ELSE 0 END) AS boleto_bnc_ee ");
		sql.append("    FROM CAJA_DIVERSOS cd ");
		sql.append("    JOIN CAJA_DIVERSOS_PAGO cdp ON cdp.CAJADIVERSOS_ID = cd.CAJADIVERSOS_ID ");
		sql.append("    INNER JOIN forma_pago fp ON fp.formapago_id = cdp.formapago_id ");
		sql.append("    INNER JOIN EVENTO_EXTRA EE ON EE.EVENTOEXTRA_ID = cd.EVENTOEXTRA_ID ");
		sql.append("    JOIN tipo_evento_extra tee ON tee.tipoeventoextra_id = ee.tipoeventoextra_id ");
		sql.append("    LEFT OUTER JOIN empresa e ON ee.empresa_id = e.empresa_id ");
		sql.append("    INNER JOIN CONTA_CORRENTE_PTOVTA ccp ON e.EMPRESA_ID = ccp.EMPRESA_ID ");
		sql.append("    			AND ccp.PUNTOVENTA_ID = cd.PUNTOVENTA_ID AND ccp.FECCORTE = cd.FECCORTE ");
		sql.append("    			AND ccp.TURNO_ID = cd.turno_id AND cd.USUARIO_ID = ccp.USUARIO_ID ");
		sql.append("    JOIN punto_venta pv ON pv.puntoventa_id = ee.puntoventa_id ");
		sql.append("    LEFT JOIN parada po ON po.parada_id = pv.parada_id ");
		sql.append("    LEFT JOIN ciudad co ON co.ciudad_id = po.ciudad_id ");
		sql.append("    LEFT JOIN estado eo ON eo.estado_id = co.estado_id ");
		sql.append("    WHERE ( cd.indreimpresion = 0 ");
		sql.append("    OR cd.indreimpresion IS NULL ) ");
		sql.append("    AND ee.empresa_id = :EMPRESA_ID  ");
		sql.append("    AND ccp.FECCORTE BETWEEN :DATE_INICIO AND :DATE_FIM ");

		sql.append(ufs == null ? "" : " and eo.estado_id in ( " + ufs + " )  ");
		sql.append(pdvs == null ? "" : "and ccp.puntoventa_id in ( " + pdvs + " ) ");
		sql.append(tipoptovtaId == -1 ? "" : "and pv.tipoptovta_id = " + tipoptovtaId);

		sql.append("    GROUP BY ee.empresa_id, ");
		sql.append("      cd.puntoventa_id, ");
		sql.append("      eo.estado_id ");
		sql.append("  ) eed ON agrc.empresaId = eed.empresaId ");
		sql.append("   AND agrc.puntoventaId = eed.puntoventaId ");
		sql.append("   AND agrc.estadoId = eed.estadoId ");

		sql.append(" FULL JOIN  ");
		sql.append("     (select empresaId, puntoventaId, estadoId, codigo_rec, estadoOrigem_rec, sum(tarifa) as receita_rdi_bpr ");
		sql.append(isBpe ? ", xml_bpe_rec, xml_bpe_rec_2, xml_bpe_rec_3 " : "");
		sql.append("      from ( ");
		sql.append("     SELECT DISTINCT ");
		sql.append("       c.caja_id as cajaId, ");
		sql.append("       e.empresa_id AS empresaId,  ");
		sql.append("       pv.puntoventa_id AS puntoventaId,  ");
		sql.append("       pv.numpuntoventa AS codigo_rec,  ");
		sql.append("       eo.estado_id AS estadoId,  ");
		sql.append("       eo.cveestado AS estadoOrigem_rec,  ");
		sql.append(isBpe ? " DBMS_LOB.substr(coalesce(bpe.xmlregular, bpe.xmlcontingencia), 3000) as xml_bpe_rec, " : "");
		sql.append(isBpe ? " DBMS_LOB.substr(coalesce(bpe.xmlregular, bpe.xmlcontingencia), 3000, 3001) as xml_bpe_rec_2, " : "");
		sql.append(isBpe ? " DBMS_LOB.substr(coalesce(bpe.xmlregular, bpe.xmlcontingencia), 3000, 6001) as xml_bpe_rec_3, " : "");
		sql.append("       COALESCE(c.preciopagado, 0) AS tarifa, ");
		sql.append("       COALESCE(c.importetaxaembarque, 0) AS taxaEmbarque, ");
		sql.append("       COALESCE(c.importepedagio, 0) AS pedagio, ");
		sql.append("       COALESCE(c.importeseguro, 0) AS seguro, ");
		sql.append("       COALESCE(c.importeoutros, 0) AS outros ");
		sql.append("     FROM caja c ");
		sql.append(isBpe ? " INNER JOIN bpe bpe ON bpe.boleto_id = c.transacao_id " : "");
		sql.append(isBpe ? " and bpe.activo = (case when c.motivocancelacion_id = 17 and c.transacaooriginal_id = c.transacao_id then 0 else 1 end) " : "");
		sql.append(isBpe ? " INNER JOIN estado e_bpe ON e_bpe.codibge = bpe.uf " : "");
		sql.append("     INNER JOIN marca m ON m.marca_id = c.marca_id AND m.activo  = 1 ");
		sql.append("     INNER JOIN empresa e ON e.empresa_id = m.empresa_id ");
		sql.append("     INNER JOIN punto_venta pv ON pv.puntoventa_id = c.puntoventa_id ");
		sql.append("     INNER JOIN parada p  ON pv.parada_id = p.parada_id  ");
		sql.append("     INNER JOIN ciudad co ON co.ciudad_id = p.ciudad_id  ");
		sql.append("     INNER JOIN estado eo ON eo.estado_id = co.estado_id ");
		sql.append("     WHERE c.activo = 1 ");
		sql.append("     AND p.activo = 1 ");
		sql.append("     AND co.activo = 1 ");
		sql.append("     AND eo.activo = 1 ");
		sql.append("     AND c.serieimpfiscal IS NOT NULL ");
		sql.append(isBpe ? " " : " and c.num_bpe is null ");
		sql.append("     AND ((c.indreimpresion = 0 AND c.motivocancelacion_id IS NULL ");
		sql.append("     AND c.numfoliosistema IS NOT NULL) OR (c.indstatusboleto = 'E' AND c.indreimpresion = 1)) ");
		sql.append("     AND (COALESCE(c.preciopagado,0) + COALESCE(c.importetaxaembarque,0) + COALESCE(c.importeseguro,0) + COALESCE(c.importepedagio,0) + COALESCE(c.importeoutros,0)) > 0 ");
		sql.append("     AND c.feccreacion >= :DATE_INICIO AND c.feccreacion <= :DATE_FIM ");
		sql.append("     AND e.empresa_id   = :EMPRESA_ID ");
		sql.append(ufs == null ? "" : " and COALESCE(e_bpe.estado_id, eo.estado_id) in ( " + ufs + " )  ");
		sql.append(pdvs == null ? "" : "and pv.puntoventa_id in ( " + pdvs + " ) ");
		sql.append(tipoptovtaId == -1 ? "" : "and pv.tipoptovta_id = " + tipoptovtaId);
		sql.append("     UNION ALL ");
		sql.append("     SELECT DISTINCT c.caja_id AS cajaId, ");
		sql.append("       e.empresa_id AS empresaId,  ");
		sql.append("       pv.puntoventa_id AS puntoventaId,  ");
		sql.append("       pv.numpuntoventa AS codigo_rec,  ");
		sql.append("       eo.estado_id AS estadoId,  ");
		sql.append("       eo.cveestado AS estadoOrigem_rec,  ");
		sql.append(isBpe ? " DBMS_LOB.substr(coalesce(bpe.xmlregular, bpe.xmlcontingencia), 3000) as xml_bpe_rec, " : "");
		sql.append(isBpe ? " DBMS_LOB.substr(coalesce(bpe.xmlregular, bpe.xmlcontingencia), 3000, 3001) as xml_bpe_rec_2, " : "");
		sql.append(isBpe ? " DBMS_LOB.substr(coalesce(bpe.xmlregular, bpe.xmlcontingencia), 3000, 6001) as xml_bpe_rec_3, " : "");
		sql.append("       COALESCE(c.preciopagado, 0) AS tarifa, ");
		sql.append("       COALESCE(c.importetaxaembarque, 0) AS taxaEmbarque, ");
		sql.append("       COALESCE(c.importepedagio, 0) AS pedagio, ");
		sql.append("       COALESCE(c.importeseguro, 0) AS seguro, ");
		sql.append("       COALESCE(c.importeoutros, 0) AS outros ");
		sql.append("     FROM caja c ");
		sql.append(isBpe ? " INNER JOIN bpe bpe ON bpe.boleto_id = c.transacao_id " : "");
		sql.append(isBpe ? " and bpe.activo = (case when c.motivocancelacion_id = 17 and c.transacaooriginal_id = c.transacao_id then 0 else 1 end) " : "");
		sql.append(isBpe ? " INNER JOIN estado e_bpe ON e_bpe.codibge = bpe.uf " : "");
		sql.append("     JOIN marca m ON c.marca_id = m.marca_id ");
		sql.append("     JOIN empresa e ON e.empresa_id = m.empresa_id ");
		sql.append("     JOIN aidf a ON a.aidf_id = c.aidf_id ");
		sql.append("     JOIN punto_venta pv ON pv.puntoventa_id = c.puntoventa_id ");
		sql.append("     JOIN parada po ON po.parada_id = pv.parada_id ");
		sql.append("     JOIN ciudad co ON co.ciudad_id = po.ciudad_id ");
		sql.append("     JOIN estado eo ON eo.estado_id = co.estado_id ");
		sql.append("     WHERE ((c.tipoventa_id       = 3 ");
		sql.append("     AND c.indstatusboleto        = 'V' ");
		sql.append("     AND c.indreimpresion         = 0) ");
		sql.append("     OR (c.tipoventa_id          IN (12,18) ");
		sql.append("     AND c.indstatusboleto        = 'E' ");
		sql.append("     AND c.numfoliosistema        = c.numfoliopreimpreso)) ");
		sql.append("     AND (c.motivocancelacion_id IS NULL ");
		sql.append("     OR c.motivocancelacion_id   <> 35) ");
		sql.append("     AND c.indcancelacion         = 0 ");
		sql.append(isBpe ? " " : " and c.num_bpe is null ");
		sql.append("     AND e.empresa_id      = :EMPRESA_ID ");
		sql.append("     AND c.feccreacion BETWEEN :DATE_INICIO AND :DATE_FIM ");
		sql.append(ufs == null ? "" : " and COALESCE(e_bpe.estado_id, eo.estado_id) in ( " + ufs + " )  ");
		sql.append(pdvs == null ? "" : "and pv.puntoventa_id in ( " + pdvs + " ) ");
		sql.append(tipoptovtaId == -1 ? "" : "and pv.tipoptovta_id = " + tipoptovtaId);
		sql.append("     ) rbl ");
		sql.append("     GROUP BY rbl.estadoId, rbl.puntoventaId, rbl.empresaId, rbl.codigo_rec, rbl.estadoOrigem_rec ");
		sql.append(isBpe ? " , rbl.xml_bpe_rec, rbl.xml_bpe_rec_2, rbl.xml_bpe_rec_3 " : "");
		sql.append("     )rbpr ON agrc.empresaId = rbpr.empresaId ");
		sql.append(" AND agrc.puntoventaId = rbpr.puntoventaId ");
		sql.append(" AND agrc.estadoId = rbpr.estadoId  ");

		sql.append(" FULL JOIN ");

		sql.append(" ( select empresaId, puntoventaId, estadoId, codigo_dev, estadoOrigem_dev, sum(tarifa) as receita_cancel_rdi_bpr ");
		sql.append(isBpe ? ", xml_bpe_dev, xml_bpe_dev_2, xml_bpe_dev_3 " : "");
		sql.append("  	from  (  ");

		if (isBpe) {

			sql.append(" select distinct ");
			sql.append("  b.boleto_id AS cajaId, ");
			sql.append("  e.empresa_id AS empresaId, ");
			sql.append("  PTVO.PUNTOVENTA_ID AS puntoventaId, ");
			sql.append("  PTVO.NUMPUNTOVENTA AS codigo_dev, ");
			sql.append("  COALESCE(ESAIDF.ESTADO_ID, EOS.ESTADO_ID, EST.ESTADO_ID) AS estadoId, ");
			sql.append("  COALESCE(ESAIDF.CVEESTADO, EOS.CVEESTADO, EST.CVEESTADO) AS estadoOrigem_dev, ");
			sql.append("  dbms_lob.substr((case when bpeori.tipoevento is not null then bpeant.xmlregular else bpeori.xmlregular end), 3000) as xml_bpe_dev, ");
			sql.append("  dbms_lob.substr((case when bpeori.tipoevento is not null then bpeant.xmlregular else bpeori.xmlregular end), 3000, 3001) as xml_bpe_dev_2, ");
			sql.append("  dbms_lob.substr((case when bpeori.tipoevento is not null then bpeant.xmlregular else bpeori.xmlregular end), 3000, 6001) as xml_bpe_dev_3, ");
			sql.append("  COALESCE(b.preciopagado, 0) AS tarifa, ");
			sql.append("  COALESCE(b.importetaxaembarque, 0) AS taxaEmbarque, ");
			sql.append("  COALESCE(b.importepedagio, 0) AS pedagio, ");
			sql.append("  COALESCE(b.importeseguro, 0) AS seguro, ");
			sql.append("  COALESCE(b.importeoutros, 0) AS outros ");
			sql.append("from boleto bori ");
			sql.append("  inner join marca m on m.marca_id = bori.marca_id and m.activo = 1 ");
			sql.append("  inner join empresa e on e.empresa_id = m.empresa_id ");
			sql.append("  inner join bpe bpe on bpe.boleto_id = bori.boleto_id ");
			sql.append("      and bpe.activo = (case when bori.motivocancelacion_id = 17 and bori.boletooriginal_id is null then 0 else 1 end) ");
			sql.append("  inner join estado est_bpe on bpe.uf = est_bpe.codibge ");
			sql.append("  left join bpe bpeori on bpeori.chbpe = bpe.chbpe_substituicao ");
			sql.append("      and bpeori.activo = (case when bori.motivocancelacion_id = 17 and bori.boletooriginal_id is null then 0 else 1 end) ");
			sql.append("  left join boleto b on b.boleto_id = bpeori.boleto_id ");
			sql.append("  inner join punto_venta ptv on ptv.puntoventa_id = b.puntoventa_id ");
			sql.append("  inner join parada ori on (b.origen_id = ori.parada_id ) ");
			sql.append("  inner join parada des on (b.destino_id = des.parada_id ) ");
			sql.append("  inner join ciudad co on (co.ciudad_id = ori.ciudad_id ) ");
			sql.append("  inner join ciudad cd on (cd.ciudad_id = des.ciudad_id ) ");
			sql.append("  inner join estado est on est.estado_id = co.estado_id ");
			sql.append("  left join alias_servico s on s.origen_id = b.origen_id ");
			sql.append("                 		  and s.destino_id = b.destino_id and (s.corrida_id = b.corrida_id or s.corrida_id is null) ");
			sql.append("                 		  and s.ruta_id = b.ruta_id and s.activo = 1 ");
			sql.append("  left join parada pos on pos.parada_id = s.aliasorigen_id ");
			sql.append("  left join ciudad cos on cos.ciudad_id = pos.ciudad_id ");
			sql.append("  left join estado eos on eos.estado_id = cos.estado_id ");
			sql.append("  left join parada pds on pds.parada_id = s.aliasdestino_id ");
			sql.append("  left join ciudad cds on cds.ciudad_id = pds.ciudad_id ");
			sql.append("  left join estado eds on eds.estado_id = cds.estado_id ");
			sql.append("  join inscricao_estadual ie on e.empresa_id = ie.empresa_id ");
			sql.append("               			   and ie.estado_id = coalesce(eos.estado_id, est.estado_id) and ie.activo = 1 ");
			sql.append("  join empresa_imposto ei on ei.empresa_id = e.empresa_id ");
			sql.append("               			   and ei.estado_id = coalesce(eos.estado_id, est.estado_id) and ei.activo = 1 ");
			sql.append("  left join aidf aidf on aidf.aidf_id = b.aidf_id and b.tipoventa_id = 3 ");
			sql.append("  left join estado esaidf on esaidf.estado_id = aidf.estado_id ");
			sql.append("  left join boleto bant on bant.boleto_id = (case when bpeori.tipoevento is not null then coalesce(b.boletoanterior_id, b.boletooriginal_id) else null end) ");
			sql.append("  left join bpe bpeant on bpeant.boleto_id = bant.boleto_id ");
			sql.append("  left join punto_venta ptvo on ptvo.puntoventa_id = coalesce(bant.puntoventa_id, bori.puntoventa_id,b.ptovtaventa_id) ");
			sql.append("where ( (bpe.codstat in ('-1','100','101','102','135','150') and bpe.chbpe_substituicao is not null) ");
			sql.append("    or (bpe.codstat in ('101','135') and to_char(b.feccreacion, 'mm/yyyy') < to_char(bori.feccreacion, 'mm/yyyy')) ) ");
			sql.append("    and (bpe.codstat in ('-1','100','101','102','135','150') and bpe.tipoevento <> '110115' or bpe.tipoevento is null) ");
			sql.append("    and (bpeori.codstat in ('-1','100','101','102','135','150') and bpeori.tipoevento <> '110115' or bpeori.tipoevento is null) ");
			sql.append("    and bori.feccreacion >= :DATE_INICIO and bori.feccreacion <= :DATE_FIM ");
			sql.append("    and e.empresa_id = :EMPRESA_ID ");
			sql.append(ufs == null ? "" : " and est_bpe.estado_id in ( " + ufs + " ) ");
			sql.append(pdvs == null ? "" : " and ptvo.puntoventa_id in  ( " + pdvs + " ) ");
			sql.append(tipoptovtaId == -1 ? "" : " and ptvo.tipoptovta_id = " + tipoptovtaId);

			sql.append("  union all  ");

			sql.append("select distinct ");
			sql.append("  b.boleto_id AS cajaId, ");
			sql.append("  e.empresa_id AS empresaId, ");
			sql.append("  PTVO.PUNTOVENTA_ID AS puntoventaId, ");
			sql.append("  PTVO.NUMPUNTOVENTA AS codigo_dev, ");
			sql.append("  COALESCE(ESAIDF.ESTADO_ID, EOS.ESTADO_ID, EST.ESTADO_ID) AS estadoId, ");
			sql.append("  COALESCE(ESAIDF.CVEESTADO, EOS.CVEESTADO, EST.CVEESTADO) AS estadoOrigem_dev, ");
			sql.append("  dbms_lob.substr((case when bpeori.tipoevento is not null then bpeant.xmlregular else bpeori.xmlregular end), 3000) as xml_bpe_dev, ");
			sql.append("  dbms_lob.substr((case when bpeori.tipoevento is not null then bpeant.xmlregular else bpeori.xmlregular end), 3000, 3001) as xml_bpe_dev_2, ");
			sql.append("  dbms_lob.substr((case when bpeori.tipoevento is not null then bpeant.xmlregular else bpeori.xmlregular end), 3000, 6001) as xml_bpe_dev_3, ");
			sql.append("  COALESCE(b.preciopagado, 0) AS tarifa, ");
			sql.append("  COALESCE(b.importetaxaembarque, 0) AS taxaEmbarque, ");
			sql.append("  COALESCE(b.importepedagio, 0) AS pedagio, ");
			sql.append("  COALESCE(b.importeseguro, 0) AS seguro, ");
			sql.append("  COALESCE(b.importeoutros, 0) AS outros ");
			sql.append("from boleto bori ");
			sql.append("  inner join marca m on m.marca_id = bori.marca_id and m.activo = 1 ");
			sql.append("  inner join empresa e on e.empresa_id = m.empresa_id ");
			sql.append("  inner join bpe bpe on bpe.boleto_id = bori.boleto_id ");
			sql.append("      and bpe.activo = (case when bori.motivocancelacion_id = 17 and bori.boletooriginal_id is null then 0 else 1 end) ");
			sql.append("  inner join estado est_bpe on bpe.uf = est_bpe.codibge ");
			sql.append("  left join boleto b on b.boleto_id = (case when bori.motivocancelacion_id = 99 then  bori.boletoanterior_id else bori.boletooriginal_id end) ");
			sql.append("  left join bpe bpeori on b.boleto_id = bpeori.boleto_id ");
			sql.append("      and bpeori.activo = (case when bori.motivocancelacion_id = 17 and bori.boletooriginal_id is null then 0 else 1 end) ");
			sql.append("  inner join punto_venta ptv on ptv.puntoventa_id = bori.puntoventa_id ");
			sql.append("  inner join parada ori on (b.origen_id = ori.parada_id ) ");
			sql.append("  inner join parada des on (b.destino_id = des.parada_id ) ");
			sql.append("  inner join ciudad co on (co.ciudad_id = ori.ciudad_id ) ");
			sql.append("  inner join ciudad cd on (cd.ciudad_id = des.ciudad_id ) ");
			sql.append("  inner join estado est on est.estado_id = co.estado_id ");
			sql.append("left join alias_servico s on s.origen_id = b.origen_id ");
			sql.append("                 		  and s.destino_id = b.destino_id and (s.corrida_id = b.corrida_id or s.corrida_id is null) ");
			sql.append("                 		  and s.ruta_id = b.ruta_id and s.activo = 1 ");
			sql.append("left join parada pos on pos.parada_id = s.aliasorigen_id ");
			sql.append("left join ciudad cos on cos.ciudad_id = pos.ciudad_id ");
			sql.append("left join estado eos on eos.estado_id = cos.estado_id ");
			sql.append("left join parada pds on pds.parada_id = s.aliasdestino_id ");
			sql.append("left join ciudad cds on cds.ciudad_id = pds.ciudad_id ");
			sql.append("left join estado eds on eds.estado_id = cds.estado_id ");
			sql.append("join inscricao_estadual ie on e.empresa_id = ie.empresa_id ");
			sql.append("               			   and ie.estado_id = coalesce(eos.estado_id, est.estado_id) and ie.activo = 1 ");
			sql.append("join empresa_imposto ei on ei.empresa_id = e.empresa_id ");
			sql.append("               			   and ei.estado_id = coalesce(eos.estado_id, est.estado_id) and ei.activo = 1 ");
			sql.append("left join aidf aidf on aidf.aidf_id = b.aidf_id and b.tipoventa_id = 3 ");
			sql.append("left join estado esaidf on esaidf.estado_id = aidf.estado_id ");
			sql.append("left join boleto bant on bant.boleto_id = (case when bpeori.tipoevento is not null then coalesce(b.boletoanterior_id, b.boletooriginal_id) else null end) ");
			sql.append("left join bpe bpeant on bpeant.boleto_id = bant.boleto_id ");
			sql.append("      and bpeant.activo = (case when bori.motivocancelacion_id = 17 and bori.boletooriginal_id is null then 0 else 1 end) ");
			sql.append("left join punto_venta ptvo on ptvo.puntoventa_id = coalesce(bant.puntoventa_id, bori.puntoventa_id,b.ptovtaventa_id) ");
			sql.append("where ");
			sql.append("    (bpe.codstat in ('101','135') and to_char(b.feccreacion, 'mm/yyyy') < to_char(bori.feccreacion, 'mm/yyyy')) ");
			sql.append("    and (bpe.codstat in ('-1','100','101','102','135','150') and bpe.tipoevento <> '110115' or bpe.tipoevento is null) ");
			sql.append("    and (bpeori.codstat in ('-1','100','101','102','135','150') and bpeori.tipoevento <> '110115' or bpeori.tipoevento is null) ");
			sql.append("    and bori.feccreacion >= :DATE_INICIO and bori.feccreacion <= :DATE_FIM ");
			sql.append("    and e.empresa_id = :EMPRESA_ID ");
			sql.append(ufs == null ? "" : " and est_bpe.estado_id in ( " + ufs + " ) ");
			sql.append(pdvs == null ? "" : " and ptvo.puntoventa_id in  ( " + pdvs + " ) ");
			sql.append(tipoptovtaId == -1 ? "" : " and ptvo.tipoptovta_id = " + tipoptovtaId);

		} else {

			sql.append(" SELECT DISTINCT b.boleto_id AS cajaId, ");
			sql.append("             e.empresa_id AS empresaId, ");
			sql.append("             PTVO.PUNTOVENTA_ID AS puntoventaId, ");
			sql.append("             PTVO.NUMPUNTOVENTA AS codigo_dev, ");
			sql.append("             COALESCE(ESAIDF.ESTADO_ID, EOS.ESTADO_ID, EST.ESTADO_ID) AS estadoId, ");
			sql.append("             COALESCE(ESAIDF.CVEESTADO, EOS.CVEESTADO, EST.CVEESTADO) AS estadoOrigem_dev, ");
			sql.append("             COALESCE(b.preciopagado, 0) AS tarifa, ");
			sql.append("             COALESCE(b.importetaxaembarque, 0) AS taxaEmbarque, ");
			sql.append("             COALESCE(b.importepedagio, 0) AS pedagio, ");
			sql.append("             COALESCE(b.importeseguro, 0) AS seguro, ");
			sql.append("             COALESCE(b.importeoutros, 0) AS outros ");
			sql.append("      FROM BOLETO B ");
			sql.append("        INNER JOIN MARCA M ON M.MARCA_ID = B.MARCA_ID AND M.ACTIVO = 1 ");
			sql.append("        INNER JOIN EMPRESA E ON E.EMPRESA_ID = M.EMPRESA_ID ");
			sql.append("        INNER JOIN PUNTO_VENTA PTV ON PTV.PUNTOVENTA_ID = B.PUNTOVENTA_ID ");
			sql.append("        INNER JOIN PARADA ORI ON (B.ORIGEN_ID = ORI.PARADA_ID ) ");
			sql.append("        INNER JOIN PARADA DES ON (B.DESTINO_ID = DES.PARADA_ID ) ");
			sql.append("        INNER JOIN CIUDAD CO ON (CO.CIUDAD_ID = ORI.CIUDAD_ID ) ");
			sql.append("        INNER JOIN CIUDAD CD ON (CD.CIUDAD_ID = DES.CIUDAD_ID ) ");
			sql.append("        INNER JOIN ESTADO EST ON EST.ESTADO_ID = CO.ESTADO_ID ");
			sql.append("        LEFT JOIN PUNTO_VENTA PTVO ON PTVO.PUNTOVENTA_ID = B.PTOVTAVENTA_ID ");
			sql.append("        LEFT JOIN ALIAS_SERVICO S ON S.ORIGEN_ID = B.ORIGEN_ID ");
			sql.append("                       		  AND S.DESTINO_ID = B.DESTINO_ID AND (S.CORRIDA_ID = B.CORRIDA_ID OR S.CORRIDA_ID IS NULL) ");
			sql.append("                       		  AND S.RUTA_ID = B.RUTA_ID AND S.ACTIVO = 1 ");
			sql.append("        LEFT JOIN PARADA POS ON POS.PARADA_ID = S.ALIASORIGEN_ID ");
			sql.append("        LEFT JOIN CIUDAD COS ON COS.CIUDAD_ID = POS.CIUDAD_ID ");
			sql.append("        LEFT JOIN ESTADO EOS ON EOS.ESTADO_ID = COS.ESTADO_ID ");
			sql.append("        LEFT JOIN PARADA PDS ON PDS.PARADA_ID = S.ALIASDESTINO_ID ");
			sql.append("        LEFT JOIN CIUDAD CDS ON CDS.CIUDAD_ID = PDS.CIUDAD_ID ");
			sql.append("        LEFT JOIN ESTADO EDS ON EDS.ESTADO_ID = CDS.ESTADO_ID ");
			sql.append("        JOIN INSCRICAO_ESTADUAL IE ON E.EMPRESA_ID = IE.EMPRESA_ID ");
			sql.append("                     			   AND IE.ESTADO_ID = COALESCE(EOS.ESTADO_ID, EST.ESTADO_ID) AND IE.ACTIVO = 1 ");
			sql.append("        JOIN EMPRESA_IMPOSTO EI ON EI.EMPRESA_ID = E.EMPRESA_ID ");
			sql.append("                     			   AND EI.ESTADO_ID = COALESCE(EOS.ESTADO_ID, EST.ESTADO_ID) AND EI.ACTIVO = 1 ");
			sql.append("        LEFT JOIN AIDF AIDF ON AIDF.AIDF_ID = B.AIDF_ID AND B.TIPOVENTA_ID = 3 ");
			sql.append("        LEFT JOIN ESTADO ESAIDF ON ESAIDF.ESTADO_ID = AIDF.ESTADO_ID ");
			sql.append("        LEFT JOIN BOLETO BORI ON BORI.BOLETO_ID = B.BOLETOORIGINAL_ID ");
			sql.append("      WHERE B.MOTIVOCANCELACION_ID IN (31,32,10,37,99,36) ");
			sql.append("        AND B.INDSTATUSBOLETO = 'C' AND B.INDCANCELACION = 1 ");
			sql.append("      	AND BORI.FECHORVENTA >= :DATE_INICIO ");
			sql.append("      	AND BORI.FECHORVENTA <= :DATE_FIM ");
			sql.append("      	AND B.FECHORVENTA >= :DATE_INICIO ");
			sql.append("      	AND B.FECHORVENTA <= :DATE_FIM ");
			sql.append(ufs == null ? "" : " AND COALESCE(ESAIDF.ESTADO_ID, EOS.ESTADO_ID, EST.ESTADO_ID) IN ( " + ufs + " ) ");
			sql.append(pdvs == null ? "" : " AND PTVO.PUNTOVENTA_ID IN  ( " + pdvs + " ) ");
			sql.append(tipoptovtaId == -1 ? "" : " AND PTVO.TIPOPTOVTA_ID = " + tipoptovtaId);
			sql.append("      	AND E.EMPRESA_ID = :EMPRESA_ID ");
			sql.append("        AND B.NUM_BPE IS NULL ");
			sql.append("        AND B.CATEGORIA_ID NOT IN (SELECT VALORCONSTANTE FROM CONSTANTE WHERE NOMBCONSTANTE = 'GRATUIDADE_CRIANCA') ");
			sql.append("        AND B.NUM_BPE IS NULL ");

		}

		sql.append("           ) cbl ");
		sql.append("      GROUP BY cbl.estadoId, cbl.puntoventaId, cbl.empresaId, cbl.codigo_dev, cbl.estadoOrigem_dev ");
		sql.append(isBpe ? " , cbl.xml_bpe_dev, cbl.xml_bpe_dev_2, cbl.xml_bpe_dev_3 " : "");

		sql.append(" ) cbpr ");
		sql.append(" ON agrc.empresaId      = cbpr.empresaId ");
		sql.append(" AND agrc.puntoventaId  = cbpr.puntoventaId ");
		sql.append(" AND agrc.estadoId      = cbpr.estadoId ");

		return sql.toString();
	}

}
