<template>
  <affix class="cart" relative-element-selector=".eshop-header">
    <b-dropdown
      id="cart_oppener"
      ref="cartdrop"
      right
      no-flip
      variant="link"
      no-caret
      class="cart-dropdown bg-transparent"
      data-qa="open-cart-dropdown"
    >
      <template slot="button-content">
        <b-badge v-if="getCartTotal !== 0" pill variant="danger" class="cart-badge ml-2">
          {{ getCartTotal }}
        </b-badge>
        <icon name="eshop-cart" class="icon-size-2 icon-size-md-4 text-white" />
      </template>
      <div
        v-mobile-page.no-padding-x="$refs.cartdrop && $refs.cartdrop.visible"
        @onMobileCancel="$refs.cartdrop.hide(true)"
        :mobile-page-title="$t('Eshop.Checkout.Cart.Title')"
      >
        <b-container class="py-3" v-if="getCartTotal === 0" :class="{ 'cart-loading': isLoading('loadingCart') }">
          <eshop-cart-btn-cv-display />
          <div class="py-4 text-center">
            <icon name="eshop-empty-cart" class="icon-size-5 text-light" />
            <div class=" text-dark font-weight-bold">
              {{ $t('Common.Cart.EmptyCart') }}
            </div>
          </div>
          <div class="divider clearfix text-center py-4 no-overflow-imp">
            <b-btn variant="primary w-50" @click="closeDropdown">
              {{ $t('Eshop.Product.GoShopping') }}
            </b-btn>
          </div>
        </b-container>
        <div v-else class="mt-4 mt-md-0">
          <!-- Need a wrapper to make v-bar work -->
          <div class="cart-content" :class="{ 'cart-loading': isLoading('loadingCart') }" ref="vueBarSider">
            <b-container class="py-1 px-0 custom-scroll-bar">
              <div v-if="getCartHasUpgrade && getMemberEnrollmentRank.id !== 1" class="divider">
                <h6 class="text-primary text-center mb-0">
                  {{ $t('Eshop.Rank.Type.Title') }}
                </h6>
                <h2 class="text-center text-dark mb-0">
                  {{ nextRankName }}
                </h2>
                <cart-upgrade-steps
                  ref="cartUpgradeStepsElement"
                  :member-enrollment-rank-id="getMemberEnrollmentRank.id"
                  :cart-cvs="getCartCv"
                  :update-step-watcher="updateStepWatcher"
                />
                <template v-if="getCheckout.status === true">
                  <div class="px-4 py-2" v-if="nextRnkCv || nextAmpCv">
                    <span class="text-upgrade font-weight-bold-extra" v-if="nextRnkCv">
                      {{ nextRnkCv }} {{ $t('Common.Terminology.RnkCv') }}
                    </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>
                </template>
                <template v-else>
                  <div class="py-2">
                    <span class="text-danger font-weight-bold-extra">
                      {{ getCheckout.messages.default }}
                    </span>
                  </div>
                  <template v-if="getCheckout.status === false">
                    <div
                      class="py-2 text-danger font-weight-bold-extra"
                      v-for="(error, index) in getCheckoutErrors"
                      :key="index"
                    >
                      {{ error }}
                    </div>
                  </template>
                </template>
              </div>
              <div v-else>
                <div class="py-0" v-if="getCheckout.status === false">
                  <span class="text-danger font-weight-bold-extra">
                    {{ getCheckout.messages.default }}
                  </span>
                </div>
                <template v-if="getCheckout.status === false">
                  <div
                    class="text-danger font-weight-bold-extra"
                    v-for="(error, index) in getCheckoutErrors"
                    :key="index"
                  >
                    {{ error }}
                  </div>
                </template>
              </div>
              <eshop-cart-btn-cv-display class="m-0" />
              <b-container class="divider py-1 cart-items overflow-y-auto">
                <!-- PRODUCT LIST START ------------------------------------------------------------------------------------->
                <div
                  v-for="(item, index) in getCartDisplayItems"
                  class="divider mt-2"
                  :key="`eshopCart-${index}-${item.product_id}-${item.kitting_id}`"
                >
                  <div>
                    <b-row no-gutters class="mb-2">
                      <b-col>
                        <div class="font-weight-bolder">{{ item.name }}</div>
                        <div>{{ item.sku }}</div>
                      </b-col>
                      <b-col cols="auto">
                        <b-button
                          class="pt-0 pr-0"
                          variant="link"
                          @click="updateProductQuantity(item, 0)"
                          :data-qa="`eshop-cart-product-${item.sku.toLowerCase()}-remove-product-btn`"
                        >
                          <icon name="eshop-remove" class="text-light icon-size-3" />
                        </b-button>
                      </b-col>
                    </b-row>
                  </div>

                  <div class="mb-2">
                    <b-row>
                      <b-col cols="auto">
                        <b-badge
                          v-if="item.eligible_sales_type.id === baUpgradeSalesTypeId"
                          variant="upgrade"
                          class="p-2"
                        >
                          {{ $t('Eshop.Product.Upgrade') }}
                        </b-badge>

                        <b-badge
                          v-else-if="item.eligible_sales_type.id === autoMaintenanceSalesTypeId"
                          variant="amp"
                          class="p-2"
                        >
                          {{ $t('Eshop.Product.AMP') }}
                        </b-badge>

                        <b-badge
                          v-else-if="item.eligible_sales_type.id === formationSalesTypeId"
                          variant="fpp"
                          class="p-2"
                        >
                          {{ $t('Eshop.Product.FPP') }}
                        </b-badge>
                      </b-col>
                      <b-col class="text-right font-weight-bold">
                        <div class="text-primary">
                          <span v-if="item.rental_plan">
                            {{ $t('Common.Terminology.Bv') }}
                            {{ item.rental_plan.cv_value }} x
                            {{ item.rental_plan.number_cv }}
                            {{ $t('Eshop.Product.Tenure') }}
                          </span>
                          <span v-else>
                            {{ $t('Common.Terminology.Bv') }}
                            {{ item.total_cv.eligible }}
                          </span>
                        </div>

                        <div v-if="isEvo" class="text-primary">
                          <span v-if="item.rental_plan">
                            {{ $t('Common.Terminology.Sv') }}
                            {{ item.rental_plan.sv_value }} x
                            {{ item.rental_plan.number_sv }}
                            {{ $t('Eshop.Product.Tenure') }}
                          </span>
                          <span v-else>
                            {{ $t('Common.Terminology.Sv') }}
                            {{ item.total_cv.sv }}
                          </span>
                        </div>

                        <div v-if="isEvo" class="text-primary">
                          <span v-if="item.rental_plan">
                            {{ $t('Common.Terminology.Cbp') }}
                            {{ item.rental_plan.total_cbp_point }}
                          </span>
                          <span v-else>
                            {{ $t('Common.Terminology.Cbp') }}
                            {{ item.total_cv.cbp_point }}
                          </span>
                        </div>

                        <div
                          v-if="item.eligible_sales_type.id === autoMaintenanceSalesTypeId && !isEvo"
                          class="text-info-green"
                        >
                          <span>
                            {{ $t('Common.Terminology.AmpCv') }}
                            {{ item.total_cv.amp }}
                          </span>
                        </div>

                        <div v-if="item.total_cv.upgrade !== 0 && !isEvo && !item.rental_plan" class="text-upgrade">
                          <span>
                            {{ $t('Common.Terminology.RnkCv') }}
                            {{ item.total_cv.upgrade }}
                          </span>
                        </div>
                      </b-col>
                    </b-row>
                  </div>

                  <div class="font-weight-bold mb-2">
                    <b-row class="m-0">
                      <b-col cols="auto" class="align-self-end">
                        <eshop-product-quantity-selector
                          force-show-quantity-selector
                          :pill="isEvo"
                          :quantity-buttons-wrapper-class="['px-1']"
                          @update="val => updateProductQuantity(item, val)"
                          :quantity="getCartProductQuantity(item.product_id, item.kitting_id)"
                          :max-range="item.eligible_sales_type.id === rentalSalesTypeId ? 1 : 999"
                          :is-busy="isLoading('productsAddingToCart-' + item.product_id + '-' + item.kitting_id)"
                          :data-qa-prefix="`eshopCartBtn-${item.sku.toLowerCase()}`"
                        />
                      </b-col>
                      <b-col class="text-right align-self-end text-black pr-0">
                        <div v-if="item.rental_plan">
                          <div>
                            <span>
                              {{ currency }}
                              {{ item.rental_plan.initial_payment }}
                              ({{ $t('Eshop.Product.Initial') }})
                            </span>
                          </div>
                          <div>
                            <span>
                              {{ currency }}
                              {{ item.rental_plan.monthly_repayment }} x {{ item.rental_plan.month }}
                              {{ $t('Eshop.Product.Tenure') }}
                            </span>
                          </div>
                        </div>

                        <div v-else>
                          <span>
                            {{ currency }}
                            {{ item.total_price_formatted }}
                          </span>
                        </div>
                      </b-col>
                    </b-row>
                  </div>
                </div>
                <!-- PRODUCT LIST END --------------------------------------------------------------------------------------->
              </b-container>
              <b-container>
                <b-row
                  v-for="(value, type) in cvTypes"
                  :key="`total_${type}`"
                  class="border-dashed-bottom clearfix mx-1 mt-2"
                >
                  <b-col>
                    <span class="align-middle"> {{ $t('Common.Sales.Total') }} {{ $t(value.label) }} </span>
                  </b-col>
                  <b-col class="h6 text-right p-1 m-0" :class="[value.color]">
                    {{ getCartCv[type] }}
                  </b-col>
                </b-row>

                <b-row v-if="getCartCampaignDetails" class="border-dashed-bottom clearfix mx-1 mt-2">
                  <b-col>{{ $t('Itoken.TotalITokenPoint') }}</b-col>
                  <b-col class="h6 text-right p-1 m-0">
                    {{ $helpers.getValue(getCartCampaignDetails, 'calculation.total_point', 0) }}
                  </b-col>
                </b-row>

                <b-row class="divider clearfix">
                  <b-col>
                    <span class="align-middle text-dark line-height-3 font-weight-bold">
                      {{ $t('Common.Sales.Total') }} {{ getSelectedCountry.currency.code }}
                    </span>
                  </b-col>
                  <b-col class="h3 text-right py-2">
                    {{ getCartTotalPriceFormatted }}
                  </b-col>
                </b-row>
                <div class="divider clearfix text-center py-2">
                  <router-link :to="checkoutPath" @click.native="closeDropdown">
                    <b-btn
                      variant="primary w-50"
                      :disabled="!getCheckout.status || isLoading(['loadingCart', 'productsAddingToCart'])"
                      data-qa="checkout-btn"
                    >
                      {{ $t('Common.Sales.PreCheckout') }}
                    </b-btn>
                  </router-link>
                </div>
              </b-container>
            </b-container>
          </div>
        </div>
      </div>
    </b-dropdown>
  </affix>
