package br.com.centralit.citcorpore.ajaxForms;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

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

import br.com.centralit.citajax.html.AjaxFormAction;
import br.com.centralit.citajax.html.DocumentHTML;
import br.com.centralit.citajax.html.HTMLElement;
import br.com.centralit.citcorpore.bean.AtributoDemandaDTO;
import br.com.centralit.citcorpore.bean.AtributoDemandaServicoDTO;
import br.com.centralit.citcorpore.bean.ImportarAtributoDemandaDTO;
import br.com.centralit.citcorpore.negocio.AtributoDemandaService;
import br.com.centralit.citcorpore.negocio.AtributoDemandaServicoService;
import br.com.centralit.citcorpore.negocio.OcorrenciaServicoService;
import br.com.centralit.citcorpore.util.Enumerados;
import br.com.centralit.citcorpore.util.Enumerados.PagesPortfolio;
import br.com.centralit.citcorpore.util.Permissoes;
import br.com.centralit.citcorpore.util.WebUtil;
import br.com.citframework.excecao.ServiceException;
import br.com.citframework.service.ServiceLocator;
import br.com.citframework.util.UtilI18N;
import br.com.citframework.util.UtilNumbersAndDecimals;

public class ImportarAtributoDemanda extends AjaxFormAction {

	private AtributoDemandaService atributoDemandaService;
	private AtributoDemandaServicoService atributoDemandaServicoService;
	private OcorrenciaServicoService ocorrenciaServicoService;
	private static Permissoes permissao;
	
	@Override
	public Class<ImportarAtributoDemandaDTO> getBeanClass() {
		return ImportarAtributoDemandaDTO.class;
	}

	@Override
	public void load(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}
		permissao = new Permissoes(document, request, PagesPortfolio.SERVICO_NEGOCIO_ATRIBUTO_DEMANDA.getCaminho());
		ImportarAtributoDemandaDTO beanDto = (ImportarAtributoDemandaDTO) document.getBean();

		if (beanDto != null && !UtilNumbersAndDecimals.isNull(beanDto.getIdServico())) {
			this.restoreIndicadoresCapacidade(beanDto, document, request);
		}

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

