/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.rjconsultores.ventaboletos.dao.hibernate;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.rjconsultores.ventaboletos.dao.FormaPagamentoAgenciaDAO;

/**
 *
 * @author Administrador
 */
@Repository("formaPagamentoAgenciaDAO")
public class FormaPagamentoAgenciaDAOImpl implements FormaPagamentoAgenciaDAO {

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

    private String getSql(Date dataInicio, Date dataFinal) {
        StringBuilder where = new StringBuilder();
        where.append(" WHERE 1 = 1 ");

        if (dataInicio != null) {
            where.append(" AND c.fechorventa >= ? ");
        }

        if (dataFinal != null) {
            where.append(" AND c.fechorventa <= ? ");
        }

        StringBuilder sql = new StringBuilder();
        sql.append(" select to_char(c.fechorventa, 'dd/mm/yyyy') as data, ");
        sql.append(" pv.PUNTOVENTA_ID as agencia, ");
        sql.append(" fp.DESCPAGO as forma_pagamento, "); 
        sql.append(" sum(nvl(c.PRECIOPAGADO,0)) as tarifa, ");
        sql.append(" sum(nvl(c.IMPORTEPEDAGIO,0)) as pedagio, ");
        sql.append(" sum(nvl(c.IMPORTESEGURO,0)) as seguro, "); 
        sql.append(" sum(nvl(c.IMPORTETAXAEMBARQUE,0)) as taxa, ");
        sql.append(" sum((c.PRECIOPAGADO + c.IMPORTEPEDAGIO + c.IMPORTESEGURO + c.IMPORTETAXAEMBARQUE)) as total, ");
        sql.append(" count(c.PRECIOPAGADO) as qtde ");
        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(where);
        sql.append(" group by to_char(c.fechorventa, 'dd/mm/yyyy'), pv.PUNTOVENTA_ID, fp.DESCPAGO ");
        sql.append(" order by data, agencia, forma_pagamento");

        return sql.toString();
    }

    public ResultSet executarSQL(Connection conn, Map parameters) {
        Date dataInicio = (Date) parameters.get("dataInicio");
        Date dataFinal = (Date) parameters.get("dataFinal");
        String sql = getSql(dataInicio, dataFinal);

        PreparedStatement stmt = null;
        ResultSet rset = null;

        try {
            stmt = conn.prepareStatement(sql);
            stmt.setDate(1, new java.sql.Date(dataInicio.getTime()));
            stmt.setDate(2, new java.sql.Date(dataFinal.getTime()));
            rset = stmt.executeQuery();
        } catch (Exception ex) {
            log.error(ex);
        }

        return rset;
    }
}
