package br.com.centralit.citcorpore.ajaxForms;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.centralit.citajax.html.AjaxFormAction;
import br.com.centralit.citajax.html.DocumentHTML;
import br.com.centralit.citajax.html.HTMLSelect;
import br.com.centralit.citcorpore.bean.PortfolioServicoDTO;
import br.com.centralit.citcorpore.bean.RelatorioIncidenteRequisicaoPorServicoDTO;
import br.com.centralit.citcorpore.bean.ServicoDTO;
import br.com.centralit.citcorpore.bean.UsuarioDTO;
import br.com.centralit.citcorpore.negocio.PortfolioServicoService;
import br.com.centralit.citcorpore.negocio.ServicoService;
import br.com.centralit.citcorpore.negocio.SolicitacaoServicoService;
import br.com.centralit.citcorpore.util.CITCorporeUtil;
import br.com.centralit.citcorpore.util.Enumerados;
import br.com.centralit.citcorpore.util.Enumerados.TipoCatalogoServico;
import br.com.centralit.citcorpore.util.LogoRel;
import br.com.centralit.citcorpore.util.UtilRelatorio;
import br.com.centralit.citcorpore.util.WebUtil;
import br.com.citframework.excecao.ServiceException;
import br.com.citframework.service.ServiceLocator;
import br.com.citframework.util.Constantes;
import br.com.citframework.util.UtilDatas;
import br.com.citframework.util.UtilI18N;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.fill.JRAbstractLRUVirtualizer;
import net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer;
import net.sf.jasperreports.engine.util.JRSwapFile;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class RelatorioIncidenteRequisicaoPorServico extends AjaxFormAction {

	@Override
	public void load(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}

		carregaComboCatalogoServico(document, request);
		carregaComboPortfolio(document, request);
		carregaComboNumeroRegistros(document, request);

		this.atualizaServicos(document, request, response);
	}

	private void carregaComboCatalogoServico(DocumentHTML document, HttpServletRequest request) throws Exception {
		HTMLSelect comboCatalogoServico = document.getSelectById("tipoServico");
		inicializaCombo(request, comboCatalogoServico);

		for (TipoCatalogoServico tipo : TipoCatalogoServico.values()) {
			comboCatalogoServico.addOption(tipo.getIdentificador(), UtilI18N.internacionaliza(request, tipo.getChave()));
		}
	}

	private void carregaComboPortfolio(DocumentHTML document, HttpServletRequest request) throws Exception, ServiceException {
		HTMLSelect comboPortfolio = document.getSelectById("idPortfolioServico");
		inicializaCombo(request, comboPortfolio);
		PortfolioServicoService portfolioService = (PortfolioServicoService) ServiceLocator.getInstance().getService(PortfolioServicoService.class, null);
		Collection<PortfolioServicoDTO> colPortfolio = portfolioService.findAtivos();
		if (colPortfolio != null) {
			comboPortfolio.addOptions(colPortfolio, "idPortfolioServico", "descPortfolioServico", null);
		}
	}

	private void inicializaCombo(HttpServletRequest request, HTMLSelect combo) {
		combo.removeAllOptions();
		combo.addOption("", UtilI18N.internacionaliza(request, "citcorpore.comum.todos"));
	}

	private void carregaComboNumeroRegistros(DocumentHTML document, HttpServletRequest request) throws Exception {
		HTMLSelect comboNumeroRegistros = document.getSelectById("numeroRegistros");
		for (Enumerados.TopListEnum valor : Enumerados.TopListEnum.values()) {
			comboNumeroRegistros.addOption(valor.getValorTopList().toString(), UtilI18N.internacionaliza(request, valor.getNomeTopList()));
		}
	}

	public void atualizaServicos(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RelatorioIncidenteRequisicaoPorServicoDTO dto = (RelatorioIncidenteRequisicaoPorServicoDTO) document.getBean();
		ServicoDTO servicoDto = new ServicoDTO();
		servicoDto.setTipoServico(dto.getTipoServico());
		servicoDto.setIdPortfolioServico(dto.getIdPortfolioServico());
		HTMLSelect comboServico = document.getSelectById("idServico");
		comboServico.removeAllOptions();
		ServicoService servico = (ServicoService) ServiceLocator.getInstance().getService(ServicoService.class, null);
		Collection<ServicoDTO> listaServicos = servico.listServicosCombo(servicoDto);
		comboServico.addOption("", UtilI18N.internacionaliza(request, "citcorpore.comum.todos"));
		if (listaServicos != null) {
			comboServico.addOptions(listaServicos, "idServico", "nomeServico", null);
		}
	}

	public void imprimirRelatorioQuantitativo(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}
		try {
			HttpSession session = request.getSession();
			Set<String> setSolicitacao = new HashSet<>();
			Set<String> setServico = new HashSet<>();

			RelatorioIncidenteRequisicaoPorServicoDTO solicitacaoServicoDTO = (RelatorioIncidenteRequisicaoPorServicoDTO) document.getBean();
			SolicitacaoServicoService solicitacaoServicoService = (SolicitacaoServicoService) ServiceLocator.getInstance().getService(SolicitacaoServicoService.class, null);

			if (solicitacaoServicoDTO.getDataInicio() == null) {
				document.alert(UtilI18N.internacionaliza(request, "citcorpore.comum.validacao.datainicio"));
				document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
				return;
			}

			if (solicitacaoServicoDTO.getDataFim() == null) {
				document.alert(UtilI18N.internacionaliza(request, "citcorpore.comum.validacao.datafim"));
				document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
				return;
			}

			Collection<RelatorioIncidenteRequisicaoPorServicoDTO> listaQuantidadeServicoCatalogo = solicitacaoServicoService.listaRelatorioQuantitativoServicoCatalogo(solicitacaoServicoDTO);

			Date dt = new Date();

			String strCompl = "" + dt.getTime();
			String caminhoJasper = CITCorporeUtil.CAMINHO_REAL_APP + Constantes.getValue("CAMINHO_RELATORIOS") + "RelatorioIncidenteRequisicaoPorServico.jasper";
			String diretorioReceita = CITCorporeUtil.CAMINHO_REAL_APP + "/tempFiles";
			String diretorioRelativoOS = Constantes.getValue("SERVER_ADDRESS") + Constantes.getValue("CONTEXTO_APLICACAO") + "/tempFiles";

			Map<String, Object> parametros = new HashMap<String, Object>();
			parametros = UtilRelatorio.trataInternacionalizacaoLocale(session, parametros);

			UsuarioDTO usuario = WebUtil.getUsuario(request);

			parametros.put("TITULO_RELATORIO", UtilI18N.internacionaliza(request, "relatorioQuantitativo.RelatorioIncidenteRequisicaoPorServico"));
			parametros.put("CIDADE", getCidadeParametrizada(request));
			parametros.put("DATA_HORA", UtilDatas.getDataHoraAtual());
			parametros.put("NOME_USUARIO", usuario.getNomeUsuario());
			parametros.put("dataInicio", solicitacaoServicoDTO.getDataInicio());
			parametros.put("dataFim", solicitacaoServicoDTO.getDataFim());
			parametros.put("Logo", LogoRel.getFile());
			parametros.put("TotalRegistros", listaQuantidadeServicoCatalogo.size());
			parametros.put("TotalSolicitacoes", setSolicitacao.size());
			parametros.put("TotalServicos", setServico.size());

			if (listaQuantidadeServicoCatalogo.size() == 0) {
				document.alert(UtilI18N.internacionaliza(request, "citcorpore.comum.relatorioVazio"));
				document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
				return;
			}

			JRDataSource dataSource = new JRBeanCollectionDataSource(listaQuantidadeServicoCatalogo);

			JRSwapFile arquivoSwap = new JRSwapFile(diretorioReceita, 4096, 25);
			JRAbstractLRUVirtualizer virtualizer = new JRSwapFileVirtualizer(25, arquivoSwap, true);
			parametros.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
			JasperPrint print = JasperFillManager.fillReport(caminhoJasper, parametros, dataSource);

			JasperExportManager.exportReportToPdfFile(print, diretorioReceita + "/RelatorioIncidenteRequisicaoPorServico" + strCompl + "_" + usuario.getIdUsuario() + ".pdf");

			document.executeScript("window.open('" + Constantes.getValue("SERVER_ADDRESS") + Constantes.getValue("CONTEXTO_APLICACAO") + "/printPDF/printPDF.jsp?url=" + diretorioRelativoOS + "/RelatorioIncidenteRequisicaoPorServico"
					+ strCompl + "_" + usuario.getIdUsuario() + ".pdf')");
		} catch (Exception e) {
			e.printStackTrace();
			document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
			document.alert(UtilI18N.internacionaliza(request, "citcorpore.erro.erroServidor"));
		}

		document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
	}

	public void imprimirRelatorioQuantitativoXls(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}
		try {
			HttpSession session = request.getSession();
			Set<String> setSolicitacao = new HashSet<>();
			Set<String> setServico = new HashSet<>();

			RelatorioIncidenteRequisicaoPorServicoDTO solicitacaoServicoDTO = (RelatorioIncidenteRequisicaoPorServicoDTO) document.getBean();
			SolicitacaoServicoService solicitacaoServicoService = (SolicitacaoServicoService) ServiceLocator.getInstance().getService(SolicitacaoServicoService.class, null);

			UsuarioDTO usuario = WebUtil.getUsuario(request);

			if (solicitacaoServicoDTO.getDataInicio() == null) {
				document.alert(UtilI18N.internacionaliza(request, "citcorpore.comum.validacao.datainicio"));
				document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
				return;
			}

			if (solicitacaoServicoDTO.getDataFim() == null) {
				document.alert(UtilI18N.internacionaliza(request, "citcorpore.comum.validacao.datafim"));
				document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
				return;
			}

			Collection<RelatorioIncidenteRequisicaoPorServicoDTO> listaQuantidadeServicoCatalogo = solicitacaoServicoService.listaRelatorioQuantitativoServicoCatalogo(solicitacaoServicoDTO);

			Date dt = new Date();

			String strCompl = "" + dt.getTime();
			String diretorioReceita = CITCorporeUtil.CAMINHO_REAL_APP + "/tempFiles";
			String diretorioRelativoOS = Constantes.getValue("SERVER_ADDRESS") + Constantes.getValue("CONTEXTO_APLICACAO") + "/tempFiles";

			Map<String, Object> parametros = new HashMap<String, Object>();
			parametros = UtilRelatorio.trataInternacionalizacaoLocale(session, parametros);

			parametros.put("TITULO_RELATORIO", UtilI18N.internacionaliza(request, "relatorioQuantitativo.RelatorioQuantitativoServicoConcluidosAnalitico"));
			parametros.put("CIDADE", getCidadeParametrizada(request));
			parametros.put("DATA_HORA", UtilDatas.getDataHoraAtual());
			parametros.put("NOME_USUARIO", usuario.getNomeUsuario());
			parametros.put("dataInicio", solicitacaoServicoDTO.getDataInicio());
			parametros.put("dataFim", solicitacaoServicoDTO.getDataFim());
			parametros.put("Logo", LogoRel.getFile());
			parametros.put("TotalRegistros", listaQuantidadeServicoCatalogo.size());
			parametros.put("TotalSolicitacoes", setSolicitacao.size());
			parametros.put("TotalServicos", setServico.size());

			if (listaQuantidadeServicoCatalogo.size() == 0) {
				document.alert(UtilI18N.internacionaliza(request, "citcorpore.comum.relatorioVazio"));
				document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
				return;
			}

			JRDataSource dataSource = new JRBeanCollectionDataSource(listaQuantidadeServicoCatalogo);
			JasperDesign desenho = JRXmlLoader.load(CITCorporeUtil.CAMINHO_REAL_APP + Constantes.getValue("CAMINHO_RELATORIOS") + "RelatorioIncidenteRequisicaoPorServico.jrxml");

			JasperReport relatorio = JasperCompileManager.compileReport(desenho);
			JasperPrint impressao = JasperFillManager.fillReport(relatorio, parametros, dataSource);

			JRXlsExporter exporter = new JRXlsExporter();
			exporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, impressao);
			exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
			exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.TRUE);
			exporter.setParameter(JRXlsExporterParameter.OUTPUT_FILE_NAME, diretorioReceita + "/RelatorioIncidenteRequisicaoPorServico" + strCompl + "_" + usuario.getIdUsuario() + ".xls");

			exporter.exportReport();

			document.executeScript("window.open('" + Constantes.getValue("SERVER_ADDRESS") + Constantes.getValue("CONTEXTO_APLICACAO") + "/printPDF/printPDF.jsp?url=" + diretorioRelativoOS + "/RelatorioIncidenteRequisicaoPorServico"
					+ strCompl + "_" + usuario.getIdUsuario() + ".xls')");
			document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
		} catch (Exception e) {
			document.getJanelaPopupById("JANELA_AGUARDE_MENU").hide();
			document.alert(UtilI18N.internacionaliza(request, "citcorpore.erro.erroServidor"));
		}
	}

	@Override
	public Class<RelatorioIncidenteRequisicaoPorServicoDTO> getBeanClass() {
		return RelatorioIncidenteRequisicaoPorServicoDTO.class;
	}

}
