<template>
  <b-container class="products">
    <b-row class="sticky-top bg-white pb-1">
      <!-- filters and controls -->
      <b-col cols="12">
        <product-filter
          v-model="filters"
          @search-product="searchProduct"
          @clear-search-text="clearSearchText"
          :selected-category-name="getSelectedCategoryName"
        />
      </b-col>
      <!-- filters and controls -->
    </b-row>
    <b-row align-h="between">
      <b-col cols="12" class="pb-3">
        <div class="eshop-products-wrapper">
          <product-list
            identifier="byDzyne-products"
            :simple="false"
            :allow-disable="false"
            :default-sale-type-keys="['repurchase']"
            :products-getter="getProducts"
            :product-quantity-getter="getCartProductQuantity"
            :is-external-link-routing="true"
            :external-link-base="externalLinkBase"
            :external-link-open-method="externalLinkOpenMethod"
            :is-display-product-only="false"
            class="m-0 px-3"
            loading-check="byDzyne-products"
          >
            <template slot="spinner">
              <div></div>
            </template>
          </product-list>
          <pagination
            :disabled="isLoading('byDzyne-products')"
            class="eshop-pagination text-center"
            name="byDzyne-products"
            :total="getProductTotal"
            :per-page="12"
            data-qa-prefix="productList"
          />
        </div>
      </b-col>
      <div
        v-show="isLoading(['productsAddingToCart', 'loadingCart', 'byDzyne-products'])"
        ref="loader"
        class="loader loading"
      ></div>
    </b-row>
    <b-row align-h="end" class="px-3 z-1000" v-if="!isLoading('byDzyne-products')">
      <b-col cols="auto" class="my-2 view-cart-button fixed-bottom">
        <b-button
          pill
          size="md"
          variant="warning"
          @click="doRouteToCheckout"
          :disabled="getCartTotal <= 0"
          v-b-tooltip.hover
          :title="$t('3rdParty.Common.ViewCart.Text')"
        >
          <icon :class="{ 'animated flash infinite': getCartTotal > 0 }" name="eshop-cartsmall"></icon>
          <span class="mx-2"
            >( {{ getCartTotal }} ) <small>{{ $t('3rdParty.Common.Items.Text') }}</small></span
          >
          <icon name="dashboard-arrow-right"></icon>
        </b-button>
      </b-col>
    </b-row>
  </b-container>
</template>

<script>
import ProductFilter from '@@/app/_global/components/elements/ProductFilter'
import ProductList from '@/app/_global/components/elements/ProductList'
import Pagination from '@/app/_global/components/elements/Pagination'
import { productsMixin, cartCountMixin, customRoutingMixin } from '@@/app/_global/mixins'
import { mapMasterData } from '@/app/_global/mixins'
import Loader from '@@/app/_global/components/elements/lottie/loader.json'
import lottie from 'lottie-web'
import { mapGetters, mapActions } from 'vuex'
import { API_TOKEN_KEY } from '@/store/utils/localStorageKeys'
import AppSettings from '@/config/app-settings'

export default {
  name: 'Listing',
  components: { ProductFilter, ProductList, Pagination },
  mixins: [productsMixin, cartCountMixin, customRoutingMixin],
  watch: {
    '$route.params.page': {
      async handler() {
        this.loadProductList()
      },
    },
    filters: {
      async handler() {
        await this.resolveMasters
        this.salesTypesIds = [this.repurchaseSalesTypeId]
        this.productFilters = [this.autoshipFilterKey]
        this.loadProductList()
      },
      deep: true,
    },
  },
  computed: {
    ...mapGetters('eshop', ['getProductMainCategoriresOptions']),
    ...mapGetters(['isLoading']),
    ...mapMasterData({
      SALE_TYPES: {
        repurchaseSalesTypeId: 'RE_PURCHASE',
      },
      PRODUCT_AND_KITTING_FILTERS: {
        autoshipFilterKey: { name: 'PRODUCT_FILTER_EKBD', type: 'key' },
      },
    }),
    getSelectedCategoryName() {
      let selectedCategory = this.getProductMainCategoriresOptions.filter(x => x.value === parseInt(this.getCategoryId))
      return this.$helpers.getValue(selectedCategory, '[0].text')
    },
  },
  async mounted() {
    await this.loadCart()
    this.$nextTick(async () => {
      await lottie.loadAnimation({
        container: this.$refs.loader,
        renderer: 'svg',
        loop: true,
        animationData: Loader,
      })
    })
  },
  methods: {
    ...mapActions('eshop', ['loadCart']),
    doRouteToCheckout() {
      let checkoutPath = AppSettings.byDzyne.eshopCheckoutBaseUrl || ''

      if (checkoutPath) {
        let token = localStorage.getItem(localStorage.getItem(API_TOKEN_KEY)) || ''
        checkoutPath += `/on-behalf?token=${token}&medium=wp`
      }

      window.location = checkoutPath
    },
  },
}
</script>
