/**
  * TRATAMENTO DE MATRIZ Este metodo trata do motor do sistema dinamico de gravacao de dados de
  * visoes (montadas dinamicamente)
  */
 @Override
 public void saveMatriz(
     final UsuarioDTO usuarioDto,
     final DinamicViewsDTO dinamicViewDto,
     final HttpServletRequest request)
     throws Exception {
   final String jsonMatriz = dinamicViewDto.getJsonMatriz();
   Map<String, Object> mapMatriz = null;
   try {
     mapMatriz = JSONUtil.convertJsonToMap(jsonMatriz, true);
   } catch (final Exception e) {
     LOGGER.error(e.getMessage(), e);
     LOGGER.debug("jsonMatriz: " + jsonMatriz);
     throw e;
   }
   final Collection colCamposPKPrincipal = new ArrayList<>();
   final Collection colCamposTodosPrincipal = new ArrayList<>();
   final List colMatrizTratada = (List) mapMatriz.get("MATRIZ");
   if (colMatrizTratada != null) {
     final Integer idVisao = dinamicViewDto.getDinamicViewsIdVisao();
     this.setInfoSave(idVisao, colCamposPKPrincipal, colCamposTodosPrincipal);
     CamposObjetoNegocioDTO camposObjetoNegocioDTO = null;
     if (colCamposPKPrincipal != null && colCamposPKPrincipal.size() > 0) {
       camposObjetoNegocioDTO = (CamposObjetoNegocioDTO) colCamposPKPrincipal.iterator().next();
     }
     if (camposObjetoNegocioDTO == null) {
       throw new Exception("Problema ao obter a chave da VISAO!");
     }
     for (final Iterator it = colMatrizTratada.iterator(); it.hasNext(); ) {
       final HashMap mapItem = (HashMap) it.next();
       mapItem.put(camposObjetoNegocioDTO.getNomeDB(), mapItem.get("FLD_0"));
       LOGGER.debug("Processando... " + mapItem);
       this.save(usuarioDto, dinamicViewDto, mapItem, request);
     }
   }
 }
  /**
   * Este metodo trata do motor do sistema dinamico de gravacao de dados de visoes (montadas
   * dinamicamente)
   */
  @Override
  public void save(
      final UsuarioDTO usuarioDto,
      final DinamicViewsDTO dinamicViewDto,
      final Map map,
      final HttpServletRequest request)
      throws Exception {
    final VisaoRelacionadaDao visaoRelacionadaDao = new VisaoRelacionadaDao();
    final GrupoVisaoDao grupoVisaoDao = new GrupoVisaoDao();
    final GrupoVisaoCamposNegocioDao grupoVisaoCamposNegocioDao = new GrupoVisaoCamposNegocioDao();
    final CamposObjetoNegocioDao camposObjetoNegocioDao = new CamposObjetoNegocioDao();
    final VinculoVisaoDao vinculoVisaoDao = new VinculoVisaoDao();
    final ScriptsVisaoDao scriptsVisaoDao = new ScriptsVisaoDao();
    final MatrizVisaoDao matrizVisaoDao = new MatrizVisaoDao();
    final VisaoDao visaoDao = this.getDao();
    final TransactionControler tc = this.getDao().getTransactionControler();

    visaoRelacionadaDao.setTransactionControler(tc);
    grupoVisaoDao.setTransactionControler(tc);
    grupoVisaoCamposNegocioDao.setTransactionControler(tc);
    camposObjetoNegocioDao.setTransactionControler(tc);
    vinculoVisaoDao.setTransactionControler(tc);
    scriptsVisaoDao.setTransactionControler(tc);
    matrizVisaoDao.setTransactionControler(tc);

    final Integer idVisao = dinamicViewDto.getDinamicViewsIdVisao();
    final Collection colScripts = scriptsVisaoDao.findByIdVisao(idVisao);
    final HashMap mapScritps = new HashMap<>();
    if (colScripts != null) {
      for (final Iterator it = colScripts.iterator(); it.hasNext(); ) {
        final ScriptsVisaoDTO scriptsVisaoDTO = (ScriptsVisaoDTO) it.next();
        mapScritps.put(
            scriptsVisaoDTO.getTypeExecute() + "#" + scriptsVisaoDTO.getScryptType().trim(),
            scriptsVisaoDTO.getScript());
      }
    }

    final Collection colCamposPKPrincipal = new ArrayList<>();
    final Collection colCamposTodosPrincipal = new ArrayList<>();
    Collection colCamposTodosVinc = null;
    CamposObjetoNegocioDTO camposObjetoNegocioChaveMatriz = new CamposObjetoNegocioDTO();

    this.setInfoSave(idVisao, colCamposPKPrincipal, colCamposTodosPrincipal);

    final Collection colVisoesRelacionadas = visaoRelacionadaDao.findByIdVisaoPaiAtivos(idVisao);

    try {
      tc.start();

      if (this.isPKExists(colCamposPKPrincipal, map)) {
        String strScript =
            (String)
                mapScritps.get(
                    ScriptsVisaoDTO.SCRIPT_EXECUTE_SERVER
                        + "#"
                        + ScriptsVisaoDTO.SCRIPT_ONUPDATE.getName());
        if (strScript != null && !strScript.trim().equalsIgnoreCase("")) {
          final ScriptRhinoJSExecute scriptExecute = new ScriptRhinoJSExecute();
          final RuntimeScript runtimeScript = new RuntimeScript();
          final Context cx = Context.enter();
          final Scriptable scope = cx.initStandardObjects();
          scope.put("mapFields", scope, map);
          final String action = "UPDATE";
          scope.put("ACTION", scope, action);
          scope.put("userLogged", scope, usuarioDto);
          scope.put("transactionControler", scope, tc);
          scope.put("dinamicViewDto", scope, dinamicViewDto);
          scope.put("RuntimeScript", scope, runtimeScript);
          scope.put("language", scope, WebUtil.getLanguage(request));
          scriptExecute.processScript(
              cx,
              scope,
              strScript,
              VisaoServiceEjb.class.getName() + "_" + ScriptsVisaoDTO.SCRIPT_ONUPDATE.getName());
        }
        if (!dinamicViewDto.isAbortFuncaoPrincipal()) {
          this.updateFromMap(map, colCamposTodosPrincipal, usuarioDto, visaoDao, request);
          strScript =
              (String)
                  mapScritps.get(
                      ScriptsVisaoDTO.SCRIPT_EXECUTE_SERVER
                          + "#"
                          + ScriptsVisaoDTO.SCRIPT_AFTERUPDATE.getName());
          if (strScript != null && !strScript.trim().equalsIgnoreCase("")) {
            final ScriptRhinoJSExecute scriptExecute = new ScriptRhinoJSExecute();
            final RuntimeScript runtimeScript = new RuntimeScript();
            final Context cx = Context.enter();
            final Scriptable scope = cx.initStandardObjects();
            scope.put("mapFields", scope, map);
            final String action = "UPDATE";
            scope.put("ACTION", scope, action);
            scope.put("userLogged", scope, usuarioDto);
            scope.put("transactionControler", scope, tc);
            scope.put("dinamicViewDto", scope, dinamicViewDto);
            scope.put("RuntimeScript", scope, runtimeScript);
            scope.put("language", scope, WebUtil.getLanguage(request));
            scriptExecute.processScript(
                cx,
                scope,
                strScript,
                VisaoServiceEjb.class.getName()
                    + "_"
                    + ScriptsVisaoDTO.SCRIPT_AFTERUPDATE.getName());
          }
        }
      } else {
        String strScript =
            (String)
                mapScritps.get(
                    ScriptsVisaoDTO.SCRIPT_EXECUTE_SERVER
                        + "#"
                        + ScriptsVisaoDTO.SCRIPT_ONCREATE.getName());
        if (strScript != null && !strScript.trim().equalsIgnoreCase("")) {
          final ScriptRhinoJSExecute scriptExecute = new ScriptRhinoJSExecute();
          final RuntimeScript runtimeScript = new RuntimeScript();
          final Context cx = Context.enter();
          final Scriptable scope = cx.initStandardObjects();
          scope.put("mapFields", scope, map);
          final String action = "CREATE";
          scope.put("ACTION", scope, action);
          scope.put("userLogged", scope, usuarioDto);
          scope.put("transactionControler", scope, tc);
          scope.put("dinamicViewDto", scope, dinamicViewDto);
          scope.put("RuntimeScript", scope, runtimeScript);
          scope.put("language", scope, WebUtil.getLanguage(request));
          scriptExecute.processScript(
              cx,
              scope,
              strScript,
              VisaoServiceEjb.class.getName() + "_" + ScriptsVisaoDTO.SCRIPT_ONCREATE.getName());
        }
        if (!dinamicViewDto.isAbortFuncaoPrincipal()) {
          this.createFromMap(map, colCamposTodosPrincipal, usuarioDto, visaoDao, request);
          strScript =
              (String)
                  mapScritps.get(
                      ScriptsVisaoDTO.SCRIPT_EXECUTE_SERVER
                          + "#"
                          + ScriptsVisaoDTO.SCRIPT_AFTERCREATE.getName());
          if (strScript != null && !strScript.trim().equalsIgnoreCase("")) {
            final ScriptRhinoJSExecute scriptExecute = new ScriptRhinoJSExecute();
            final RuntimeScript runtimeScript = new RuntimeScript();
            final Context cx = Context.enter();
            final Scriptable scope = cx.initStandardObjects();
            scope.put("mapFields", scope, map);
            final String action = "CREATE";
            scope.put("ACTION", scope, action);
            scope.put("userLogged", scope, usuarioDto);
            scope.put("transactionControler", scope, tc);
            scope.put("dinamicViewDto", scope, dinamicViewDto);
            scope.put("RuntimeScript", scope, runtimeScript);
            scope.put("language", scope, WebUtil.getLanguage(request));
            scriptExecute.processScript(
                cx,
                scope,
                strScript,
                VisaoServiceEjb.class.getName()
                    + "_"
                    + ScriptsVisaoDTO.SCRIPT_AFTERCREATE.getName());
          }
        }
      }
      if (colVisoesRelacionadas != null) {
        for (final Iterator it = colVisoesRelacionadas.iterator(); it.hasNext(); ) {
          final VisaoRelacionadaDTO visaoRelacionadaDto = (VisaoRelacionadaDTO) it.next();
          final Collection colVinculos =
              vinculoVisaoDao.findByIdVisaoRelacionada(visaoRelacionadaDto.getIdVisaoRelacionada());

          final Object objFromHash =
              map.get(
                  VisaoRelacionadaDTO.PREFIXO_SISTEMA_TABELA_VINCULADA
                      + visaoRelacionadaDto.getIdVisaoFilha());
          VisaoDTO visaoDtoAux = new VisaoDTO();
          visaoDtoAux.setIdVisao(visaoRelacionadaDto.getIdVisaoFilha());
          visaoDtoAux = (VisaoDTO) visaoDao.restore(visaoDtoAux);
          MatrizVisaoDTO matrizVisaoDTO = new MatrizVisaoDTO();
          boolean ehMatriz = false;
          if (visaoDtoAux != null) {
            if (visaoDtoAux.getTipoVisao().equalsIgnoreCase(VisaoDTO.MATRIZ)) {
              ehMatriz = true;
              matrizVisaoDTO.setIdVisao(visaoDtoAux.getIdVisao());
              final Collection colMatriz = matrizVisaoDao.findByIdVisao(visaoDtoAux.getIdVisao());
              if (colMatriz != null && colMatriz.size() > 0) {
                matrizVisaoDTO = (MatrizVisaoDTO) colMatriz.iterator().next();
                camposObjetoNegocioChaveMatriz.setIdCamposObjetoNegocio(
                    matrizVisaoDTO.getIdCamposObjetoNegocio1());
                camposObjetoNegocioChaveMatriz.setIdObjetoNegocio(
                    matrizVisaoDTO.getIdObjetoNegocio());
                camposObjetoNegocioChaveMatriz =
                    (CamposObjetoNegocioDTO)
                        camposObjetoNegocioDao.restore(camposObjetoNegocioChaveMatriz);
              }
            }
          }

          if (HashMap.class.isInstance(objFromHash)) {
            final HashMap mapVinc = (HashMap) objFromHash;
            if (mapVinc != null) { // Se existir dados recebidos.
              final Collection colCamposPKVinc = new ArrayList<>();
              colCamposTodosVinc = new ArrayList<>();
              this.setInfoSave(
                  visaoRelacionadaDto.getIdVisaoFilha(), colCamposPKVinc, colCamposTodosVinc);
              // Grava os dados de informacoes vinculadas.
              if (this.isPKExists(colCamposPKVinc, mapVinc)) {
                this.updateFromMap(mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request);
              } else {
                this.createFromMap(mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request);
              }
            }
          } else if (Collection.class.isInstance(objFromHash)) {
            final Collection colVinc = (Collection) objFromHash;
            if (colVinc != null) {
              for (final Iterator it2 = colVinc.iterator(); it2.hasNext(); ) {
                Map mapVinc = (Map) it2.next();
                if (mapVinc != null) { // Se existir dados recebidos.
                  final Collection colCamposPKVinc = new ArrayList<>();
                  colCamposTodosVinc = new ArrayList<>();
                  this.setInfoSave(
                      visaoRelacionadaDto.getIdVisaoFilha(),
                      colCamposPKVinc,
                      colCamposTodosVinc); // *****
                  String tipoVinc = "";
                  if (colVinculos != null && colVinculos.size() > 0) {
                    final VinculoVisaoDTO vinculoVisaoDTO =
                        (VinculoVisaoDTO) ((List) colVinculos).get(0);
                    tipoVinc = vinculoVisaoDTO.getTipoVinculo();
                  }
                  if (ehMatriz) {
                    if (camposObjetoNegocioChaveMatriz != null) {
                      mapVinc.put(camposObjetoNegocioChaveMatriz.getNomeDB(), mapVinc.get("FLD_0"));
                    }
                    CamposObjetoNegocioDTO camposObjetoNegocioDTO = null;
                    if (colCamposPKVinc != null && colCamposPKVinc.size() > 0) {
                      for (final Iterator itVinc = colCamposPKVinc.iterator(); itVinc.hasNext(); ) {
                        camposObjetoNegocioDTO = (CamposObjetoNegocioDTO) itVinc.next();
                        if (!camposObjetoNegocioDTO
                            .getNomeDB()
                            .trim()
                            .equalsIgnoreCase(camposObjetoNegocioChaveMatriz.getNomeDB().trim())) {
                          mapVinc.put(
                              camposObjetoNegocioDTO.getNomeDB(),
                              map.get(camposObjetoNegocioDTO.getNomeDB()));
                        }
                      }
                    }
                    if (tipoVinc == null || tipoVinc.equalsIgnoreCase("")) {
                      tipoVinc = VinculoVisaoDTO.VINCULO_1_TO_N;
                    }
                  }
                  if (tipoVinc.equalsIgnoreCase(VinculoVisaoDTO.VINCULO_N_TO_N)) {
                    // Grava os dados de informacoes vinculadas.
                    if (this.isPKExists(colCamposPKVinc, mapVinc)) {
                      this.updateFromMap(
                          mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request);
                    } else {
                      this.createFromMap(
                          mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request);
                    }
                    this.processCreateVinc(
                        visaoRelacionadaDto, colVinculos, map, mapVinc, usuarioDto, request);
                  }
                  if (tipoVinc.equalsIgnoreCase(VinculoVisaoDTO.VINCULO_1_TO_N)) {
                    mapVinc = this.createUniqueMap(map, mapVinc); // ******
                    // Grava os dados de informacoes vinculadas.
                    if (this.isPKExists(colCamposPKVinc, mapVinc)) {
                      this.updateFromMap(
                          mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request);
                    } else {
                      this.createFromMap(
                          mapVinc, colCamposTodosVinc, usuarioDto, visaoDao, request);
                    }
                  }
                }
              }
            }
          }
        }
      }

      if (dinamicViewDto.getIdFluxo() != null || dinamicViewDto.getIdTarefa() != null) {
        new ExecucaoSolicitacaoServiceEjb()
            .executa(
                usuarioDto,
                tc,
                dinamicViewDto.getIdFluxo(),
                dinamicViewDto.getIdTarefa(),
                dinamicViewDto.getAcaoFluxo(),
                map,
                colCamposTodosPrincipal,
                colCamposTodosVinc);
      }

      tc.commit();
      tc.close();
    } catch (final Exception e) {
      this.rollbackTransaction(tc, e);
    }
  }