<template>
  <div class="eshop-product-wrapper">
    <div
      ref="product"
      class="h-100"
      :class="[
        'rounded-1',
        'eshop-product',
        {
          'border-primary': getProductQuantity !== 0,
          disabled: disabled,
          simple: simple,
        },
      ]"
    >
      <div class="product-count" :class="{ 'product-count-tick': showTickForCount }" v-if="getProductQuantity !== 0">
        <icon v-if="showTickForCount" name="check" class="icon-size-1" />
        <template v-else>
          {{ getProductQuantity }}
        </template>
      </div>
      <div
        v-if="disabled && disabledText !== ''"
        class="p-3 pos-absolute-br d-flex flex-column disabled-area c-pointer"
      >
        <icon
          name="eshop-padlock"
          class="icon-size-3 text-success"
          @mouseover="() => $refs.disabledTextTooltip.$emit('open')"
          @mouseleave="() => $refs.disabledTextTooltip.$emit('close')"
        />
        <div v-if="disabledText" class="tag bg-success text-white border border-white" ref="disabledText">
          {{ disabledText }}
        </div>
      </div>
      <!--TODO: IMPLEMENT IN VERSION 2-->
      <!--<div class="product-like pos-absolute-tr" v-if="!simple">-->
      <!--<button @click="toggleLike">-->
      <!--<icon :class="{'text-white' : true, 'icon-size-4' : true, 'liked' : liked }" @click="toggleLike">-->
      <!--<icon name="eshop-like"/>-->
      <!--<icon v-if="liked" name="eshop-like-heart" class="text-black heart-shadow"/>-->
      <!--<icon v-if="liked" name="eshop-like-heart" class="heart"/>-->
      <!--</icon>-->
      <!--</button>-->
      <!--</div>-->
      <div class="product-image h-auto align-items-center">
        <b-link @click="viewProductDetails">
          <b-img-lazy
            :alt="getProductDetails.name"
            :title="getProductDetails.name"
            :src="getProductDetails.image || imagePlaceholder"
          />
        </b-link>
      </div>
      <div
        class="product-ribbon"
        v-if="getProductDetails.label"
        :style="`background-color:${getProductDetails.label.color_hex}`"
      >
        {{ getProductDetails.label.name }}
      </div>
      <div v-if="$appSettings.evo.enable" class="px-3 d-flex flex-column h-100 pb-3 flex-grow-1">
        <h6 class="text-black-50 font-weight-bold-semi text-break mt-4">{{ getEllipsisProductName }}</h6>
        <div class="mt-auto pt-4">
          <b-row class="align-items-end">
            <b-col class="pr-0" cols="auto">
              <span class="text-black-50">{{ getProductDetails.sku }}</span>
            </b-col>
            <b-col
              cols="12"
              xl="auto"
              class="font-weight-bold"
              :class="displayGrid ? ['text-right', 'ml-auto'] : ['w-100']"
            >
              <template v-if="isRental">
                <div>
                  <span>
                    {{ currency }}
                    {{ $helpers.getValue(getProductDetails, 'rental_plan.initial_payment', '') }}
                    ({{ $t('Eshop.Product.Initial') }})
                  </span>
                </div>
                <div>
                  <span>
                    {{ currency }}
                    {{ $helpers.getValue(getProductDetails, 'rental_plan.monthly_repayment', '') }} x
                    {{ $helpers.getValue(getProductDetails, 'rental_plan.month', '') }}
                    {{ $t('Eshop.Product.Tenure') }}
                  </span>
                </div>
              </template>
              <span v-else>{{ currency }} {{ getProductDetails.price }}</span>
            </b-col>
          </b-row>
          <div v-if="showPointsAllocation">
            <hr class="my-2" />
            <b-row v-if="isRental" class="text-black-50 mb-2">
              <b-col cols="12" class="font-weight-bold mb-1 text-capitalize">
                {{ $t('Eshop.CommissionEntitlement') }}
              </b-col>
              <b-col cols="12">
                <b-row no-gutters>
                  <b-col>
                    <small>{{ $t('Eshop.CommissionEntitlement.Description') }}</small>
                  </b-col>
                  <b-col cols="auto" class="ml-auto">
                    <b-button variant="link" class="p-0 pl-2" @click="viewCommissionEntitlement">
                      <icon name="info-circle-icon" />
                    </b-button>
                  </b-col>
                </b-row>
              </b-col>
            </b-row>
            <b-row>
              <b-col cols="auto" v-for="(cv, index) in getDisplayUnitCv" :key="index">
                <small class="text-black-50 font-weight-bold">{{ cv.label }}</small>
                <small class="text-primary pl-1 font-weight-bold">{{ cv.value }}</small>
              </b-col>
            </b-row>
          </div>
          <hr class="my-2" />
          <eshop-product-quantity-selector
            pill
            class="mt-3"
            :is-rental="isRental"
            :centered="displayGrid"
            :quantity="getProductQuantity"
            @update="updateProductQuantity"
            :max-range="isStarterKit ? 1 : 999"
            :is-busy="getProductQuantityUpdateStatus"
            :disabled="disabledEshopProductQuantitySelector"
            :quantity-buttons-wrapper-class="eshopQuantitySelectorButtonsWrapperClass"
            :add-to-cart-btn-text="(isStarterKit && $t('Eshop.Order.GlobalWords.Select')) || ''"
            :data-qa-prefix="getDataQaPrefix"
            ref="eshopProductQuantitySelector"
          />
        </div>
      </div>

      <div v-else class="product-content">
        <div class="tags font-size-8" v-if="!simple">
          <div :class="[['tag', 'colored', 'upgrade'], { 'pos-absolute-br': disabled }]" v-if="upgrade">
            {{ $t('Eshop.Product.Upgrade') }}
          </div>
          <div :class="[['tag', 'colored', 'amp'], { 'pos-absolute-br': disabled }]" v-if="amp">
            {{ $t('Eshop.Product.AMP') }}
          </div>
          <div :class="[['tag', 'colored', 'fpp'], { 'pos-absolute-br': disabled }]" v-if="fpp">
            {{ $t('Eshop.Product.FPP') }}
          </div>
        </div>
        <div class="font-weight-bold product-title">
          {{ getEllipsisProductName }}
        </div>
        <div class="tags font-size-8" v-if="!simple && !isRental">
          <div class="font-weight-bold-extra tag cv mr-2" v-if="basicCv !== 0">
            {{ $t('Eshop.Product.CV') }} {{ basicCv }}
          </div>
          <div class="font-weight-bold-extra tag amp mr-2" v-if="ampCv !== 0">
            {{ $t('Common.Terminology.AmpCv') }} {{ ampCv }}
          </div>
          <div class="font-weight-bold-extra tag upgrade mr-2" v-if="wpCv !== 0">
            {{ $t('Common.Terminology.WpCv') }} {{ wpCv }}
          </div>
          <div class="font-weight-bold tag upgrade mr-2" v-if="rnkCv !== 0">
            {{ $t('Common.Terminology.RnkCv') }} {{ rnkCv }}
          </div>
          <div class="font-weight-bold tag" v-if="ampCv === 0 && basicCv === 0 && rnkCv === 0 && wpCv === 0">
            &nbsp;
          </div>
        </div>
        <div class="font-weight-bold product-code">
          {{ getProductDetails.sku }}
        </div>
        <div class="cv" v-if="simple && isRental">
          <div class="content">
            <div class="subtitle font-weight-bold-extra tag upgrade font-weight-bold">
              {{ $t('Eshop.Product.CV') }}
            </div>
            <div class="subcontent">{{ rentalCv }} x {{ rentalCvNum }} {{ $t('Eshop.Product.Tenure') }}</div>
          </div>
        </div>
        <div class="font-weight-bold-extra product-price" :class="{ 'text-danger': simple }" v-if="isRental">
          {{ currency }} {{ initialPayment }} ({{ $t('Eshop.Product.Initial') }})
        </div>
        <div class="font-weight-bold-extra product-price mb-2" :class="{ 'text-danger': simple }" v-if="isRental">
          {{ currency }} {{ monthlyRepayment }} x {{ repaymentMonths }} {{ $t('Eshop.Product.Tenure') }}
        </div>

        <div class="font-weight-bold-extra product-price" :class="{ 'text-danger': simple }" v-if="!isRental">
          {{ currency }} {{ getProductDetails.price }}
        </div>
        <div class="cv" v-if="simple && !isRental">
          <div class="box">
            <div class="title">
              {{ $t('Eshop.Product.CV') }}
            </div>
            <div class="content">
              <div class="subtitle font-weight-bold-extra tag upgrade font-weight-bold">
                {{ $t('Eshop.Product.WP') }}
              </div>
              <div class="subcontent ">
                {{ wpCv }}
              </div>
            </div>
          </div>
        </div>
        <eshop-item-quantity
          v-if="showQuantitySelector()"
          class="pt-2"
          :get-custom-product-details="appendFullProductDetailsToPayload"
          :custom-product-details="getProductDetails"
          :simple="fullWidthButtonGroup || simple"
          :short-btn="shortBtn"
          :product-quantity-getter="productQuantityGetter"
          :product-id="productDetails.product_id"
          :kitting-id="productDetails.kitting_id"
          :sales-type-id="saleTypeId"
          :quantity="getProductQuantity"
          :is-adding="getProductQuantityUpdateStatus"
          :process-cart-callback="addProductToCartBypass ? addProductToCartBypass : addProductToCart"
          :data-qa-prefix="getDataQaPrefix"
        />
      </div>
    </div>
    <b-tooltip
      v-if="disabled && disabledText !== ''"
      :target="() => $refs.disabledText"
      class="small"
      ref="disabledTextTooltip"
      placement="bottom"
    >
      {{ $t('Eshop.Product.AddedToCartAs', { type: disabledText }) }}
    </b-tooltip>
  </div>
