package br.com.centralit.citcorpore.ajaxForms;

import java.util.Collection;

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.citajax.html.HTMLSelect;
import br.com.centralit.citcorpore.bean.BaseConhecimentoDTO;
import br.com.centralit.citcorpore.bean.CategoriaServicoDTO;
import br.com.centralit.citcorpore.bean.GerenciamentoPortfolioCadastroServicoDTO;
import br.com.centralit.citcorpore.bean.ServicoAutoRelacionamentoDTO;
import br.com.centralit.citcorpore.bean.ServicoDTO;
import br.com.centralit.citcorpore.bean.TemplateSolicitacaoServicoDTO;
import br.com.centralit.citcorpore.bean.TipoServicoDTO;
import br.com.centralit.citcorpore.negocio.BaseConhecimentoService;
import br.com.centralit.citcorpore.negocio.CategoriaServicoService;
import br.com.centralit.citcorpore.negocio.ServicoAutoRelacionamentoService;
import br.com.centralit.citcorpore.negocio.ServicoService;
import br.com.centralit.citcorpore.negocio.TemplateSolicitacaoServicoService;
import br.com.centralit.citcorpore.negocio.TipoServicoService;
import br.com.centralit.citcorpore.util.CITCorporeUtil;
import br.com.centralit.citcorpore.util.Enumerados.AuditoriaAcoes;
import br.com.centralit.citcorpore.util.Enumerados.BusinessImportance;
import br.com.centralit.citcorpore.util.Enumerados.PagesPortfolio;
import br.com.centralit.citcorpore.util.Enumerados.ParametroSistema;
import br.com.centralit.citcorpore.util.Enumerados.ServiceDemandType;
import br.com.centralit.citcorpore.util.Enumerados.ServiceExecutionPlace;
import br.com.centralit.citcorpore.util.Enumerados.ServiceSituation;
import br.com.centralit.citcorpore.util.Enumerados.ServiceTypeEvent;
import br.com.centralit.citcorpore.util.Enumerados.SimNao;
import br.com.centralit.citcorpore.util.Enumerados.TipoServico;
import br.com.centralit.citcorpore.util.ParametroUtil;
import br.com.centralit.citcorpore.util.Permissoes;
import br.com.centralit.citcorpore.util.WebUtil;
import br.com.citframework.excecao.ServiceException;
import br.com.citframework.integracao.core.PageRequest;
import br.com.citframework.integracao.core.Pageable;
import br.com.citframework.service.ServiceLocator;
import br.com.citframework.util.Configuracoes;
import br.com.citframework.util.Reflexao;
import br.com.citframework.util.UtilDatas;
import br.com.citframework.util.UtilHTML;
import br.com.citframework.util.UtilI18N;
import br.com.citframework.util.UtilNumbersAndDecimals;
import br.com.citframework.util.UtilStrings;

public class GerenciamentoPortfolioCadastroServico extends AjaxFormAction {

	private ServicoService servicoService;
	private CategoriaServicoService categoriaServicoService;
	private BaseConhecimentoService baseConhecimentoService;
	private TemplateSolicitacaoServicoService templateSolicitacaoServicoService;
	private ServicoAutoRelacionamentoService servicoAutoRelacionamentoService;
	private TipoServicoService tipoServicoService;
	private static Permissoes permissao;

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

