<template>
  <b-overlay :show="showLoadingScreen" variant="white" :class="{ 'vh-100': showLoadingScreen }" opacity="0.97">
    <template v-slot:overlay>
      <b-row class="align-items-baseline text-center text-primary">
        <b-col class="px-0 m-2" cols="12" md="auto">
          <b-spinner />
        </b-col>
        <b-col class="px-0">
          <strong class="h4">{{ $t('MyBundle.GenerateBundle.Loading.text') }}</strong>
        </b-col>
      </b-row>
    </template>

    <div>
      <b-row>
        <b-col v-if="!isUpdate" cols="12" class="mb-3">
          <h5 class="mb-4 text-black">{{ $t('MyBundle.GenerateBundle.BundleCountry') }}</h5>
          <b-row>
            <b-col cols="12" md="4">
              <b-form-select
                :name="$t('MyBundle.GenerateBundle.BundleCountry')"
                :options="getCountries"
                text-field="custom_text"
                @change="updateBundleCountry"
                v-model="selectedBundleCountry"
                data-qa="myBundle-selectProductStep-bundleCountry-select"
              />
            </b-col>
          </b-row>
          <hr />
        </b-col>

        <b-col cols="12" id="product-selection" class="eshop">
          <h5 class="mb-4 text-black">{{ $t('MyBundle.GenerateBundle.SelectProduct') }}</h5>
          <div class="eshop-products-wrapper">
            <product-filter
              :filter-setter="setBundleProductFilter"
              :load-product-bypass="loadProductByPass"
              :filter-options="getSortedProductMainCategoriesOptions"
            />

            <div class="text-right my-2">
              <span class="mr-2">{{ $t('Common.Layout.Label') }}:</span>
              <b-button variant="outline-primary" @click="layoutToggle" class="px-2 rounded-circle">
                <icon :name="displayGrid ? 'th-large' : 'bars'" />
              </b-button>
            </div>

            <product-list
              class="col"
              :simple="false"
              :allow-disable="false"
              :products-getter="getProducts"
              identifier="myBundle-products"
              :is-popup-product-viewer="true"
              :get-custom-product-details="true"
              :show-product-previewer-action-bar="false"
              :product-quantity-getter="getProductUnitQuantity"
              :add-product-to-cart-bypass="addProductToCartBypass"
              :default-sale-type-keys="['registration', 'formation', 'repurchase', 'auto-maintenance']"
            />

            <pagination
              name="myBundle-products"
              :total="getProductTotal"
              @getData="loadProductByPass"
              class="eshop-pagination text-center"
              :per-page="getBundleProductFilter.perPage"
              :disabled="isLoading('myBundle-products')"
              data-qa-prefix="myBundle-selectProductStep"
            />
          </div>
        </b-col>
      </b-row>
    </div>

    <div v-if="showHeaderCartBtn" class="my-bundle">
      <my-bundle-cart
        id="my-bundle-cart"
        :currency-symbol="currency || ''"
        :sub-total-price="getCartSubTotal"
        data-qa-prefix="myBundle-selectProductStep"
        :checkout-action="() => navigateNext(false)"
        :add-product-call-back="addProductToCartBypass"
        :product-list="getBundleCartDetails.bundleItems"
        :remove-product-call-back="removeProductFromCart"
        :product-quantity-getter="getProductUnitQuantity"
        :action-button-text="$t('Common.Continue')"
        :checkout-loader="isLoading('updatingBundleCart')"
      />
    </div>
  </b-overlay>
</template>

<script>
import _ from 'lodash'
import { mapGetters, mapActions } from 'vuex'
import { getValue } from '@/helpers/variable-handling'
import { CurrencyMixin, mapMasterDataId } from '@/app/_global/mixins'
import Pagination from '@/app/_global/components/elements/Pagination'
import ProductList from '@/app/_global/components/elements/ProductList'
import componentProps from '../fixtures/validated-route-component-props'
import ProductFilter from '@/app/_global/components/elements/ProductFilter'
import MyBundleCart from '@/app/my-bundle/wizard/components/block/MyBundleCart'

