// Set new default font family and font color to mimic Bootstrap's default styling
Chart.defaults.global.defaultFontFamily = 'Nunito', '-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif';
Chart.defaults.global.defaultFontColor = '#858796';

function number_format(number, decimals, dec_point, thousands_sep) {
  // *     example: number_format(1234.56, 2, ',', ' ');
  // *     return: '1 234,56'
  number = (number + '').replace(',', '').replace(' ', '');
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function(n, prec) {
      var k = Math.pow(10, prec);
      return '' + Math.round(n * k) / k;
    };
  // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || '';
    s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
}

loadDataHalaman(validasiToken);



function loadDataHalaman(token){
  $(document).ready(function(){
    $.ajax({
      type: 'POST',
      dataType: 'json',
      url: baseURL + '/api/loadcharthalaman',
      data: {
        token : token
      },
      success: function(result){
        if(result.code==0){
          let data = result.data;

          
          var halaman = [];
          let jumlah = [];

          for(o in data){
            halaman[o] = data[o].name_page;
            jumlah[o] = data[o].count;
          }
          // Bar Chart Example
          
          configpagebar =  {
            type: 'bar',
            data: {
              labels: halaman,
              datasets: [{
                label: "Total",
                backgroundColor: "#4e73df",
                hoverBackgroundColor: "#2e59d9",
                borderColor: "#4e73df",
                data: jumlah,
              }],
            },
            options: {
              maintainAspectRatio: false,
              layout: {
                padding: {
                  left: 10,
                  right: 25,
                  top: 25,
                  bottom: 0
                }
              },
              scales: {
                xAxes: [{
                  time: {
                    unit: 'month'
                  },
                  gridLines: {
                    display: false,
                    drawBorder: false
                  },
                  ticks: {
                    maxTicksLimit: 6
                  },
                  maxBarThickness: 25,
                }],
                yAxes: [{
                  ticks: {
                    min: 0,
                    stepSize: 10,
                    maxTicksLimit: 5,
                    padding: 10,
                    // Include a dollar sign in the ticks
                    callback: function(value, index, values) {
                      return '' +  value;//number_format(value);
                    }
                  },
                  gridLines: {
                    color: "rgb(234, 236, 244)",
                    zeroLineColor: "rgb(234, 236, 244)",
                    drawBorder: false,
                    borderDash: [2],
                    zeroLineBorderDash: [2]
                  }
                }],
              },
              legend: {
                display: false
              },
              tooltips: {
                titleMarginBottom: 10,
                titleFontColor: '#6e707e',
                titleFontSize: 14,
                backgroundColor: "rgb(255,255,255)",
                bodyFontColor: "#858796",
                borderColor: '#dddfeb',
                borderWidth: 1,
                xPadding: 15,
                yPadding: 15,
                displayColors: false,
                caretPadding: 10,
                callbacks: {
                  label: function(tooltipItem, chart) {
                    var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
                    return datasetLabel + ': ' + tooltipItem.yLabel;//number_format(tooltipItem.yLabel);
                  }
                }
              },
            }
          }
          var ctx = document.getElementById("myBarChart").getContext("2d");
          window.myBarpage = getNewChart(ctx, configpagebar);

        }else{
          alert(result.info);
        }
      }
    });
  });
}

 
function getNewChart(canvas, configpagebar) {
  return new Chart(canvas, configpagebar);
}


loadselectfirstpage(validasiToken);
function loadselectfirstpage(tokeni){
  option = '';
  $.ajax({
    type  : "post",
    dataType  : "JSON",
    url   : baseURL + "/api/loadcountry",
    data : {
      token : tokeni
    },
    success:function(result){
      let data = result.data;
      option = '';
      option += `<option value=''>All Country</option>`
      for (x in data){  
        option += `<option value = `+data[x]['country']+`>`+data[x]['country']+`</option>`
      }
      $('#selectcountrypage').html(option);
    }
  }); 
 
    optionprov = `<option value=''>All Province</option>`
    $('#selectprovincepage').html(optionprov);
  
    optioncity = `<option value=''>All City</option>`
    $('#selectcitypage').html(optioncity);
  
}

$('#selectcountrypage').change(function(){
  let country = $('#selectcountrypage').val();
  let province =  $('#selectprovincepage').val();
  let city =  $('#selectcitypage').val();
 
  $.ajax({
    type  : "post",
    dataType  : "JSON",
    url   : baseURL + "/api/loadprovince",
    data : {
      token : validasiToken,
      country : country
    },success:function(result){
      let data = result.data;
      optionprov = '';
      optionprov = `<option value=''>All Province</option>`;

      for (x in data){
        optionprov += `<option value = '`+data[x]['province']+`'>`+data[x]['province']+`</option>`
      }
      $('#selectprovincepage').html(optionprov);
    }
  });

  optionprov = `<option value=''>All Province</option>`
  $('#selectprovincepage').html(optionprov);

  optioncity = `<option value=''>All City</option>`
  $('#selectcitypage').html(optioncity);

  changedatapage(country, null, null);

});

$('#selectprovincepage').change(function(){
  let province = $('#selectprovincepage').val();
  let country = $('#selectcountrypage').val();
  let city =  $('#selectcitypage').val();

  $.ajax({
    type  : "post",
    dataType  : "JSON",
    url   : baseURL + "/api/loadcity",
    data : {
      token : validasiToken,
      country : country,
      province : province
    },success:function(result){
      let data = result.data;

      optioncity = '';
      optioncity += `<option value=''>All City</option>`;

      for (x in data){
        optioncity += `<option value = `+data[x]['city']+`>`+data[x]['city']+`</option>`
      }
      $('#selectcitypage').html(optioncity);
    }
  });

  changedatapage(country, province, city);

});


$('#selectcitypage').change(function(){
  let province = $('#selectprovincepage').val();
  let country = $('#selectcountrypage').val();
  let city =  $('#selectcitypage').val();

  changedatapage(country, province, city);

})

function changedatapage(country, province, city){
  $.ajax({
    type  : "post",
    dataType  : "JSON",
    url   : baseURL + "/api/loadpagebylocat",
    data : {
      token : validasiToken,
      country : country,
      province : province,
      city : city
    },success:function(result){
      let data =  result.data;
      // console.log(data);
      let label = [];
      let total = [];
      for(x in data){
        label[x]=data[x]['name_page'];
        total[x]=data[x]['count'];
      }
      configpagenew = {
        labels: label,
        datasets: [{
          label: "Total",
          backgroundColor: "#4e73df",
          hoverBackgroundColor: "#2e59d9",
          borderColor: "#4e73df",
          data: total,
        }],
      };
      myBarpage.data = configpagenew;
      window.myBarpage.update();

    }
  });


}




