$(document).ready(function() {
  window.language.load('sale/order');

  var token = $('body').data('token'),
    info = $('[data-info]').data('info');

  $('.js-filter-accordion').accordionFutura({
    onlyOneActive: false, // True: Abre um e fecha os outros elementos
  });

  $('.js-order-mkt').on('click', function() {
    $('.success, .warning').remove();

    $.ajax({
      url: 'index.php?route=sale/order/syncronizedOrderMkt&token=' + token,
      dataType: 'json',
      beforeSend: function() {
        $('.js-order-mkt')
          .addClass('text-gray')
          .css('pointer-events', 'none');
        $('.js-refresh')
          .removeClass('hidden')
          .addClass('rotate');
      },
      complete: function() {
        $('.js-order-mkt')
          .removeClass('text-gray')
          .removeAttr('style');
        $('.js-refresh')
          .removeClass('rotate')
          .addClass('hidden');
      },
      success: function(json) {
        if (json['error']) {
          $('.js-header-notifications').append(
            '<div class="warning full-width">' +
              '<span class="visible-inline-block">Nenhum pedido esta disponível para sincronia</span>' +
              '<span class="js-toggle-original-error visible-block text-small cursor-pointer text-primary">Ver original</span>' +
              '<span class="hidden">' +
              json['error'] +
              '</span></div>'
          );
        } else {
          if (json['total'] > 0 || json['total_error'] > 0) {
            location.reload();
          } else {
            $('.js-header-notifications').append(
              '<div class="warning full-width">Nenhum pedido esta disponível para sincronia</div>'
            );
          }
        }
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
      },
    });
  });

  function calendarField() {
    $('.date').datepicker({
      changeMonth: true,
      changeYear: true,
      closeText: 'Fechar',
      prevText: '&#x3c;Anterior',
      nextText: 'Pr&oacute;ximo&#x3e;',
      currentText: 'Hoje',
      maxDate: 0,
      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'],
      weekHeader: 'Sm',
      firstDay: 0,
      isRTL: false,
      showMonthAfterYear: false,
      yearSuffix: '',
      dateFormat: 'dd/mm/yy',
      minDate: new Date(1990, 1 - 1, 1),
      onSelect: function(date) {
        $('#validade').datepicker({
          changeMonth: true,
          changeYear: true,
          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'],
          weekHeader: 'Sm',
          firstDay: 0,
          isRTL: false,
          showMonthAfterYear: false,
          yearSuffix: '',
          dateFormat: 'dd/mm/yy',
        });
      },
    });
  }
  calendarField();

  function filter() {
    url = 'index.php?route=sale/order&token=' + token;

    var filter_order_id = $("input[name='filter_order_id']").attr('value');
    if (filter_order_id) {
      url += '&filter_order_id=' + encodeURIComponent(filter_order_id);
    }

    var filter_customer = $("input[name='filter_customer']").attr('value');
    if (filter_customer) {
      url += '&filter_customer=' + encodeURIComponent(filter_customer);
    }

    var filter_order_status_id = $("select[name='filter_order_status_id']").attr('value');
    if (filter_order_status_id != '*') {
      url += '&filter_order_status_id=' + encodeURIComponent(filter_order_status_id);
    }

    var filter_order_payment_method = $("select[name='filter_order_payment_method']").attr('value');
    if (filter_order_payment_method != '*') {
      url += '&filter_order_payment_method=' + encodeURIComponent(filter_order_payment_method);
    }

    var filter_order_shipping_method = $("select[name='filter_order_shipping_method']").attr('value');
    if (filter_order_shipping_method != '*') {
      url += '&filter_order_shipping_method=' + encodeURIComponent(filter_order_shipping_method);
    }

    var filter_total = $("input[name='filter_total']").attr('value');
    if (filter_total) {
      url += '&filter_total=' + encodeURIComponent(filter_total);
      var filter_content_total = $("select[name='filter_content_total']").attr('value');
      if (filter_content_total) {
        url += '&filter_content_total=' + encodeURIComponent(filter_content_total);
      }
    }

    var filter_subtotal = $("input[name='filter_subtotal']").attr('value');
    if (filter_subtotal) {
      url += '&filter_subtotal=' + encodeURIComponent(filter_subtotal);
      var filter_content_subtotal = $("select[name='filter_content_subtotal']").attr('value');
      if (filter_content_subtotal) {
        url += '&filter_content_subtotal=' + encodeURIComponent(filter_content_subtotal);
      }
    }

    var filter_date_added = $("input[name='filter_date_added']").attr('value');
    if (filter_date_added) {
      url += '&filter_date_added=' + encodeURIComponent(filter_date_added);
    }

    var filter_date_modified = $("input[name='filter_date_modified']").attr('value');
    if (filter_date_modified) {
      url += '&filter_date_modified=' + encodeURIComponent(filter_date_modified);
    }

    var filter_mkt_order_id = $("input[name='filter_mkt_order_id']").attr('value');
    if (filter_mkt_order_id) {
      url += '&filter_mkt_order_id=' + encodeURIComponent(filter_mkt_order_id);
    }

    var filter_lp = $("input[name='filter_lp']:checked").attr('value');
    if (filter_lp) {
      url += '&filter_lp=' + encodeURIComponent(filter_lp);
    }

    var filter_origem_pedido = $("select[name='filter_origem_pedido']").attr('value');
    if (filter_origem_pedido != '*') {
      url += '&filter_origem_pedido=' + encodeURIComponent(filter_origem_pedido);
    }

    var filter_integracao = $("select[name='filter_integracao']").attr('value') || '*';
    if (filter_integracao != '*') {
      url += '&filter_integracao=' + encodeURIComponent(filter_integracao);
    }

    var filter_marketplace = $("select[name='filter_marketplace']").attr('value') || '*';
    if (filter_marketplace != '*') {
      url += '&filter_marketplace=' + encodeURIComponent(filter_marketplace);
    }

    location = url;
  }

  $('.js-filter').on('submit', function(event) {
    event.preventDefault();
    filter();
  });

  $.widget('custom.catcomplete', $.ui.autocomplete, {
    _renderMenu: function(ul, items) {
      var self = this,
        currentCategory = '';
      $.each(items, function(index, item) {
        if (item.category != currentCategory) {
          ul.append('<li class="ui-autocomplete-category">' + item.category + '</li>');
          currentCategory = item.category;
        }
        self._renderItem(ul, item);
      });
    },
  });

  $("input[name='filter_customer']").catcomplete({
    delay: 500,
    source: function(request, response) {
      $.ajax({
        url:
          'index.php?route=sale/customer/autocomplete&token=' +
          token +
          '&filter_name=' +
          encodeURIComponent(request.term),
        dataType: 'json',
        success: function(json) {
          response(
            $.map(json, function(item) {
              return {
                category: item.customer_group,
                label: item.name,
                value: item.customer_id,
              };
            })
          );
        },
      });
    },
    select: function(event, ui) {
      $("input[name='filter_customer']").val(ui.item.label);
      return false;
    },
    focus: function(event, ui) {
      return false;
    },
  });

  /*
  ================================================================================
  ================================================================================
  ================================================================================
  ================================== Order info ==================================
  ================================================================================
  ================================================================================
  ================================================================================
  */

  function getOrderInfo() {
    return JSON.parse($('[data-order-info]').data('order-info'));
  }

  if ($('[data-order-info]').length > 0) {
    var orderInfo = getOrderInfo();
    var tabAntiFraude = document.getElementById('tab-info').querySelector('[data-tab-control="tab-info-6"]');

    const PAYMENT_ADDRESS_INFO = $('[data-payment-address]').data('payment-address'),
      PAYMENT_ADDRESS = String(PAYMENT_ADDRESS_INFO).replace(/\s/g, '+');

    $('.payment-map').html(
      "<iframe src='https://maps.google.com/maps?q=" +
        PAYMENT_ADDRESS +
        "&hl=es;z=14&amp;output=embed' width='400' height='500' frameborder='0' style='border:0; width:100%;' allowfullscreen></iframe>"
    );

    const SHIPPING_ADDRESS_INFO = $('[data-shipping-address]').data('shipping-address'),
      SHIPPING_ADDRESS = String(SHIPPING_ADDRESS_INFO).replace(/\s/g, '+');

    $('.shipping-map').html(
      "<iframe src='https://www.google.com/maps?q=" +
        SHIPPING_ADDRESS +
        "&hl=es;z=14&amp;output=embed' width='400' height='500' frameborder='0' style='border:0; width:100%;' allowfullscreen></iframe>"
    );

    const PICKUP_ADDRESS_INFO = $('[data-pickup-address]').data('pickup-address'),
      PICKUP_ADDRESS = String(PICKUP_ADDRESS_INFO).replace(/\s/g, '+');

    $('.pickup-map').html(
      "<iframe src='https://www.google.com/maps?q=" +
        PICKUP_ADDRESS +
        "&hl=es;z=14&amp;output=embed' width='400' height='500' frameborder='0' style='border:0; width:100%;' allowfullscreen></iframe>"
    );

    $('#tracking-events').load(
      'index.php?route=sale/order/trackingevents&token=' + token + '&order_id=' + orderInfo.orderId
    );

    $('#history').load(
      'index.php?route=sale/order/history&token=' +
        token +
        '&order_id=' +
        orderInfo.orderId +
        '&mercaOrderId=' +
        orderInfo.mktOrderId +
        '&mkt_integracao_tipo=' +
        orderInfo.mkt_integracao_tipo,
      function() {
        initHandleDropdown();
        selectErrors();
      }
    );

    $('#history').on('click', '.adm-pagination a', function(event) {
      event.preventDefault();
      $('#history').load(this.href, function() {
        initHandleDropdown();
        selectErrors();
      });
      return false;
    });

    $('#log').load(
      'index.php?route=sale/order/log&token=' +
        token +
        '&orderId=' +
        orderInfo.orderId +
        '&mktOrderId=' +
        encodeURIComponent(orderInfo.mktOrderIdNormal) +
        '&mktIntegracaoTipo=' +
        orderInfo.mkt_integracao_tipo,
      function() {}
    );

    $('select[name="order_status_id"]').on('change', function() {
      if (
        orderInfo.trackingStatus &&
        orderInfo.trackingStatus.length &&
        orderInfo.trackingStatus.includes($(this).val())
      ) {
        var html = '<label class="field field-medium bottom-margin-large js-tracking-code">';
        html += '<span class="field-label">Código de Rastreio</span>';
        html += '<input type="text" name="tracking_code" value="" class="field-entry">';
        html += '</label>';

        $('.js-tracking-code').remove();
        $(this)
          .parent()
          .after(html);
        calendarField();
      } else {
        $('.js-tracking-code').remove();
      }

      getMessageStatus($(this));
    });

    $('select[name="order_status_id"]').trigger('change');

    function getMessageStatus($this) {
      $('body').append(loadBeforeSend());

      $.ajax({
        url: 'index.php?route=sale/order/messageStatus&token=' + token,
        type: 'POST',
        data: { status_id: $this.val() },
      })
        .done(function(json) {
          if (json['message']) {
            $("textarea[name='comment']").text('');
            $("textarea[name='comment']").text(json['message']);
          }
        })
        .fail(function() {
          console.log('error');
        })
        .always(function() {
          $('.loadBeforeSend').fadeOut();
        });
    }

    $('#button-cancel-payment').on('click', function() {
      let msgConfirm;

      data = {};
      data['cancelOrder'] = window.confirm('Você também deseja cancelar o pedido?');

      data['cancelOrder']
        ? (msgConfirm = 'Tem certeza que deseja estornar o pagamento e cancelar esse pedido?')
        : (msgConfirm = 'Tem certeza que deseja estornar o pagamento desse pedido?');

      if (!window.confirm(msgConfirm)) {
        return;
      }

      $.ajax({
        url: 'index.php?route=sale/order/cancelPayment&token=' + token + '&order_id=' + orderInfo.orderId,
        type: 'post',
        dataType: 'json',
        data: data,
        beforeSend: function() {
          $('.cancel_payment_message').remove();
          $('#button-cancel-payment').attr('disabled', true);
        },
        complete: function() {
          $('#button-cancel-payment').attr('disabled', false);
        },
        success: function(data) {
          let message, messageClass;
          if (data['success']) {
            message = data['success'];
            messageClass = 'background-success text-success border-success';
          } else {
            message = 'Erro ao estornar o pagamento: ' + data['error'];
            messageClass = 'background-error text-error border-error';
          }
          $('.cancel_payment_container').append(
            '<div class="cancel_payment_message content-box top-margin-medium padding-medium rounded-small ' +
              messageClass +
              '">' +
              message +
              '</div>'
          );
          loadHistory();
        },
      });
    });

    function loadHistory() {
      $('#history').load(
        'index.php?route=sale/order/history&token=' +
          token +
          '&order_id=' +
          orderInfo.orderId +
          '&mercaOrderId=' +
          orderInfo.mktOrderId +
          '&mkt_integracao_tipo=' +
          orderInfo.mkt_integracao_tipo,
        function() {
          initHandleDropdown();
          selectErrors();
        }
      );
    }

    $('#button-history').on('click', function() {
      var orderPagamento = orderInfo.codePagamento,
        orderPagamentoCancelado = orderInfo.status_pagamento_canceldo,
        extornoCartao = false,
        integracao = '',
        data = {};

      if (
        orderPagamentoCancelado == $("select[name='order_status_id']").val() &&
        (orderPagamento == 'rede_credito' || orderPagamento == 'cielo_api_credito') &&
        window.confirm('Deseja extornar o pagamento do cartão de crédito junto ao cancelamento desse pedido?')
      ) {
        extornoCartao = orderPagamento;
      }

      if (typeof orderInfo.mkt_integracao_tipo !== 'undefined') {
        integracao = '&mkt_integracao_tipo=' + orderInfo.mkt_integracao_tipo;
      }

      data['order_status_id'] = $("select[name='order_status_id']").val();
      data['client_notify'] = $("input[name='client_notify']").attr('checked') ? 1 : 0;
      data['append'] = $("input[name='append']").attr('checked') ? 1 : 0;
      data['comment'] = $("textarea[name='comment']").val();
      data['tracking_code'] =
        typeof $("input[name='tracking_code']").val() !== 'undefined' ? $("input[name='tracking_code']").val() : '';
      data['manual'] = 1;

      $.ajax({
        url:
          'index.php?route=sale/order/history&token=' +
          token +
          '&order_id=' +
          orderInfo.orderId +
          '&mercaOrderId=' +
          orderInfo.mktOrder +
          '&mercadolivre_stopsync=' +
          orderInfo.mlStopsync +
          '&extornoCartao=' +
          extornoCartao +
          integracao,
        type: 'post',
        dataType: 'html',
        data: data,
        beforeSend: function() {
          $('.success, .warning').remove();
          $('#button-history').attr('disabled', true);
          $('#history')
            .css('opacity', '.5')
            .prepend(
              '<div class="flex center-xs abs full-width full-height js-img-loading"><img src="../assets/img/loading-black.svg" alt="Carregando..." /></div>'
            );
        },
        complete: function() {
          $('#button-history').attr('disabled', false);
          $('#history').removeAttr('style');
          selectErrors();
          appendErrorIcon();
        },
        success: function(html) {
          let dados;
          if (isJson(html)) {
            dados = JSON.parse(html);
          } else {
            dados = html;
          }

          if (dados['error']) {
            $('.js-img-loading').remove();
            if (dados['error']['code']) {
              notificationMsg(window.language.get('error_cant_reverse_payment'), 'error');
            }
          } else {
            $('#history').html(dados);
            initHandleDropdown();
            $("textarea[name='comment']").val('');
            $('#order-status').html($("select[name='order_status_id'] option:selected").text());
          }
        },
      });
    });

    $('#button-captura-pagamento').on('click', function() {
      $.ajax({
        url: 'index.php?route=sale/order/aprovaPagamentoPendente&token=' + token + '&order_id=' + orderInfo.orderId,
        type: 'post',
        dataType: 'json',
        beforeSend: function() {
          $('.success, .warning').remove();
          $('#button-captura-pagamento')
            .prop('disabled', true)
            .addClass('btn-loading');
        },
        complete: function() {
          $('#button-captura-pagamento').removeClass('btn-loading');
          $('#button-captura-pagamento')
            .prop('disabled', true)
            .removeClass('btn-success');

          $('#button-nega-pagamento')
            .prop('disabled', true)
            .removeClass('btn-error');

          if (orderInfo.antifraude_verificado && orderInfo.captura_disponivel) {
            var warning_antifraude_icon = tabAntiFraude.querySelector('.fa-exclamation-triangle');
            if (warning_antifraude_icon !== null) {
              warning_antifraude_icon.remove();
            }
          }
        },
        success: function(json) {
          if (json['success']) {
            admAlert(json['success'], 'success');
          }
        },
      });
    });

    $('#button-nega-pagamento').on('click', function() {
      $.ajax({
        url: 'index.php?route=sale/order/cancelaPagamentoPendente&token=' + token + '&order_id=' + orderInfo.orderId,
        type: 'post',
        dataType: 'json',
        beforeSend: function() {
          $('.success, .warning').remove();
          $('#button-nega-pagamento')
            .prop('disabled', true)
            .addClass('btn-loading');
        },
        complete: function() {
          $('#button-nega-pagamento').removeClass('btn-loading');
          $('#button-captura-pagamento')
            .prop('disabled', true)
            .removeClass('btn-success');
          $('#button-nega-pagamento')
            .prop('disabled', true)
            .removeClass('btn-error');
        },
        success: function(json) {
          if (json['success']) {
            admAlert(json['success'], 'success');
          }
        },
      });
    });

    $('#clearsale').load('index.php?route=sale/order/clearsale&token=' + token + '&order_id=' + orderInfo.orderId);
    $('body').on('click', '#button-consultaclearsale', function() {
      $('#formclearsale').submit();

      var elementiFrameStart = document.getElementById('iFrameStart');
      var buttonConsultaClearsale = document.getElementById('button-consultaclearsale');

      $.ajax({
        url: 'index.php?route=sale/order/setVerificadoClearsaleStart&token=' + token + '&order_id=' + orderInfo.orderId,
        type: 'post',
        dataType: 'json',
        beforeSend: function() {
          buttonConsultaClearsale.classList.add('btn-loading');
          buttonConsultaClearsale.setAttribute('disabled', true);
        },
        complete: function() {
          buttonConsultaClearsale.classList.remove('btn-loading');
          buttonConsultaClearsale.removeAttribute('disabled');
        },
        success: function() {
          elementiFrameStart.classList.remove('hidden');
        },
        error: function() {
          console.log('erro ao consultar clearsale');
        },
      });
    });

    if (typeof orderInfo.mktOrderId != 'undefined' && typeof orderInfo.mlStatus != 'undefined') {
      function confirm(message, value) {
        $('#meuConfirm').html(message);
        $('#meuConfirm').dialog({
          modal: true,
          maxWidth: 300,
          maxHeight: 150,
          minWidth: 300,
          minHeight: 150,
          buttons: {
            Não: function() {
              $(this).dialog('close');
            },
            Sim: function() {
              desincronizar(value);
            },
          },
        });
      }

      $('body').on('click', '.js-order-stop-ml', function() {
        var orderid = typeof $(this).data('orderid') == 'undefined' ? false : $(this).data('orderid');
        if (typeof orderid !== 'undefined') {
          confirm(orderInfo.mlMsgOrderStop, orderid);
        }
      });

      function desincronizar(value) {
        var data = {};
        data['orderid'] = value;
        $.ajax({
          url: 'index.php?route=module/mercadolivre/mercadolivre/descronizarOrder&token=' + token,
          type: 'get',
          data: data,
          dataType: 'json',
          beforeSend: function() {
            $('.js-order-stop-ml')
              .prop('disabled', true)
              .addClass('btn-loading');
          },
          complete: function() {
            $('.js-order-stop-ml')
              .prop('disabled', false)
              .removeClass('btn-loading');
          },
          success: function(json) {
            $('#meuConfirm').dialog('close');
            if (json['error']) {
              $('.box').before(
                '<div class="warning"><span>' +
                  json['error'] +
                  '<i class="btn-close fas fa-times" aria-hidden="true"></i></span></div>'
              );
            }
            if (json['success']) {
              location.reload();
            }
          },
        });
      }
    }

    $('[data-modal-id="product-adjust"]').on('click', function() {
      $('#product-adjust').remove();
      var mercaid = typeof $(this).data('mercaid') == 'undefined' ? false : $(this).data('mercaid');
      var mktintegracaotipo =
        typeof $(this).data('mktintegracaotipo') == 'undefined' ? null : $(this).data('mktintegracaotipo');

      var html = '<div class="js-adm-modal-container adm-modal-container-full">';
      html += '<div class="adm-modal-header flex end-xs">';
      html += '<i class="fas fa-times text-small text-dark padding-large cursor-pointer js-adm-modal-close"></i>';
      html += '<form class="horizontal-padding-large bottom-padding-large full-width" id="ajuste-item">';
      html += '<div class="row small-space-xs bottom-xs">';
      html += '<div class="col-xs">';
      html += '<div class="field-group">';
      html += '<label class="field-label" for="filter_name">Nome do Produto</label>';
      html +=
        '<input type="text" name="filter_name" id="filter_name" value="" class="ui-autocomplete-input field-entry field-entry-medium" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">';
      html += '</div>';
      html += '</div>';
      html += '<div class="col-xs">';
      html += '<div class="field-group">';
      html += '<label class="field-label" for="filter_category_id">Categoria</label>';
      html += '<select name="filter_category_id" id="filter_category_id" class="field-entry field-entry-medium">';
      html += '<option value="*"></option>';
      for (var i = 0; i < orderInfo.categories.length; i++) {
        html +=
          '<option value="' + orderInfo.categories[i].category_id + '">' + orderInfo.categories[i].name + '</option>';
      }
      html += '</select>';
      html += '</div>';
      html += '</div>';
      html += '<div class="col-xs">';
      html += '<div class="field-group">';
      html += '<label class="field-label" for="filter_model">Código</label>';
      html += '<div class="field-entry-group">';
      html += '<select name="filter_content_model" id="filter_content_model" class="field-entry field-entry-medium">';
      for (var i = 0; i < orderInfo.filterContent.length; i++) {
        html +=
          '<option value="' + orderInfo.filterContent[i].value + '" >' + orderInfo.filterContent[i].name + '</option>';
      }
      html += '</select>';
      html +=
        '<input type="text" name="filter_model" id="filter_model" value="" class="ui-autocomplete-input field-entry field-entry-medium" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">';
      html += '</div>';
      html += '</div>';
      html += '</div>';
      html += '<div class="col-xs-width-auto">';
      html +=
        '<a id="btnFilterProducts" class="btn-default btn-primary btn-medium button-filter-error mercaid" data-mercaid="' +
        mercaid +
        '" data-mktintegracaotipo="' +
        mktintegracaotipo +
        '" >';
      html += '<span>Filtrar</span>';
      html += '</a>';
      html += '</div>';
      html += '</div>';
      html += '</form>';
      html += '</div>';
      html += '<div class="adm-modal-content js-content-ajuste horizontal-padding-large">';
      html += '</div>';
      html += '<div class="js-adm-modal-footer horizontal-padding-large">';
      html += '<div class="js-adm-modal-buttons flex end-xs vertical-padding-large">';
      html += '<button class="btn-default btn-medium btn-white right-margin-small js-adm-modal-close" >';
      html += '<span>Cancelar</span>';
      html += '</button>';
      html +=
        '<button class="btn-default btn-primary btn-medium button-filter-apply" data-mercaId="' +
        mercaid +
        '" data-orderid="' +
        orderInfo.orderId +
        '" >';
      html += '<span>Aplicar</span>';
      html += '</button>';
      html += '</div>';
      html += '</div>';
      html += '</div>';

      $(this).modalFutura({
        dataModalId: $(this).data('modal-id'),
        appendModal: html,
      });
      $('#' + $(this).data('modal-id'))
        .find('.button-filter-error')
        .trigger('click');
    });

    $('body').on('click', '.button-filter-error', function() {
      var data = $('#ajuste-item').serializeObject(),
        mktIntegracaoTipo = document.getElementById('btnFilterProducts').dataset.mktintegracaotipo;

      data['page'] = typeof $(this).data('page') == 'undefined' ? 1 : $(this).data('page');
      data['mktintegracaotipo'] = mktIntegracaoTipo;

      var mercaid = typeof $('.mercaid').data('mercaid') == 'undefined' ? false : $('.mercaid').data('mercaid');

      $('.button-filter-error')
        .prop('disabled', true)
        .addClass('btn-loading');
      $('#product-adjust').addClass('js-adm-modal-overlay-no-close');

      $.ajax({
        url: 'index.php?route=catalog/product/retornoJson&token=' + token,
        type: 'get',
        data: data,
        dataType: 'html',
        beforeSend: function() {},
        complete: function() {
          $('.button-filter-error')
            .prop('disabled', false)
            .removeClass('btn-loading');
          $('#product-adjust').removeClass('js-adm-modal-overlay-no-close');
        },
        success: function(html) {
          $('.js-content-ajuste').html(html);
        },
      });
    });

    $('body').on('click', 'input[name="ajustem-item"]:checked', function() {
      $('.js-content-select-grid').addClass('hidden');
      $(this)
        .closest('.js-table-product')
        .find('.js-content-select-grid')
        .removeClass('hidden');
    });

    $('body').on('click', '.button-filter-apply', function() {
      $('.warning').remove();
      var data = {};

      if ($('input[name="ajustem-item"]:checked').hasClass('js-radio-grade')) {
        data['product_id'] = $('input[name="ajustem-item"]:checked')
          .closest('.js-table-product')
          .find('select')
          .val();
      } else {
        data['product_id'] = $('input[name="ajustem-item"]:checked').val();
      }

      if (typeof data['product_id'] == 'undefined' || data['product_id'] == '*') {
        alert('Selecione um produto que será vinculado!');
        return;
      }

      data['mercaid'] = typeof $(this).data('mercaid') == 'undefined' ? false : $(this).data('mercaid');
      data['orderid'] = typeof $(this).data('orderid') == 'undefined' ? false : $(this).data('orderid');

      if (typeof data['product_id'] != 'undefined' && data['mercaid'] != false && data['orderid'] != false) {
        $('.button-filter-apply')
          .prop('disabled', true)
          .addClass('btn-loading');
        $('#product-adjust').addClass('js-adm-modal-overlay-no-close');

        if (!window.confirm('Deseja realmente vincular esse produto?')) {
          return;
        }

        $.ajax({
          url: 'index.php?route=sale/order/orderproductMl&token=' + token,
          type: 'get',
          data: data,
          dataType: 'json',
          beforeSend: function() {},
          complete: function() {
            $('.button-filter-apply')
              .prop('disabled', false)
              .removeClass('btn-loading');
            $('#product-adjust').removeClass('js-adm-modal-overlay-no-close');
          },
          success: function(json) {
            if (json['error']) {
              $('.content-ajuste').before('<div class="warning">' + json['error'] + '</div>');
            } else {
              location.href = json['redirect'];
            }
          },
        });
      } else {
        $('.content-ajuste').before('<div class="warning">Selecione um produto para aplicar!</div>');
      }
    });
  } //fim length

  $('.js-skyhub-etiqueta-download').on('click', function(e) {
    e.preventDefault();

    window.addLoad();
    $('.js-warning-etiqueta').remove();

    fetch($('.js-skyhub-etiqueta-download').prop('href'))
      .then(response => {
        if (response.headers.get('Content-Type') == 'application/pdf') {
          response.blob().then(blob => {
            let link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = 'skyhub_etiqueta_' + $('.js-skyhub-etiqueta-download').attr('data-order-id') + '.pdf';
            link.click();
          });
        } else {
          response.json().then(json => {
            const { error } = json;
            $('.js-header-notifications').append(
              '<div class="warning full-width top-margin-small js-warning-etiqueta">' + error + '</div>'
            );
          });
        }
      })
      .catch(console.error)
      .finally(() => window.removeLoad());
  });

  $('.js-mercadolivre-etiqueta-download').on('click', function(e) {
    e.preventDefault();

    // tem que usar XMLHttpRequest porque o AJAX buga o arquivo PDF
    var req = new XMLHttpRequest();
    req.open('GET', $('.js-mercadolivre-etiqueta-download').prop('href'), true);
    req.responseType = 'blob';

    req.beforeSend = function(event) {
      window.addLoad();
      $('.js-warning-etiqueta').remove();
    };

    req.beforeSend(e);

    req.onload = function(event) {
      if (req.status == 200) {
        var blob = req.response;
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download =
          'mercadolivre_etiqueta_' + $('.js-mercadolivre-etiqueta-download').attr('data-order-id') + '.pdf';
        link.click();
      } else {
        $('.js-header-notifications').append(
          '<div class="warning full-width top-margin-small js-warning-etiqueta">Etiqueta indisponível</div>'
        );
      }
      window.removeLoad();
    };

    req.send();
  });

  $('.js-melhorenvio-etiqueta-download').on('click', function(e) {
    e.preventDefault();
    var $this = $('.js-melhorenvio-etiqueta-download');

    var result = true;

    if (!$this.attr('data-shipping-label-id')) {
      result = window.confirm(
        'Essa operação poderá gastar seu saldo do Melhor Envio, você tem certeza que deseja comprar a etiqueta?'
      );
    }

    if (result) {
      $.ajax({
        url:
          $this.prop('href') +
          '&orderId=' +
          $this.attr('data-order-id') +
          '&shippingLabelId=' +
          $this.attr('data-shipping-label-id'),
        type: 'get',
        dataType: 'json',
        beforeSend: function() {
          window.addLoad();
          $('.js-warning-etiqueta').remove();
        },
        complete: function() {
          window.removeLoad();
        },
        success: function(json) {
          if (json) {
            if (!json.error) {
              $this.attr('data-shipping-label-id', json.label_id);
              window.open(json.url, '_blank');
            } else {
              $('.js-header-notifications').append(
                '<div class="warning full-width top-margin-small js-warning-etiqueta">' + json.error + '</div>'
              );
            }
          } else {
            $('.js-header-notifications').append(
              '<div class="warning full-width top-margin-small js-warning-etiqueta">Etiqueta indisponível</div>'
            );
          }
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.log(jqXHR, textStatus, errorThrown);
        },
      });
    }
  });

  $('.js-kangu-etiqueta-download').on('click', function(e) {
    e.preventDefault();
    var $this = $('.js-kangu-etiqueta-download');

    var result = true;

    if (!$this.attr('data-shipping-label-id')) {
      result = window.confirm('Você tem certeza que deseja imprimir a etiqueta?');
    }

    if (result) {
      $.ajax({
        url:
          $this.prop('href') +
          '&orderId=' +
          $this.attr('data-order-id') +
          '&shippingLabelId=' +
          $this.attr('data-shipping-label-id'),
        type: 'get',
        dataType: 'json',
        beforeSend: function() {
          window.addLoad();
          $('.js-warning-etiqueta').remove();
        },
        complete: function() {
          window.removeLoad();
        },
        success: function(json) {
          if (json) {
            if (json.error) {
              $('.js-header-notifications').append(
                '<div class="warning full-width top-margin-small js-warning-etiqueta">' + json.error.mensagem + '</div>'
              );
            } else {
              var deBase64 = new Buffer(json.pdf, 'base64');
              var file = new Blob([deBase64], { type: 'pdf' });
              var link = document.createElement('a');
              link.href = window.URL.createObjectURL(file);
              link.download = 'kangu_etiqueta_' + $('.js-kangu-etiqueta-download').attr('data-order-id') + '.pdf';
              link.click();
            }
          } else {
            $('.js-header-notifications').append(
              '<div class="warning full-width top-margin-small js-warning-etiqueta">Etiqueta indisponível</div>'
            );
          }
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.log(jqXHR, textStatus, errorThrown);
        },
      });
    }
  });

  $('.js-order-force-repli').on('click', function() {
    var token = $('body').data('token');
    var orderInfo = getOrderInfo();

    $.ajax({
      url: 'index.php?route=sale/order/forcarReplciacao&token=' + token + '&order_id=' + orderInfo.orderId,
      beforeSend: function() {
        $('.js-order-force-repli')
          .prop('disabled', true)
          .addClass('btn-loading');
      },
      success: function() {
        $('.js-order-force-repli')
          .prop('disabled', false)
          .removeClass('btn-loading');
        admAlert(
          'Registro inserido na fila de sincronia, aguarde alguns minutos para que ele seja sincronizado com o FuturaServer.',
          'success'
        );
      },
      error: function() {
        console.log('Erro na função forcarReplciacao');
      },
    });
  });

  const WARNING_CONTAINER = document.querySelector('.js-more-info-content');
  if (WARNING_CONTAINER != null) {
    var wc_more_info = WARNING_CONTAINER.querySelector('.js-more-info');
    if (wc_more_info != null) {
      wc_more_info.onclick = showError;
    }
  }

  $('body').on('click', '.js-btn-message-status', function() {
    const $THIS = $(this),
      $ELEMENT = $THIS.parent().find('.js-content-message-status'),
      $ICON = $THIS.find('i');

    if ($ELEMENT.hasClass('hidden')) {
      $ICON.removeClass('fa-chevron-down').addClass('fa-chevron-up');
      $ELEMENT.removeClass('hidden');
    } else {
      $ICON.removeClass('fa-chevron-up').addClass('fa-chevron-down');
      $ELEMENT.addClass('hidden');
    }
  });
});

