$(document).ready(async function () {
  let options = {
    series: [
      {
        data: [{}],
      },
    ],
    chart: {
      type: "bar",
      height: 325,
    },
    tooltip: {
      y: {
        title: {
          formatter: function (val) {
            return val;
          },
        },
      },
    },
    plotOptions: {
      bar: {
        distributed: true,
        horizontal: true,
      },
    },
    fill: {
      colors: [
        "#75BE25",
        "#2195F0",
        "#F43E47",
        "#AF69D9",
        "#EDFC2C",
        "#818181",
        "#29E8FC",
        "#F800E0",
        "#F86A00",
        "#1200F8",
      ],
    },
    legend: {
      show: false,
    },
    title: {
      text: "",
    },
  };

  let options2 = {
    series: [
      {
        data: [{}],
      },
    ],
    chart: {
      type: "bar",
      height: 325,
    },
    tooltip: {
      y: {
        title: {
          formatter: function (val) {
            return val;
          },
        },
      },
    },
    plotOptions: {
      bar: {
        distributed: true,
        horizontal: true,
      },
    },
    fill: {
      colors: [
        "#75BE25",
        "#2195F0",
        "#F43E47",
        "#AF69D9",
        "#EDFC2C",
        "#818181",
        "#29E8FC",
        "#F800E0",
        "#F86A00",
        "#1200F8",
      ],
    },
    legend: {
      show: false,
    },
    title: {
      text: "",
    },
  };

  let options3 = {
    series: [
      {
        data: [{}],
      },
    ],
    chart: {
      type: "bar",
      height: 325,
    },
    tooltip: {
      y: {
        title: {
          formatter: function (val) {
            return val;
          },
        },
      },
    },
    plotOptions: {
      bar: {
        distributed: true,
        horizontal: true,
      },
    },
    fill: {
      colors: [
        "#75BE25",
        "#2195F0",
        "#F43E47",
        "#AF69D9",
        "#EDFC2C",
        "#818181",
        "#29E8FC",
        "#F800E0",
        "#F86A00",
        "#1200F8",
      ],
    },
    legend: {
      show: false,
    },
    title: {
      text: "",
    },
  };

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

  let listaOrdenacao = [];

  if (colunas == null || colunas.analiseVendedor == undefined) {
    localStorage.setItem(
      "colunasInvisiveisRelatorios",
      JSON.stringify({ ...colunas, analiseVendedor: [] })
    );
    colunas = JSON.parse(localStorage.getItem("colunasInvisiveisRelatorios"));
  }

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

      const novasColunas = retornaNovasColunasInvisiveis();

      localStorage.setItem(
        "colunasInvisiveisRelatorios",
        JSON.stringify({ ...colunas, analiseVendedor: 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");
    }
  });

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

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

  async function pesquisaRadioProduto() {
    const divRelAnalise = document.getElementById("divRelAnalise");

    divRelAnalise.innerHTML = `<div class="form-group col-lg-2 col-2 col-sm-6 mb-0">
    <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 col-2 col-sm-6 mb-0">
    <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-6 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-2 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="form-group col-lg-4 col-4 col-sm-12">
    <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-4 col-sm-12">
    <label 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="Guia"> -->
        <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 class="form-group col-lg-4 col-4 col-sm-12">
    <label 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="Cliente"> -->
        <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-4 col-sm-12 classFornecedor">
    <label data-error="wrong" data-success="right" id="labelFornecedor" 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-4 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-4 col-sm-12">
    <label data-error="wrong" data-success="right" id="labelUsuario" 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-4 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-4 col-sm-12 classColecao">
    <label data-error="wrong" data-success="right" id="labelColecao" 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-4 col-sm-12 classModelo">
    <label data-error="wrong" data-success="right" id="labelModelo" for="txtModelo">Modelo: </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="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-4 col-sm-12 classGrupo">
    <label data-error="wrong" data-success="right" for="txtGrupoPA">Grupo: </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="Grupo"> -->
        <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-4 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-4 col-sm-12">
    <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-4 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-4 col-sm-12 classDeposito">
    <label data-error="wrong" data-success="right" id="labelDeposito" for="txtDeposito">Depósito: </label>
    <div class="relative">
      <div class="input-group">
        <!-- <input type="text" class="input-default focus form-control" id="txtDeposito" name="txtDeposito" class="form-control" placeholder="Depósito"> -->
        <select class="js-example-programmatic js-states form-control" id="txtDeposito" name="txtDeposito" multiple="multiple">
        </select>
        <div class="input-group-append">
          <button class="btn bg-danger" id="btnDeposito" name="btnDeposito" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
          <button class="btn bg-danger" id="btnLimpaDeposito" 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-4 col-sm-12 classTabela">
    <label data-error="wrong" data-success="right" id="labelTabPreco" 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>`;

    componenteFiltro("vendedor", true);
    componenteFiltro("guia", true);
    componenteFiltro("cliente", true);
    componenteFiltro("fornecedor", true);
    componenteFiltro("produto", true);
    componenteFiltro("grupoPA", true);
    componenteFiltro("usuario", true);
    componenteFiltro("tipoVenda", true);
    componenteFiltro("marca", true);
    componenteFiltro("etiqueta", true);
    componenteFiltro("deposito", true);
    componenteFiltro("tabPreco", true);
    // componenteFiltro("tipoProduto", true);
    componenteFiltro("colecao", true);
    componenteFiltro("linha", true);
    componenteFiltro("modelo", true);

    adicionaClickDate();

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

  async function pesquisaRadioMaterial() {
    const divRelAnalise = document.getElementById("divRelAnalise");
    divRelAnalise.innerHTML = `<div class="form-group col-lg-2 col-2 col-sm-6 mb-0">
    <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 col-2 col-sm-6 mb-0">
    <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-6 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-2 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="form-group col-lg-4 col-4 col-sm-12">
    <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-4 col-sm-12">
    <label 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="Guia"> -->
        <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 class="form-group col-lg-4 col-4 col-sm-12">
    <label 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="Cliente"> -->
        <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-4 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-4 col-sm-12 classColecao">
    <label data-error="wrong" data-success="right" id="labelColecao" 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-4 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-4 col-sm-12 classGrupo">
    <label data-error="wrong" data-success="right" for="txtGrupoMA">Grupo: </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-4 col-sm-12 classSubGrupo">
    <label data-error="wrong" data-success="right" id="labelSubGrupo" for="txtSubGrupo">SubGrupo: </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="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-4 col-sm-12">
    <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-4 col-sm-12 classDeposito">
    <label data-error="wrong" data-success="right" id="labelDeposito" for="txtDeposito">Depósito: </label>
    <div class="relative">
      <div class="input-group">
        <!-- <input type="text" class="input-default focus form-control" id="txtDeposito" name="txtDeposito" class="form-control" placeholder="Depósito"> -->
        <select class="js-example-programmatic js-states form-control" id="txtDeposito" name="txtDeposito" multiple="multiple">
        </select>
        <div class="input-group-append">
          <button class="btn bg-danger" id="btnDeposito" name="btnDeposito" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
          <button class="btn bg-danger" id="btnLimpaDeposito" 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-4 col-sm-12 classTabela">
    <label data-error="wrong" data-success="right" id="labelTabPreco" 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-4 col-sm-12">
    <label data-error="wrong" data-success="right" id="labelUsuario" 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>
`;

    componenteFiltro("vendedor", true);
    componenteFiltro("guia", true);
    componenteFiltro("cliente", true);
    componenteFiltro("material", true);
    componenteFiltro("grupoMA", true);
    componenteFiltro("usuario", true);
    componenteFiltro("tipoVenda", true);
    componenteFiltro("subGrupo", true);
    componenteFiltro("deposito", true);
    componenteFiltro("tabPreco", true);
    componenteFiltro("colecao", true);
    componenteFiltro("linha", true);
    limparFiltros();

    adicionaClickDate();

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

  $('#btnLimparFiltros').on('click', function () {
    limparFiltros();
    $('#radioQtde').prop('checked', true);
    $('#cbEmitido').prop('checked', true);
    $('#cbDevolvido').prop('checked', true);
    $('#cbPendente').prop('checked', false);
  });

  // limpa campos
  $("#btn-limpa-Vendedor").on("click", function () {
    if ($("#listaVendedor").val() == "") {
      $("#txtVendedor").val("");
    } else {
      $("#listaVendedor").val("");
    }
  });
  $("#btn-limpa-Guia").on("click", function () {
    if ($("#listaGuia").val() == "") {
      $("#txtGuia").val("");
    } else {
      $("#listaGuia").val("");
    }
  });
  $("#btn-limpa-Cliente").on("click", function () {
    if ($("#listaCliente").val() == "") {
      $("#txtCliente").val("");
    } else {
      $("#listaCliente").val("");
    }
  });
  $("#btn-limpa-Fornecedor").on("click", function () {
    if ($("#listaFornecedor").val() == "") {
      $("#txtFornecedor").val("");
    } else {
      $("#listaFornecedor").val("");
    }
  });
  $("#btn-limpa-Codigo").on("click", function () {
    if ($("#listaCodigo").val() == "") {
      $("#txtCodigo").val("");
    } else {
      $("#listaCodigo").val("");
    }
  });
  $("#btn-limpa-Grupo").on("click", function () {
    if ($("#listaGrupo").val() == "") {
      $("#txtGrupo").val("");
    } else {
      $("#listaGrupo").val("");
    }
  });
  $("#btnLimpaUsuario").on("click", function () {
    $("#txtUsuario").val("");
  });
  $("#btnLimpaTipoVenda").on("click", function () {
    if ($("#listaTipoVenda").val() == "") {
      $("#txtTipoVenda").val("");
    } else {
      $("#listaTipoVenda").val("");
    }
  });
  $("#btn-limpa-Marca").on("click", function () {
    if ($("#listaMarca").val() == "") {
      $("#txtMarca").val("");
    } else {
      $("#listaMarca").val("");
    }
  });
  $("#btn-limpa-Etiqueta").on("click", function () {
    if ($("#listaEtiqueta").val() == "") {
      $("#txtEtiqueta").val("");
    } else {
      $("#listaEtiqueta").val("");
    }
  });
  $("#btn-limpa-Deposito").on("click", function () {
    if ($("#listaDeposito").val() == "") {
      $("#txtDeposito").val("");
    } else {
      $("#listaDeposito").val("");
    }
  });
  $("#btn-limpa-Tabela").on("click", function () {
    if ($("#listaTabela").val() == "") {
      $("#txtTabela").val("");
    } else {
      $("#listaTabela").val("");
    }
  });
  $("#btn-limpa-TpProduto").on("click", function () {
    if ($("#listaTpProduto").val() == "") {
      $("#txtTpProduto").val("");
    } else {
      $("#listaTpProduto").val("");
    }
  });
  $("#btn-limpa-Colecao").on("click", function () {
    if ($("#listaColecao").val() == "") {
      $("#txtColecao").val("");
    } else {
      $("#listaColecao").val("");
    }
  });
  $("#btn-limpa-Linha").on("click", function () {
    if ($("#listaLinha").val() == "") {
      $("#txtLinha").val("");
    } else {
      $("#listaLinha").val("");
    }
  });
  $("#btnLimpaSubGrupo").on("click", function () {
    if ($("#listaSubGrupo").val() == "") {
      $("#txtSubGrupo").val("");
    } else {
      $("#listaSubGrupo").val("");
    }
  });

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

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

  $("#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;
    }
  });

  $("#btnImprimir").on("click", async function () {
    try {
      $.LoadingOverlay("show");
      try {
        const ordemOrdenacao = $('#selectOpcaoRelatorio').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/relanalisevendedor?ordem_ordenacao=${ordemOrdenacao}&emitido=${emitido}&devolvido=${devolvido}&pendente=${pendente}&agrupado=${agrupado}&cancelado=${cancelado}&USAMATERIAL=${material}&ORDERBY=${listaOrdenacao}&`;
        const Filtros = await preencheFiltros(material);
        const bImprimeAutomatico = await verificaImprimirAutomatico(
          "RelAnaliseVendedor"
        );
        const arquivo = await GeraRelatorio(
          `${url}${Filtros}`,
          "POST",
          100000,
          false,
          "RelAnaliseVendedor"
        );

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

  function formataColunas(txt) {
    if (txt == "CODREP") {
      return "Vendedor";
    } else if (txt == "NOME_REPRESEN") {
      return "Nome Vendedor";
    } else if (txt == "QUANTIDADE") {
      return "Quantidade";
    } else if (txt == "VALOR") {
      return "Valor";
    } else if (txt == "VENDAS") {
      return "Vendas";
    } else if (txt == "TICKET_MEDIO") {
      return "Ticket Médio";
    } else if (txt == "PA") {
      return "P.A.";
    } else if (txt == "VM") {
      return "V.M.";
    } else {
      return txt;
    }
  }

  $("#btnConsultar").on("click", async function () {
    try {
      $.LoadingOverlay("show");
      try {
        if ($.fn.DataTable.isDataTable("#tabelaRanking")) {
          $("#tabelaRanking").DataTable().destroy();
          $("#tabelaRanking").empty();
        }

        listaOrdenacao = [];
        let dataSetCols = [];
        const ordemOrdenacao = $('#selectOpcaoRelatorio').val();
        const emitido = $("#cbEmitido").prop("checked");
        const pendente = $("#cbPendente").prop("checked");
        const agrupado = $('#cbAgrupado').prop('checked');
        const devolvido = $("#cbDevolvido").prop("checked");
        const cancelado = $('#cbCancelado').prop('checked');
        const material = $("#radioMaterial").prop("checked");
        const url = `/sisplan/impressao/v1/relanalisevendedor?ordem_ordenacao=${ordemOrdenacao}&emitido=${emitido}&devolvido=${devolvido}&pendente=${pendente}&agrupado=${agrupado}&cancelado=${cancelado}&USAMATERIAL=${material}&`;
        const Filtros = await preencheFiltros(material);
        const response = await requisicao("GET", url, Filtros, "", 30000);

        if (!response) {
          return;
        }

        const jsonStr = await response.json();

        if (jsonStr.length == 0) {
          msgAlerta("Nenhum registro encontrado!");
          return;
        }

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

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

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

        $("#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).toFixed(2);
              },
              targets: [5, 6, 7],
            },
            {
              render: function (data) {
                return parseFloat(data).toLocaleString("pt-br", {
                  maximumFractionDigits: 2,
                  minimumFractionDigits: 2,
                });
              },
              targets: [3],
            },
          ],
        });

        const colunasInvisiveis = JSON.parse(
          localStorage.getItem("colunasInvisiveisRelatorios")
        );

        $("#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 ordemOrdenacao = $('#selectOpcaoRelatorio').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/relanalisevendedor?ordem_ordenacao=${ordemOrdenacao}&emitido=${emitido}&devolvido=${devolvido}&pendente=${pendente}&agrupado=${agrupado}&cancelado=${cancelado}&USAMATERIAL=${material}&`;
          const Filtros = await preencheFiltros(material);
          await exportaCSV(
            url+`&ORDERBY=${listaOrdenacao}&`,
            Filtros,
            false,
            null,
            "Relatório de Análise Vendedor",
            "#tabelaRanking",
            formataCampos()
          );
        });

        $('#tabelaRanking th').on('click', function () {
          listaOrdenacao = adicionaOrdenacao(
            retornaDataSrcColuna($('#tabelaRanking'), $(this)),
            listaOrdenacao
          );
        });

        $("#buttonColVis").prop("title", "Configurar colunas");
        $("#buttonExcel").prop("title", "Exportar CSV");

        $("#tabelaRanking")
          .DataTable()
          .columns()
          .every(function () {
            if (
              colunasInvisiveis.analiseVendedor.indexOf(this.dataSrc()) != -1
            ) {
              this.visible(false);
            }
          });

        await montaGraficos(jsonStr);
      } catch (error) {
        console.error(error);
      }
    } finally {
      $.LoadingOverlay("hide");
      $("#modal-filtros").modal("hide");
    }
  });

  async function montaGraficos(dados) {
    $("#chart").empty();
    $("#chart2").empty();
    $("#chart3").empty();

    let c = dados.length;

    if (c > 10) {
      c = 10;
    }

    let arrDadosGrafico = [];
    for (i = 0; i < c; i++) {
      arrDadosGrafico.push({
        x: dados[i].CODREP + ' - ' + dados[i].NOME_REPRESEN,
        y: parseFloat(dados[i]["TICKET_MEDIO"]).toFixed(2),
      });
    }

    let arrDadosGrafico2 = [];
    for (i = 0; i < c; i++) {
      arrDadosGrafico2.push({
        x: dados[i].CODREP + ' - ' + dados[i].NOME_REPRESEN,
        y: parseFloat(dados[i]["PA"]).toFixed(2),
      });
    }

    let arrDadosGrafico3 = [];
    for (i = 0; i < c; i++) {
      arrDadosGrafico3.push({
        x: dados[i].CODREP + ' - ' + dados[i].NOME_REPRESEN,
        y: parseFloat(dados[i]["VM"]).toFixed(2),
      });
    }

    arrDadosGrafico.sort(function (a, b) {
      if (parseFloat(a.y) < parseFloat(b.y)) {
        return 1;
      } else if (parseFloat(a.y) > parseFloat(b.y)) {
        return -1;
      } else {
        return 0;
      }
    });

    arrDadosGrafico2.sort(function (a, b) {
      if (parseFloat(a.y) < parseFloat(b.y)) {
        return 1;
      } else if (parseFloat(a.y) > parseFloat(b.y)) {
        return -1;
      } else {
        return 0;
      }
    });

    arrDadosGrafico3.sort(function (a, b) {
      if (parseFloat(a.y) < parseFloat(b.y)) {
        return 1;
      } else if (parseFloat(a.y) > parseFloat(b.y)) {
        return -1;
      } else {
        return 0;
      }
    });

    options.series[0].data = arrDadosGrafico;
    options.series[0].name = 'Ticket Médio';
    options.title.text = "Gráfico Ticket Médio (Top 10)";
    const chart = await new ApexCharts(
      document.querySelector("#chart"),
      options
    );
    chart.render();
    options2.series[0].data = arrDadosGrafico2;
    options2.series[0].name = 'P. A.';
    options2.title.text = "Gráfico P.A. (Top 10)";
    const chart2 = await new ApexCharts(
      document.querySelector("#chart2"),
      options2
    );
    chart2.render();
    options3.series[0].data = arrDadosGrafico3;
    options3.series[0].name = 'V. M.';
    options3.title.text = "Gráfico V.M. (Top 10)";
    const chart3 = await new ApexCharts(
      document.querySelector("#chart3"),
      options3
    );
    chart3.render();
  }

  $("#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(),
        });
      });
    adicionaColunas(cols, colunasInvisiveis.analiseVendedor ?? []);
  });

  function formataCampos() {
    retorno =
      "dados = dados.map((key) => { \n" +
      `let v1 = key.VALOR 
      if (typeof v1 == 'string') {
      v1 = parseFloat(v1.replace(".", "").replace(",", ".")).toFixed(2)
      } else {
      v1 = parseFloat(v1).toFixed(2) }
      let v2 = key.TICKET_MEDIO 
      if (typeof v2 == 'string') {
      v2 = parseFloat(v2.replace(".", "").replace(",", ".")).toFixed(2)
      } else {
      v2 = parseFloat(v2).toFixed(2) }
      let v3 = key.PA 
      if (typeof v3 == 'string') {
      v3 = parseFloat(v3.replace(".", "").replace(",", ".")).toFixed(2)
      } else {
      v3 = parseFloat(v3).toFixed(2) }
      let v4 = key.VM 
      if (typeof v4 == 'string') {
      v4 = parseFloat(v4.replace(".", "").replace(",", ".")).toFixed(2)
      } else {
      v4 = parseFloat(v4).toFixed(2) }` +
      "return {...key, VALOR: v1, TICKET_MEDIO: v2, PA: v3, VM: v4 } \n" +
      "}) \n";
    return retorno;
  }

  async function preencheFiltros(tipoFiltros) {
    try {
      let retorno = "";
      const sTipoVenda = await formataListas(
        $("#txtTipoVenda").val().toString()
      );
      // const usuario = pegaDescricao('#txtUsuario') == '** TODOS **' ? '' : pegaDescricao('#txtUsuario');
      const usuario = await validaFiltroUsuario(
        await formataListas($("#txtUsuario").val().toString())
      );
      if (tipoFiltros) {
        const Vendedor = await formataListas(
          $("#txtVendedor").val().toString()
        );
        const Codigo = await formataListas($("#txtMaterial").val().toString());
        const Tabela = await formataListas($("#txtTabPreco").val().toString());
        const DataIni = $("#txtDataEmissaoI").val();
        const DataFim = $("#txtDataEmissaoF").val();
        const Cliente = await formataListas($("#txtCliente").val().toString());
        const sSubGrupo = await formataListas(
          $("#txtSubGrupo").val().toString()
        );
        const Grupo = await formataListas($("#txtGrupoMA").val().toString());
        const Linha = await formataListas($("#txtLinha").val().toString());
        const Deposito = await formataListas(
          $("#txtDeposito").val().toString()
        );
        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")];
        const Guia = await formataListas($("#txtGuia").val().toString());
        retorno =
          `VENDEDOR=${Vendedor}` +
          `&DATAINI=${DataIni}` +
          `&DATAFIM=${DataFim}` +
          `&CODIGO=${Codigo}` +
          `&TABELA=${Tabela}` +
          `&SUBGRUPO=${sSubGrupo}` +
          `&CLIENTE=${Cliente}` +
          `&GRUPO=${Grupo}` +
          `&DEPOSITO=${Deposito}` +
          `&EMP_IDS=${listaEmpIds}` +
          `&TIPO_VENDA=${sTipoVenda}` +
          `&LINHA=${Linha}` +
          `&USR_CAIXA=${usuario}` +
          `&GUIA=${Guia}` +
          `&EMP_ID=${listaEmpIds}`;
      } else {
        const Vendedor = await formataListas(
          $("#txtVendedor").val().toString()
        );
        const Codigo = await formataListas($("#txtProduto").val().toString());
        const Tabela = await formataListas($("#txtTabPreco").val().toString());
        const DataIni = $("#txtDataEmissaoI").val();
        const DataFim = $("#txtDataEmissaoF").val();
        const Cliente = await formataListas($("#txtCliente").val().toString());
        const Marca = await formataListas($("#txtMarca").val().toString());
        const Grupo = await formataListas($("#txtGrupoPA").val().toString());
        const Modelo = await formataListas($('#txtModelo').val().toString());
        const Etiqueta = await formataListas(
          $("#txtEtiqueta").val().toString()
        );
        const Fornecedor = await formataListas(
          $("#txtFornecedor").val().toString()
        );
        const Colecao = await formataListas($("#txtColecao").val().toString());
        const Linha = await formataListas($("#txtLinha").val().toString());
        const Deposito = await formataListas(
          $("#txtDeposito").val().toString()
        );
        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")];
        const Guia = await formataListas($("#txtGuia").val().toString());
        retorno =
          `VENDEDOR=${Vendedor}` +
          `&DATAINI=${DataIni}` +
          `&DATAFIM=${DataFim}` +
          `&CODIGO=${Codigo}` +
          `&TABELA=${Tabela}` +
          `&MARCA=${Marca}` +
          `&CLIENTE=${Cliente}` +
          `&GRUPO=${Grupo}` +
          `&ETIQUETA=${Etiqueta}` +
          `&FORNECEDOR=${Fornecedor}` +
          `&COLECAO=${Colecao}` +
          `&LINHA=${Linha}` +
          `&DEPOSITO=${Deposito}` +
          `&EMP_IDS=${listaEmpIds}` +
          `&TIPO_VENDA=${sTipoVenda}` +
          `&USR_CAIXA=${usuario}` +
          `&GUIA=${Guia}` +
          `&MODELO=${Modelo}` +
          `&EMP_ID=${listaEmpIds}`;
      }

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

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

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

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

  await adicionaOrdem();

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

  $("#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: "#tabelaRanking",
        popover: {
          title: "Tabela",
          description: "Aqui estão os dados dos itens Filtrados.",
          position: "top",
        },
      },
    ]);
    driver.start();
  });
});
