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

  if (info.marketplace_active) {
    $('.js-product-form input[type=checkbox]').on('change', function() {
      if ($('.js-product-form input[type=checkbox]:checked').length > 0) {
        $('#suspended-side-actions').prop('disabled', false);
      } else {
        $('#suspended-side-actions').prop('disabled', true);
      }
    });
  }

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

  $('.js-bulkSetting, .js-bulkSettingUnique').on('click', function(event) {
    var $this = $(this),
      $loading =
        '<div class="js-adm-modal-container"><img src="../assets/img/loading-black.svg" width="64" height="64" alt="" /></div>';

    var $data = {};
    $data['token'] = token;
    $data['type'] = info.titleModules;
    $data['type_products'] = '';

    if ($this.hasClass('js-bulkSetting')) {
      var $pids = $('input[name="selected[]"]:checked')
        .map(function() {
          var $this = $(this);
          return this.value;
        })
        .get()
        .join(',');

      $data['type_products'] = $('input[name="selected[]"]:checked')
        .map(function() {
          var $this = $(this);
          return $this.data('prod-type');
        })
        .get()
        .join(',');

      $data['pids'] = $pids;
    } else if ($this.hasClass('js-bulkSettingUnique')) {
      $data['unique'] = true;
      $data['pids'] = $(this).data('product-id');
      $data['type_products'] = $this.data('prod-type');
    } else {
      return false;
    }

    $data['redirect'] = encodeURI(info.urlRetorno);
    $data['type_marketplace'] = info.type_marketplace;

    $('#bulk-setting').remove();
    $('#adm-modal-loading').remove();

    $this.modalFutura({
      dataModalId: 'adm-modal-loading',
      appendModal: $loading,
    });
    $('#adm-modal-loading').addClass('js-adm-modal-overlay-no-close');

    $.ajax({
      url: 'index.php?route=marketplace/Marketplacecalls/bulkSetting',
      type: 'GET',
      dataType: 'json',
      data: $data,
    })
      .done(function(data) {

        if(data.error){
          notificationMsg(data.error, 'error');
        }else{
          var $modal = $this.modalFutura({
            dataModalId: 'bulk-setting',
            appendModal: data.html,
          });
        }
      })
      .error(function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
      })
      .fail(function() {
        // adaptação técnica(gambiarra) pra quando o token expira, e voltava a tela de login toda bugada,
        // agora ele atualiza pra mostrar a página de login correta, caso esse código de algum problema, pode remover
        document.location.reload();
        console.log('error');
      })
      .always(function() {
        $('#adm-modal-loading').remove();
      });
  });

  $('.js-button-advertisement').on('click', function(event) {
    event.preventDefault();

    var $element = $(this)
      .closest('.row')
      .find('.js-content-advertisement');

    $element.toggleClass('hidden');
  });

  //function to show error synchronize ml and shopee
  $('.js-icon-error-synchronize').on('click', function(event) {
    event.preventDefault();

    var $textError = $(this)
      .closest('.row')
      .find('.js-span-error-synchronize');
    $textError.toggleClass('hidden');
  });

  function filter() {
    url = 'index.php?route=' + info.route + '&token=' + token + (info.sort ? '&sort=' + info.sort : '') + (info.order ? '&order=' + info.order : '');

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    location = url;
  }

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

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

  $("input[name='filter_model']").autocomplete({
    delay: 500,
    source: function(request, response) {
      $.ajax({
        url:
          'index.php?route=catalog/product/autocomplete&token=' +
          token +
          '&filter_model=' +
          encodeURIComponent(request.term),
        dataType: 'json',
        success: function(json) {
          response(
            $.map(json, function(item) {
              return {
                label: item.model,
                value: item.product_id,
              };
            })
          );
        },
      });
    },
    select: function(event, ui) {
      $("input[name='filter_model']").val(ui.item.label);
      return false;
    },
    focus: function(event, ui) {
      return false;
    },
  });

  $("input[name='filter_manufacturer']").autocomplete({
    delay: 500,
    source: function(request, response) {
      $.ajax({
        url:
          'index.php?route=catalog/manufacturer/autocomplete&token=' +
          token +
          '&filter_manutecturer=' +
          encodeURIComponent(request.term),
        dataType: 'json',
        success: function(json) {
          response(
            $.map(json, function(item) {
              return {
                label: item.name,
                value: item.manufacturer_id,
              };
            })
          );
        },
      });
    },
    select: function(event, ui) {
      $("input[name='filter_manufacturer']").val(ui.item.label);
      return false;
    },
    focus: function(event, ui) {
      return false;
    },
  });

  $("input[name='filter_color']").autocomplete({
    delay: 500,
    source: function(request, response) {
      $.ajax({
        url:
          'index.php?route=catalog/color_product/autocomplete&token=' +
          token +
          '&filter_color=' +
          encodeURIComponent(request.term),
        dataType: 'json',
        success: function(json) {
          response(
            $.map(json, function(item) {
              return {
                label: item.description,
                value: item.productcolor_id,
              };
            })
          );
        },
      });
    },
    select: function(event, ui) {
      $("input[name='filter_color']").val(ui.item.label);
      return false;
    },
    focus: function(event, ui) {
      return false;
    },
  });

  $("input[name='filter_size']").autocomplete({
    delay: 500,
    source: function(request, response) {
      $.ajax({
        url:
          'index.php?route=catalog/size_product/autocomplete&token=' +
          token +
          '&filter_size=' +
          encodeURIComponent(request.term),
        dataType: 'json',
        success: function(json) {
          response(
            $.map(json, function(item) {
              return {
                label: item.description,
                value: item.productsize_id,
              };
            })
          );
        },
      });
    },
    select: function(event, ui) {
      $("input[name='filter_size']").val(ui.item.label);
      return false;
    },
    focus: function(event, ui) {
      return false;
    },
  });

  $('#filter_name').autocomplete({
    delay: 500,
    source: function(request, response) {
      $.ajax({
        url:
          'index.php?route=catalog/product/autocomplete&token=' +
          token +
          '&filter_name=' +
          encodeURIComponent(request.term),
        dataType: 'json',
        success: function(json) {
          response(
            $.map(json, function(item) {
              return {
                label: item.name,
                value: item.product_id,
              };
            })
          );
        },
      });
    },
    select: function(event, ui) {
      $('#filter_name').val(ui.item.label);

      return false;
    },
    focus: function(event, ui) {
      return false;
    },
  });

  $('.js-bulkSynchronize').on('click', function() {
    var chklista = $('input[name="selected[]"]:checked')
      .toArray()
      .map(function(check) {
        return $(check).data('sincro');
      });

    if (chklista.length == 0) {
      alert('Nenhum produto selecionado para sincronização!');
      return false;
    }

    chklista = jQuery.grep(chklista, function(n, i) {
      return n === '' && i !== 1;
    });

    if (chklista.length > 0) {
      if (!confirm('Os produtos ainda não sincronizados criarão novos anúncios no marketplace. Deseja continuar?')) {
        return false;
      }
    }

    $('.js-product-form').attr(
      'action',
      'index.php?route=marketplace/Marketplacecalls/bulkSynchronize&token=' +
        token +
        info.urlFilter +
        '&type_marketplace=' +
        info.type_marketplace
    );
    $('.js-product-form').submit();
  });

  $('.js-bulkDeSynchronize').on('click', function() {
    var chklista = $('input[name="selected[]"]:checked').toArray();

    if (chklista.length == 0) {
      alert('Nenhum produto selecionado para dessincronizar!');
      return false;
    }

    $('.js-product-form').attr(
      'action',
      'index.php?route=marketplace/Marketplacecalls/bulkDesynchronize&token=' +
        token +
        info.urlFilter +
        '&type_marketplace=' +
        info.type_marketplace
    );
    $('.js-product-form').submit();
  });

  $('.js-bulkMLVinc').on('click', function() {
    var chklista = $('input[name="selected[]"]:checked').toArray();

    if (chklista.length == 0) {
      alert('Nenhum produto selecionado para desvincular!');
      return false;
    }

    $('.js-product-form').attr(
      'action',
      'index.php?route=marketplace/Marketplacecalls/bulkMLVinc&token=' +
        token +
        info.urlFilter +
        '&type_marketplace=' +
        info.type_marketplace
    );
    $('.js-product-form').submit();
  });

  $(document).on('click', '.finalizar', function(e) {
    if (confirm('Deseja realmente finalizar o anúncio? Esta ação excluirá o anúncio no marketplace')) {
      $.ajax({
        method: 'GET',
        url: $(this).attr('data-link'),
      }).done(function(json) {
        location.href = info.urlRetorno;
      });
    }
  });

  $(document).on('click', '.sincronizar', function(e) {
    if ($(this).attr('data-sincro') == 1) {
      location.href = $(this).attr('data-link');
    } else if ($(this).attr('data-sincro') == 'closed') {
      if (confirm('Anúncio finalizado no Mercado Livre, deseja criar um novo anúncio?')) {
        location.href = $(this).attr('data-link');
      }
    } else if (!$(this).attr('data-mercaid')) {
      if (confirm('Deseja realmente sincronizar este produto?')) {
        location.href = $(this).attr('data-link');
      }
    } else {
      location.href = $(this).attr('data-link');
    }
  });

  $(document).on('click', '.js-sincronizarCatalog', function(e) {

    var $this = $(this),
        $loading = '<div class="js-adm-modal-container"><img src="../assets/img/loading-black.svg" width="64" height="64" alt="" /></div>';

    var $data = {};
    $data['token'] = token;
    $data['product_type'] = $(this).data('prod-type');
    $data['product_id'] = $(this).data('product-id');
    $data['codigo_barra'] = $(this).data('codigobarra');
    $data['main_ad'] = $(this).data('mercaid');
    $data['main_ad_id'] = $(this).data('mainadid');
    $data['redirect'] = $(this).data('url-redirect');

    $('#synchronize-catalog').remove();
    $('#adm-modal-loading').remove();

    $this.modalFutura({
      dataModalId: 'adm-modal-loading',
      appendModal: $loading,
    });
    $('#adm-modal-loading').addClass('js-adm-modal-overlay-no-close');

    $.ajax({
      url: $(this).attr('data-link'),
      type: 'GET',
      dataType: 'html',
      data: $data,
    })
      .done(function(data) {
        var $modal = $this.modalFutura({
          dataModalId: 'synchronize-catalog',
          appendModal: data,
          closeClickOut: false
        });
      })
      .fail(function() {
        console.log('error');
      });
  });

  $('#order_list_data_added').on('change', function (e) {
    e.preventDefault();
    const $url = $('#order_list_data_added').attr('value');

    if ($url) {
      window.location.href = $url;
    }
  });
});