		if (permissao.isGravar()) {
			GerenciamentoPortfolioOcorrenciasServico auditoria = new GerenciamentoPortfolioOcorrenciasServico();
			ImportarAtributoDemandaDTO beanDto = (ImportarAtributoDemandaDTO) document.getBean();
			if (beanDto.getAtributoDemandaCheck() != null) {
				for (Integer idAtributoDemanda : beanDto.getAtributoDemandaCheck()) {
					AtributoDemandaServicoDTO atributoDemandaServicoDTO = new AtributoDemandaServicoDTO();
					atributoDemandaServicoDTO.setIdServico(beanDto.getIdServico());
					atributoDemandaServicoDTO.setIdAtributoDemanda(idAtributoDemanda);
					getAtributoDemandaServicoService().create(atributoDemandaServicoDTO);
				}
				this.getOcorrenciaServicoService().salvaOcorrenciaServicoDemanda(beanDto.getIdServico(), Enumerados.AuditoriaAcoes.VINCULADO.getIdentificador(), beanDto.getAtributoDemandaCheck(), document, request);
			}
			document.executeScript("atualizaTelaAtributoDemanda();");
			document.executeScript("Modal.close('modal-portfolio-atributo-demanda-add');");
		} else {
			document.executeScript("Modal.close('modal-portfolio-atributo-demanda-add');");
			document.executeScript("notificacaoErro('citcorpore.comum.naoFoiPossivelVincular','citcorpore.comum.usuarioSemPermissao')");
		}
	}

	private void restoreIndicadoresCapacidade(ImportarAtributoDemandaDTO importarAtributoDemandaDTO, final DocumentHTML document, final HttpServletRequest request) throws ServiceException, Exception {
		if(importarAtributoDemandaDTO != null && importarAtributoDemandaDTO.getIdServico() != null){
			this.preencheTabela(importarAtributoDemandaDTO, document, request);
		}

	}

	private void preencheTabela(ImportarAtributoDemandaDTO importarAtributoDemandaDTO, final DocumentHTML document, final HttpServletRequest request) throws ServiceException, Exception {
		HTMLElement divTabela = document.getElementById("tabelaAtributoDemanda");
		document.executeScript("limpaTabelaAtributoDemanda()");
		List<Integer> listIdAtributoDemanda = convertListAtributoDemandaServicoToListIdAtributoDemanda(getAtributoDemandaServicoService().listAllByIdServico(importarAtributoDemandaDTO.getIdServico()));
		Collection<AtributoDemandaDTO> listAtributos = getAtributoDemandaService().list();
		StringBuilder sb = new StringBuilder();
		if(listAtributos != null && !listAtributos.isEmpty()){
			sb.append("		<table class='dynamicTable table table-striped table-bordered' id='tableAtributoDemanda'> ");
			sb.append("			<thead> ");
			sb.append("				<tr> ");
			sb.append("					<th><input type='checkbox' name='atributoDemandaAll' id='atributoDemandaAll' onChange='markAll()'/></th> ");
			sb.append("					<th>" + UtilI18N.internacionaliza(request, "citcorpore.comum.nome") + "</th> ");
			sb.append("					<th>" + UtilI18N.internacionaliza(request, "citcorpore.comum.valor") + "</th> ");
			sb.append("				</tr> ");
			sb.append("			</thead> ");
			sb.append("			<tbody> ");

			for (AtributoDemandaDTO atributoDemandaDTO: listAtributos) {
				Integer id = atributoDemandaDTO.getIdAtributoDemanda();
				if(!listIdAtributoDemanda.contains(atributoDemandaDTO.getIdAtributoDemanda())){
					sb.append("		<tr>");
					sb.append("			<td>")
						.append("			<input class='checkAtributoDemanda' type='checkbox' name='atributoDemandaCheck' onChange='checkCheckBoxes()' id='atributoDemanda").append(id).append("' value='").append(id).append("'").append(" />")
						.append("		</td>");
					sb.append("			<td>"+atributoDemandaDTO.getNome()+"</td>");
					sb.append("			<td>"+atributoDemandaDTO.getValor()+"</td>");
					sb.append("		</tr>");
				}
			}
			sb.append("			</tbody> ");
			sb.append("		</table> ");
			sb.append("");

			sb.append("<div class='separator'></div>");
			divTabela.appendHTML(sb.toString());
		}else{
			sb.append("<h4>"+ UtilI18N.internacionaliza(request, "gerenciamentoportfolio.atributoDemanda.nenhumAtributoDemandaCadastrado"));
			divTabela.appendHTML(sb.toString());
		}
	}
	
	private List<Integer> convertListAtributoDemandaServicoToListIdAtributoDemanda(List<AtributoDemandaServicoDTO> listAtributoDemandaServico){
		List<Integer> listId = new ArrayList<>();
		if(listId != null){
			for(AtributoDemandaServicoDTO atributo : listAtributoDemandaServico){
				listId.add(atributo.getIdAtributoDemanda());
			}
		}
		return listId;
	}

	private AtributoDemandaService getAtributoDemandaService() throws ServiceException{
		if(atributoDemandaService == null)
			atributoDemandaService = (AtributoDemandaService) ServiceLocator.getInstance().getService(AtributoDemandaService.class, null);
		return atributoDemandaService;
	}
	
	private AtributoDemandaServicoService getAtributoDemandaServicoService() throws ServiceException{
		if(atributoDemandaServicoService == null)
			atributoDemandaServicoService = (AtributoDemandaServicoService) ServiceLocator.getInstance().getService(AtributoDemandaServicoService.class, null);
		return atributoDemandaServicoService;
	}

	private OcorrenciaServicoService getOcorrenciaServicoService() throws ServiceException {
		if (ocorrenciaServicoService == null)
			ocorrenciaServicoService = (OcorrenciaServicoService) ServiceLocator.getInstance().getService(OcorrenciaServicoService.class, null);
		return ocorrenciaServicoService;
	}

}
