$(document).ready(function () {
  // if (getCookie('cod_usuario') !== '0000') {
  //   window.location.href = `${BASE_URI}/index`;
  // }

  $('#btn-identar').on('click', function () {
    $(`#txtSelect`).val(window.sqlFormatter.format($(`#txtSelect`).val()));
    ConverteUpperCase();
  });

  $('#btn-consultar').on('click', async function () {
    await rotinaValidarSQL();
  });

  function ConverteUpperCase() {
    $(`#txtSelect`).val($(`#txtSelect`).val().replaceAll("select", "SELECT"));
    $(`#txtSelect`).val($(`#txtSelect`).val().replaceAll("from", "FROM"));
    $(`#txtSelect`).val($(`#txtSelect`).val().replaceAll("where", "WHERE"));
    $(`#txtSelect`).val($(`#txtSelect`).val().replaceAll("and", "AND"));
    $(`#txtSelect`).val($(`#txtSelect`).val().replaceAll("left join", "LEFT JOIN"));
    $(`#txtSelect`).val($(`#txtSelect`).val().replaceAll("inner join", "INNER JOIN"));
    $(`#txtSelect`).val($(`#txtSelect`).val().replaceAll("on", "ON"));
  };

  $(document).keyup(async function (e) {
    if (e.keyCode == 120) {
      await rotinaValidarSQL();
    }
  });

  async function rotinaValidarSQL(bMensagem = true, bPassou = false) {
    if ($('#txtSelect').val() == '') {
      msgAlerta('Nenhum select informado.');
      return;
    }
    try {
      try {
        $('#btn-identar').trigger('click');
        $.LoadingOverlay("show");
        const SQL = $(`#txtSelect`).val();
        const url = '/sisplan/funcoes/v1/editorsql?';

        if (!(SQL.toUpperCase().includes('WHERE')) && (!bPassou)){
          if ((!SQL.toUpperCase().includes('INSERT INTO')) && (!SQL.toUpperCase().includes('ALTER TABLE'))) {
            msgAlerta('Não é possÍvel rodar o select sem WHERE');
            return;
          }
        }

        if (SQL.toUpperCase().includes('1 = 1')) {
          msgErro('Não é possÍvel rodar o select com WHERE 1=1');
          return;
        }
        const response = await requisicao('POST', url, '', `JSON=${encodeURIComponent(SQL)}`, null);

        let dataSet = [];
        let dataSetCols = [];

        if (!response) {
          return;
        }

        if (SQL.indexOf('UPDATE')  > -1) {
          let jsonStr = await response.json();
          $('#tabela-resultados').DataTable().clear().draw(false);
          msgAlerta(jsonStr.mensagem);
        } else if (SQL.indexOf('DELETE') > -1) {
          let jsonStr = await response.json();
          $('#tabela-resultados').DataTable().clear().draw(false);
          msgAlerta(jsonStr.mensagem);
        } else if (SQL.indexOf('INSERT INTO') > -1) {
          let jsonStr = await response.json();
          $('#tabela-resultados').DataTable().clear().draw(false);
          msgAlerta(jsonStr.mensagem);
        } else if (SQL.indexOf('ALTER TABLE') > -1) {
          let jsonStr = await response.json();
          $('#tabela-resultados').DataTable().clear().draw(false);
          msgAlerta(jsonStr.mensagem);
        } else {

          let jsonStr = await response.json();
          if (response.status === 400) {
            msgErro(jsonStr.mensagem);
            return;
          }

          if (!$.isEmptyObject(jsonStr)) {
            dataSet = jsonStr;
            const keys = Object.keys(dataSet[0]);
            keys.forEach((key) => {
              dataSetCols.push({
                'title': key,
                'data': key
              });
            });

            $('#resultados').html('<table id="tabela-resultados" class="table table-sm table-select table-hover display"></table>');
            $('#tabela-resultados').DataTable({
              paging: true,
              filter: false,
              info: false,
              order: false,
              destroy: true,
              autowidth: true,
              "language": {
                "sEmptyTable": "Nenhum registro encontrado",
                "sInfo": "_TOTAL_ registros",
                "sInfoEmpty": " 0 registros",
                "sInfoFiltered": "(Filtrados de _MAX_ registros)",
                "sInfoPostFix": "",
                "sInfoThousands": ".",
                "sLengthMenu": "_MENU_ resultados",
                "sLoadingRecords": "Carregando...",
                "sProcessing": "Processando...",
                "sZeroRecords": "Nenhum registro encontrado",
                "sSearch": "Pesquisar",
                "oPaginate": {
                  "sNext": "Próximo",
                  "sPrevious": "Anterior",
                  "sFirst": "Primeiro",
                  "sLast": "Último"
                },
                "oAria": {
                  "sSortAscending": ": Ordenar colunas de forma ascendente",
                  "sSortDescending": ": Ordenar colunas de forma descendente"
                }
              },
              "columns": dataSetCols,
              "data": dataSet
            });

          } else {
            $('#tabela-resultados').DataTable().clear().draw(false);
            return;
          }
          if (bMensagem) {
            return;
          }
        }

      } catch (error) {
        console.error(error);
        msgErro('Erro ao validar sql.');
      }
    } finally {
      $.LoadingOverlay("hide");
    }
  }
});