$(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').myDatePicker({
    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').myDatePicker({
        maxDate: data1 >= data2 ? 'today' : data1,
        minDate: $(this).datepicker('getDate'),
      });
      $('#date-end').attr('disabled', false);
      $('#date-end').attr('readonly', true);
    },
  });

  $(document).on('click', '.js-search-order-filter', function() {
    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['page'] = typeof $(this).data('page') == 'undefined' ? 1 : $(this).data('page');

    $.ajax({
      url: 'index.php?route=module/skyhub/searchorder/searchorderfilter&token=' + token,
      type: 'get',
      data: data,
      dataType: 'json',
      beforeSend: function() {
        $('body').append(loadBeforeSend());
      },
      complete: function() {
        $('.loadBeforeSend').fadeOut();
      },
      success: function(json) {
        $('.text-error, .tablesearchskyhub, .js-pagination-search-orders, .success, .warning').remove();
        $('.border-error').removeClass('border-error');

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

        $('.search-orders').html('');

        var html = '';

        var orderFound = false;
        if (json['orders']) {
          orderFound = Object.keys(json['orders']).length > 0;
        }

        if (orderFound) {
          html += '<div class="tablesearchskyhub">';

          html += '<label class="checkbox checkbox-large horizontal-padding-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="background-white shadow-small hover:shadow-large bottom-margin-small">';
              html += '<div class="row no-space-xs middle-xs">';

              html += '<div class="col-xs-12 col-md">';
              html += '<div class="content-box padding-medium">';
              if (val['order_href']) {
                html += '<span class="text-medium text-bold text-dark">#' + val['order_id'] + '</span>';
              } else {
                html += '<label class="checkbox">';
                html +=
                  '<input class="checkbox-entry" type="checkbox" name="selected[]" value="' + val['order_id'] + '" />';
                html += '<span class="checkbox-text text-bold">#' + val['order_id'] + '</span>';
                html += '</label>';
              }
              html += '</div>';
              html += '</div>';

              html += '<div class="col-xs-6 col-md">';
              html += '<div class="content-box padding-medium">';
              html += '<span class="text-small text-dark visible-block">' + val['order_buyer_name'] + '</span>';
              html += '</div>';
              html += '</div>';

              html += '<div class="col-xs-6 col-md-2">';
              html += '<div class="content-box 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-xs">';
              html += '<div class="content-box padding-medium">';
              html += '<span class="text-small text-dark">' + value['order_total'] + '</span>';
              html += '</div>';
              html += '</div>';

              html += '<div class="col-xs-width-auto">';
              html += '<div class="content-box padding-medium">';
              html += '<img src="' + val['order_img'] + '" alt="">';
              html += '</div>';
              html += '</div>';

              html += '<div class="col-xs-width-auto">';
              html += '<div class="content-box padding-medium flex flex-row js-search-order-action">';
              if (val['order_href']) {
                html +=
                  '<a class="btn-default btn-outline btn-small" data-order="' +
                  val['order_id'] +
                  '" href="' +
                  val['order_href'] +
                  '" target="_Blank">';
                html += '<span>Visualizar pedido</span>';
                html += '</a>';
              } 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 += '<div data-tooltip="Baixar pedido">';
                html +=
                  '<button class="btn-default btn-primary btn-small js-search-order-download" data-order="' +
                  val['order_id'] +
                  '">';
                html += '<i class="fas fa-cloud-download-alt"></i>';
                html += '</button>';
                html += '</div>';
              }
              html += '</div>';
              html += '</div>';

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

          html += '</div>';
        } else {
          html +=
            '<div class="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>';
        }

        $('.search-orders').append(html);

        if (json['pagination']) {
          $('.pagination').append("<div class='js-pagination-search-orders'>" + json['pagination'] + '</div>');
        }
      },
      error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
      },
    });
  });

  $(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 background-white border-gray'>";

    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>';

    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-3">';
    html += '<span class="text-small text-dark text-bold">ID</span>';
    html += '</div>';
    html += '<div class="col-md col-xs">';
    html += '<span class="text-small text-dark text-bold">Produto</span>';
    html += '</div>';
    html += '<div class="col-xs-width-auto">';
    html += '<span class="text-small text-dark text-bold">Qtde</span>';
    html += '</div>';
    html += '<div class="col-md-2 col-xs-2">';
    html += '<span class="text-small text-dark text-bold">Valor</span>';
    html += '</div>';

    html += '</div>';
    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-3">';
      html += '<span class="text-small text-dark text-bold">#' + value['order_item_id'] + '</span>';
      html += '</div>';
      html += '<div class="col-md col-xs">';
      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">' + value['order_item_quantity'] + '</span>';
      html += '</div>';
      html += '<div class="col-md-2 col-xs-2">';
      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/skyhub/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']) {
          $('.js-header-notifications').after(
            '<div class="warning full-width"><span>' + json['warning'] + '</span></div>'
          );
          if (json['warning_item']) {
            $.each(json['warning_item'], function(index, value) {
              $('.tablesearchskyhub')
                .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']) {
          $('.js-header-notifications').after('<div class="success"><span>' + json['success'] + '</span></div>');
          if (json['order_href']) {
            $.each(json['order_href'], function(index, value) {
              $('.tablesearchskyhub')
                .find('[data-order="' + index + '"]')
                .closest('.js-search-order-action')
                .empty()
                .html(
                  '<a href="' +
                    value +
                    '" target="_Blank" class="btn-default btn-outline btn-small"><span>Visualizar pedido</span></a>'
                );
            });
          }

          $.each($("input[name*='selected']"), function(index, value) {
            $(value).prop('checked', false);
          });
        }
      },
    });
  }

  $(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();
    }
  });
});
