<template>
  <div>
    <template v-for="promo in promotions">
      <div class="px-0 py-2" v-if="validatePromoType(promo.promo_type_id)" :key="`foc-${promo.promo_id}`">
        <div class="table table-bordered pl-2 px-3">
          <div class="row pl-3 py-3 border-bottom">
            <span class="font-weight-bold-extra">
              {{ promo.name }}
            </span>
          </div>
          <div class="row options" v-for="(option, indexOptions) in promo.conditions.options" :key="indexOptions">
            <div
              class="col border-right py-3"
              :class="{ 'border-bottom': indexOptions < promo.conditions.options.length - 1 }"
            >
              <span
                v-if="indexOptions > 0"
                style="top: -13px;"
                class="position-absolute bg-light font-weight-bold-extra text-white rounded-4 py-1 px-3"
              >
                {{
                  promo.conditions.operator === 'OR'
                    ? $t('Eshop.Order.FocPwp.OperatorOr')
                    : $t('Eshop.Order.FocPwp.OperatorAnd')
                }}
              </span>
              <span class="text-danger">
                {{ $t('Eshop.Order.FocPwp.ChooseOne') }}
              </span>
              <div>{{ promo.currency.code }} 0.00</div>
            </div>
            <div
              class="col-md-10 col-sm-12 option-set"
              :class="{ 'border-bottom': indexOptions < promo.conditions.options.length - 1 }"
            >
              <div v-for="(set, optionKey) in option" :key="`option-${optionKey}`">
                <template v-for="(product, setKey, setIndex) in set">
                  <div v-if="setKey !== 'option_id'" class="option-product row" :key="`set-${setIndex}`">
                    <div class="col-12 col-md-9 col-xl-10">
                      <div v-for="(item, itemsKey) in product" class="row py-2" :key="`items-${itemsKey}`">
                        <div class="col-lg-1 col-sm-2 mr-2">
                          <img :src="getImage(item.product.product_images)" class="order-item-image" />
                        </div>
                        <div class="col-xl-9 col-lg-8 col-md-7 col-sm-6 d-flex align-items-center">
                          <span class=""> {{ item.product.sku }} {{ item.product.name }} x {{ item.quantity }} </span>
                        </div>
                      </div>
                    </div>
                    <div class="py-2 col-auto h-auto d-flex justify-content-end align-items-center pr-0 mb-2 mb-md-0">
                      <b-btn
                        :class="{ active: isActive(promo, optionKey, setKey) }"
                        class="btn-select border-primary rounded-4 px-4"
                        @click="setSelectedFoc(promo, optionKey, setKey)"
                        :data-qa="`product-foc-${setIndex}-select-btn`"
                      >
                        {{ $t('Eshop.Order.FocPwp.Select') }}
                      </b-btn>
                    </div>
                    <div v-if="setIndex < Object.keys(set).length - 1" class="w-100 line-devided">
                      {{ $t('Eshop.Order.FocPwp.OperatorOr') }}
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'

export default {
  name: 'Focitem',
  components: {},
  data() {
    return {
      promotions: [],
      promotionLength: 0,
      price: 0,
      image: '/static/products/img-placeholder.svg',
      selected: null,
      selectedAnd: [],
    }
  },
  mounted() {
    this.populateData()
  },
  computed: {
    ...mapGetters('eshop', ['getEligiblePromotion']),
    ...mapMasterDataId({
      PROMOTION_FREE_ITEM_PROMO_TYPES: {
        focId: 'PROMO_TYPE_FOC',
      },
    }),
  },
  methods: {
    ...mapActions('eshop', ['setSelectedFocItems', 'setFocSelectionComplete']),
    getImage(productImage) {
      if (
        typeof productImage === 'undefined' ||
        productImage === null ||
        productImage === '' ||
        productImage.length === 0
      ) {
        return this.image
      }
      return productImage[0].image_link
    },
    isActive(promo, optionName, setName) {
      if (promo.conditions.operator === 'AND') {
        return (
          typeof this.selectedAnd.find(
            x => x.promoId === promo.promo_id && x.optionName === optionName && x.setName === setName
          ) !== 'undefined'
        )
      }
      return promo.promo_id + optionName + setName === this.selected
    },
    setSelectedFoc(promo, optionName, setName) {
      this.setFocSelectionComplete(false)
      let products = []
      let promoId = promo.promo_id
      if (promo.conditions.operator === '' || promo.conditions.operator === 'OR') {
        this.selected = promoId + optionName + setName
        products = this.populateItems(promoId, optionName, setName)
        this.setFocSelectionComplete(true)
      } else {
        if (typeof this.selectedAnd.find(x => x.promoId === promoId && x.optionName === optionName) === 'undefined') {
          this.selectedAnd.push({ promoId, optionName, setName })
        } else {
          for (let index = this.selectedAnd.length - 1; index >= 0; index--) {
            if (this.selectedAnd[index].promoId === promoId && this.selectedAnd[index].optionName === optionName) {
              this.selectedAnd.splice(index, 1)
            }
          }
          this.selectedAnd.push({ promoId, optionName, setName })
        }
        this.selectedAnd.forEach(sel => {
          let productList = this.populateItems(sel.promoId, sel.optionName, sel.setName)
          productList.forEach(product => {
            products.push(product)
          })
        })
        if (this.selectedAnd.length === this.promotionLength) {
          this.setFocSelectionComplete(true)
        }
      }
      this.setSelectedFocItems(products)
    },
    populateItems(promoId, optionName, setName) {
      let products = []
      this.promotions.forEach(promo => {
        if (promo.promo_id === promoId) {
          let promoType = promo.promo_type_id
          promo.conditions.options.forEach(option => {
            if (Object.keys(option)[0] === optionName) {
              option[optionName][setName].forEach(set => {
                products.push({
                  product_id: set['product']['id'],
                  sku: set['product']['sku'],
                  name: set['product']['name'],
                  image: this.getImage(set['product']['image']),
                  promo_type: promoType,
                  quantity: set['quantity'],
                  price: this.price,
                  promo_id: promo.promo_id,
                  option_id: set['option_id'],
                  set_id: set['id'],
                  operator: promo.conditions.operator,
                  currency: promo.currency,
                  set_key: setName,
                  selected_quantity: set['quantity'],
                })
              })
            }
          })
        }
      })
      return products
    },
    validatePromoType(type) {
      return type === this.focId
    },
    populateData() {
      this.promotions = this.getEligiblePromotion
      this.promotions.forEach(promotion => {
        if (promotion.promo_type_id === this.focId) {
          this.promotionLength += promotion.conditions.options.length
        }
      })
    },
  },
}
</script>
