package com.rjconsultores.ventaboletos.dao.hibernate;

import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.transform.AliasToBeanResultTransformer;
import org.hibernate.type.BigDecimalType;
import org.hibernate.type.DateType;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.rjconsultores.ventaboletos.dao.RelatorioAgepanDAO;
import com.rjconsultores.ventaboletos.exception.BusinessException;
import com.rjconsultores.ventaboletos.vo.OrgaoConcedente.RelatorioGratuidadeAgepanVO;

@Repository("relatorioAgepanDAO")
public class RelatorioAgepanHibernateDAO extends HibernateDaoSupport implements RelatorioAgepanDAO {
	
//	public static int ORGAOCONCEDENTE_ID_AGEPAN = 4;
	
	@Autowired
    public RelatorioAgepanHibernateDAO(@Qualifier("sessionFactory") SessionFactory factory) {
        setSessionFactory(factory);
    }

	@Override
	public List<RelatorioGratuidadeAgepanVO> listar(Map<String, Object> parametros)  throws BusinessException {
		try {
		
			String fecInicioVenda = null;
			if (parametros.get("fecInicioVenda") != null) {
				fecInicioVenda = parametros.get("fecInicioVenda").toString() + " 00:00";
			}
			String fecFinalVenda = null;
			if (parametros.get("fecFinalVenda") != null) {
				fecFinalVenda = parametros.get("fecFinalVenda").toString() + " 23:59";
			}
			
			String tipGratuIds = parametros.get("tipGratuIds").toString();
			String linhaIds = parametros.get("linhaIds").toString();
			Integer empresa = parametros.get("empresa") != null ? Integer.valueOf(parametros.get("empresa").toString()) : null;
			Integer orgaoConcendenteAgepanId = parametros.get("orgaoConcendenteAgepanId") != null ? Integer.valueOf(parametros.get("orgaoConcendenteAgepanId").toString()) : null;
			
			
			String sQuery = getSql(fecInicioVenda, fecFinalVenda, linhaIds, tipGratuIds, empresa);
			
			Query qr = getSession().createSQLQuery(sQuery)
								   .addScalar("numBpe", StringType.INSTANCE)
								   .addScalar("fechorventa", DateType.INSTANCE)
								   .addScalar("origenId", IntegerType.INSTANCE)
								   .addScalar("puntoventaId", IntegerType.INSTANCE)
								   .addScalar("origem", StringType.INSTANCE)
								   .addScalar("destino", StringType.INSTANCE)
								   .addScalar("dhemb", StringType.INSTANCE)
								   .addScalar("nombpasajero", StringType.INSTANCE)
								   .addScalar("desctipodoc", StringType.INSTANCE)
								   .addScalar("descnumdoc", StringType.INSTANCE)
								   .addScalar("desctipodoc2", StringType.INSTANCE)
								   .addScalar("descnumdoc2", StringType.INSTANCE)
								   .addScalar("corridaextra", StringType.INSTANCE)
								   .addScalar("tiposervicobpe", StringType.INSTANCE)
								   .addScalar("fechorviaje", DateType.INSTANCE)
								   .addScalar("prefixo", StringType.INSTANCE)
								   .addScalar("numasiento", StringType.INSTANCE)
								   .addScalar("totalbilhete", BigDecimalType.INSTANCE)
								   .addScalar("totalbase", BigDecimalType.INSTANCE)
								   .addScalar("descontobpe", StringType.INSTANCE)
								   .addScalar("chbpe", StringType.INSTANCE)
								   .setResultTransformer(new AliasToBeanResultTransformer(RelatorioGratuidadeAgepanVO.class));
			
			
			qr.setParameter("agepanId", orgaoConcendenteAgepanId);
			qr.setParameter("fecInicioVenda", fecInicioVenda);
			qr.setParameter("fecFinalVenda", fecFinalVenda);
			if (empresa != null){
				qr.setParameter("empresaId", empresa);
			}
			
			List<RelatorioGratuidadeAgepanVO> retorno = qr.list();
			if(retorno == null || retorno.isEmpty()) {
				throw new BusinessException("MSG.ningunRegistroRelatorio");
			}
			
			return retorno;
		
		} catch (BusinessException e) {
			throw e;
		} catch (Exception e) {
			throw new BusinessException(e.getMessage(), e);
		}
		
	}
	
	private String getSql(String fecInicioVenda, String fecFinalVenda, String linha, String tipoGratu, Integer empresa) {
		
		StringBuilder sb = new StringBuilder();

		sb.append("SELECT b.num_bpe numBpe, COALESCE(b.fechorventa_h,b.fechorventa) fechorventa, b.origen_id origenId, b.puntoventa_id puntoventaId, ");
		sb.append("ori.descparada origem, des.descparada destino, bpe.dhemb, b.nombpasajero, b.desctipodoc, b.descnumdoc, b.desctipodoc2, b.descnumdoc2, ");
		sb.append("CASE WHEN co.tiposervicio_id = 2 THEN '00' ELSE '01' END corridaextra, cs.tiposervicobpe, b.fechorviaje, r.prefixo, ");
		sb.append("CASE WHEN b.numasiento like 'P%' THEN '0' ELSE b.numasiento END numasiento, ");
		sb.append("NVL(b.preciobase,0) + NVL(b.importetaxaembarque,0) + NVL(b.importeseguro,0) + NVL(b.importeoutros,0) + NVL(b.importepedagio,0) as totalbase, ");
		sb.append("NVL(b.preciopagado,0) + NVL(b.importetaxaembarque,0) + NVL(b.importeseguro,0) + NVL(b.importeoutros,0) + NVL(b.importepedagio,0) as totalbilhete, ");
		sb.append("cat.descontobpe, bpe.chbpe ");		
		sb.append("from boleto b ");		
		sb.append("join bpe bpe on bpe.boleto_id = b.boleto_id ");		
		sb.append("join parada ori on ori.parada_id = b.origen_id ");
		sb.append("join parada des on des.parada_id = b.destino_id ");
		sb.append("join corrida co on co.corrida_id = b.corrida_id and co.feccorrida = b.feccorrida ");
		sb.append("join clase_servicio cs on cs.claseservicio_id = co.claseservicio_id ");
		sb.append("join ruta r on r.ruta_id = co.ruta_id ");
		sb.append("join categoria cat on cat.categoria_id = b.categoria_id ");
		sb.append("join marca m on m.marca_id = b.marca_id ");
		sb.append("WHERE b.activo = 1 ");
		sb.append("AND COALESCE(b.fechorventa_h,b.fechorventa) BETWEEN to_date(:fecInicioVenda,'dd/mm/yyyy hh24:mi') AND to_date(:fecFinalVenda,'dd/mm/yyyy hh24:mi') ");
		sb.append("AND r.orgaoconcedente_id = :agepanId ");
		sb.append("AND b.motivocancelacion_id is null ");
		sb.append("AND bpe.codstat in ('100','102','150','-1') ");
		
		if( tipoGratu != null ) {
			sb.append(" AND b.categoria_id in (").append(tipoGratu).append(") ");
		}
		
		if( linha != null && !linha.equals("Todas")) {
			sb.append(" AND r.ruta_id in (").append(linha).append(") ");
		}
		
		if (empresa != null){
			sb.append("AND m.empresa_id = :empresaId  ");
		}

		return sb.toString();
	}

}
