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

  $(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_name'] = $("input[name='filter_name']").val();
    data['page'] = typeof $(this).data('page') == 'undefined' ? 1 : $(this).data('page');

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

        if (json['error']) {
          $.each(json['error'], function(index, value) {
            $('input[name=' + index + ']')
              .closest('label')
              .addClass('field-error');
          });
        }

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

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

        var html = '';

        if (json['orders']) {
          html += '<div class="content-box tablesearchml">';
          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 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 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-width-auto col-xs-12">';
              html += '<div class="content-box flex flex-row bottom-padding-medium 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>';
            });
          });

          if (json['pagination']) {
            $('.pagination').append("<div class='js-pagination-sarch-orders'>" + json['pagination'] + '</div>');
          }
        } else {
          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);
      },
      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'>";

    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-md-2 col-xs-4">';
      html +=
        '<span class="text-small text-dark" data-tooltip="Tipo de Anúncio">' +
        value['order_item_listing_type_id'] +
        '</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/mercadolivre/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) {
              $('.tablesearchml')
                .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) {
              $('.tablesearchml')
                .find('[data-order="' + index + '"]')
                .closest('.js-search-order-action')
                .empty()
                .html(
                  "<button class='btn-default btn-outline btn-small'>" +
                    "  <a href='" +
                    value +
                    "' target='_Blank'>" +
                    "    <span class='text-gray'>Visualizar pedido</span>" +
                    '  </a>' +
                    '</button>'
                );
            });
          }
        }
      },
    });
  }

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