export default {
  name: 'SelectProductStep',
  components: { MyBundleCart, ProductFilter, ProductList, Pagination },
  mixins: [CurrencyMixin],
  props: {
    ...componentProps,
  },
  data() {
    return {
      selectedBundleCountry: null,
    }
  },
  computed: {
    ...mapMasterDataId({
      SALE_TYPES: {
        repurchaseSalesTypeId: 'RE_PURCHASE',
      },
    }),
    ...mapGetters([
      'isLoading',
      'getAppLocationCountry',
      'getPagination',
      'getLayoutMode',
      'getCountries',
      'getMemberCountryId',
    ]),
    ...mapGetters('eshop', ['getProducts', 'getProductTotal', 'getSortedProductMainCategoriesOptions']),
    ...mapGetters('myBundle', [
      'getBundleProductFilter',
      'getBundleCartDetails',
      'getProductUnitQuantity',
      'getBundleCountryId',
    ]),
    isUpdate() {
      return Boolean(this.$route.query.id)
    },
    showLoadingScreen() {
      let loadingState = ['loadingBundleDetails']
      return this.isLoading(loadingState)
    },
    displayGrid() {
      return this.getLayoutMode('myBundle-products', 'grid') === 'grid'
    },
    getCartSubTotal() {
      let cart = this.getBundleCartDetails.bundleItems || []
      return cart.reduce(
        (accum, current) => {
          return {
            memberPrice:
              accum.memberPrice + Number(current.product_quantity) * Number(current.product_prices.gmp_price_tax),
            retailPrice:
              accum.retailPrice + Number(current.product_quantity) * Number(current.product_prices.rp_price_tax),
          }
        },
        { memberPrice: 0, retailPrice: 0 }
      )
    },
    showHeaderCartBtn() {
      return this.$route.meta.showHeaderCart
    },
  },
  watch: {
    getBundleCountryId() {
      this.loadProductByPass()
    },
  },
  async mounted() {
    let bundleCountry = this.getBundleCountryId
    await this.resolveMasters

    if (this.getBundleCartDetails.validate !== true) {
      bundleCountry = this.getMemberCountryId
      this.layoutBlocks({ block: 'myBundle-products', layout: 'grid' })
      this.loadProductCategories({ setCategory: false })
      if (this.isUpdate) {
        await this.loadBundleDetails(this.$route.query.id).then(response => {
          if (response && response.bundle_country_id) {
            bundleCountry = response.bundle_country_id
            this.setBundleCartDetails(response)
          }
        })
      }
      await this.updateBundleCountry(bundleCountry, false)
    }
    this.selectedBundleCountry = bundleCountry
  },
  methods: {
    ...mapActions(['layoutBlocks']),
    ...mapActions('eshop', ['loadProducts', 'loadProductCategories']),
    ...mapActions('myBundle', [
      'setBundleProductFilter',
      'addProductToBundleCart',
      'setBundleCartDetails',
      'loadBundleDetails',
      'setBundleCountry',
    ]),
    async loadProductByPass() {
      await this.loadProducts({
        identifier: 'myBundle-products',
        name: this.getBundleProductFilter.search,
        countryId: this.getAppLocationCountry.countryId,
        locationId: this.getAppLocationCountry.locationId,
        sortOrder: this.getBundleProductFilter.selectedSort,
        categoryIds:
          (this.getBundleProductFilter.selectedCategory && [this.getBundleProductFilter.selectedCategory]) || [],
        ek_smart: false,
        salesTypesIds: [this.repurchaseSalesTypeId],
        pagination: {
          limit: getValue(this.getPagination('myBundle-products'), 'limit', this.getBundleProductFilter.perPage),
          offset: getValue(this.getPagination('myBundle-products'), 'offset', 0),
        },
      })
    },
    layoutToggle() {
      let layout = (this.displayGrid && 'list') || 'grid'
      this.layoutBlocks({ block: 'myBundle-products', layout })
    },
    async addProductToCartBypass(params) {
      params = {
        productName: getValue(params, 'custom.name', ''),
        productSku: getValue(params, 'custom.sku', ''),
        productPrice: getValue(params, 'custom.prices', {}),
        kittingId: params.kitting_id,
        productId: params.product_id,
        productQuantity: params.quantity,
        productSaleTypeId: params.salesTypeId,
      }
      await this.addProductToBundleCart(params)
    },
    removeProductFromCart({ product_sku }) {
      let params = { productSku: product_sku, productQuantity: 0 }
      this.addProductToBundleCart(params)
    },
    validateAndSubmit() {
      let cartDetails = _.cloneDeep(this.getBundleCartDetails)
      let valid = cartDetails.bundleItems.length > 0

      if (valid) {
        let payload = {
          bundle_items: cartDetails.bundleItems,
          bundle_total: {
            member_price: this.getCartSubTotal.memberPrice,
            retail_price: this.getCartSubTotal.retailPrice,
          },
          validate: valid,
        }
        this.setBundleCartDetails(payload)
      } else {
        this.$swal({
          title: this.$t('Common.Cart.EmptyCart'),
          text: this.$t('MyBundle.GenerateBundle.Error.CartEmpty.HelpText', { lowerBoundary: 1 }),
          type: 'warning',
        })
      }
      return valid
    },
    async updateBundleCountry(value, clearCart = true) {
      let flag = true
      if (this.getBundleCartDetails.bundleItems.length && clearCart) {
        let countryName = (this.getCountries.find(country => country.value === value) || {}).custom_text

        await this.$swal({
          type: 'warning',
          title: this.$t('MyBundle.GenerateBundle.RegionClearCart.Title', { to: countryName || '' }),
          text: this.$t('MyBundle.GenerateBundle.RegionClearCart.Message'),
          confirmButtonText: this.$t('Common.Proceed'),
          cancelButtonText: this.$t('Common.Cancel'),
          showCancelButton: true,
        }).then(res => {
          if (res.value) {
            this.setBundleCartDetails() // clear cart
          } else {
            flag = false
          }
        })
      }

      if (flag) {
        await this.setBundleCountry(value)
      } else {
        this.selectedBundleCountry = this.getBundleCountryId // undo changes
      }
    },
  },
}
</script>
