<template>
  <div>
    <slot name="title" v-if="getCartDummies.length > 0"></slot>
    <div v-for="(productOrKitting, index) in getCartDummies" :key="`cart-dummies-${index}`">
      <product-size-selection
        :identifier="`productSelection${index}`"
        :e-voucher-enabled="eVoucherEnabled"
        :product-id="productOrKitting.product_id"
        :kitting-id="productOrKitting.kitting_id"
        :img="productOrKitting.image"
        :title="productOrKitting.name"
        :quantity="productOrKitting.quantity"
        :cv="productOrKitting.total_cv.basic"
        :amp="typeof productOrKitting.total_cv.amp !== 'undefined'"
        :amp-cv="productOrKitting.total_cv.amp"
        :fpp="typeof productOrKitting.total_cv.fpp !== 'undefined'"
        :fpp-cv="productOrKitting.total_cv.fpp"
        :code="productOrKitting.sku"
        :price="productOrKitting.price"
        :selected-evoucher-quantity="selectedEvoucherQuantity(productOrKitting.product_id, productOrKitting.kitting_id)"
        :selected-sizes="selectedSizes(productOrKitting.product_id, productOrKitting.kitting_id)"
        :dummies="getProductOrKittingDummies(productOrKitting.product_id, productOrKitting.kitting_id)"
        :is-evoucher-option-available="isEvoucherOptionAvailable"
        @change="saveChanges"
        ref="producSizeSelection"
      />
    </div>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import ProductSizeSelection from '@/app/_global/components/blocks/ProductSizeSelection'
import _ from 'lodash'

export default {
  name: 'SelectSizes',
  inject: ['$validator'],
  components: { ProductSizeSelection },
  props: {
    eVoucherEnabled: {
      type: Boolean,
      default: true,
    },
    isEvoucherOptionAvailable: {
      type: Boolean,
      default: true,
    },
  },
  watch: {
    getCartDummies: {
      async handler() {
        await this.loadCartSizesDetails()
      },
      immediate: true,
    },
  },
  mounted() {
    this.removeError('cartError')
  },
  methods: {
    ...mapActions('eshop', ['loadCartSizesDetails', 'selectCartProductsSizes']),
    ...mapActions(['logError', 'removeError']),
    async validate() {
      this.removeError('cartError')
      if (this.getCartDummies.length > 0) {
        this.$refs.producSizeSelection.forEach(async product => {
          if (typeof product.validate === 'function') {
            this.errors.items = await product.validate().items
          }
        })

        if (this.errors.items.length === 0) {
          this.logError({ cartError: '' })
          this.saveChanges()
          return true
        } else {
          this.$scrollTo('[data-vv-scope="' + this.errors.items[0].scope + '"]', { offset: -100 })
          this.logError({ cartError: this.errors.first('cartError') })
          return false
        }
      } else {
        return true
      }
    },
    selectedEvoucherQuantity(productId, kittingId) {
      let quantity = 0
      if (this.$helpers.isSet(this.getCartIsAllDummiesSelected, 'evoucher')) {
        let selectedDumy = this.getCartIsAllDummiesSelected['evoucher'].find(evoucher => {
          return evoucher.product_id === productId && evoucher.kitting_id === kittingId
        })
        quantity = selectedDumy ? selectedDumy.quantity : 0
      }
      return quantity
    },
    selectedSizes(productId, kittingId) {
      let selectedSizes = []
      if (this.$helpers.isSet(this.getCartIsAllDummiesSelected, 'sizes')) {
        selectedSizes =
          this.getCartIsAllDummiesSelected['sizes'].filter(size => {
            return (
              (size.kitting_id !== null && size.kitting_id !== null && size.kitting_id === kittingId) ||
              (size.product_id !== null && size.product_id !== null && size.product_id === productId)
            )
          }) || []
      }
      return selectedSizes
    },
    saveChanges() {
      let selectedDummies = {
        sizes: [],
        evoucher: [],
      }
      this.$refs.producSizeSelection.forEach(product => {
        if (typeof product.getSelectedDummies === 'function') {
          let dummySelection = product.getSelectedDummies()
          selectedDummies.sizes = _.union(selectedDummies.sizes, dummySelection.sizes)
          selectedDummies.evoucher = _.union(selectedDummies.evoucher, dummySelection.evoucher)
        }
      })
      this.selectCartProductsSizes(selectedDummies)
    },
  },
  computed: {
    ...mapGetters('eshop', [
      'getCartDummies',
      'getCartProductQuantity',
      'getProductOrKittingDummies',
      'getCartIsAllDummiesSelected',
    ]),
  },
}
</script>
