import AdmVue from '@assets/js/adm-vue';
import axiosApi, { param } from "@assets/js/axios-api";

const vm = new AdmVue({
  data() {
    return {
      edit: false,
      showModal: false, 
      btnSubmitLoading: false,
      editingProductId: null,
      settings: {},
      produtos: {},
      oldProducts: {},
    }
  },
  watch: {},
  computed: {},
  components: {
    BaseCep: () => import(/* webpackChunkName: "BaseCep" */ '@elements/BaseCep/index.vue'),
    BaseCard: () => import(/* webpackChunkName: "BaseCard" */ '@elements/BaseCard/index.vue'),
    BaseAlert: () => import(/* webpackChunkName: "BaseAlert" */ '@elements/BaseAlert/index.vue'),
    BaseInput: () => import(/* webpackChunkName: "BaseInput" */ '@elements/BaseInput/index.vue'),
    BaseModal: () => import(/* webpackChunkName: "BaseModal" */ '@components/BaseModal/index.vue'),
    BaseUpdate: () => import(/* webpackChunkName: "BaseUpdate" */ '@elements/BaseUpdate/index.vue'),
    BaseButton: () => import(/* webpackChunkName: "Basebutton" */ '@elements/BaseButton/index.vue'),
    BaseListing: () => import(/* webpackChunkName: "BaseListing" */ '@elements/BaseListing/index.vue'), 
  },
  methods: {
    dataReturn(selectedValues) {},
    updateItemQuantity(quantity, index) {
      this.produtos[index].qtde =  quantity;
    },
    limitText(text, maxLength) {
      text = text.replace(/<br \/>/g, "");
      if (text.length > maxLength) {
        return text.substring(0, maxLength) + "...";
      }
      return text;
    },
    transformPrice(price) {
      if (price) {
        price = price.replace(/\s/g, "");
        price = price.replace(/R\$/g, "");
        return price;
      }
    },
    onOpen() {
      this.showModal = true;
    },
    onClose() {
      this.showModal = false;
    },
    onEdit(item) {
      const idProduct = document.getElementById(`${item}`)
      const attributeKey = idProduct.getAttribute('id');

      if (attributeKey == item) {
        idProduct.classList.add('btn-loading');
        setTimeout(() => {
          this.editingProductId = item;
          idProduct.classList.remove('btn-loading');
          this.edit = true;
        }, 500); 
      }
    },
    validateLimit(value) {

      const datePattern = /^\d{2}\/\d{2}\/\d{4}$/;
      if (!datePattern.test(value)) {
        this.settings.validade = '';
        return this.settings.validade;
      }

      const parts = value.split('/');
      const day = parseInt(parts[0], 10);
      const month = parseInt(parts[1], 10);
      const year = parseInt(parts[2], 10);

      const date = new Date(year, month - 1, day);
    
      date.setDate(date.getDate() - this.settings.intervalo_Validade);
    
      const newDay = date.getDate().toString().padStart(2, '0');
      const newMonth = (date.getMonth() + 1).toString().padStart(2, '0');
      const newYear = date.getFullYear().toString();
    
      const newDate = `${newDay}/${newMonth}/${newYear}`;
    
      this.settings.validade = newDate;
      return this.settings.validade;
    },
    async onSubmit() {
      this.btnSubmitLoading = true;
      this.settings.produtos = this.produtos;
      this.settings.oldProducts = this.oldProducts;

      await axiosApi({
        method: 'post',
        url: this.settings.action,
        data: param(this.settings),
      })
        .then(({ data }) => {

          if (data.errors_validate) {
            this.$refs.validationObserver.setErrors(data.errors_validate);
            notificationMsg(this.language.error_validate, 'error');
          }

          if (data.redirect) return window.location.href = data.redirect;
        })
        .catch((err) => {
          console.log(err);
          this.alert = {
            type: 'warning',
            message: this.language.error_warning,
          };
        })
        .finally(() => {
          this.btnSubmitLoading = false;
        });
    },
    async onRemoveProduct(event, item) {
      const dataItem = event.currentTarget;
      const dataItemId = event.currentTarget.dataset.item;

      if (dataItemId == item) dataItem.classList.add('btn-loading');

      setTimeout(() => {
        dataItem.classList.remove('btn-loading');
      }, 500);
      setTimeout(() => {
        this.produtos = this.produtos.filter( (product) => {
          return product.item != item;
        }) 
      }, 500);

    },
  },
  mounted() {
    document.getElementById('form-gift').classList.remove('hidden');
    this.edit = false; 
    this.oldProducts = this.produtos;
    
  },
});

AdmVue.init(vm);