<template>
  <div class="mb-5 mb-sm-d-2">
    <b-row class="p-4 border border-bottom-0 no-gutters d-sm-d-block">
      <b-col cols="auto" class="display-image d-sm-d-none">
        <img :src="img" class="p-2" />
      </b-col>
      <b-col class="d-flex flex-column justify-content-center d-sm-d-block">
        <div class="font-weight-bold d-sm-d-inline-block">
          {{ title }}
        </div>
        <div v-if="amp" class="text-info-green font-weight-bold d-sm-d-none">
          {{ $t('Eshop.Product.CV') }} {{ ampCv }}
        </div>
        <div v-else-if="fpp" class="text-fpp font-weight-bold d-sm-d-none">
          {{ $t('Eshop.Product.CV') }} {{ fppCv }}
        </div>
        <div v-else class="text-primary font-weight-bold d-sm-d-none">{{ $t('Eshop.Product.CV') }} {{ cv }}</div>
        <div class="text-medium d-sm-d-inline-block">
          {{ code }}
        </div>
        <div class="text-secondary font-weight-bold d-sm-d-none">{{ currency }} {{ price }}</div>
      </b-col>
      <b-col
        cols="auto"
        class="text-right text-sm-d-left d-flex justify-content-center flex-column px-5 d-sm-d-block px-sm-d-0"
      >
        <h5 class="font-size-md-d-6 d-sm-d-inline-block">
          {{ $t('Eshop.SizeSelection.TotalQuantity') }}
        </h5>
        <h1 class="font-size-md-d-6 d-sm-d-inline-block">
          {{ quantity }}
        </h1>
      </b-col>
    </b-row>
    <b-row class="p-3 border border-bottom-0 no-gutters p-sm-2" :class="{ 'd-none': !isEvoucherOptionAvailable }">
      <b-col
        cols="8"
        sm="3"
        v-if="eVoucherEnabled"
        class="p-1 border border-md-0 border-right-0 d-flex flex-column justify-content-center"
      >
        <div class="font-weight-bold">
          {{ $t('Eshop.SizeSelection.EVoucher') }}
        </div>
        <div class="small">
          {{ $t('Eshop.SizeSelection.FutureRedemption') }}
        </div>
      </b-col>
      <b-col class="text-right border border-md-0 border-left-0 p-1" v-if="eVoucherEnabled">
        <label class="required pr-0 pr-md-2 font-size-sm-d-7">
          {{ $t('Common.Quantity') }}
        </label>
        <b-form-select
          class="w-auto ml-1"
          v-model="eVoucher"
          @change="updateEvoucher"
          data-qa="evoucher-quantity-select"
        >
          <option v-for="(amount, idx) in quantity + 1" :value="amount - 1" :key="idx">
            {{ amount - 1 }}
          </option>
        </b-form-select>
      </b-col>
      <b-col cols="12" md="1" class="py-2 px-3 text-center" v-if="eVoucherEnabled">
        <div class="line-devided-20">
          {{ $t('Eshop.SizeSelection.Or') }}
        </div>
      </b-col>
      <b-col cols="8" sm="3" class="border-sm-d-y p-sm-d-1 border-sm-d-left flex-column d-flex justify-content-center">
        <div class="font-weight-bold">
          {{ $t('Eshop.SizeSelection.InstantRedemption') }}
        </div>
        <div class="small">
          {{ $t('Eshop.SizeSelection.SelectSize') }}
        </div>
      </b-col>
      <b-col class="text-right border-sm-d-y border-sm-d-right py-sm-d-1 pr-sm-d-1">
        <label class="required pr-2 pr-sm-d-0 font-size-sm-d-7">
          {{ $t('Common.Quantity') }}
        </label>
        <b-form-select
          class="w-auto ml-1"
          v-model="instantRedemption"
          @change="updateInstantRedemption"
          :disabled="!eVoucherEnabled"
          data-qa="instant-quantity-select"
        >
          <option v-for="(amount, index) in quantity + 1" :value="amount - 1" :key="index">
            {{ amount - 1 }}
          </option>
        </b-form-select>
      </b-col>
    </b-row>
    <b-row class="border border-bottom-0 no-gutters bg-light-extra d-sm-d-none">
      <b-col cols="2" class="py-2 pl-4 text-medium">
        {{ $t('Eshop.SizeSelection.Code') }}
      </b-col>
      <b-col cols="6" class="p-2 text-medium">
        {{ $t('Eshop.SizeSelection.Items') }}
      </b-col>
      <b-col cols="1" class="p-2 text-medium text-right">
        {{ $t('Common.Quantity') }}
      </b-col>
    </b-row>
    <b-row :id="identifier" class="no-gutters p-sm-d-3 pt-sm-d-0 border-sm-d-x border-sm-d-bottom">
      <div v-for="(dummy, index) in dummies" :key="`dumy-${index}`" class="w-100">
        <slot name="productSize" :dummy="dummy">
          <product-choose-size
            :identifier="identifier"
            :index="index"
            :length="dummies.length"
            :code="findDummyFromDummiesProducts(dummy).sku"
            :title="findDummyFromDummiesProducts(dummy).name"
            :quantity="instantRedemption * dummy.quantity"
            :dummies="findProductsFromDummiesProducts(dummy)"
            :selected-dummy-data="getSelectedSizes(dummy.product_id, dummy.kitting_id, dummy.is_foc).data"
            :product-id="dummy.product_id"
            :kitting-id="dummy.kitting_id"
            :is-dummy="dummy.is_dummy"
            :is-foc="dummy.is_foc"
            ref="productSizeChooser"
            @change="emitChange"
          />
        </slot>
      </div>
    </b-row>
  </div>
