import {elementsNeutralColor, elementsColorPredominante, elementsColorSecundaria, elementsColorPredominanteHover,
  setColorElement, hoverColor, getColorHexElement, setColors, desmarcaCor, isColor}
  from '@admin/view/javascript/colors.js';

$(document).ready(function() {
  var token = document.body.dataset.token;

  if (window.errorCeo) {
    document.querySelector('.js-error-ceo').addEventListener('click', function() {
      document.querySelector('.js-error-ceo-message').classList.toggle('hidden');
    });

    closeQuickConfig();
  }

  habilitast();
  closeQuickConfig();

  const openFileManager = document.querySelectorAll('.js-open-file-manager');

  for (const item of openFileManager) {
    item.addEventListener('click', () => {
      handleFileManager();
    });
  }

  function handleFileManager() {
    window.dispatchEvent(
      new CustomEvent('vue-file-manager', {
        detail: {
          callbackFunction: file => {
            document.querySelector('#config_logo').value = 'data/' + file.file;
            document.querySelector('#img_config_logo').src = file.thumbnail;
          },
          options: {
            maxWidth: 400,
            maxHeight: 150,
            minWidth: 32,
            minHeight: 32,
            square: false,
            extensions: ['jpg', 'jpeg', 'png', 'pdf'],
          },
        },
      })
    );
  }

  const telephoneContainer = document.querySelector('.js-telephone-container');
  window.info = JSON.parse(document.querySelector('[data-info]').getAttribute('data-info'));

  const configTelephones = window.info.config_telephone;

  let telephoneIndex = '';
  telephoneIndex++;

  for (const key in configTelephones) {
    addTelephone(configTelephones[key]);
  }

  document.querySelector('.js-add-telephone').onclick = addTelephone;

  if (!configTelephones) {
    document.querySelector('.js-add-telephone').click();
  }

  function initRemoveTelephone(context) {
    context = context || document;
    var telephoneList = context.querySelectorAll('.js-remove-telephone');
    for (let i = 0; i < telephoneList.length; i++) {
      telephoneList[i].onclick = removeTelephone;
    }
  }

  function removeTelephone() {
    this.closest('.js-telephone').remove();
    telephoneIndex--;

    const telephoneButton = document.querySelector('.js-add-telephone');

    if (telephoneIndex <= 10 && telephoneButton.hasAttribute('disabled', 'disabled')) {
      telephoneButton.removeAttribute('disabled');
    }
  }

  function addTelephone(configTelephone = {}) {
    if (telephoneIndex == 10) {
      document.querySelector('.js-add-telephone').setAttribute('disabled', 'disabled');
    }

    new Type(typePhone);
    const { type, numero, display, display_header } = configTelephone;
    const TELEPHONE = window.Type_Phone.getEnumList(),
      telephoneItem = document.createElement('div'),
      HTML = `
        <div class="row small-space-xs">
          <div class="col-xs-6">
            <label class="field field-medium bottom-padding-medium">
              <span class="field-label">Tipo</span>
              <select type="text" name="config_telephone[${telephoneIndex}][type]" class="field-entry">
                ${Object.keys(TELEPHONE)
                  .map(key => `<option value="${key}"  ${key == type ? 'selected' : ''}>${TELEPHONE[key]}</option>`)
                  .join('')}
              </select>
            </label>
          </div>
          <div class="col-xs-6">
            <label class="field field-medium bottom-padding-medium">
              <span class="field-label">Número</span>
              <input type="text" name="config_telephone[${telephoneIndex}][numero]" class="field-entry mask-celular"
              value="${typeof numero !== 'undefined' ? numero : ''}">
            </label>
          </div>
        </div>
        <div class="bottom-margin-medium">
          <label class="checkbox checkbox-medium checkbox-inline">
            <input type="checkbox" name="config_telephone[${telephoneIndex}][display]"
            ${display ? 'checked' : ''} class="checkbox-entry" value="1">
            <span class="checkbox-text">Mostrar no rodapé</span>
          </label>
          <label class="checkbox checkbox-medium checkbox-inline">
            <input type="checkbox" name="config_telephone[${telephoneIndex}][display_header]"
            ${display_header ? 'checked' : ''} class="checkbox-entry" value="1">
            <span class="checkbox-text">Mostrar no topo</span>
          </label>
        </div>
        <button type="button" class="btn-default btn-outline btn-medium js-remove-telephone">
          <span>Excluir</span>
        </button>
        `;

    telephoneItem.setAttribute('class', 'bottom-padding-medium js-telephone');
    telephoneItem.innerHTML = HTML;

    telephoneContainer.prepend(telephoneItem);
    initRemoveTelephone(telephoneItem);

    telephoneIndex++;
  }

  $('.js-habilitar-st').on('click', function() {
    habilitast();
  });

  function habilitast() {
    let element = $('.js-empresa-st'),
      $this = $("input[name='config_mode_st']:checked"),
      ramo = $("input[name='tipo_ramo']:checked").val();

    if ($this.is(':checked') && ramo == 0) {
      element.removeClass('hidden');
    } else {
      element.addClass('hidden');
    }
  }

  function closeQuickConfig() {
    $('.close-quick-config').on('click', function(e) {
      e.preventDefault();
      $('.overlay').remove();
    });
  }

  var finishSteps = $('.quick-setup-container').data('finish-steps');
  var currentStep = parseInt($('.quick-setup-container').data('current-step'), 10);

  function displayErrors(json) {
    $('.error')
      .prev('input.field-entry')
      .on('keydown', function() {
        $(this).removeClass('border-error');
        $(this)
          .next('.error')
          .remove();
        $(this)
          .attr('placeholder')
          .remove();
      });
    if (json['error']['warning']) {
      $('.quick-setup-title').after(
        '<span class="quick-setup-error-warning text-error background-error border-error padding-large rounded-medium top-margin-large">' +
          json['error']['warning'] +
          '</span>'
      );
      $('.quick-setup-error-warning')
        .css('display', 'block')
        .delay(1000)
        .fadeOut(400, $('.quick-setup-error-warning').remove());
    }
    if (json['error']['warning']) {
      $('.quick-setup-title').after('<span class="error">' + json['error']['warning'] + '</span>');
    }
    $.each(json['error'], function(key, value) {
      if (json['error'][key] != '' && key != 'error_warning') {
        var errSeletorID = '#' + key.replace('error_', '');
        if ($(errSeletorID).val() != '') {
          $(errSeletorID)
            .addClass('border-error')
            .focus();
          $(errSeletorID).after('<span class="error">' + json['error'][key] + '</span>');
        } else {
          $(errSeletorID)
            .addClass('border-error')
            .focus();
          $(errSeletorID).attr('placeholder', json['error'][key]);
        }
      }
    });
  }

  function updateFinishStep() {
    finishSteps.push(String(currentStep));
    $.ajax({
      url: 'index.php?route=extension/easyconfigure/updateFinishStep&token=' + token,
      type: 'post',
      dataType: 'json',
      data: { finish_steps: finishSteps },
    }).fail(function() {
      console.log('error');
    });
  }

  function updateCurrentStep(step) {
    currentStep = step;
    $.ajax({
      url: 'index.php?route=extension/easyconfigure/updateCurrentStep&token=' + token,
      type: 'post',
      dataType: 'json',
      data: { current_step: currentStep },
    }).fail(function() {
      console.log('error');
    });
  }

  function updateStepLineView(step, finish) {
    if (typeof finish != 'undefined' && finish) {
      updateFinishStep();
      $('.stepline-step-' + currentStep)
        .addClass('finish')
        .find('i')
        .removeClass()
        .addClass('fas fa-check');
    } else {
      var $currentStepLine = $('.stepline-step-' + currentStep);
      if ($.inArray($currentStepLine.attr('id'), finishSteps) == -1) {
        $currentStepLine
          .find('i')
          .removeClass()
          .addClass('fas fa-minus');
      } else {
        $currentStepLine
          .find('i')
          .removeClass()
          .addClass('fas fa-check');
      }
    }

    if (step === 3) {
      var ramo = $("input[name='tipo_ramo']:checked").val(),
        element = $('.js-config-st');
      if (ramo == 0) {
        element.removeClass('hidden');
      } else {
        element.addClass('hidden');
      }
    }

    $('.current').removeClass('current');
    $('.stepline-step-' + step)
      .addClass('current')
      .find('i')
      .removeClass()
      .addClass('fas fa-pencil-alt');
  }

  function gotoStep(step, finish) {
    $('.step-' + step)
      .removeClass('hidden')
      .siblings('div')
      .addClass('hidden');
    updateStepLineView(step, finish);
    updateCurrentStep(step);
  }

  gotoStep(currentStep);

  $('.js-next-step').on('click', function(e) {
    e.preventDefault();
    gotoStep(currentStep + 1);
  });
  $('.js-prev-step').on('click', function(e) {
    e.preventDefault();
    gotoStep(currentStep - 1);
  });
  $('.js-close').on('click', function(e) {
    e.preventDefault();
    $('.overlay').remove();
  });
  $('.js-remember-me').on('click', function(e) {
    e.preventDefault();
    // code action
    $('.overlay').remove();
  });
  $('.js-container-stepline').on('click', function() {
    if (currentStep == 2) {
      return false;
    }
    gotoStep(parseInt($(this).attr('id'), 10));
  });

  $('.js-btn-clear-image').on('click', function() {
    $('#img_config_logo').attr('src', 'view/image/sem-imagem.png');
    $('#config_logo').val('');
  });


  $('.js-btn-save-and-go-next').on('click', function() {
    var dataArray = $(
      '#' +
        $(this)
          .attr('id')
          .replace('send-', '')
    ).serializeObject();
    var step = parseInt(
      $(this)
        .attr('id')
        .replace('send-form-step-', ''),
      10
    );
    if (dataArray == '') {
      dataArray = {};
    }

    if (step == 4) {
      dataArray['cores'] = setColors();
    }

    if (step == 6) {
      var redesSociais = {
        wg24_facebook_url: '',
        wg24_twitter_url: '',
        wg24_google_url: '',
        wg24_rss_url: '',
        wg24_pinterest_url: '',
        wg24_linking_url: '',
        wg24_youtub_url: '',
        wg24_instagram_url: '',
        wg24_blogger_url: '',
      };
      for (var key in redesSociais) {
        if (dataArray[key]) {
          redesSociais[key] = dataArray[key];
        }
      }
      dataArray = redesSociais;
    }

    dataArray['current_step'] = currentStep;
    dataArray['finish_steps'] = finishSteps;
    dataArray['step'] = step;

    $.ajax({
      url: 'index.php?route=extension/easyconfigure/saveData&token=' + token,
      type: 'post',
      dataType: 'json',
      data: param(dataArray),
    })
      .done(function(json) {
        $('.error').remove();
        $('.field-entry').removeClass('border-error');
        if (typeof json['error'] != 'undefined') {
          displayErrors(json);
        } else {
          gotoStep(currentStep + 1, true);
          habilitast();
        }
      })
      .fail(function(json) {
        console.log('error');
        console.log(json);
      });
  });
  $('.js-remember-me, .js-cancel').on('click', function(e) {
    if ($(this).hasClass('js-cancel')) {
      var value = 2;
    } else {
      var value = 1;
    }
    e.preventDefault();
    $.ajax({
      url: 'index.php?route=extension/easyconfigure/rememberOrCancel&token=' + token,
      type: 'post',
      dataType: 'json',
      data: { quick_config: value },
    })
      .done(function(json) {
        $('.overlay').remove();
      })
      .fail(function(json) {
        console.log('error');
      });
  });

  $('.btn-connect-test').on('click', function(event) {
    event.preventDefault();

    $.ajax({
      url: 'index.php?route=setting/setting/connectEmail&token=' + token,
      type: 'POST',
      data: {
        config_smtp_host: $("input[name='config_smtp_host']").val(),
        config_smtp_username: $("input[name='config_smtp_username']").val(),
        config_smtp_password: $("input[name='config_smtp_password']").val(),
        config_smtp_port: $("input[name='config_smtp_port']").val(),
        config_smtp_timeout: $("input[name='config_smtp_timeout']").val(),
        config_mail_protocol: $("select[name='config_mail_protocol']").val(),
        config_mail_parameter: $("input[name='config_mail_parameter']").val(),
        config_email_test: $("input[name='config_email_test']").val(),
        config_owner: $("input[name='config_owner']").val(),
      },
      dataType: 'json',
      beforeSend: function() {
        $('.btn-connect-test').addClass('btn-loading');
        $('.btn-connect-test').attr('disabled', true);
      },
      complete: function() {
        $('.btn-connect-test').removeClass('btn-loading');
        $('.btn-connect-test').attr('disabled', false);
      },
      success: function(json) {
        $('.error, .success, .warning').remove();
        $('.field-entry-error').removeClass();

        if (json['success']) {
          $('.btn-connect-test').after(
            '<span class="success visible-block top-margin-small">' + json['success'] + '</span>'
          );
        } else {
          $('.btn-connect-test').after(
            '<span class="error visible-block top-margin-small">Não foi possível enviar o email com as configurações atuais</span>'
          );
        }
      },
      error: function(json) {
        if (json['warning']) {
          $.each(json['warning'], function(key, value) {
            $("input[name='" + key + "']")
              .addClass('field-entry-error')
              .after('<span class="error">' + value + '</span>');
          });

          if (json['warning']['connect']) {
            $('.btn-connect-test').after(
              '<span class="warning visible-block top-margin-small">' + json['error']['connect'] + '</span>'
            );
          }

          $('.btn-connect-test')
            .removeClass('btn-primary')
            .addClass('btn-error');
        } else {
          console.log('Erro na validação do e-mail do easyconfigure');
        }
      },
    });
  });

  //Inverte as cores dos inputs e marca na paleta
  $('body').on('click', '#exchange-colors', function() {
    var change = getColorHexElement('primary_color');
    setColorElement('primary_color', getColorHexElement('secondary_color'));
    setColorElement('secondary_color', change);
    $('.setted-color').each(function() {
      if ($(this).text() == 1) {
        $(this).text(2);
      } else if ($(this).text() == 2) {
        $(this).text(1);
      }
    });
  });

  var contColor = 0;
  $(document).on('click', '.input-color-pallet', function() {
    var element = 'secondary_color';
    if (contColor > 2 || contColor == 0) {
      contColor = 1;
      element = 'primary_color';
    }

    desmarcaCor(contColor);

    $(this)
      .find('.setted-color')
      .text(contColor)
      .show();
    setColorElement(
      element,
      getColorHexElement(
        $(this)
          .find('input')
          .attr('name')
      )
    );
    contColor++;
  });

  $(document).on('click', '#corespadroes', function() {
    var colorThief = new ColorThief();

    var img = new Image();
    img.src = $('#img_config_logo').attr('src');

    var vpaleta = colorThief.getPalette(img, 7);
    var vcor = colorThief.getColor(img);

    var paletaPosition = 0;
    for (paletaPosition = 0; paletaPosition < vpaleta.length - 1; paletaPosition++) {
      var rgb1 = String(vcor).split(',');
      var rgb2 = String(vpaleta[paletaPosition]).split(',');
      var soma = 0;

      for (var i = 0; i < 3; i++) {
        soma += Math.abs(rgb1[i] - rgb2[i]);
      }

      if (soma > 75) {
        break;
      }
    }

    var vcorpredominante = window.chroma(vcor).hex(); //window.chroma(vcor).hex();
    var vcorsecundaria = window.chroma(vpaleta[paletaPosition]).hex(); //window.chroma(vpaleta[0]).hex();

    setColorElement('primary_color', vcorpredominante);
    setColorElement('secondary_color', vcorsecundaria);

    $('.color-pallet').show();
    $('.setted-color').hide();
    $('#color0 ~ .setted-color')
      .text(1)
      .show();
    $('#color' + (paletaPosition + 1) + ' ~ .setted-color')
      .text(2)
      .show();

    setColorElement('color0', vcorpredominante);
    for (var i = 0; i < vpaleta.length; i++) {
      setColorElement('color' + (i + 1), window.chroma(vpaleta[i]).hex());
    }
  });

  $(document).on('change', '#primary_color', function() {
    if (isColor($(this).val())) {
      desmarcaCor(1);
    }
  });
  $(document).on('change', '#secondary_color', function() {
    if (isColor($(this).val())) {
      desmarcaCor(2);
    }
  });
});

