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

$form.validate({
  onfocusout: function(element) {
    if (!$(element).hasClass('mask-number-decimal')) {
      $(element).valid();
    }
  },
  onkeyup: function(element) {
    if ($(element).hasClass('mask-number-decimal')) {
      validNumberDecimal($(element));
    } else {
      if ($(element).valid()) {
        $(element).removeClass('form-error');
        $(element)
          .siblings('span.form-error')
          .remove();
      }
    }
  },
  onsubmit: true,
  errorElement: 'span',
  errorClass: 'form-error',
  validClass: 'form-success',
  rules: {
    postcode: {
      postalcodeBR: true,
    },
  },
});

function validNumberDecimal(inputElement) {
  var value = inputElement.val();
  var testValue = /^[0-9]+(,[0-9]{1,3})?$/.test(value);
  inputElement.removeClass('form-success');
  inputElement.removeClass('form-error');

  if (value) {
    inputElement.addClass(testValue ? 'form-success' : 'form-error');
  }
}

$('.js-modal-save').on('click', function(e) {
  $('.mask-number-decimal').each(function() {
    validNumberDecimal($(this));
  });

  if ($('.mask-number-decimal').hasClass('form-error')) {
    return;
  }

  if ($form.valid()) {
    $('.warning, .error').remove();
    $('.field-entry').removeClass('border-error');
    if ($('.js-modal-save').data('sincro') == '') {
      if (confirm('Deseja realmente sincronizar este produto?')) {
        sincronizarml();
      } else {
        return false;
      }
    } else {
      sincronizarml();
    }
  }
});

function sincronizarml() {
  $.ajax({
    url: 'index.php?route=module/mercadolivre/bulksetting/bulk_setting_validate&token=' + token,
    dataType: 'json',
    type: 'POST',
    data: $('#js-mlfichatecnica').serialize(),
    beforeSend: function() {
      $('.js-modal-save').addClass('btn-loading');
      $('.js-modal-save').attr('disabled', true);
      $('#bulk-setting').addClass('js-adm-modal-overlay-no-close');
    },
    complete: function() {},
    success: function(json) {
      if (json['error']) {
        $.each(json['error'], function(index, value) {
          if (index == 'mercaVariation') {
            $('#attribute_variation').prepend('<div class="col-xs-12"><span class="error">' + value + '</span></div>');
            $('#attribute_variation').addClass('border-error');
          } else {
            let idx_regex = index.replace(/([\[\]])/g,"\\$1"); //precisa fazer o regex do cochete por conta do jQuery

            $('#' + idx_regex).addClass('border-error');
            $('#' + idx_regex)
              .closest('.field-group')
              .append('<span class="error">' + value + '</span>');
          }
        });
        $('.js-modal-save').removeClass('btn-loading');
        $('#bulk-setting').removeClass('js-adm-modal-overlay-no-close');
      }
      if (json['results']) {
        $.each(json['results'], function(index, value) {
          if (value === false) {
            let idx_regex = index.replace(/([\[\]])/g,"\\$1"); //precisa fazer o regex do cochete por conta do jQuery

            $('#' + idx_regex)
              .addClass('border-error')
              .after('<span class="error">A categoria selecionada não aceita esta opção!</span>');
            $('.js-modal-save').removeClass('btn-loading');
            $('#bulk-setting').removeClass('js-adm-modal-overlay-no-close');
          }
        });
      }
      if (json['warning']) {
        window.notificationMsg(json['warning'], 'error');
      }
      if (json['success'] === true) {
        $('#js-mlfichatecnica').submit();
      }
      $('.js-modal-save').attr('disabled', false);
      $('.js-modal-save').removeClass('btn-loading');
      $('#bulk-setting').removeClass('js-adm-modal-overlay-no-close');
    },
  });
}

$('.js-mercaWarrantyType').on('change', function(e) {
  $tiposGarantia = $('[data-tempos-garantia]').data('tempos-garantia');

  var $this = $(this);
  if ($this.val() == $tiposGarantia.Tp_GaSemGarantia) {
    $('#mercaWarranty').val('');
    $('#mercaWarrantyTypeTime').val(0);
    $('#mercaWarranty').attr('readonly', true);
    $('#mercaWarrantyTypeTime').attr('readonly', true);
  } else {
    $('#mercaWarranty').attr('readonly', false);
    $('#mercaWarrantyTypeTime').attr('readonly', false);
  }
});

