var _features;
featureSet();
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
    )
  );
};
(function() {
  var days = ['V','H','K','Sze','Cs','P','Szo'];

  var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

  Date.prototype.getMonthName = function() {
      return months[ this.getMonth() ];
  };
  Date.prototype.getDayName = function() {
      return days[ this.getDay() ];
  };
})();

function loadTable(filter) {
  console.log(filter);
  $.ajax({
    url: "/ajax/get/cashflow/day",
    dataType: "json",
    type: "GET",
    delay: 250,
    data: filter,
  }).done(function (jsonData) {
    var sumRevenue = 0;
    var sumCost = 0;
    jsonData.forEach((e) => {
      //console.log(e);
      e.date = new Date(Date.parse(e.date) + 2 * 3600 * 1000);
      var m = e.date;
      var dateString =
        m.getFullYear() +
        "-" +(m.getMonth()<10?'0':'') +
        (m.getMonth() + 1) +
        "-" +(m.getDate()<10?'0':'') +
        m.getDate() +
        " " +(m.getHours()<10?'0':'') +
        m.getHours() +
        ":" +(m.getMinutes()<10?'0':'') +
        m.getMinutes();
      e.date = dateString;
      //console.log(m);
      sumRevenue += parseInt(e.revenue);
      sumCost -= e.cost;
    });
    $("#machineRevenue").html(sumRevenue + " Ft");
    $("#machineCost").html(sumCost + " Ft");
    $("#jsGrid1").jsGrid({
      width: "100%",
      height: "400px",
      readonly: true,
      sorting: true,
      paging: true,
      pageSize: 50,
      data: jsonData,
      fields: [
        { name: "date", type: "text", width: 100, title: "Időpont" },
        { name: "revenue", type: "number", width: 75, title: "Bevétel" },
        { name: "cost", type: "number", width: 75, title: "Kiadás" },
        //{ name: "cashout", type: "checkbox", title: "Kiadás?" },
      ],
    });
  });
  loadTable2(filter);
  loadGraph(filter);
  loadGraph2(filter);
  loadGraph3(filter);
}
function loadTable2(filter) {
  $.ajax({
    url: "/ajax/get/features/log",
    dataType: "json",
    type: "GET",
    delay: 250,
    data: filter,
  }).done(function (jsonData) {
    //console.log(jsonData);
    let customerCount = 0;
    let customerTemp = Date.parse("2019-07-18 15:43:48");
    //customerTemp
      $.each(jsonData,function(i,v){
        let date = Date.parse(v.date);
        if((customerTemp+(5*60*1000))<date){
          //console.log("CT: "+customerTemp+ " NT: "+(date)+ " OT: "+date);
          customerCount++;
        }
        customerTemp = date;
      });
      //console.log("vásárlók: " + customerCount);
    $("#jsGrid2").jsGrid({
      width: "100%",
      height: "400px",
      readonly: true,
      sorting: true,
      paging: true,
      pageSize: 50,
      data: jsonData,
      fields: [
        { name: "date", type: "text", width: 100, title: "Időpont" },
        { name: "featureName", type: "number", width: 75, title: "Szolgáltatás" },
        { name: "measured", type: "number", width: 75, title: "Mért" },
        { name: "featurePrice", type: "number", title: "Kalk ár" },
        //{ name: "createdAt", type: "number", title: "DEV!Created" },
        { name: "istest", type: "checkbox", title: "Test?" },
      ],
    });
  });
}
function featureSet() {
  $.ajax({
    url: "/ajax/get/features",
    dataType: "json",
    type: "GET",
    delay: 250,
    success:function(jsonData){
      let features = $.map(jsonData, function (obj) {
        console.log(obj);
        let date = `${obj.year}-${obj.month}-${obj.day}`;
        //features.push({id:obj.id,name:obj.name});
        obj2 = new Object({name:obj.name,id:obj.id,unit:obj.unit});
        return obj2;
      });
      _features = features;
    }
  });
  console.log(_features);
};

