import axios from 'axios';

document.addEventListener('DOMContentLoaded', function() {
  const configInstallments = document.querySelector('.js-advanced-installments-config');
  const inputInstallments = document.querySelector('.js-advanced-installments-number');

  const advancedInstallments = document.querySelector('.parcelamento-avancado');
  const defaultInstallments = document.querySelector('.parcelamento-padrao');
  const fieldInstallmentFee = document.querySelector('.field_installment_fee');

  const parcelamentoURL = configInstallments.dataset.url;
  const parcelamentoModulo = configInstallments.dataset.modulo;

  var load = true;

  function getParcelamento(e) {
    e.preventDefault();
    const vTypeInstallments = parseInt(configInstallments.value);
    var cardTypes = document.querySelectorAll('.js-credit-card-flag');

    if (cardTypes) {
      for (const iterator of cardTypes) {
        if (vTypeInstallments === Type_ConfigParcelamento.PorBandeira) {
          iterator.classList.add('js-content-options');
          iterator.querySelector('.credit-flag-configs').classList.add('js-check-options');
          if (iterator.querySelector('.js-check-options').checked) {
            iterator.querySelector('.credit-flag-configs').classList.remove('hidden');
          } else {
            iterator.querySelector('.credit-flag-configs').classList.add('hidden');
          }
        } else {
          iterator.classList.remove('js-content-options');
          iterator.querySelector('.credit-flag-configs').classList.add('hidden');
        }
      }
    }

    switch (vTypeInstallments) {
      case Type_ConfigParcelamento.PorParcela:
        const installments = inputInstallments.value;
        this.disabled = true;
        axiosApi({
          method: 'get',
          url: parcelamentoURL,
          params: { modulo: parcelamentoModulo, qtd_parcelas: installments, loadmodule: load },
        })
          .then(reponse => {
            load = false;
            advancedInstallments.innerHTML = reponse.data;
            defaultInstallments.classList.add('hidden');
            advancedInstallments.classList.remove('hidden');
            fieldInstallmentFee.classList.add('hidden');
          })
          .catch(err => {
            console.log(err);
          })
          .finally(() => {
            this.disabled = false;
          });
        break;
      case Type_ConfigParcelamento.Padrao:
        defaultInstallments.classList.remove('hidden');
        advancedInstallments.classList.add('hidden');
        fieldInstallmentFee.classList.remove('hidden');
        break;
      case Type_ConfigParcelamento.PorBandeira:
        advancedInstallments.classList.add('hidden');
        defaultInstallments.classList.add('hidden');
        fieldInstallmentFee.classList.remove('hidden');
        break;
      default:
        console.log('Tipo ' + configInstallments.value + ' não encontrado');
    }
  }

  configInstallments.addEventListener('change', getParcelamento);
  inputInstallments.addEventListener('blur', getParcelamento);

  configInstallments.dispatchEvent(new Event('change'));

  const buttonSave = document.querySelector('.js-submit-payment-form');
  const saveUrl = buttonSave.dataset.url;
  const redirectUrl = buttonSave.dataset.redirect;

  function saveConfigs(e) {
    e.preventDefault();
    let dataForm = document.querySelector('.js-main-form');
    let vInput, vSelect, vDiv;
    let span;
    this.classList.add('btn-loading');
    this.disabled = true;

    axiosApi({
      method: 'post',
      url: saveUrl,
      data: new FormData(dataForm),
      headers: { 'Content-Type': 'multipart/form-data' },
    })
      .then(({ data }) => {
        document.querySelectorAll('.form-error').forEach(el => el.remove());

        if (data.errors) {
          if (data.errors.warning) {
            notificationMsg(data.errors.warning, 'error');
          }
          $.each(data.errors, function(index, value) {
            span = document.createElement('span');
            span.classList.add('form-error', 'text-small');
            span.innerHTML = value;

            vDiv = document.querySelector('div[name=' + index + ']');
            if (vDiv) {
              vDiv.after(span);
            }
            vInput = document.querySelector('input[name=' + index + ']');
            if (vInput) {
              vInput.after(span);
            }
            vSelect = document.querySelector('select[name=' + index + ']');
            if (vSelect) {
              vSelect.after(span);
            }
            vInput = document.querySelector('.' + index);
            if (vInput) {
              vInput.after(span);
            }

            if(typeof value == 'object'){
              $.each(value, function(idx, obj) {
                $.each(obj, function(name, warning) {
                  span = document.createElement('span');
                  span.classList.add('form-error', 'text-small');
                  span.innerHTML = warning;

                  vInput = document.querySelector('input[name="' + index + '[' + idx + '][' + name + ']"]');
                  if (vInput) {
                    vInput.after(span);
                  }
                  vSelect = document.querySelector('select[name="' + index + '[' + idx + '][' + name + ']"]');
                  if (vSelect) {
                    vSelect.after(span);
                  }
                });
              });
            }
          });

          this.disabled = false;
          this.classList.remove('btn-loading');
        }

        if (data.success) {
          window.location.href = redirectUrl;
        }
      })
      .catch(err => {
        console.log(err);
      })
      .finally(() => {
        this.disabled = false;
        this.classList.remove('btn-loading');
      });
  }

  buttonSave.addEventListener('click', saveConfigs);
});