function getSelectCategory(element) {
  var ml_attr_row = '';
  element.on('change', function() {
    var $this = $(this);
    if ($this.val() == '') return false;
    $('#mercaId').val($this.val());
    $.ajax({
      url: 'index.php?route=module/mercadolivre/mercadolivre/category&token=' + token,
      dataType: 'json',
      data: { catId: $this.val(), listingType: $('#mercaListType').val() },
      beforeSend: function() {
        $('body').css('cursor', 'wait');
      },
      success: function(result) {
        $('body').css('cursor', 'default');
        $this.nextAll('select.mercadolivre_cat_selection').remove();
        if (result.categories.length > 0) {
          var select = $('<select>')
            .attr('name', 'mercadolivre_cat_selection[]')
            .addClass('mercadolivre_cat_selection field-entry field-entry-medium bottom-margin-small');
          var html = '<option value="">-Select-</option>';
          for (i = 0; i < result.categories.length; i++) {
            html += '<option value="' + result.categories[i].id + '">' + result.categories[i].name + '</option>';
          }
          select.html(html);
          getSelectCategory(select);
          $this.after(select);
        }
        getCategoryTree();
        if (result.listing_type != '') {
          $('#mercaListType').html(result.listing_type);
        }

        if (result.allowed == '1') {
          $('#category_tree_span').removeClass('category_nok');
          $('#category_tree_span').addClass('category_ok');
          getCatNotVariable($this.val());
          getCatVariation($this.val());
          getCatDimensions($this.val());
          getNewRequired($("[name='mercaCondition'] option:selected").val());
        } else {
          $('#attribute_not_variable').html('');
          $('#attribute_not_variable_title').addClass('hidden');
          $('#category_tree_span').removeClass('category_ok');
          $('#category_tree_span').addClass('category_nok');
          $('#category_shipping_preferences').addClass('hidden');
        }
        if (result.attribute_types == '1') {
          getCatAttr($this.val());
        } else {
          $('#ml_attr_row_wrapper').html('');
          $('#ml_attr_row_wrapper').hide();
        }
      },
    });
  });
}

function getCategoryTree() {
  var tree = '';
  $('select.mercadolivre_cat_selection option:selected').each(function() {
    if ($(this).val() != '') {
      if (tree == '') tree += $(this).text();
      else tree += ' » ' + $(this).text();
    }
  });
  $('#mercaTree').val(tree);
  $('#category_tree_span').html(tree);
}

function getCatNotVariable(catId) {
  var produtoid = 0;
  var type_product = null;
  if ($('#tabela_temp').hasClass('unique_produto')) {
    produtoid = $('#idproduto').attr('value');
    type_product = $('input[name="type_product[' + produtoid + ']"]').attr('value');
  }

  $.ajax({
    url: 'index.php?route=module/mercadolivre/bulksetting/renderAttrNotVariable&token=' + token,
    dataType: 'html',
    data: { initload: false, catId: catId, prodid: produtoid, type_products: type_product },
    beforeSend: function() {
      $('body').css('cursor', 'wait');
    },
    success: function(result) {
      $('body').css('cursor', 'default');
      if (result == '') {
        $('#attribute_not_variable').html('');
        $('#attribute_not_variable_title').addClass('hidden');
      } else {
        $('#attribute_not_variable').html(result);
        $('#attribute_not_variable_title').removeClass('hidden');
        eachAttributesDisabled();
      }
    },
  });
}

function getCatVariation(catId) {
  var produtoid = 0;
  var type_product = null;
  if ($('#tabela_temp').hasClass('unique_produto')) {
    produtoid = $('#idproduto').attr('value');
    type_product = $('input[name="type_product[' + produtoid + ']"]').attr('value');
  }

  $.ajax({
    url: 'index.php?route=module/mercadolivre/bulksetting/renderAttrVariable&token=' + token,
    dataType: 'html',
    data: { initload: false, catId: catId, prodid: produtoid, type_products: type_product },
    beforeSend: function() {
      $('body').css('cursor', 'wait');
    },
    success: function(result) {
      $('body').css('cursor', 'default');
      $('#attribute_variation').html(result);
    },
  });
}

function getCatDimensions(catId) {
  $.ajax({
    url: 'index.php?route=module/mercadolivre/mercadolivre/categoryDimensions&token=' + token,
    dataType: 'JSON',
    data: { catId: catId },
    beforeSend: function() {
      $('body').css('cursor', 'wait');
    },
    success: function(result) {
      $('body').css('cursor', 'default');
      if (result != '') {
        $('#category_shipping_preferences').removeClass('hidden');
        $('#category_shipping_preferences_items').html('');
        for (var key in result) {
          $('#category_shipping_preferences_items').prepend(
            '<span class="visible-block top-margin-small text-small bottom-border-gray">' + result[key] + '</span>'
          );
        }
      }
    },
  });
}

function getCatAttr(catId) {
  var product_id = $('[data-product-id]').data('product-id');
  $.ajax({
    url: 'index.php?route=module/mercadolivre/mercadolivre/attribute&token=' + token,
    dataType: 'json',
    data: { catId: catId, product_id: product_id },
    beforeSend: function() {
      $('body').css('cursor', 'wait');
    },
    success: function(result) {
      $('body').css('cursor', 'default');
      ml_attr_row = result.row;
      $('#ml_attr_row_wrapper').html(result.html);
      if (result.html == '') {
        $('#ml_attr_row_wrapper').hide();
      } else {
        $('#ml_attr_row_wrapper').show();
      }
    },
  });
}