function initHandleDropdown() {
  if (window.handleDropdown) {
    window.handleDropdown($('#history'));
  } else {
    setTimeout(function() {
      initHandleDropdown();
    }, 200);
  }
}

function showError() {
  const WARNING_CONTAINER = document.querySelector('.js-more-info-content');
  var wc_hidden = WARNING_CONTAINER.querySelector('.hidden');
  if (wc_hidden != null) {
    wc_hidden.classList.remove('hidden');
  }
  this.remove();
}

function appendErrorIcon() {
  var tabActive = document.querySelector('.js-tab.active'),
    tabText = tabActive.textContent,
    history = document.getElementById('history'),
    historyErro = history.querySelector('.background-error');

  if (historyErro) {
    tabActive.innerHTML = '<i class="fas fa-exclamation-triangle text-error right-margin-small"></i>' + tabText;
  }
}

function selectErrors() {
  var resendButton = document.querySelectorAll('.js-resend-status');

  for (var i = 0; i < resendButton.length; i++) {
    resendButton[i].addEventListener('click', function(event) {
      event.currentTarget.classList.add('btn-loading');

      var historyInfo = JSON.parse(this.parentNode.getAttribute('data-history-info'));

      reenviarMktStatus(historyInfo.order_history_id, historyInfo.order_status_id);
    });
  }

  var notSendButton = document.querySelectorAll('.js-not-send-status');
  for (var j = 0; j < notSendButton.length; j++) {
    notSendButton[j].addEventListener('click', function() {
      var historyInfo = JSON.parse(this.parentNode.getAttribute('data-history-info'));
      naoEnviarMaisMktStatus(historyInfo.order_history_id);
    });
  }
}