		if (beanDto != null && !UtilNumbersAndDecimals.isNull(beanDto.getIdServicoRelacionado())) {
			setPermissoesServico(document, request);
			if (TipoServico.SERVICO_NEGOCIO.getIdentificador().equalsIgnoreCase(beanDto.getTipoServicoRelacionado())) {
				this.restoreServicoNegocioCarregaServicosRequisicaoIncidente(beanDto, document, request);
			} else {
				this.restoreServicoApoioCarregaServicosRequisicaoIncidente(beanDto, document, request);
			}
		}
		setarDataImplantacao(document, request);
	}

	private void setarDataImplantacao(DocumentHTML document, HttpServletRequest request) throws Exception {
		UtilDatas.setLocale(WebUtil.getLanguage(request));
		document.getElementById("dataInicioServicoReqIncOS").setValue(UtilDatas.getDataAtualStr());
	}

	private void setPermissoesServico(DocumentHTML document, HttpServletRequest request) {
		GerenciamentoPortfolioCadastroServicoDTO beanDto = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();
		String caminhoPermissao = "";

		if (TipoServico.SERVICO_NEGOCIO.getIdentificador().equalsIgnoreCase(beanDto.getTipoServicoRelacionado())) {
			if(TipoServico.SERVICO_REQUISICAO.getIdentificador().equalsIgnoreCase(beanDto.getTipoServico())) {
				caminhoPermissao = PagesPortfolio.SERVICO_NEGOCIO_REQUISICAO_SERVICO.getCaminho();
			} else if(TipoServico.SERVICO_INCIDENTE.getIdentificador().equalsIgnoreCase(beanDto.getTipoServico())) {
				caminhoPermissao = PagesPortfolio.SERVICO_NEGOCIO_INICIDENTES.getCaminho();
			} else if(TipoServico.SERVICO_PROCEDIMENTO.getIdentificador().equalsIgnoreCase(beanDto.getTipoServico())) {
				caminhoPermissao = PagesPortfolio.SERVICO_NEGOCIO_PROCEDIMENTOS.getCaminho();
			}
		} else if (TipoServico.SERVICO_APOIO.getIdentificador().equalsIgnoreCase(beanDto.getTipoServicoRelacionado())) {
			if(TipoServico.SERVICO_REQUISICAO.getIdentificador().equalsIgnoreCase(beanDto.getTipoServico())) {
				caminhoPermissao = PagesPortfolio.SERVICO_APOIO_REQUISICAO_SERVICOS.getCaminho();
			} else if(TipoServico.SERVICO_INCIDENTE.getIdentificador().equalsIgnoreCase(beanDto.getTipoServico())) {
				caminhoPermissao = PagesPortfolio.SERVICO_APOIO_INCIDENTES.getCaminho();
			}
		}

		permissao = new Permissoes(document, request, caminhoPermissao);
	}

	private void carregaCombosCadastroServico(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		carregaComboTipoEventoServico(document, request);
		carregaComboTipoDemandaServico(document, request);
		carregaComboSituacaoServico(document, request);
		carregaComboTemplateSolicitacao(document, request);
		carregaComboTemplateAcompanhamento(document, request);
		carregaCombosCheckbox(document, request);
		carregaComboLocalExecucaoServico(document, request, response);
		carregaComboImportanciaNegocio(document, request, response);
		carregaComboTipoServico(document, request, response);
	}

	private void iniciaCombo(DocumentHTML document, HttpServletRequest request, HTMLSelect combo) throws Exception {
		combo.removeAllOptions();
		combo.addOption("", UtilI18N.internacionaliza(request, "citcorpore.comum.selecione"));
	}

	private void carregaComboTipoEventoServico(DocumentHTML document, HttpServletRequest request) throws Exception {
		HTMLSelect combo = document.getSelectById("idTipoEventoServicoReqIncOS");
		iniciaCombo(document, request, combo);

		for (ServiceTypeEvent serviceTypeEvent : ServiceTypeEvent.values()) {
			combo.addOption(serviceTypeEvent.getId().toString(), UtilI18N.internacionaliza(request, serviceTypeEvent.getI18NKey()));
			}
		}

	private void carregaComboTipoDemandaServico(DocumentHTML document, HttpServletRequest request) throws Exception {
		HTMLSelect combo = document.getSelectById("idTipoDemandaServicoReqIncOS");
		iniciaCombo(document, request, combo);

		for (ServiceDemandType serviceDemandType : ServiceDemandType.values()) {
			combo.addOption(String.valueOf(serviceDemandType.getId()), UtilI18N.internacionaliza(request, serviceDemandType.getI18NKey()));
		}
	}

	private void carregaComboSituacaoServico(DocumentHTML document, HttpServletRequest request) throws Exception {
		HTMLSelect combo = document.getSelectById("idSituacaoServicoReqIncOS");
		combo.removeAllOptions();

		for (ServiceSituation serviceSituation : ServiceSituation.values()) {
			combo.addOption(String.valueOf(serviceSituation.getId()), UtilI18N.internacionaliza(request, serviceSituation.getI18NKey()));
		}

		combo.setValue(ServiceSituation.ACTIVE.getId().toString());
	}

	private void carregaComboTemplateSolicitacao(DocumentHTML document, HttpServletRequest request) throws Exception {
		HTMLSelect combo = document.getSelectById("idTemplateSolicitacaoReqIncOS");
		iniciaCombo(document, request, combo);

		Collection<TemplateSolicitacaoServicoDTO> listTemplateSolicitacaoServicoDto = this.getTemplateSolicitacaoServicoService().getAtivos();

		if (listTemplateSolicitacaoServicoDto != null) {
			for (TemplateSolicitacaoServicoDTO templateSolicitacaoServicoDto : listTemplateSolicitacaoServicoDto) {
				combo.addOption(String.valueOf(templateSolicitacaoServicoDto.getIdTemplate()), templateSolicitacaoServicoDto.getNomeTemplate());
			}
		}
	}

	private void carregaComboTemplateAcompanhamento(DocumentHTML document, HttpServletRequest request) throws Exception {
		HTMLSelect combo = document.getSelectById("idTemplateAcompanhamentoReqIncOS");
		iniciaCombo(document, request, combo);

		Collection<TemplateSolicitacaoServicoDTO> listTemplateSolicitacaoServicoDto = this.getTemplateSolicitacaoServicoService().getAtivos();

		if (listTemplateSolicitacaoServicoDto != null) {
			for (TemplateSolicitacaoServicoDTO templateSolicitacaoServicoDto : listTemplateSolicitacaoServicoDto) {
				combo.addOption(String.valueOf(templateSolicitacaoServicoDto.getIdTemplate()), templateSolicitacaoServicoDto.getNomeTemplate());
			}
		}
	}

	private void carregaCombosCheckbox(DocumentHTML document, HttpServletRequest request) throws Exception {
		HTMLSelect comboDispPortal = document.getSelectById("dispPortal");
		HTMLSelect comboIncidenteCritico = document.getSelectById("incidenteCritico");

		carregaOpcoesSimNao(comboDispPortal, request);
		carregaOpcoesSimNao(comboIncidenteCritico, request);
	}

	private void carregaComboImportanciaNegocio(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		HTMLSelect combo = document.getSelectById("idImportanciaNegocioReqIncOS");
		iniciaCombo(document, request, combo);

		for (BusinessImportance businessImportance : BusinessImportance.values()) {
			combo.addOption(String.valueOf(businessImportance.getId()), UtilI18N.internacionaliza(request, businessImportance.getI18NKey()));
		}
	}

	private void carregaComboTipoServico(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		HTMLSelect combo = document.getSelectById("idTipoServicoNegocioReqIncOS");
		iniciaCombo(document, request, combo);

		Collection<TipoServicoDTO> listTipoServicoDto = this.getTipoServicoService().getAtivos();

		if (listTipoServicoDto != null) {
			for (TipoServicoDTO tipoServicoDto : listTipoServicoDto) {
				combo.addOption(String.valueOf(tipoServicoDto.getIdTipoServico()), tipoServicoDto.getNomeTipoServico());
			}
		}

	}

	/**
	 * @since 18.01.2016
	 * @author douglas.japiassu
	 */
	private void carregaComboLocalExecucaoServico(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		HTMLSelect combo = document.getSelectById("idLocalExecucaoServicoNegocioReqIncOS");
		iniciaCombo(document, request, combo);

		for (ServiceExecutionPlace serviceExecutionPlace : ServiceExecutionPlace.values()) {
			combo.addOption(String.valueOf(serviceExecutionPlace.getId()), UtilI18N.internacionaliza(request, serviceExecutionPlace.getI18NKey()));
		}
	}

	private void carregaOpcoesSimNao(HTMLSelect combo, HttpServletRequest request) {
		combo.removeAllOptions();

		combo.addOption(SimNao.NAO.getValorStr(), UtilI18N.internacionaliza(request, SimNao.NAO.getChave()));
		combo.addOption(SimNao.SIM.getValorStr(), UtilI18N.internacionaliza(request, SimNao.SIM.getChave()));
	}

	public void carregaTabelaServicosRequisicaoNegocio(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws ServiceException, Exception {
		GerenciamentoPortfolioCadastroServicoDTO servicoRequisicaoDto = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();

		servicoRequisicaoDto.setTipoServico(TipoServico.SERVICO_REQUISICAO.getIdentificador());
		montaHTMLServicosRequisicaoIncidenteNegocio(servicoRequisicaoDto, document, request);

		document.executeScript("depoisCarregarServicosRequisicaoNegocio();");
	}

	public void carregaTabelaServicosIncidenteNegocio(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws ServiceException, Exception {
		GerenciamentoPortfolioCadastroServicoDTO servicoIncidenteDto = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();

		servicoIncidenteDto.setTipoServico(TipoServico.SERVICO_INCIDENTE.getIdentificador());
		montaHTMLServicosRequisicaoIncidenteNegocio(servicoIncidenteDto, document, request);

		document.executeScript("depoisCarregarServicosIncidenteNegocio();");
	}

	public void carregaTabelaServicosProcedimento(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws ServiceException, Exception {
		GerenciamentoPortfolioCadastroServicoDTO servicoProcedimentoDto = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();
		servicoProcedimentoDto.setTipoServico(TipoServico.SERVICO_PROCEDIMENTO.getIdentificador());
		montaHTMLServicosRequisicaoIncidenteNegocio(servicoProcedimentoDto, document, request);

		document.executeScript("depoisCarregarServicosProcedimento();");
	}

	private void montaHTMLServicosRequisicaoIncidenteNegocio(GerenciamentoPortfolioCadastroServicoDTO servicoRequisicaoIncidenteDto, final DocumentHTML document,
			final HttpServletRequest request) throws ServiceException, Exception {
		WebUtil.validarSeUsuarioEstaNaSessao(request, document);

		String descTipoServico = "";
		if (TipoServico.SERVICO_REQUISICAO.getIdentificador().equalsIgnoreCase(servicoRequisicaoIncidenteDto.getTipoServico())) {
			descTipoServico = "Requisicao";
		} else if (TipoServico.SERVICO_INCIDENTE.getIdentificador().equalsIgnoreCase(servicoRequisicaoIncidenteDto.getTipoServico())) {
			descTipoServico = "Incidente";
		} else if (TipoServico.SERVICO_PROCEDIMENTO.getIdentificador().equalsIgnoreCase(servicoRequisicaoIncidenteDto.getTipoServico())) {
			descTipoServico = "Procedimento";
		}

		HTMLElement divListaServicos;

		if(TipoServico.SERVICO_APOIO.getIdentificador().equalsIgnoreCase(servicoRequisicaoIncidenteDto.getTipoServicoRelacionado())){
			divListaServicos = document.getElementById("divDinamicoListaServicos".concat(descTipoServico).concat("Apoio"));
		}else{
			divListaServicos = document.getElementById("divDinamicoListaServicos".concat(descTipoServico).concat("Negocio"));
		}

		String filtroServico = servicoRequisicaoIncidenteDto.getFiltroServico();
		if (filtroServico == null) {
			filtroServico = "";
		}

		Integer itensPorPagina = Integer.parseInt(ParametroUtil.getValorParametroCitSmartHashMap(ParametroSistema.QUANT_RETORNO_PESQUISA, "10"));

		Integer paginaSelecionadaRequisicao = servicoRequisicaoIncidenteDto.getPaginaSelecionadaServico();
		if (paginaSelecionadaRequisicao == null || paginaSelecionadaRequisicao == 0) {
			paginaSelecionadaRequisicao = 1;
		}

		Pageable pageable = new PageRequest(paginaSelecionadaRequisicao - 1, itensPorPagina);


		Collection<ServicoDTO> listServicoRequisicao = getServicoService().listServicosNegocioRequisicaoIncidente(servicoRequisicaoIncidenteDto.getTipoServico(), servicoRequisicaoIncidenteDto.getIdPortfolioServico(),
				servicoRequisicaoIncidenteDto.getIdServicoRelacionado(), filtroServico, pageable, false).getContent();

		if (listServicoRequisicao != null && !listServicoRequisicao.isEmpty()) {
			divListaServicos.setInnerHTML(GerenciamentoPortfolio.geraHTMLServicosRequisicaoIncidente(document, request, listServicoRequisicao, servicoRequisicaoIncidenteDto.getTipoServico()));

			Integer totalPaginasRequisicao = getServicoService().listServicosNegocioRequisicaoIncidente(servicoRequisicaoIncidenteDto.getTipoServico(), servicoRequisicaoIncidenteDto.getIdPortfolioServico(),
					servicoRequisicaoIncidenteDto.getIdServicoRelacionado(), filtroServico, pageable, true).getTotalPages();

			HTMLElement paginacaoServicos = document.getElementById("paginacaoServicos".concat(descTipoServico));
			String funcaoJsPaginar = "paginarServicos".concat(descTipoServico).concat("Negocio");
			paginacaoServicos.setInnerHTML(UtilHTML.paginacaoHtml(request, funcaoJsPaginar, totalPaginasRequisicao, paginaSelecionadaRequisicao));
		} else {
			final StringBuilder htmlDivSemRegistros = new StringBuilder();
			htmlDivSemRegistros.append("<h4>" + UtilI18N.internacionaliza(request, "gerenciaportfolio.nenhumServicoRegistrado") + "</h4>");
			divListaServicos.setInnerHTML(htmlDivSemRegistros.toString());
		}

	}

	public void carregaTabelaServicosRequisicaoApoio(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws ServiceException, Exception {
		GerenciamentoPortfolioCadastroServicoDTO servicoRequisicaoDto = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();

		servicoRequisicaoDto.setTipoServico(TipoServico.SERVICO_REQUISICAO.getIdentificador());
		montaHTMLServicosRequisicaoIncidenteApoio(servicoRequisicaoDto, document, request);

		document.executeScript("depoisCarregarServicosRequisicaoApoio();");
	}

	public void carregaTabelaServicosIncidenteApoio(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws ServiceException, Exception {
		GerenciamentoPortfolioCadastroServicoDTO servicoIncidenteDto = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();

		servicoIncidenteDto.setTipoServico(TipoServico.SERVICO_INCIDENTE.getIdentificador());
		montaHTMLServicosRequisicaoIncidenteApoio(servicoIncidenteDto, document, request);

		document.executeScript("depoisCarregarServicosIncidenteApoio();");
	}

	private void montaHTMLServicosRequisicaoIncidenteApoio(GerenciamentoPortfolioCadastroServicoDTO servicoRequisicaoIncidenteDto, final DocumentHTML document,
			final HttpServletRequest request) throws ServiceException, Exception {
		WebUtil.validarSeUsuarioEstaNaSessao(request, document);

		String descTipoServico = "";
		if (TipoServico.SERVICO_REQUISICAO.getIdentificador().equalsIgnoreCase(servicoRequisicaoIncidenteDto.getTipoServico())) {
			descTipoServico = "Requisicao";
		} else if (TipoServico.SERVICO_INCIDENTE.getIdentificador().equalsIgnoreCase(servicoRequisicaoIncidenteDto.getTipoServico())) {
			descTipoServico = "Incidente";
		}

		HTMLElement divListaServicos = document.getElementById("divDinamicoListaServicos".concat(descTipoServico).concat("Apoio"));

		String filtroServico = servicoRequisicaoIncidenteDto.getFiltroServico();
		if (filtroServico == null) {
			filtroServico = "";
		}

		Integer itensPorPagina = Integer.parseInt(ParametroUtil.getValorParametroCitSmartHashMap(ParametroSistema.QUANT_RETORNO_PESQUISA, "10"));

		Integer paginaSelecionadaRequisicao = servicoRequisicaoIncidenteDto.getPaginaSelecionadaServico();
		if (paginaSelecionadaRequisicao == null || paginaSelecionadaRequisicao == 0) {
			paginaSelecionadaRequisicao = 1;
		}

		Pageable pageable = new PageRequest(paginaSelecionadaRequisicao - 1, itensPorPagina);


		Collection<ServicoDTO> listServicoRequisicao = getServicoService().listServicosNegocioRequisicaoIncidente(servicoRequisicaoIncidenteDto.getTipoServico(), servicoRequisicaoIncidenteDto.getIdPortfolioServico(),
				servicoRequisicaoIncidenteDto.getIdServicoRelacionado(), filtroServico, pageable, false).getContent();

		if (listServicoRequisicao != null && !listServicoRequisicao.isEmpty()) {
			divListaServicos.setInnerHTML(GerenciamentoPortfolio.geraHTMLServicosRequisicaoIncidente(document, request, listServicoRequisicao, servicoRequisicaoIncidenteDto.getTipoServico()));

			Integer totalPaginasRequisicao = getServicoService().listServicosNegocioRequisicaoIncidente(servicoRequisicaoIncidenteDto.getTipoServico(), servicoRequisicaoIncidenteDto.getIdPortfolioServico(),
					servicoRequisicaoIncidenteDto.getIdServicoRelacionado(), filtroServico, pageable, true).getTotalPages();

			HTMLElement paginacaoServicos = document.getElementById("paginacaoServicos".concat(descTipoServico));
			String funcaoJsPaginar = "paginarServicos".concat(descTipoServico).concat("Apoio");
			paginacaoServicos.setInnerHTML(UtilHTML.paginacaoHtml(request, funcaoJsPaginar, totalPaginasRequisicao, paginaSelecionadaRequisicao));
		} else {
			final StringBuilder htmlDivSemRegistros = new StringBuilder();
			htmlDivSemRegistros.append("<h4>" + UtilI18N.internacionaliza(request, "gerenciaportfolio.nenhumServicoRegistrado") + "</h4>");
			divListaServicos.setInnerHTML(htmlDivSemRegistros.toString());
		}

	}

	private void restoreServicoApoioCarregaServicosRequisicaoIncidente(GerenciamentoPortfolioCadastroServicoDTO servicoDTO, DocumentHTML document, HttpServletRequest request) throws Exception {
		if (servicoDTO != null && servicoDTO.getIdServicoRelacionado() != null) {
			servicoDTO.setPaginaSelecionadaServico(1);
			servicoDTO.setFiltroServico("");

			servicoDTO.setTipoServico(TipoServico.SERVICO_REQUISICAO.getIdentificador());
			montaHTMLServicosRequisicaoIncidenteApoio(servicoDTO, document, request);

			servicoDTO.setTipoServico(TipoServico.SERVICO_INCIDENTE.getIdentificador());
			montaHTMLServicosRequisicaoIncidenteApoio(servicoDTO, document, request);

			HTMLForm form = document.getForm("formCadastroServico");
			form.setValues(servicoDTO);
		}
	}

	private void restoreServicoNegocioCarregaServicosRequisicaoIncidente(GerenciamentoPortfolioCadastroServicoDTO servicoDTO, DocumentHTML document, HttpServletRequest request) throws Exception {
		if (servicoDTO != null && servicoDTO.getIdServicoRelacionado() != null) {
			servicoDTO.setPaginaSelecionadaServico(1);
			servicoDTO.setFiltroServico("");

			montaHTMLServicosRequisicaoIncidenteNegocio(servicoDTO, document, request);

			HTMLForm form = document.getForm("formCadastroServico");
			form.setValues(servicoDTO);
		}
	}

	public void desvincularServicoNegocioRequisicaoIncidente(final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) throws ServiceException, Exception {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}
		GerenciamentoPortfolioCadastroServicoDTO servicoRequisicaoDto = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();
		setPermissoesServico(document, request);

		if (permissao.isGravar()) {
			if (servicoRequisicaoDto.getIdServico() != null && servicoRequisicaoDto.getIdServicoRelacionado() != null) {
				this.getServicoAutoRelacionamentoService().deleteServicoRelacionado(servicoRequisicaoDto.getIdServico(), servicoRequisicaoDto.getIdServicoRelacionado());
				document.alert(UtilI18N.internacionaliza(request, "gerenciaportfolio.servicoDesvinculadoSucesso"));
				montaHTMLServicosRequisicaoIncidenteNegocio(servicoRequisicaoDto, document, request);
				servicoRequisicaoDto.setIdsServicoOcorrenciaServico(servicoRequisicaoDto.getIdServico().toString());
				servicoRequisicaoDto.setAcaoServicoOcorrenciaServico(AuditoriaAcoes.DESVINCULADO.getIdentificador());
				this.salvarOcorrenciaServicoRelacionado(document, request, response);
			} else {
				document.alert(UtilI18N.internacionaliza(request, "gerenciaportfolio.servicoDesvinculadoErro"));
			}
		} else {
			document.executeScript("notificacaoErro('citcorpore.comum.permissaoFuncionalidade');");
		}
	}

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

		if (permissao.isGravar()) {
			GerenciamentoPortfolioCadastroServicoDTO gerenciamentoPortfolioCadastroServicoDto = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();

			if (SimNao.SIM.getValorStr().equalsIgnoreCase(gerenciamentoPortfolioCadastroServicoDto.getDispPortal()) && UtilStrings.isNotVazio(gerenciamentoPortfolioCadastroServicoDto.getImagemPortal())) {
				gerenciamentoPortfolioCadastroServicoDto.setImagemPortal(gerenciamentoPortfolioCadastroServicoDto.getImagemPortal().replace(CITCorporeUtil.CONTEXTO_APLICACAO, ""));
			}

			ServicoDTO servicoDto = new ServicoDTO();
			ServicoAutoRelacionamentoDTO servicoAutoRelacionamentoDTO = new ServicoAutoRelacionamentoDTO();

			Reflexao.copyPropertyValues(gerenciamentoPortfolioCadastroServicoDto, servicoDto);
			Reflexao.copyPropertyValues(gerenciamentoPortfolioCadastroServicoDto, servicoAutoRelacionamentoDTO);

			if (servicoDto != null && servicoAutoRelacionamentoDTO.getIdServicoRelacionado() != null) {
				servicoDto.setIdEmpresa(WebUtil.getIdEmpresa(request));

				if (servicoDto != null && servicoDto.getIdServico() != null) {
					this.getServicoService().update(servicoDto);
					document.alert(UtilI18N.internacionaliza(request, "MSG06"));
					gerenciamentoPortfolioCadastroServicoDto.setAcaoServicoOcorrenciaServico(AuditoriaAcoes.ALTERADO.getIdentificador());
				} else {
					servicoDto.setDataInicio(UtilDatas.getDataAtual());
					this.getServicoService().create(servicoDto);

					servicoAutoRelacionamentoDTO.setIdServico(servicoDto.getIdServico());
					servicoAutoRelacionamentoDTO.setDataInicio(UtilDatas.getDataAtual());

					this.getServicoAutoRelacionamentoService().create(servicoAutoRelacionamentoDTO);
					document.alert(UtilI18N.internacionaliza(request, "MSG05"));
					gerenciamentoPortfolioCadastroServicoDto.setAcaoServicoOcorrenciaServico(AuditoriaAcoes.VINCULADO.getIdentificador());
				}

				if (servicoDto != null && servicoDto.getIdServico() != null) {
					gerenciamentoPortfolioCadastroServicoDto.setIdsServicoOcorrenciaServico(servicoDto.getIdServico().toString());
					this.salvarOcorrenciaServicoRelacionado(document, request, response);
				}
			}
		} else {
			document.executeScript("notificacaoErro('citcorpore.comum.permissaoFuncionalidade');");
		}

	}

	public void restore(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		WebUtil.validarSeUsuarioEstaNaSessao(request, document);
		GerenciamentoPortfolioCadastroServicoDTO gerenciamentoPortfolioCadastroServicoDto = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();

		if (gerenciamentoPortfolioCadastroServicoDto.getIdServico() != null) {

			ServicoDTO servicoDto = new ServicoDTO();
			servicoDto.setIdServico(gerenciamentoPortfolioCadastroServicoDto.getIdServico());

			servicoDto = this.getServicoService().restore(servicoDto);

			if (servicoDto != null && servicoDto.getIdServico() != null) {

				if(servicoDto.getIdCategoriaServico() != null){
					CategoriaServicoDTO categoriaServicoDto = new CategoriaServicoDTO();
					categoriaServicoDto.setIdCategoriaServico(servicoDto.getIdCategoriaServico());
					categoriaServicoDto = this.getCategoriaServicoService().restore(categoriaServicoDto);
					if (categoriaServicoDto != null && categoriaServicoDto.getIdCategoriaServico() != null && categoriaServicoDto.getNomeCategoriaServico() != null) {
						HTMLElement nomeCategoriaServico = document.getElementById("nomeCategoriaServicoReqIncOS");
						nomeCategoriaServico.setValue(categoriaServicoDto.getNomeCategoriaServico());
					}
				}

				if(servicoDto.getIdBaseconhecimento() != null){
					BaseConhecimentoDTO baseConhecimentoDto = new BaseConhecimentoDTO();
					baseConhecimentoDto.setIdBaseConhecimento(servicoDto.getIdBaseconhecimento());
					baseConhecimentoDto = this.getBaseConhecimentoService().restore(baseConhecimentoDto);

					if(baseConhecimentoDto != null && baseConhecimentoDto.getIdBaseConhecimento()!=null && baseConhecimentoDto.getTitulo()!=null){
						HTMLElement tituloBaseConhecimento = document.getElementById("tituloBaseConhecimentoReqIncOS");
						tituloBaseConhecimento.setValue(baseConhecimentoDto.getTitulo());
					}
				}

				Integer idContrato = gerenciamentoPortfolioCadastroServicoDto.getIdContratoServico();

				Reflexao.copyPropertyValues(servicoDto, gerenciamentoPortfolioCadastroServicoDto);

				if (gerenciamentoPortfolioCadastroServicoDto != null) {
					gerenciamentoPortfolioCadastroServicoDto.setIdContratoServico(idContrato);
				}

				HTMLForm form = document.getForm("formCadastroServico");
				form.setValues(gerenciamentoPortfolioCadastroServicoDto);

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

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

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

	}

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

		if (gerenciamentoPortfolioCadastroServicoDto != null && gerenciamentoPortfolioCadastroServicoDto.getIdServico() != null) {
			setPermissoesServico(document, request);
			if (permissao.isDeletar()) {
				ServicoDTO servicoDto = new ServicoDTO();
				servicoDto.setIdServico(gerenciamentoPortfolioCadastroServicoDto.getIdServico());
				servicoDto = this.getServicoService().restore(servicoDto);

				if (servicoDto != null && servicoDto.getIdServico() != null) {
					servicoDto.setDeleted("y");

					this.getServicoService().update(servicoDto);

					document.alert(UtilI18N.internacionaliza(request, "MSG07"));
					document.executeScript("voltarParaListaServicos();");
					gerenciamentoPortfolioCadastroServicoDto.setIdsServicoOcorrenciaServico(gerenciamentoPortfolioCadastroServicoDto.getIdServico().toString());
					gerenciamentoPortfolioCadastroServicoDto.setAcaoServicoOcorrenciaServico(AuditoriaAcoes.DESVINCULADO.getIdentificador());
					this.salvarOcorrenciaServicoRelacionado(document, request, response);
				}
			} else {
				document.executeScript("notificacaoErro('citcorpore.comum.permissaoFuncionalidade');");
			}
		}
	}

	public void definirDadosFixosServicoAndRestore(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		definirDadosFixosServico(document, request, response);
		GerenciamentoPortfolio.setPortalImages(document);
		restore(document, request, response);
	}

	public void definirDadosFixosServico(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		setPermissoesServico(document, request);
		carregaCombosCadastroServico(document, request, response);
		setarDataImplantacao(document, request);
		try {
			GerenciamentoPortfolioCadastroServicoDTO gerenciamentoPortfolioCadastroServicoDto = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();

			if (gerenciamentoPortfolioCadastroServicoDto != null && gerenciamentoPortfolioCadastroServicoDto.getTipoServico() != null) {
				ServiceDemandType tipoDemandaServico = ServiceDemandType.fromClassification(gerenciamentoPortfolioCadastroServicoDto.getTipoServico());

				if (tipoDemandaServico != null) {
					gerenciamentoPortfolioCadastroServicoDto.setIdTipoDemandaServico(tipoDemandaServico.getId());
				}

				HTMLForm form = document.getForm("formCadastroServico");
				form.setValues(gerenciamentoPortfolioCadastroServicoDto);
				setarDataImplantacao(document, request);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		document.executeScript("depoisDefinirDadosFixosServico();");
	}

	public void vincularServicos(final String tipoServico, final Integer idPortfolioServico, final Integer idServicoNegocioApoio, final String listaServicosStr, final DocumentHTML document, final HttpServletRequest request, final HttpServletResponse response) {
		if (!WebUtil.validarSeUsuarioEstaNaSessao(request, document)) {
			return;
		}
		setPermissoesServico(document, request);
		if (permissao.isGravar()) {
			try {
				String[] listaServicosApoio = new String[] {};

				listaServicosApoio = listaServicosStr.split(";");

				if (idServicoNegocioApoio > 0 && listaServicosApoio != null && listaServicosApoio.length > 0) {
					for (String idServicoApoio : listaServicosApoio) {
						ServicoAutoRelacionamentoDTO autoRelacionamento = new ServicoAutoRelacionamentoDTO();

						autoRelacionamento.setIdServico(Integer.parseInt(idServicoApoio));
						autoRelacionamento.setIdServicoRelacionado(idServicoNegocioApoio);
						autoRelacionamento.setFaseServico(getServicoService().recuperaFaseServico(idServicoNegocioApoio));
						autoRelacionamento.setStatusServico(getServicoService().recuperaStatusServico(idServicoNegocioApoio));
						autoRelacionamento.setDataInicio(UtilDatas.getDataAtual());

						this.getServicoAutoRelacionamentoService().create(autoRelacionamento);
					}
					document.alert(UtilI18N.internacionaliza(request, "gerenciaportfolio.servicoVinculadoSucesso"));
				}

				GerenciamentoPortfolioCadastroServicoDTO servicoReqInc = new GerenciamentoPortfolioCadastroServicoDTO();
				servicoReqInc.setIdPortfolioServico(idPortfolioServico);
				servicoReqInc.setIdServicoRelacionado(idServicoNegocioApoio);
				servicoReqInc.setTipoServico(tipoServico);

				String tipoServicoRelacionado = getTipoServico(idServicoNegocioApoio);

				if (TipoServico.SERVICO_NEGOCIO.getIdentificador().equalsIgnoreCase(tipoServicoRelacionado)) {
					montaHTMLServicosRequisicaoIncidenteNegocio(servicoReqInc, document, request);
				} else if (TipoServico.SERVICO_APOIO.getIdentificador().equalsIgnoreCase(tipoServicoRelacionado)) {
					montaHTMLServicosRequisicaoIncidenteApoio(servicoReqInc, document, request);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			document.executeScript("notificacaoErro('citcorpore.comum.permissaoFuncionalidade');");
		}
	}

	private String getTipoServico(Integer idServico) throws ServiceException, Exception {
		return getServicoService().recuperaTipoServico(idServico);
	}

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

	private CategoriaServicoService getCategoriaServicoService() throws ServiceException {
		if (categoriaServicoService == null) {
			categoriaServicoService = (CategoriaServicoService) ServiceLocator.getInstance().getService(CategoriaServicoService.class, null);
		}
		return categoriaServicoService;
	}

	private BaseConhecimentoService getBaseConhecimentoService() throws ServiceException {
		if (baseConhecimentoService == null) {
			baseConhecimentoService = (BaseConhecimentoService) ServiceLocator.getInstance().getService(BaseConhecimentoService.class, null);
		}
		return baseConhecimentoService;
	}

	private TemplateSolicitacaoServicoService getTemplateSolicitacaoServicoService() throws ServiceException {
		if (templateSolicitacaoServicoService == null) {
			templateSolicitacaoServicoService = (TemplateSolicitacaoServicoService) ServiceLocator.getInstance().getService(TemplateSolicitacaoServicoService.class, null);
		}
		return templateSolicitacaoServicoService;
	}

	private ServicoAutoRelacionamentoService getServicoAutoRelacionamentoService() throws ServiceException {
		if (servicoAutoRelacionamentoService == null) {
			servicoAutoRelacionamentoService = (ServicoAutoRelacionamentoService) ServiceLocator.getInstance().getService(ServicoAutoRelacionamentoService.class, null);
		}
		return servicoAutoRelacionamentoService;
	}

	private TipoServicoService getTipoServicoService() throws ServiceException {
		if (tipoServicoService == null) {
			tipoServicoService = (TipoServicoService) ServiceLocator.getInstance().getService(TipoServicoService.class, null);
		}
		return tipoServicoService;
	}


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

	/**
	 * @author deborah.ferreira
	 * @since 27.01.2016
	 */

	public void salvarOcorrenciaServicoRelacionado(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception {
		GerenciamentoPortfolioCadastroServicoDTO gerenciamentoPortfolioCadastroServicoDTO = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();
		GerenciamentoPortfolioOcorrenciasServico gerenciamentoPortfolioOcorrenciasServico = new GerenciamentoPortfolioOcorrenciasServico();

		gerenciamentoPortfolioOcorrenciasServico.salvaOcorrenciaServicoRelacionado(gerenciamentoPortfolioCadastroServicoDTO.getIdServicoRelacionado(),
				gerenciamentoPortfolioCadastroServicoDTO.getIdsServicoOcorrenciaServico(), gerenciamentoPortfolioCadastroServicoDTO.getAcaoServicoOcorrenciaServico(),
				gerenciamentoPortfolioCadastroServicoDTO.getTipoServico(), document, request);
	}


	/**
	 * @author gilmar.junior
	 * @since 11.08.2016
	 *
	 */
	public void recuperaServicoRelacionadoDeletado(DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception{
		setPermissoesServico(document, request);

		if (permissao.isGravar()) {
			GerenciamentoPortfolioCadastroServicoDTO servicoRequisicaoDto = (GerenciamentoPortfolioCadastroServicoDTO) document.getBean();
			if (servicoRequisicaoDto != null && servicoRequisicaoDto.getIdServico() != null && servicoRequisicaoDto.getIdServicoRelacionado() != null) {
				this.getServicoAutoRelacionamentoService().recuperaServicoRelacionadoDeletado(servicoRequisicaoDto.getIdServico(), servicoRequisicaoDto.getIdServicoRelacionado());
			}
		} else {
			document.executeScript("notificacaoErro('citcorpore.comum.permissaoFuncionalidade');");
		}
	}
}