function addMLAttribute() {
  var no_of_ml_attr = $('tr.ml_attr_row').length;
  no_of_ml_attr = parseInt(no_of_ml_attr) + 1;
  while ($('#ml_attr_row' + no_of_ml_attr).length != 0) {
    no_of_ml_attr++;
  }
  ml_attr_row_html = ml_attr_row;
  ml_attr_row_html = ml_attr_row_html.replace(/__AINDEX__/g, no_of_ml_attr);
  $('#ml_attribute tbody').append(ml_attr_row_html);
}

function removeMLAttribute(id) {
  $('#ml_attr_row' + id).remove();
}

function image_upload(field, thumb) {
  $('#dialog').remove();
  $('#content').prepend(
    '<div id="dialog" style="padding: 3px 0px 0px 0px;"><iframe src="index.php?route=common/filemanager&token=' +
      token +
      '&field=' +
      encodeURIComponent(field) +
      '" style="padding:0; margin: 0; display: block; width: 100%; height: 100%;" frameborder="no" scrolling="auto"></iframe></div>'
  );

  $('#dialog').dialog({
    title: $('[data-image-manager]').data('image-manager'),
    close: function(event, ui) {
      if ($('#' + field).attr('value')) {
        $.ajax({
          url:
            'index.php?route=common/filemanager/list&token=' +
            token +
            '&file=' +
            encodeURIComponent($('#' + field).attr('value')),
          dataType: 'text',
          success: function(text) {
            $('#' + thumb).replaceWith('<img src="' + text + '" alt="" id="' + thumb + '" />');
          },
        });
      }
    },
    bgiframe: false,
    width: 800,
    height: 400,
    resizable: false,
    modal: false,
  });
}

$('.tooltip-container').on({
  mouseover: function() {
    $(this)
      .find('.tooltip-content')
      .show();
  },
  mouseout: function() {
    $(this)
      .find('.tooltip-content')
      .hide();
  },
});

function disabledNa($this, element) {
  if ($this.prop('checked')) {
    element.attr('readonly', true);
  } else {
    element.attr('readonly', false);
  }
}

function eachAttributesDisabled() {
  $('.js-attributes-disabled').each(function(index) {
    var element = $(this)
        .closest('.field-group')
        .find('input[type=text], input[type=number], select'),
      $this = $(this);

    disabledNa($this, element);
  });

  $('.js-attributes-disabled').on('change', function(event) {
    var element = $(this)
        .closest('.field-group')
        .find('input[type=text], input[type=number], select'),
      $this = $(this);

    disabledNa($this, element);
  });

  $('.js-attributes-clear').on('click', function(event) {
    event.preventDefault();
    var field = $(this)
      .closest('.field-group')
      .find('.field-entry')
      .val('');
  });
}

eachAttributesDisabled();

getCatDimensions($('input[type=hidden][name=mercaId]').val());

getSelectCategory($('.mercadolivre_cat_selection'));

if ($('#mercaId').length > 0) {
  if ($('#mercaId').val() != '') getCatAttr($('#mercaId').val());
}

// Autocomplete
$("input[name='ml']").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) {
    $('#product-ml' + ui.item.value).remove();
    $('#product-ml').append(
      '<div id="product-ml' +
        ui.item.value +
        '">' +
        ui.item.label +
        '<img src="view/image/delete.png" alt="" /><input type="hidden" name="product_ml[]" value="' +
        ui.item.value +
        '" /></div>'
    );
    $('#product-ml div:odd').attr('class', 'odd');
    $('#product-ml div:even').attr('class', 'even');
    return false;
  },
  focus: function(event, ui) {
    return false;
  },
});
$('#product-ml').on('click', '#product-ml div img', function() {
  $(this)
    .parent()
    .remove();
  $('#product-ml div:odd').attr('class', 'odd');
  $('#product-ml div:even').attr('class', 'even');
});

$("[name='mercaCondition']").on('change', function() {
  getNewRequired($(this).val());
});

function getNewRequired(value) {
  var $elements = $('#attribute_not_variable').find('input, select');

  if (value === 'new') {
    $elements.each(function(index, element) {
      var $element = $(element);
      if ($element.attr('type') != 'hidden' && $element.data('new-required')) {
        $element.attr('required', 'req');
        $label = $element.closest('.field-group').find('label:first-child');
        $span = $label.find('.js-title-attr');
        $span.text($label.find('.js-attr-name').val() + ' *');
      }
    });
  }

  if (value === 'used') {
    $elements.each(function(index, element) {
      var $element = $(element);
      if ($element.attr('type') != 'hidden' && $element.data('new-required')) {
        $element.removeAttr('required').removeClass('form-error');
        $element.siblings('span.form-error').remove();
        $label = $element.closest('.field-group').find('label:first-child');
        $span = $label.find('.js-title-attr');
        $span.text($label.find('.js-attr-name').val() + ' (opicional)');
      }
    });
  }
}

getNewRequired($("[name='mercaCondition'] option:selected").val());
