<template lang="pug">
  vm-prompt(@vm-cancel="close" @vm-accept="saveRecord" @vm-close="close" :vm-accept-text="$t('strings.accept')" :vm-cancel-text="$t('strings.cancel')" :vm-is-valid="!$v.detail.$invalid" :vm-active="isModalVisible" :vm-title='getTitle')
    vm-row(vm-align="center" vm-type="flex" vm-justify="space-between" vm-w="12")
      vm-col(vm-justify="center", vm-align="center", vm-w=12)
        b-form-group
          vm-input(type="number" :placeholder='$t("purchase_orders.detail.quantity_placeholder")' :danger="!$v.detail.quantity.numeric" :danger-text="'Is Numeric'" v-model="detail.quantity" :label='$t("purchase_orders.detail.quantity")')
      vm-col(vm-justify="center", vm-align="center", vm-w=12)
        b-form-group
          vm-input(type="number" :placeholder='$t("purchase_orders.detail.unit_price_placeholder")' :danger="!$v.detail.unit_price.decimal" :danger-text="'Is decimal'" v-model="detail.unit_price" :label='$t("purchase_orders.detail.unit_price")')
</template>

<script>
import { required, numeric, decimal } from 'vuelidate/lib/validators' // Ver documentacion
import { createNamespacedHelpers } from 'vuex'
const { mapGetters, mapActions } = createNamespacedHelpers('PurchaseOrders')

export default {
  name: 'ModalPurchaseOrdersDetail',
  props: {
    detail: {
      type: Object
    },
    index: {
      type: Number
    },
    isAdd: {
      default: true,
      type: Boolean
    }
  },
  validations: {
    detail: {
      quantity: {
        required,
        numeric
      },
      unit_price: {
        required,
        decimal
      }
    }
  },
  async created () {
    this.getCatalog()
  },
  computed: {
    ...mapGetters([
      'isModalVisible',
      'purchaseOrdersCatalog'
    ]),
    getTitle () {
      return this.isAdd ? this.$t('purchase_orders.detail.add') : this.$t('purchase_orders.detail.edit')
    }
  },
  methods: {
    ...mapActions([
      'addPurchaseOrderDetail',
      'editPurchaseOrderDetail',
      'setModalVisible',
      'loadCatalog'
    ]),
    saveRecord () {
      this.isAdd ? this.addPurchaseOrderDetail(this.detail) : this.editPurchaseOrderDetail({ detail: this.detail, index: this.index })
    },
    async getCatalog () {
      Object.keys(this.purchaseOrdersCatalog).forEach(e => this.loadCatalog({ url: e, filter: '' }))
    },
    autoCompleteFunc (value, url) {
      this.loadCatalog({ filter: value, url: url })
    },
    close () {
      this.setModalVisible(false)
    }
  }
}
</script>
