<template>
  <div>
    <custom-alert
      :is-display="getCheckoutErrors.length > 0"
      variant="warning"
      class="mt-3"
      :title="$t('Common.Warning')"
      :items="getCheckoutErrors"
    />
    <loading-wrapper
      no-center
      :wrapper-class="['eshop-products', getLayoutMode(identifier, 'grid'), 'no-gutters']"
      :busy="!hasLoaded(loadingCheck || identifier) || isLoading(loadingCheck || identifier)"
    >
      <template v-if="productsGetter.length > 0">
        <!-- Below key string is complicated is to force vue rerender the list when new set of data retrieve-->
        <product
          v-for="(product, index) in productsGetter"
          :key="`${identifier}-${index}-${product.id}-${isLoading(loadingCheck || identifier)}`"
          :simple="simple"
          :product-details="product"
          :identifier="identifier"
          :product-quantity-getter="productQuantityGetter"
          :sale-type-id="setDefaultSaleType(product.sales_types, defaultSaleTypeKeys)"
          :upgrade="isUpgradeProduct(product)"
          :fpp="checkSalesType(product, formationSalesTypeId)"
          :amp="checkSalesType(product, autoMaintenanceSalesTypeId)"
          :amp-cv="getCvBreakdown(product).amp"
          :basic-cv="getCvBreakdown(product).eligible"
          :rnk-cv="getCvBreakdown(product).upgrade"
          :initial-payment="getRentalPlanInfo(product, 'initial_payment')"
          :monthly-repayment="getRentalPlanInfo(product, 'monthly_repayment')"
          :repayment-months="getRentalPlanInfo(product, 'month')"
          :rental-cv="getRentalPlanInfo(product, 'cv_value')"
          :rental-cv-num="getRentalPlanInfo(product, 'number_cv')"
          :rental-total-payment="getRentalPlanInfo(product, 'total_payment')"
          :wp-cv="getCvBreakdown(product).welcome_pack"
          :add-product-to-cart-bypass="addProductToCartBypass"
          :disabled="isDisabled(product)"
          :disabled-text="getDisableText(product)"
          :max-title-length="getTitleCharLimit"
          :is-popup-product-viewer="isPopupProductViewer"
          :is-display-product-only="isDisplayProductOnly"
          :is-external-link-routing="isExternalLinkRouting"
          :external-link-base="externalLinkBase"
          :external-link-open-method="externalLinkOpenMethod"
          :full-width-button-group="fullWidthButtonGroup"
          @openModal="showProductDetail"
          @commission-entitlement="showCommissionEntitlementModal"
          :append-full-product-details-to-payload="getCustomProductDetails"
          :eshop-quantity-selector-buttons-wrapper-class="eshopQuantitySelectorButtonsWrapperClass || []"
          :show-points-allocation="showProductPointsAllocation"
          :show-tick-for-count="showTickForCount"
          :disabled-eshop-product-quantity-selector="disabledEshopProductQuantitySelector"
        />
      </template>
      <slot v-else-if="productsGetter.length <= 0 && !isLoading(loadingCheck || identifier)" name="empty-product-list">
        <div class="w-100 my-5 text-center font-size-3">
          <span>{{ $t('Eshop.Product.NotFound') }}</span>
        </div>
      </slot>
    </loading-wrapper>

    <product-details-previewer-popup
      :show-bv="!isEnrolment"
      :show-amp-cv="!isEnrolment"
      :show-rnk-cv="!isEnrolment"
      :show-wp-cv="isEnrolment"
      :add-product-call-back="addProductToCartBypass"
      :show-action-bar="showProductPreviewerActionBarOption"
      ref="product_previewer"
    />

    <product-commission-entitlement-modal v-if="$appSettings.evo.enable" ref="commission_entitlement" />
  </div>
</template>
<script>
import _ from 'lodash'
import Product from './Product'
import { mapGetters } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import CustomAlert from '@/elements/common/components/CustomAlert'
import LoadingWrapper from '@/app/_global/components/elements/LoadingWrapper'
import ProductCommissionEntitlementModal from '@/app/_global/components/elements/ProductCommissionEntitlementModal'
import ProductDetailsPreviewerPopup from '@/app/_global/components/elements/ProductDetailsPreviewerPopup'

