$(document).ready(async function () {
  const utilizaStatus = await CopiaParametro('VENDA', 37) == 1;
  if (utilizaStatus) {
    $('#statusContainer').removeClass('d-none')
  } else {
    $('#statusContainer').addClass('d-none')
  }

  const dados = [
    [
      { "x": 1, "y": 1, "z": 20, "t": 1 },
      { "x": 2, "y": 1, "z": 45, "t": 1 },
      { "x": 3, "y": 1, "z": 12, "t": 1 },
      { "x": 4, "y": 1, "z": 37, "t": 1 },
      { "x": 5, "y": 1, "z": 42, "t": 1 },
      { "x": 8, "y": 1, "z": 57, "t": 1 },
      { "x": 9, "y": 1, "z": 86, "t": 1 },
      { "x": 10, "y": 1, "z": 92, "t": 1 },
      { "x": 11, "y": 1, "z": 49, "t": 1 },
      { "x": 12, "y": 1, "z": 42, "t": 1 },
      { "x": 15, "y": 1, "z": 48, "t": 1 },
      { "x": 16, "y": 1, "z": 97, "t": 1 },
      { "x": 17, "y": 1, "z": 87, "t": 1 },
      { "x": 18, "y": 1, "z": 92, "t": 1 },
      { "x": 19, "y": 1, "z": 83, "t": 1 },
      { "x": 22, "y": 1, "z": 35, "t": 1 },
      { "x": 23, "y": 1, "z": 21, "t": 1 },
      { "x": 24, "y": 1, "z": 45, "t": 1 },
      { "x": 25, "y": 1, "z": 96, "t": 1 },
      { "x": 26, "y": 1, "z": 82, "t": 1 }
    ],
    [
      { "x": 1, "y": 2, "z": 73, "t": 2 },
      { "x": 2, "y": 2, "z": 92, "t": 2 },
      { "x": 3, "y": 2, "z": 41, "t": 2 },
      { "x": 4, "y": 2, "z": 33, "t": 2 },
      { "x": 5, "y": 2, "z": 63, "t": 2 },
      { "x": 8, "y": 2, "z": 20, "t": 2 },
      { "x": 9, "y": 2, "z": 27, "t": 2 },
      { "x": 10, "y": 2, "z": 25, "t": 2 },
      { "x": 11, "y": 2, "z": 12, "t": 2 },
      { "x": 12, "y": 2, "z": 75, "t": 2 },
      { "x": 15, "y": 2, "z": 84, "t": 2 },
      { "x": 16, "y": 2, "z": 71, "t": 2 },
      { "x": 17, "y": 2, "z": 94, "t": 2 },
      { "x": 18, "y": 2, "z": 79, "t": 2 },
      { "x": 19, "y": 2, "z": 53, "t": 2 },
      { "x": 22, "y": 2, "z": 94, "t": 2 },
      { "x": 23, "y": 2, "z": 63, "t": 2 },
      { "x": 24, "y": 2, "z": 67, "t": 2 },
      { "x": 25, "y": 2, "z": 86, "t": 2 },
      { "x": 26, "y": 2, "z": 27, "t": 2 }
    ],
    [
      { "x": 1, "y": 3, "z": 20, "t": 3 },
      { "x": 2, "y": 3, "z": 53, "t": 3 },
      { "x": 3, "y": 3, "z": 83, "t": 3 },
      { "x": 4, "y": 3, "z": 11, "t": 3 },
      { "x": 5, "y": 3, "z": 2, "t": 3 },
      { "x": 8, "y": 3, "z": 71, "t": 3 },
      { "x": 9, "y": 3, "z": 28, "t": 3 },
      { "x": 10, "y": 3, "z": 84, "t": 3 },
      { "x": 11, "y": 3, "z": 65, "t": 3 },
      { "x": 12, "y": 3, "z": 3, "t": 3 },
      { "x": 15, "y": 3, "z": 60, "t": 3 },
      { "x": 16, "y": 3, "z": 49, "t": 3 },
      { "x": 17, "y": 3, "z": 96, "t": 3 },
      { "x": 18, "y": 3, "z": 46, "t": 3 },
      { "x": 19, "y": 3, "z": 33, "t": 3 },
      { "x": 22, "y": 3, "z": 28, "t": 3 },
      { "x": 23, "y": 3, "z": 28, "t": 3 },
      { "x": 24, "y": 3, "z": 46, "t": 3 },
      { "x": 25, "y": 3, "z": 57, "t": 3 },
      { "x": 26, "y": 3, "z": 66, "t": 3 }
    ],
    [
      { "x": 1, "low": 0, "high": 113, "week": 1, "avg": 37, "highscore": 73, "topEarner": "Sofia" },
      { "x": 2, "low": 0, "high": 190, "week": 1, "avg": 63, "highscore": 92, "topEarner": "Sofia" },
      { "x": 3, "low": 0, "high": 136, "week": 1, "avg": 45, "highscore": 83, "topEarner": "Asmara" },
      { "x": 4, "low": 0, "high": 81, "week": 1, "avg": 27, "highscore": 37, "topEarner": "Ulambaator" },
      { "x": 5, "low": 0, "high": 107, "week": 1, "avg": 35, "highscore": 63, "topEarner": "Sofia" },
      { "x": 8, "low": 0, "high": 148, "week": 2, "avg": 49, "highscore": 71, "topEarner": "Asmara" },
      { "x": 9, "low": 0, "high": 141, "week": 2, "avg": 47, "highscore": 86, "topEarner": "Ulambaator" },
      { "x": 10, "low": 0, "high": 201, "week": 2, "avg": 67, "highscore": 92, "topEarner": "Ulambaator" },
      { "x": 11, "low": 0, "high": 126, "week": 2, "avg": 42, "highscore": 65, "topEarner": "Asmara" },
      { "x": 12, "low": 0, "high": 120, "week": 2, "avg": 40, "highscore": 75, "topEarner": "Sofia" },
      { "x": 15, "low": 0, "high": 192, "week": 3, "avg": 64, "highscore": 84, "topEarner": "Sofia" },
      { "x": 16, "low": 0, "high": 217, "week": 3, "avg": 72, "highscore": 97, "topEarner": "Ulambaator" },
      { "x": 17, "low": 0, "high": 277, "week": 3, "avg": 92, "highscore": 96, "topEarner": "Asmara" },
      { "x": 18, "low": 0, "high": 217, "week": 3, "avg": 72, "highscore": 92, "topEarner": "Ulambaator" },
      { "x": 19, "low": 0, "high": 169, "week": 3, "avg": 56, "highscore": 83, "topEarner": "Ulambaator" },
      { "x": 22, "low": 0, "high": 157, "week": 4, "avg": 52, "highscore": 94, "topEarner": "Sofia" },
      { "x": 23, "low": 0, "high": 112, "week": 4, "avg": 37, "highscore": 63, "topEarner": "Sofia" },
      { "x": 24, "low": 0, "high": 158, "week": 4, "avg": 52, "highscore": 67, "topEarner": "Sofia" },
      { "x": 25, "low": 0, "high": 239, "week": 4, "avg": 79, "highscore": 96, "topEarner": "Ulambaator" },
      { "x": 26, "low": 0, "high": 175, "week": 4, "avg": 58, "highscore": 82, "topEarner": "Ulambaator" }
    ]
  ]

  const arrReps = ['Tiago', 'Eliton', 'Guerra'];

  // graficoAnaliseAvancada(dados, arrReps);

  $('#btnGrafico').on('click', function () {
    $('#modal-grafico').modal('show');
  });

  function graficoAnaliseAvancada(dados, arrReps) {
    const
      data = dados,
      scoreData = data[3],
      colors = Highcharts.getOptions().colors.map(Highcharts.Color.parse),

      // Defining recurring values.
      monthExtremes = { min: 0, max: 26 },
      weekExtremes = { min: 1, max: 5 },
      paneOpeningAngles = { startAngle: 40.5, endAngle: 319.5 },
      noLabelProp = { labels: { enabled: false } },
      specialSeriesProps = {
        showInLegend: false,
        groupPadding: 0,
        pointPadding: 0
      },

      // A gradient background for the inner circle (aka pane.)
      toggleableGradient = {
        pattern: undefined,
        radialGradient: [1, 0.25, 0.1],
        stops: [
          [0, '#1f1836'],
          [1, '#45445d']
        ]
      },

      // A function which (re)sets the inner circles background to our gradient.
      setGradient = function () {
        const chart = this.series.chart;
        chart.setMidPaneBg({
          backgroundColor: toggleableGradient,
          outerRadius: '75%'
        });
        chart.subtitle.element.style.opacity = 1;
      },

      // A function used in the creation of our second custom tooltip.
      asColFieldStr = str => (
        '<span class="col-display-fieldwrap">' +
        '<span class="symbolSize" ' +
        'style="color:{point.color};">●</span> ' + str + '</span>'
      ),

      // We create our teams, 1 serie per team.
      teamNames = arrReps,
      teamColors = [
        colors[9 % colors.length].tweenTo(colors[0], 0.25),
        colors[9 % colors.length].tweenTo(colors[8 % colors.length], 0.65),
        colors[9 % colors.length].tweenTo(colors[3], 0.85)
      ],
      teamSeries = Array(3).fill({
        type: 'bubble',
        shadow: true,
        maxSize: '4%',
        minSize: '1%',
        clip: false,
        point: {
          events: {

            // When hovering a bubble, change the inner circles background
            // to the color of its parent series.
            mouseOver: function () {
              const chart = this.series.chart;
              chart.subtitle.element.style.opacity = 0;
              chart.setMidPaneBg({
                backgroundColor: teamColors[this.series.index],
                innerRadius: '0%'
              });
            },
            mouseOut: setGradient
          }
        },
        colorKey: 't',

        // A custom tooltip, using our own CSS
        tooltip: {
          headerFormat: (
            '<div class="team-day center">' +
            '<span class="team-header">' +
            '<b class="team-index">Dia {point.x}</b></span>' +
            '<span class="team-name" style="' +
            'border: 0 outset {series.color};' +
            'border-block-end: 0 outset {series.color};">' +
            '<b>{series.name}</b></span>'
          ),
          pointFormat: (
            '<span class="team-points">' +
            '<span class="team-salescount-header">Vendas diárias:</span>' +
            '</br>' +
            '<span class="team-salescount">{point.z}</span>'
          ),
          footerFormat: '</div>'
        }
      }).map((seriesProps, i) => ({
        ...seriesProps,
        name: teamNames[i],
        data: data[i],
        color: teamColors[i],
        marker: {
          fillColor: teamColors[i],
          fillOpacity: 1,
          lineColor: '#46465C',
          lineWidth: 2
        }
      })),

      // We create a series which only purpose is to act as a label
      // indicating the week in which a given datapoint occurred.
      weekLabels = Array(4)
        .fill(0)
        .map((_value, index) => ({
          dataLabels: {
            format: 'Semana {x}',
            enabled: true,
            inside: true,
            style: {
              textOutline: undefined,
              fontSize: '0.7em',
              fontWeight: '700',
              textTransform: 'uppercase',
              fontStyle: 'normal',
              letterSpacing: '0.01em'
            },
            textPath: {
              enabled: true,
              attributes: {
                startOffset: (
                  index % 3 ? '75%' : (
                    index % 2 ? '22%' : '28%'
                  )
                ),
                dx: index % 2 ? '-2%' : '0%',
                dy: index % 3 ? '2.8%' : '3.3%'
              }
            }
          },
          x: index + 1,
          y: 1.5
        }));

    Highcharts.chart('container', {
      chart: {
        polar: true,
        height: '100%',
        events: {

          load: function () {
            const midPane = this.pane[1];

            // Our custom background functions are actually wrappers of the
            // function defined below. This function needs to be defined in
            // the load-event so that it is able to reference an instance
            // of Highcharts, without Highcharts being instantiated yet.
            this.setMidPaneBg = function (background) {
              midPane.update({ background: background });
            };
          },

          // We assign a function which positions our  dynamically
          // regardless of viewport or chart dimensions.
          render: function () {
            if (this.legend.group) {

              const
                { chartWidth, chartHeight, legend } = this,
                { legendWidth, legendHeight } = legend;

              legend.group.translate(
                (
                  (chartWidth - legendWidth) / 2
                ),
                legendHeight * (chartWidth / chartHeight)
              );
            }
          }
        }
      },
      title: {
        text: 'Análise avançada'
      },
      subtitle: {
        text: 'Performance dos<br>Vendedores',
        useHTML: 'true',
        align: 'center',
        y: 35,
        verticalAlign: 'middle',
        style: {
          fontSize: '1em',
          color: 'white',
          textAlign: 'center'
        }
      },
      tooltip: {
        animation: false,
        backgroundColor: undefined,
        hideDelay: 0,
        useHTML: true,

        // This function positions our tooltip in the center,
        // regardless of viewport or chart dimensions.
        positioner: function (labelWidth, labelHeight) {
          const { chartWidth, chartHeight } = this.chart;
          return {
            x: (chartWidth / 2) - (labelWidth / 2),
            y: (chartHeight / 2) - (labelHeight / 2)
          };
        }
      },
      colorAxis: [{
        minColor: colors[0].brighten(0.05).get('rgba'),
        maxColor: colors[5].brighten(0.05).get('rgba'),
        showInLegend: false,
        ...weekExtremes
      }, {
        minColor: colors[1].tweenTo(colors[5], 0.5),
        maxColor: colors[8 % colors.length].tweenTo(
          colors[8 % colors.length],
          0.5
        ),
        showInLegend: false,
        ...monthExtremes
      }],

      // Our chart is made of 3 different panes/circles
      pane: [{
        size: '80%',
        innerSize: '75%',
        ...paneOpeningAngles,
        background: {
          borderColor: colors[4],
          backgroundColor: toggleableGradient,
          innerRadius: '40%'
        }
      }, {
        size: '55%',
        innerSize: '45%',
        ...paneOpeningAngles,
        background: {
          borderWidth: 0,
          backgroundColor: toggleableGradient,
          outerRadius: '75%'
        }

        // ...And this the one we alter
      }, {
        size: '100%',
        innerSize: '88%',
        startAngle: 16.5,
        endAngle: 343.5,
        background: {
          borderWidth: 1,
          borderColor: colors[4],
          backgroundColor: '#46465C',
          innerRadius: '55%',
          outerRadius: '100%'
        }
      }],
      xAxis: [{
        pane: 0,
        tickInterval: 1,
        lineWidth: 0,
        gridLineWidth: 0,
        min: 1,
        max: 26,
        ...noLabelProp
      }, {
        pane: 1,
        linkedTo: 0,
        gridLineWidth: 0,
        lineWidth: 0,

        // We put some plotbands on the chart to represent weekends
        // when no datapoints occur.
        plotBands: Array(3).fill(7).map(
          (weekendOffset, week) => {
            const
              from = weekendOffset * (week + 1),
              to = from - 1;
            return { from, to, color: '#BBBAC5' };
          }
        ),
        ...monthExtremes,
        ...noLabelProp
      }, {
        pane: 2,
        tickAmount: 4,
        tickInterval: 0.5,
        gridLineWidth: 0,
        lineWidth: 0,
        ...weekExtremes,
        ...noLabelProp
      }],
      yAxis: [{
        pane: 0,
        gridLineWidth: 0.5,
        gridLineDashStyle: 'longdash',
        tickInterval: 1,
        title: null,
        ...noLabelProp,
        min: 1,
        max: 3
      }, {
        pane: 1,
        reversed: true,
        gridLineWidth: 0,
        tickInterval: 100,
        min: 0,
        max: 400,
        title: null,
        ...noLabelProp
      }, {
        pane: 2,
        tickInterval: 0.25,
        gridLineWidth: 0,
        gridLineColor: colors[1].brighten(0.05).get('rgba'),
        min: -3,
        max: 1,
        title: null,
        ...noLabelProp
      }],
      legend: {
        enabled: true,
        floating: true,
        layout: 'vertical',
        verticalAlign: 'center',
        align: 'center',
        backgroundColor: '#1f1836',
        borderRadius: 14,
        borderColor: 'transparent',
        borderWidth: 0,
        lineHeight: 8,
        itemStyle: {
          color: '#FFF',
          fontSize: '0.8em'
        },
        itemHoverStyle: {
          color: '#BBBAC5',
          fontSize: '0.9em'
        },
        padding: 2,
        itemDistance: 0,
        symbolPadding: 8,
        symbolHeight: 8,
        width: '36%',
        maxHeight: '14%'
      },
      plotOptions: {
        columnrange: {
          custom: {
            textSizeClass: 'small-size'
          }
        }
      },
      responsive: {
        rules: [
          {
            condition: {
              minWidth: 400
            },
            chartOptions: {
              legend: {
                lineHeight: 16,
                padding: 3,
                borderWidth: 0.5,
                itemStyle: {
                  fontSize: '0.9em'
                },
                itemHoverStyle: {
                  fontSize: '1.1em'
                },
                width: '34%'
              },
              subtitle: {
                style: {
                  fontSize: '1em'
                }
              }
            }
          }, {
            condition: {
              minWidth: 520
            },
            chartOptions: {
              legend: {
                borderWidth: 1,
                itemStyle: {
                  fontSize: '1.1em'
                },
                itemHoverStyle: {
                  fontSize: '1.25em'
                },
                width: '30%'
              },
              subtitle: {
                style: {
                  fontSize: '1.4em'
                }
              }
            }
          }, {
            condition: {
              minWidth: 600
            },
            chartOptions: {
              legend: {
                borderWidth: 1.5,
                itemStyle: {
                  fontSize: '1.2em'
                },
                itemHoverStyle: {
                  fontSize: '1.4em'
                },
                width: '26%'
              },
              plotOptions: {
                columnrange: {
                  custom: {
                    textSizeClass: 'mid-size'
                  }
                }
              },
              subtitle: {
                style: {
                  fontSize: '1.8em'
                }
              }
            }
          }, {
            condition: {
              minWidth: 680
            },
            chartOptions: {
              legend: {
                borderWidth: 2,
                symbolPadding: 12,
                symbolHeight: 12,
                itemStyle: {
                  fontSize: '1.4em'
                },
                itemHoverStyle: {
                  fontSize: '1.6em'
                }
              },
              plotOptions: {
                columnrange: {
                  custom: {
                    textSizeClass: 'large-size'
                  }
                }
              },
              subtitle: {
                style: {
                  fontSize: '2em'
                }
              }
            }
          }
        ]
      },
      series: [
        ...teamSeries, {
          ...specialSeriesProps,
          animation: false,
          name: 'Mês',
          type: 'column',
          data: weekLabels,
          xAxis: 2,
          yAxis: 2,
          borderRadius: 50,
          colorKey: 'x',
          pointWidth: 1.2,
          pointPlacement: 'between',
          enableMouseTracking: false
        }, {
          showInLegend: false,
          ...specialSeriesProps,
          animation: false,
          name: 'Total',
          type: 'columnrange',
          data: scoreData,
          xAxis: 1,
          yAxis: 1,
          shadow: false,
          colorAxis: 1,
          colorKey: 'x',
          borderColor: '#46465C',
          borderWidth: 2,
          pointPlacement: 'on',
          pointStart: 1,
          point: {
            events: {

              // Here we change our circle once again but this time
              // it is when the innermost column series is hovered.
              mouseOver: function () {
                const chart = this.series.chart;
                chart.setMidPaneBg({
                  backgroundColor: toggleableGradient,
                  outerRadius: '75%'
                });
                chart.subtitle.element.style.opacity = 0;
              },

              // We reuse our originally defined "setGradient" function
              // to reset the circles background when the mouse leaves
              // a hovered column.
              mouseOut: setGradient
            }
          },

          // ...And here is the custom tooltip content for the columns
          tooltip: {
            headerFormat: (
              '<span class="team-day center">' +
              '<span class="{series.options.custom.textSizeClass}">' +
              '<b style="color:{point.color};">Dia {point.x}</b></span>'
            ),
            hideDelay: 0,
            pointFormat: (
              asColFieldStr(
                '<b>Vendas: </b><span>{point.high}</span>'
              ) +
              asColFieldStr(
                '<b>Média: </b><span>{point.avg}</span>'
              ) +
              asColFieldStr(
                '<b>Recorde: </b><span>{point.highscore}</span>'
              ) +
              asColFieldStr(
                '<b>Maior vendedor: </b><span>{point.topEarner}</span>'
              )
            ),
            footerFormat: (
              '<i class="col-display-footer center">' +
              'Semana {point.week}</i></span></span>'
            )
          }
        }
      ]
    });
  }


  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 col-12 col-sm-6 mb-0 mr-2">
      <label for="txtDataEmissaoI">Data Emissão De/Até:</label>
      <div class="d-flex">
        <input type="date" max="2500-12-31" value="1200-01-01" max="2500-12-31" class="input-default focus form-control mr-2 col-12 col-sm-6" style="border-radius: 4px 0 0 4px;" id="txtDataEmissaoI" name="DataDe">
        <input type="date" max="2500-12-31" value="2500-12-01" max="2500-12-31" class="input-default focus form-control col-12 col-sm-6" style="border-radius: 0 4px 4px 0;" id="txtDataEmissaoF" name="DataAte">
    </div>
  </div>

  <div class="form-group col-lg-auto 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="d-flex pr-sm-2 pr-0" style="flex-wrap: wrap;">
        <div class="form-check mb-0 pb-0 icheck-primary">
          <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 icheck-primary">
          <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 icheck-primary">
          <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 icheck-primary">
          <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 icheck-primary">
          <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 col-12 col-sm-12 pt-1 text-center mb-2 mb-sm-0 mt-sm-3 mt-0">
    <div class="pl-0 pt-0 mt-2">
      <button id="btn-selecionar-empresas" type='button' class="btn btn-danger ml-0 mr-0 w-100">Selecionar empresas</button>
    </div>
  </div>

  <div class="form-group col-lg-4 col-12 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-12 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-12 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-12 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-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" id="statusContainer">
    <label data-error="wrong" data-success="right" for="txtStatus">Status: </label>
    <div class="relative">
      <div class="input-group">
        <select class="js-example-programmatic js-states form-control" id="txtStatus" name="txtStatus" multiple="multiple">
        </select>
        <div class="input-group-append">
          <button class="btn bg-danger" id="btnStatus" name="btnStatus" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
          <button class="btn bg-danger" id="btnLimpaStatus" 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="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-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" 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-12 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-12 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-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">
    <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 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-12 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);
    componenteFiltro('status', true, true, 'Status', [`TIPO = 'VEN'`])

    adicionaClickDate();

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

  async function pesquisaRadioMaterial() {
    const divRelAnalise = document.getElementById("divRelAnalise");
    divRelAnalise.innerHTML = `<div class="form-group col-lg col-12 col-sm-6 mb-0 mr-2">
    <label for="txtDataEmissaoI">Data Emissão De/Até:</label>
    <div class="d-flex">
      <input type="date" max="2500-12-31" value="1200-01-01" max="2500-12-31" class="input-default focus form-control mr-2 col-12 col-sm-6" style="border-radius: 4px 0 0 4px;" id="txtDataEmissaoI" name="DataDe">
      <input type="date" max="2500-12-31" value="2500-12-01" max="2500-12-31" class="input-default focus form-control col-12 col-sm-6" style="border-radius: 0 4px 4px 0;" id="txtDataEmissaoF" name="DataAte">
  </div>
</div>
  <div class="form-group col-lg-auto 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="d-flex pr-sm-2 pr-0" style="flex-wrap: wrap;">
        <div class="form-check mb-0 pb-0 icheck-primary">
          <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 icheck-primary">
          <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 icheck-primary">
          <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 icheck-primary">
          <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 icheck-primary">
          <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 col-12 col-sm-12 pt-1 text-center mb-2 mb-sm-0 mt-sm-3 mt-0">
    <div class="pl-0 pt-0 mt-2">
      <button id="btn-selecionar-empresas" type='button' class="btn btn-danger ml-0 mr-0 w-100">Selecionar empresas</button>
    </div>
  </div>

  <div class="form-group col-lg-4 col-12 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-12 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-12 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-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" 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-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" id="statusContainer">
    <label data-error="wrong" data-success="right" for="txtStatus">Status: </label>
    <div class="relative">
      <div class="input-group">
        <select class="js-example-programmatic js-states form-control" id="txtStatus" name="txtStatus" multiple="multiple">
        </select>
        <div class="input-group-append">
          <button class="btn bg-danger" id="btnStatus" name="btnStatus" data-button="absolute" type="button"><i class="m-0 p-0 fas fa-search"></i></button>
          <button class="btn bg-danger" id="btnLimpaStatus" 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 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-12 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-12 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-12 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-12 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-12 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);
    componenteFiltro('status', true, true, 'Status', [`TIPO = 'VEN'`])
    limparFiltros();

    adicionaClickDate();

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

  $('#btnLimparFiltros').on('click', function () {
    limparFiltros(true);
    $('#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;
    }
  });

  retornaHintRelatorio('btnImprimir', 'RelAnaliseVendedorPadrao')

  $('#txtOrdem').on('change', function () {
    retornaHintRelatorio('btnImprimir', $('#txtOrdem option')
      .toArray()
      .map(map => { return [map.selected, $(map).attr('nome_prt')] })
      .filter(filter => filter[0] == true)[0][1])
  })

  $("#btnImprimir").on("click", async function () {
    try {
      $.LoadingOverlay("show");
      try {
        const ordemOrdenacao = $('#txtOrdem').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;
    }
  }

  let chart = null;

  $("#btnConsultar").on("click", async function () {
    Graficos.limpaGrafico(['graficoRelAnaliseVendedor', 'graficoRelAnaliseVendedor1', 'graficoRelAnaliseVendedor2']);
    try {
      $.LoadingOverlay("show");
      try {
        if ($.fn.DataTable.isDataTable("#tabelaRanking")) {
          $("#tabelaRanking").DataTable().destroy();
          $("#tabelaRanking").empty();
        }

        listaOrdenacao = [];
        let dataSetCols = [];
        const ordemOrdenacao = $('#txtOrdem').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!");
          $('#chart').empty();
          $('#chart2').empty();
          $('#chart3').empty();
          $('#chart').addClass('d-none');
          $('#chart2').addClass('d-none');
          $('#chart3').addClass('d-none');
          chart.destroy();
          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,
          filter: true,
          paging: true,
          destroy: true,
          autoWidth: true,
          colReorder: true,
          data: jsonStr,
          columns: dataSetCols,
          columnDefs: [
            {
              render: function (data) {
                return parseFloat(data).toLocaleString("pt-br", {
                  maximumFractionDigits: 2,
                  minimumFractionDigits: 2,
                });
              },
              targets: [3, 5, 6, 7],
              "className": 'pr-4 text-right'
            },
            {
              targets: [2, 4],
              "className": 'pr-4 text-right'
            },
          ],
        });

        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 = $('#txtOrdem').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);
            }
          }
          );

        const dados = $('#tabelaRanking').DataTable().data().toArray();
        await montaGraficos(dados);
      } catch (error) {
        console.error(error);
      }
    } finally {
      $.LoadingOverlay("hide");
      $("#modal-filtros").modal("hide");
    }
  });

  async function montaGraficos(dados) {
    dados.forEach(item => {
      item.NOME_REPRESEN = `${item.CODREP} - ${item.NOME_REPRESEN}`;
    });

    Graficos.criarGrafico({
      container: 'graficoRelAnaliseVendedor',
      tipo: 'column',
      dados: dados,
      nomeSerie: 'TicketMedio',
      colunasAgrupamento: ['NOME_REPRESEN'],
      colunasValor: ['TICKET_MEDIO'],
      bHorizontal: true,
      qtdeRegistros: 10,
      title: 'Gráfico Ticket Médio (Top 10)'
    })

    Graficos.criarGrafico({
      container: 'graficoRelAnaliseVendedor1',
      tipo: 'column',
      dados: dados,
      nomeSerie: 'PA',
      colunasAgrupamento: ['NOME_REPRESEN'],
      colunasValor: ['PA'],
      bHorizontal: true,
      qtdeRegistros: 10,
      title: 'Gráfico P.A. (Top 10)'
    })

    Graficos.criarGrafico({
      container: 'graficoRelAnaliseVendedor2',
      tipo: 'column',
      dados: dados,
      nomeSerie: 'VM',
      colunasAgrupamento: ['NOME_REPRESEN'],
      colunasValor: ['VM'],
      bHorizontal: true,
      qtdeRegistros: 10,
      title: 'Gráfico V.M. (Top 10)'
    })
  }

  $("#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 status = await formataListas($('#txtStatus').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}` +
          `&STATUS=${status}` +
          `&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}` +
          `&STATUS=${status}` +
          `&EMP_ID=${listaEmpIds}`;
      }

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

  await preencheOrdenacaoTela('RelAnaliseVendedor');

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