import seeKitProducts from '../../see-kit-products';
import Vue from 'vue';
import initVue from '@assets/js/initVue';
import copyContent from '@assets/js/copyContent';
import axiosApi from '@assets/js/axios-api';

const vm = new Vue({
  data() {
    return {
      totals: {},
      comments: {},
      order_id: '',
      fidelity: '',
      intervalId: '',

      showModal: false,
      showAllProducts: false,
      showAllProductsSchool: false,
      showPaidMsg: false,
      showErrorMsg: false,

      histories: {},
      order_history_proccess: {},
      order_tracking_events: {},

      pickup_info: {},
      shipping_method: '',
      shipping_address: '',
      shipping_pickup: '',

      payment_info_detail: {},
      payment_pix: {},
      payment_method: '',
      payment_billet: '',
      payment_address: '',
      payment_comment: '',
      payment_commentTitle: '',
      payment_commentFooter: '',

      minutes: 0,
      seconds: 0,
      nfe_info: {},
      link_see_nfe: 'http://www.nfe.fazenda.gov.br/portal/consultaRecaptcha.aspx?tipoConsulta=resumo&tipoConteudo=d09fwabTnLk=',
      productlist: {},
      showLoading: false,
      showBtnRealod: false,
      showErrorReloadPix: false,
      stop: false,
      futuragrade_status: '',
      timerTimeOut: '',

      tracking_code: null,
    };
  },
  components: {
    BaseInput: () => import(/* webpackChunkName: "BaseInput" */ '@elements/BaseInput/index.vue'),
    BaseButton: () => import(/* webpackChunkName: "BaseButton" */ '@elements/BaseButton/index.vue'),
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    BaseModal: () => import(/* webpackChunkName: "BaseModal" */ '@components/BaseModal/index.vue'),
  },
  computed: {
    reversedHistories() {
      return this.histories.slice().reverse();
    },
    displayMinute() {
      return String(this.minutes).padStart(2, '0');
    },
    displaySeconds() {
      return String(this.seconds).padStart(2, '0');
    },
  },
  watch: {},
  methods: {
    setData({
      totals,
      order_id,
      fidelity,
      histories,
      order_history_proccess,
      order_tracking_events,
      pickup_info,
      shipping_method,
      shipping_address,
      shipping_pickup,
      payment_info_detail,
      payment_method,
      payment_billet,
      payment_pix,
      payment_address,
      comments,
      nfe_info,
      productlist,
      futuragrade_status,
      tracking_code,
    }) {
      this.totals = totals;
      this.order_id = order_id;
      this.nfe_info = nfe_info;
      this.productlist = productlist;
      this.futuragrade_status = futuragrade_status;
      this.fidelity = fidelity;
      this.comments = comments;

      this.histories = histories;
      this.order_history_proccess = order_history_proccess;
      this.order_tracking_events = order_tracking_events;

      this.pickup_info = pickup_info;
      this.shipping_method = shipping_method;
      this.shipping_address = shipping_address;
      this.shipping_pickup = shipping_pickup;

      this.payment_info_detail = payment_info_detail;
      this.payment_method = payment_method;
      this.payment_billet = payment_billet;
      this.payment_pix = payment_pix;
      this.payment_address = payment_address;
      this.tracking_code = tracking_code;

      if (payment_pix && payment_pix.data_vencimento) {
        const data_vencimento = new Date(payment_pix.data_vencimento);
        const data = new Date();

        if (data_vencimento > data) {
          this.timer = data_vencimento.getTime() - data.getTime();
          this.minutes = Math.floor(this.timer / 60000);
          this.seconds = ((this.timer % 60000) / 1000).toFixed(0);
        }

        this.countDown();
      }
    },
    limitText(text, maxLength) {
      text = this.replaceTag(text);
      if (text.length > maxLength) {
        return text.substring(0, maxLength) + '...';
      }
      return text;
    },
    countDown() {
      this.timerTimeOut = setTimeout(
        function() {
          if (this.seconds == 0 && this.minutes > 0) {
            this.minutes -= 1;
            this.seconds = 60;
          }

          if (this.minutes == 0 && this.seconds == 0) {
            this.reloadPix(this.order_id);
          }

          this.seconds -= 1;

          this.countDown();
        }.bind(this),
        1000
      );
    },
    replaceTag(text) {
      return text.replace(/<br \/>/g, '');
    },
    copyCode(code) {
      copyContent(code);
      notificationMsg('Código copiado com sucesso!', 'success');
    },
    copyNfeKey(key) {
      copyContent(key);
      notificationMsg('Chave de acesso copiada com sucesso!', 'success');
    },
    formatDateTime(dateTime) {
      const [date, time] = dateTime.split(' ');
      return date + ' - ' + time;
    },
    formatAddress(address) {
      address = address.replace(/,/g, '');
      address = address.replace(/<br \/>/g, ', ');
      return address;
    },
    transformPrice(price) {
      if (price) {
        price = price.replace(/\s/g, '');
        price = price.replace(/R\$/g, '');
        return price;
      }
    },
    paymentComments() {
      const [{ comment }]  = this.histories;

      this.payment_commentTitle = comment.slice(0, 39);
      this.payment_comment = comment.slice(39, -59);
      this.payment_commentFooter = comment.slice(-59);
      
      return;
    },
    openModal() {
      this.showModal = true;
    },
    onClose() {
      this.showModal = false;
    },
    async reloadPix(order_id) {
      this.showLoading = true;

      await axiosApi({
        url: 'index.php?route=payment/getnet/reloadPix&id=' + order_id,
        type: 'get',
        dataType: 'json',
        timeout: 20000,
        contentType: 'application/json; charset=utf-8',
      }).then(({ data }) => {
        var imgQR = document.querySelector('.js-imgQr');
        var spanQr = document.querySelector('.js-copy-content');

        if (data.additional_data) {
          imgQR &&
            imgQR.setAttribute(
              'src',
              'https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=' + data.additional_data.qr_code
            );
          spanQr ? (spanQr.textContent = data.additional_data.qr_code) : null;

          this.minutes = 2;
          this.seconds = 59;

          this.stop && this.countDown();

          this.showBtnRealod = false;
          this.showErrorReloadPix = false;
          this.stop = false;
          this.showLoading = false;

          notificationMsg('Código atualizado com sucesso', 'success');
        } else {
          this.showBtnRealod = true;
          this.showErrorReloadPix = true;
          this.stop = true;
          this.showLoading = false;
          clearTimeout(this.timerTimeOut);
          notificationMsg('Erro ao atualizar pix, tente novamente por favor', 'error');
        }
      });
    },
    async paymentStatus() {
      var imgQR = document.querySelector('.js-imgQr');
      if (imgQR && !(imgQR.getAttribute('src') == 'image/qrcode_pago.png')) {
        await axiosApi({
          url: 'index.php?route=checkout/success/verifyPaymentPix',
          type: 'get',
          dataType: 'json',
          timeout: 20000,
          contentType: 'application/json; charset=utf-8',
        }).then(json => {
          if (json.data) {
            imgQR.setAttribute('src', 'image/qrcode_pago.png');
            clearTimeout(this.timerTimeOut);
            this.showPaidMsg = true;
          }
        });
      }
    },
    forceReload() {
      this.reloadPix(this.order_id);
    },
    debitCardPayment(payment_method_debit) {
      this.payment_method = payment_method_debit.toLowerCase();
      if (this.payment_method.includes('cartão') || this.payment_method.includes('débito')) {
        return this.payment_method;
      }
    },
    showProducts() {
      this.showAllProducts = !this.showAllProducts;
      const showProducts = document.querySelector('.js-more-products');
      const linkShowMore = document.querySelector('.linkShowMore');
      const linkHideProducts = document.querySelector('.linkHideProducts');

      if (showProducts) {
        showProducts.classList.toggle('hidden');
      }
      if (linkShowMore && linkHideProducts) {
        linkShowMore.classList.toggle('hidden');
        linkHideProducts.classList.toggle('hidden');
      }
    },
    showProductsSchool(nameKey) {
      const showProductsSchool = document.querySelectorAll('.id-' + nameKey);
      const id = document.getElementById(`${nameKey}`);
      const attributeKey = id.getAttribute('id');
      const linkShowMoreSchool = document.querySelectorAll('.key-' + nameKey);

      if (nameKey === attributeKey) {
        if (showProductsSchool) {
          showProductsSchool.forEach(item => {
            item.classList.toggle('hidden');
          });
          linkShowMoreSchool.forEach(item => {
            item.classList.toggle('hidden');
          });
        }
      }
    },
    reorderProduct(idProduct) {
      seeKitProducts();
      const reorderButton = document.querySelectorAll('.js-product-reorder');
      if (reorderButton.length > 0) {
        reorderButton.forEach(item => {
          const id = item.dataset.productId;
          const qty = item.dataset.productQty;
          const size = item.dataset.productSize;
          const specification = item.dataset.productSpecification;

          if (size != '' || specification != '') {
            const grid = {
              size_id: size,
              specification_id: specification,
            };
            if (idProduct == id) {
              window.addToCart(id, qty, 10, grid, true);
            }
          } else {
            if (idProduct == id) {
              window.addToCart(id, qty);
            }
          }
        });
      }
    },
  },
  mounted() {
    document.getElementById('order-info').classList.remove('hidden');
    this.intervalId = setInterval(() => {
      this.paymentStatus();
    }, 5000);
    this.paymentComments();
  },
  beforeDestroy() {
    clearInterval(this.intervalId);
  },
});

initVue(vm);
