$(document).ready(async function () {
  configuraGrafico();

  let chart;
  let utilizaMaterial = await CopiaParametro('VENDA', 17) == 1;
  let colunas = JSON.parse(localStorage.getItem('colunasInvisiveisRelatorios'));

  if (utilizaMaterial == 1) {
    $('#radioMaterial').prop('checked', true);
    await pesquisaRadioMaterial();
  } else {
    await pesquisaRadioProduto();
  }

  $('#btnConfirmarColunas').on('click', async function () {
    try {
      $.LoadingOverlay('show');
      const propRelRanking = `relRankingVendas${$('#selectOrdem').val()}`
      const novasColunas = retornaNovasColunasInvisiveis();
      localStorage.setItem('colunasInvisiveisRelatorios', JSON.stringify({ ...colunas, [propRelRanking]: novasColunas }))

      $('#tabelaRanking').DataTable().columns().visible(true);
      $('#tabelaRanking').DataTable().columns().every(
        function () {
          if ((novasColunas).indexOf(this.dataSrc()) != -1) {
            this.visible(false);
          }
        })

    } finally {
      $.LoadingOverlay('hide');
      $('#modal-ColunasVisiveis').modal('hide');
    }
  })

  const filtroDeposito = await buscaDepositoEmpresaUsuario();

  async function pesquisaRadioProduto() {

    const divRelRankLoja = document.getElementById("divRelRankLoja");

    divRelRankLoja.innerHTML = `<div class="form-group col-lg-2">
                                  <div class="">
                                    <label for="">Data Emissão:</label>
                                    <div class="relative">
                                      <input type="date" max="2500-12-31" value="1200-01-01" max="2500-12-31" class="input-default focus form-control validate" id="txtDataEmissaoI" name="DataDe">
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-2">
                                  <div class="">
                                    <label for="dtEmifim">Até:</label>
                                    <div class="relative">
                                      <input type="date" max="2500-12-31" value="2500-12-01" max="2500-12-31" class="input-default focus form-control validate" id="txtDataEmissaoF" name="DataAte">
                                    </div>
                                  </div>
                                </div>

                                <div class="form-group col-lg-6 col-12 col-sm-12 mt-3 mb-0">
                                  <fieldset class="form border-Field p-0">
                                    <legend class="textoBorda pb-0 mb-0">Status Venda</legend>
                                    <div class="form-row">
                                      <div class="form-check mb-0 pb-0">
                                        <input class="form-check-input mb-0" type="checkbox" id="cbEmitido" checked> <label for="cbEmitido">Emitido</label>
                                      </div>
                                      <div class="form-check mb-0 pb-0">
                                        <input class="form-check-input mb-0" type="checkbox" id="cbPendente" checked> <label for="cbPendente">Pendente</label>
                                      </div>
                                      <div class="form-check mb-0 pb-0">
                                        <input class="form-check-input mb-0" type="checkbox" id="cbAgrupado" checked> <label for="cbAgrupado">Agrupado</label>
                                      </div>
                                      <div class="form-check mb-0 pb-0">
                                        <input class="form-check-input mb-0" type="checkbox" id="cbDevolvido" checked> <label for="cbDevolvido">Devolvido</label>
                                      </div>
                                      <div class="form-check mb-0 pb-0">
                                        <input class="form-check-input mb-0" type="checkbox" id="cbCancelado" checked> <label for="cbCancelado">Cancelado</label>
                                      </div>
                                    </div>
                                  </fieldset>
                                </div>
                                <div class="form-group col-lg-2 col-12 col-sm-6 mt-3 pt-1 mb-0">
                                  <div class="pl-0 pt-0 mt-2">
                                    <button id="btn-selecionar-empresas" type='button' class="btn btn-danger ml-0 mr-0">Selecionar empresas</button>
                                  </div>
                                </div>

                                <!-- <div class="col-lg-4 col-12" id="divCliente" style="margin-top: 5px;"> -->
                                <div class="form-group col-lg-4 col-12 col-sm-12 classVendedor mt-3 mt-sm-0">
                                  <label data-error="wrong" data-success="right" for="txtVendedor">Vendedor: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtVendedor" name="txtVendedor" class="form-control" placeholder="Vendedor"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtVendedor" name="txtVendedor" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnVendedor" name="btnVendedor" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaVendedor" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                
                                <div class="form-group col-lg-4 col-12 col-sm-12" id="divCliente">
                                  <label id="lblCliente" data-error="wrong" data-success="right" for="txtCliente">Cliente: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtCliente" name="txtCliente" class="form-control" placeholder="Etiqueta"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtCliente" name="txtCliente" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnCliente" name="btnCliente" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaCliente" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>

                                <div class="form-group col-lg-4 col-12 col-sm-12" id="divGrupoCli">
                                  <label id="lblGrupoCli" data-error="wrong" data-success="right" for="txtGrupoCli">Grupo de Cliente: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtCliente" name="txtCliente" class="form-control" placeholder="Etiqueta"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtGrupoCli" name="txtGrupoCli" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnGrupoCli" name="btnGrupoCli" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaGrupoCli" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                
                                <div class="form-group col-lg-4 col-12 col-sm-12 classFornecedor">
                                  <label data-error="wrong" data-success="right" for="txtFornecedor">Fornecedor: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtFornecedor" name="txtFornecedor" class="form-control" placeholder="Fornecedor"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtFornecedor" name="txtFornecedor" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnFornecedor" name="btnFornecedor" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaFornecedor" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12">
                                  <label data-error="wrong" data-success="right" id="labelTipoVenda" for="txtTipoVenda">Tipo Venda: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtTipoVenda" name="txtTipoVenda" class="form-control" placeholder="Tipo Venda"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtTipoVenda" name="txtTipoVenda" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnTipoVenda" name="btnTipoVenda" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaTipoVenda" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12">
                                  <label data-error="wrong" data-success="right" for="txtUsuario">Usuário: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtUsuario" name="txtUsuario" class="form-control" placeholder="Usuário"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtUsuario" name="txtUsuario" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnUsuario" name="btnUsuario" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaUsuario" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>

                                <div class="form-group col-lg-4 col-12 col-sm-12">
                                  <label data-error="wrong" data-success="right" id="labelProduto" for="txtProduto">Produto: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtProduto" name="txtProduto" class="form-control" placeholder="Produto"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtProduto" name="txtProduto" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnProduto" name="btnProduto" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaProduto" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12 classColecao">
                                  <label data-error="wrong" data-success="right" for="txtColecao">Coleção: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtColecao" name="txtColecao" class="form-control" placeholder="Coleção"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtColecao" name="txtColecao" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnColecao" name="btnColecao" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaColecao" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12 classModelo">
                                  <label data-error="wrong" data-success="right" for="txtModelo">Modelo: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtModelo" name="txtModelo" class="form-control" placeholder="Modelo"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtModelo" name="txtModelo" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnModelo" name="btnModelo" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaModelo" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                
                                <div class="form-group col-lg-4 col-12 col-sm-12 classGrupoPA">
                                  <label data-error="wrong" data-success="right" for="txtGrupoPA">Grupo de Produto: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtGrupoPA" name="txtGrupoPA" class="form-control" placeholder="GrupoPA"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtGrupoPA" name="txtGrupoPA" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnGrupoPA" name="btnGrupoPA" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaGrupoPA" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12 classEtiqueta">
                                  <label data-error="wrong" data-success="right" for="txtEtiqueta">Etiqueta: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtEtiqueta" name="txtEtiqueta" class="form-control" placeholder="Etiqueta"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtEtiqueta" name="txtEtiqueta" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnEtiqueta" name="btnEtiqueta" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaEtiqueta" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12 classLinha">
                                  <label data-error="wrong" data-success="right" for="txtLinha">Linha: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtLinha" name="txtLinha" class="form-control" placeholder="Linha"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtLinha" name="txtLinha" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnLinha" name="btnLinha" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaLinha" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>

                                <div class="form-group col-lg-4 col-12 col-sm-12 classMarca">
                                  <label data-error="wrong" data-success="right" id="labelMarca" for="txtMarca">Marca: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtMarca" name="txtMarca" class="form-control" placeholder="Marca"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtMarca" name="txtMarca" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnMarca" name="btnMarca" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaMarca" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12 classDepositoUsuario">
                                  <label data-error="wrong" data-success="right" for="txtDepositoUsuario">Depósito: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtDepositoUsuario" name="txtDepositoUsuario" class="form-control" placeholder="DepositoUsuario"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtDepositoUsuario" name="txtDepositoUsuario" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnDepositoUsuario" name="btnDepositoUsuario" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaDepositoUsuario" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12 classTabPreco">
                                  <label data-error="wrong" data-success="right" for="txtTabPreco">Tabela: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtTabPreco" name="txtTabPreco" class="form-control" placeholder="TabPreco"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtTabPreco" name="txtTabPreco" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnTabPreco" name="btnTabPreco" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaTabPreco" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12" id="divGuia">
                                  <label id="lblGuia" data-error="wrong" data-success="right" for="txtGuia">Guia: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtGuia" name="txtGuia" class="form-control" placeholder="Etiqueta"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtGuia" name="txtGuia" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnGuia" name="btnGuia" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaGuia" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </div>`;

    adicionaClickDate();

    componenteFiltro('vendedor', true);
    componenteFiltro('guia', true);
    componenteFiltro('cliente', true);
    componenteFiltro('fornecedor', true);
    componenteFiltro('tipoVenda', true);
    componenteFiltro('usuario', true);
    componenteFiltro('produto', true);
    componenteFiltro('colecao', true);
    componenteFiltro('modelo', true);
    componenteFiltro('grupoPA', true);
    componenteFiltro('etiqueta', true);
    componenteFiltro('linha', true);
    componenteFiltro('marca', true);
    componenteFiltro('depositoUsuario', true);
    componenteFiltro('tabPreco', true);
    componenteFiltro('grupoCli', true);


    $("#btn-selecionar-empresas").on("click", function () {
      carregaEmpresasDisponiveis();
    });
  }

  async function pesquisaRadioMaterial() {

    const divRelRankLoja = document.getElementById("divRelRankLoja");
    divRelRankLoja.innerHTML = `<div class="form-group col-lg-2">
                                  <div class="">
                                    <label for="">Data Emissão:</label>
                                    <div class="relative">
                                      <input type="date" max="2500-12-31" value="1200-01-01" max="2500-12-31" class="input-default focus form-control validate" id="txtDataEmissaoI" name="DataDe">
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-2">
                                  <div class="">
                                    <label for="dtEmifim">Até:</label>
                                    <div class="relative">
                                      <input type="date" max="2500-12-31" value="2500-12-01" max="2500-12-31" class="input-default focus form-control validate" id="txtDataEmissaoF" name="DataAte">
                                    </div>
                                  </div>
                                </div>

                                <div class="form-group col-lg-6 col-12 col-sm-12 mt-3 mb-0">
                                  <fieldset class="form border-Field p-0">
                                    <legend class="textoBorda pb-0 mb-0">Status Venda</legend>
                                    <div class="form-row">
                                      <div class="form-check mb-0 pb-0">
                                        <input class="form-check-input mb-0" type="checkbox" id="cbEmitido" checked> <label for="cbEmitido">Emitido</label>
                                      </div>
                                      <div class="form-check mb-0 pb-0">
                                        <input class="form-check-input mb-0" type="checkbox" id="cbPendente" checked> <label for="cbPendente">Pendente</label>
                                      </div>
                                      <div class="form-check mb-0 pb-0">
                                        <input class="form-check-input mb-0" type="checkbox" id="cbAgrupado" checked> <label for="cbAgrupado">Agrupado</label>
                                      </div>
                                      <div class="form-check mb-0 pb-0">
                                        <input class="form-check-input mb-0" type="checkbox" id="cbDevolvido" checked> <label for="cbDevolvido">Devolvido</label>
                                      </div>
                                      <div class="form-check mb-0 pb-0">
                                        <input class="form-check-input mb-0" type="checkbox" id="cbCancelado" checked> <label for="cbCancelado">Cancelado</label>
                                      </div>
                                    </div>
                                  </fieldset>
                                </div>
                                <div class="form-group col-lg-2 col-12 col-sm-6 mt-3 pt-1 mb-0">
                                  <div class="pl-0 pt-0 mt-2">
                                    <button id="btn-selecionar-empresas" type='button' class="btn btn-danger ml-0 mr-0">Selecionar empresas</button>
                                  </div>
                                </div>

                                <!-- <div class="col-lg-3 col-12" id="divCliente" style="margin-top: 5px;"> -->
                                <div class="form-group col-lg-4 col-12 col-sm-12 classVendedor mt-3 mt-sm-0">
                                  <label data-error="wrong" data-success="right" for="txtVendedor">Vendedor: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtVendedor" name="txtVendedor" class="form-control" placeholder="Vendedor"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtVendedor" name="txtVendedor" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnVendedor" name="btnVendedor" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaVendedor" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                
                                <div class="form-group col-lg-4 col-12 col-sm-12" id="divCliente">
                                  <label id="lblCliente" data-error="wrong" data-success="right" for="txtCliente">Cliente: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtCliente" name="txtCliente" class="form-control" placeholder="Etiqueta"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtCliente" name="txtCliente" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnCliente" name="btnCliente" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaCliente" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>

                                <div class="form-group col-lg-4 col-12 col-sm-12" id="divGrupoCli">
                                  <label id="lblGrupoCli" data-error="wrong" data-success="right" for="txtGrupoCli">Grupo de Cliente: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtCliente" name="txtCliente" class="form-control" placeholder="Etiqueta"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtGrupoCli" name="txtGrupoCli" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnGrupoCli" name="btnGrupoCli" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaGrupoCli" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>

                                <div class="form-group col-lg-4 col-12 col-sm-12">
                                  <label data-error="wrong" data-success="right" id="labelMaterial" for="txtMaterial">Material: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtMaterial" name="txtMaterial" class="form-control" placeholder="Material"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtMaterial" name="txtMaterial" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnMaterial" name="btnMaterial" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaMaterial" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12 classColecao">
                                  <label data-error="wrong" data-success="right" for="txtColecao">Coleção: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtColecao" name="txtColecao" class="form-control" placeholder="Coleção"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtColecao" name="txtColecao" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnColecao" name="btnColecao" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaColecao" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12">
                                  <label data-error="wrong" data-success="right" id="labelTipoVenda" for="txtTipoVenda">Tipo Venda: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtTipoVenda" name="txtTipoVenda" class="form-control" placeholder="Tipo Venda"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtTipoVenda" name="txtTipoVenda" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnTipoVenda" name="btnTipoVenda" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaTipoVenda" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>

                                <div class="form-group col-lg-4 col-12 col-sm-12 classGrupoMA">
                                  <label data-error="wrong" data-success="right" for="txtGrupoMA">Grupo de Material: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtGrupoMA" name="txtGrupoMA" class="form-control" placeholder="Grupo"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtGrupoMA" name="txtGrupoMA" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnGrupoMA" name="btnGrupoMA" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaGrupoMA" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12 classSubGrupo">
                                  <label data-error="wrong" data-success="right" for="txtSubGrupo">SubGrupo: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtSubGrupo" name="txtSubGrupo" class="form-control" placeholder="SubGrupo"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtSubGrupo" name="txtSubGrupo" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnSubGrupo" name="btnSubGrupo" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaSubGrupo" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12 classLinha">
                                  <label data-error="wrong" data-success="right" for="txtLinha">Linha: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtLinha" name="txtLinha" class="form-control" placeholder="Linha"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtLinha" name="txtLinha" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnLinha" name="btnLinha" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaLinha" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>

                                <div class="form-group col-lg-4 col-12 col-sm-12 classDepositoUsuario">
                                  <label data-error="wrong" data-success="right" for="txtDepositoUsuario">Depósito: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtDepositoUsuario" name="txtDepositoUsuario" class="form-control" placeholder="DepositoUsuario"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtDepositoUsuario" name="txtDepositoUsuario" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnDepositoUsuario" name="btnDepositoUsuario" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaDepositoUsuario" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12 classTabPreco">
                                  <label data-error="wrong" data-success="right" for="txtTabPreco">Tabela: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtTabPreco" name="txtTabPreco" class="form-control" placeholder="TabPreco"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtTabPreco" name="txtTabPreco" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnTabPreco" name="btnTabPreco" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaTabPreco" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12">
                                  <label data-error="wrong" data-success="right" for="txtUsuario">Usuário: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtUsuario" name="txtUsuario" class="form-control" placeholder="Usuário"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtUsuario" name="txtUsuario" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnUsuario" name="btnUsuario" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaUsuario" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                                <div class="form-group col-lg-4 col-12 col-sm-12" id="divGuia">
                                  <label id="lblGuia" data-error="wrong" data-success="right" for="txtGuia">Guia: </label>
                                  <div class="relative">
                                    <div class="input-group">
                                      <!-- <input type="text" class="input-default focus form-control" id="txtGuia" name="txtGuia" class="form-control" placeholder="Etiqueta"> -->
                                      <select class="js-example-programmatic js-states form-control" id="txtGuia" name="txtGuia" multiple="multiple">
                                      </select>
                                      <div class="input-group-append">
                                        <button class="btn bg-danger" id="btnGuia" name="btnGuia" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
                                        <button class="btn bg-danger" id="btnLimpaGuia" type="button"><i class="m-0 p-0 fas fa-trash"></i></button>
                                      </div>
                                    </div>
                                  </div>
                                </div>`;


    adicionaClickDate();

    componenteFiltro('vendedor', true);
    componenteFiltro('guia', true);
    componenteFiltro('cliente', true);
    componenteFiltro('tipoVenda', true);
    componenteFiltro('usuario', true);
    componenteFiltro('material', true);
    componenteFiltro('colecao', true);
    componenteFiltro('grupoMA', true);
    componenteFiltro('subGrupo', true);
    componenteFiltro('linha', true);
    componenteFiltro('depositoUsuario', true);
    componenteFiltro('tabPreco', true);
    componenteFiltro('grupoCli', true);
  }

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

  $("#btnOpcoesFiltros").on("click", async function () {
    $("#modal-opcoesFiltros").modal("show");
  });

  async function adicionaOrdem() {
    const dadosSelect = {
      tabela: `${"ORDEM_TELA"}`,
      camposSelect: [`${"NOME_ORD_TELA"}, ${"ORDEM"}`],
      where: [`${"NOME_TELA"} = '${"RelRankLoja"}'`],
    };

    const retornoSelect = await retornaJsonPesquisaPadrao(
      JSON.stringify(dadosSelect)
    );
    if (!retornoSelect) {
      return;
    }

    retornoSelect.forEach(function (item) {
      $("#selectOrdem").append(
        `<option value=${item.ORDEM}>${item.NOME_ORD_TELA}</option>`
      );
    });

  }

  $('#radioProduto, #radioMaterial').on('change', async function () {
    const tipoConsulta = ($('#radioMaterial').is(':checked') ? 'M' : 'P');
    if (tipoConsulta == 'M') {
      await pesquisaRadioMaterial();
      utilizaMaterial = 1;

    } else {
      await pesquisaRadioProduto();
      utilizaMaterial = 0;
    }
  });

  await adicionaOrdem();

  $("#btnImprimir").on("click", async function () {
    try {
      $.LoadingOverlay("show");
      try {
        const ordemOrdenacao = $('#selectOrdem').val();

        const emitido = $('#cbEmitido').prop('checked');
        const devolvido = $('#cbDevolvido').prop('checked');
        const pendente = $('#cbPendente').prop('checked');
        const agrupado = $('#cbAgrupado').prop('checked');
        const cancelado = $('#cbCancelado').prop('checked');
        const material = $('#radioMaterial').prop('checked');
        const url = `/sisplan/impressao/v1/imprimirrellojarank?ordem_ordenacao=${ordemOrdenacao}&emitido=${emitido}&devolvido=${devolvido}&pendente=${pendente}&USAMATERIAL=${material}&agrupado=${agrupado}&cancelado=${cancelado}&`;
        const Filtros = await preencheFiltros(utilizaMaterial);
        const bImprimeAutomatico = await verificaImprimirAutomatico('RelRankLoja');
        const arquivo = await GeraRelatorio(`${url}${Filtros}`, "GET", 100000, false, 'RelRankLoja');

        if (arquivo != undefined) {
          if (!bImprimeAutomatico) {
            window.open(`${BASE_URI}/relatorios_api/pdf/${arquivo}`, "_blank");
          }
          await limparRelatorios();
        }
      } catch (error) {
        console.error(error);
      }
    } finally {
      $.LoadingOverlay("hide");
    }
  });

  $('#btn-selecionar-empresas').on('click', function () {
    carregaEmpresasDisponiveis();
  });

  $('#modal-ColunasVisiveis').on('show.bs.modal', function () {
    const cols = [];

    let colunasInvisiveis = JSON.parse(localStorage.getItem('colunasInvisiveisRelatorios'));

    $('#tabelaRanking').DataTable().columns().every(function () {
      cols.push({
        'title': $(this.header()).text(),
        'data': this.dataSrc()
      })
    });

    const propRelRanking = `relRankingVendas${$('#selectOrdem').val()}`
    adicionaColunas(cols, colunasInvisiveis[propRelRanking] ?? []);
  });

  $("#btnConsultar").on("click", async function () {
    try {
      $.LoadingOverlay("show");
      try {

        if ($.fn.DataTable.isDataTable('#tabelaRanking')) {
          $('#tabelaRanking').DataTable().destroy();
          $('#tabelaRanking').empty();
        };

        let dataSetCols = [];
        const ordemOrdenacao = $('#selectOrdem').val();
        const ordenacao = await buscaValor('ORDEM_TELA', 'CAMPO_SUM, NOME_ORD_SIST', 'ORDEM', `${ordemOrdenacao}' AND NOME_TELA = 'RelRankLoja`);
        const campo = ordenacao.CAMPO_SUM == '0' ? 'QUANTIDADE' : 'VALOR'
        const emitido = $('#cbEmitido').prop('checked');
        const devolvido = $('#cbDevolvido').prop('checked');
        const pendente = $('#cbPendente').prop('checked');
        const agrupado = $('#cbAgrupado').prop('checked');
        const cancelado = $('#cbCancelado').prop('checked');
        const material = $('#radioMaterial').prop('checked');
        const url = `/sisplan/impressao/v1/consultarellojarank?ordem_ordenacao=${ordemOrdenacao}&emitido=${emitido}&devolvido=${devolvido}&pendente=${pendente}&USAMATERIAL=${material}&agrupado=${agrupado}&cancelado=${cancelado}&`;
        const Filtros = await preencheFiltros(utilizaMaterial);
        const response = await requisicao("GET", url, Filtros, '', 30000);

        if (!response) {
          return;
        }

        const jsonStr = await response.json();

        if (jsonStr.length == 0) {
          msgAlerta("Nenhum registro encontrado!");
          if (chart) {
            let arrDadosGrafico = [];
            chart.updateSeries([{ data: arrDadosGrafico }]);
          }
          return;
        }

        if (response.status != 200) {
          console.error(jsonStr.mensagem);
          return;
        }

        jsonStr.sort(function (a, b) {
          return b[campo] - a[campo];
        });

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

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

        let indiceValor;

        for (let i = 0; i < keys.length; i++) {
          if (keys[i] == 'VALOR') {
            indiceValor = i;
          }
        }

        $("#tabelaRanking").DataTable({
          order: [],
          sort: true,
          paging: true,
          destroy: 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",
            },
          },
          autoWidth: true,
          colReorder: true,
          data: jsonStr,
          columns: dataSetCols,
          "columnDefs": [{
          },
          {
            "render": function (data) {
              return parseFloat(data).toLocaleString('pt-br', {
                maximumFractionDigits: 2,
                minimumFractionDigits: 2
              });
            },
            "targets": indiceValor
          }
          ],
        });

        const colunasInvisiveis = JSON.parse(localStorage.getItem('colunasInvisiveisRelatorios'));
        // adiciona o botão na tabela e adiciona a função de abrir o modal
        $('#tabelaRanking_length').prepend('<button class="buttonColVis" id="buttonColVis"><i class="fas fa-cogs"></i></button>');
        $('#tabelaRanking_length').prepend('<button class="buttonExcel" id="buttonExcel"><i class="fas fa-file-excel"></i></button>');

        $('#buttonColVis').on('click', async function () {
          $.LoadingOverlay('show');
          $('#modal-ColunasVisiveis').modal('show');
          $.LoadingOverlay('hide');
        })

        $('#buttonExcel').on('click', async function () {
          const url = `/sisplan/impressao/v1/consultarellojarank?ordem_ordenacao=${ordemOrdenacao}&emitido=${emitido}&devolvido=${devolvido}&pendente=${pendente}&USAMATERIAL=${material}&`;
          const filtros = await preencheFiltros(utilizaMaterial);
          await exportaCSV(url, filtros, false, null, 'Relatório de Ranking de Vendas', '#tabelaRanking');
        })

        try {
          $('#tabelaRanking').DataTable().columns().every(
            function () {
              if ((colunasInvisiveis[`relRankingVendas${$('#selectOrdem').val()}`]).indexOf(this.dataSrc()) != -1) {
                this.visible(false);
              }
            }
          )
        } catch (error) {

        }

        // GRAFICO
        let arrDadosGrafico = [];
        jsonStr.map((item, index) => {
          if (index < 25) {
            arrDadosGrafico.push({
              x: `${item[ordenacao.NOME_ORD_SIST.split(';')[0]]} - ${item[ordenacao.NOME_ORD_SIST.split(';')[1]]}`,
              y: parseFloat(item[campo])
            });
          }
        });

        options.series[0].data = arrDadosGrafico;
        if (!chart) {
          chart = new ApexCharts(document.querySelector("#chart"), options);
          chart.render();
        }
        chart.updateSeries([{ data: arrDadosGrafico }]);
        // chart.updateSeries([{ data: arrDadosGrafico }]);
        // FIM GRAFICO        
      } catch (error) {
        console.error(error);
      }
    } finally {
      $.LoadingOverlay("hide");
      $("#modal-filtros").modal("hide");
    }
  });

  async function preencheFiltros(tipoFiltros) {
    try {
      let retorno = '';
      let codigo = '';
      let subgrupo = '';
      let grupo = '';
      let marca = '';
      let etiqueta = '';
      let fornecedor = '';
      let modelo = '';
      const dataini = $('#txtDataEmissaoI').val();
      const datafim = $('#txtDataEmissaoF').val();
      const vendedor = await formataListas($('#txtVendedor').val().toString());
      const guia = await formataListas($('#txtGuia').val().toString());
      const cliente = await formataListas($('#txtCliente').val().toString());
      const grupoCliente = await formataListas($('#txtGrupoCli').val().toString());
      const colecao = await formataListas($('#txtColecao').val().toString());
      const tipovenda = await formataListas($('#txtTipoVenda').val().toString());
      const linha = await formataListas($('#txtLinha').val().toString());
      const tabela = await formataListas($('#txtTabPreco').val().toString());
      const usuario = await formataListas($('#txtUsuario').val().toString());
      let deposito = await formataListas($('#txtDepositoUsuario').val().toString());
      deposito = deposito != ''
        ? deposito : filtroDeposito;
      const listaempids = $('.empresa_selecionada:checked').toArray().length > 0 ? $('.empresa_selecionada:checked').toArray().map(input => input.id.substring(input.id.indexOf('-') + 1, input.id.length))
        : [getCookie('emp_id')];
      if (tipoFiltros == 1) {
        codigo = await formataListas($('#txtMaterial').val().toString());
        subgrupo = await formataListas($('#txtSubGrupo').val().toString());
        grupo = await formataListas($('#txtGrupoMA').val().toString());
        retorno =
          `VENDEDOR=${vendedor}` +
          `&DATAINI=${dataini}` +
          `&DATAFIM=${datafim}` +
          `&CODIGO=${codigo}` +
          `&TABELA=${tabela}` +
          `&SUBGRUPO=${subgrupo}` +
          `&GRUPOCLIENTE=${grupoCliente}` +
          `&CLIENTE=${cliente}` +
          `&GRUPO=${grupo}` +
          `&DEPOSITO=${deposito}` +
          `&EMP_IDS=${listaempids}` +
          `&TIPO_VENDA=${tipovenda}` +
          `&LINHA=${linha}` +
          `&USR_CAIXA=${usuario}` +
          `&GUIA=${guia}`;
      } else {
        codigo = await formataListas($('#txtProduto').val().toString());
        marca = await formataListas($('#txtMarca').val().toString());
        grupo = await formataListas($('#txtGrupoPA').val().toString());
        etiqueta = await formataListas($('#txtEtiqueta').val().toString());
        fornecedor = await formataListas($('#txtFornecedor').val().toString());
        modelo = await formataListas($('#txtModelo').val().toString());
        retorno =
          `VENDEDOR=${vendedor}` +
          `&DATAINI=${dataini}` +
          `&DATAFIM=${datafim}` +
          `&CODIGO=${codigo}` +
          `&TABELA=${tabela}` +
          `&MARCA=${marca}` +
          `&CLIENTE=${cliente}` +
          `&GRUPOCLIENTE=${grupoCliente}` +
          `&GRUPO=${grupo}` +
          `&ETIQUETA=${etiqueta}` +
          `&FORNECEDOR=${fornecedor}` +
          `&COLECAO=${colecao}` +
          `&LINHA=${linha}` +
          `&DEPOSITO=${deposito}` +
          `&MODELO=${modelo}` +
          `&EMP_IDS=${listaempids}` +
          `&TIPO_VENDA=${tipovenda}` +
          `&USR_CAIXA=${usuario}` +
          `&GUIA=${guia}`;
      }

      return retorno;

    } catch (error) {
      console.error(error);
    }
  }

  function configuraGrafico() {
    options = {
      series: [{
        name: '',
        data: [{}]
      }],
      chart: {
        type: 'bar',
        height: 300
      },
      plotOptions: {
        bar: {
          colors: {
            ranges: [{
              from: -100,
              to: -46,
              color: '#F15B46'
            }, {
              from: -45,
              to: 0,
              color: '#FEB019'
            }]
          },
          columnWidth: '80%',
        }
      },
      dataLabels: {
        enabled: false,
      },
      title: {
        text: 'Ranking top 25',
      },
      tooltip: {
        x: {
          formatter: function (val) {
            return val;
          }
        }
      },
      yaxis: {
        labels: {
          formatter: function (y) {
            return y;
          }
        }
      },
      xaxis: {
        type: 'category',
        labels: {
          formatter: function (val) {
            return val.split(' - ')[0];
          }
        }
      },
      labels: {
        rotate: -90
      }
    };
  }

  function adicionaClickDate() {
    $('input[type="date"]').keydown(function (e) {
      let data = new Date();
      if (e.keyCode == 84) {
        $(this).val(`${data.getUTCFullYear()}-${String(data.getUTCMonth() + 1).padStart(2, 0)}-${String(data.getUTCDate()).padStart(2, 0)}`);
      } else if (e.keyCode == 82) {
        $(this).val(`1200-01-01`);
      } else if (e.keyCode == 89) {
        $(this).val(`2500-12-31`);
      } else if (e.keyCode === 189 || e.keyCode === 109) {
        let dtAtual = new Date($(this).val());
        dtAtual.setDate(dtAtual.getDate() - 1);
        let newData = dtAtual.toISOString().slice(0, 10);
        $(this).val(newData)
      } else if (e.keyCode === 187 || e.keyCode === 107) {
        let dtAtual = new Date($(this).val());
        dtAtual.setDate(dtAtual.getDate() + 1);
        let newData = dtAtual.toISOString().slice(0, 10);
        $(this).val(newData)
      }
    });
  };

  function esconderColunas() {

    const c = $('#tabelaRanking').DataTable().columns()[0].length;

    for (let i = 4; i < c - 3; i++) {
      $('#tabelaRanking').DataTable().column(i).visible(true);
      sum = 0;
      $('#tabelaRanking').DataTable().column(i, { search: 'applied' }).data().each(function (value) {
        let valor = parseFloat(value);
        if (!isNaN(valor)) {
          sum += valor;
        }
      });
      if (sum == 0) {
        $('#tabelaRanking').DataTable().column(i).visible(false);
      }
    }

    let listaColsInv = [];

    $('#tabelaRanking').DataTable().columns().every(function () {
      if (!this.visible()) {
        listaColsInv.push(this.dataSrc());
      }
    });

    localStorage.setItem(`colunasInvisiveisRelatorios`, JSON.stringify({ ...colunas, relRankingVendas: listaColsInv }));
  }

  $("#tutorial").on("click", 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 abrir os filtros padrões da tela.",
          position: "right",
        },
      },
      {
        element: "#btnImprimir",
        popover: {
          title: "Botão Imprimir",
          description: "Clique aqui para Imprimir um relatório.",
          position: "right",
        },
      },
      {
        element: "#tabelaRelEstoque",
        popover: {
          title: "Tabela",
          description: "Aqui estão os dados dos produtos Filtrados.",
          position: "top",
        },
      },
    ]);
    driver.start();
  });
});