<template>
  <div>
    <b-row class="position-relative eshop">
      <b-col cols="12" lg="8" md="7" xl="8">
        <b-card>
          <b-card-title class="text-black">{{ $t('Autoship.AutoshipCountry') }}</b-card-title>
          <b-row>
            <b-col cols="12" md="5">
              <b-form-select
                :name="$t('Autoship.AutoshipCountry')"
                v-model="selectedCountry"
                :options="getCountries"
                text-field="custom_text"
                data-qa="autoship-select-product-country-select"
              />
            </b-col>
          </b-row>
        </b-card>
        <b-card class="my-3">
          <b-card-title class="text-black">{{ $t('Common.CheckoutSteps.SelectProduct') }}</b-card-title>
          <b-col id="product-selection" class="px-0">
            <div class="eshop-products-wrapper">
              <product-filter
                class="mb-3"
                :filter-setter="setAutoshipSearchFilter"
                :load-product-bypass="loadProductBypass"
                :filter-options="getSortedProductMainCategoriesOptions"
                ref="productFilter"
              />
              <div class="container">
                <product-list
                  identifier="autoship-products"
                  :simple="false"
                  :allow-disable="false"
                  :default-sale-type-keys="['repurchase']"
                  :add-product-to-cart-bypass="addProductToCartBypass"
                  :products-getter="getProducts"
                  :product-quantity-getter="getCartProductQuantity"
                  :is-popup-product-viewer="true"
                  :eshop-quantity-selector-buttons-wrapper-class="['px-3', 'px-md-2', 'px-xl-3']"
                />
                <pagination
                  :disabled="isLoading('autoship-products')"
                  class="eshop-pagination text-center"
                  name="autoship-products"
                  :total="getProductTotal"
                  :per-page="getAutoshipSearchFilter.perPage"
                  data-qa-prefix="autoship-select-product"
                />
              </div>
            </div>
          </b-col>
        </b-card>
      </b-col>
      <b-col cols="12" lg="4" md="5" xl="4">
        <b-card class="sticky-top">
          <b-card-body>
            <h5 class="text-black">{{ $t('Common.Checkout.SelectProducts.HelpText') }}</h5>
            <span v-show="getErrors('productError')" class="help text-danger animated flash">
              {{ getErrors('productError') }}
            </span>
            <span v-show="getCheckout.status === false" class="help text-danger animated flash">
              {{ getCheckout.messages.default }}
            </span>
            <div class="product-container custom-scroll-bar">
              <div class="selected-item-list overflow-y-auto">
                <div
                  v-for="(item, index) in getCartDisplayItemsWithMemberKit"
                  :key="`product-cart-${index}-${item.product_id}-${item.kitting_id}`"
                  class="divider p-2 clearfix"
                  :class="{ 'bg-light-extra': item.memberKit }"
                >
                  <b-button
                    variant="link"
                    class="float-right p-0"
                    v-if="item.memberKit === false"
                    @click="
                      addProductToCart({
                        countryId: getAppLocationCountry.countryId,
                        locationId: getAppLocationCountry.locationId,
                        product_id: item.product_id,
                        kitting_id: item.kitting_id,
                        quantity: 0,
                      })
                    "
                    :data-qa="`autoship-cart-product-${item.sku.toLowerCase()}-remove-product-btn`"
                  >
                    <icon name="eshop-remove" class="text-light icon-size-3" />
                  </b-button>
                  <div class="float-right text-right clearfix mt-4">
                    <div
                      class="text-info-green font-weight-bold"
                      v-if="typeof item.total_cv.amp !== 'undefined' && item.total_cv.amp !== 0"
                    >
                      {{ $t('Eshop.Product.AMP') }} {{ item.total_cv.amp }} {{ $t('Eshop.Product.CV') }}
                    </div>
                    <div
                      class="text-primary font-weight-bold"
                      v-if="typeof item.total_cv.eligible !== 'undefined' && item.total_cv.eligible !== 0"
                    >
                      {{ item.total_cv.eligible }} {{ $t('Eshop.Product.CV') }}
                    </div>
                    <div class="text-dark font-weight-bold">
                      {{ currency }} {{ $helpers.getCurrencyValue(item.total_price) }}
                    </div>
                  </div>
                  <div class="product-name text-dark font-weight-bold">
                    {{ item.name }}
                  </div>
                  <div class="product-sku">
                    {{ item.sku }}
                  </div>
                  <eshop-item-quantity
                    v-if="item.memberKit === false"
                    :product-id="item.product_id"
                    :kitting-id="item.kitting_id"
                    :sales-type-id="item.eligible_sales_type.id"
                    :quantity="getCartProductQuantity(item.product_id, item.kitting_id)"
                    :is-adding="isLoading('addingProductToCart-' + item.product_id + '-' + item.kitting_id)"
                    :process-cart-callback="addProductToCartBypass"
                    :data-qa-prefix="`autoship-cart-product-${item.sku.toLowerCase()}`"
                  />
                </div>
              </div>
            </div>
            <b-row class="divider clearfix">
              <b-col>
                <span class="align-middle text-dark line-height-3 font-weight-bold">
                  {{ $t('Common.Terminology.TotalBV') }}
                </span>
              </b-col>
              <b-col class="h3 text-right py-2">
                {{ getBaseCv }}
              </b-col>
            </b-row>
            <b-row class="divider clearfix">
              <b-col>
                <span class="align-middle text-dark line-height-3 font-weight-bold">
                  {{ $t('Common.Sales.Total') }}
                  {{ currency }}
                </span>
              </b-col>
              <b-col class="h3 text-right py-2">
                {{ getCartTotalPriceFormatted }}
              </b-col>
            </b-row>
            <div class="divider clearfix text-center py-4">
              <b-btn
                variant="primary w-50"
                @click="navigateNext()"
                :disabled="
                  isLoading(['loadingCart', 'productsAddingToCart', 'loadingCartProductEligible']) ||
                    getCheckout.status === false ||
                    getCartTotal <= 0
                "
                data-qa="autoship-select-product-checkout-btn"
              >
                {{ this.nextRoute.next }}
              </b-btn>
            </div>
          </b-card-body>
        </b-card>
      </b-col>
    </b-row>
  </div>
