$(document).ready(function() {
  window.language.load('sale/order');

  var token = $('body').data('token'),
    info = $('[data-info]').data('info');

  function getOrderInfo() {
    return JSON.parse($('[data-order-info]').data('order-info'));
  }

  const orderInfo = getOrderInfo();

  const openTheSearchCustomer = document.querySelector('.js-select-customer-button');
  const openTheSearchPaymentAddress = document.querySelector('.js-select-payment-address-button');
  const openTheSearchShippingAddress = document.querySelector('.js-select-shipping-address-button');
  const postProducts = document.querySelector('.js-button-postar-kangu');
  const shippingVolumes = document.querySelector('.js-volumes');
  const { configuration } = window.DATA;

  function getAddressMapString(addressInfo) {
    const city = String(addressInfo.city).replace("'", '');
    const paymentAddressInfoAux = addressInfo.address_1 + ' ' + addressInfo.numero + ' ' + city + addressInfo.zone,
      paymentAddressAux = String(paymentAddressInfoAux).replace(/\s/g, '+');

    return paymentAddressAux;
  }

  function setAddressMapInfo(addressInfo, type) {
    let address_string = getAddressMapString(addressInfo);
    const html =
      "<iframe src='https://maps.google.com/maps?q=" +
      address_string +
      "&hl=es;z=14&amp;output=embed' width='400' height='500' frameborder='0' style='border:0; width:100%;' allowfullscreen></iframe>";

    switch (type) {
      case Type_Address.Tp_Faturamento:
        $('.payment-map').html(html);
        break;
      case Type_Address.Tp_Entrega:
        $('.shipping-map').html(html);
        break;
    }
  }

  function readyToProceed() {
    return state.customerSelected && state.paymentAddressSelected && state.shippingAddressSelected;
  }

  if (openTheSearchCustomer) {
    openTheSearchCustomer.addEventListener('click', () => {
      handleTheSearchCustomer();
    });
  }

  if (openTheSearchPaymentAddress) {
    openTheSearchPaymentAddress.addEventListener('click', () => {
      if (!openTheSearchPaymentAddress.hasAttribute('customer-id')) {
        notificationMsg(window.language.get('warning_customer_not_selected'), 'warning');
        return;
      }
      handleTheSearchPaymentAddress(openTheSearchPaymentAddress.getAttribute('customer-id'));
    });
  }

  if (openTheSearchShippingAddress) {
    openTheSearchShippingAddress.addEventListener('click', () => {
      if (!openTheSearchShippingAddress.hasAttribute('customer-id')) {
        notificationMsg(window.language.get('warning_customer_not_selected'), 'warning');
        return;
      }
      handleTheSearchShippingAddress(openTheSearchShippingAddress.getAttribute('customer-id'));
    });
  }

  if (postProducts) {
    postProducts.addEventListener('click', e => {
      let referencia = e.target.id;

      $.ajax({
        url:
          'index.php?route=sale/order/postCollectionRequest&token=' +
          token +
          '&order_id=' +
          orderInfo.orderId +
          '&referencia=' +
          referencia,
        type: 'post',
        dataType: 'json',
        success: function(json) {
          if (json.codigo) {
            let contentHtml = `<br><span className="text-small text-gray visible-block top-margin-x-large">Código de acompanhamento</span>`;
            contentHtml += `<br><br><span className="text-medium text-dark visible-block top-margin-small">${json.codigo}</span>`;

            let content = document.querySelector('.js_tracking_code');

            content.innerHTML = contentHtml;

            notificationMsg('Pedido postado com sucesso código: ' + json.codigo, 'success');

            postProducts.setAttribute('disabled', false);
            postProducts.classList.remove('btn-primary');
            postProducts.classList.add('btn-success');

            document.querySelector('.js-button-postar-kangu span').textContent = window.language.get(
              'text_shipping_button_reference_postado'
            );
          } else if (json.error) {
            notificationMsg(json.error.mensagem, 'error');
          }
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.log(jqXHR, textStatus, errorThrown);
        },
      });
    });
  }

  if (shippingVolumes) {
    $('.js-volumes').each(function() {
      var $this = $(this),
        $control = $('.js-volumes-control', $this),
        $content = $('.js-volumes-content', $this),
        clickOnActive = false;

      $this.data('status', true);

      $content.css('display', 'none');

      slideActive();

      $('.js-volumes-control', $this).on('click', function(e) {
        e.preventDefault();

        if ($control.hasClass('active')) {
          clickOnActive = true;
          $control.removeClass('active');
        } else {
          $control.addClass('active');
        }

        slideActive();
      });

      function slideActive() {
        if ($control.hasClass('active')) {
          $control.removeClass('fa-plus-circle');
          $control.addClass('fa-minus-circle');
          $content.stop(false, true).slideDown(400);
        } else {
          $control.removeClass('fa-minus-circle');
          $control.addClass('fa-plus-circle');
          $content.stop(false, true).slideUp(400);
        }
      }
    });

    $('.js-volume-products').accordionFutura({
      initFirstActive: false,
      onlyOneActive: false,
    });
  }

  const state = {
    customerSelected: !openTheSearchCustomer,
    paymentAddressSelected: !openTheSearchPaymentAddress,
    shippingAddressSelected: !openTheSearchShippingAddress,
  };

  function setOrderConfirmed() {
    $.ajax({
      url: 'index.php?route=sale/order/setOrderConfirmed&token=' + token + '&order_id=' + orderInfo.orderId,
      type: 'post',
      dataType: 'json',
    })
      .done(function(data) {
        if (data.type == 'success') {
          //sepa aqui remove a notificacao geral do bagulho
        } else {
          notificationMsg('Ocorreu um erro ao confirmar o pedido!', 'error');
          return;
        }
      })
      .fail(function() {
        console.log('Nao foi possivel confirmar o pedido!');
      });
  }

  function getAddressSelectedHtmlContent(itemsSelectedInfo, addressType) {
    const {
      address_id,
      firstname,
      lastname,
      apelido,
      address_1,
      address_2,
      postcode,
      logradouro,
      city,
      codigo_municipio,
      numero,
      complemento,
      zone,
      zone_code,
      zone_id,
      country,
      country_id,
      company,
      company_id,
    } = itemsSelectedInfo;

    let addressContent = ``;

    if (addressType == Type_Address.Tp_Faturamento) {
      addressContent += `<span class="text-small text-gray visible-block">${window.language.get(
        'text_payment_method'
      )}</span>
              <span class="text-medium text-dark visible-block top-margin-small">${orderInfo.payment_method}</span>
    `;
    } else {
      addressContent += `<span class="text-small text-gray visible-block">${window.language.get(
        'text_shipping_method'
      )}</span>
              <span class="text-medium text-dark visible-block top-margin-small">${orderInfo.shipping_method}</span>`;
    }

    if (firstname && firstname.trim() !== '') {
      addressContent += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_firstname'
      )}</span>
                  <span class="text-medium text-dark visible-block top-margin-small">${firstname} ${lastname}</span>`;
    }

    if (apelido && apelido.trim() !== '') {
      addressContent += `<span class="text-small text-gray visible-block top-margin-x-large">Local</span>
                  <span class="text-medium text-dark visible-block top-margin-small">${apelido}</span>`;
    }

    if (company && company.trim() !== '') {
      addressContent += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_company'
      )}</span>
                  <span class="text-medium text-dark visible-block top-margin-small">${company}</span>`;
    }

    if (company_id) {
      addressContent += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_company_id'
      )}</span>
                  <span class="text-medium text-dark visible-block top-margin-small">${company_id}</span>`;
    }

    addressContent += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
      'text_address_1'
    )}</span>
                  <span class="text-medium text-dark visible-block top-margin-small">
                    ${address_1}
                    ${numero ? ', ' + numero : ''}
                    ${address_2 ? ' - ' + address_2 : ''}
                  </span>`;

    addressContent += `<span class="text-medium text-dark visible-block top-margin-x-small">
                    ${city} - ${zone}
                    ${zone_code}
                  </span>`;

    addressContent += `<span class="text-medium text-dark visible-block top-margin-x-small">${country}</span>`;

    if (postcode && postcode.trim() !== '') {
      addressContent += `<span class="text-medium text-dark visible-block top-margin-x-small mask-cep">${postcode}</span>`;
    }

    if (complemento && complemento.trim() !== '') {
      addressContent += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_address_complemento'
      )}</span>
                <span class="text-medium text-dark visible-block top-margin-small">${complemento}</span>`;
    }

    return addressContent;
  }

  function handleAddressSelected(itemsSelected, typeAddress) {
    let content;
    let showNotification = true;
    const contentHtml = getAddressSelectedHtmlContent(itemsSelected.info, typeAddress);

    if (typeAddress == Type_Address.Tp_Faturamento) {
      content = document.querySelector('.js-selected-payment-address-content');
    } else if (typeAddress == Type_Address.Tp_Entrega) {
      content = document.querySelector('.js-selected-shipping-address-content');
    }

    $.ajax({
      url: 'index.php?route=sale/order/setOrderAddress&token=' + token + '&order_id=' + orderInfo.orderId,
      type: 'post',
      data: {
        customer_address: itemsSelected.info,
        type: typeAddress,
      },
      dataType: 'json',
    })
      .done(function(data) {
        if (data.type == 'success') {
          content.innerHTML = '';
          content.innerHTML = contentHtml;
          setAddressMapInfo(itemsSelected.info, typeAddress);

          if (typeAddress == Type_Address.Tp_Faturamento) {
            state.paymentAddressSelected = true;
          } else if (typeAddress == Type_Address.Tp_Entrega) {
            state.shippingAddressSelected = true;
          }

          if (readyToProceed()) {
            setOrderConfirmed();
          }

          let tab_value = typeAddress == Type_Address.Tp_Faturamento ? '1' : '2';

          let tabAddress = document
            .getElementById('tab-info')
            .querySelector('[data-tab-control="tab-info-' + tab_value + '"]');
          let warning_tab_address_icon = tabAddress.querySelector('.fa-exclamation-triangle');
          if (warning_tab_address_icon !== null) {
            warning_tab_address_icon.remove();
          }

          if (
            (typeAddress == Type_Address.Tp_Faturamento && !state.shippingAddressSelected) ||
            (typeAddress == Type_Address.Tp_Entrega && !state.paymentAddressSelected)
          ) {
            const opositTypeDescription = typeAddress == Type_Address.Tp_Faturamento ? 'entrega' : 'pagamento';
            if (window.confirm('Deseja usar o mesmo endereco para o endereco de ' + opositTypeDescription + '?')) {
              const opositType =
                typeAddress == Type_Address.Tp_Faturamento ? Type_Address.Tp_Entrega : Type_Address.Tp_Faturamento;
              handleAddressSelected(itemsSelected, opositType);
              showNotification = false; //se ele for adicionar o segundo endereco igual o primeiro, so pode mostrar uma notificacao (para nao aparecer a mesma 2x)
            }
          }

          if (showNotification) {
            notificationMsg(window.language.get('text_success_address_select'), 'success');
          }
        } else {
          notificationMsg(window.language.get('error_address_select'), 'error');
          return;
        }
      })
      .fail(function() {
        console.log(window.language.get('error_address_select'));
      });
  }

  function handleCustomerSelected(itemsSelected) {
    const orderInfo = getOrderInfo();
    const content = document.querySelector('.js-selected-customer-content');

    const {
      customer_id,
      name,
      first_name,
      last_name,
      razao_social,
      data_nascimento,
      sexo,
      cpf,
      cnpj,
      rg,
      inscricao_estadual,
      email,
      telephone,
      celular,
      fax,
      address,
    } = itemsSelected.info;

    const data_nascimento_condition =
      data_nascimento && data_nascimento != '0000-00-00' && orderInfo.fields_register_brazil_status_data_nascimento
        ? true
        : '';
    const sexo_condition = sexo && orderInfo.fields_register_brazil_status_sexo ? true : '';
    const fax_condition = fax && orderInfo.fields_register_brazil_status_telefone2 ? true : '';
    let contentCustomerHtml = '';

    if (name && name.trim() !== '') {
      contentCustomerHtml += `<span class="text-small text-gray visible-block">${window.language.get(
        'text_customer'
      )}</span>
        <span class="text-medium text-dark visible-block top-margin-small">${name}</span>`;
    }

    if (email && email.trim() !== '') {
      contentCustomerHtml += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_email'
      )}</span>
        <span style="width:260px;" class="text-medium text-dark visible-block top-margin-small text-ellipsis">${email}</span>`;
    }

    if (telephone) {
      contentCustomerHtml += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_telephone'
      )}</span>
        <span class="text-medium text-dark visible-block top-margin-small mask-phone">${telephone}</span>`;
    }

    if (celular) {
      contentCustomerHtml += `<span class="text-small text-gray visible-block top-margin-x-large bottom-margin-small">${window.language.get(
        'text_celular'
      )}</span>
        <a href="https://api.whatsapp.com/send?phone=55${celular}" target="_blank" class="text-medium text-primary">
          <span class="mask-celular">${celular}</span>
          <i class="fab fa-whatsapp left-margin-small text-success"></i>
        </a>`;
    }

    if (cpf && cpf.trim() !== '') {
      contentCustomerHtml += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_cpf'
      )}</span>
        <span class="text-medium text-dark visible-block top-margin-small mask-cpf">${cpf}</span>`;
    }

    if (rg && rg.trim() !== '') {
      contentCustomerHtml += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_rg'
      )}</span>
        <span class="text-medium text-dark visible-block top-margin-small">${rg}</span>`;
    }

    if (cnpj && cnpj.trim() !== '') {
      contentCustomerHtml += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_cnpj'
      )}</span>
        <span class="text-medium text-dark visible-block top-margin-small mask-cnpj">${cnpj}</span>`;
    }

    if (razao_social && razao_social.trim() !== '') {
      contentCustomerHtml += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_razao'
      )}</span>
        <span class="text-medium text-dark visible-block top-margin-small">${razao_social}</span>`;
    }

    if (inscricao_estadual && inscricao_estadual.trim() !== '') {
      contentCustomerHtml += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_ie'
      )}</span>
        <span class="text-medium text-dark visible-block top-margin-small">${inscricao_estadual}</span>`;
    }

    if (sexo_condition) {
      contentCustomerHtml += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_sexo'
      )}</span>
        <span class="text-medium text-dark visible-block top-margin-small">${
          sexo == 'm' ? 'Masculino' : 'Feminino'
        }</span>`;
    }

    if (data_nascimento_condition) {
      contentCustomerHtml += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_data_nascimento'
      )}</span>
        <span class="text-medium text-dark visible-block top-margin-small">${data_nascimento}</span>`;
    }

    if (fax_condition) {
      contentCustomerHtml += `<span class="text-small text-gray visible-block top-margin-x-large">${window.language.get(
        'text_fax'
      )}</span>
        <span class="text-medium text-dark visible-block top-margin-small mask-phone">${fax}</span>`;
    }

    $.ajax({
      url: 'index.php?route=sale/order/setOrderCustomer&token=' + token + '&order_id=' + orderInfo.orderId,
      type: 'post',
      data: {
        customer: itemsSelected.info,
      },
      dataType: 'json',
    })
      .done(function(data) {
        if (data.type == 'success') {
          content.innerHTML = '';
          content.innerHTML = contentCustomerHtml;
          state.customerSelected = true;
          openTheSearchPaymentAddress.setAttribute('customer-id', customer_id);
          openTheSearchShippingAddress.setAttribute('customer-id', customer_id);

          let tabGeral = document.getElementById('tab-info').querySelector('[data-tab-control="tab-info-0"]');
          let warning_tab_geral_icon = tabGeral.querySelector('.fa-exclamation-triangle');
          if (warning_tab_geral_icon !== null) {
            warning_tab_geral_icon.remove();
          }

          notificationMsg(window.language.get('text_success_customer_select'), 'success');
        } else {
          notificationMsg(window.language.get('error_customer_select'), 'error');
          return;
        }
      })
      .fail(function() {
        console.log(window.language.get('error_customer_select'));
      });
  }

  function handleTheSearchPaymentAddress(customer_id) {
    window.dispatchEvent(
      new CustomEvent('vue-the-search-payment-address', {
        detail: {
          callbackFunction: itemsSelected => {
            configuration.payment_address_items = itemsSelected;
            handleAddressSelected(itemsSelected, Type_Address.Tp_Faturamento);
          },
          options: {
            itemsAlreadySelected: configuration.payment_address_items,
            aditionalParam: customer_id,
          },
        },
      })
    );
  }

  function handleTheSearchCustomer() {
    window.dispatchEvent(
      new CustomEvent('vue-the-search-customer', {
        detail: {
          callbackFunction: itemsSelected => {
            configuration.value_item = itemsSelected;
            handleCustomerSelected(itemsSelected);
          },
          options: {
            itemsAlreadySelected: configuration.value_item,
          },
        },
      })
    );
  }

  function handleTheSearchShippingAddress(customer_id) {
    window.dispatchEvent(
      new CustomEvent('vue-the-search-payment-address', {
        detail: {
          callbackFunction: itemsSelected => {
            configuration.shipping_address_items = itemsSelected;
            handleAddressSelected(itemsSelected, Type_Address.Tp_Entrega);
          },
          options: {
            itemsAlreadySelected: configuration.shipping_address_items,
            aditionalParam: customer_id,
          },
        },
      })
    );
  }

  //schedule ticket
  window.addEventListener('load', function() {
    $('.js-data-ticket').each(function() {
      const maxLength = 20;
      const text = $(this).text();
      if (text.length > maxLength) {
        const truncatedText = text.substring(0, maxLength) + '...';
        $(this).text(truncatedText);
      }
    });
  });

  $('body').on('click', '.js-link-ticket', function(e) {
    const ticketContainer = document.querySelector('.ticket-container');
    const jsTicketError = document.querySelector('.js-ticket-error');
    const jsTicketEmail = document.querySelector('.js-ticket-email');
    const emailContainer = document.querySelector('.email-container');

    emailContainer.classList.add('hidden');
    ticketContainer.classList.toggle('hidden');
    jsTicketEmail.classList.toggle('hidden');
    jsTicketError.classList.remove('active');
    jsTicketError.classList.add('hidden');
  });

  $('body').on('click', '.js-save-ticket', function(e) {
    const jsTicketNumber = document.querySelector('.js-ticket-number');
    const jsTicketType = document.querySelector('.js-ticket-type');
    const jsTicketError = document.querySelector('.js-ticket-error');
    const ticketContainer = document.querySelector('.ticket-container');
    const ticketNumber = jsTicketNumber.value.trim();
    const ticketType = jsTicketType.value.trim();

    if (ticketNumber && ticketType) {
      jsTicketError.classList.remove('active');
      jsTicketError.classList.add('hidden');

      const data = {
        order_id: orderInfo.orderId,
        ticket_number: ticketNumber,
        ticket_type: ticketType,
      };

      $.ajax({
        url: 'index.php?route=sale/order/linkTicketSchedule&token=' + token,
        type: 'post',
        data: data,
        dataType: 'json',
        success: function(res) {
          if (res && res !== 2601) {
            notificationMsg('Ticket vinculado com sucesso!', 'success');
            location.reload();
            ticketContainer.classList.toggle('hidden');
          } else {
            notificationMsg('Ticket já vinculado a algum pedido', 'error');
          }
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.log(jqXHR, textStatus, errorThrown);
        },
      });
    } else {
      jsTicketError.classList.remove('hidden');
      jsTicketError.classList.add('active');
    }
  });

  $('body').on('click', '.js-ticket-remove', function(e) {
    const infoContent = document.getElementById(e.currentTarget.id);
    const ticketShow = infoContent.querySelector('div');
    const ticketHidde = infoContent.children[1];

    ticketHidde.classList.remove('hidden');
    ticketHidde.classList.add('active');
    ticketShow.classList.add('hidden');
  });

  $('body').on('click', '.js-ticket-cancel', function(e) {
    const infoContent = document.getElementById(e.currentTarget.id);
    const ticketShow = infoContent.querySelector('div');
    const ticketHidde = infoContent.children[1];

    ticketHidde.classList.remove('active');
    ticketHidde.classList.add('hidden');
    ticketShow.classList.remove('hidden');
    ticketShow.classList.add('active');
  });

  $('body').on('click', '.js-ticket-unlinked', function(e) {
    const attTicketNumber = e.currentTarget.dataset.ticket;

    const data = {
      order_id: orderInfo.orderId,
      ticket_number: attTicketNumber,
    };

    $.ajax({
      url: 'index.php?route=sale/order/unlinkTicketSchedule&token=' + token,
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(res) {
        if (res) {
          notificationMsg('Ticket desvinculado com sucesso!', 'success');
          location.reload();
        } else {
          notificationMsg('erro', 'error');
        }
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR, textStatus, errorThrown);
      },
    });
  });

  $('body').on('click', '.js-ticket-email', function(e) {
    const emailContainer = document.querySelector('.email-container');
    emailContainer.classList.toggle('hidden');
  });

  $('body').on('click', '.js-send-email', function(e) {
    const emailContainer = document.querySelector('.email-container');

    const data = {
      order_id: orderInfo.orderId,
    };

    $.ajax({
      url: 'index.php?route=sale/order/sendEmailTicket&token=' + token,
      type: 'post',
      data: data,
      dataType: 'json',
      success: function(res) {
        if (res) {
          notificationMsg('E-mail enviado com sucesso!', 'success');
          emailContainer.classList.toggle('hidden');
        } else {
          notificationMsg('Erro ao enviar e-mail', 'error');
        }
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR, textStatus, errorThrown);
      },
    });
  });

  $('body').on('click', '.js-cancel-email', function(e) {
    const emailContainer = document.querySelector('.email-container');
    emailContainer.classList.add('hidden');
  });
});
