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.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.Estado;
import com.rjconsultores.ventaboletos.entidad.PuntoVenta;
import com.rjconsultores.ventaboletos.relatorios.utilitarios.DataSource;
import com.rjconsultores.ventaboletos.relatorios.utilitarios.DevolucaoBilhetes;
import com.rjconsultores.ventaboletos.relatorios.utilitarios.Relatorio;
import com.rjconsultores.ventaboletos.utilerias.DateUtil;
import com.rjconsultores.ventaboletos.utilerias.MoneyHelper;
import com.rjconsultores.ventaboletos.utilerias.UtiliteriasFiscal;
import com.rjconsultores.ventaboletos.utilerias.exportacao.bpe.ExportacaoBPEVo.TipoComp;
import com.rjconsultores.ventaboletos.utilerias.exportacao.bpe.xml.BPeUtil;
import com.rjconsultores.ventaboletos.web.utilerias.NamedParameterStatement;

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

public class RelatorioDevolucaoBilhetes extends Relatorio {

	private static Logger log = LogManager.getLogger(RelatorioDevolucaoBilhetes.class);

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

		this.setCustomDataSource(new DataSource(this) {
			@SuppressWarnings("unchecked")
			@Override
			public void initDados() throws Exception {

				Connection conexao = this.relatorio.getConexao();
				Map<String, Object> parametros = this.relatorio.getParametros();

				List<PuntoVenta> lsPuntoVenta = parametros.get("PUNTOVENTAS") == null ? new ArrayList<PuntoVenta>() : (ArrayList<PuntoVenta>) parametros.get("PUNTOVENTAS");
				List<Estado> lsEstado = parametros.get("ESTADOS") == null ? new ArrayList<Estado>() : (ArrayList<Estado>) parametros.get("ESTADOS");
				Integer empresaId = parametros.get("EMPRESA_ID") == null ? null : (Integer) parametros.get("EMPRESA_ID");
				Date dataVendaInicial = parametros.get("dataVendaInicial") == null ? null : (Date) parametros.get("dataVendaInicial");
				Date dataVendaFinal = parametros.get("dataVendaFinal") == null ? null : (Date) parametros.get("dataVendaFinal");
				Date dataDevolucaoInicial = parametros.get("dataDevolucaoInicial") == null ? null : (Date) parametros.get("dataDevolucaoInicial");
				Date dataDevolucaoFinal = parametros.get("dataDevolucaoFinal") == null ? null : (Date) parametros.get("dataDevolucaoFinal");
				Boolean isApenasBilhetesImpressos = parametros.get("isApenasBilhetesImpressos") == null ? Boolean.FALSE : Boolean.valueOf(parametros.get("isApenasBilhetesImpressos").toString());
				Boolean isBpe = (Boolean) parametros.get("isBpe");
				Boolean isNoXML = (Boolean) parametros.get("isConsultaOtimizada");

				String puntoVentas = null;
				for (PuntoVenta pv : lsPuntoVenta) {
					if (lsPuntoVenta.indexOf(pv) == 0) {
						puntoVentas = "" + pv.getPuntoventaId();
					} else {
						puntoVentas += ", " + pv.getPuntoventaId();
					}
				}

				String estados = null;
				for (Estado e : lsEstado) {
					if (lsEstado.indexOf(e) == 0) {
						estados = "" + e.getEstadoId();
					} else {
						estados += ", " + e.getEstadoId();
					}
				}

				String sql = null;
				if (isBpe) {
					if (isNoXML) {
						sql = getSqlBpeNoXml(empresaId, puntoVentas, estados, dataVendaInicial, dataVendaFinal, dataDevolucaoInicial, dataDevolucaoFinal, isApenasBilhetesImpressos);
					} else {
						sql = getSqlBpeXml(empresaId, puntoVentas, estados, dataVendaInicial, dataVendaFinal, dataDevolucaoInicial, dataDevolucaoFinal, isApenasBilhetesImpressos);
					}

				} else {
					sql = getSql(empresaId, puntoVentas, estados, dataVendaInicial, dataVendaFinal, dataDevolucaoInicial, dataDevolucaoFinal, isApenasBilhetesImpressos);
				}
				log.info("Devolucao Bilhetes: " + sql);

				NamedParameterStatement stmt = new NamedParameterStatement(conexao, sql);
				ResultSet rset = null;

				if (dataVendaInicial != null && !isBpe) {
					stmt.setString("dataVendaInicial", DateUtil.getStringDate(dataVendaInicial, "dd/MM/yyyy HH:mm"));
				}

				if (dataVendaFinal != null && !isBpe) {
					stmt.setString("dataVendaFinal", DateUtil.getStringDate(dataVendaFinal, "dd/MM/yyyy HH:mm"));
				}

				if (dataDevolucaoInicial != null) {
					stmt.setString("dataDevolucaoInicial", DateUtil.getStringDate(dataDevolucaoInicial, "dd/MM/yyyy HH:mm"));
				}

				if (dataDevolucaoFinal != null) {
					stmt.setString("dataDevolucaoFinal", DateUtil.getStringDate(dataDevolucaoFinal, "dd/MM/yyyy HH:mm"));
				}

				rset = stmt.executeQuery();

				List<DevolucaoBilhetes> lsDev = new ArrayList<DevolucaoBilhetes>();
				while (rset.next()) {

					DevolucaoBilhetes db = new DevolucaoBilhetes();
					db.setAidf((String) rset.getObject("AIDF"));
					db.setNumFolioSistema((String) rset.getObject("NUMFOLIOSISTEMA"));
					db.setSerieSubSerie(isBpe ? (String) rset.getObject("TIPO_SIT") : (String) rset.getObject("SERIE_SUBSERIE"));
					db.setFolio((String) rset.getObject("FOLIO"));
					db.setUf((String) rset.getObject("UF"));
					db.setEstado((String) rset.getObject("ESTADO"));
					db.setEstadoId(rset.getInt("ESTADO_ID"));
					db.setFechorVenta((String) rset.getObject("FECHOR_VENTA"));
					db.setFechorDevolucao((String) rset.getObject("FECHOR_DEVOLUCAO"));
					db.setIcmsInterestadual(rset.getObject("ICMSINTERESTADUAL") != null ? rset.getBigDecimal("ICMSINTERESTADUAL") : BigDecimal.ZERO);
					db.setIcmsIntermunicipal(rset.getObject("ICMSINTERMUNICIPAL") != null ? rset.getBigDecimal("ICMSINTERMUNICIPAL") : BigDecimal.ZERO);
					db.setTributacaoimportacao(rset.getObject("TRIBUTACAOIMPORTACAO") != null ? rset.getBigDecimal("TRIBUTACAOIMPORTACAO") : null);
					db.setPorcredbaseicms(rset.getBigDecimal("PORCREDBASEICMS"));
					db.setPrecioBase(rset.getBigDecimal("PRECIOBASE"));
					db.setPrecioPagado(rset.getBigDecimal("PRECIOPAGADO"));
					db.setImporteoutros(rset.getBigDecimal("IMPORTEOUTROS"));
					db.setImportepedagio(rset.getBigDecimal("IMPORTEPEDAGIO"));
					db.setImporteseguro(rset.getBigDecimal("IMPORTESEGURO"));
					db.setImportetaxaembarque(rset.getBigDecimal("IMPORTETAXAEMBARQUE"));
					db.setIndPedagioMunicipal(rset.getInt("INDPEDAGIOMUNICIPAL") == 1);
					db.setIndSeguroMunicipal(rset.getInt("INDSEGUROMUNICIPAL") == 1);
					db.setIndTarifaMunicipal(rset.getInt("INDTARIFAMUNICIPAL") == 1);
					db.setIndTxEmbarqueMunicipal(rset.getInt("INDTXEMBARQUEMUNICIPAL") == 1);
					db.setIndPedadioEstdual(rset.getInt("INDPEDAGIOESTDUAL") == 1);
					db.setIndSeguroEstadual(rset.getInt("INDSEGUROESTADUAL") == 1);
					db.setIndTarifaEstadual(rset.getInt("INDTARIFAESTADUAL") == 1);
					db.setIndTxEmbarqueEstadual(rset.getInt("INDTXEMBARQUEESTADUAL") == 1);
					db.setEmpresaId(rset.getObject("EMPRESA_ID") == null ? null : ((BigDecimal) rset.getObject("EMPRESA_ID")).intValue());
					db.setEmpresa((String) rset.getObject("NOMB_EMPRESA"));
					db.setNumpuntoventa((String) rset.getObject("NUMPUNTOVENTA"));
					db.setNumpuntoventaOrigem((String) rset.getObject("NUMPUNTOVENTAORIGEM"));
					db.setIsenta(rset.getInt("ISENTA") == 1);
					db.setTotalBilhete(rset.getBigDecimal("TOTAL"));
					db.setValorIcms(BigDecimal.ZERO);
					db.setValorIsenta(BigDecimal.ZERO);
					db.setPorcMunicipal(rset.getBigDecimal("PORC_MUNICIPAL"));
					db.setPorcEstadual(rset.getBigDecimal("PORC_ESTADUAL"));

					if (isBpe) {
						bpeResultSet(rset, db, isNoXML);

					} else {

						boolean isEstadual = rset.getInt("IS_ESTADUAL") == 1;
						db.setEstadual(isEstadual);

						BigDecimal valorContabil = valorPassagem(db);
						db.setValorContabil(valorContabil);

						db.setValorOutras(BigDecimal.ZERO);

						BigDecimal isenta = valorIsenta(db);
						db.setValorIsenta(isenta);

						BigDecimal redBaseCalcIcms = BigDecimal.ZERO;
						redBaseCalcIcms = db.getPorcredbaseicms() == null ? BigDecimal.ZERO : db.getPorcredbaseicms().divide(UtiliteriasFiscal.CEM);

						BigDecimal tarifa = valorBaseCalculo(db);
						BigDecimal redutor = tarifa.multiply(redBaseCalcIcms);
						BigDecimal baseCalculoIcms = tarifa.subtract(redutor);

						BigDecimal aliquota = BigDecimal.ZERO;
						if (isEstadual) {
							aliquota = db.getTributacaoimportacao() == null ? db.getIcmsInterestadual() : db.getTributacaoimportacao();
						} else {
							aliquota = db.getTributacaoimportacao() == null ? db.getIcmsIntermunicipal() : db.getTributacaoimportacao();
						}

						BigDecimal valorIcms = baseCalculoIcms.multiply(aliquota.divide(UtiliteriasFiscal.CEM));

						db.setValorIcms(valorIcms);
						db.setBaseCalculoIcms(baseCalculoIcms);
						db.setEstornoEstadual(BigDecimal.ZERO);
						db.setEstornoMunicipal(BigDecimal.ZERO);

						if (isEstadual) {
							db.setEstornoEstadual(valorContabil);
						} else {
							db.setEstornoMunicipal(valorContabil);
						}
					}

					lsDev.add(db);
				}
				setLsDadosRelatorio(lsDev);
			}
		});

	}

	private void bpeResultSet(ResultSet rset, DevolucaoBilhetes db, boolean isNoXML) throws SQLException {

		if (isNoXML) {
			db.setChbpe(rset.getString("CHBPE"));
			db.setChbpeSubstituicao(rset.getString("CHBPE_SUBSTITUICAO"));
			db.setCmunini(rset.getString("CMUNINI"));
			db.setCmunfim(rset.getString("CMUNFIM"));
			db.setUfini(rset.getString("UFINI"));
			db.setUffim(rset.getString("UFFIM"));
			db.setNbp(rset.getString("NBP"));
			db.setDhemb(rset.getString("DHEMB"));
			db.setCst00(rset.getString("CST00"));
			db.setCst20(rset.getString("CST20"));
			db.setCst45(rset.getString("CST45"));
			db.setCst90(rset.getString("CST90"));
			db.setCstoutrauf(rset.getString("CSTOUTRAUF"));
			db.setCstsn(rset.getString("CSTSN"));
			db.setVbc00(rset.getString("VBC00"));
			db.setPicms00(rset.getString("PICMS00"));
			db.setVicms00(rset.getString("VICMS00"));
			db.setVbc20(rset.getString("VBC20"));
			db.setPicms20(rset.getString("PICMS20"));
			db.setVicms20(rset.getString("VICMS20"));
			db.setVbp(rset.getString("VBP"));
			db.setVdesconto(rset.getString("VDESCONTO"));
			db.setVpgto(rset.getString("VPGTO"));
			db.setTpcomp01(rset.getString("TPCOMP01"));
			db.setTpcomp02(rset.getString("TPCOMP02"));
			db.setTpcomp03(rset.getString("TPCOMP03"));
			db.setTpcomp04(rset.getString("TPCOMP04"));
			db.setTpcomp05(rset.getString("TPCOMP05"));
			db.setTpcomp06(rset.getString("TPCOMP06"));
			db.setTpcomp99(rset.getString("TPCOMP99"));
			db.setVcomp01(rset.getString("VCOMP01"));
			db.setVcomp02(rset.getString("VCOMP02"));
			db.setVcomp03(rset.getString("VCOMP03"));
			db.setVcomp04(rset.getString("VCOMP04"));
			db.setVcomp05(rset.getString("VCOMP05"));
			db.setVcomp06(rset.getString("VCOMP06"));
			db.setVcomp99(rset.getString("VCOMP99"));
			db.setpRedBC(rset.getString("PREDBC"));

			String estadoOrigem = db.getUfini();
			String estadoDestino = db.getUffim();

			boolean isInterEstadual = !estadoOrigem.equals(estadoDestino);

			String vBC = null;
			String pICMS = null;
			String vICMS = null;
			String pRedBC = null;

			if (StringUtils.isNotBlank(db.getPicms00())) {
				vBC = db.getVbc00();
				pICMS = db.getPicms00();
				vICMS = db.getVicms00();
			} else if (StringUtils.isNotBlank(db.getPicms20())) {
				vBC = db.getVbc20();
				pICMS = db.getPicms20();
				vICMS = db.getVicms20();
				pRedBC = db.getpRedBC();
			}

			String vPgto = db.getVpgto();
			BigDecimal valorContabil = new BigDecimal(vPgto == null ? "0.0" : vPgto);
			db.setValorContabil(valorContabil);

			BigDecimal valorIsenta = BigDecimal.ZERO;

			BigDecimal pedagio = new BigDecimal(db.getVcomp02() == null ? "0.0" : db.getVcomp02());
			BigDecimal pedagioIsento = isInterEstadual && !db.getIndPedadioEstdual() ? pedagio : BigDecimal.ZERO;
			if (pedagioIsento.compareTo(BigDecimal.ZERO) == 0)
				pedagioIsento = !isInterEstadual && !db.getIndPedagioMunicipal() ? pedagio : BigDecimal.ZERO;

			BigDecimal taxaEmbarque = new BigDecimal(db.getVcomp03() == null ? "0.0" : db.getVcomp03());
			BigDecimal taxaEmbarqueIsento = isInterEstadual && !db.getIndTxEmbarqueEstadual() ? taxaEmbarque : BigDecimal.ZERO;
			if (taxaEmbarqueIsento.compareTo(BigDecimal.ZERO) == 0)
				taxaEmbarqueIsento = !isInterEstadual && !db.getIndTxEmbarqueMunicipal() ? taxaEmbarque : BigDecimal.ZERO;

			BigDecimal seguro = new BigDecimal(db.getVcomp04() == null ? "0.0" : db.getVcomp04());
			BigDecimal seguroIsento = isInterEstadual && !db.getIndSeguroEstadual() ? seguro : BigDecimal.ZERO;
			if (seguroIsento.compareTo(BigDecimal.ZERO) == 0)
				seguroIsento = isInterEstadual && !db.getIndSeguroMunicipal() ? seguro : BigDecimal.ZERO;

			valorIsenta = MoneyHelper.somar(valorIsenta, pedagioIsento, taxaEmbarqueIsento, seguroIsento);

			BigDecimal baseCalculoICMS = new BigDecimal(vBC == null ? "0.0" : vBC);
			db.setBaseCalculoIcms(baseCalculoICMS);

			BigDecimal icms = new BigDecimal(pICMS == null ? "0.0" : pICMS);
			db.setAliquota(icms);
			BigDecimal valorIcms = new BigDecimal(vICMS == null ? "0.0" : vICMS);
			db.setValorIcms(valorIcms);

			BigDecimal outras = new BigDecimal(pRedBC == null ? "0.0" : pRedBC);
			if (pRedBC != null) {
				outras = MoneyHelper.subtrair(valorContabil, baseCalculoICMS);
				outras = MoneyHelper.subtrair(outras, valorIsenta);
			}

			db.setValorOutras(outras);
			db.setValorIsenta(valorIsenta);
			db.setEstornoEstadual(BigDecimal.ZERO);
			db.setEstornoMunicipal(BigDecimal.ZERO);

			if (isInterEstadual) {
				db.setEstornoEstadual(valorContabil);
			} else {
				db.setEstornoMunicipal(valorContabil);
			}

		} else {

			db.setChbpe((String) rset.getObject("CHBPE"));
			db.setChbpeSubstituicao((String) rset.getObject("CHBPE_SUBSTITUICAO"));
			String xml = null;

			String xml_bpe = rset.getNString("XML_BPE");
			String xml_bpe_2 = rset.getNString("XML_BPE_2");
			String xml_bpe_3 = rset.getNString("XML_BPE_3");
			xml = StringUtils.join(new String[] { xml_bpe, xml_bpe_2, xml_bpe_3 });

			BigDecimal valorContabil = BigDecimal.ZERO;
			BigDecimal baseCalculoICMS = BigDecimal.ZERO;
			BigDecimal valorIsenta = BigDecimal.ZERO;

			TBPe tbpe = null;
			if (StringUtils.isNotBlank(xml))
				tbpe = BPeUtil.convertXmlToBpe(xml);

			String estadoOrigem = (StringUtils.isNotBlank(xml) ? tbpe.getInfBPe().getIde().getUFIni().value() : db.getUf());
			String estadoDestino = (StringUtils.isNotBlank(xml) ? tbpe.getInfBPe().getIde().getUFFim().value() : db.getUf());
			boolean isEstadual = !estadoOrigem.equals(estadoDestino);

			String vBC = null;
			String pICMS = null;
			String vICMS = null;
			String pRedBC = null;

			if (StringUtils.isNotBlank(xml)) {
				if (tbpe.getInfBPe().getImp().getICMS().getICMS00() != null) {
					vBC = tbpe.getInfBPe().getImp().getICMS().getICMS00().getVBC();
					pICMS = tbpe.getInfBPe().getImp().getICMS().getICMS00().getPICMS();
					vICMS = tbpe.getInfBPe().getImp().getICMS().getICMS00().getVICMS();
				} else if (tbpe.getInfBPe().getImp().getICMS().getICMS20() != null) {
					vBC = tbpe.getInfBPe().getImp().getICMS().getICMS20().getVBC();
					pICMS = tbpe.getInfBPe().getImp().getICMS().getICMS20().getPICMS();
					vICMS = tbpe.getInfBPe().getImp().getICMS().getICMS20().getVICMS();
					pRedBC = tbpe.getInfBPe().getImp().getICMS().getICMS20().getPRedBC();
				}

				if (tbpe.getInfBPe().getInfValorBPe() != null) {

					String vPgto = tbpe.getInfBPe().getInfValorBPe().getVPgto();
					valorContabil = new BigDecimal(vPgto == null ? "0.0" : vPgto);

					for (TBPe.InfBPe.InfValorBPe.Comp comp : tbpe.getInfBPe().getInfValorBPe().getComp()) {
						if (comp.getTpComp().equals(TipoComp.PEDAGIO)) {
							valorIsenta = valorIsenta.add(isEstadual && !db.getIndPedadioEstdual() ? new BigDecimal(comp.getVComp() == null ? "0.0" : comp.getVComp()) : BigDecimal.ZERO);
							valorIsenta = valorIsenta.add(!isEstadual && !db.getIndPedagioMunicipal() ? new BigDecimal(comp.getVComp() == null ? "0.0" : comp.getVComp()) : BigDecimal.ZERO);
						}

						if (comp.getTpComp().equals(TipoComp.TAXA_EMBARQUE)) {
							valorIsenta = valorIsenta.add(isEstadual && !db.getIndTxEmbarqueEstadual() ? new BigDecimal(comp.getVComp() == null ? "0.0" : comp.getVComp()) : BigDecimal.ZERO);
							valorIsenta = valorIsenta.add(!isEstadual && !db.getIndTxEmbarqueMunicipal() ? new BigDecimal(comp.getVComp() == null ? "0.0" : comp.getVComp()) : BigDecimal.ZERO);
						}

						if (comp.getTpComp().equals(TipoComp.SEGURO)) {
							valorIsenta = valorIsenta.add(isEstadual && !db.getIndSeguroEstadual() ? new BigDecimal(comp.getVComp() == null ? "0.0" : comp.getVComp()) : BigDecimal.ZERO);
							valorIsenta = valorIsenta.add(!isEstadual && !db.getIndSeguroMunicipal() ? new BigDecimal(comp.getVComp() == null ? "0.0" : comp.getVComp()) : BigDecimal.ZERO);
						}
					}
				}
			}

			db.setValorContabil(valorContabil);

			baseCalculoICMS = new BigDecimal(vBC == null ? "0.0" : vBC);
			db.setBaseCalculoIcms(baseCalculoICMS);

			BigDecimal icms = new BigDecimal(pICMS == null ? "0.0" : pICMS);
			db.setAliquota(icms);
			BigDecimal valorIcms = new BigDecimal(vICMS == null ? "0.0" : vICMS);
			db.setValorIcms(valorIcms);

			BigDecimal outras = new BigDecimal(pRedBC == null ? "0.0" : pRedBC);
			if (pRedBC != null) {
				outras = MoneyHelper.subtrair(valorContabil, baseCalculoICMS);
				outras = MoneyHelper.subtrair(outras, valorIsenta);
			}

			db.setValorOutras(outras);
			db.setValorIsenta(valorIsenta);
			db.setEstornoEstadual(BigDecimal.ZERO);
			db.setEstornoMunicipal(BigDecimal.ZERO);

			if (isEstadual) {
				db.setEstornoEstadual(valorContabil);
			} else {
				db.setEstornoMunicipal(valorContabil);
			}
		}
	}

	private BigDecimal valorBaseCalculo(DevolucaoBilhetes det) {
		BigDecimal total = BigDecimal.ZERO;
		total = total.add(det.getPrecioPagado() == null ? BigDecimal.ZERO : det.getPrecioPagado());

		if (det.isEstadual() && det.getIndTxEmbarqueEstadual() || !det.isEstadual() && det.getIndTxEmbarqueMunicipal())
			total = total.add(det.getImportetaxaembarque() == null ? BigDecimal.ZERO : det.getImportetaxaembarque());

		if (det.isEstadual() && det.getIndPedadioEstdual() || !det.isEstadual() && det.getIndPedagioMunicipal())
			total = total.add(det.getImportepedagio() == null ? BigDecimal.ZERO : det.getImportepedagio());

		if (det.isEstadual() && det.getIndSeguroEstadual() || !det.isEstadual() && det.getIndSeguroMunicipal())
			total = total.add(det.getImporteseguro() == null ? BigDecimal.ZERO : det.getImporteseguro());

		return total;
	}

	private BigDecimal valorIsenta(DevolucaoBilhetes det) {
		BigDecimal total = BigDecimal.ZERO;
		// if (det.isEstadual() && !det.getIndTxEmbarqueEstadual() || !det.isEstadual() && !det.getIndTxEmbarqueMunicipal())
		// total = total.add(det.getImportetaxaembarque() == null ? BigDecimal.ZERO : det.getImportetaxaembarque());
		//
		// if (det.isEstadual() && !det.getIndPedadioEstdual() || !det.isEstadual() && !det.getIndPedagioMunicipal())
		// total = total.add(det.getImportepedagio() == null ? BigDecimal.ZERO : det.getImportepedagio());
		//
		// if (det.isEstadual() && !det.getIndSeguroEstadual() || !det.isEstadual() && !det.getIndSeguroMunicipal())
		// total = total.add(det.getImporteseguro() == null ? BigDecimal.ZERO : det.getImporteseguro());
		return total;
	}

	private BigDecimal valorPassagem(DevolucaoBilhetes det) {
		BigDecimal total = BigDecimal.ZERO;
		total = total.add(det.getPrecioPagado() == null ? BigDecimal.ZERO : det.getPrecioPagado());

		// total = total.add(det.getImportetaxaembarque() == null ? BigDecimal.ZERO : det.getImportetaxaembarque());
		// total = total.add(det.getImportepedagio() == null ? BigDecimal.ZERO : det.getImportepedagio());
		// total = total.add(det.getImporteseguro() == null ? BigDecimal.ZERO : det.getImporteseguro());

		return total;
	}

	public void setLsDadosRelatorio(List<DevolucaoBilhetes> lsDev) {
		this.setCollectionDataSource(new JRBeanCollectionDataSource(lsDev));
	}

	private String getSqlBpeNoXml(Integer empresaId, String puntoVentas, String estados, Date dataVendaInicial, Date dataVendaFinal, Date dataDevolucaoInicial, Date dataDevolucaoFinal, Boolean isApenasBilhetesImpressos) {

		StringBuilder sql = new StringBuilder();
		sql.append("SELECT DISTINCT ");
		sql.append("  TO_CHAR(COALESCE(BANT.FECCREACION, B.FECCREACION), 'DD/MM/YYYY') AS FECHOR_VENTA, ");
		sql.append("  TO_CHAR(BORI.FECCREACION, 'DD/MM/YYYY') AS FECHOR_DEVOLUCAO, ");
		sql.append("  COALESCE(AIDF.DOCFISCAL, COALESCE(BORI.SERIEIMPFISCALORIGINAL, B.SERIEIMPFISCALORIGINAL), ");
		sql.append("  COALESCE(BORI.SERIEIMPFISCAL, B.SERIEIMPFISCAL)) AS AIDF, ");
		sql.append("  COALESCE(BORI.NUM_BPE, BANT.NUM_BPE) AS NUMFOLIOSISTEMA, ");
		sql.append("  CASE WHEN COALESCE(BORI.SERIEIMPFISCALORIGINAL,BORI.SERIEIMPFISCAL) IS NOT NULL THEN NULL ");
		sql.append("  										ELSE AIDF.SERIE || COALESCE(AIDF.SUBSERIE, '') END AS SERIE_SUBSERIE, ");
		sql.append("  COALESCE(BORI.NUMFOLIOPREIMPRESO, B.NUMFOLIOPREIMPRESO) AS FOLIO, ");
		sql.append("  COALESCE(BORI.PRECIOBASE ,B.PRECIOBASE) AS PRECIOBASE, ");
		sql.append("  E.NOMBEMPRESA AS NOMB_EMPRESA, ");
		sql.append("  E.EMPRESA_ID AS EMPRESA_ID, ");
		sql.append("  PTV.NUMPUNTOVENTA AS NUMPUNTOVENTA, ");
		sql.append("  PTVO.NUMPUNTOVENTA AS NUMPUNTOVENTAORIGEM, ");
		sql.append("  EST_BPE.NOMBESTADO AS ESTADO, ");
		sql.append("  EST_BPE.CVEESTADO AS UF, ");
		sql.append("  EST_BPE.ESTADO_ID AS ESTADO_ID, ");
		sql.append("  '' AS UF_CORRIDA, ");
		sql.append("  COALESCE(EI.ICMS, EST_BPE.ICMS) AS ICMSINTERESTADUAL, ");
		sql.append("  NVL(EI.ICMSIM,0) AS ICMSINTERMUNICIPAL, ");
		sql.append("  EI.TRIBUTACAOIMPORTACAO AS TRIBUTACAOIMPORTACAO, ");
		sql.append("  NVL(EI.PORCREDBASEICMS,0) AS PORCREDBASEICMS, ");
		sql.append("  0 AS IS_ESTADUAL, ");
		sql.append("  NVL(EI.PORCREDMUNICIPAL,0) AS PORC_MUNICIPAL, ");
		sql.append("  NVL(EI.PORCREDESTADUAL,0) AS PORC_ESTADUAL, ");
		sql.append("  0 AS ISENTA, ");
		sql.append("  NVL(B.PRECIOPAGADO,0) AS PRECIOPAGADO, NVL(B.IMPORTEOUTROS,0) AS IMPORTEOUTROS, NVL(B.IMPORTEPEDAGIO,0) AS IMPORTEPEDAGIO, NVL(B.IMPORTESEGURO,0) AS IMPORTESEGURO, NVL(B.IMPORTETAXAEMBARQUE,0) AS IMPORTETAXAEMBARQUE, ");
		sql.append("  NVL(EI.INDTARIFAMUNICIPAL,0) AS INDTARIFAMUNICIPAL, NVL(EI.INDSEGUROMUNICIPAL,0) AS INDSEGUROMUNICIPAL, NVL(EI.INDTXEMBARQUEMUNICIPAL,0) AS INDTXEMBARQUEMUNICIPAL, NVL(EI.INDPEDAGIOMUNICIPAL,0) AS INDPEDAGIOMUNICIPAL, ");
		sql.append("  NVL(EI.INDTARIFAESTADUAL,0) AS INDTARIFAESTADUAL, NVL(EI.INDSEGUROESTADUAL,0) AS INDSEGUROESTADUAL, NVL(EI.INDTXEMBARQUEESTADUAL,0) AS INDTXEMBARQUEESTADUAL, NVL(EI.INDPEDAGIOESTDUAL,0) AS INDPEDAGIOESTDUAL, ");
		sql.append("  NVL(B.PRECIOPAGADO,0) + NVL(B.IMPORTEOUTROS,0) + NVL(B.IMPORTEPEDAGIO,0) + NVL(B.IMPORTESEGURO,0) + NVL(B.IMPORTETAXAEMBARQUE,0) AS TOTAL, ");
		sql.append("  BPE.TIPOSUBSTITUICAO, ");
		sql.append("  CASE WHEN BPE.TIPOEVENTO = 110111 THEN 'CANCELAMENTO' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '1' THEN 'REMARCACAO' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '2' THEN 'TRANSFERENCIA' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '3' THEN 'TRANSFERENCIA/REMARCACAO' ELSE '' END AS TIPO_SIT, ");
		sql.append("  BPEORI.CHBPE AS CHBPE, ");
		sql.append("  BPE.CHBPE AS CHBPE_SUBSTITUICAO, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.CMUNINI ELSE BPEORI.CMUNINI END AS CMUNINI, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.CMUNFIM ELSE BPEORI.CMUNFIM END AS CMUNFIM, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.UFINI ELSE BPEORI.UFINI END AS UFINI, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.UFFIM ELSE BPEORI.UFFIM END AS UFFIM, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.NBP  ELSE BPEORI.NBP  END AS NBP, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.DHEMB ELSE BPEORI.DHEMB END AS DHEMB, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.CST00 ELSE BPEORI.CST00 END AS CST00, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.CST20 ELSE BPEORI.CST20 END AS CST20, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.CST45 ELSE BPEORI.CST45 END AS CST45, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.CST90 ELSE BPEORI.CST90 END AS CST90, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.CSTOUTRAUF ELSE BPEORI.CSTOUTRAUF END AS CSTOUTRAUF, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.CSTSN ELSE BPEORI.CSTSN END AS CSTSN, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VBC00 ELSE BPEORI.VBC00 END AS VBC00, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.PICMS00 ELSE BPEORI.PICMS00 END AS PICMS00, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VICMS00 ELSE BPEORI.VICMS00 END AS VICMS00, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VBC20 ELSE BPEORI.VBC20 END AS VBC20, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.PICMS20 ELSE BPEORI.PICMS20 END AS PICMS20, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VICMS20 ELSE BPEORI.VICMS20 END AS VICMS20, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VBP ELSE BPEORI.VBP END AS VBP, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VDESCONTO ELSE BPEORI.VDESCONTO END AS VDESCONTO, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VPGTO ELSE BPEORI.VPGTO END AS VPGTO, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP01 ELSE BPEORI.TPCOMP01 END AS TPCOMP01, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP02 ELSE BPEORI.TPCOMP02 END AS TPCOMP02, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP03 ELSE BPEORI.TPCOMP03 END AS TPCOMP03, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP04 ELSE BPEORI.TPCOMP04 END AS TPCOMP04, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP05 ELSE BPEORI.TPCOMP05 END AS TPCOMP05, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP06 ELSE BPEORI.TPCOMP06 END AS TPCOMP06, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP99 ELSE BPEORI.TPCOMP99 END AS TPCOMP99, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP01 ELSE BPEORI.VCOMP01 END AS VCOMP01, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP02 ELSE BPEORI.VCOMP02 END AS VCOMP02, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP03 ELSE BPEORI.VCOMP03 END AS VCOMP03, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP04 ELSE BPEORI.VCOMP04 END AS VCOMP04, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP05 ELSE BPEORI.VCOMP05 END AS VCOMP05, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP06 ELSE BPEORI.VCOMP06 END AS VCOMP06, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP99 ELSE BPEORI.VCOMP99 END AS VCOMP99, ");
		sql.append("  CASE WHEN BPE.UFINI IS NOT NULL THEN BPE.PREDBC ELSE BPEORI.PREDBC END AS PREDBC ");
		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("  JOIN INSCRICAO_ESTADUAL IE ON E.EMPRESA_ID = IE.EMPRESA_ID ");
		sql.append("               			   AND IE.ESTADO_ID = EST_BPE.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 = EST_BPE.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 (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 not in('110115','110116') OR BPE.TIPOEVENTO IS NULL) ");
		sql.append("    AND (BPEORI.CODSTAT IN ('-1','100','101','102','135','150') AND BPEORI.TIPOEVENTO not in('110115','110116')OR BPEORI.TIPOEVENTO IS NULL)  ");
		sql.append("   and (bpe.xmlregular is not null or bpe.xmlcontingencia is not null) ");
		if (dataDevolucaoInicial != null) {
			sql.append("AND BORI.FECCREACION >= TO_DATE(:dataDevolucaoInicial,'DD/MM/YYYY HH24:MI') ");
		}

		if (dataDevolucaoFinal != null) {
			sql.append("AND BORI.FECCREACION <= TO_DATE(:dataDevolucaoFinal,'DD/MM/YYYY HH24:MI') ");
		}

		sql.append(estados == null ? "" : "AND EST_BPE.ESTADO_ID IN (" + estados + ") ");
		sql.append(puntoVentas == null ? "" : "AND PTV.PUNTOVENTA_ID IN (" + puntoVentas + ") ");
		sql.append(empresaId == null ? "" : "AND E.EMPRESA_ID IN (" + empresaId + ") ");

		sql.append("  UNION ALL ");

		sql.append("SELECT DISTINCT ");
		sql.append("  TO_CHAR(COALESCE(BANT.FECCREACION, B.FECCREACION), 'DD/MM/YYYY') AS FECHOR_VENTA, ");
		sql.append("  TO_CHAR(BORI.FECCREACION, 'DD/MM/YYYY') AS FECHOR_DEVOLUCAO, ");
		sql.append("  COALESCE(AIDF.DOCFISCAL, COALESCE(BORI.SERIEIMPFISCALORIGINAL, B.SERIEIMPFISCALORIGINAL), ");
		sql.append("  COALESCE(BORI.SERIEIMPFISCAL, B.SERIEIMPFISCAL)) AS AIDF, ");
		sql.append("  COALESCE(BANT.NUM_BPE, B.NUM_BPE, B.NUMFOLIOSISTEMA, B.NUMOPERACION) AS NUMFOLIOSISTEMA, ");
		sql.append("  CASE WHEN COALESCE(BORI.SERIEIMPFISCALORIGINAL,BORI.SERIEIMPFISCAL) IS NOT NULL THEN NULL ");
		sql.append("  	      ELSE AIDF.SERIE || COALESCE(AIDF.SUBSERIE, '') END AS SERIE_SUBSERIE, ");
		sql.append("  COALESCE(BANT.NUMFOLIOPREIMPRESO, B.NUMFOLIOPREIMPRESO) AS FOLIO, ");
		sql.append("  COALESCE(BANT.PRECIOBASE ,B.PRECIOBASE) AS PRECIOBASE, ");
		sql.append("  E.NOMBEMPRESA AS NOMB_EMPRESA, ");
		sql.append("  E.EMPRESA_ID AS EMPRESA_ID, ");
		sql.append("  PTV.NUMPUNTOVENTA AS NUMPUNTOVENTA, ");
		sql.append("  PTVO.NUMPUNTOVENTA AS NUMPUNTOVENTAORIGEM, ");
		sql.append("  EST_BPE.NOMBESTADO AS ESTADO, ");
		sql.append("  EST_BPE.CVEESTADO AS UF, ");
		sql.append("  EST_BPE.ESTADO_ID AS ESTADO_ID, ");
		sql.append("  '' AS UF_CORRIDA, ");
		sql.append("  COALESCE(EI.ICMS, EST_BPE.ICMS) AS ICMSINTERESTADUAL, ");
		sql.append("  NVL(EI.ICMSIM,0) AS ICMSINTERMUNICIPAL, ");
		sql.append("  EI.TRIBUTACAOIMPORTACAO AS TRIBUTACAOIMPORTACAO, ");
		sql.append("  NVL(EI.PORCREDBASEICMS,0) AS PORCREDBASEICMS, ");
		sql.append("  0 AS IS_ESTADUAL, ");
		sql.append("  NVL(EI.PORCREDMUNICIPAL,0) AS PORC_MUNICIPAL, ");
		sql.append("  NVL(EI.PORCREDESTADUAL,0) AS PORC_ESTADUAL, ");
		sql.append("  0 AS ISENTA, ");
		sql.append("  NVL(B.PRECIOPAGADO,0) AS PRECIOPAGADO, NVL(B.IMPORTEOUTROS,0) AS IMPORTEOUTROS, NVL(B.IMPORTEPEDAGIO,0) AS IMPORTEPEDAGIO, NVL(B.IMPORTESEGURO,0) AS IMPORTESEGURO, NVL(B.IMPORTETAXAEMBARQUE,0) AS IMPORTETAXAEMBARQUE, ");
		sql.append("  NVL(EI.INDTARIFAMUNICIPAL,0) AS INDTARIFAMUNICIPAL, NVL(EI.INDSEGUROMUNICIPAL,0) AS INDSEGUROMUNICIPAL, NVL(EI.INDTXEMBARQUEMUNICIPAL,0) AS INDTXEMBARQUEMUNICIPAL, NVL(EI.INDPEDAGIOMUNICIPAL,0) AS INDPEDAGIOMUNICIPAL, ");
		sql.append("  NVL(EI.INDTARIFAESTADUAL,0) AS INDTARIFAESTADUAL, NVL(EI.INDSEGUROESTADUAL,0) AS INDSEGUROESTADUAL, NVL(EI.INDTXEMBARQUEESTADUAL,0) AS INDTXEMBARQUEESTADUAL, NVL(EI.INDPEDAGIOESTDUAL,0) AS INDPEDAGIOESTDUAL, ");
		sql.append("  NVL(B.PRECIOPAGADO,0) + NVL(B.IMPORTEOUTROS,0) + NVL(B.IMPORTEPEDAGIO,0) + NVL(B.IMPORTESEGURO,0) + NVL(B.IMPORTETAXAEMBARQUE,0) AS TOTAL, ");
		sql.append("  BPE.TIPOSUBSTITUICAO, ");
		sql.append("  CASE WHEN BPE.TIPOEVENTO = 110111 THEN 'CANCELAMENTO' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '1' THEN 'REMARCACAO' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '2' THEN 'TRANSFERENCIA' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '3' THEN 'TRANSFERENCIA/REMARCACAO' ELSE '' END AS TIPO_SIT, ");
		sql.append("  BPE.CHBPE AS CHBPE, ");
		sql.append("  '' AS CHBPE_SUBSTITUICAO, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.CMUNINI WHEN BPE.UFINI IS NOT NULL THEN BPE.CMUNINI ELSE BPEORI.CMUNINI END AS CMUNINI, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.CMUNFIM WHEN BPE.UFINI IS NOT NULL THEN BPE.CMUNFIM ELSE BPEORI.CMUNFIM END AS CMUNFIM, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.UFINI WHEN BPE.UFINI IS NOT NULL THEN BPE.UFINI ELSE BPEORI.UFINI END AS UFINI, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.UFFIM WHEN BPE.UFINI IS NOT NULL THEN BPE.UFFIM ELSE BPEORI.UFFIM END AS UFFIM, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.NBP WHEN BPE.UFINI IS NOT NULL THEN BPE.NBP ELSE BPEORI.NBP END AS NBP, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.DHEMB WHEN BPE.UFINI IS NOT NULL THEN BPE.DHEMB ELSE BPEORI.DHEMB END AS DHEMB, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.CST00 WHEN BPE.UFINI IS NOT NULL THEN BPE.CST00 ELSE BPEORI.CST00 END AS CST00, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.CST20 WHEN BPE.UFINI IS NOT NULL THEN BPE.CST20 ELSE BPEORI.CST20 END AS CST20, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.CST45 WHEN BPE.UFINI IS NOT NULL THEN BPE.CST45 ELSE BPEORI.CST45 END AS CST45, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.CST90 WHEN BPE.UFINI IS NOT NULL THEN BPE.CST90 ELSE BPEORI.CST90 END AS CST90, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.CSTOUTRAUF WHEN BPE.UFINI IS NOT NULL THEN BPE.CSTOUTRAUF ELSE BPEORI.CSTOUTRAUF END AS CSTOUTRAUF, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.CSTSN WHEN BPE.UFINI IS NOT NULL THEN BPE.CSTSN ELSE BPEORI.CSTSN END AS CSTSN, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VBC00 WHEN BPE.UFINI IS NOT NULL THEN BPE.VBC00 ELSE BPEORI.VBC00 END AS VBC00, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.PICMS00 WHEN BPE.UFINI IS NOT NULL THEN BPE.PICMS00 ELSE BPEORI.PICMS00 END AS PICMS00, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VICMS00 WHEN BPE.UFINI IS NOT NULL THEN BPE.VICMS00 ELSE BPEORI.VICMS00 END AS VICMS00, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VBC20 WHEN BPE.UFINI IS NOT NULL THEN BPE.VBC20 ELSE BPEORI.VBC20 END AS VBC20, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.PICMS20 WHEN BPE.UFINI IS NOT NULL THEN BPE.PICMS20 ELSE BPEORI.PICMS20 END AS PICMS20, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VICMS20 WHEN BPE.UFINI IS NOT NULL THEN BPE.VICMS20 ELSE BPEORI.VICMS20 END AS VICMS20, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VBP WHEN BPE.UFINI IS NOT NULL THEN BPE.VBP ELSE BPEORI.VBP END AS VBP, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VDESCONTO WHEN BPE.UFINI IS NOT NULL THEN BPE.VDESCONTO ELSE BPEORI.VDESCONTO END AS VDESCONTO, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VPGTO WHEN BPE.UFINI IS NOT NULL THEN BPE.VPGTO ELSE BPEORI.VPGTO END AS VPGTO, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.TPCOMP01 WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP01 ELSE BPEORI.TPCOMP01 END AS TPCOMP01, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.TPCOMP02 WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP02 ELSE BPEORI.TPCOMP02 END AS TPCOMP02, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.TPCOMP03 WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP03 ELSE BPEORI.TPCOMP03 END AS TPCOMP03, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.TPCOMP04 WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP04 ELSE BPEORI.TPCOMP04 END AS TPCOMP04, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.TPCOMP05 WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP05 ELSE BPEORI.TPCOMP05 END AS TPCOMP05, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.TPCOMP06 WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP06 ELSE BPEORI.TPCOMP06 END AS TPCOMP06, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.TPCOMP99 WHEN BPE.UFINI IS NOT NULL THEN BPE.TPCOMP99 ELSE BPEORI.TPCOMP99 END AS TPCOMP99, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VCOMP01 WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP01 ELSE BPEORI.VCOMP01 END AS VCOMP01, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VCOMP02 WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP02 ELSE BPEORI.VCOMP02 END AS VCOMP02, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VCOMP03 WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP03 ELSE BPEORI.VCOMP03 END AS VCOMP03, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VCOMP04 WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP04 ELSE BPEORI.VCOMP04 END AS VCOMP04, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VCOMP05 WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP05 ELSE BPEORI.VCOMP05 END AS VCOMP05, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VCOMP06 WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP06 ELSE BPEORI.VCOMP06 END AS VCOMP06, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.VCOMP99 WHEN BPE.UFINI IS NOT NULL THEN BPE.VCOMP99 ELSE BPEORI.VCOMP99 END AS VCOMP99, ");
		sql.append("  CASE WHEN BPEANT.UFINI IS NOT NULL THEN BPEANT.PREDBC WHEN BPE.UFINI IS NOT NULL THEN BPE.PREDBC ELSE BPEORI.PREDBC END AS PREDBC ");
		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 AND BPE.ACTIVO = 1 ");
		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 AND BORI.TIPOVENTA_ID NOT IN (5,12,18,81,82,49,41)) THEN  BORI.BOLETOANTERIOR_ID ELSE BORI.BOLETOORIGINAL_ID END) ");
		sql.append("  LEFT JOIN BPE BPEORI ON B.BOLETO_ID = BPEORI.BOLETO_ID AND BPEORI.ACTIVO = 1 ");
		sql.append("  INNER JOIN PUNTO_VENTA PTV ON PTV.PUNTOVENTA_ID = BORI.PUNTOVENTA_ID ");
		sql.append("JOIN INSCRICAO_ESTADUAL IE ON E.EMPRESA_ID = IE.EMPRESA_ID ");
		sql.append("               			   AND IE.ESTADO_ID = EST_BPE.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 =EST_BPE.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 COALESCE(BPE.TIPOEVENTO, BPEORI.TIPOEVENTO) IS NOT NULL THEN ");
		sql.append("     COALESCE(BORI.BOLETOANTERIOR_ID, B.BOLETOANTERIOR_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 ('101','135') ");
		sql.append("    	AND TO_CHAR(COALESCE(BANT.FECCREACION, 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 not in('110115','110116') OR BPE.TIPOEVENTO IS NULL) ");
		sql.append("    AND (BPEORI.CODSTAT IN ('-1','100','101','102','135','150') AND BPEORI.TIPOEVENTO not in('110115','110116') OR BPEORI.TIPOEVENTO IS NULL) ");
		if (dataDevolucaoInicial != null) {
			sql.append("AND BORI.FECCREACION >= TO_DATE(:dataDevolucaoInicial,'DD/MM/YYYY HH24:MI') ");
		}

		if (dataDevolucaoFinal != null) {
			sql.append("AND BORI.FECCREACION <= TO_DATE(:dataDevolucaoFinal,'DD/MM/YYYY HH24:MI') ");
		}
		sql.append("   and (bpe.xmlregular is not null or bpe.xmlcontingencia is not null) ");

		sql.append(estados == null ? "" : "AND EST_BPE.ESTADO_ID IN (" + estados + ") ");
		sql.append(puntoVentas == null ? "" : "AND PTV.PUNTOVENTA_ID IN (" + puntoVentas + ") ");
		sql.append(empresaId == null ? "" : "AND E.EMPRESA_ID IN (" + empresaId + ") ");

		sql.append("ORDER BY NOMB_EMPRESA, ESTADO, UF, FECHOR_DEVOLUCAO, NUMFOLIOSISTEMA");

		return sql.toString();
	}

	@Deprecated
	private String getSqlBpeXml(Integer empresaId, String puntoVentas, String estados, Date dataVendaInicial, Date dataVendaFinal, Date dataDevolucaoInicial, Date dataDevolucaoFinal, Boolean isApenasBilhetesImpressos) {

		StringBuilder sql = new StringBuilder();
		sql.append("SELECT DISTINCT ");
		sql.append("  TO_CHAR(B.FECCREACION, 'DD/MM/YYYY') AS FECHOR_VENTA, ");
		sql.append("  TO_CHAR(BORI.FECCREACION, 'DD/MM/YYYY') AS FECHOR_DEVOLUCAO, ");
		sql.append("  COALESCE(AIDF.DOCFISCAL, COALESCE(BORI.SERIEIMPFISCALORIGINAL, B.SERIEIMPFISCALORIGINAL), ");
		sql.append("  COALESCE(BORI.SERIEIMPFISCAL, B.SERIEIMPFISCAL)) AS AIDF, ");
		sql.append("  COALESCE(B.NUM_BPE, B.NUMFOLIOSISTEMA, B.NUMOPERACION) AS NUMFOLIOSISTEMA, ");
		sql.append("  CASE WHEN COALESCE(BORI.SERIEIMPFISCALORIGINAL,BORI.SERIEIMPFISCAL) IS NOT NULL THEN NULL ");
		sql.append("  	   ELSE AIDF.SERIE || COALESCE(AIDF.SUBSERIE, '') END AS SERIE_SUBSERIE, ");
		sql.append("  B.NUMFOLIOPREIMPRESO AS FOLIO, ");
		sql.append("  B.PRECIOBASE AS PRECIOBASE, ");
		sql.append("  E.NOMBEMPRESA AS NOMB_EMPRESA, ");
		sql.append("  E.EMPRESA_ID AS EMPRESA_ID, ");
		sql.append("  PTV.NUMPUNTOVENTA AS NUMPUNTOVENTA, ");
		sql.append("  PTVO.NUMPUNTOVENTA AS NUMPUNTOVENTAORIGEM, ");
		sql.append("  EST_BPE.NOMBESTADO AS ESTADO, ");
		sql.append("  EST_BPE.CVEESTADO AS UF, ");
		sql.append("  EST_BPE.ESTADO_ID AS ESTADO_ID, ");
		sql.append("  COALESCE(EOS.CVEESTADO, EST.CVEESTADO) AS UF_CORRIDA, ");
		sql.append("  COALESCE(EI.ICMS, EST.ICMS) AS ICMSINTERESTADUAL, ");
		sql.append("  NVL(EI.ICMSIM,0) AS ICMSINTERMUNICIPAL, ");
		sql.append("  EI.TRIBUTACAOIMPORTACAO AS TRIBUTACAOIMPORTACAO, ");
		sql.append("  NVL(EI.PORCREDBASEICMS,0) AS PORCREDBASEICMS, ");
		sql.append("  (CASE WHEN COALESCE(COS.ESTADO_ID,CO.ESTADO_ID) <> COALESCE(CDS.ESTADO_ID,CD.ESTADO_ID) THEN 1 ELSE 0 END) IS_ESTADUAL, ");
		sql.append("  NVL(EI.PORCREDMUNICIPAL,0) AS PORC_MUNICIPAL, ");
		sql.append("  NVL(EI.PORCREDESTADUAL,0) AS PORC_ESTADUAL, ");
		sql.append("  (CASE WHEN NVL(COALESCE(POS.REGIONMETROPOLITANA_ID,ORI.REGIONMETROPOLITANA_ID) ,-1) = NVL(COALESCE(PDS.REGIONMETROPOLITANA_ID,DES.REGIONMETROPOLITANA_ID),-2) THEN 1 ELSE 0 END) AS ISENTA, ");
		sql.append("  NVL(B.PRECIOPAGADO,0) AS PRECIOPAGADO, NVL(B.IMPORTEOUTROS,0) AS IMPORTEOUTROS, NVL(B.IMPORTEPEDAGIO,0) AS IMPORTEPEDAGIO, NVL(B.IMPORTESEGURO,0) AS IMPORTESEGURO, NVL(B.IMPORTETAXAEMBARQUE,0) AS IMPORTETAXAEMBARQUE, ");
		sql.append("  NVL(EI.INDTARIFAMUNICIPAL,0) AS INDTARIFAMUNICIPAL, NVL(EI.INDSEGUROMUNICIPAL,0) AS INDSEGUROMUNICIPAL, NVL(EI.INDTXEMBARQUEMUNICIPAL,0) AS INDTXEMBARQUEMUNICIPAL, NVL(EI.INDPEDAGIOMUNICIPAL,0) AS INDPEDAGIOMUNICIPAL, ");
		sql.append("  NVL(EI.INDTARIFAESTADUAL,0) AS INDTARIFAESTADUAL, NVL(EI.INDSEGUROESTADUAL,0) AS INDSEGUROESTADUAL, NVL(EI.INDTXEMBARQUEESTADUAL,0) AS INDTXEMBARQUEESTADUAL, NVL(EI.INDPEDAGIOESTDUAL,0) AS INDPEDAGIOESTDUAL, ");
		sql.append("  NVL(B.PRECIOPAGADO,0) + NVL(B.IMPORTEOUTROS,0) + NVL(B.IMPORTEPEDAGIO,0) + NVL(B.IMPORTESEGURO,0) + NVL(B.IMPORTETAXAEMBARQUE,0) AS TOTAL, ");
		sql.append("  BPE.TIPOSUBSTITUICAO, ");
		sql.append("  CASE WHEN BPE.TIPOEVENTO = 110111 THEN 'CANCELAMENTO' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '1' THEN 'REMARCACAO' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '2' THEN 'TRANSFERENCIA' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '3' THEN 'TRANSFERENCIA/REMARCACAO' ELSE '' END AS TIPO_SIT, ");
		sql.append("  BPEORI.CHBPE AS CHBPE, ");
		sql.append("  BPE.CHBPE AS CHBPE_SUBSTITUICAO, ");
		sql.append("  DBMS_LOB.SUBSTR((CASE WHEN BPEORI.TIPOEVENTO IS NOT NULL THEN BPEANT.XMLREGULAR ELSE BPEORI.XMLREGULAR END), 3000) AS XML_BPE, ");
		sql.append("  DBMS_LOB.SUBSTR((CASE WHEN BPEORI.TIPOEVENTO IS NOT NULL THEN BPEANT.XMLREGULAR ELSE BPEORI.XMLREGULAR END), 3000, 3001) AS XML_BPE_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_3 ");
		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 ");
		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 (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)  ");
		if (dataDevolucaoInicial != null) {
			sql.append("AND BORI.FECCREACION >= TO_DATE(:dataDevolucaoInicial,'DD/MM/YYYY HH24:MI') ");
		}

		if (dataDevolucaoFinal != null) {
			sql.append("AND BORI.FECCREACION <= TO_DATE(:dataDevolucaoFinal,'DD/MM/YYYY HH24:MI') ");
		}

		sql.append(estados == null ? "" : "AND EST_BPE.ESTADO_ID IN (" + estados + ") ");
		sql.append(puntoVentas == null ? "" : "AND PTV.PUNTOVENTA_ID IN (" + puntoVentas + ") ");
		sql.append(empresaId == null ? "" : "AND E.EMPRESA_ID IN (" + empresaId + ") ");

		sql.append("  UNION ALL ");

		sql.append("SELECT DISTINCT ");
		sql.append("  TO_CHAR(B.FECCREACION, 'DD/MM/YYYY') AS FECHOR_VENTA, ");
		sql.append("  TO_CHAR(BORI.FECCREACION, 'DD/MM/YYYY') AS FECHOR_DEVOLUCAO, ");
		sql.append("  COALESCE(AIDF.DOCFISCAL, COALESCE(BORI.SERIEIMPFISCALORIGINAL, B.SERIEIMPFISCALORIGINAL), ");
		sql.append("  COALESCE(BORI.SERIEIMPFISCAL, B.SERIEIMPFISCAL)) AS AIDF, ");
		sql.append("  COALESCE(B.NUM_BPE, B.NUMFOLIOSISTEMA, B.NUMOPERACION) AS NUMFOLIOSISTEMA, ");
		sql.append("  CASE WHEN COALESCE(BORI.SERIEIMPFISCALORIGINAL,BORI.SERIEIMPFISCAL) IS NOT NULL THEN NULL ");
		sql.append("        ELSE AIDF.SERIE || COALESCE(AIDF.SUBSERIE, '') END AS SERIE_SUBSERIE, ");
		sql.append("  B.NUMFOLIOPREIMPRESO AS FOLIO, ");
		sql.append("  B.PRECIOBASE AS PRECIOBASE, ");
		sql.append("  E.NOMBEMPRESA AS NOMB_EMPRESA, ");
		sql.append("  E.EMPRESA_ID AS EMPRESA_ID, ");
		sql.append("  PTV.NUMPUNTOVENTA AS NUMPUNTOVENTA, ");
		sql.append("  PTVO.NUMPUNTOVENTA AS NUMPUNTOVENTAORIGEM, ");
		sql.append("  EST_BPE.NOMBESTADO AS ESTADO, ");
		sql.append("  EST_BPE.CVEESTADO AS UF, ");
		sql.append("  EST_BPE.ESTADO_ID AS ESTADO_ID, ");
		sql.append("  COALESCE(EOS.CVEESTADO, EST.CVEESTADO) AS UF_CORRIDA, ");
		sql.append("  COALESCE(EI.ICMS, EST.ICMS) AS ICMSINTERESTADUAL, ");
		sql.append("  NVL(EI.ICMSIM,0) AS ICMSINTERMUNICIPAL, ");
		sql.append("  EI.TRIBUTACAOIMPORTACAO AS TRIBUTACAOIMPORTACAO, ");
		sql.append("  NVL(EI.PORCREDBASEICMS,0) AS PORCREDBASEICMS, ");
		sql.append("  (CASE WHEN COALESCE(COS.ESTADO_ID,CO.ESTADO_ID) <> COALESCE(CDS.ESTADO_ID,CD.ESTADO_ID) THEN 1 ELSE 0 END) IS_ESTADUAL, ");
		sql.append("  NVL(EI.PORCREDMUNICIPAL,0) AS PORC_MUNICIPAL, ");
		sql.append("  NVL(EI.PORCREDESTADUAL,0) AS PORC_ESTADUAL, ");
		sql.append("  (CASE WHEN NVL(COALESCE(POS.REGIONMETROPOLITANA_ID,ORI.REGIONMETROPOLITANA_ID) ,-1) = NVL(COALESCE(PDS.REGIONMETROPOLITANA_ID,DES.REGIONMETROPOLITANA_ID),-2) THEN 1 ELSE 0 END) AS ISENTA, ");
		sql.append("  NVL(B.PRECIOPAGADO,0) AS PRECIOPAGADO, NVL(B.IMPORTEOUTROS,0) AS IMPORTEOUTROS, NVL(B.IMPORTEPEDAGIO,0) AS IMPORTEPEDAGIO, NVL(B.IMPORTESEGURO,0) AS IMPORTESEGURO, NVL(B.IMPORTETAXAEMBARQUE,0) AS IMPORTETAXAEMBARQUE, ");
		sql.append("  NVL(EI.INDTARIFAMUNICIPAL,0) AS INDTARIFAMUNICIPAL, NVL(EI.INDSEGUROMUNICIPAL,0) AS INDSEGUROMUNICIPAL, NVL(EI.INDTXEMBARQUEMUNICIPAL,0) AS INDTXEMBARQUEMUNICIPAL, NVL(EI.INDPEDAGIOMUNICIPAL,0) AS INDPEDAGIOMUNICIPAL, ");
		sql.append("  NVL(EI.INDTARIFAESTADUAL,0) AS INDTARIFAESTADUAL, NVL(EI.INDSEGUROESTADUAL,0) AS INDSEGUROESTADUAL, NVL(EI.INDTXEMBARQUEESTADUAL,0) AS INDTXEMBARQUEESTADUAL, NVL(EI.INDPEDAGIOESTDUAL,0) AS INDPEDAGIOESTDUAL, ");
		sql.append("  NVL(B.PRECIOPAGADO,0) + NVL(B.IMPORTEOUTROS,0) + NVL(B.IMPORTEPEDAGIO,0) + NVL(B.IMPORTESEGURO,0) + NVL(B.IMPORTETAXAEMBARQUE,0) AS TOTAL, ");
		sql.append("  BPE.TIPOSUBSTITUICAO, ");
		sql.append("  CASE WHEN BPE.TIPOEVENTO = 110111 THEN 'CANCELAMENTO' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '1' THEN 'REMARCACAO' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '2' THEN 'TRANSFERENCIA' ");
		sql.append("       WHEN BPE.TIPOEVENTO IS NULL AND BPE.CHBPE_SUBSTITUICAO IS NOT NULL AND BPE.TIPOSUBSTITUICAO = '3' THEN 'TRANSFERENCIA/REMARCACAO' ELSE '' END AS TIPO_SIT, ");
		sql.append("  BPEORI.CHBPE AS CHBPE, ");
		sql.append("  '' AS CHBPE_SUBSTITUICAO, ");
		sql.append("  DBMS_LOB.SUBSTR((CASE WHEN BPEORI.TIPOEVENTO IS NOT NULL THEN BPEANT.XMLREGULAR ELSE BPEORI.XMLREGULAR END), 3000) AS XML_BPE, ");
		sql.append("  DBMS_LOB.SUBSTR((CASE WHEN BPEORI.TIPOEVENTO IS NOT NULL THEN BPEANT.XMLREGULAR ELSE BPEORI.XMLREGULAR END), 3000, 3001) AS XML_BPE_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_3 ");
		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) ");
		if (dataDevolucaoInicial != null) {
			sql.append("AND BORI.FECCREACION >= TO_DATE(:dataDevolucaoInicial,'DD/MM/YYYY HH24:MI') ");
		}

		if (dataDevolucaoFinal != null) {
			sql.append("AND BORI.FECCREACION <= TO_DATE(:dataDevolucaoFinal,'DD/MM/YYYY HH24:MI') ");
		}

		sql.append(estados == null ? "" : "AND EST_BPE.ESTADO_ID IN (" + estados + ") ");
		sql.append(puntoVentas == null ? "" : "AND PTV.PUNTOVENTA_ID IN (" + puntoVentas + ") ");
		sql.append(empresaId == null ? "" : "AND E.EMPRESA_ID IN (" + empresaId + ") ");

		sql.append("ORDER BY NOMB_EMPRESA, ESTADO, UF, FECHOR_DEVOLUCAO, NUMFOLIOSISTEMA");

		return sql.toString();
	}

	private String getSql(Integer empresaId, String puntoVentas, String estados, Date dataVendaInicial, Date dataVendaFinal, Date dataDevolucaoInicial, Date dataDevolucaoFinal, Boolean isApenasBilhetesImpressos) {

		StringBuilder sql = new StringBuilder();
		sql.append("SELECT DISTINCT ");
		sql.append("  COALESCE(AIDF.DOCFISCAL, COALESCE(BORI.SERIEIMPFISCALORIGINAL, B.SERIEIMPFISCALORIGINAL), ");
		sql.append("  COALESCE(BORI.SERIEIMPFISCAL, B.SERIEIMPFISCAL)) AS AIDF, ");
		sql.append("  COALESCE(B.NUMFOLIOSISTEMA, B.NUMOPERACION) AS NUMFOLIOSISTEMA, ");
		sql.append("  CASE WHEN COALESCE(BORI.SERIEIMPFISCALORIGINAL,BORI.SERIEIMPFISCAL) IS NOT NULL THEN NULL ");
		sql.append("        ELSE AIDF.SERIE || COALESCE(AIDF.SUBSERIE, '') END AS SERIE_SUBSERIE, ");
		sql.append("  B.NUMFOLIOPREIMPRESO AS FOLIO, ");
		sql.append("  B.PRECIOBASE AS PRECIOBASE, ");
		sql.append("  E.NOMBEMPRESA AS NOMB_EMPRESA, ");
		sql.append("  E.EMPRESA_ID AS EMPRESA_ID, ");
		sql.append("  PTV.NUMPUNTOVENTA AS NUMPUNTOVENTA, ");
		sql.append("  PTVO.NUMPUNTOVENTA AS NUMPUNTOVENTAORIGEM, ");
		sql.append("  COALESCE(ESAIDF.NOMBESTADO, EOS.NOMBESTADO, EST.NOMBESTADO) AS ESTADO,");
		sql.append("  COALESCE(ESAIDF.CVEESTADO, EOS.CVEESTADO, EST.CVEESTADO) AS UF, ");
		sql.append("  COALESCE(ESAIDF.ESTADO_ID, EOS.ESTADO_ID, EST.ESTADO_ID) AS ESTADO_ID, ");
		sql.append("  COALESCE(EOS.CVEESTADO, EST.CVEESTADO) AS UF_CORRIDA, ");
		sql.append("  COALESCE(EI.ICMS, EST.ICMS) AS ICMSINTERESTADUAL, ");
		sql.append("  NVL(EI.ICMSIM,0) AS ICMSINTERMUNICIPAL, ");
		sql.append("  EI.TRIBUTACAOIMPORTACAO AS TRIBUTACAOIMPORTACAO, ");
		sql.append("  NVL(EI.PORCREDBASEICMS,0) AS PORCREDBASEICMS, ");
		sql.append("  TO_CHAR(BORI.FECHORVENTA, 'DD/MM/YYYY') AS FECHOR_VENTA, ");
		sql.append("  TO_CHAR(B.FECHORVENTA, 'DD/MM/YYYY') AS FECHOR_DEVOLUCAO, ");
		sql.append("  (CASE WHEN COALESCE(COS.ESTADO_ID,CO.ESTADO_ID) <> COALESCE(CDS.ESTADO_ID,CD.ESTADO_ID) THEN 1 ELSE 0 END) IS_ESTADUAL, ");
		sql.append("  NVL(EI.PORCREDMUNICIPAL,0) AS PORC_MUNICIPAL, ");
		sql.append("  NVL(EI.PORCREDESTADUAL,0) AS PORC_ESTADUAL, ");
		sql.append("  (CASE WHEN NVL(COALESCE(POS.REGIONMETROPOLITANA_ID,ORI.REGIONMETROPOLITANA_ID) ,-1) = NVL(COALESCE(PDS.REGIONMETROPOLITANA_ID,DES.REGIONMETROPOLITANA_ID),-2) THEN 1 ELSE 0 END) as ISENTA, ");
		sql.append("  NVL(B.PRECIOPAGADO,0) AS PRECIOPAGADO, NVL(B.IMPORTEOUTROS,0) AS IMPORTEOUTROS, NVL(B.IMPORTEPEDAGIO,0) AS IMPORTEPEDAGIO, NVL(B.IMPORTESEGURO,0) AS IMPORTESEGURO, NVL(B.IMPORTETAXAEMBARQUE,0) AS IMPORTETAXAEMBARQUE, ");
		sql.append("  NVL(EI.INDTARIFAMUNICIPAL,0) AS INDTARIFAMUNICIPAL, NVL(EI.INDSEGUROMUNICIPAL,0) AS INDSEGUROMUNICIPAL, NVL(EI.INDTXEMBARQUEMUNICIPAL,0) AS INDTXEMBARQUEMUNICIPAL, NVL(EI.INDPEDAGIOMUNICIPAL,0) AS INDPEDAGIOMUNICIPAL, ");
		sql.append("  NVL(EI.INDTARIFAESTADUAL,0) AS INDTARIFAESTADUAL, NVL(EI.INDSEGUROESTADUAL,0) AS INDSEGUROESTADUAL, NVL(EI.INDTXEMBARQUEESTADUAL,0) AS INDTXEMBARQUEESTADUAL, NVL(EI.INDPEDAGIOESTDUAL,0) AS INDPEDAGIOESTDUAL, ");
		sql.append("  NVL(B.PRECIOPAGADO,0) + NVL(B.IMPORTEOUTROS,0) + NVL(B.IMPORTEPEDAGIO,0) + NVL(B.IMPORTESEGURO,0) + NVL(B.IMPORTETAXAEMBARQUE,0) AS TOTAL ");
		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 ");

		/* JOIN COM TABELAS DE ALIAS */
		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 ");

		if (isApenasBilhetesImpressos) {
			sql.append("AND B.NUMFOLIOPREIMPRESO IS NOT NULL ");
		}

		if (dataVendaInicial != null) {
			sql.append("AND BORI.FECHORVENTA >= TO_DATE(:dataVendaInicial,'DD/MM/YYYY HH24:MI') ");
		}

		if (dataVendaFinal != null) {
			sql.append("AND BORI.FECHORVENTA <= TO_DATE(:dataVendaFinal,'DD/MM/YYYY HH24:MI') ");
		}

		if (dataDevolucaoInicial != null) {
			sql.append("AND B.FECHORVENTA >= TO_DATE(:dataDevolucaoInicial,'DD/MM/YYYY HH24:MI') ");
		}

		if (dataDevolucaoFinal != null) {
			sql.append("AND B.FECHORVENTA <= TO_DATE(:dataDevolucaoFinal,'DD/MM/YYYY HH24:MI') ");
		}

		sql.append(estados == null ? "" : "AND COALESCE(ESAIDF.ESTADO_ID, EOS.ESTADO_ID, EST.ESTADO_ID) IN (" + estados + ") ");
		sql.append(puntoVentas == null ? "" : "AND PTV.PUNTOVENTA_ID IN (" + puntoVentas + ") ");
		sql.append(empresaId == null ? "" : "AND E.EMPRESA_ID IN (" + empresaId + ") ");

		sql.append("AND B.CATEGORIA_ID NOT IN (SELECT VALORCONSTANTE FROM CONSTANTE WHERE NOMBCONSTANTE = 'GRATUIDADE_CRIANCA') ");
		sql.append("ORDER BY NOMB_EMPRESA, ESTADO, UF, FECHOR_DEVOLUCAO, NUMFOLIOSISTEMA");

		return sql.toString();
	}

	@Override
	protected void processaParametros() throws Exception {
	}

}
