import axios from 'axios';

function initVincular() {

  const
    TOKEN = document.body.dataset.token,
    $VINCULAR = document.querySelectorAll('.js-mkt-vincular');

  for (var i = 0; i < $VINCULAR.length; i++) {
    $VINCULAR[i].addEventListener('click', getIndex);
  }

  function getIndex() {

    let
      product = {};

    product['product_id'] = this.dataset.productId;
    product['product_name'] = this.dataset.productName;
    product['product_type'] = this.dataset.typeProduct;
    product['type_marketplace'] = this.dataset.typeMarketplace;

    axios({
      headers: {'content-type': 'application/x-www-form-urlencoded'},
      method: 'post',
      url: `index.php?route=marketplace/Marketplacecalls/vincular&token=${TOKEN}`,
      data: objectToParam(product)
    })
      .then(function ({data}) {

        var modal = $('body').modalFutura({
          dataModalId: 'js-mkt-vincular-content',
          appendModal: data
        });

        for (let i = 0; i < modal.length; i++) {
          initAction(modal[i].get(0), product);
        }

      })
      .catch(function (error) {
        console.log(error);
      });
  }

  function initAction(context, product) {
    context = context || document;

    let
      $btnSearch = context.querySelector('.js-mkt-vincular-search');

    $btnSearch.addEventListener('click', function (event) {
      event.preventDefault();

      if(this.previousElementSibling.value!==''){
        product['mkt_product_code'] = this.previousElementSibling.value;
        getMktProductInfo(context, product, this);
      }

    });
  }


  function getMktProductInfo(context, product, $btnSearch) {

    $btnSearch.classList.add('btn-loading');

    axios({
      headers: {'content-type': 'application/x-www-form-urlencoded'},
      method: 'post',
      url: `index.php?route=marketplace/Marketplacecalls/vincular&function=info&token=${TOKEN}`,
      data: objectToParam(product)
    })
      .then(function ({data}) {

        $btnSearch.classList.remove('btn-loading');

        var modal = $('body').modalFutura({
          dataModalId: 'js-mkt-vincular-product-info',
          appendModal: data,
          prevModal: context
        });

        for (let i = 0; i < modal.length; i++) {
          initActionInfo(modal[i].get(0), product);
        }
      })
      .catch(function (error) {
        console.log(error);
      });

  }


  function initActionInfo(context, product) {
    context = context || document;

    let
      $btnVincularAccept = context.querySelector('.js-mkt-vincular-apply'),
      msgConfirm = '';

    $btnVincularAccept.addEventListener('click', function () {

      const
        $THIS = this,
        WARNING = document.querySelectorAll('#warning');

      if (typeof $THIS.dataset.sku === 'undefined' || $THIS.dataset.sku === '') {
        alert('Código do produto no marketplace não encontrado, contate a Futura Sistemas');
        return;
      }

      if (typeof $THIS.dataset.error !== 'undefined' && $THIS.dataset.error) {
        msgConfirm = $THIS.dataset.error;
      }

      if (confirm(msgConfirm + 'Deseja realmente vincular o produto?')) {
        product['mkt_product_id'] = $THIS.dataset.sku;

        var variationsLink = [];

        var gridVincData = $($($THIS).parent().parent().parent().find('.js-form-vinc-mkt-grid')[0]).find('.js-variation-link');
        gridVincData.each(function(index, element) {
          variationsLink.push({
            productId: element.value,
            mktProductId: element.dataset.mktProductId,
          });
        });

        product['grid_vinc_data'] = JSON.stringify(variationsLink);
        product['last_link'] = window.location.href;

        $THIS.classList.add('btn-loading');

        for (var i = 0; i < WARNING.length; i++) {
          WARNING[i].remove();
        }

        axios({
          headers: {'content-type': 'application/x-www-form-urlencoded'},
          method: 'post',
          url: `index.php?route=marketplace/Marketplacecalls/vincular&function=apply&token=${TOKEN}`,
          data: objectToParam(product)
        })
          .then(function ({data}) {

            if (data['error']) {
              const
                DIV = '<div id="warning" class="background-error border-error text-medium text-error padding-small horizontal-margin-large top-margin-small">' + data['error'] + '</div>';

              $THIS.closest('.js-adm-modal-container').querySelector('.adm-modal-header').insertAdjacentHTML('beforeend', DIV);
            }

            if (data['redirect']) {
              location.href = data['redirect']
            }

            $THIS.classList.remove('btn-loading');

          })
          .catch(function (error) {
            console.log(error);
          });
      }

    });

  }

}


if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initVincular);
} else {
  initVincular();
}