//==================================== Add ===================================
$('body').on('click', '.redes button', function(e) {
  e.preventDefault();
  var html = '';
  html += '<div class="col-xs-12 field-group">';
  html += '<div class="field-entry-group rel">';
  html += '<label class="field field-medium">';
  html +=
    '<input type="text" name="' +
    $(this).data('id') +
    '" id="' +
    $(this).data('id') +
    '" id="' +
    $(this).data('id') +
    '" id="' +
    $(this).data('id') +
    '" class="field-entry" value="">';
  html += '</label>';
  html +=
    '<button type="button" class="btn-default btn-medium-square btn-error js-btn-remove-redes style="display: none;">';
  html += '<i class="fas fa-trash"></i>';
  html += '</button>';
  html += '</div>';
  html += '</div>';

  $('.rede-inputs').append(html);
  var $fieldGroup = $('.rede-inputs .field-group').filter(':last');
  $fieldGroup.find('.field-entry').css({
    'max-width': '0',
    visibility: 'hidden',
  });
  $fieldGroup.find('.js-btn-remove-redes').css({
    'max-width': '0',
    'padding-right': 0,
    'padding-left': 0,
    display: 'block',
  });
  var $this = $(this);
  var thisTopFinal =
    $('.field-entry')
      .filter(':last')
      .offset().top - $this.offset().top;
  var thisLeft = $this.offset().left - $this.closest('.content-box').offset().left;
  $this
    .closest('.redes')
    .css({
      position: 'absolute',
      top: '0',
      left: thisLeft,
      'z-index': '5',
    })
    .animate(
      {
        top: thisTopFinal,
        left: '0',
      },
      function() {
        $this.addClass('js-btn-icon');
        var $fieldEntryGroup = $fieldGroup.find('.field-entry-group');
        $this.clone().prependTo($fieldEntryGroup);
        $this.closest('.redes').remove();
        $fieldGroup
          .find('.field-entry')
          .css({
            visibility: 'visible',
          })
          .animate(
            {
              'max-width': '100%',
            },
            function() {
              $fieldGroup.find('.js-btn-remove-redes').animate({
                'max-width': '30px',
                'padding-right': '.6rem',
                'padding-left': '.6rem',
              });
            }
          );
      }
    );
});

