if (document.readyState === 'complete') {
  init();
} else {
  document.addEventListener('DOMContentLoaded', function() {
    init();
  });
}

function init() {
  window.info = JSON.parse(document.querySelector('[data-info]').getAttribute('data-info'));
  window.containerModuleList = document.getElementById('container_modules');

  window.language.add(window.info.languagesJS);
  window.language.load('module/special_action');

  document.getElementById('add_module').onclick = addModule;

  const MODULES = window.info.modules;

  for (const key in MODULES) {
    addModule(MODULES[key]);
  }

  function updateValues() {
    $("input[name='special_action_item']").attr(
      'value',
      $.map($('#special_action-product input'), element => element.value).join()
    );
  }

  const INPUT = $('input[name=special_action]');
  INPUT.autocomplete({
    delay: 500,
    source: function(request, response) {
      $.ajax({
        url:
          'index.php?route=module/special_action/autocomplete&token=' +
          TOKEN +
          '&filter_special=' +
          encodeURIComponent(request.term),
        dataType: 'json',
        complete: function() {
          $('.js-clear-input').removeClass('hidden');
        },
        success: function(json) {
          response(
            $.map(json, function(item) {
              return {
                label: item.description,
                value: item.order_promotion_id,
              };
            })
          );
        },
      });
    },
    select: function(event, ui) {
      if ($('#special_action-product' + ui.item.value).length > 0) {
        alert('Este produto já foi adicionado a lista!');
        return false;
      }

      let container = $('#special_action-product');
      container.append(`
        <div id="special_action-product${ui.item.value}" class="scrollbox-item flex between-xs">
          <span class="text-small text-dark">${ui.item.label}</span>
          <i class="fas fa-trash-alt text-small right-margin-small text-error"></i>
          <input type="hidden" value="${ui.item.value}">
        </div>
      `);
      container.scrollTop(2000);

      updateValues();

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

  $('#special_action-product').on('click', 'i', function() {
    $(this)
      .parent()
      .remove();
    updateValues();
  });
}

let moduleId = '';
moduleId++;

function initRemoveModules(context) {
  context = context || document;
  let removeButtons = context.querySelectorAll('.js-remove-module');
  for (let i = 0; i < removeButtons.length; i++) {
    removeButtons[i].onclick = removeModule;
  }
}

function removeModule() {
  this.closest('.js-module-row').remove();
}

function initDisabledStyleApp(context) {
  context = context || document;
  let positionEntries = context.querySelectorAll('.js-special-action-module-position');
  for (let i = 0; i < positionEntries.length; i++) {
    const POSITION = positionEntries[i];
    POSITION.onchange = disabledStyleApp;
    POSITION.dispatchEvent(new Event('change', { bubbles: true }));
  }
}

function disabledStyleApp() {
  const STYLE = this.closest('.js-module-row').querySelector('.js-special-action-module-style');
  if (this.value == Type_ModulePosition.Tp_AppMobile) {
    STYLE.disabled = true;
  } else {
    STYLE.disabled = false;
  }
}

function addModule(module = {}) {
  const { layout_id, status, position, limit, style, sort_order } = module;
  const CONTAINER_MODULE = document.createElement('div'),
    ERROR_LIMIT = window.info.error_limit,
    ERROR_SORT_ORDER = window.info.error_sort_order,
    STATUS = Type_Status.getEnumList(),
    POSITION = window.info.positions,
    LAYOUTS = window.info.layouts,
    STYLES = Type_ActionPromotionStyle.getEnumList(),
    HTML = `<div class="row x-small-space-xs">
      <div class="col-md">
        <label class="fiel field-medium">
          <span class="field-label">${language.get('entry_layout')}</span>
          <select class="field-entry" name="special_action_module[${moduleId}][layout_id]">
           ${LAYOUTS.map(
             layout =>
               `<option value="${layout.layout_id}" ${layout_id == layout.layout_id ? 'selected' : ''}>${
                 layout.name
               }</option>`
           ).join('')}
          </select>
        </label>
      </div>
      <div class="col-md">
        <label class="fiel field-medium">
          <span class="field-label">${language.get('entry_position')}</span>
          <select name="special_action_module[${moduleId}][position]" class="field-entry js-special-action-module-position">
          ${Object.keys(POSITION)
            .map(key => `<option value="${key}" ${key == position ? 'selected' : ''}>${POSITION[key]}</option>`)
            .join('')}
          </select>
        </label>
      </div>
      <div class="col-md-width-auto">
        <label class="fiel field-medium">
          <span class="field-label">${language.get('entry_limit')}</span>
          <input type="text" class="field-entry mask-number2" name="special_action_module[${moduleId}][limit]"
            value="${typeof limit !== 'undefined' ? limit : 6}" size="1">
          ${ERROR_LIMIT[moduleId] ? `<span class="text-error text-small">${ERROR_LIMIT[moduleId]}</span>` : ''}
        </label>
      </div>
      <div class="col-md">
        <label class="fiel field-medium">
          <span class="field-label">${language.get('entry_style')}</span>
          <select name="special_action_module[${moduleId}][style]" class="field-entry js-special-action-module-style">
          ${Object.keys(STYLES)
            .map(key => `<option value="${key}" ${key == style ? 'selected' : ''}>${STYLES[key]}</option>`)
            .join('')}
          </select>
        </label>
      </div>
      <div class="col-md">
        <label class="fiel field-medium">
          <span class="field-label">${language.get('entry_status')}</span>
          <select class="field-entry" name="special_action_module[${moduleId}][status]">
          ${Object.keys(STATUS)
            .map(key => `<option value="${key}" ${key == status ? 'selected' : ''}>${STATUS[key]}</option>`)
            .join('')}
          </select>
        </label>
      </div>
      <div class="col-md-width-auto">
        <label class="fiel field-medium">
          <span class="field-label">${language.get('entry_sort_order')}</span>
          <input type="text" name="special_action_module[${moduleId}][sort_order]"
          value="${typeof sort_order !== 'undefined' ? sort_order : 0}" size="1" class="field-entry mask-number2">
          ${
            ERROR_SORT_ORDER[moduleId] ? `<span class="text-error text-small">${ERROR_SORT_ORDER[moduleId]}</span>` : ''
          }
        </label>
      </div>
      <div class="col-xs-12 col-md-width-auto">
        <div class="padding-medium cursor-pointer top-margin-medium js-remove-module"
        data-tooltip="${language.get('button_remove')}"
        >
          <i class="fas fa-trash text-gray"></i>
        </div>
      </div>
    </div>`;
  CONTAINER_MODULE.setAttribute(
    'class',
    'background-white padding-large bottom-margin-medium shadow-small adm-focus-within js-module-row'
  );
  CONTAINER_MODULE.innerHTML = HTML;
  window.containerModuleList.prepend(CONTAINER_MODULE);
  initRemoveModules(CONTAINER_MODULE);
  initDisabledStyleApp(CONTAINER_MODULE);

  moduleId++;
}
