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

  $('.js-mkt-content-notices').on('click', '.js-mkt-noticies-close', function(event){
    event.preventDefault();
    $('.js-mkt-noticies-close-confirm').removeClass('hidden');
  });

  $('.js-mkt-content-notices').on('click', '.js-mkt-noticies-cancel', function(event) {
    event.preventDefault();
    $('.js-mkt-noticies-close-confirm').addClass('hidden');
  });

  $('.js-mkt-content-notices').on('click', '.js-mkt-noticies-remove', function(event) {
    event.preventDefault();

    var
      data = {},
      $this = $(this);

    data['noticies_id'] = (typeof $('.js-mkt-noticies-remove').data('noticies-id') != "undefined") ? $('.js-mkt-noticies-remove').data('noticies-id') : false ;

    $.ajax({
      url: 'index.php?route=module/mercadolivre/noticies/remove&token=' + token,
      type: 'post',
      data: data,
      dataType: 'json',
      beforeSend:function(){
        $this.addClass('btn-loading').attr('disabled', true);
      },
      complete:function(){
        $this.removeClass('btn-loading').attr('disabled', false);
      }
    }).done(function(json) {
      if(json['success']){
        location.reload();
      }
    });
  });

  $(document).on('click', '.desvincular', function(e) {
        if(confirm('Deseja realmente desvincular o produto? Esta ação excluirá o vínculo com mercado livre')){
            $.ajax({
                method: "GET",
                url: $(this).attr('data-link'),
            })
            .done(function( json ) {
                location.href = info.urlRetorno
            });
        }
  });

  function getSearchAdsMl(data) {
    var
    html = '<div class="js-adm-modal-container adm-modal-container-full">';
      html += '<div class="adm-modal-header">';
        html += '<div class="flex between-xs">';
          html += '<div class="padding-large">';
            html += '<span class="text-x-large text-dark text-bold">Vincular com o Mercado Livre</span>';
            html += '<a href="http://manual.futurasistemas.com.br/manual-do-sistema/vinculacao-dos-produtos-com-o-mercado-livre-faq23/" target="_blank" class="visible-inline-block left-margin-small" data-tooltip="Manual online"><i class="fas fa-question-circle text-large text-info"></i></a>';
            html += '<span class="text-medium text-gray visible-block top-margin-x-small">' + data['product_name'] + '</span>';
          html += '</div>';
          html += '<i class="fas fa-times text-small text-dark padding-large cursor-pointer ft-more-container js-adm-modal-close"></i>';
        html += '</div>';
      html += '</div>';
      html += '<div class="adm-modal-content padding-large">';
        html += '<label for="filter_vincular" class="field-label">Código Mercado Livre</label>';
        html += '<div class="field-entry-group">';
          html += '<input type="text" name="filter_vincular" value="" class="field-entry field-entry-large mask-alphanumeric-no-spaces">';
          html += '<a class="btn-default btn-primary btn-large-square js-btn-search-ads" data-modal-id="result-ads-ml" data-product-id="' + data['product_id'] + '" data-type-product="'+data['type_product']+'" ><i class="fas fa-search"></i></a>';
        html += '</div>';
        html += '<div class="js-search-ads-error"></div>'
        html += '<div class="border-gray top-margin-medium padding-medium">';
          html += '<span class="text-small visible-block">Você encontra o código no painel do Mercado Livre em <b>Vendas</b> <i class="fas fa-angle-right text-small"></i> <b>Anúncios</b></span>';
          html += '<img src="view/image/where-is-id-ml.jpg" alt="" class="visible-block top-margin-small" />';
        html += '</div>';
      html += '</div>';
      html += '<div class="adm-modal-footer padding-large"></div>';
    html += '</div>';
    return html;
  }

  function getResultAdsMl(data) {
    var html_variation, html_warning = '',
        type_product = data['type_product'];

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

      if (data['variations_count'] > (html_variation.match(/field-variation/g) || []).length){
          html_warning =
              '<span class="text-medium text-warning padding-medium visible-block">' +
                'O anúncio tem mais variações que a grade, ao vincular algumas podem ser removidas.' +
              '</span>';
      }

    var
    html = '<div class="js-adm-modal-container adm-modal-container-full">';
      html += '<div class="adm-modal-header">';
        html += '<div class="flex between-xs">';
          html += '<div class="padding-large">';
            html += '<span class="text-x-large text-dark text-bold">Vincular com o Mercado Livre</span>';
            html += '<a href="http://manual.futurasistemas.com.br/manual-do-sistema/como-vincular-produtos-com-o-mercado-livre-faq28/" target="_blank" class="visible-inline-block left-margin-small" data-tooltip="Manual online"><i class="fas fa-question-circle text-large text-info"></i></a>';
          html += '</div>';
          html += '<i class="fas fa-times text-small text-dark padding-large cursor-pointer js-adm-modal-close"></i>';
        html += '</div>';
      html += '</div>';
      html += '<div class="adm-modal-content padding-large">';
      if (html_warning) {
          html += '<div class="js-result-ads-ml-warning row no-space-xs middle-xs full-width border-warning background-warning rounded-medium visible-block bottom-margin-medium">';
          html += html_warning;
          html += '</div>';
      }
        html += '<div class="row no-space-xs middle-xs padding-medium full-width border-gray">';
          html += '<div class="col-xs-width-auto right-padding-medium">';
            html += '<img src=' + data['thumbnail'] + '" class="visible-block" />';
          html += '</div>';
          html += '<div class="col-xs">';
            html += '<span class="text-small text-dark text-uppercase visible-block">Cod.:' + data['mercaid'] + '<span class="horizontal-margin-small right-border-gray"></span>' + data['status'] + '</span>';
            html += '<a href="' + data['permalink'] + '" class="text-decoration-none vertical-margin-x-small visible-block" target="_blank">';
              html += '<span class="text-large text-primary">' + data['title'] + '</span>';
            html += '</a>'
            html += '<span class="text-medium text-dark visible-block">' + data['price'] + '</span>';
          html += '</div>';
      if (html_variation) {
          html += '<div class="row full-width small-space-xs padding-medium" id="attribute_variation">'
          html += html_variation;
          html += '</div>';
      }
        html += '</div>';
        html += '<div class="js-result-ads-ml-error"></div>';

      if (data.variations_has_relations){
      	html += data.html_catalog_link;
      }
      html += '</div>';
      html += '<div class="adm-modal-footer padding-large">';
        html += '<div class="flex end-xs">';
          html += '<button type="button" class="btn-default btn-medium btn-outline right-margin-small js-adm-modal-close">';
            html += '<span>Cancelar</span>';
          html += '</button>';
          html += '<button type="button" class="btn-default btn-medium btn-primary js-ads-ml-apply" data-product-id="' + data['product_id'] + '" data-mercaId="' + data['mercaid'] + '" data-type-product="'+type_product+'" >';
            html += '<span>Aplicar</span>';
          html += '</button>';
        html += '</div>';
      html += '</div>';
    html += '</div>';

    return html;
  }

  $('.js-mkt-vincular').on('click', function(event) {
    $('#search-ads-mkt').remove();
    var data = {};
    data['product_id']   = $(this).data('product-id');
    data['product_name'] = $(this).data('product-name');
    data['type_product'] = $(this).data('type-product');

    $(this).modalFutura({
      dataModalId: 'search-ads-mkt',
      appendModal: getSearchAdsMl(data),
      closeClickOut: false
    });
    $('#search-ads-mkt').find('input[name="filter_vincular"]').focus();

    $('#search-ads-mkt').find('.js-btn-search-ads').on('click', function(event) {
      $('#result-ads-ml').remove();
        $('.js-adm-modal-container .error, .js-adm-modal-container .text-error').remove();
        var
            data = {},
            $this = $(this),
        $getResultAdsMl;
      data['mercaid']       = $("input[name='filter_vincular']").val();
      data['product_id']    = $(this).data('product-id');
      data['type_product']  = $(this).data('type-product');

      $this.closest('.js-adm-modal-overlay').addClass('js-adm-modal-overlay-no-close');

      $.ajax({
        url: 'index.php?route=module/mercadolivre/vincular/searchads&token=' + token,
        type:'get',
        data: data,
        dataType: 'json',
        beforeSend: function() {
          $this.addClass('btn-loading');
        },
        complete: function() {
          $this.removeClass('btn-loading');
          $this.closest('.js-adm-modal-overlay').removeClass('js-adm-modal-overlay-no-close');
        },
        success: function(json) {
          if (json['error']) {
            $('.js-search-ads-error').append('<span class="top-margin-small text-medium text-error visible-block">' + json['error'] + '</span>');
          } else {
            $getResultAdsMl = getResultAdsMl(json['result']);
            $this.modalFutura({
              dataModalId: 'result-ads-ml',
              appendModal: $getResultAdsMl
            });

            $('#result-ads-ml').find('.js-ads-ml-apply').on('click', function(event) {
              var
              data = {},
              $this = $(this),
              mercaVariationColor = $("select[name='mercaVariationColor']")[0],
              mercaVariationSize = $("select[name='mercaVariationSize']")[0],
              mercaVariationSpecification = $("select[name='mercaVariationSpecification']")[0],
                catalog_links_select = $("select[name='catalog_product']");

              data['mercaid']       = $(this).data('mercaid');
              data['product_id']    = $(this).data('product-id');
              data['type_product']  = $(this).data('type-product');
              data['mercaVariationColor'] = (mercaVariationColor !== undefined ? mercaVariationColor.options[mercaVariationColor.selectedIndex].value : '');
              data['mercaVariationSize'] = (mercaVariationSize  !== undefined ? mercaVariationSize.options[mercaVariationSize.selectedIndex].value : '');
              data['mercaVariationSpecification'] = (mercaVariationSpecification !== undefined ? mercaVariationSpecification.options[mercaVariationSpecification.selectedIndex].value : '');
              data['mercaVariationSpecification'] = (mercaVariationSpecification !== undefined ? mercaVariationSpecification.options[mercaVariationSpecification.selectedIndex].value : '');

              catalog_links = [];
              if (catalog_links_select.length > 0) {
                for (var x = 0; x < catalog_links_select.length; x++) {
                  catalog_links[x] = {
                    "productId": catalog_links_select[x].dataset.productId,
                    "variationId": catalog_links_select[x].value
                  };
                }
              }
              data['catalogLinks'] = catalog_links;

              $this.closest('.js-adm-modal-overlay').addClass('js-adm-modal-overlay-no-close');

              $.ajax({
                url: 'index.php?route=module/mercadolivre/vincular/applyads&token=' + token + '&type_marketplace=' + info.type_marketplace + info.urlFilter,
                type:'post',
                data: data,
                dataType: 'json',
                beforeSend: function() {
                  $this.addClass('btn-loading');
                },
                complete: function() {
                  $this.removeClass('btn-loading');
                },
                success: function(json) {

                  if (json['error']) {
                      var error_append = '';
                      error_append = '<div class="top-margin-medium background-error border-error text-error text-medium padding-medium rounded-medium">' + json['error'];

                      if ((json['error_original']) && (json['error_original'] != json['error'])){
                          error_append += '<span class="js-toggle-original-error visible-block text-small cursor-pointer text-primary">Ver Original</span>';
                          error_append += '<span class="hidden">' + json['error_original'] + '</span>';
                      }

                      error_append += '</div>';

                    $('.js-result-ads-ml-error').html("").append(error_append);
                    $('.js-adm-modal-overlay').removeClass('js-adm-modal-overlay-no-close');

                    // vai para o topo pra visualizar a validação
                    $('#result-ads-ml').find('.adm-modal-content').scrollTop(0);

                  } else {
                    window.location.reload();
                  }
                },
                  error: function (request, status, error) {
                      console.log(request.responseText);
                  }
              });
            });

          }
        }
      });
    });
  });


  $('.js-mlerror-grade').on('click', function(){
     var
      $this = $(this),
       data = {};

       data['product_grid_id'] = $this.data('product-grid-id');
       data['urlretorno'] = info.urlRetorno;

    $.ajax({
      url: 'index.php?route=module/mercadolivre/error/grade&token=' + token,
      dataType: 'html',
      data: data,
      beforeSend:function() {
      },
      success: function(html) {
        $(this).modalFutura({
          appendModal: html
        });
      }
    });
  });

  $('body').on('click', '.js-grade-vincular, .js-grade-cancel-vincular', function(event) {
    $('.js-content-grade-vincular').toggleClass('hidden');
    $('.js-content-grade-option').toggleClass('hidden');
  });

  $('body').on('click', '.js-grade-vincular-apply', function (event) {
    var link      = $("input[name='anuncio']:checked").data('link');
    if(confirm("Deseja realmente transformar o anúncio selecionado em um anúncio de grade?")){
        location.href = link;
        $(this).addClass('btn-loading');
        $('body').append('<div style="position: fixed; width: 100%; height: 100%; top:0; left:0; z-index: 120;"></div>');
    }
  });

  $('body').on('click', 'input[name="anuncio"]', function(event){
    $('.js-grade-vincular-apply').prop('disabled', false);
    $.each( $('input[name="anuncio"]'), function( key, element ) {
        $(element).closest('label').find('.js-error-anuncio').remove();
        if(!element.checked){
            $(element).next().after('<span class="js-error-anuncio text-medium text-error">Este anúncio será finalizado.</span>');
        }
    });
  });

  $('body').on('click', '.js-grade-novo, .js-grade-cancel-novo', function (event) {
    $('.js-content-grade-novo').toggleClass('hidden');
    $('.js-content-grade-option').toggleClass('hidden');
  });

  $('body').on('click', '.js-grade-novo-apply', function (event) {
      var link = $(this).data('link');
      if(confirm("Deseja realmente criar um novo anúncio de grade?")){
          location.href = link;
          $(this).addClass('btn-loading');
          $('body').append('<div style="position: fixed; width: 100%; height: 100%; top:0; left:0; z-index: 120;"></div>');
      }
  });

  $('.js-filter-error').on('click', function() {

    url = 'index.php?route=module/mercadolivre/error&token=' + token + '&type=' + info.type.toString();

    var filter_product_ml_id = $('#filter_product_ml_id').val();

    if (filter_product_ml_id) {
      url += '&filter_product_ml_id=' + encodeURIComponent(filter_product_ml_id);
    }

    var filter_model = $('#filter_model').val();

    if (filter_model) {
      url += '&filter_model=' + encodeURIComponent(filter_model);

      var filter_content_model = $('#filter_content_model').val();

      if (filter_content_model) {
        url += '&filter_content_model=' + encodeURIComponent(filter_content_model);
      }

    }

    var filter_name = $('#filter_name').val();

    if (filter_name) {
      url += '&filter_name=' + encodeURIComponent(filter_name);
    }

    location = url;

  });

  $('.js-ml-features').on('click', function(e) {

    var
      $this     = $(this);

    $('#js-ml-features-content').remove();
    $(this).modalFutura({
      dataModalId: 'js-ml-features-content',
      appendModal: '<div class="js-adm-modal-container"><img src="../image/loader.gif" alt="" /></div>'
    });
    $('#js-ml-features-content').addClass('js-adm-modal-overlay-no-close');

    var
      data = {};
    data['codigo_barras'] = $(this).data('codigo-barra');
    data['product_id']    = $(this).data('product-id');
    data['type_product']  = $(this).data('type-product');

    $.ajax({
      url: 'index.php?route=module/mercadolivre/bulksetting/bulk_setting_features&token=' + token,
      dataType: 'html',
      type:'POST',
      data: data,
      beforeSend: function(){},
      complete: function(){},
      success: function(html) {
        $(this).modalFutura({
          dataModalId: 'js-ml-features-content',
          appendModal: html
        });

      }
    });

    $('#js-ml-features-content').removeClass('js-adm-modal-overlay-no-close');
  });

  $('body').on('click','.js-ml-features-apply', function(e) {

    if(confirm('Deseja aplicar as características na Ficha Técnica?')){

      $('#js-ml-features-content').remove();
      $(this).modalFutura({
        dataModalId: 'adm-modal-loading',
        appendModal: '<div class="js-adm-modal-container"><img src="../image/loader.gif" alt="" /></div>'
      });
      $('#adm-modal-loading').addClass('js-adm-modal-overlay-no-close');

      var data = {};
      data['atributos'] = $(this).data('atributos');
      data['pids'] = $(this).data('product-id');
      data['type_products'] = $(this).data('type-product');
      data['redirect'] = info.urlRetorno ;

      $.ajax({
        url: 'index.php?route=module/mercadolivre/bulksetting&token='+token+'&unique=true&type_marketplace=' + info.type_marketplace,
        type: 'GET',
        dataType: 'html',
        data: data
      }).done(function(html) {
        //precisou fazer com JSON parse por conta da bulksetting retornar JSON ao inves do HTML direto
        const modalAux = JSON.parse(html);
        $(this).modalFutura({
          dataModalId: 'bulk-ml-setting',
          appendModal: modalAux.html
        });
      });
      $('#adm-modal-loading').removeClass('js-adm-modal-overlay-no-close');
    }
  });
});