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

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

      showModal: false,
      showAllProducts: false,
      showAllProductsSchool: 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: '',

      nfe_info: {},
      link_see_nfe: 'http://www.nfe.fazenda.gov.br/portal/consultaRecaptcha.aspx?tipoConsulta=resumo&tipoConteudo=d09fwabTnLk=',

      productlist: {},
      futuragrade_status: '',
    }
  },
  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();
    },
  },
  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 }) {
      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;


    },
    limitText(text, maxLength) {
      text = this.replaceTag(text);
      if (text.length > maxLength) {
        return text.substring(0, maxLength) + "...";
      }
      return text;
    },
    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;
      }
    },
    openModal(){
      this.showModal = true;
    },
    onClose(){
      this.showModal = false;
    },
    reloadPix(order_id){
      $.ajax({
        url: 'index.php?route=payment/getnet/reloadPix&id='+order_id,
        type: 'get',
        dataType: 'json',
        timeout: 3000,
        contentType: 'application/json; charset=utf-8',

        error: function(xhr, ajaxOptions, thrownError) {
          console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
        },
        success: function(json) {
          if(json){
            var imgQR = document.querySelector('.js-imgQr');
            var spanQr = document.querySelector('.js-copy-content');
            imgQR.setAttribute('src','https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl='+json.additional_data.qr_code);
            spanQr.textContent = json.additional_data.qr_code;
            notificationMsg('Código atualizado com sucesso', 'success');
          }
        },
      });
    },
    paymentStatus(){
      var imgQR = document.querySelector('.js-imgQr');
      if(imgQR && ! (imgQR.getAttribute('src') == 'image/qrcode_pago.png')){
        $.ajax({
          url: 'index.php?route=checkout/success/verifyPaymentPix',
          type: 'get',
          dataType: 'json',
          timeout: 3000,
          contentType: 'application/json; charset=utf-8',
          error: function(xhr, ajaxOptions, thrownError) {
            console.log(thrownError + '\r\n' + xhr.statusText + '\r\n' + xhr.responseText);
          },
          success: function(json) {
            if(json){
              imgQR.setAttribute('src','image/qrcode_pago.png');
            }
          },
        });
      }
    },
    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() {
    this.intervalId = setInterval(() => {
      this.paymentStatus();
    }, 5000);
  },
  beforeDestroy() {
    clearInterval(this.intervalId);
  }
});

initVue(vm);