$("#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.",
          position: "right",
        },
      },
      {
        element: "#btnIncluir",
        popover: {
          title: "Botão Incluir",
          description: "Clique aqui para iniciar o cadastro de um CST COFINS.",
          position: "right",
        },
      },
      {
        element: "#tabelaCSTCofins",
        popover: {
          title: "Tabela CST COFINS",
          description: "Aqui estão os CST COFINS cadastrados.",
          position: "top",
        },
      },
    ]);
    driver.start();
  });
});
$(document).ready(async function () {
  const permissaoUsuarioLogado = await permissaoAcessos("CSTCOFINS");

  // autocompleta
  $("#txtConsultaCstCofins").autocompleta(
    1,
    `JSON={ "tabela":"tabcofins", "camposSelect":[ "codigo chave", "descricao descricao"], "where": null}`
  );
  // pesquisa
  $("#btn-CstCofins").pesquisa(
    "#txtConsultaCstCofins",
    "CODIGO",
    "DESCRICAO",
    `/sisplan/funcoes/v1/pesquisa?JSON={ "tabela":"tabcofins", "camposSelect":[ "codigo", "descricao"]}`,
    "Pesquisa CST COFINS",
    "tabcofins"
  );
  // limpacampo
  $("#btn-limpa-CstCofins").on("click", function () {
    $("#txtConsultaCstCofins").val("");
  });

  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;
};

  ConsultaCSTCofins();

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

  $("#btnIncluir").on("click", function () {
    if (permissaoUsuarioLogado.INCLUI == 'S') {
        window.location.href = "cstcofins/create";
    } else {
        msgAlertaSemConfirmacao("Sem permissão para incluir!");
    }
  });

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

  $("#btnLimparFiltros").on("click", async function () {
    $("#txtConsultaCstCofins").val("");
  });

  async function ConsultaCSTCofins(bBotao = false) {
    try {
      let response;
      $.LoadingOverlay("show");
      let cstcofins =
        pegaChave("#txtConsultaCstCofins") != ""
          ? ` AND codigo = '${pegaChave("#txtConsultaCstCofins")}'`
          : "";
      if (bBotao) {
        response = await requisicao(
          "GET",
          "/Sisplan/Funcoes/V1/pesquisa?",
          `JSON={ "tabela":"tabcofins", "camposSelect":[ "codigo", "descricao"], "where": ["1=1 ${cstcofins} "]}`,
          null
        );
      } else {
        response = await requisicao(
          "GET",
          "/Sisplan/Funcoes/V1/pesquisa?",
          'JSON={ "tabela":"tabcofins", "camposSelect":[ "codigo", "descricao"], "where": null}',
          null
        );
      }

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

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

      $("#tabelaCSTCofins").DataTable({
        destroy: true,
        lengthChange: false,
        serverside: true,

        autoWidth: true,
        data: jsonStr.RESULT[0],
        columns: [
          {
            data: "CODIGO",
          },
          {
            data: "DESCRICAO",
          },
        ],
        columnDefs: [
          {
            targets: [0], render: function (data, type, row) {
              return retornaBotaoOpcoes(data);
          }
          },
        ],
      });

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

  $("#tabelaCSTCofins").on("click", "#btn-editar", async function () {
    if (permissaoUsuarioLogado.ALTERA == 'S') {
      let data = $("#tabelaCSTCofins")
        .DataTable()
        .row($(this).parents("tr"))
        .data();
      let registroLiberado = await verificarRegistro("CSTCOFINS", data.CODIGO);
      if (registroLiberado) {
        window.location.href = `cstcofins/${data.CODIGO}`;
      }
    } else {
        msgAlertaSemConfirmacao("Sem permissão para alterar!");
    }
  });

  $("#tabelaCSTCofins").on("dblclick", "tr", async function () {
    if (permissaoUsuarioLogado.ALTERA == 'S') {
      let data = $("#tabelaCSTCofins").DataTable().row($(this)).data();
      let registroLiberado = await verificarRegistro("CSTCOFINS", data.CODIGO);
      if (registroLiberado) {
        window.location.href = `cstcofins/${data.CODIGO}`;
      }
    } else {
        msgAlertaSemConfirmacao("Sem permissão para alterar!");
    }
  });


  $('#tabelaCSTCofins').on('click', '#btn-excluir', async function () {
    if (permissaoUsuarioLogado.EXCLUI == 'S') {
      msgAlerta('Você realmente deseja excluir esse registro?', async () => {
        const data = $("#tabelaCSTCofins").DataTable().row($(this).parents("tr"));
        await excluiRegistro(data);
      });
    } else {
        msgAlertaSemConfirmacao("Sem permissão para excluir!");
    }
  });

  async function excluiRegistro(data) {
    try {
      $.LoadingOverlay("show");
      try {
        let valorLinha = data.data();
        let response = await requisicao("DELETE", "/Sisplan/Cadastros/v1/cstcofins?", `CODIGOCSTCOFINS=${encodeURIComponent(valorLinha.CODIGO)}`, null);
        if (!response) {
          return;
        }
        if (response.status != 200) {
          let jsonStr = await response.json();
          msgErro(jsonStr.mensagem);
          return;
        }

        toastr.success("Exclusão efetuada com sucesso!", "Confirmação", {
          toastClass: "success",
          iconClasses: {
            error: "alert-error",
            info: "alert-info",
            success: "alert-success",
            warning: "alert-warning",
          },
          positionClass: "toast-top-center",
          progressBar: true,
          timeOut: 3000,
          fadeOut: 1000,
          onHidden() {
            data.remove().draw(false);
          },
        }).css({
          "margin-top": "20%",
          width: "500px",
          "max-width": "500px",
        });

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