function naoEnviarMaisMktStatus(order_history_id) {
  var token = $('body').data('token');
  var orderInfo = JSON.parse($('[data-order-info]').data('order-info'));
  $.ajax({
    url:
      'index.php?route=sale/order/desvincularMktHistorico&order_history_id=' +
      order_history_id +
      '&order_id=' +
      orderInfo.orderId +
      '&token=' +
      token +
      '&mkt_integracao_tipo=' +
      orderInfo.mkt_integracao_tipo,
    type: 'get',
    beforeSend: function() {},
    success: function(json) {
      $.ajax({
        url:
          'index.php?route=sale/order/history&token=' +
          token +
          '&order_id=' +
          orderInfo.orderId +
          '&mercaOrderId=' +
          orderInfo.mktOrderId +
          '&mkt_integracao_tipo=' +
          orderInfo.mkt_integracao_tipo,
        success: function(html) {
          $('#history').html(html);
          initHandleDropdown();
        },
        complete: function() {
          selectErrors();
        },
      });
      if (!json['error_mkt_status_history']) {
        $('.fa-exclamation-triangle').remove();
      }
    },
    error: function() {
      notificationMsg('Erro ao tentar cancelar o envio automático.', 'error');
      console.log('Erro na função naoEnviarMaisMktStatus');
    },
  });
}

