<template>
  <div>
    <b-modal
      :id="identifier"
      centered
      no-close-on-backdrop
      size="lg"
      :title="$t('OrderHistory.Detail.eVoucher.SelectSize.PleaseSelectSize')"
      header-class="border-bottom"
      footer-class="justify-content-md-end justify-content-center"
      :ok-title="$t('Common.Confirm')"
      :cancel-title="$t('Common.Cancel')"
      @ok="confirm"
      cancel-variant="link"
    >
      <b-container class="eshop p-0 nh-75">
        <b-row :id="identifier" class=" no-gutters">
          <div v-for="(dummy, index) in getProductOrKittingDummies(null, null, product)" class="w-100" :key="index">
            <slot name="productSize" :dummy="dummy">
              <span class="text-danger animated" :class="{ flash: errors.items.length > 0 }">{{
                $helpers.getValue(errors, 'items[0].msg', '')
              }}</span>
              <product-choose-size
                :identifier="identifier"
                :index="index"
                :length="product.dummy.dummy_products.length"
                :code="findDummyFromDummiesProducts(dummy).sku"
                :title="findDummyFromDummiesProducts(dummy).name"
                :quantity="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"
                :dummy-id="dummy.id"
                :is-foc="dummy.is_foc"
                :foc-qty="product.foc_qty"
                ref="productSizeChooser"
                :expanding="expanding"
              />
            </slot>
          </div>
        </b-row>
      </b-container>
    </b-modal>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import ProductChooseSize from '@/app/_global/components/elements/ProductChooseSize'
import _ from 'lodash'

export default {
  name: 'OrderHistoryEvoucherSizing',
  components: { ProductChooseSize },
  inject: ['$validator'],
  props: {
    identifier: { type: String, required: true },
    selectedSizes: { type: Array, default: () => [] },
    evoucher: null,
    product: null,
  },
  data() {
    return {
      sizeList: '',
      maxQuantity: 0,
      chosenQty: 0,
      showMaxQtyNotice: false,
      isQuantityChanged: false,
      instantRedemption: 0,
      expanding: true,
    }
  },
  methods: {
    ...mapActions('orderhistory', ['setSalesVoucherToRedeem']),
    getSelectedDummies() {
      if (this.$refs.productSizeChooser !== undefined) {
        let selectedDummies = []
        this.$refs.productSizeChooser.forEach(el => {
          selectedDummies = _.union(selectedDummies, el.getSelectedDummies())
        })
        let results = {
          sizes: _.chain(selectedDummies)
            .groupBy(function(note) {
              return _.values(_.pick(note, ['product_id', 'kitting_id', 'is_foc'])).join('-')
            })
            .map(obj => {
              let newobj = {}
              newobj.voucher_id = this.evoucher.id
              newobj.product_id = obj[0].product_id
              newobj.kitting_id = obj[0].kitting_id
              newobj.dummy_id = obj[0].dummy_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' && x.quantity > 0)
                .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: [
            {
              voucher_id: this.evoucher.id,
              product_id: this.product.product_id,
              kitting_id: this.product.kitting_id,
              quantity: this.product.quantity,
            },
          ],
        }
        return results
      } else {
        return { sizes: [], evoucher: [] }
      }
    },
    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: [] }
      )
    },
    validate() {
      this.$refs.productSizeChooser.forEach(el => {
        this.errors.items = el.validate().items
      })
      return this.errors
    },
    async confirm(bvModalEvt) {
      bvModalEvt.preventDefault()
      if ((await this.validate().items.length) === 0) {
        this.$emit('change', this.getSelectedDummies())
        this.$bvModal.hide(this.identifier)
      }
    },
  },
  watch: {
    product: function(newVal, oldVal) {},
  },
  computed: {
    ...mapGetters('eshop', ['getProductOrKittingDummies']),
    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>
