<template>
  <div class="listings">
    <fluid-three-nine left-slot-class="col-lg-4" right-slot-class="col-lg-8">
      <items-filter-panel
        slot="left"
        :mobile-page-footer="$t('Common.Continue')"
        v-mobile-page.close.footer="filterPanelMobile"
        :mobile-page-title="$t('Eshop.LeftPanel.Filter')"
        :show-pay-cycle-dropdown="$appSettings.evo.enable"
        :show-bv-filter="!$appSettings.evo.enable"
        :show-price-filter="!$appSettings.evo.enable"
        :show-sub-category="!$appSettings.evo.enable"
        class="panel d-md-block d-none rounded-1 border-0"
        @onMobileCancel="filterPanelOff"
        @onMobileContinue="filterPanelOff"
      />
      <div class="eshop-products-wrapper" :class="{ 'vh-75': isLoading(loadings) }">
        <!--MOBILE FILTER PANEL ------------------------------------------------------------------------------------ -->
        <div
          class="remove-gutter-1 mobile-filter-column d-flex d-md-none p-2 mb-2 justify-content-between border-bottom"
        >
          <b-form-select v-model="selectedSort" :options="sortOptions" class="col-6 font-weight-bold" />
          <div>
            <b-button variant="outline-primary" @click="gridDisplayToggle(!displayGrid)" class="border-0">
              <icon :name="displayGrid ? 'eshop-list-layout' : 'eshop-grid-layout'" />
            </b-button>
            <span class="border-left mx-2" />
            <b-button variant="outline-primary" class="border-0" @click="filterPanelOn">
              <icon name="eshop-filter" />
              <span class="ml-1">
                {{ $t('Eshop.LeftPanel.Filter') }}
              </span>
            </b-button>
          </div>
        </div>
        <!-------------------------------------------------------------------------------------- MOBILE FILTER PANEL -->
        <b-row class="d-none d-md-flex mb-2">
          <b-col xl="7">
            <h2 class="text-break">
              <span v-if="getProductSearchName" class="animated fadeInLeft">
                {{
                  $t('Eshop.Listing.SearchResult.Placeholder', {
                    result: getProductTotal,
                    keyword: getProductSearchName,
                  })
                }}
              </span>
              <span v-else class="animated fadeInLeft">{{ $t('Eshop.Listing.Title') }}</span>
            </h2>
            <h5 v-if="getProductSearchName" class="animated fadeIn text-black-50 font-weight-bold-semi">
              {{ $t('Eshop.Listing.SearchCategory.Placeholder', { category: getProductCurrentCategory.name }) }}
            </h5>
          </b-col>
          <b-col xl="5" class="d-flex justify-content-end align-items-baseline eshop-options-menu pr-1">
            <label class="mb-0">{{ $t('Eshop.SortBy.Title') }}</label>
            <b-form-select v-model="selectedSort" :options="sortOptions" class="border-0 mx-2 w-auto flex-grow-1" />
            <b-button
              :variant="displayGrid ? 'primary' : 'white'"
              @click="gridDisplayToggle(true)"
              class="mr-2 px-2 border-0"
            >
              <icon name="eshop-grid-layout" class="icon-size-2" />
            </b-button>
            <b-button
              :variant="!displayGrid ? 'primary' : 'white'"
              @click="gridDisplayToggle(false)"
              class="px-2 border-0"
            >
              <icon name="eshop-list-layout" class="icon-size-2" />
            </b-button>
          </b-col>
        </b-row>
        <product-list
          v-if="getProducts.length > 0"
          identifier="products"
          :loading-check="loadings"
          :products-getter="getProducts"
          :full-width-button-group="displayButtonType"
          :product-quantity-getter="getCartProductQuantity"
          :default-sale-type-keys="['registration', 'formation', 'rental', 'repurchase', 'auto-maintenance']"
        />
        <div
          v-else-if="!isLoading(loadings) && getProducts.length <= 0"
          class="bg-white border d-flex flex-column h-100 justify-content-center p-3 text-center vh-50 mt-1"
        >
          <div class="font-size-5 font-weight-bold p-5">
            {{ $t('Eshop.Product.NotFound') }}
          </div>
        </div>
        <div v-else-if="isLoading(loadings) && getProducts.length <= 0" class="eshop-products">
          <icon name="spinner" pulse />
        </div>
        <!--Pagination component don't use v-if side-effects on load products-->
        <pagination
          :disabled="isLoading(loadings) || getProducts.length <= 0"
          class="eshop-pagination"
          name="products"
          :total="getProductTotal"
          :per-page="getProductsPerPage"
          data-qa-prefix="eshop-listing"
        />
      </div>
    </fluid-three-nine>
  </div>
