<template>
  <div class="content guide">
    <div class="enrol-product-selection-wrapper w-100">
      <enrol-grid-8-4>
        <template v-slot:left-big>
          <b-card class="mb-3 eshop-products-wrapper">
            <product-filter class="mb-3" immediate-update @filter-update="setFilterMeta" />
            <product-list
              simple
              :allow-disable="false"
              :identifier="identifier"
              :show-tick-for-count="true"
              :products-getter="getProducts"
              :is-popup-product-viewer="true"
              :show-product-points-allocation="false"
              :product-quantity-getter="getCartProductQuantity"
              :add-product-to-cart-bypass="addProductToCartByPass"
              :default-sale-type-keys="['registration', 'formation']"
              :disabled-eshop-product-quantity-selector="isLoading('productsAddingToCart')"
            />
            <pagination
              :name="identifier"
              :identifier="identifier"
              :total="getProductTotal"
              :per-page="filterMeta.perPage"
              :disabled="isLoading(identifier)"
              class="eshop-pagination text-center"
              data-qa-prefix="enrolment-salesKit"
            />
          </b-card>
        </template>
        <template v-slot:right-small>
          <product-cart
            class="mb-3 text-black"
            :currency="currency"
            v-bind="getProductCartConfig"
            :show-total-points="false"
            :show-total-price="false"
            :total-price="getCartTotalPriceFormatted"
            :cart-items="getCartDisplayItemsWithMemberKit"
            :process-cart-callback="addProductToCartByPass"
            :product-quantity-getter="getCartProductQuantity"
            data-qa-prefix="enrolment-productSelection"
          >
            <template v-slot:footer>
              <div class="text-center px-2">
                <b-button
                  block
                  size="lg"
                  variant="primary"
                  @click="validateAndSave"
                  :disabled="
                    isLoading(['loadingCart', 'productsAddingToCart', 'loadingCartProductEligible']) ||
                      getCartHasStarterKit === false ||
                      getCartTotal <= 0
                  "
                >
                  <b-spinner
                    v-show="isLoading(['loadingCart', 'productsAddingToCart', 'loadingCartProductEligible'])"
                    small
                    class="mr-2 align-middle"
                  />
                  <span>{{ next }}</span>
                </b-button>
              </div>
            </template>
          </product-cart>
        </template>
      </enrol-grid-8-4>
    </div>
  </div>
</template>

<script>
import { mapMasterDataId } from '@/app/_global/mixins'
import enrolGrid84 from '@/app/enrolment/_global/components/templates/layouts/enrol-grid-8-4'
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 { mapActions, mapGetters } from 'vuex'
import ProductCart from '@/app/_global/components/blocks/ProductCart'
import currencyMixin from '@/app/_global/mixins/currencyMixin'

export default {
  name: 'EnrolmentSalesKitPage',
  mixins: [currencyMixin],
  components: { ProductCart, ProductList, ProductFilter, enrolGrid84, Pagination },
  props: {
    currentPage: { type: Number, required: true },
    enrolmentData: { type: Object, required: true },
    previous: {
      type: String,
    },
    next: {
      type: String,
    },
    nextAction: {
      type: Function,
    },
    isEkSmart: { type: Boolean, default: false },
  },
  data() {
    return {
      identifier: 'starter-kit-products',
      filterMeta: {
        perPage: 12,
      },
    }
  },
  watch: {
    filterMeta: {
      handler() {
        this.loadProductBypass()
      },
      deep: true,
    },
    getCartHasStarterKit: {
      handler(val) {
        this.enrolmentData.step_states['select-starter-kit'] = val
      },
      immediate: true,
    },
  },
  computed: {
    ...mapMasterDataId({
      SALE_TYPES: {
        formationSalesTypeId: 'FORMATION',
        registrationSalesTypeId: 'REGISTRATION',
      },
    }),
    ...mapGetters(['getEnrolmentRegion', 'isLoading', 'getErrors']),
    ...mapGetters('eshop', [
      'getCartCv',
      'getCartTotal',
      'getProducts',
      'getCartProductQuantity',
      'getProductTotal',
      'getCartHasStarterKit',
      'getCartTotalPriceFormatted',
      'getCartDisplayItemsWithMemberKit',
      'getCheckout',
    ]),
    getCartErrorMsg() {
      return [
        ...((this.getErrors('starterKitError') && [this.getErrors('starterKitError')]) || []),
        ...((this.getCheckout.status === false && [this.getCheckout.messages.default]) || []),
      ]
    },
    getProductCartConfig() {
      let isEvo = this.$appSettings.evo.enable

      return {
        showItemBv: isEvo,
        showItemSv: isEvo,
        showItemCbp: isEvo,
        showItemAmp: !isEvo,
        showSkuCode: !isEvo,
        showItemWpBv: !isEvo,
        pillQuantitySelector: isEvo,
        smallQuantitySelector: isEvo,
      }
    },
  },
  async mounted() {
    this.setGrid()
    await this.loadCart({
      countryId: this.getEnrolmentRegion.id,
      locationId: this.getEnrolmentRegion.entity.locations[0].id,
      ekSmart: this.isEkSmart,
    })
    await this.resolveMasters
  },
  methods: {
    ...mapActions(['layoutBlocks']),
    ...mapActions('eshop', ['loadProducts', 'addProductToCart', 'loadCart']),
    loadProductBypass() {
      this.loadProducts({
        identifier: this.identifier,
        name: this.filterMeta.search,
        countryId: this.getEnrolmentRegion.id,
        locationId: this.getEnrolmentRegion.entity.locations[0].id,
        sortOrder: this.filterMeta.selectedSort,
        categoryIds: [],
        filters: ['starter_kit'],
        salesTypesIds: [this.formationSalesTypeId, this.registrationSalesTypeId],
        ek_smart: this.isEkSmart,
        pagination: {
          limit: this.filterMeta.perPage,
          offset: this.filterMeta.perPage * (this.currentPage - 1),
        },
      })
    },
    addProductToCartByPass(payload) {
      let self = this
      payload = {
        ...payload,
        countryId: this.getEnrolmentRegion.id,
        locationId: this.getEnrolmentRegion.entity.locations[0].id,
      }

      if (payload.quantity === 0 && this.$helpers.getValue(payload, 'custom.isStarterKit') === true) {
        // double step status lock, to prevent status remains before latest cart details data return
        self.enrolmentData.step_states['select-starter-kit'] = false
      }
      return this.addProductToCart(payload)
    },
    setGrid() {
      this.layoutBlocks({ block: this.identifier, layout: 'grid-big' })
    },
    setFilterMeta(meta) {
      this.filterMeta = { ...meta }
    },
    async validateAndSave() {
      let self = this
      if (self.getCartHasStarterKit) {
        self.$nextTick(() => {
          self.nextAction()
        })
      }
    },
  },
}
</script>
