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

function validNumberDecimal(inputElement) {
  var value = inputElement.val();
  var testValue = /^\d+(\.\d+)?$/.test(value);
  inputElement.removeClass('form-success');
  inputElement.removeClass('form-error');

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

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

  if (!valid) {
    valid = true;
    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?')) {
        sincronizarShopee();
      } else {
        return false;
      }
    } else {
      sincronizarShopee();
    }
  // }
});

function sincronizarShopee() {
  $.ajax({
    url: 'index.php?route=module/shopee/bulksetting/bulk_setting_validate&token=' + token,
    dataType: 'json',
    type: 'POST',
    data: $form.serialize(),
    beforeSend: function() {
      $('.js-modal-save').addClass('btn-loading');
      $('.js-modal-save').attr('disabled', true);
      $('#bulk-setting').addClass('js-adm-modal-overlay-no-close');
    },
    success: function(json) {
      if (json['error']) {
        $.each(json['error'], function(index, value) {
          if (index == 'shopeeVariation') {
            $('#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');
      } else if (json['warning']) {
        window.notificationMsg(json['warning'], 'error');
      } else if (json['success'] === true) {
        $('#js-shopeefichatecnica').submit();
      }
      $('.js-modal-save').attr('disabled', false);
      $('.js-modal-save').removeClass('btn-loading');
      $('#bulk-setting').removeClass('js-adm-modal-overlay-no-close');
    },
    error: function(xhr, ajaxOptions, thrownError) {
      console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
    },
  });
}

function getSelectCategory(element) {
  var ml_attr_row = '';
  element.on('change', function() {
    var $this = $(this);
    if ($this.val() == '') return false;
    $('#shopeeCategoryId').val($this.val());
    $.ajax({
      url: 'index.php?route=module/shopee/shopee/category&token=' + token,
      dataType: 'json',
      data: { catId: $this.val() },
      beforeSend: function() {
        $('body').css('cursor', 'wait');
      },
      error: function(xhr, ajaxOptions, thrownError) {
        console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
      },
      success: function(result) {
        $this.nextAll('select.shopee_cat_selection').remove();
        if (Object.keys(result).length > 0) {
          var select = $('<select>')
            .attr('name', 'shopee_cat_selection[]')
            .addClass('shopee_cat_selection field-entry field-entry-medium bottom-margin-small');
          var html = '<option value="">-Select-</option>';
          for (let category in result){
            html += '<option value="' + result[category].category_id + '">' + result[category].display_category_name + '</option>';
          }
          select.html(html);
          getSelectCategory(select);
          $this.after(select);
        }
        getCategoryTree();

        if (Object.keys(result).length == 0) {
          $('#category_tree_span').removeClass('category_nok');
          $('#category_tree_span').addClass('category_ok');
          getCatNotVariable($this.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();
        }
      },
      complete: function(result) {
        $('body').css('cursor', 'default');
      }
    });
  });
}

function getCategoryTree() {
  var tree = '';
  $('select.shopee_cat_selection option:selected').each(function() {
    if ($(this).val() != '') {
      if (tree == '') tree += $(this).text();
      else tree += ' » ' + $(this).text();
    }
  });
  $('#shopeeCategoryTree').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/shopee/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) {
      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();
      }
    },
    complete: function(result) {
      $('body').css('cursor', 'default');
    }
  });
}

function getCatAttr(catId) {
  var product_id = $('[data-product-id]').data('product-id');
  $.ajax({
    url: 'index.php?route=module/shopee/shopee/attribute&token=' + token,
    dataType: 'json',
    data: { catId: catId, product_id: product_id },
    beforeSend: function() {
      $('body').css('cursor', 'wait');
    },
    success: function(result) {
      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();
      }
    },
    complete: function(result) {
      $('body').css('cursor', 'default');
    }
  });
}

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

getSelectCategory($('.shopee_cat_selection'));

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

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

  var $element = $(this)
    .closest('.field-group')
    .find('.js-content-logistic-details');

  var $elementParent = $(this)
    .closest('.field-group')
    .find('.js-logistic-details-parent');

  var $elementButtonIcon = $(this)
    .closest('.field-group')
    .find('.js-button-logistic-icon');

  $element.toggleClass('hidden');
  $elementParent.toggleClass('bottom-border-gray');
  $elementButtonIcon.toggleClass('fa-angle-down');
  $elementButtonIcon.toggleClass('fa-angle-up');
});