export default {
  name: 'ProductList',
  props: [
    'identifier',
    'productsGetter',
    'productQuantityGetter',
    'addProductToCartBypass',
    'simple',
    'defaultSaleTypeKeys',
    'allowDisable',
    'loadingCheck',
    'isPopupProductViewer',
    'displayProductOnly',
    'isDisplayProductOnly',
    'isExternalLinkRouting',
    'externalLinkBase',
    'externalLinkOpenMethod',
    'fullWidthButtonGroup',
    'getCustomProductDetails',
    'showProductPreviewerActionBar',
    'productUnitCv',
    'eshopQuantitySelectorButtonsWrapperClass',
    'showProductPointsAllocation',
    'showTickForCount',
    'disabledEshopProductQuantitySelector',
  ],
  data() {
    return {
      shortBtn: true,
    }
  },
  components: {
    ProductDetailsPreviewerPopup,
    ProductCommissionEntitlementModal,
    LoadingWrapper,
    CustomAlert,
    Product,
  },
  computed: {
    ...mapGetters(['getLayoutMode', 'isLoading', 'getMasterDataTitleByKeyAndId', 'hasLoaded', 'getAppStatus']),
    ...mapGetters('eshop', [
      'getProducts',
      'getBaSalesTypeId',
      'getFilteredSalesTypes',
      'getCartProductEligibleAsBaUpgrade',
      'getCartProductSalesTypes',
      'getCartProductEligibleSalesType',
      'getCheckout',
      'getCheckoutErrors',
    ]),
    ...mapMasterDataId({
      SALE_TYPES: {
        formationSalesTypeId: 'FORMATION',
        autoMaintenanceSalesTypeId: 'AUTO_MAINTENANCE',
        baUpgradeSalesTypeId: 'BA_UPGRADE',
        rentalSalesTypeId: 'RENTAL',
      },
    }),
    showProductPreviewerActionBarOption() {
      return this.showProductPreviewerActionBar !== false
    },
    checkSalesType: vue => (product, salesType) => {
      let productCartEligibleSalesTypes = vue.getCartProductEligibleSalesType(product.product_id, product.kitting_id)
      if (vue.getFilteredSalesTypes !== undefined) {
        return (
          (!vue.getFilteredSalesTypes.includes(vue.getBaSalesTypeId) &&
            typeof product.sales_types.find(type => type.id === salesType) !== 'undefined' &&
            ((productCartEligibleSalesTypes !== false && productCartEligibleSalesTypes.id === salesType) ||
              productCartEligibleSalesTypes === false)) ||
          (vue.getFilteredSalesTypes.includes(vue.getBaSalesTypeId) &&
            productCartEligibleSalesTypes !== false &&
            productCartEligibleSalesTypes.id === salesType)
        )
      }
      return false
    },
    isUpgradeProduct: vue => product => {
      let productCartEligibleSalesTypes = vue.getCartProductEligibleSalesType(product.product_id, product.kitting_id)
      if (vue.getFilteredSalesTypes !== undefined) {
        return (
          (vue.getFilteredSalesTypes.includes(vue.getBaSalesTypeId) &&
            typeof product.sales_types.find(type => type.key === 'ba-upgrade') !== 'undefined' &&
            ((productCartEligibleSalesTypes !== false &&
              productCartEligibleSalesTypes.id === vue.baUpgradeSalesTypeId) ||
              productCartEligibleSalesTypes === false)) ||
          (!vue.getFilteredSalesTypes.includes(vue.getBaSalesTypeId) &&
            productCartEligibleSalesTypes !== false &&
            productCartEligibleSalesTypes.key === 'ba-upgrade')
        )
      }
      return false
    },
    isDisabled: vue => product => {
      if (vue.$helpers.getValue(product, 'label.allow_checkout', '') === false) {
        return true
      } else {
        let productCartEligibleSalesTypes = vue.getCartProductEligibleSalesType(product.product_id, product.kitting_id)
        return (
          (typeof vue.allowDisable === 'undefined' || vue.allowDisable === null || vue.allowDisable === true) &&
          typeof productCartEligibleSalesTypes !== 'undefined' &&
          productCartEligibleSalesTypes !== false &&
          !vue.getFilteredSalesTypes.includes(productCartEligibleSalesTypes.id)
        )
      }
    },
    getDisableText: vue => product => {
      if (vue.$helpers.getValue(product, 'label.allow_checkout', '') === false) {
        return ''
      } else {
        let productCartEligibleSalesTypes = vue.getCartProductEligibleSalesType(product.product_id, product.kitting_id)
        if (productCartEligibleSalesTypes !== false) {
          return productCartEligibleSalesTypes.title
        } else {
          return ''
        }
      }
    },
    getTitleCharLimit() {
      return this.getLayoutMode(this.identifier, 'grid') === 'list' ? 100 : 35
    },
    isEnrolment() {
      return this.getAppStatus('enrolment')
    },
  },
  methods: {
    showProductDetail(val) {
      this.$refs.product_previewer.show(val)
    },
    showCommissionEntitlementModal(kittingId) {
      if (this.$refs.commission_entitlement) {
        this.$refs.commission_entitlement.show(kittingId)
      }
    },
    setDefaultSaleType(types, keys) {
      let id = null
      if (keys !== undefined && keys.length > 0) {
        for (let i = 0; i < keys.length; i++) {
          for (let j = 0; j < types.length; j++) {
            if (types[j].key === keys[i]) {
              id = types[j].id
            }
          }
        }
      }
      return id
    },
    getRentalPlanInfo(product, key) {
      let value = ''
      if (typeof product.rental_plan !== 'undefined') {
        if (product.rental_plan !== null) {
          value = product.rental_plan[key] + ''
        }
      }
      return value
    },
    getCvBreakdown(product) {
      let unitCv = product.unit_cv || {}
      return _.defaults(unitCv, {
        amp: 0,
        eligible: 0,
        upgrade: 0,
        welcome_pack: 0,
      })
    },
  },
}
</script>
