$('#tutorial').on('click', function () {
  $(document).ready(async function () {
    const driver = new Driver({
      doneBtnText: 'Sair',
      closeBtnText: 'Fechar',
      nextBtnText: 'Próximo',
      prevBtnText: 'Anterior',
      allowClose: false
    });
    driver.defineSteps([{
      element: '#btnFiltros',
      popover: {
        title: 'Botão Filtros',
        description: 'Clique aqui para filtrar a consulta da tabela de LOG.',
        position: 'right'
      }
    }
    ]);
    driver.start();
  });
});

$(document).ready(function () {
  $("#btnFiltros").on("click", function () {
    $("#modal-filtros").modal("show");
  });

  $("#btnLimparFiltros").on("click", function () {
    LimpaCamposFiltro();
  });

  $("#btnConsultar").on("click", async function () {
    $("#modal-filtros").modal("hide");
    await ConsultaLogs();
  });

  preencheOrdenacaoTela('RelLog')
  retornaHintRelatorio('btnImprimir', 'RelLog')

  $('#btnImprimir').on('click', async function () {
    try {
      $.LoadingOverlay('show');
      try {
        const url = `/sisplan/impressao/v1/imprimirrellog?`;
        const ordem = `&TELA_ORDENACAO=RelLog&ORDEM_ORDENACAO=${$('#txtOrdem').val()}`;
        const filtros = await retornaFiltros();
        const bImprimeAutomatico = await verificaImprimirAutomatico('RelLog');
        const arquivo = await GeraRelatorio(`${url}${filtros}${ordem}&`, 'GET', 100000, false, 'RelLog');
        if (arquivo != undefined) {
          if (!bImprimeAutomatico) {
            window.open(`${BASE_URI}/relatorios_api/pdf/${arquivo}`, '_blank');
          }
          await limparRelatorios();
        }

      } catch (error) {
        console.error(error);
      }
    } finally {
      $.LoadingOverlay('hide');
    }
  });

  async function retornaFiltros() {
    const usuario = $('#txtUsuario').val()
    const empresa = pegaChave('#txtEmpresa')
    const acao = $('#txtAcao').val()
    const chave = $('#txtChave').val()
    const form = $('#txtForm').val()
    const tela = $('#txtTela').val()
    const dataIni = $('#txtDataIni').val()
    const dataFim = $('#txtDataFim').val()

    const filtros =
      `USUARIO=${usuario}&` +
      `EMP=${empresa}&` +
      `ACAO=${acao}&` +
      `CHAVE=${chave}&` +
      `FORM=${form}&` +
      `DATAINI=${dataIni}&` +
      `DATAFIM=${dataFim}&` +
      `TELA=${tela}`;

    return filtros;
  }

  $("#txtEmpresa").autocompleta(1, `JSON={ "tabela":"empresa", "camposSelect":[ "emp_pat chave", "emp_nome descricao"], "where": null}`);
  $("#btn-empresa").pesquisa("#txtEmpresa", "EMP_PAT", "EMP_NOME", `/sisplan/funcoes/v1/pesquisa?JSON={"tabela":"empresa", "camposSelect":[ "EMP_PAT", "EMP_NOME"]}`, "Pesquisa Empresa", "empresa");
  $("#btn-limpa-empresa").on("click", function () {
    $("#txtEmpresa").val('');
  });

  function LimpaCamposFiltro() {
    $("#txtUsuario").val("");
    $("#txtEmpresa").val("");
    $("#txtAcao").val("");
    $("#txtChave").val("");
    $("#txtTela").val("");
    $("#txtForm").val("");
    $('#txtDataIni').val('1200-01-01');
    $('#txtDataFim').val('2500-12-01');
  };

  async function ConsultaLogs() {
    try {
      const tipoBanco = await retornaDatabase();
      let dataSetCols = [];
      $.LoadingOverlay("show");
      let filtros = '1=1';
      filtros += $('#txtUsuario').val() != '' ? ` AND LOG.USUARIO LIKE '[PERCENTUAL]${$('#txtUsuario').val()}[PERCENTUAL]'` : '';
      filtros += pegaChave('#txtEmpresa') != '' ? ` AND LOG.EMPRESA = '${pegaChave('#txtEmpresa')}'` : '';
      filtros += $('#txtAcao').val() != '' ? ` AND LOG.DESCRICAO LIKE '[PERCENTUAL]${$('#txtAcao').val()}[PERCENTUAL]'` : '';
      filtros += $('#txtChave').val() != '' ? ` AND LOG.CHAVE LIKE '[PERCENTUAL]${$('#txtChave').val()}[PERCENTUAL]'` : '';
      filtros += $('#txtTela').val() != '' ? ` AND LOG.TELA LIKE '[PERCENTUAL]${$('#txtTela').val()}[PERCENTUAL]'` : '';
      filtros += $('#txtForm').val() != '' ? ` AND LOG.FORM LIKE '[PERCENTUAL]${$('#txtForm').val()}[PERCENTUAL]'` : '';
      if (tipoBanco == 'ORACLE') {
        filtros += ` AND LOG.DATA [MAIORQUE] TO_TIMESTAMP('${$('#txtDataIni').val()} 00:00:00', 'YYYY-MM-DD HH24:MI:SS')`;
        filtros += ` AND LOG.DATA [MENORQUE] TO_TIMESTAMP('${$('#txtDataFim').val()} 23:59:59', 'YYYY-MM-DD HH24:MI:SS')`;
      } else {
        filtros += ` AND LOG.DATA [MAIORQUE] '` + $('#txtDataIni').val() + `'`;
        filtros += ` AND LOG.DATA [MENORQUE] '` + $('#txtDataFim').val() + `'`;
      }

      let response = await requisicao(
        "GET",
        "/Sisplan/Funcoes/V1/pesquisa?",
        `JSON={"tabela":"LOG", 
               "camposSelect":["LOG.CHAVE", "LOG.DATA", "LOG.DESCRICAO", "LOG.EMPRESA", "LOG.HORA", "LOG.OPERACAO", 
                               "LOG.TELA", "LOG.USUARIO", "LOG.FORM"], 
               "where": ["${filtros}"]}`, null
      );

      if (!response) {
        $.LoadingOverlay("hide");
        return;
      }

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

      let keys = Object.keys(jsonStr[0]);

      keys.forEach(k => {
        dataSetCols.push({
          'title': k,
          'data': k
        });
      });

      // dataSetCols[1].type = 'date-br';
      // dataSetCols[1].render = function (data, type, row) {
      //   return $.datepicker.formatDate("dd/mm/yy", new Date(data));
      // }
      dataSetCols[4].type = 'date-br';
      dataSetCols[4].render = function (data, type, row) {
        return $.datepicker.formatDate("dd/mm/yy", new Date(data)) + row['HORA'].slice(10);
      }

      $('#tabelaLogs').DataTable({
        destroy: true,
        autoWidth: true,
        data: jsonStr,
        columns: dataSetCols,
        columnDefs: [
          //   {
          //   render: $.fn.dataTable.render.moment('DD/MM/YYYY'),
          //   targets: 1,
          // }
          {
            type: 'date-br',
            targets: [1],
            render: function (data) {
              if (data != undefined && data != '') {
                x = data.slice(0, 10).split('-');
                return `${x[2]}/${x[1]}/${x[0]}`;
              } else {
                return ''
              }
            }
          },]
      });

      $('#tabelaLogs tbody tr td [data-toggle="tooltip"]').tooltip();

      $.LoadingOverlay("hide");
    } catch (error) {
      console.error(error);
      $.LoadingOverlay("hide");
    }
  };
});