</template>
<script>
import { getValue } from '@/helpers/variable-handling'
import { mapGetters, mapActions } from 'vuex'
import EshopItemQuantity from './EshopItemQuantity'
import currencyMixin from '../../mixins/currencyMixin'
import ImagePlaceholder from '@/assets/img/image-placeholder-with-frame.svg'
import EshopProductQuantitySelector from '@/app/_global/components/blocks/EshopProductQuantitySelector'

export default {
  name: 'Product',
  mixins: [currencyMixin],
  props: {
    simple: {
      type: Boolean,
      default: false,
    },
    identifier: {
      type: String,
      required: true,
    },
    productQuantityGetter: {
      type: Function,
      required: true,
    },
    saleTypeId: {
      type: Number,
    },
    initialPayment: {
      type: String,
    },
    monthlyRepayment: {
      type: String,
    },
    repaymentMonths: {
      type: String,
    },
    rentalCv: {
      type: String,
    },
    rentalCvNum: {
      type: String,
    },
    rentalTotalPayment: {
      type: String,
    },
    upgrade: {
      type: Boolean,
      default: false,
    },
    fpp: {
      type: Boolean,
      default: false,
    },
    amp: {
      type: Boolean,
      default: false,
    },
    ampCv: {
      type: [Number, String],
      default: 0,
    },
    basicCv: {
      type: [Number, String],
      default: 0,
    },
    rnkCv: {
      type: [Number, String],
      default: 0,
    },
    wpCv: {
      type: [Number, String],
      default: 0,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    maxTitleLength: {
      type: Number,
      default: 35,
    },
    addProductToCartBypass: {
      type: Function,
    },
    disabledText: {
      type: String,
      default: '',
    },
    isPopupProductViewer: {
      type: Boolean,
      default: false,
    },
    isDisplayProductOnly: {
      type: Boolean,
      default: false,
    },
    isExternalLinkRouting: {
      type: Boolean,
      default: false,
    },
    externalLinkBase: {
      type: String,
    },
    externalLinkOpenMethod: {
      Type: String,
    },
    fullWidthButtonGroup: {
      type: Boolean,
      default: false,
    },
    productDetails: {
      type: Object,
      default: () => ({}),
    },
    appendFullProductDetailsToPayload: {
      type: Boolean,
      default: false,
    },
    eshopQuantitySelectorButtonsWrapperClass: {
      type: [Array, String],
      default: () => [],
    },
    showPointsAllocation: {
      type: Boolean,
      default: true,
    },
    showTickForCount: {
      type: Boolean,
      default: false,
    },
    disabledEshopProductQuantitySelector: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      liked: false,
      selectedProduct: null,
      shortBtn: false,
      isRental: false,
      itemWidth: 25,
      imagePlaceholder: ImagePlaceholder,
    }
  },
  mounted() {
    this.liked = this.getProductDetails.favorites_id !== null
    if (this.saleTypeId !== null) {
      let sales_type_title = this.getMasterDataTitleByKeyAndId('sale_types', this.saleTypeId)
      sales_type_title = sales_type_title && sales_type_title.toLowerCase()
      this.isRental = sales_type_title === 'rental'
    }
  },
  components: { EshopProductQuantitySelector, EshopItemQuantity },
  methods: {
    ...mapActions('eshop', ['addProductToCart', 'setShowProductDetailModal']),
    toggleLike() {
      this.liked = !this.liked
    },
    navigateProductDetailsPage() {
      if (this.getFilteredSalesTypes !== undefined) {
        let saleType = this.getMasterDataTitleByKeyAndId('sale_types', this.getFilteredSalesTypes[0])
        if (saleType) {
          let { product_id, kitting_id } = this.getProductDetails

          this.$router.push({
            name: 'EshopProductDetail',
            params: {
              saleType: saleType.toLowerCase(),
              productType: kitting_id === null ? 'product' : 'kitting',
              pid: (kitting_id === null ? product_id : kitting_id).toString(),
            },
          })
        }
      }
    },
    showProductDetailModal() {
      this.$emit('openModal', {
        ...this.getProductDetails,
        sales_type_id: this.saleTypeId,
        has_amp: this.amp,
        has_fpp: this.fpp,
        is_rental: this.isRental,
        is_starter_kit: this.isStarterKit,
      })
    },
    openExternalLink() {
      let { product_id, kitting_id } = this.getProductDetails
      const dataMap = {
        origin: location.origin,
        type: kitting_id === null ? 'product' : 'kitting',
        id: kitting_id === null ? product_id : kitting_id,
      }
      let link = (this.externalLinkBase || '#').replace(/{origin}|{type}|{id}/gi, key => dataMap[key.slice(1, -1)])
      window.open(link, this.externalLinkOpenMethod || '_blank')
    },
    showQuantitySelector() {
      return !this.isDisplayProductOnly || getValue(this.getProductDetails, 'label.allow_checkout', '') !== false
    },
    viewProductDetails() {
      let action =
        (this.isPopupProductViewer && this.showProductDetailModal) ||
        (this.isExternalLinkRouting && this.openExternalLink) ||
        this.navigateProductDetailsPage
      action()
    },
    async updateProductQuantity(qty) {
      let self = this
      let action = this.addProductToCartBypass ? this.addProductToCartBypass : this.addProductToCart
      let payload = {
        product_id: this.getProductDetails.product_id,
        kitting_id: this.getProductDetails.kitting_id,
        quantity: qty,
        salesTypeId: this.saleTypeId,
      }

      if (this.appendFullProductDetailsToPayload) {
        payload['custom'] = { ...this.getProductDetails }
      }

      await action(payload).then(res => {
        if (res === false) {
          if (self.$refs.eshopProductQuantitySelector) {
            self.$refs.eshopProductQuantitySelector.setProductQuantity(self.getProductQuantity)
          }
        }
      })
    },
    viewCommissionEntitlement() {
      this.$emit('commission-entitlement', this.productDetails.kitting_id)
    },
  },
  computed: {
    ...mapGetters(['isLoading', 'getMasterDataTitleByKeyAndId', 'getMasterDataByKey', 'getLayoutMode']),
    ...mapGetters('eshop', ['getFilteredSalesTypes']),
    displayGrid() {
      return this.getLayoutMode('products', 'grid') !== 'list'
    },
    getProductDetails() {
      return this.productDetails || {}
    },
    getEllipsisProductName() {
      let productName = this.getProductDetails.name || ''
      return productName.length > this.maxTitleLength
        ? productName.substring(0, this.maxTitleLength) + ' ...'
        : productName
    },
    getDisplayUnitCv() {
      let { cbp_point, eligible, sv, amp, upgrade, welcome_pack } = this.getProductDetails.unit_cv || {}

      if (this.isRental && this.getProductDetails.rental_plan) {
        eligible = this.getProductDetails.rental_plan.total_bv
        sv = this.getProductDetails.rental_plan.total_sv
        cbp_point = this.getProductDetails.rental_plan.total_cbp_point
      }

      if (this.$appSettings.evo.enable) {
        return [
          { label: this.$t('Common.Terminology.Bv'), value: eligible || '0.00' },
          { label: this.$t('Common.Terminology.Sv'), value: sv || 0 },
          { label: this.$t('Common.Terminology.Cbp'), value: cbp_point || '0.0000' },
        ]
      }
      return [
        { label: this.$t('Common.Terminology.Bv'), value: eligible || 0 },
        { label: this.$t('Common.Terminology.AmpCv'), value: amp || 0 },
        { label: this.$t('Common.Terminology.RnkCv'), value: upgrade || 0 },
        { label: this.$t('Common.Terminology.WpCv'), value: welcome_pack || 0 },
      ].filter(cv => cv.value)
    },
    getProductQuantity() {
      let { product_id, kitting_id } = this.getProductDetails
      return this.productQuantityGetter(product_id, kitting_id)
    },
    getProductQuantityUpdateStatus() {
      let { product_id, kitting_id } = this.getProductDetails
      return this.isLoading([
        `${this.identifier}AddingToCart-${product_id}-${kitting_id}`,
        `productsAddingToCart-${product_id}-${kitting_id}`,
      ])
    },
    getDataQaPrefix() {
      return `product-${(this.getProductDetails.sku || '').toLowerCase()}`
    },
    isStarterKit() {
      return (this.getProductDetails.filters || []).includes('starter_kit')
    },
  },
}
</script>
