<template>
  <div class="content-quantity quantity-control">
    <button class="btn-control" title="Diminuir" @click.prevent="decrement">
      <i class="fas fa-minus text-dark-opacity" />
    </button>
    <input
      v-model="quantity"
      type="number"
      mask="positiveInteger"
      class="quantity-input numeric input-text"
      maxlength="4"
      min="1"
      @blur="updateQuantity"
      @input="maxValue(quantity)"
    />
    <button class="btn-control" title="Aumentar" @click.prevent="increment">
      <i class="fas fa-plus text-dark-opacity" />
    </button>
  </div>
</template>

<script>
export default {
  name: 'BaseUpdate',
  props: {
    value: {
      type: Number,
      default: 0,
    },
    qtdeComp: {
      type: Number,
      default: 0,
    },
    productIndex: Number,
  },
  data() {
    return {
      quantity: this.value,
      quantity_comp: this.qtdeComp,
      index: this.productIndex,
    };
  },
  watch: {
    value(newVal) {
      this.quantity = newVal;
    },
  },
  methods: {
    maxValue(value) {
      if (value >= 9999) return (this.quantity = 9999);
    },
    increment() {
      if (this.quantity < 9999) this.quantity++;
      this.updateQuantity();
    },
    decrement() {
      if (this.quantity > 1 && this.quantity > this.quantity_comp) this.quantity--;
      this.updateQuantity();
    },
    updateQuantity() {
      if (parseInt(this.quantity) == 0 || this.quantity == '') this.quantity = 1;
      if (this.quantity < this.quantity_comp) this.quantity = this.quantity_comp;

      this.$emit('input', parseInt(this.quantity), this.index);
    },
  },
};
</script>

<style scoped>
.quantity-control {
  display: flex;
  flex-grow: 1;
  align-items: stretch;
  width: 100%;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}
.quantity-control .quantity-input {
  flex-grow: 1;
  background: transparent;
  border: none;
  text-align: center;
}
.quantity-control .quantity-input,
.quantity-control .btn-control {
  background: transparent;
  border: none;
  cursor: pointer;
}
.quantity-input {
  width: 100%;
}
.content-quantity {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
