Date.prototype.getWeek = function () {
  var date = new Date(this.getTime());
  date.setHours(0, 0, 0, 0);
  // Thursday in current week decides the year.
  date.setDate(date.getDate() + 3 - ((date.getDay() + 6) % 7));
  // January 4 is always in week 1.
  var week1 = new Date(date.getFullYear(), 0, 4);
  // Adjust to Thursday in week 1 and count number of weeks from date to week1.
  return (
    1 +
    Math.round(
      ((date.getTime() - week1.getTime()) / 86400000 -
        3 +
        ((week1.getDay() + 6) % 7)) /
        7
    )
  );
};
var days = function (month, year) {
  return new Date(year, month, 0).getDate();
};
function loadTable(filter) {
  console.log(filter);
  $.ajax({
    url: "/ajax/get/statistic/balance",
    dataType: "json",
    type: "GET",
    delay: 250,
    data: filter,
  }).done(function (jsonData) {
    var sumRevenue = 0;
    var sumCost = 0;
    var sumAvg = 0;
    var sumAvgNotEmpty = 0;
    var countMachines = 0;
    var sumBalance = 0;
    jsonData.forEach((e) => {
      sumAvg += e.avarage;
      sumBalance += e.balance;
      e.loc = e.city + " " + e.address;
      e.grossAvg = e.balance / days(e.month, e.year);
      sumAvgNotEmpty += e.grossAvg;
      countMachines += 1;
      e.grossAvg = e.grossAvg.toFixed(2);
      e.avarage = e.avarage.toFixed(2);
    });
    sumAvg /= countMachines;
    sumAvg = sumAvg.toFixed(2);
    sumAvgNotEmpty /= countMachines;
    sumAvgNotEmpty = sumAvgNotEmpty.toFixed(2);

    var sumDate = {
      address: "-",
      avarage: sumAvg,
      balance: sumBalance,
      city: "-",
      grossAvg: sumAvgNotEmpty,
      loc: "-",
      title: "Összes",
    };
    jsonData.push(sumDate);
    $("#machineRevenue").html(sumRevenue + " Ft");
    $("#machineCost").html(sumCost + " Ft");
    $("#jsGrid").jsGrid({
      width: "100%",
      height: "600px",
      readonly: true,
      sorting: true,
      paging: true,
      pageSize: 50,
      data: jsonData,
      fields: [
        { name: "title", type: "text", width: 100, title: "Megnevezés" },
        { name: "loc", type: "text", title: "Helyszín" },
        { name: "balance", type: "number", width: 75, title: "Bevétel" },
        { name: "grossAvg", type: "number", width: 75, title: "Átlag" },
        { name: "avarage", type: "number", width: 75, title: "Átlag, !EMPTY" },
      ],
    });
  });
}
$("button.refreshData").on("click", function (ev, picker) {
  let dateText = $(".datepicker").val();
  $(this).datepicker("setDate", new Date(dateText));
  let date = new Date(dateText);
  let dateType = $("#dateType").val();
  //console.log(date.getUTCDay());
  var urlParams = new URLSearchParams(window.location.search);
  let _id = urlParams.get("econid");
  switch (dateType) {
    case "year":
      loadTable({ year: date.getFullYear() });
      loadGraph({ year: date.getFullYear() });
      break;
    case "month":
      loadTable({
        year: date.getFullYear(),
        month: date.getMonth() + 1,
      });
      loadGraph({
        year: date.getFullYear(),
        month: date.getMonth() + 1,
      });
      break;
    case "week":
      loadTable({ year: date.getFullYear(), week: date.getWeek() });
      loadGraph({ year: date.getFullYear(), week: date.getWeek() });
      break;
    case "day":
      loadTable({
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        day: date.getDate(),
      });
      loadGraph({
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        day: date.getDate(),
      });
      break;
  }
});
$(".datepicker").daterangepicker({
  singleDatePicker: true,
  firstDay: 1,
  locale: {
    format: "YYYY-MM-DD",
    separator: " - ",
    firstDay:1,
    applyLabel: "Mentés",
    cancelLabel: "Mégse",
    startView: "months", 
    minViewMode: "months",
    daysOfWeek: ["V", "H", "K", "Sze", "Cs", "P", "Szo"],
    monthNames: [
      "Január",
      "Február",
      "Március",
      "Április",
      "Május",
      "Június",
      "Július",
      "Augusztus",
      "Szeptember",
      "Október",
      "November",
      "December",
    ],
  },
});
function loadGraph(filter) {
  // Sales graph chart
  $("#line-chart").remove();
  $(".card-body.line-Chart").append(
    `<canvas class="chart chartjs-render-monitor" id="line-chart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%; display: block; width: 674px;" width="674" height="250"></canvas>`
  );
  var salesGraphChartCanvas = $("#line-chart").get(0).getContext("2d");
  // $('#revenue-chart').get(0).getContext('2d');
  $.ajax({
    url: "/ajax/get/statistic/balance",
    dataType: "json",
    type: "GET",
    delay: 250,
    data: filter,
  }).done(function (jsonData) {
    let labelss = [];
    var money = [];
    var avarages = [];
    var data = $.map(jsonData, function (obj) {
      let name = `${obj.city} - ${obj.title}`;
      labelss.push(name);
      money.push(obj.balance);
      avarages.push(obj.avarage);
    });
    //data = [labels,money];
    var salesGraphChartData = {
      labels: labelss,
      datasets: [
        /*{
          label: "Bevétel",
          fill: false,
          borderWidth: 2,
          lineTension: 0,
          spanGaps: true,
          borderColor: "#efefef",
          pointRadius: 3,
          pointHoverRadius: 7,
          pointColor: "#efefef",
          pointBackgroundColor: "#efefef",
          data: money,
        },*/{
          label: "Átlag",
          fill: true,
          borderWidth: 2,
          lineTension: 0,
          spanGaps: true,
          borderColor: "#ff0000",
          pointRadius: 3,
          pointHoverRadius: 7,
          pointColor: "#ff0000",
          pointBackgroundColor: "#ff0000",
          data: avarages,
        },
      ],
    };
    var salesGraphChartOptions = {
      maintainAspectRatio: false,
      responsive: true,
      legend: {
        display: false,
      },
      scales: {
        xAxes: [
          {
            ticks: {
              fontColor: "#efefef",
            },
            gridLines: {
              display: false,
              color: "#efefef",
              drawBorder: false,
            },
          },
        ],
        yAxes: [
          {
            ticks: {
              stepSize: 5000,
              fontColor: "#efefef",
            },
            gridLines: {
              display: true,
              color: "#efefef",
              drawBorder: false,
            },
          },
        ],
      },
    };
    // This will get the first returned node in the jQuery collection.
    // eslint-disable-next-line no-unused-vars
    
    var salesGraphChart = new Chart(salesGraphChartCanvas, {
      // lgtm[js/unused-local-variable]
      type: "bar",
      data: salesGraphChartData,
      options: salesGraphChartOptions,
    });
    
  });
  //salesGraphChartCanvas.update();
}