</template>

<script>
import ProductList from '@/app/_global/components/elements/ProductList'
import Pagination from '@/app/_global/components/elements/Pagination'
import EshopItemQuantity from '@/app/_global/components/elements/EshopItemQuantity'
import { mapGetters, mapActions } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import ProductFilter from '@/app/_global/components/elements/ProductFilter'
import currencyMixin from '@/app/_global/mixins/currencyMixin'
import componentProps from '../fixtures/validated-route-component-props'
export default {
  name: 'SelectProduct',
  components: { ProductFilter, Pagination, ProductList, EshopItemQuantity },
  mixins: [currencyMixin],
  props: {
    ...componentProps,
  },
  data() {
    return {
      selectedCountry: '',
    }
  },
  mounted() {
    this.loadCountries()
    this.layoutBlocks({ block: 'autoship-products', layout: 'grid-big' })
    this.getAutoshipCountry
      ? (this.selectedCountry = this.getAutoshipCountry)
      : (this.selectedCountry = this.getSelectedCountry.id)
    this.loadProductCategories({ setCategory: false })
  },
  computed: {
    ...mapMasterDataId({
      SALE_TYPES: {
        repurchaseSalesTypeId: 'RE_PURCHASE',
      },
    }),
    ...mapGetters([
      'getCountries',
      'getSelectedCountry',
      'isLoading',
      'getPagination',
      'getAppLocationCountry',
      'getAutoshipCountry',
      'getErrors',
      'getAutoshipSearchFilter',
    ]),
    ...mapGetters('eshop', [
      'getProducts',
      'getCartProductQuantity',
      'getProductTotal',
      'getCheckout',
      'getCartDisplayItemsWithMemberKit',
      'getCartTotalPriceFormatted',
      'getCartCv',
      'getCartTotal',
      'getCartProductRentalPlan',
      'getSortedProductMainCategoriesOptions',
    ]),
    getBaseCv() {
      return this.$helpers.getValue(this.getCartCv, 'break_down.base') || 0
    },
  },
  methods: {
    ...mapActions([
      'updateSelectedCountry',
      'layoutBlocks',
      'setAutoshipCountry',
      'loadAutoshipProductCategories',
      'loadCountries',
      'setAutoshipSearchFilter',
      'clearLoadedData',
    ]),
    ...mapActions('eshop', ['loadProducts', 'addProductToCart', 'loadCart', 'loadProductCategories']),
    async loadProductBypass() {
      await this.resolveMasters
      await this.loadProducts({
        identifier: 'autoship-products',
        name: this.getAutoshipSearchFilter.search,
        countryId: this.selectedCountry,
        locationId: this.getAppLocationCountry.locationId,
        sortOrder: this.getAutoshipSearchFilter.selectedSort,
        categoryIds:
          this.getAutoshipSearchFilter.selectedCategory !== null ? [this.getAutoshipSearchFilter.selectedCategory] : [],
        filters: ['auto_ship'],
        ek_smart: false,
        pagination: {
          limit: this.getPagination('autoship-products').limit,
          offset: this.getPagination('autoship-products').offset,
        },
      })
    },
    addProductToCartBypass(params) {
      let localParams = {
        countryId: this.getAppLocationCountry.countryId,
        locationId: this.getAppLocationCountry.locationId,
      }
      let merge = Object.assign({}, params, localParams)
      return this.addProductToCart(merge)
    },
  },
  watch: {
    async selectedCountry() {
      this.setAutoshipCountry(this.selectedCountry)
      this.$refs.productFilter.clearFilters()
      await this.loadCart()
      this.clearLoadedData('order')
    },
    '$route.params.page': {
      handler: 'loadProductBypass',
      immediate: true,
    },
  },
}
</script>
