$(document).ready(function() {

  var token = $('body').data('token');

  $('select[name="to"]').bind('change', function(event) {
    $('#mail .to').hide();
    document.querySelector('#to_select').addEventListener('change', function(event) {
      const storeSelect = document.querySelector('#store_id');
      const marketingOption = new Option('Marketing', 'marketing');
      const padraoOption = new Option('Padrão', 'padrao');

      storeSelect.innerHTML = '';
  
      if (event.target.value == 'all_customers_abandoned_carts' || 
          event.target.value == 'customer_group' || 
          event.target.value == 'customer_all' || 
          event.target.value == 'newsletter') {
          storeSelect.add(marketingOption);
      } else if (event.target.value == 'customer' || 
                 event.target.value == 'product' || 
                 event.target.value == 'module_newsletter') {
          storeSelect.add(padraoOption);
          storeSelect.add(marketingOption);
      } 
    });
    $(
      '#mail #to-' +
        $(this)
          .attr('value')
          .replace('_', '-')
    ).show();
  });

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

  $.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);
      });
    },
  });

  $(document).ready(function() {
    var filterShoppingCart = $('#filter-shopping-cart');
  
    $('input[name="customers"], input[name="products"]').on('focus', function() {
      var type = $(this).attr('name').replace(/[s]$/, ''),
          $this = $(this),
          route = type == 'customer' ? 'sale/' + type : 'catalog/' + type,
          url = 'index.php?route=' + route + '/autocomplete';
      $this.autocomplete({
        delay: 500,
        source: function(request, response) {
          var filterCart = filterShoppingCart.is(':checked') ? '&filter_shopping_cart=true' : '';
          $.ajax({
            url: url + '&token=' + token + '&filter_name=' + encodeURIComponent(request.term) + filterCart,
            dataType: 'json',
            success: function(json) {
              response(
                $.map(json, function(item) {
                  return {
                    category: item.customer_group,
                    label: item.name,
                    value: item[type + '_id'],
                  };
                })
              );
            },
          });
        },
        select: function(event, ui) {
          var $scrollbox = $this.closest('.field').next('.scrollbox');
          var $item = $scrollbox.find('#' + type + ui.item.value).remove();
  
          if ($item && $item.length) return false;
  
          $scrollbox.append(
            '<div id="' +
              type +
              ui.item.value +
              '" class="scrollbox-item flex between-xs middle-xs vertical-padding-small"><span class="text-small text-dark text-ellipsis" style="width:80%;">' +
              ui.item.label +
              '</span><i class="fas fa-trash text-small right-margin-small text-gray padding-x-small"></i><input type="hidden" name="'+
              type +'[]" value="' +
              ui.item.value +
              '" /></div>'
          );
          return false;
        },
        focus: function(event, ui) {
          return false;
        },
      });
    });
  
    filterShoppingCart.on('change', function() {
      $('input[name="customers"]').val('');
      $('input[name="customers"]').focus();
    });
  });
  
  $('.fa-trash').live('click', function() {
    $(this)
      .parent()
      .remove();
  });

  $('.js-btn-csv').on('click', function(event) {
    event.preventDefault();
    $.ajax({
      url: 'index.php?route=sale/contact/gerarCsv&token=' + token,
      type: 'get',
      data: $('select, input, textarea'),
      dataType: 'json',
      beforeSend: function() {
        $('.js-btn-csv').addClass('btn-loading');
        $('.js-btn-csv').attr('disabled', true);
      },
      complete: function() {
        $('.js-btn-csv').removeClass('btn-loading');
        $('.js-btn-csv').attr('disabled', false);
      },
      success: function(json) {
        $('.warning, .success').remove();

        if (json['error']) {
          $('.box').before('<div class="warning full-width">' + json['error'] + '</div>');
        }

        if (json['success']) {
          window.location = 'index.php?route=sale/contact/downloadCsv&token=' + token;
          $('.box').before('<div class="success full-width">' + json['success'] + '</div>');
        }

        setInterval(function() {
          $('.warning, .success').fadeOut();
        }, 5000);
      },
    });
  });

  window.CKEDITOR.replace('message', {
    filebrowserBrowseUrl: 'index.php?route=common/filemanager&token=' + token,
    filebrowserImageBrowseUrl: 'index.php?route=common/filemanager&token=' + token,
    filebrowserFlashBrowseUrl: 'index.php?route=common/filemanager&token=' + token,
    filebrowserUploadUrl: 'index.php?route=common/filemanager&token=' + token,
    filebrowserImageUploadUrl: 'index.php?route=common/filemanager/sendFilesCkeditor&token=' + token,
    filebrowserFlashUploadUrl: 'index.php?route=common/filemanager&token=' + token,
  });

  $('.js-variables').each(function () {
    $(this).on('click', function () {
      var element = CKEDITOR.dom.element.createFromHtml('<span contenteditable="false">{{ ' + $(this).data('variableName') + ' }}</span>' );
      CKEDITOR.instances.message.insertElement(element);
    });
  });

  $('#button-send').click(function() {
    $('textarea[name="message"]').val(CKEDITOR.instances.message.getData());
    send();
  });

  function send(json = 'index.php?route=sale/contact/send&token=' + token,){

    $.ajax({
      url: json,
      type: 'post',
      data: $('select, input, textarea'),
      dataType: 'json',
      beforeSend: function() {
        $('#button-send').attr('disabled', true);
        $('#button-send').addClass('btn-loading');
      },
      complete: function() {
        $('#button-send').attr('disabled', false);
        $('#button-send').removeClass('btn-loading');
        $('.wait').remove();
      },
      success: function(json) {
        $('.success, .warning, .error').remove();

        if (json['error']) {
          if (json['error']['warning']) {
            $('.box').before('<div class="warning full-width" style="display: none;">' + json['error']['warning'] + '</div>');

            $('.warning').fadeIn('slow');
          }

          if (json['error']['subject']) {
            $("input[name='subject']").after('<span class="error">' + json['error']['subject'] + '</span>');
          }

          if (json['error']['message']) {
            $("textarea[name='message']")
              .parent()
              .append('<span class="error">' + json['error']['message'] + '</span>');
          }
        }

        if (json['next']) {
          if (json['success']) {
            $('.box').before('<div class="success full-width">' + json['success'] + '</div>');
            send(json['next']);
          }
        } else {
          if (json['success']) {
            $('.box').before('<div class="success full-width" style="display: none;">' + json['success'] + '</div>');
            $('.success').fadeIn('slow');
          }
        }
      },
    })
  }
});