</template>
<script>
import ItemsFilterPanel from './blocks/ItemsFilterPanel'
import FluidThreeNine from '@/elements/layouts/fluid/Fluid-3-9'
import ProductList from '@/app/_global/components/elements/ProductList'
import Pagination from '@/app/_global/components/elements/Pagination'
import { mapActions, mapGetters } from 'vuex'
export default {
  name: 'ListingHome',
  components: {
    ItemsFilterPanel,
    ProductList,
    Pagination,
    FluidThreeNine,
  },
  data() {
    return {
      selectedSort: 2,
      loadings: ['products', 'categoriesLoading', 'cwInfo', 'memberDetails'],
      sortOptions: [
        // TODO: removed until backend logic is applied
        // { value: 1, text: this.$t('Eshop.SortBy.BestSelling') },
        { value: 2, text: this.$t('Eshop.SortBy.Latest') },
        { value: 4, text: this.$t('Eshop.SortBy.PriceHighToLow') },
        { value: 5, text: this.$t('Eshop.SortBy.PriceLowToHigh') },
        { value: 6, text: this.$t('Eshop.SortBy.CVHighToLow') },
        { value: 7, text: this.$t('Eshop.SortBy.CVLowToHigh') },
      ],
    }
  },
  mounted() {
    this.clearLoadedData('iToken')
    this.selectedSort = this.getProductSortOrder
    if (this.$appSettings.evo.enable && this.displayGrid) {
      this.gridDisplayToggle(true)
    }
  },
  methods: {
    ...mapActions(['layoutBlocks', 'clearLoadedData']),
    ...mapActions('eshop', ['setProductSortOrder', 'filterProductsName']),
    gridDisplayToggle(value) {
      let layout = (value && ((this.$appSettings.evo.enable && 'grid-big') || 'grid')) || 'list'
      this.layoutBlocks({ block: 'products', layout })
    },
    filterPanelOn: function() {
      this.layoutBlocks({ block: 'filter-panel', layout: 'show' })
    },
    filterPanelOff: function() {
      this.layoutBlocks({ block: 'filter-panel', layout: 'hide' })
    },
  },
  computed: {
    ...mapGetters(['getLayoutMode', 'isLoading', 'getMasterDataKeysByKeysTitles', 'getMemberEnrollmentRank']),
    ...mapGetters('eshop', [
      'getProductSortOrder',
      'getProductTotal',
      'getProductsPerPage',
      'getProducts',
      'getCartProductQuantity',
      'getProductSearchName',
      'getFilteredSalesTypes',
      'getProductCurrentCategory',
    ]),
    displayGrid: function() {
      return this.getLayoutMode('products', 'grid') !== 'list'
    },
    filterPanelMobile() {
      return this.getLayoutMode('filter-panel', 'hide') !== 'hide'
    },
    displayButtonType() {
      let salesType = this.getMasterDataKeysByKeysTitles(
        'sale_types',
        this.getMemberEnrollmentRank.sales_types.values || []
      ).find(type => type.id === this.getFilteredSalesTypes[0])
      return !!salesType && salesType.title.toLowerCase() === 'rental'
    },
  },
  watch: {
    selectedSort() {
      this.setProductSortOrder(this.selectedSort)
    },
  },
}
</script>
