import {getPaletteColor} from '../../../assets/js/palette-colors.js';

$( document ).ready(function() {
  var token = $('body').data('token');
  var info  = $('[data-home-info]').data('home-info');


    function getCustomersOnline(){
    $.ajax({
        url: 'index.php?route=common/home/updateDashboard&token=' + token,
        // type: 'get',
    })
    .done(function(json){
      $('.js-total-order').html(json['total_order']);
      $('.js-total-order-year').html(json['total_order_year']);

      $('.js-total-sale').html(json['total_sale']);
      $('.js-total-sale-year').html(json['total_sale_year']);

      $('.js-average-sale').html(json['average_sale']);
      $('.js-text-last-12-months').html(json['text_last_12_months']);

      $('.js-total-product').html(json['total_product']);
      $('.js-total-product-year').html(json['total_product_year']);

      $('.js-total-customer').html(json['total_customer']);
      $('.js-total-customer-year').text(json['total_customer_year']);

      $('.js-customer-online').html(json['total_customer_online']);
      $('.js-customers-online-last-refresh').html(json['customers_online_last_refresh']);
    })
    .fail(function() {

      // notificationMsg('Erro ao recarregar as informações.', 'error');
    })
  }

  $('#refresh-users-online').on('click', function(e){
      // e.preventDefault();
      // e.stopPropagation();     
      getCustomersOnline();
  });



  $('body').on('change', '.js-status-proccess', function(){

    var url = 'index.php?route=common/home/last_sales_order&token=' + token;
    var proccess_status = $(this).val();
    if (proccess_status != '*') {
      url += '&proccess_status=' + encodeURIComponent(proccess_status);
    }

    document.getElementById('loading').classList.remove('hidden');

    $.ajax({
      url : url,
      type: 'get',
      dataType: 'html',
    })
    .done(function(html) {
      $('.js-sales-order').empty().append(html);
    })
    .fail(function() {
       console.log("error");
    })
    .always(function() {
      console.log("complete");
    });

  });

  function getSalesChartDevice(range) {
    $.ajax({
      url : 'index.php?route=common/home/chartDevice&token=' + token + '&range=' + range,
      type: 'get',
      dataType: 'json',
      async: false
    })
    .done(function(json) {
      $('#myChartDevice').remove();
      $('.js-my-chart-device').append('<canvas id="myChartDevice" width="400" height="220"></canvas>');
      var
      ctx = document.getElementById("myChartDevice"),
      myChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: json.xaxis,
          datasets: [{
            label: json['label_desktop'],
            backgroundColor: "rgba(42,110,160,0.2)",
            borderColor: "rgba(42,110,160,1)",
            pointBackgroundColor: "rgba(42,110,160,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(42,110,160,1)",
            data: json.desktop
          }, {
            label: json['label_tablet'],
            backgroundColor: "rgba(245,131,39,0.2)",
            borderColor: "rgba(245,131,39,1)",
            pointBackgroundColor: "rgba(245,131,39,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(245,131,39,1)",
            data: json.tablet
          }, {
            label: json['label_mobile'],
            backgroundColor: "rgba(50,131,39,0.2)",
            borderColor: "rgba(50,131,39,1)",
            pointBackgroundColor: "rgba(50,131,39,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(50,131,39,1)",
            data: json.mobile
          }]
        },
        options: {
          elements: {
            line: {
              tension: 0 // disables bezier curves
            }
          },
          legend: {
            position: 'bottom'
          },
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        }
      });
    })
    .fail(function() {
      // console.log("error");
    })
    .always(function() {
      // console.log("complete");
    });
  }

  function getSalesChart(range) {
    $.ajax({
      url: 'index.php?route=common/home/chart&token=' + token + '&range=' + range,
      type: 'get',
      dataType: 'json',
      async: false
    })
    .done(function(json) {
      $('#myChart').remove();
      $('.js-my-chart').append('<canvas id="myChart" width="400" height="220"></canvas>');
      var ctx = document.getElementById("myChart"),
      myChart = new Chart(ctx, {
        type: 'line',
        data: {
          labels: json.xaxis,
          datasets: [{
            label: json['label_order'],
            backgroundColor: "rgba(42,110,160,0.2)",
            borderColor: "rgba(42,110,160,1)",
            pointBackgroundColor: "rgba(42,110,160,1)",
            pointBorderColor: "#fff",
            pointHoverBackgroundColor: "#fff",
            pointHoverBorderColor: "rgba(42,110,160,1)",
            data: json.order
          }]
        },
        options: {
          elements: {
            line: {
              tension: 0 // disables bezier curves
            }
          },
          legend: {
            position: 'bottom'
          },
          scales: {
            yAxes: [{
              ticks: {
                beginAtZero: true
              }
            }]
          }
        },
      });
    })
    .fail(function() {
      // console.log("error");
    })
    .always(function() {
      // console.log("complete");
    });
  }

    function getSalesChartMarketplace(range) {
      if (info.marketplace_status == "") {
            return false;
        }

        $.ajax({
            url: 'index.php?route=common/home/chartMarketplace&token=' + token + '&range=' + range,
            type: 'get',
            dataType: 'json',
            async: false
        })
            .done(function(json) {
                $('#myChartMarketplace').remove();
                $('.js-my-chart-marketplace').append('<canvas id="myChartMarketplace" width="400" height="220"></canvas>');

                var dataArray = [];

                for (var x=1; x < Object.keys(json).length; x++) {
                    dataArray.push({
                        label: json[x].label,
                        backgroundColor: getPaletteColor(x, 0.2),
                        borderColor: getPaletteColor(x),
                        pointBackgroundColor: getPaletteColor(x),
                        pointBorderColor: "#fff",
                        pointHoverBackgroundColor: "#fff",
                        pointHoverBorderColor: getPaletteColor(x),
                        data: json[x].data
                    })
                }

                var
                    ctx = document.getElementById("myChartMarketplace"),
                    myChart = new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels: json.xaxis,
                            datasets: dataArray
                        },
                        options: {
                            elements: {
                                line: {
                                    tension: 0 // disables bezier curves
                                }
                            },
                            legend: {
                                position: 'bottom'
                            },
                            scales: {
                                yAxes: [{
                                    ticks: {
                                        beginAtZero: true
                                    }
                                }]
                            }
                        },
                    });
            })
            .fail(function(xhr, status, error, json) {
                console.log(xhr.responseText);
                console.log(status);
                console.log(error);
            })
            .always(function() {
                // console.log("complete");
            });
    }

    function getSalesChartSalesChannel(range) {
        if (info.marketplace_status == "" && info.app_status == 0) {
            return false;
        }

        $.ajax({
            url: 'index.php?route=common/home/chartSalesChannel&token=' + token + '&range=' + range,
            type: 'get',
            dataType: 'json',
            async: false
        })
            .done(function(json) {
                $('#myChartSalesChannel').remove();
                $('.js-my-chart-sales-channel').append('<canvas id="myChartSalesChannel" width="400" height="220"></canvas>');

                var dataArray = [];

                for (var x=1; x < Object.keys(json).length; x++) {
                    dataArray.push({
                        label: json[x].label,
                        backgroundColor: getPaletteColor(x, 0.2),
                        borderColor: getPaletteColor(x),
                        pointBackgroundColor: getPaletteColor(x),
                        pointBorderColor: "#fff",
                        pointHoverBackgroundColor: "#fff",
                        pointHoverBorderColor: getPaletteColor(x) ,
                        data: json[x].data
                    })
                }

                var
                    ctx = document.getElementById("myChartSalesChannel"),
                    myChart = new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels: json.xaxis,
                            datasets: dataArray
                        },
                        options: {
                            elements: {
                                line: {
                                    tension: 0 // disables bezier curves
                                }
                            },
                            legend: {
                                position: 'bottom'
                            },
                            scales: {
                                yAxes: [{
                                    ticks: {
                                        beginAtZero: true
                                    }
                                }]
                            }
                        },
                    });
            })
            .fail(function(xhr, status, error, json) {
                console.log(xhr.responseText);
                console.log(status);
                console.log(error);
            })
            .always(function() {
                // console.log("complete");
            });
    }


  function easyconfigure() {
    $.ajax({
      url: 'index.php?route=extension/easyconfigure&token=' + token,
      type: 'post',
      dataType: 'html',
    })
    .done(function(json) {
      $('body').append(json);
    })
    .fail(function(json) {
      console.log("error");
    });
  }

  $('input[name=range]').on('change', function(event) {
    event.preventDefault();
    getSalesChart($(this).val());
    getSalesChartDevice($(this).val());
    getSalesChartMarketplace($(this).val());
    getSalesChartSalesChannel($(this).val());
  });
  getSalesChart($('input[name=range]').val());
  getSalesChartDevice($('input[name=range]').val());
  getSalesChartMarketplace($('input[name=range]').val());
  getSalesChartSalesChannel($('input[name=range]').val());

  // Configuração rápida
  if ($('.js-quick-config').length > 0) {
    easyconfigure();
  }
  $('.js-setup').on('click', function(event) { // Configbar
    event.preventDefault();
    easyconfigure();
  });

  $('.ads-banner').on('click', '.js-ads-close', function(event) {
    event.preventDefault();
    $('.js-ads-close-confirm').removeClass('hidden');
  });
  $('.ads-banner').on('click', '.js-ads-cancel', function(event) {
    event.preventDefault();
    $('.js-ads-close-confirm').addClass('hidden');
  });

  $('.ads-banner').on('click', '.js-ads-remove', function(event) {

    var data = {};
        data['promotion_id'] = (typeof $('.js-ads-remove').data('promotion-id') != "undefined") ? $('.js-ads-remove').data('promotion-id') : false ;

    $.ajax({
      url: 'index.php?route=common/adsbanner/remove&token=' + token,
			type: 'post',
      data: data,
      dataType: 'json',
      beforeSend:function(){
        $('.js-ads-remove').addClass('btn-loading').attr('disabled', true);
      },
      complete:function(){
        $('.js-ads-remove').removeClass('btn-loading').attr('disabled', false);
      }
    }).done(function(json) {
      if(json['success']){
        location.reload();
      }
    });

    event.preventDefault();
  });

  $.ajax({
    url: 'index.php?route=common/adsbanner&token=' + token,
    dataType:'html'
  }).done(function(html) {
    if(html){
      $('.ads-banner').append(html);
    }
  });


});
