<?php include_once('../../config.php') ?>
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Sisplan Web | Loja</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css?versao=3.258.28.1">
  <!-- Theme style -->
  <link rel="stylesheet" href="dist/css/adminlte.min.css?versao=3.258.28.1">
  <!-- overlayScrollbars -->
  <link rel="stylesheet" href="plugins/overlayScrollbars/css/OverlayScrollbars.min.css?versao=3.258.28.1">
  <!-- Daterange picker -->
  <link rel="stylesheet" href="plugins/daterangepicker/daterangepicker.css?versao=3.258.28.1">
  <!-- Google Font: Source Sans Pro -->
  <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet">
  <link rel="stylesheet" href="dist/css/animate.min.css?versao=3.258.28.1">
  <link rel="stylesheet" href="dist/css/custom.css?versao=3.258.28.1">
  <link rel="stylesheet" href="dist/css/sisplan.css?versao=3.258.28.1">
  <link rel="stylesheet" type="text/css" href="dist/css/dataTables.bootstrap4.min.css?versao=3.258.28.1" />
  <link rel="shortcut icon" href="favicon.ico">
  <link href="dist/css/jquery.gridly.css?versao=3.258.28.1" rel="stylesheet" type="text/css" />
  <link rel="stylesheet" href="plugins/toastr/toastr.min.css?versao=3.258.28.1">
  <style type="text/css">
    .dash {
      width: 150px;
      height: 80px;
      display: flex;
      justify-content: space-evenly;
      align-content: center;
      flex-wrap: wrap;
      background-color: var(--blue-color);
      border-radius: 5px;
      text-align: center;


    }

    .dash p {
      margin-bottom: 0px;
    }

    .content-wrapper {
      margin-left: 0px !important;
    }

    .main-header,
    .main-sidebar,
    footer {
      display: none;
    }
  </style>

</head>