$(".datepicker").daterangepicker({
  singleDatePicker: true,
  firstDay: 1,
  locale: {
    format: "YYYY-MM-DD",
    separator: " - ",
    applyLabel: "Mentés",
    cancelLabel: "Mégse",
    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",
    ],
  },
});
$("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({ id: _id, year: date.getFullYear() });
      break;
    case "month":
      loadTable({
        id: _id,
        year: date.getFullYear(),
        month: date.getMonth() + 1,
      });
      break;
    case "week":
      loadTable({ id: _id, year: date.getFullYear(), week: date.getWeek() });
      break;
    case "day":
      loadTable({
        id: _id,
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        day: date.getDate(),
      });
      break;
  }
});

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/cashflow/month",
    dataType: "json",
    type: "GET",
    delay: 250,
    data: filter,
  }).done(function (jsonData) {
    let labelss = [];
    var money = [];
    var data = $.map(jsonData, function (obj) {
      var tdate = new Date(`${obj.year}-${obj.month}-${obj.day}`);
      tdate = tdate.getDayName();
      let date = `${obj.year}-${obj.month}-${obj.day} ${tdate}`;
      labelss.push(date);
      money.push(obj.balance);
    });
    //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,
        },
      ],
    };
    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();
}
function loadGraph2(filter) {
  //console.log("teszt");
  // Sales graph chart
  $("#line-chart2").remove();
  $(".card-body.line-Chart2").append(
    `<canvas class="chart chartjs-render-monitor" id="line-chart2" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%; display: block; width: 674px;" width="674" height="250"></canvas>`
  );
  var salesGraphChartCanvas = $("#line-chart2").get(0).getContext("2d");
  //$('#revenue-chart').get(0).getContext('2d');
  //console.log(filter);
  $.ajax({
    url: "/ajax/get/features/day",
    dataType: "json",
    type: "GET",
    delay: 250,
    data: filter,
  }).done(function (jsonData) {
    let labelss = [];
    var money = [];
    var measured = [];
    var data = $.map(jsonData, function (obj) {
      //console.log(obj);
      let label = obj.featureName;
      labelss.push(label);
      money.push(obj.balance);
      measured.push(obj.measured);
    });
    //console.log(labelss);
    /*datas = new Object;*/
    datas = [money, measured];
    //console.log(datas);
    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: datas[0],
        },
      ],
    };

    var salesGraphChartOptions = {
      maintainAspectRatio: true,
      responsive: true,
      legend: {
        display: false,
      },
      scales: {
        xAxes: [
          {
            ticks: {
              fontColor: "#efefef",
            },
            gridLines: {
              display: false,
              color: "#efefef",
              drawBorder: false,
            },
          },
        ],
        yAxes: [
          {
            ticks: {
              stepSize: 100,
              fontColor: "#efefef",
              beginAtZero: true
            },
            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,
    });
  });
  loadGraph3(filter);
  //salesGraphChartCanvas.update();
}
function loadGraph3(filter) {
  //console.log("teszt");
  // Sales graph chart
  $("#line-chart3").remove();
  $(".card-body.line-Chart3").append(
    `<canvas class="chart chartjs-render-monitor" id="line-chart3" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%; display: block; width: 674px;" width="674" height="250"></canvas>`
  );
  var salesGraphChartCanvas = $("#line-chart3").get(0).getContext("2d");
  //$('#revenue-chart').get(0).getContext('2d');
  console.log(filter);
  $.ajax({
    url: "/ajax/get/features/day",
    dataType: "json",
    type: "GET",
    delay: 250,
    data: filter,
  }).done(function (jsonData) {
    let labelss = [];
    var money = [];
    var measured = [];
    var data = $.map(jsonData, function (obj) {
      //console.log(filter);
      let label = obj.featureName;
      let divider = (obj.featureUnit=="min"?60:1);
      labelss.push(label);
      measured.push(obj.measured/divider);
    });

    /*datas = new Object;*/
    datas = [money, measured];
    var salesGraphChartData = {
      labels: labelss,
      datasets: [
        {
          label: "Használat",
          fill: false,
          borderWidth: 2,
          lineTension: 0,
          spanGaps: true,
          borderColor: "#dfdfdf",
          pointRadius: 3,
          pointHoverRadius: 7,
          pointColor: "#dfdfdf",
          pointBackgroundColor: "#dfdfdf",
          data: datas[1],
        },
      ],
    };

    var salesGraphChartOptions = {
      maintainAspectRatio: false,
      responsive: true,
      legend: {
        display: false,
      },
      scales: {
        xAxes: [
          {
            ticks: {
              fontColor: "#efefef",
            },
            gridLines: {
              display: false,
              color: "#efefef",
              drawBorder: false,
            },
          },
        ],
        yAxes: [
          {
            ticks: {
              stepSize: 10,
              fontColor: "#efefef",
              beginAtZero: true
            },
            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();
}