</template>
<script>
import currencyMixin from '../../mixins/currencyMixin'
import ProductChooseSize from '../elements/ProductChooseSize'
import _ from 'lodash'

export default {
  name: 'ProductSizeSelection',
  mixins: [currencyMixin],
  components: { ProductChooseSize },
  inject: ['$validator'],
  props: {
    identifier: { type: String, required: true },
    productId: { type: Number, required: false },
    kittingId: { type: Number, required: false },
    title: { type: String, default: '' },
    img: { type: String, default: '' },
    code: { type: String, default: '' },
    amp: { type: Boolean, default: false },
    fpp: { type: Boolean, default: false },
    cv: { type: Number, default: 0 },
    ampCv: { type: Number, default: 0 },
    fppCv: { type: Number, default: 0 },
    price: { type: String, default: '' },
    quantity: { type: Number, default: 0 },
    dummies: { type: Array, default: () => [] },
    selectedEvoucherQuantity: { type: Number, default: 0 },
    selectedSizes: { type: Array, default: () => [] },
    eVoucherEnabled: { type: Boolean, default: true },
    isEvoucherOptionAvailable: { type: Boolean, default: true },
  },
  data() {
    return {
      instantRedemption: 0,
      eVoucher: 0,
    }
  },
  mounted() {
    this.eVoucher = this.selectedEvoucherQuantity
    this.instantRedemption = this.quantity - this.eVoucher
  },
  methods: {
    updateInstantRedemption: function(to) {
      this.instantRedemption = to
      this.eVoucher = this.quantity - to
      this.refreshDummySelectedQuantities()
    },
    updateEvoucher: function(to) {
      this.eVoucher = to
      this.instantRedemption = this.quantity - to
      this.refreshDummySelectedQuantities()
    },
    refreshDummySelectedQuantities: function() {
      this.$refs.productSizeChooser.forEach(el => {
        el.refresh()
      })
      this.$emit('change', this.getSelectedDummies())
    },
    validate() {
      this.$refs.productSizeChooser.forEach(async el => {
        this.errors.items = await el.validate().items
      })
      return this.errors
    },
    getSelectedDummies() {
      let selectedDummies = []
      this.$refs.productSizeChooser.forEach(el => {
        selectedDummies = _.union(selectedDummies, el.getSelectedDummies())
      })
      let results = {
        sizes:
          this.instantRedemption !== 0
            ? _.chain(selectedDummies)
                .groupBy(function(note) {
                  return _.values(_.pick(note, ['product_id', 'kitting_id', 'is_foc'])).join('-')
                })
                .map(obj => {
                  let newobj = {}
                  newobj.product_id = obj[0].product_id
                  newobj.kitting_id = obj[0].kitting_id
                  newobj.is_dummy = obj[0].is_dummy
                  newobj.is_foc = obj[0].is_foc
                  newobj.data = _.chain(obj)
                    .map(x => _.clone(x.dummy))
                    .filter(x => typeof x.quantity !== 'undefined')
                    .value()
                  if (newobj.is_dummy) {
                    newobj.quantity = _.reduce(
                      newobj.data,
                      (carry, dummy) => {
                        carry += dummy.quantity
                        return carry
                      },
                      0
                    )
                  } else {
                    newobj.quantity = obj[0].quantity
                  }
                  return newobj
                })
                .value()
            : [],
        evoucher: [
          {
            product_id: this.productId,
            kitting_id: this.kittingId,
            quantity: this.eVoucher,
          },
        ],
      }
      return results
    },
    getSelectedSizes(productId, kittingId, isFoc) {
      return (
        this.selectedSizes.find(item => {
          return (
            (item.kitting_id === kittingId && item.product_id === productId && item.is_foc === isFoc) ||
            (item.kitting_id === null && item.product_id === productId && item.is_foc === isFoc)
          )
        }) || { quantity: 0, data: [] }
      )
    },
    emitChange() {
      this.$emit('change', this.getSelectedDummies())
    },
  },
  computed: {
    quantityToRedeem() {
      return this.quantity - this.eVoucher
    },
    quantityToEVoucher() {
      return this.quantity - this.instantRedemption
    },
    findDummyFromDummiesProducts: vue => dummy => {
      if (dummy) {
        if (typeof dummy.dummy_products !== 'undefined') {
          return dummy.dummy_products.find(dummyProduct => {
            return dummyProduct.is_dummy_code === 1
          })
        } else {
          return dummy
        }
      } else {
        return {
          sku: '',
          name: '',
        }
      }
    },
    findProductsFromDummiesProducts: vue => dummy => {
      if (dummy) {
        if (typeof dummy.dummy_products !== 'undefined') {
          return dummy.dummy_products.filter(dummyProduct => {
            return dummyProduct.is_dummy_code === 0
          })
        } else {
          return [dummy]
        }
      }
    },
  },
}
</script>