</template>
<script>
import { ESHOP_CHECKOUT } from '@/config/url-prefix'
import { mapGetters, mapActions } from 'vuex'
import currencyMixin from '@/app/_global/mixins/currencyMixin'
import { mapMasterDataId } from '@/app/_global/mixins'
import CartUpgradeSteps from '@/app/_global/components/elements/CartUpgradeSteps'
import EshopCartBtnCvDisplay from './EshopCartBtnCvDisplay'
import EshopProductQuantitySelector from '@/app/_global/components/blocks/EshopProductQuantitySelector'

export default {
  name: 'EshopCartBtn',
  mixins: [currencyMixin],
  data() {
    return {
      vueSidebarConfig: {
        preventParentScroll: true,
        resizeRefresh: true,
      },
      checkoutPath: ESHOP_CHECKOUT,
      nextRankName: '-',
      nextAmpCv: null,
      nextRnkCv: null,
      isEvo: this.$appSettings.evo.enable,
    }
  },
  components: {
    EshopProductQuantitySelector,
    CartUpgradeSteps,
    EshopCartBtnCvDisplay,
  },
  mounted() {},
  methods: {
    ...mapActions('eshop', ['addProductToCart', 'loadCartProductEligible']),
    closeDropdown() {
      ;(obj => (obj ? obj.click() : ''))(document.querySelector('#cart_oppener__BV_toggle_'))
    },
    updateStepWatcher(updateSteps) {
      let title = '-'
      this.nextAmpCv = null
      this.nextRnkCv = null
      let nextStep = this.$helpers.getValue(updateSteps, 'nextStep')
      if (nextStep) {
        if (nextStep.entitlement_lvl > this.getMemberEnrollmentRank.entitlement_lvl) {
          title = nextStep.rank_name
        }
        if (nextStep.entitlement_lvl + 1 === this.getMemberEnrollmentRank.entitlement_lvl + 1) {
          if (updateSteps.isWp && updateSteps.wpCvToNextLevel) {
            this.nextRnkCv = updateSteps.wpCvToNextLevel
          }
          if (updateSteps.ampCvToNextLevel) {
            this.nextAmpCv = updateSteps.ampCvToNextLevel
          }
        }
        this.nextRankName = title
      }
    },
    updateProductQuantity(item, qty) {
      let payload = {
        product_id: item.product_id,
        kitting_id: item.kitting_id,
        quantity: qty,
      }
      this.addProductToCart(payload)
    },
  },
  computed: {
    ...mapGetters('eshop', [
      'getCartCv',
      'getCartTotal',
      'getCartTotalPriceFormatted',
      'getCartPriceFormatted',
      'getCartHasUpgrade',
      'getCartItems',
      'getCartProductQuantity',
      'getCartProductSaleTypeId',
      'getEligiblePromotion',
      'getCwInfo',
      'getCartHasAmpUpgrade',
      'getCheckout',
      'getCartUserNeedActivation',
      'getCheckoutErrors',
      'getCartCampaignDetails',
    ]),
    ...mapGetters(['getSelectedCountry', 'getMemberEnrollmentRank', 'getMemberEnrollmentRankCW', 'isLoading']),
    ...mapMasterDataId({
      SALE_TYPES: {
        formationSalesTypeId: 'FORMATION',
        autoMaintenanceSalesTypeId: 'AUTO_MAINTENANCE',
        baUpgradeSalesTypeId: 'BA_UPGRADE',
        rentalSalesTypeId: 'RENTAL',
      },
    }),
    cvTypes() {
      let cvTypes = {}
      let types = {
        eligible: { label: 'Common.Terminology.Bv', color: 'text-primary', forceShow: this.isEvo },
        amp: { label: 'Eshop.Product.AMP', color: 'text-info-green', show: !this.isEvo },
        welcome_pack: { label: 'Common.Terminology.WpCv', color: 'text-upgrade', show: !this.isEvo },
        sv: { label: 'Common.Terminology.Sv', color: 'text-primary', forceShow: this.isEvo },
        cbp_point: { label: 'Common.Terminology.Cbp', color: 'text-primary', forceShow: this.isEvo },
      }

      for (let i in types) {
        if ((this.$helpers.getValue(this.getCartCv, i, 0) !== 0 || types[i].forceShow) && types[i].show !== false) {
          cvTypes[i] = types[i]
        }
      }

      return cvTypes
    },
    getCartDisplayItems() {
      return this.getCartItems.filter(item => item.free === false)
    },
  },
  watch: {
    getCartTotal(to) {
      if (to > 0) {
        if (typeof this.$refs.vueBarSider !== 'undefined') {
          this.$vuebar.refreshScrollbar(this.$refs.vueBarSider, this.vueSidebarConfig)
        }
      }
    },
  },
}
</script>
