package br.com.centralit.citcorpore.ajaxForms;

import java.util.Collection;
import java.util.Iterator;

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.citajax.html.HTMLForm;
import br.com.centralit.citcorpore.bean.PortfolioServicoDTO;
import br.com.centralit.citcorpore.bean.ServicoDTO;
import br.com.centralit.citcorpore.negocio.PortfolioServicoService;
import br.com.centralit.citcorpore.negocio.ServicoService;
import br.com.centralit.citcorpore.util.CITCorporeUtil;
import br.com.centralit.citcorpore.util.Enumerados.PagesPortfolio;
import br.com.centralit.citcorpore.util.Enumerados.SimNao;
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.Configuracoes;
import br.com.citframework.util.UtilDatas;
import br.com.citframework.util.UtilI18N;
import br.com.citframework.util.UtilStrings;

public class GerenciamentoPortfolioCadastroPortfolio extends AjaxFormAction {

	private PortfolioServicoService portfolioServicoService;
	private ServicoService servicoService;
	private static Permissoes permissao;

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

		GerenciamentoPortfolio.setPortalImages(document);
		setPermissoesPortfolio(document, request);
		carregaTabelaPortfolios(document, request, response);
	}

	private void setPermissoesPortfolio(DocumentHTML document, HttpServletRequest request) throws Exception {
		permissao = new Permissoes(document, request, PagesPortfolio.PORTFOLIO.getCaminho());
	}

	private void carregaTabelaPortfolios(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Collection<PortfolioServicoDTO> colPortfolioServico = getPortfolioServicoService().findAtivos();

		HTMLElement divTabelaPortfolio = document.getElementById("divDinamicoTabelaPortfolio");

		StringBuilder sb = new StringBuilder();

		if (colPortfolioServico != null && !colPortfolioServico.isEmpty() && colPortfolioServico.size() > 0) {
			sb.append(geraHtmlCabecalhoTabela(request));

			for (Iterator<PortfolioServicoDTO> iterator = colPortfolioServico.iterator(); iterator.hasNext();) {
				PortfolioServicoDTO portfolioServicoDTO = iterator.next();

				sb.append(geraHtmlDadosTabela(portfolioServicoDTO.getIdPortfolioServico(), portfolioServicoDTO.getDescPortfolioServico(), request));
			}

			sb.append(geraHTMLFinalTabela());
		} else {
			sb.append("<h4>" + UtilI18N.internacionaliza(request, "gerenciaportfolio.nenhumPortfolioRegistrado") + "</h4>");
		}

		divTabelaPortfolio.setInnerHTML(sb.toString());

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

	public void save(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}
		PortfolioServicoDTO portfolioServicoDTO = (PortfolioServicoDTO) document.getBean();
		setPermissoesPortfolio(document, request);

		if(permissao.isGravar()) {
			if (SimNao.SIM.getValorStr().equalsIgnoreCase(portfolioServicoDTO.getDisponivelPortal()) && UtilStrings.isNotVazio(portfolioServicoDTO.getImagemPortal())) {
				portfolioServicoDTO.setImagemPortal(portfolioServicoDTO.getImagemPortal().replace(CITCorporeUtil.CONTEXTO_APLICACAO, ""));
			}

			if (portfolioServicoDTO != null && portfolioServicoDTO.getIdPortfolioServico() != null) {
				this.getPortfolioServicoService().updateNotNull(portfolioServicoDTO);
				document.executeScript("notificacaoI18N('MSG06');");
			} else if (portfolioServicoDTO != null){
				portfolioServicoDTO.setDataInicio(UtilDatas.getDataAtual());
				this.getPortfolioServicoService().create(portfolioServicoDTO);
				document.executeScript("notificacaoI18N('MSG05');");
			}

			HTMLForm form = document.getForm("formCadastroPortfolio");
			form.clear();

			carregaTabelaPortfolios(document, request, response);
		} else {
			document.executeScript("notificacaoErro('citcorpore.comum.permissaoFuncionalidade');");
		}

		document.executeScript("Modal.close('modal-portfolio-cadastro');");
	}

	public void restore(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}
		PortfolioServicoDTO portfolioServicoDTO = (PortfolioServicoDTO) document.getBean();

		if (portfolioServicoDTO.getIdPortfolioServico() != null) {
			portfolioServicoDTO = this.getPortfolioServicoService().restore(portfolioServicoDTO);

			if (portfolioServicoDTO != null && portfolioServicoDTO.getIdPortfolioServico() != null) {
				HTMLForm form = document.getForm("formCadastroPortfolio");
				form.setValues(portfolioServicoDTO);

				if (portfolioServicoDTO.getDisponivelPortal() != null && portfolioServicoDTO.getDisponivelPortal().equalsIgnoreCase("S")) {
					document.executeScript("$('.portal-content').show();");
				} else {
					document.executeScript("$('.portal-content').hide();");
				}

				document.executeScript("Modal.adjust('modal-portfolio-cadastro');");

				if (UtilStrings.isNotVazio(portfolioServicoDTO.getImagemPortal())) {
					document.executeScript("$('.carousel li img[src=\"" + Configuracoes.getCaminhoComContexto(portfolioServicoDTO.getImagemPortal()) + "\"]').parent('li').trigger('click');");
				}
			}
		}

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

	public void excluir(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}
		PortfolioServicoDTO portfolioServicoDTO = (PortfolioServicoDTO) document.getBean();
		setPermissoesPortfolio(document, request);

		if(permissao.isDeletar()) {
			if (portfolioServicoDTO != null && portfolioServicoDTO.getIdPortfolioServico() != null) {
				Collection<ServicoDTO> servicosDoPortfolio = this.getServicoService().findByIdPortfolioServico(portfolioServicoDTO.getIdPortfolioServico());
				if (servicosDoPortfolio != null && !servicosDoPortfolio.isEmpty()) {
					document.executeScript("notificacaoErro('MSG09');");
				} else {
					portfolioServicoDTO.setDataFim(UtilDatas.getDataAtual());
					this.getPortfolioServicoService().updateNotNull(portfolioServicoDTO);
					document.executeScript("notificacaoI18N('MSG07');");

					HTMLForm form = document.getForm("formCadastroPortfolio");
					form.clear();

					carregaTabelaPortfolios(document, request, response);
				}
			}
		} else {
			document.executeScript("notificacaoErro('citcorpore.comum.permissaoFuncionalidade');");
		}
	}

	private String geraHtmlCabecalhoTabela(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();

		sb.append("<div class='row-fluid'> ");
		sb.append("	<div class=\"table-responsive tabela\">");
		sb.append("		<table class=\"table table-bordered table-striped table-condensed table-vertical-center checkboxs js-table-sortable ui-sortable\"> ");
		sb.append("			<thead> ");
		sb.append("				<tr> ");
		sb.append("					<th style=\"width: 1%;\" class=\"center\">" + UtilI18N.internacionaliza(request, "gerenciaportfolio.id") + "</th> ");
		sb.append("					<th>" + UtilI18N.internacionaliza(request, "gerenciaportfolio.descricaoPortfolio") + "</th> ");
		sb.append("					<th class=\"center\">" + UtilI18N.internacionaliza(request, "gerenciaportfolio.acoes") + "</th> ");
		sb.append("				</tr> ");
		sb.append("			</thead> ");
		sb.append("			<tbody> ");

		return sb.toString();
	}

	private String geraHtmlDadosTabela(Integer idPortfolio, String descricaoPortfolio, HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();

		String onMouseOverAvancar = "onmouseover=\"abreTooltip(this, '"+UtilI18N.internacionaliza(request, "gerenciaportfolio.avancarPortfolio")+"')\" onmouseout=\"fechaTooltip()\"";
		String onMouseOverEditar = "onmouseover=\"abreTooltip(this, '"+UtilI18N.internacionaliza(request, "gerenciaportfolio.editarPortfolio")+"')\" onmouseout=\"fechaTooltip()\"";

		sb.append("		<tr>");
		sb.append("			<td class=\"center\">" + idPortfolio + "</td> ");
		sb.append("			<td>" + descricaoPortfolio + "</td> ");
		sb.append("			<td class=\"center\" style=\"width: 60px;\"> ");
		sb.append("				<a onclick=\"avancarPortfolio(this, " + idPortfolio + ", '" + descricaoPortfolio + "');\" "+onMouseOverAvancar+" class=\"btn-action glyphicons right_arrow btn-default\"><i></i></a> ");
		sb.append("				<a onclick=\"editarPortfolio(" + idPortfolio + ");\" "+onMouseOverEditar+" class=\"btn-action glyphicons pencil btn-success\"><i></i></a> ");
		sb.append("			</td> ");
		sb.append("		</tr> ");

		return sb.toString();
	}

	private String geraHTMLFinalTabela() {
		StringBuilder sb = new StringBuilder();
		sb.append("			</tbody> ");
		sb.append("		</table>");
		sb.append("	</div>");
		sb.append("</div>");

		return sb.toString();
	}

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

	private PortfolioServicoService getPortfolioServicoService() throws ServiceException {
		if (portfolioServicoService == null) {
			portfolioServicoService = (PortfolioServicoService) ServiceLocator.getInstance().getService(PortfolioServicoService.class, null);
		}
		return portfolioServicoService;
	}

	private ServicoService getServicoService() throws ServiceException {
		if (servicoService == null) {
			servicoService = (ServicoService) ServiceLocator.getInstance().getService(ServicoService.class, null);
		}
		return servicoService;
	}

}