//================================ Remove ====================================
$('body').on('click', '.js-btn-remove-redes', function(e) {
  e.preventDefault();
  var $this = $(this);
  var $fieldGroup = $this.closest('.field-group');
  var $button = $this.siblings('.js-btn-icon');

  var buttonClass = $button.attr('class');
  var redeClass = buttonClass.substring(0, buttonClass.indexOf(' '));
  var title = $button.attr('title');
  var dataId = $button.data('id');
  $fieldGroup.find('.js-btn-remove-redes').animate(
    {
      'max-width': 0,
      'padding-right': 0,
      'padding-left': 0,
      display: 'block',
    },
    function() {
      $fieldGroup.find('.js-btn-remove-redes').remove();
      if ($button.find('img')) {
        var iconImg = $button.find('img').attr('src');
      }
      var iconClass = $button.find('i').attr('class');

      $fieldGroup.find('.field-entry').animate(
        {
          'max-width': 0,
          'padding-right': 0,
          'padding-left': 0,
        },
        function() {
          $fieldGroup.find('.field-entry').css({
            display: 'none',
          });
          var $social = $('.social');
          if ($('.redes').length > 0) {
            // valores para inserir depois de um botão já existente
            var $rede = $('.redes').filter(':last');
            var heightFinal = $rede.height();
            var thisTopFinal = $button.offset().top - $rede.find('button').offset().top;
            var thisLeftFinal =
              $rede.offset().left + $rede.outerWidth() - $rede.closest('.content-box').offset().left + 4; //4px referente ao padding da direita da $rede
          } else {
            // valores para inserir quanto não tem nenhum botão no container
            var heightFinal = 36;
            var thisTopFinal = $button.offset().top - $social.offset().top + 4; // +4 referente ao padding de $social
            var thisLeftFinal = $('.social').width() / 2 - $button.width() / 2;
          }

          $button.removeClass('rounded-left-x-small').addClass('rounded-x-small');
          $button.css({
            height: heightFinal,
            position: 'absolute',
            padding: '.8rem', //=====================errado
            top: '0',
            left: '0',
            'z-index': '5',
          });
          $button.animate(
            {
              top: '-' + thisTopFinal + 'px',
              left: thisLeftFinal,
            },
            function() {
              $button.addClass('rounded-x-small');

              html = '';
              html += '<div class="padding-x-small redes">';
              html +=
                '<button type="button" class="' +
                redeClass +
                ' btn-default btn-medium-square" style="color: white;" title="' +
                title +
                '" data-id="' +
                dataId +
                '">';
              html += '<i class="' + iconClass + '"></i>';
              html += '</button>';
              html += '</div>';

              $('.social').append(html);
              $fieldGroup.remove();
            }
          );
        }
      );
    }
  );
});
