<template>
  <div :data-vv-scope="`${identifier}${index}`">
    <b-row
      :id="`${identifier}${index}handle`"
      class="no-gutters border font-weight-bold py-sm-d-2"
      :class="{ 'border-bottom-0': length ? length - 1 !== index : false }"
    >
      <b-col
        cols="12"
        sm="2"
        class="d-flex order-2 order-sm-1 px-sm-d-2 py-sm-d-0 flex-column justify-content-center pl-4 py-3"
      >
        <span>{{ code }}</span>
      </b-col>
      <b-col
        cols="12"
        sm="6"
        class="d-flex order-1 order-sm-2 px-sm-d-2 py-sm-d-0 flex-column justify-content-center px-2 py-3"
      >
        <span>{{ title }}</span>
      </b-col>
      <b-col
        cols="12"
        sm="1"
        class="d-flex order-3 order-sm-3 px-sm-d-2 py-sm-d-0 text-md-d-left flex-column justify-content-center px-2 py-3 text-right"
      >
        <div v-if="quantity > 0">
          <span
            v-if="isDummy === true"
            :class="{ 'text-danger animated flash': errors.has('totalSelectedQuantity', identifier + index) }"
          >
            {{ totalSelectedQuantity }} </span
          ><span v-if="isDummy === true"> / </span><span>{{ quantity }}</span>
        </div>
        <div v-else>
          <span>-</span>
        </div>
      </b-col>
      <b-col
        cols="12"
        sm="3"
        class="d-flex order-4 order-sm-4 px-sm-d-2 pt-sm-d-2 pb-sm-d-0 flex-column justify-content-center px-2 py-3 text-center  text-sm-d-left"
      >
        <div>
          <b-btn
            v-if="quantity > 0 && dummies.length > 0 && isDummy === true && !expanding"
            :variant="errors.has('totalSelectedQuantity', identifier + index) ? 'outline-danger' : 'outline-primary'"
            v-b-toggle="`${identifier}${index}`"
            :class="{
              'rounded-4 px-3': true,
              'animated pulse': errors.has('totalSelectedQuantity', identifier + index),
            }"
            @click="refreshVueBar"
            :data-qa="`product-${code.toLowerCase()}-choose-size-btn`"
          >
            {{ $t('Eshop.SizeSelection.ChooseSize') }}
          </b-btn>
          <div v-else class="py-2 d-sm-d-none">
            &nbsp;
          </div>
        </div>
      </b-col>
    </b-row>
    <b-collapse
      class="w-100 no-overflow"
      :visible="expanding"
      :id="`${identifier}${index}`"
      :accordion="`${identifier}`"
      ref="collapseAccordian"
      :role="`${identifier}${index}handle`"
    >
      <div class="animated slideInDown border border-top-0">
        <div class="bg-light-extra border-y border-primary">
          <b-row class="no-gutters">
            <b-col cols="12" sm="5" offset="0" offset-md="2" class="px-2 py-3">
              <input
                v-model="search"
                type="text"
                class="form-control rounded"
                :placeholder="$t('Common.Search')"
                :data-qa="`product-${code.toLowerCase()}-size-search-input`"
              />
            </b-col>
          </b-row>
        </div>
        <div
          class="bg-light-extra"
          :class="{ 'product-choose-size': !expanding, 'nh-50': expanding }"
          v-bar="vueSidebarConfig"
          ref="vueBarSider"
        >
          <div>
            <template v-for="(filterItem, filterIndex) in filteredDummies">
              <b-row class="no-gutters" v-if="quantity > 0 && isDummy === true" :key="filterIndex">
                <b-col cols="12" sm="5" offset="0" offset-md="2" class="px-2 py-3">
                  {{ filterItem.name }}
                </b-col>
                <b-col cols="12" sm="3" class="px-2 py-3 text-right text-sm-d-left pt-sm-d-0">
                  <eshop-item-quantity
                    :quantity="selectedDummyQuantity(filterItem.id)"
                    :product-id="filterItem.id"
                    :foc-qty="focQty"
                    :process-cart-callback="dummySelectSizes"
                    :max="balanceQuantity(filterItem)"
                    ref="eshopItemQuantity"
                    variant="side"
                    :data-qa-prefix="`product-${filterItem.sku.toLowerCase()}`"
                  />
                </b-col>
              </b-row>
            </template>
          </div>
        </div>
      </div>
    </b-collapse>
  </div>
</template>
<script>
import EshopItemQuantity from './EshopItemQuantity'
import _ from 'lodash'

