<template>
  <div class="content guide">
    <div class="enrol-product-selection-wrapper">
      <enrol-grid-8-4>
        <template slot="left-big">
          <div class="card w-100 mb-3" id="enrol_second_step_card">
            <div class="card-body">
              <div class="enrol-product-selection" id="enrol-product-selection-form">
                <div class="eshop-products-wrapper">
                  <product-filter
                    class="mb-3"
                    :filter-options="getEnrolProductMainCategories"
                    :filter-setter="setEnrolProductSearchFilter"
                    :load-product-bypass="loadProductBypass"
                  />
                  <product-list
                    identifier="enrol-products"
                    :simple="simple"
                    :default-sale-type-keys="getdefaultSaleTypeKeys"
                    :add-product-to-cart-bypass="addProductToCartBypass"
                    :products-getter="getProducts"
                    :allow-disable="false"
                    :product-quantity-getter="getCartProductQuantity"
                    :is-popup-product-viewer="true"
                    :full-width-button-group="true"
                    :eshop-quantity-selector-buttons-wrapper-class="['px-3', 'px-md-2', 'px-lg-3']"
                    :show-tick-for-count="$appSettings.evo.enable"
                  />
                  <pagination
                    :disabled="isLoading('enrol-products')"
                    class="eshop-pagination text-center"
                    name="enrol-products"
                    identifier="enrol-products"
                    :total="getProductTotal"
                    :per-page="getEnrolProductSearchFilter.perPage"
                    @getData="loadProductBypass"
                    data-qa-prefix="enrolment-productSelection"
                  />
                </div>
              </div>
            </div>
          </div>
        </template>
        <template slot="right-small">
          <div class="sticky-top">
            <div class="card mb-3 stepper-details" v-if="isEnrolmentTypeMember && showStepper">
              <div class="card-body pb-0 cart-list">
                <div class="divider remove-gutter-1 overflow-auto">
                  <cart-upgrade-steps
                    :cart-cvs="getCartCv"
                    :min-member-enrollment-rank-id="getMinMemberEnrollmentRankId()"
                    :member-enrollment-rank-id="
                      getCartCv.total_accumulated_base > 0 ? getMemberEnrollmentRankList.length - upgradeLevel : 0
                    "
                    :update-step-watcher="updateStepWatcher"
                    :show-amp-text="false"
                    :show-upg-text="true"
                    center
                  />
                  <div class="px-4 py-2 text-center" v-if="nextRnkCv || nextAmpCv">
                    <span class="text-upgrade font-weight-bold-extra" v-if="nextRnkCv">
                      {{ nextRnkCv }} {{ $t('Common.Terminology.RnkCv') }} {{ $t('Eshop.Product.CV') }}
                    </span>
                    <span class="font-weight-bold-extra" v-if="nextRnkCv & nextAmpCv">
                      /
                    </span>
                    <span class="text-amp font-weight-bold-extra" v-if="nextAmpCv">
                      {{ nextAmpCv }} {{ $t('Eshop.Product.AMP') }}
                    </span>
                    <span class="text-medium">
                      {{ $t('Eshop.Rank.Type.BaCvRequired') }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <product-cart
              class="mb-3 text-black"
              :currency="currency"
              :error-bag="getCartErrorMsg"
              v-bind="getProductCartConfig"
              :total-price="getCartTotalPriceFormatted"
              :cart-items="getCartDisplayItemsWithMemberKit"
              :process-cart-callback="addProductToCartBypass"
              :product-quantity-getter="getCartProductQuantity"
              data-qa-prefix="enrolment-productSelection"
            >
              <template v-slot:total-points-allocation>
                <div v-if="$appSettings.evo.enable">
                  <b-row>
                    <b-col>{{ $t('Common.Terminology.Bv') }}</b-col>
                    <b-col cols="auto" class="text-right text-primary">{{ getCartCv.eligible || '0.00' }} </b-col>
                  </b-row>

                  <b-row>
                    <b-col>{{ $t('Common.Terminology.Sv') }}</b-col>
                    <b-col cols="auto" class="text-right text-primary">{{ getCartCv.sv || 0 }} </b-col>
                  </b-row>

                  <b-row>
                    <b-col>{{ $t('Common.Terminology.Cbp') }}</b-col>
                    <b-col cols="auto" class="text-right text-primary">{{ getCartCv.cbp_point || '0.0000' }} </b-col>
                  </b-row>
                </div>

                <div v-else>
                  <b-row>
                    <b-col>{{ $t('Common.Terminology.WpCv') }}</b-col>
                    <b-col cols="auto" class="text-right text-primary">
                      {{ getCartCv.total_accumulated_upgrade || 0 }}
                    </b-col>
                  </b-row>
                </div>
              </template>

              <template v-slot:footer>
                <div class="text-center px-2">
                  <b-button
                    block
                    size="lg"
                    variant="primary"
                    @click="continueNext"
                    :disabled="
                      isLoading(['loadingCart', 'productsAddingToCart', 'loadingCartProductEligible']) ||
                        getCheckout.status === 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>
          </div>
        </template>
      </enrol-grid-8-4>
    </div>
  </div>
</template>
<script>
import enrolGrid84 from '@/app/enrolment/_global/components/templates/layouts/enrol-grid-8-4'
import ProductList from '@/app/_global/components/elements/ProductList'
import Pagination from '@/app/_global/components/elements/Pagination'
import CartUpgradeSteps from '@/app/_global/components/elements/CartUpgradeSteps'
import currencyMixin from '@/app/_global/mixins/currencyMixin'
import _ from 'lodash'
import { mapActions, mapGetters } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import ProductFilter from '@/app/_global/components/elements/ProductFilter'
import AppSettings from '@/config/app-settings'
import ProductCart from '@/app/_global/components/blocks/ProductCart'

export default {
  name: 'EnrolmentProductSelectionPage',
  components: {
    ProductCart,
    ProductFilter,
    enrolGrid84,
    ProductList,
    Pagination,
    CartUpgradeSteps,
  },
  mixins: [currencyMixin],
  props: {
    enrolmentData: {
      type: Object,
      required: true,
    },
    previous: {
      type: String,
    },
    next: {
      type: String,
    },
    prevAction: {
      type: Function,
    },
    nextAction: {
      type: Function,
    },
    steps: {
      type: Array,
      default: () => [],
    },
    isEkSmart: { type: Boolean, default: false },
  },
  data() {
    return {
      affixMinWidth: null,
      isEnrolmentTypeMember: true,
      selected: '',
      upgradeLevel: null,
      initializationTimer: null,
      vueSidebarConfig: {
        // preventParentScroll: true,
        resizeRefresh: true,
      },
      nextRankName: '-',
      nextAmpCv: null,
      nextRnkCv: null,
      simple: true,
      defaultSaleTypeKeys: [],
    }
  },
  async mounted() {
    let readyToLoadCart = this.hasSalesKitSteps ? await this.getStepValidationStatus('select-starter-kit') : true
    await this.initPage(readyToLoadCart)
    let vue = this
    this.getIsEnrolTypeIsMember().then(type => {
      vue.isEnrolmentTypeMember = type
    })
    this.saveOrderShipping(null)
    // Try catch master resolver to prevent cancel request halt the code
    try {
      await this.resolveMasters
      // eslint-disable-next-line no-empty
    } catch (e) {}
  },
  computed: {
    ...mapMasterDataId({
      SALE_TYPES: {
        formationSalesTypeId: 'FORMATION',
        registrationSalesTypeId: 'REGISTRATION',
        repurchaseSalesTypeId: 'RE_PURCHASE',
        rentalSalesTypeId: 'RENTAL',
      },
    }),
    ...mapGetters('eshop', [
      'getCartCv',
      'getCartTotal',
      'getCartTotalPriceFormatted',
      'getCartHasUpgrade',
      'getCartDisplayItemsWithMemberKit',
      'getCartProductQuantity',
      'getProductSortOrder',
      'getProductTotal',
      'getProductsPerPage',
      'getProducts',
      'getCwInfo',
      'isProductFree',
      'getCheckout',
      'getRentalInstDetails',
      'getCartProductRentalPlan',
    ]),
    ...mapGetters('enrolment', [
      'getEnrolProductMainCategories',
      'getEnrolCountryId',
      'getEnrolmentTypes',
      'getEnrolProductSearchFilter',
    ]),
    ...mapGetters([
      'getPagination',
      'getErrors',
      'getEnrolmentRegion',
      'getEligibleMemberEnrollmentRank',
      'getMemberEnrollmentRankList',
      'getMemberEnrollmentRankCW',
      'isLoading',
      'getMemberEnrollmentRank',
      'getEnrolmentMasterDataIdByKey',
      'getAppStatus',
    ]),
    activeStep() {
      let memberEnrollmentRank = this.getEligibleMemberEnrollmentRank(this.enrolmentData.enrolment_type)
      let newStepIndex = this.getMemberEnrollmentRankList.findIndex(function(item) {
        if (item.entitlement_lvl === memberEnrollmentRank.entitlement_lvl - 1) {
          return true
        }
      })
      return newStepIndex || this.getMemberEnrollmentRankList.length
    },
    getdefaultSaleTypeKeys() {
      var defaultSaleTypeKeys = []
      if (this.isEnrolmentTypeMember && this.enrolmentData.membershipType === this.$const.masterKey.EK_SMART) {
        defaultSaleTypeKeys = ['rental']
      } else if (this.isEnrolmentTypeMember && this.enrolmentData.membershipType !== this.$const.masterKey.EK_SMART) {
        defaultSaleTypeKeys = ['registration', 'formation']
      } else {
        defaultSaleTypeKeys = ['repurchase']
      }

      return defaultSaleTypeKeys
    },
    showStepper() {
      return this.$helpers.getValue(this.getCartCv, 'is_member_rank_upgradable')
    },
    getCartErrorMsg() {
      return [
        ...((this.getErrors('productError') && [this.getErrors('productError')]) || []),
        ...((this.getCheckout.status === false && [this.getCheckout.messages.default]) || []),
      ]
    },
    getProductCartConfig() {
      let isEvo = AppSettings.evo.enable

      return {
        showItemBv: isEvo,
        showItemSv: isEvo,
        showItemCbp: isEvo,
        showItemAmp: !isEvo,
        showSkuCode: !isEvo,
        showItemWpBv: !isEvo,
        pillQuantitySelector: isEvo,
        smallQuantitySelector: isEvo,
      }
    },
    hasSalesKitSteps() {
      return (
        AppSettings.evo.enable &&
        this.$helpers.getValue(this.getEnrolForm, 'membershipType') === this.$const.masterKey.STANDARD
      )
    },
  },
  methods: {
    ...mapActions(['layoutBlocks', 'loadEnrollmentRanks', 'loadCartProductEligible', 'loadMasterDataKeysEnrolment']),
    ...mapActions('eshop', ['loadProducts', 'addProductToCart', 'loadCart', 'loadCwInfo', 'saveOrderShipping']),
    ...mapActions('enrolment', [
      'loadEnrolProductCategories',
      'postTempEnrolment',
      'getIsEnrolTypeIsMember',
      'setEnrolProductSearchFilter',
      'getStepValidationStatus',
    ]),
    getSaleTypeTitle(item) {
      let title = ''
      let sale_types = this.getEnrolmentMasterDataIdByKey('sale_types')
      if (sale_types !== undefined && item.sales_types !== undefined && item.sales_types !== null) {
        for (let i = 0; i < sale_types.length; i++) {
          if (sale_types[i].id === item.sales_types[0].id) {
            title = sale_types[i].title.toLowerCase()
          }
        }
      }
      return title
    },
    async initPage(loadProducts) {
      this.setGrid()
      await this.loadCwInfo()
      await this.loadEnrolProductCategories()
      await this.loadEnrollmentRanks()
      await this.loadCart({
        countryId: this.getEnrolmentRegion.id,
        locationId: this.getEnrolmentRegion.entity.locations[0].id,
        ekSmart: this.isEkSmart,
      })
      if (loadProducts) {
        await this.loadProductBypass()
      }
      await this.loadMasterDataKeysEnrolment({
        country_id: this.enrolmentData.region.value,
        keys: ['sale_types', 'product_additional_requirements'],
      }).then(async () => {})
    },
    async loadProductBypass() {
      let salesTypesIds = []
      if (this.isEnrolmentTypeMember && this.enrolmentData.membershipType === this.$const.masterKey.EK_SMART) {
        salesTypesIds = [this.rentalSalesTypeId]
      } else if (this.isEnrolmentTypeMember && this.enrolmentData.membershipType !== this.$const.masterKey.EK_SMART) {
        salesTypesIds = [this.formationSalesTypeId, this.registrationSalesTypeId]
      } else {
        salesTypesIds = [this.repurchaseSalesTypeId]
      }
      await this.loadProducts({
        identifier: 'enrol-products',
        name: this.getEnrolProductSearchFilter.search,
        countryId: this.getEnrolmentRegion.id,
        locationId: this.getEnrolmentRegion.entity.locations[0].id,
        sortOrder: this.getEnrolProductSearchFilter.selectedSort,
        categoryIds:
          this.getEnrolProductSearchFilter.selectedCategory !== null
            ? [this.getEnrolProductSearchFilter.selectedCategory]
            : [],
        /* salesTypesIds: this.isEnrolmentTypeMember
            ? [ this.formationSalesTypeId, this.registrationSalesTypeId ]
            : [ this.repurchaseSalesTypeId ],*/
        salesTypesIds: salesTypesIds,
        ek_smart: this.enrolmentData.membershipType === this.$const.masterKey.EK_SMART,
        pagination: {
          limit: this.$helpers.getValue(this.getPagination('enrol-products'), 'limit', 12),
          offset: this.$helpers.getValue(this.getPagination('enrol-products'), 'offset', 0),
        },
      })
      this.enrolmentData.step_states['select-pwp-foc'] = false
    },
    addProductToCartBypass(params) {
      let localParams = {
        countryId: this.getEnrolmentRegion.id,
        locationId: this.getEnrolmentRegion.entity.locations[0].id,
      }
      let merge = Object.assign({}, params, localParams)
      return this.addProductToCart(merge).then(result => result)
    },
    setGrid: function() {
      this.layoutBlocks({ block: 'enrol-products', layout: 'grid-big' })
    },
    getMinMemberEnrollmentRankId() {
      if (this.getEnrolmentTypes.length > 0) {
        let type = this.getEnrolmentTypes.find(x => x.id === this.enrolmentData.enrolment_type)
        if (type !== undefined) {
          if (type.enrollment_ranks.length > 0) {
            return _.minBy(type.enrollment_ranks, 'CV').id
          }
        }
      }
    },
    async continueNext() {
      let self = this
      this.enrolmentData.step_states['select-products'] = this.getCartDisplayItemsWithMemberKit.length > 0

      self.$nextTick(() => {
        self.nextAction()
      })
    },
    updateStepWatcher(updateSteps) {
      this.upgradeLevel = updateSteps.level
      let title = '-'
      this.nextAmpCv = null
      this.nextRnkCv = null
      let nextStep = this.$helpers.getValue(updateSteps, 'nextStep')
      if (nextStep) {
        if (nextStep.entitlement_lvl) {
          title = nextStep.rank_name
        }
        if (nextStep.entitlement_lvl + 1) {
          if (updateSteps.isWp && updateSteps.wpCvToNextLevel) {
            this.nextRnkCv = updateSteps.wpCvToNextLevel
          }
          if (updateSteps.ampCvToNextLevel) {
            this.nextAmpCv = updateSteps.ampCvToNextLevel
          }
        }
        this.nextRankName = title
      }
    },
  },
}
</script>
