/**
 * 
 */
package com.rjconsultores.ventaboletos.relatorios.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

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

public class RelatorioFormaPagamentoAgencia extends RelatorioDemandas {
	public RelatorioFormaPagamentoAgencia(Map<String, Object> parametros, Connection conexao) throws Exception {
		super(parametros, conexao);
		this.setCustomDataSource(new ArrayDataSource(this) {
			@Override
			public void initDados() throws Exception {
				SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
				Connection conexao = this.relatorio.getConexao();
				Map<String, Object> parametros = this.relatorio.getParametros();

				Date dataIncial = (Date) parametros.get("DATA_INICIAL");
				Date dataFinal = (Date) parametros.get("DATA_FINAL");				
				Integer empresa = (Integer) parametros.get("EMPRESA");
				Integer agencia = (Integer) parametros.get("AGENCIA");				
				Short formaPagoId = (Short) parametros.get("FORMA_PAGO");

				StringBuilder where = new StringBuilder();
		        where.append(" WHERE 1 = 1 ");

		        if (dataIncial != null) {
		            where.append(" AND c.fechorventa >= to_date('" + format.format(dataIncial) + " 00:00:00','dd/MM/yyyy hh24:mi:ss') ");
		        }

		        if (dataFinal != null) {
		            where.append(" AND c.fechorventa <= to_date('" + format.format(dataFinal)  + " 23:59:59','dd/MM/yyyy hh24:mi:ss') ");
		        }
		        
		        if (empresa != null) {
		        	where.append(" AND m.EMPRESA_ID = " + empresa + " ");
		        }
		        
		        if (agencia != null) {
		        	where.append(" AND pv.PUNTOVENTA_ID = " + agencia + " ");
		        }

		        if (formaPagoId != null) {
		        	where.append(" AND cfp.FORMAPAGO_ID = " + formaPagoId + " ");
		        }
		        
		        StringBuilder sql = new StringBuilder();
		        sql.append(" SELECT to_char(c.fechorventa, 'dd/MM/yyyy')  AS data, ");
		        sql.append(" pv.nombpuntoventa AS agencia, ");
		        sql.append(" fp.descpago AS forma_pagamento, ");
		        sql.append(" SUM(CASE WHEN c.MOTIVOCANCELACION_ID IS NULL THEN 1 ELSE -1 END *(nvl(cfp.importe, 0) - nvl(c.importepedagio, 0) - nvl(c.importeseguro, 0) - nvl(c.importetaxaembarque, 0))) AS tarifa, ");
		        sql.append(" SUM(CASE WHEN c.MOTIVOCANCELACION_ID IS NULL THEN 1 ELSE -1 END * nvl(c.importepedagio, 0)) AS pedagio, ");
		        sql.append(" SUM(CASE WHEN c.MOTIVOCANCELACION_ID IS NULL THEN 1 ELSE -1 END * nvl(c.importeseguro, 0)) AS seguro, ");
		        sql.append(" SUM(CASE WHEN c.MOTIVOCANCELACION_ID IS NULL THEN 1 ELSE -1 END * nvl(c.importetaxaembarque, 0)) AS taxa, ");
		        sql.append(" SUM(CASE WHEN c.MOTIVOCANCELACION_ID IS NULL THEN 1 ELSE -1 END * nvl(cfp.importe, 0))  AS total, ");
		        sql.append(" COUNT(c.preciopagado) AS qtde, ");
		        sql.append(" max((select sum(seg.valor)   from segpolv seg ");
		        sql.append("                      inner join caja cc on cc.transacao_id = seg.boleto_id           ");
		        sql.append("                      inner join caja_formapago cfp on (cc.caja_id = cfp.caja_id)     ");
		        sql.append("                where " );
		        if (dataIncial != null) {
		        	sql.append("  cc.fechorventa >= to_date('" + format.format(dataIncial) + " 00:00:00','dd/MM/yyyy hh24:mi:ss') ");
		        }

		        if (dataFinal != null) {
		            sql.append(" AND cc.fechorventa <= to_date('" + format.format(dataFinal)  + " 23:59:59','dd/MM/yyyy hh24:mi:ss') ");
		        }
		        sql.append("   AND cc.INDREIMPRESION = 0 and c.feccorte = cc.feccorte ");
		        if (empresa != null) {
		        	sql.append(" AND cc.empresacorrida_id  = " + empresa + " ");
		        }
		        
		        if (agencia != null) {
		        	sql.append(" AND cc.PUNTOVENTA_ID = " + agencia + " ");
		        }else{
		        	sql.append(" AND cc.PUNTOVENTA_ID = c.puntoventa_id ");
		        }
		        
		        sql.append("   and cfp.formapago_id = (fp.formapago_id) ");
		        sql.append("                              ))  as seguro_opcional ");
		        sql.append(" from caja c ");
		        sql.append(" join caja_formapago cfp on c.caja_id = cfp.caja_id ");
		        sql.append(" join forma_pago fp on cfp.formapago_id =  fp.formapago_id ");
		        sql.append(" join punto_venta pv on pv.PUNTOVENTA_ID = c.PUNTOVENTA_ID ");
		        sql.append(" join marca m on m.MARCA_ID = c.MARCA_ID and m.activo = 1 ");
		        sql.append(where);
		        sql.append(" AND c.INDREIMPRESION = 0 ");
		        sql.append(" group by to_char(c.fechorventa, 'dd/MM/yyyy'), pv.NOMBPUNTOVENTA, fp.DESCPAGO ");
		        sql.append(" order by data, agencia, forma_pagamento");

				NamedParameterStatement stmt = new NamedParameterStatement(conexao, sql.toString());

				ResultSet rset = stmt.executeQuery();

				while (rset.next()) {
					Map<String, Object> dataResult = new HashMap<String, Object>();

					dataResult.put("DATA", rset.getString("DATA"));
					dataResult.put("AGENCIA", rset.getString("AGENCIA"));
					dataResult.put("FORMA_PAGAMENTO", rset.getString("FORMA_PAGAMENTO"));
					dataResult.put("TARIFA", rset.getDouble("TARIFA"));
					dataResult.put("PEDAGIO", rset.getDouble("PEDAGIO"));
					dataResult.put("SEGURO", rset.getDouble("SEGURO"));
					dataResult.put("SEGURO_OPCIONAL", rset.getDouble("SEGURO_OPCIONAL"));
					dataResult.put("TAXA", rset.getDouble("TAXA"));
					dataResult.put("TOTAL", rset.getDouble("TOTAL") + rset.getDouble("SEGURO_OPCIONAL"));
					dataResult.put("QTDE", rset.getInt("QTDE"));

					this.dados.add(dataResult);
				}

				this.resultSet = rset;
			}
		});
	}
}
