<template>
  <div>
    <template v-for="promo in promotions">
      <div class="px-0 py-2" v-if="validatePromoType(promo.promo_type_id)" :key="`pwp-${promo.promo_id}`">
        <div class="table table-bordered pl-2 px-3">
          <div class="row pl-3 py-3 border-bottom justify-content-between">
            <span class="font-weight-bold-extra">
              {{ promo.name }}
            </span>
            <b-btn
              v-if="promo.promo_type_id !== pwpfId && isPromoSelected(promo)"
              class="bg-transparent text-danger border-danger rounded-4 px-3 py-0 mr-2"
              @click="removeItems(promo)"
              data-qa="remove-selection-btn"
            >
              {{ $t('Eshop.Order.FocPwp.RemoveSelection') }}
            </b-btn>
          </div>
          <div class="row options" v-for="(option, indexOptions) in promo.conditions.options" :key="indexOptions">
            <div
              class="col border-right py-4"
              :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 }} {{ parseFloat(promo.pwp_value).toFixed(2) }}</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 class="option-product row" :key="`set-${setIndex}`" v-if="setKey !== 'option_id'">
                    <div class="col-12 col-md-9 col-xl-10">
                      <div v-for="(item, itemIndex) in product" :key="`item-${itemIndex}`" class="row py-2">
                        <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-3 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="setSelectedPwp(promo, optionKey, setKey)"
                        :data-qa="`product-foc-${optionKey}-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'
import _ from 'lodash'

export default {
  name: 'Pwpitem',
  components: {},
  data() {
    return {
      promotions: [],
      price: 0,
      image: '/static/products/img-placeholder.svg',
      selected: [],
      selectedAnd: [],
    }
  },
  mounted() {
    this.populateData()
  },
  computed: {
    ...mapGetters('eshop', ['getEligiblePromotion', 'getSelectedPwpItems', 'getPwpSelectionComplete']),
    ...mapMasterDataId({
      PROMOTION_FREE_ITEM_PROMO_TYPES: {
        pwpfId: 'PROMO_TYPE_PWPF',
        pwpnId: 'PROMO_TYPE_PWPN',
      },
    }),
  },
  methods: {
    ...mapActions('eshop', ['addProductToCart', 'setSelectedPwpItems', 'setPwpSelectionComplete']),
    getImage(productImage) {
      if (
        typeof productImage === 'undefined' ||
        productImage === null ||
        productImage === '' ||
        productImage.length === 0
      ) {
        return this.image
      }
      return productImage[0].image_link
    },
    removeItems(promo) {
      this.selected = this.selected.filter(x => x.promoId !== promo.promo_id)
      this.selectedAnd = this.selectedAnd.filter(x => x.promoId !== promo.promo_id)
      this.setSelectedPwpItems(this.getSelectedPwpItems.filter(x => x.promo_id !== promo.promo_id))
    },
    isPromoSelected(promo) {
      return (
        this.selected.find(x => x.promoId === promo.promo_id) !== undefined ||
        this.selectedAnd.find(x => x.promoId === promo.promo_id) !== undefined
      )
    },
    isActive(promo, optionName, setName) {
      if (promo.conditions.operator === 'AND') {
        return (
          this.selectedAnd.find(
            x => x.promoId === promo.promo_id && x.optionName === optionName && x.setName === setName
          ) !== undefined
        )
      } else {
        return (
          this.selected.find(
            x => x.promoId === promo.promo_id && x.optionName === optionName && x.setName === setName
          ) !== undefined
        )
      }
    },
    setSelectedPwp(promo, optionName, setName) {
      let products = []
      let promoId = promo.promo_id
      if (promo.conditions.operator === '' || promo.conditions.operator === 'OR') {
        for (let index = this.selected.length - 1; index >= 0; index--) {
          if (this.selected[index].promoId === promoId) {
            this.selected.splice(index, 1)
          }
        }
        this.selected.push({ promoId, optionName, setName })
      } 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.setSelectedItems(products)
      this.setPwpSelectionCompletion()
    },
    setPwpSelectionCompletion() {
      this.setPwpSelectionComplete(true)
      this.promotions.forEach(promo => {
        if (promo.promo_type_id === this.pwpfId) {
          if (promo.conditions.operator === '' || promo.conditions.operator === 'OR') {
            if (this.selected.find(x => x.promoId === promo.promo_id) === undefined) {
              this.setPwpSelectionComplete(false)
            }
          } else {
            if (
              this.selectedAnd.find(x => x.promoId === promo.promo_id) !== undefined &&
              promo.conditions.options.length !== this.selectedAnd.filter(x => x.promoId === promo.promo_id).length
            ) {
              this.setPwpSelectionComplete(false)
            }
          }
        } else {
          if (
            promo.conditions.operator === 'AND' &&
            this.selectedAnd.find(x => x.promoId === promo.promo_id) !== undefined &&
            promo.conditions.options.length !== this.selectedAnd.filter(x => x.promoId === promo.promo_id).length
          ) {
            this.setPwpSelectionComplete(false)
          }
        }
      })
    },
    setSelectedItems(products) {
      this.selected.forEach(sel => {
        let productList = this.populateItems(sel.promoId, sel.optionName, sel.setName)
        productList.forEach(product => {
          products.push(product)
        })
      })
      this.selectedAnd.forEach(sel => {
        let productList = this.populateItems(sel.promoId, sel.optionName, sel.setName)
        productList.forEach(product => {
          products.push(product)
        })
      })
      this.setSelectedPwpItems(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: promo.pwp_value,
                  promo_id: set['promo_id'],
                  option_id: set['option_id'],
                  set_id: set['id'],
                  operator: promo.conditions.operator,
                  set_key: setName,
                  selected_quantity: set['quantity'],
                })
              })
            }
          })
        }
      })
      return products
    },
    validatePromoType(type) {
      return type === this.pwpfId || type === this.pwpnId
    },
    populateData() {
      this.promotions = _.orderBy(this.getEligiblePromotion, 'promo_type_id', 'desc')
      this.setPwpSelectionComplete(true)
      if (this.promotions.find(promo => promo.promo_type_id === this.pwpfId) !== undefined) {
        this.setPwpSelectionComplete(false)
      }
      return true
    },
  },
}
</script>