<body class="hold-transition sidebar-mini layout-fixed">
  <div class="wrapper">
    <?php
    include_once('../../menu.php');
    ?>
    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
      <!-- Content Header (Page header) -->
      <div class="content-header">
        <div class="container-fluid">
          <div class="row mb-2">
            <div class="col-sm-6 flex">
              <h1 class="m-0 text-dark">Dashboards</h1>
            </div>
            <div class="col-sm-6">

            </div>
          </div>
        </div>
      </div>

      <!-- Main content -->
      <section class="content">
        <div class="container-fluid">
          <div class="row">
            <div class="col-sm-12 mb-2">
              <button id="btn-novo" class="btn btn-sm btn-success" title="Novo Dashboard"><i class="fas fa-plus"></i>
                <h7>Novo</h7>
              </button>
            </div>
            <div class="col-sm-12">
              <h7>Lista de Dashboards</h7>
            </div>
            <div class="col-sm-12 table-responsive">
              <table width="100%" style="width:100%;" id="tabela-dashboards" class="table table-sm"></table>
            </div>
          </div>
        </div>
      </section>
      <section class="content">
        <div class="modal fade" id="modal-edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
          <div class="modal-dialog modal-lg">
            <div class="modal-content modal-lg">
              <div class="modal-header">
                <h4 id="modal-titulo" class="modal-title">Dashboard: </h4>
                <h4 class="modal-title" id="id-dash"></h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                <div class="row">
                  <div class="col-sm-12">
                    <div class="group-default">
                      <label for="txtNomeDash">Nome</label>
                      <div class="relative">
                        <input type="text" placeholder="Nome" class="input-default focus form-control" id="txtNomeDash" name="txtNomeDash">
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="modal-footer">
                <div class="row">
                  <div class="col-sm-12">
                    <button id="btn-confirmar-edit" type="button" class="btn btn-danger btn-sisp float-right"> Confirmar
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->

    <!-- Control Sidebar -->
    <aside class="control-sidebar control-sidebar-dark">
    </aside>
    <!-- /.control-sidebar -->
  </div>
  </div>
  <!-- ./wrapper -->
  <div class="align-left">
    <?php include_once('../../modais.php'); ?>
  </div>
  <!-- jQuery -->
  <script src="plugins/jquery/jquery.min.js?versao=3.258.28.1"></script>
  <!-- jQuery UI 1.11.4 -->
  <script src="plugins/jquery-ui/jquery-ui.min.js?versao=3.258.28.1"></script>
  <!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
  <script>
    $.widget.bridge('uibutton', $.ui.button)
  </script>

  <script type="text/javascript" src="plugins/bootstrap/js/bootstrap.bundle.min.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="plugins/chart.js/Chart.min.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="plugins/sparklines/sparkline.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="dist/js/sisplan.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="utils/funcoes.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="dist/js/adminlte.min.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="dist/js/jquery.dataTables.min.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="dist/js/loadingoverlay.min.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="dist/js/dataTables.bootstrap4.min.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="dist/js/sum().js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="dist/js/jquery.maskMoney.min.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="dist/js/dataTables.keyTable.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="utils/cookies.js?versao=3.258.28.1"></script>
  <script type="text/javascript" src="dist/js/requisicoes.js?versao=3.258.28.1"></script>
  <script src="plugins/toastr/toastr.min.js?versao=3.258.28.1"></script>
  <script>
    $(document).ready(async function() {

      ipInterno = IP_INTERNO;
      ipExterno = IP_EXTERNO;
      basicAuth = BASIC_AUTH;

      const permissaoUsuarioLogado = await permissaoAcessos("CADASTRO_DASHBOARD");

      const temAcesso = await temAcessoTela('CADASTRO_DASHBOARD');
      if (!temAcesso.resultado) {
        toastrAcesso(temAcesso, '<?php echo BASE_URI; ?>');
        return;
      }

      async function buscaDashboards() {
        const _url = '';
        const _params = '';
        var dataSetCols = [];
        var dataSet = [];
        try {
          $.LoadingOverlay("show");
          try {
            var response = await requisicao('GET', '/sisplan/funcoes/v1/pesquisa?',
              `JSON={"tabela":"dash_web", "camposSelect":["id", "nome"], "where": null}`, null);

            if (!response) {
              return;
            }

            var jsonStr = await response.json();
            if (response.status != 200) {
              msgErro(jsonStr['RESULT'][0].mensagem);
              return;
            }

            if ((!$.isEmptyObject(jsonStr)) && (jsonStr['RESULT'][0].length != 0)) {
              dataSet = jsonStr['RESULT'][0];
              var keys = Object.keys(dataSet[0]);
              for (var k in keys) {
                dataSetCols.push({
                  'title': keys[k],
                  'data': keys[k]
                });
              }

              var table = $('#tabela-dashboards').DataTable({
                paging: true,
                filter: false,
                info: true,
                order: false,
                destroy: true,
                "columns": dataSetCols,
                "columnDefs": [{
                  targets: [0],
                  render: function(data, type, row) {
                    return retornaBotaoOpcoes(data);
                  }
                }],
                data: dataSet
              });

              $('#tabela-dashboards').on('click', '#btn-editar', async function() {
                if (permissaoUsuarioLogado.ALTERA == 'S') {
                  event.preventDefault();
                  var data = table.row($(this).parents('tr')).data();
                  window.location.href = "dashboard/" + data.ID;
                } else {
                  msgAlertaSemConfirmacao("Sem permissão para alterar!");
                }

              });

              $('#tabela-dashboards').on('dblclick', 'tr', async function() {
                event.preventDefault();
                var data = table.row($(this)).data();
                window.location.href = "dashboard/" + data.ID;
              });

              $('#tabela-dashboards').on('click', '#btn-excluir', async function() {

                if (permissaoUsuarioLogado.INCLUI == 'S') {

                  event.preventDefault();
                  var data = $('#tabela-dashboards').DataTable().row($(this).parents('tr')).data();

                  if (confirm('Você realmente deseja excluir esse registro?')) {
                    try {
                      try {
                        $.LoadingOverlay("show");
                        var response = await requisicao('DELETE', '/sisplan/dashboard/v1/dashboard?',
                          `id=${data.ID}`, ``, null);

                        if (!response) {
                          return;
                        };

                        jsonStr = await response.json();
                        if (response.status != 200) {
                          $.LoadingOverlay("hide");
                          msgErro(jsonStr.mensagem);
                          return;
                        }

                        toastr.success(
                          'Exclusão efetuada com sucesso!',
                          'Confirmação', {
                            toastClass: 'alert',
                            iconClasses: {
                              error: 'alert-error',
                              info: 'alert-info',
                              success: 'alert-success',
                              warning: 'alert-warning'
                            },
                            positionClass: "toast-top-center",
                            progressBar: true,
                            timeOut: 3000,
                            fadeOut: 1000,
                            onHidden: function() {
                              window.location.href = `dashboard`;
                            }
                          }
                        ).css({
                          "margin-top": "20%",
                          "width": "500px",
                          "max-width": "500px"
                        });

                      } catch (error) {
                        console.error(error);
                        msgErro('Não foi possível excluir o dashboard: ' + error)
                      }
                    } finally {
                      $.LoadingOverlay("hide");
                    }
                  }
                } else {
                  msgAlertaSemConfirmacao("Sem permissão para excluir!");
                }
              });
            }

          } catch (error) {
            console.error(error);
            msgErro('Não foi possível buscar os dashboards');
          }
        } finally {
          $.LoadingOverlay('hide')
        }
      }

      buscaDashboards();

      $('#btn-novo').on('click', function() {
        if (permissaoUsuarioLogado.INCLUI == 'S') {
          $('#id-dash').html(' Novo');
          $('#txtNomeDash').val('');
          $('#modal-edit').modal('show');
        } else {
          msgAlertaSemConfirmacao("Sem permissão para incluir!");
        }

      });

      $('#btn-confirmar-edit').on('click', async function() {
        
        let id = $('#id-dash').html();
        let nome = $('#txtNomeDash').val();

        if (nome == '') {
          msgErro('Informe um nome ao dashboard');
          return;
        }

        try {
          try {
            $('#btn-confirmar-edit').prop('disabled', true);
            $.LoadingOverlay("show");

            var dashboard = new Object();
            dashboard.id = (id != ' Novo') ? id : null;
            dashboard.nome = nome;

            var response = await requisicao('POST', '/sisplan/dashboard/v1/dashboard?',
              `JSON=${encodeURIComponent(JSON.stringify(dashboard))}`, null)

            if (!response) {
              return;
            };

            if (response.status != 200) {
              msgErro(jsonStr['RESULT'][0].mensagem);
              return;
            }

            toastr.success(
              'Cadastro efetuado com sucesso!',
              'Confirmação', {
                toastClass: 'alert',
                iconClasses: {
                  error: 'alert-error',
                  info: 'alert-info',
                  success: 'alert-success',
                  warning: 'alert-warning'
                },
                positionClass: "toast-top-center",
                progressBar: true,
                timeOut: 3000,
                fadeOut: 1000,
                onHidden: function() {
                  window.location.href = `dashboard`;
                }
              }
            ).css({
              "margin-top": "20%",
              "width": "500px",
              "max-width": "500px"
            });

          } catch (error) {
            console.error(error);
            msgErro('Não foi possível gravar os dados do tamanho: ' + error)
          }
        } finally {
          $.LoadingOverlay("hide");
          $('#btn-confirmar-edit').prop('disabled', false);
        }
      });

      function retornaBotaoOpcoes() {
        return '<div class="divBtnOpcoes"> ' +
          '    <button class="botaoOpcoes" type="button" title="Editar" id="btn-editar"><span class="fas fa-edit" style="color:green"></span></button>      ' +
          '    <button class="botaoOpcoes" type="button" title="Excluir" id="btn-excluir"><span class="fas fa-trash-alt" style="color:red"></span></button>  ' +
          '   </div>';
      }

      function retornaBotaoOpcoes(data) {
        var retorno = '<div style="text-align:start;"> ' +
          '    <button class="btn btn-info btn-sm dropdown-toggle btnVerificaOpcoes" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> ' +
          '      ' + data + ' ' +
          '    </button> ' +
          '    <div class="dropdown-menu"> ' +
          '    <button class="dropdown-item" type="button" title="Editar" id="btn-editar">Editar</button>     ' +
          '    <button class="dropdown-item" type="button" title="Excluir" id="btn-excluir">Excluir</button>  ' +
          '</div>';
        return retorno;
      };


    });
  </script>
</body>

</html>