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

const BASE_URL = document.getElementById('base-urls').dataset.baseUrlLoja;

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

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


      enableToCancel: false,
      link_reload: null,
      statusToCancel: null,
      situationsAfterCancel: null,
      situationsToCancel: {},
      
      histories: {},
      order_history_proccess: {},
      order_tracking_events: {},

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

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

      itaushopline: false,

      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: '',

      // data-infos below are used to display schedule module only to futura
      schedule_infos: {},
      showForm: false,
      showCancelScheduleModal: false,
      ticket_infos: {},
    };
  },
  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'),
    ScheduleCustomer: () => import(/* webpackChunkName: "ScheduleTable" */ '@components/Schedule/ScheduleCustomer/index.vue'),
    ScheduleCustomerSelect: () => import(/* webpackChunkName: "ScheduleCustomerSelect" */ '@components/Schedule/ScheduleCustomerSelect/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,
      link_reload,
      statusToCancel,
      situationsToCancel,
      situationsAfterCancel,
      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,
      schedule_infos,
      ticket_infos,
    }) {
      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.link_reload = link_reload;
      this.situationsToCancel = situationsToCancel;
      this.statusToCancel = statusToCancel;
      this.situationsAfterCancel = situationsAfterCancel

      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;

      this.schedule_infos = schedule_infos;
      this.ticket_infos =  ticket_infos;
      
      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();
      }
    },
    callbackCreateForm(propValue) {
      this.showForm = propValue;
    },
    callbackScheduledInfos(infos) {
      if (infos.order_id) {
        this.schedule_infos.hasOrderSchedule = true;
        this.schedule_infos.scheduledInfo = [
          {
            status: 1,
            date: infos.meet_date,
            time: infos.meet_time,
            type: infos.meet_type,
          }
        ]
      }
    },
    async handleScheduledStatus() {
      await axiosApi({
        method: 'POST',
        url: BASE_URL + 'index.php?route=common/schedule/setOrderScheduledCanceled',
        data: param({ order_id: this.order_id }),
      })
        .then(({ data }) => {
          notificationMsg(data.message, data.type)
          if (data.type == 'success') {
            this.schedule_infos.hasOrderSchedule = false;
            this.schedule_infos.scheduledInfo = [];
            setTimeout(() => this.showCancelScheduleModal = false, 2000);
          }  
        })
        .catch((err) => console.error(err))
    },
    async setCancelSituation() {
      await axiosApi({
        headers: {'content-type': 'application/x-www-form-urlencoded'},
        method: 'POST',
        url: BASE_URL + 'index.php?route=account/order/setCancelSituation',
        data: param({order_id: this.order_id}),
      })
        .then(({ data }) => {
          if (data.errors) return notificationMsg(data.errors, 'errors');
          if (data.success) return notificationMsg(data.success, 'success'); 
        })
        .catch((err) => console.log(err))
        .finally(() => {
          this.showModalCancel = !this.showModalCancel;
          setTimeout(() => {
            window.location.href = this.link_reload;
          }, 4000);
        });
    },
    enableToCancelOrder() {
      if (!this.statusToCancel) return this.enableToCancel = false;

      const orderSituations = this.histories; 
      const situationsToCancel = this.situationsToCancel;
      const alreadyCancel = orderSituations.some(info => info.id === parseInt(this.situationsAfterCancel));

      if (alreadyCancel) return this.enableToCancel = false;
      
      if (orderSituations) {
        this.enableToCancel = orderSituations.some( item => {
          return situationsToCancel.some( value => item.status === value.name);
        })
      }   
    },
    modalCancelOrder() {
      this.showModalCancel = !this.showModalCancel;
    },
    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--;
            this.seconds = 60;
          }

          if (this.minutes == 0 && this.seconds == 0) this.reloadPix(this.order_id);
          this.seconds--;
          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);

      if(comment.includes("itaushopline")){
        this.itaushopline = comment;
        this.payment_comment = comment;
      }
      
      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' , data.additional_data.qr_codeImage
            );
            
          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();
    this.enableToCancelOrder();
  },
  beforeDestroy() {
    clearInterval(this.intervalId);
  },
});

initVue(vm);