export default {
  name: 'Product',
  components: { EshopItemQuantity },
  inject: ['$validator'],
  props: {
    productId: { type: Number },
    kittingId: { type: Number },
    isDummy: { type: Boolean },
    isFoc: { type: Boolean },
    focQty: { type: Number, default: 0 },
    identifier: { type: String, required: true },
    index: { type: Number, default: 1 },
    length: { type: [Number, Boolean], default: false },
    code: { type: String, default: '' },
    title: { type: String, default: '' },
    quantity: { type: Number },
    dummies: { type: Array },
    selectedDummyData: { type: Array, default: () => [] },
    expanding: { type: Boolean, default: false },
    dummyId: { type: Number, default: 0 },
  },
  data() {
    return {
      selectedDummies: [],
      vueSidebarConfig: { preventParentScroll: true, resizeRefresh: true },
      search: '',
    }
  },
  mounted() {
    this.selectedDummies = this.selectedDummyData
  },
  methods: {
    selectedDummyQuantity: function(id) {
      let selectedDummyData = this.selectedDummyData.find(item => {
        return item.product_id === id
      })
      return selectedDummyData ? selectedDummyData.quantity : 0
    },
    dummySelectSizes: function(payload) {
      this.errors.remove('totalSelectedQuantity', this.identifier + this.index)
      this.errors.remove('cartError')
      let dummy =
        this.selectedDummies.find(item => {
          return item.product_id === payload.product_id
        }) || {}
      this.selectedDummies = _.unionWith([_.assign({}, dummy, payload)], this.selectedDummies, (obj1, obj2) => {
        return obj1.product_id === obj2.product_id
      })
      this.$emit('change')
      return Promise.resolve(dummy)
    },
    refreshVueBar: function(e) {
      let vue = this
      this.$nextTick(() => {
        if (typeof vue.$vuebar !== 'undefined') {
          vue.$vuebar.refreshScrollbar(vue.$refs.vueBarSider, vue.vueSidebarConfig)
        }
      })
    },
    refresh: function() {
      let self = this
      this.errors.remove('totalSelectedQuantity', this.identifier + this.index)
      this.errors.remove('cartError')
      if (Array.isArray(this.$refs.eshopItemQuantity)) {
        this.$refs.eshopItemQuantity.forEach(el => {
          this.$nextTick(() => {
            if (el.max < el.currentQuantity || el.max === 0) {
              el.refresh()
              this.search = ''
            }
          }, this)
        })
      }
      let totalQuantity = this.selectedDummyData.reduce((carry, payload) => {
        if (typeof payload.quantity !== 'undefined') {
          carry += payload.quantity
        }
        return carry
      }, 0)
      this.$nextTick(() => {
        let resetted = false
        this.selectedDummyData.forEach(function(item) {
          if (self.quantity < totalQuantity) {
            item.quantity = 0
            if (!resetted) {
              self.selectedDummies = []
              resetted = true
            }
          }
        })
      })
      if (this.$refs.collapseAccordian.show) {
        this.$refs.collapseAccordian.toggle()
      }
    },
    validate: function() {
      this.$validator.errors.remove('totalSelectedQuantity', this.identifier + this.index)
      if (this.isDummy && this.quantity !== 0 && this.totalSelectedQuantity !== this.quantity) {
        this.errors.add({
          field: 'totalSelectedQuantity',
          msg: this.$t('Eshop.SizeSelection.PleaseSelect'),
          scope: this.identifier + this.index,
          rule: 'text',
        })

        this.errors.add({
          field: 'cartError',
          msg: this.$t('Eshop.SizeSelection.PleaseSelect'),
          rule: 'text',
        })
        this.$validator.errors.add({
          field: 'totalSelectedQuantity',
          msg: this.$t('Eshop.SizeSelection.PleaseSelect'),
          rule: 'text',
          scope: this.identifier + this.index,
        })
        this.$validator.errors.add({
          field: 'cartError',
          msg: this.$t('Eshop.SizeSelection.PleaseSelect'),
          rule: 'text',
        })
      }
      return this.errors
    },
    getSelectedDummies: function() {
      if (this.isDummy) {
        return _.chain(this.selectedDummies)
          .filter(dummy => typeof dummy.quantity !== 'undefined' && dummy.quantity > 0)
          .map(dummy => {
            return {
              product_id: this.productId,
              kitting_id: this.kittingId,
              is_dummy: this.isDummy,
              is_foc: this.isFoc,
              dummy_id: this.dummyId,
              dummy: dummy,
            }
          })
          .value()
      } else {
        return [
          {
            product_id: this.productId,
            kitting_id: this.kittingId,
            is_dummy: this.isDummy,
            is_foc: this.isFoc,
            quantity: this.quantity,
            dummy_id: this.dummyId,
            dummy: [],
          },
        ]
      }
    },
  },
  computed: {
    balanceQuantity: vue => item => {
      let totalSelectableQuantity = vue.quantity
      let totalSelectedQuantity = vue.totalSelectedQuantity
      let currentItemSelected = vue.selectedDummies.find(dummy => {
        return dummy.product_id === item.id
      })
      if (currentItemSelected) {
        totalSelectableQuantity = totalSelectableQuantity + currentItemSelected.quantity
      }
      return totalSelectableQuantity - totalSelectedQuantity
    },
    totalSelectedQuantity() {
      return this.selectedDummies.reduce((carry, payload) => {
        if (typeof payload.quantity !== 'undefined') {
          carry += payload.quantity
        }
        return carry
      }, 0)
    },
    filteredDummies() {
      return this.dummies.filter(dummy => {
        return typeof dummy.name !== 'undefined' && dummy.name.toLowerCase().search(this.search.toLowerCase()) > -1
      })
    },
  },
}
</script>
