$(document).ready(function() {
  var token = document.body.getAttribute('data-token');

  $('#date-start').on('click', function(e) {
    $('#date-end')
      .datepicker('destroy')
      .attr('disabled', true)
      .attr('readonly', true);
    $('#date-end').val('');
    $(this).val('');
  });

  $('#date-start').datepicker({
    dateFormat: 'dd/mm/yy',
    closeText: 'Fechar',
    prevText: '&#x3c;Anterior',
    nextText: 'Pr&oacute;ximo&#x3e;',
    currentText: 'Hoje',
    monthNames: [
      'Janeiro',
      'Fevereiro',
      'Mar&ccedil;o',
      'Abril',
      'Maio',
      'Junho',
      'Julho',
      'Agosto',
      'Setembro',
      'Outubro',
      'Novembro',
      'Dezembro',
    ],
    monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
    dayNames: [
      'Domingo',
      'Segunda-feira',
      'Ter&ccedil;a-feira',
      'Quarta-feira',
      'Quinta-feira',
      'Sexta-feira',
      'Sabado',
    ],
    dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
    dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
    maxDate: 'today',
    onSelect: function(date, inst) {
      $('#date-end').datepicker('destroy');
      var data2 = new Date();
      var data1 = $(this).datepicker('getDate');
      data1.setDate(data1.getDate() + 30);

      $('#date-end')
        .datepicker({
          dateFormat: 'dd/mm/yy',
          closeText: 'Fechar',
          prevText: '&#x3c;Anterior',
          nextText: 'Pr&oacute;ximo&#x3e;',
          currentText: 'Hoje',
          monthNames: [
            'Janeiro',
            'Fevereiro',
            'Mar&ccedil;o',
            'Abril',
            'Maio',
            'Junho',
            'Julho',
            'Agosto',
            'Setembro',
            'Outubro',
            'Novembro',
            'Dezembro',
          ],
          monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
          dayNames: [
            'Domingo',
            'Segunda-feira',
            'Ter&ccedil;a-feira',
            'Quarta-feira',
            'Quinta-feira',
            'Sexta-feira',
            'Sabado',
          ],
          dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
          dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
          maxDate: data1 >= data2 ? 'today' : data1,
          minDate: $(this).datepicker('getDate'),
        })
        .attr('disabled', false)
        .attr('readonly', true);
    },
  });

  function loadOrders(nextOffset = 0){
    var data = {};
    data['filter_date_start'] = $("input[name='filter_date_start']").val();
    data['filter_date_end'] = $("input[name='filter_date_end']").val();
    data['filter_id'] = $("input[name='filter_id']").val();
    data['filter_status'] = $("select[name='filter_status']").val();
    data['offset'] = nextOffset;

    $.ajax({
      url: 'index.php?route=module/shopee/searchorder/searchorderfilter&token=' + token + '',
      type: 'get',
      data: data,
      dataType: 'json',
      beforeSend: function() {
        if (nextOffset == 0) {
          $('body').append(loadBeforeSend());
        } else {
          $('.load-more').addClass('btn-loading');
        }
      },
      complete: function() {
        if (nextOffset == 0) {
          $('.loadBeforeSend').fadeOut();
        } else {
          $('.load-more').removeClass('btn-loading');
        }
      },
      success: function(json) {
        $('.text-error, .success, .warning').remove();
        $('.border-error').removeClass('border-error');

        $('input[name="filter_date_start"], input[name="filter_date_end"]')
          .closest('label')
          .removeClass('field-error');

        if (json['error']) {
          $.each(json['error'], function(index, value) {
            $('input[name=' + index + ']')
              .closest('label')
              .addClass('field-error')
              .after('<span class="text-error text-small">' + value + '</span>');
          });
        }

        if (json['result_error']) {
          var html = '';
          html += '<div class="warning full-width">';
          html += '<span class="visible-inline-block">' + json['result_error'] + '</span>';
          html += '</div>';

          $('.js-header-notifications').append(html);
        }

        if (nextOffset == 0) {
          $('.search-orders').html('');
        }

        document.getElementById('order-list').dataset.nextoffset = (json['hasMore'] ? json['offset'] : 0);


        var html = '';

        if (json['orders']) {
          // html += '<label class="checkbox checkbox-medium left-padding-medium right-margin-medium">';
          // html += '<input class="checkbox-entry js-selected-all" type="checkbox"/>';
          // html += '<span class="checkbox-text">Selecionar Todos</span>';
          // html += '</label>';

          $.each(json['orders'], function(index, value) {
            $.each(value['order_data'], function(ind, val) {
              html +=
                '<div class="row no-space-xs middle-xs top-padding-medium horizontal-padding-medium background-white shadow-small hover:shadow-large bottom-margin-small">';

              if (val['order_href']) {
                html += '<div class="right-margin-small bottom-padding-medium">';
                html += '<label class="checkbox checkbox-medium">';
                html +=
                  '<input class="checkbox-entry" type="checkbox" name="selected[]" value="' +
                  val['order_id'] +
                  '" disabled/>';
                html += '<span class="checkbox-text"></span>';
                html += '</label>';
                html += '</div>';
              } else {
                html += '<div class="right-margin-small bottom-padding-medium">';
                html += '<label class="checkbox checkbox-medium">';
                html +=
                  '<input class="checkbox-entry" type="checkbox" name="selected[]" value="' + val['order_id'] + '" />';
                html += '<span class="checkbox-text"></span>';
                html += '</label>';
                html += '</div>';
              }

              html += '<div class="col-md col-xs">';
              html += '<div class="content-box bottom-padding-medium">';
              html += '<span class="text-small text-dark text-bold">#' + val['order_id'] + '</span>';
              html += '</div>';
              html += '</div>';
              html += '<div class="col-md-3 col-xs-6">';
              html += '<div class="content-box bottom-padding-medium">';
              html += '<span class="text-small text-dark visible-block">' + val['order_status'] + '</span>';
              html += '<span class="text-small text-gray">' + val['order_date_created'] + '</span>';
              html += '</div>';
              html += '</div>';
              html += '<div class="col-md-3 col-xs-6">';
              html += '<div class="content-box bottom-padding-medium">';
              html += '<span class="text-small text-dark">' + value['order_total'] + '</span>';
              html += '</div>';
              html += '</div>';
              html += '<div class="col-md-3 col-xs-12">';
              html += '<div class="content-box flex flex-row bottom-padding-medium pull-right js-search-order-action">';
              if (val['order_href']) {
                html += '<button class="btn-default btn-outline btn-small" data-order="' + val['order_id'] + '">';
                html += '<a class="text-decoration-none" href="' + val['order_href'] + '" target="_Blank">';
                html += '<span class="text-gray">Visualizar pedido</span>';
                html += '</a>';
                html += '</button>';
              } else {
                html +=
                  "<button class='btn-default btn-outline btn-small right-margin-small js-search-order' data-pedido='" +
                  index +
                  "' data-items='" +
                  value['order_items'] +
                  "'>";
                html += '<span>Ver itens</span>';
                html += '</button>';
                html +=
                  '<button class="btn-default btn-primary btn-small js-search-order-download" data-order="' +
                  val['order_id'] +
                  '">';
                html += '<span>Sincronizar</span>';
                html += '</button>';
              }
              html += '</div>';
              html += '</div>';
              html += '</div>';

            });
          });

          json['hasMore'] ? $('.load-more').removeClass('hidden') : $('.load-more').addClass('hidden');

          // if (json['pagination']) {
          //   $('.pagination').append("<div class='js-pagination-search-orders'>" + json['pagination'] + '</div>');
          // }
          $('.js-select-all-container').removeClass('hidden');
        } else {
          $('.js-select-all-container').addClass('hidden');
          html += '<div class="row">';
          html += '<div class="col-xs-12">';
          html +=
            '<div class="content-box background-white shadow-small vertical-padding-x-large horizontal-padding-large text-center">';
          html += '<span class="text-medium text-gray">Nenhum Pedido Encontrado!</span>';
          html += '</div>';
          html += '</div>';
          html += '</div>';
        }

        html += '</div>';

        $('.search-orders').append(html);
        // document.getElementById('order-list').insertAdjacentHTML('afterbegin', html);
      },
      error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
      },
    });
  }

  $(document).on('click', '.js-search-order-filter', function() {
    loadOrders();
  });

  $(document).on('click', '.js-selected-all', function() {
    var checked = this.checked;
    $.each($("input[name*='selected']"), function(index, value) {
      if ($(value).prop('disabled') !== true) {
        $(value).prop('checked', checked);
      }
    });
  });

  $(document).on('click', '.js-search-order', function() {
    $.each($(this).data('items'), function(index, value) {});
    var html = '';
    html += "<div class='js-search-order-items modal'>";
    html += "<div class='modal-content'>";

    html += '<div class="modal-body">';
    html += '<div class="row no-space-xs">';
    html += '<div class="col-xs-12">';
    html += '<button class="btn-default btn-white close-item pull-right padding-small cursor-pointer">';
    html += '<i class="fas fa-times js-modal-close"></i>';
    html += '</button>';
    html += '</div>';

    $.each($(this).data('items'), function(index, value) {
      html += '<div class="col-xs-12">';
      html += '<div class="content-box flex bottom-border-gray middle-xs">';
      html += '<div class="col-md-3 col-xs-12">';
      html += '<span class="text-small text-dark text-bold">#' + value['order_item_id'] + '</span>';
      html += '</div>';
      html += '<div class="col-md col-xs-12">';
      html += '<span class="text-small text-dark">' + value['order_item_title'] + '</span>';
      html += '</div>';
      html += '<div class="col-xs-width-auto">';
      html +=
        '<span class="text-small text-dark" data-tooltip="Quantidade">' + value['order_item_quantity'] + '</span>';
      html += '</div>';
      html += '<div class="col-md-2 col-xs-4">';
      html += '<span class="text-small text-dark">' + value['order_item_unit_price'] + '</span>';
      html += '</div>';
      html += '</div>';
      html += '</div>';
    });

    html += '</div>';
    html += '</div>';

    html += '</div>';
    html += '</div>';

    $('.js-search-order-items').remove();
    $('body').append(html);
  });

  $(document).on('click', '.js-search-order-download, .js-search-order-download-selected', function() {
    $('.success, .warning').remove();

    var data = {};
    data['filter_order_id'] = $(this).hasClass('js-search-order-download-selected')
      ? $('input[name="selected[]"]:checked')
          .map(function() {
            return this.value;
          })
          .get()
          .join(',')
      : $(this).data('order');
    baixarOrder(data);
  });

  function baixarOrder(data) {
    $.ajax({
      url: 'index.php?route=module/shopee/searchorder/searchorderdownload&token=' + token + '',
      type: 'get',
      data: data,
      dataType: 'json',
      beforeSend: function() {
        $('body').append(window.loadBeforeSend());
      },
      complete: function() {
        $('.loadBeforeSend').fadeOut();
      },
      success: function(json) {
        if (json['warning']) {
          notificationMsg(json['warning'], 'warning');
          if (json['warning_item']) {
            $.each(json['warning_item'], function(index, value) {
              $('.search-orders')
                .find('[data-order="' + index + '"]')
                .closest('.row')
                .addClass('border-error')
                .append(
                  '<div class="col-xs-12">' +
                    '<div class="content-box padding-small top-border-error left-border-error right-border-error background-error">' +
                    '<span class="text-error text-small">' +
                    value +
                    '</span>' +
                    '</div>' +
                    '</div>'
                );
            });
          }
        }

        if (json['success']) {
          notificationMsg(json['success'], 'success');
          if (json['order_href']) {
            $.each(json['order_href'], function(index, value) {
              $('.search-orders')
                .find('[data-order="' + index + '"]')
                .closest('.js-search-order-action')
                .empty()
                .html(
                  "<button class='btn-default btn-outline btn-small'>" +
                    "  <a class='text-decoration-none' href='" +
                    value +
                    "' target='_Blank'>" +
                    "    <span class='text-gray'>Visualizar pedido</span>" +
                    '  </a>' +
                    '</button>'
                );
            });
          }
        }
      },
      error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
      }
    });
  }

  $(document).on('click', '.js-modal-close', function() {
    event.preventDefault();
    $('body').css('overflow', 'auto');
    $(this)
      .closest('.modal')
      .remove();
  });

  $(document).on('click', '.modal', function() {
    var element = $(event.target);
    if (element.hasClass('modal')) {
      $('body').css('overflow', 'auto');
      $(this).remove();
    }
  });

  // $(window).on('scroll',function(){
  //   var nextOffset = document.getElementById('order-list').dataset.nextoffset;
  //   if(($(window).scrollTop() == $(document).height() - $(window).height()) && (nextOffset != 0)){
  //     document.getElementById('order-list').dataset.nextoffset = '0';
  //     console.log('teste loader');
  //     loadOrders(nextOffset);
  //   }
  // });

  $(document).on('click', '.load-more', function() {
    var nextOffset = document.getElementById('order-list').dataset.nextoffset;
    if(nextOffset != 0){
      document.getElementById('order-list').dataset.nextoffset = '0';
      loadOrders(nextOffset);
    }
  });
});