function reenviarMktStatus(order_history_id, order_status_id) {
  var token = $('body').data('token');
  var orderInfo = JSON.parse($('[data-order-info]').data('order-info'));
  $.ajax({
    url:
      'index.php?route=sale/order/reenviarMktHistorico&order_history_id=' +
      order_history_id +
      '&order_id=' +
      orderInfo.orderId +
      '&order_status_id=' +
      order_status_id +
      '&token=' +
      token +
      '&mkt_integracao_tipo=' +
      orderInfo.mkt_integracao_tipo,
    type: 'get',
    beforeSend: function() {},
    success: function(json) {
      $.ajax({
        url:
          'index.php?route=sale/order/history&token=' +
          token +
          '&order_id=' +
          orderInfo.orderId +
          '&mercaOrderId=' +
          orderInfo.mktOrderId +
          '&mkt_integracao_tipo=' +
          orderInfo.mkt_integracao_tipo,
        success: function(html) {
          $('#history').html(html);
          initHandleDropdown();
        },
        error: function() {
          notificationMsg('Erro ao realizar envio, tente novamente mais tarde.', 'error');
        },
        complete: function() {
          selectErrors();
        },
      });
      if (!json['error_mkt_status_history']) {
        $('.fa-exclamation-triangle').remove();
      }
    },
    error: function(error) {
      notificationMsg('Erro ao realizar envio, tente novamente mais tarde.', 'error');
      console.log(error);
      console.log('Erro na função reenviarMktStatus');
    },
  });
}
