<template>
  <b-overlay :show="isBusy" variant="white" :class="[{ 'vh-75': isBusy }]" opacity="0.96">
    <template v-slot:overlay>
      <b-spinner class="mx-2 text-primary" />
      <strong class="h4 text-primary">{{ $t('Common.Loading') }}</strong>
    </template>

    <div class="bg-white">
      <b-container class="px-0">
        <b-breadcrumb class="bg-white">
          <b-breadcrumb-item @click="navigateToListingPage()">
            <div class="align-items-center d-flex">
              <icon name="back-arrow" class="icon-size-0 pr-1" />
              <span>{{ $t('Eshop.Order.ProductDetail.Home') }}</span>
            </div>
          </b-breadcrumb-item>
          <b-breadcrumb-item
            v-for="(category, idx) in getCategories"
            :key="idx"
            @click="navigateToListingPage(category)"
          >
            {{ category.name }}
          </b-breadcrumb-item>
          <b-breadcrumb-item v-if="!productDetails.error" active>
            {{
              $helpers.getValue(
                getProductDetails,
                (productType === 'product' && 'categories.name') || 'kitting_products[0].product.category.name',
                ''
              )
            }}
          </b-breadcrumb-item>
        </b-breadcrumb>
      </b-container>
    </div>

    <b-container class="p-3 mt-4 bg-white">
      <div v-if="productDetails.error" class="d-flex align-items-center justify-content-center vh-50">
        <h4 class="text-black">{{ $t('Common.RecordNotFound') }}</h4>
      </div>

      <b-row v-else>
        <b-col cols="12" md="4" lg="3" class="mb-4 mb-md-2">
          <div class="eshop-products-wrapper">
            <div class="eshop-products list m-0">
              <div class="eshop-product-wrapper">
                <div class="eshop-product border-0">
                  <b-img :src="getProductImage" class="w-100" />
                  <div
                    v-if="getProductDetails.label"
                    class="product-ribbon"
                    :style="`background-color:${getProductDetails.label.color_hex}`"
                  >
                    {{ getProductDetails.label.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <eshop-product-quantity-selector
            v-if="getProductSalesType"
            centered
            class="mt-3"
            :is-rental="isRental"
            :is-busy="isAddingProduct"
            :quantity="getProductQuantity"
            :pill="$appSettings.evo.enable"
            @update="addProductToCartByPass"
            data-qa-prefix="eshopProductDetails"
            ref="eshopProductQuantitySelector"
          />
        </b-col>
        <b-col>
          <div class="mb-4">
            <div>
              <h5 class="text-medium mb-3">{{ getProductDetails.name }}</h5>
            </div>
            <div class="mb-1">{{ getProductDetails.sku || getProductDetails.code }}</div>

            <div class="font-weight-bolder mb-3">
              <template v-if="isRental">
                <div>
                  <span>
                    {{ currency }}
                    {{ getProductDetails.rental_plan[0].initial_payment }}
                    ({{ $t('Eshop.Product.Initial') }})
                  </span>
                </div>
                <div>
                  <span>
                    {{ currency }}
                    {{ getProductDetails.rental_plan[0].monthly_repayment }} x
                    {{ getProductDetails.rental_plan[0].month }}
                    {{ $t('Eshop.Product.Tenure') }}
                  </span>
                </div>
              </template>
              <template v-else>
                <span>{{ currency }} {{ getProductPrice }}</span>
              </template>
            </div>

            <div v-if="getProductTag" class="mb-3">
              <b-badge :variant="getProductTag.variant" class="p-2">
                {{ getProductTag.text }}
              </b-badge>
            </div>

            <div v-if="getProductSalesType && getCvBreakDown.length" class="d-flex flex-row border-y py-2 mb-3">
              <div v-for="(point, idx) in getCvBreakDown" :key="idx" class="mr-3">
                <span class="pr-1">{{ point.label }}</span>
                <span class="text-primary">{{ point.value }}</span>
              </div>
            </div>
          </div>

          <div class="mb-4">
            <template v-for="(content, index) in getProductInformation">
              <b-card no-body :key="index" class="mt-3">
                <b-card-header
                  v-b-toggle="`accordion-${index}`"
                  class="outline-none text-capitalize font-weight-bold d-flex align-items-center justify-content-between"
                >
                  <span>{{ content.title }}</span>
                  <icon name="dashboard-arrow-down" />
                </b-card-header>
                <b-collapse :id="`accordion-${index}`" visible>
                  <b-card-body class="p-3" v-html="content.body" />
                </b-collapse>
              </b-card>
            </template>
          </div>
        </b-col>
      </b-row>
    </b-container>
  </b-overlay>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { getValue } from '@/helpers/variable-handling'
import currencyMixin from '@/app/_global/mixins/currencyMixin'
import ImagePlaceholder from '@/assets/img/image-placeholder-with-frame.svg'
import { mapMasterDataId } from '@/app/_global/mixins'
import EshopProductQuantitySelector from '@/app/_global/components/blocks/EshopProductQuantitySelector'

export default {
  name: 'EshopProductDetails',
  components: { EshopProductQuantitySelector },
  mixins: [currencyMixin],
  props: {
    pid: { type: String, required: true },
    saleType: { type: String, required: true },
    productType: { type: String, required: true },
  },
  data() {
    return {
      productDetails: {},
      categories: [],
    }
  },
  computed: {
    ...mapGetters(['isLoading', 'getAppLocationCountry', 'getSelectedLanguage', 'getMasterDataIdByKeyAndTitle']),
    ...mapGetters('eshop', ['getCartProductQuantity']),
    ...mapMasterDataId({
      SALE_TYPES: {
        formationSalesTypeId: 'FORMATION',
        baUpgradeSalesTypeId: 'BA_UPGRADE',
        autoMaintenanceSalesTypeId: 'AUTO_MAINTENANCE',
      },
    }),
    isBusy() {
      return this.isLoading(['productOrKittingDetails'])
    },
    isAddingProduct() {
      let { kitting_id, product_id } = this.getProductDetails
      return this.isLoading(`productsAddingToCart-${product_id}-${kitting_id}`)
    },
    getProductDetails() {
      let details = this.productDetails.details || {}
      return { ...details, product_id: details.product_id || null, kitting_id: details.kitting_id || null }
    },
    isRental() {
      return getValue(this.getProductDetails, 'rental_plan', []).length > 0
    },
    getProductImage() {
      let imgSrc = getValue(this.getProductDetails, 'images.list', []).find(img => img.default === 1) || {}
      if (imgSrc.image_link && this.$appSettings.config.https) {
        imgSrc.image_link = imgSrc.image_link.replace('http:', 'https:')
      }
      return imgSrc.image_link || ImagePlaceholder
    },
    getProductPrice() {
      let key = (this.productType === 'product' && 'base_price') || 'kitting_price'
      return getValue(this.getProductDetails, `${key}.gmp_price_tax`, '0.00')
    },
    getProductInformation() {
      let descriptions = this.getProductDetails.description || []
      if (descriptions.length > 0) {
        let content =
          descriptions.find(info => info.language_id === (this.getSelectedLanguage.id || 1)) || descriptions[0] || {}

        return [
          { title: this.$t('Eshop.Order.ProductDetail.Benefits'), body: content.benefits },
          { title: this.$t('Eshop.Order.ProductDetail.ProductSpecification'), body: content.specification },
          { title: this.$t('Eshop.Order.ProductDetail.Description'), body: content.marketing_description },
        ].filter(info => info.body)
      }
      return []
    },
    getCategories() {
      return [...this.categories].sort((a, b) => a.code - b.code)
    },
    getProductQuantity() {
      let { kitting_id, product_id } = this.getProductDetails
      return this.getCartProductQuantity(product_id, kitting_id)
    },
    getProductSalesType() {
      let salesTypeId = this.getMasterDataIdByKeyAndTitle('sale_types', this.saleType)
      return getValue(this.getProductDetails, 'general.sale_types', []).find(type => type === salesTypeId)
    },
    getCvBreakDown() {
      let { amp, eligible, upgrade, welcome_pack, sv, cbp_point } = getValue(
        this.getProductDetails,
        `unit_cv.sales_types[${this.saleType.toLowerCase()}]`,
        {}
      )

      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,
          show:
            this.getProductSalesType === this.autoMaintenanceSalesTypeId ||
            this.getProductSalesType === this.formationSalesTypeId,
        },
        {
          label: this.$t('Common.Terminology.RnkCv'),
          value: upgrade || 0,
        },
        {
          label: this.$t('Common.Terminology.WpCv'),
          value: welcome_pack || 0,
          show:
            this.getProductSalesType === this.baUpgradeSalesTypeId ||
            this.getProductSalesType === this.formationSalesTypeId,
        },
      ].filter(cv => cv.show !== false && cv.value)
    },
    getProductTag() {
      return (
        !this.$appSettings.evo.enable &&
        ((this.getProductSalesType === this.formationSalesTypeId && {
          variant: 'fpp',
          text: this.$t('Eshop.Product.FPP'),
        }) ||
          (this.getProductSalesType === this.baUpgradeSalesTypeId && {
            variant: 'upgrade',
            text: this.$t('Eshop.Product.Upgrade'),
          }) ||
          (this.getProductSalesType === this.autoMaintenanceSalesTypeId && {
            variant: 'amp',
            text: this.$t('Eshop.Product.AMP'),
          }))
      )
    },
  },
  async mounted() {
    this.loadCart()
    await this.loadProductDetails()
  },
  methods: {
    ...mapActions('eshop', [
      'loadCart',
      'addProductToCart',
      'loadProductOrKittingDetails',
      'productChangeCurrentCategory',
      'filterProductsSubCategory',
    ]),
    async loadProductDetails() {
      let payload = {
        country_id: this.getAppLocationCountry.countryId,
        location_id: this.getAppLocationCountry.locationId,
      }
      payload[this.productType === 'product' ? 'product_id' : 'kitting_id'] = parseInt(this.pid)

      await this.loadProductOrKittingDetails(payload).then(result => {
        let categoryObject = getValue(
          result,
          (this.productType === 'product' && 'details.categories') || 'details.kitting_products[0].product.category',
          {}
        )

        this.productDetails = (result && { ...result }) || { error: true }
        this.getProductCategory(categoryObject)
      })
    },
    getProductCategory(categoryObject) {
      if (categoryObject.parent && categoryObject.parent.parent) {
        this.categories.push(categoryObject.parent)
        this.getProductCategory(categoryObject.parent)
      }
    },
    navigateToListingPage(category = null) {
      if (category && category.code) {
        if (category.code.length > 3) {
          this.productChangeCurrentCategory(category.id)
        }
        if (category.code.length > 5) {
          this.filterProductsSubCategory([category.id])
        }
      }

      this.$router.push({ name: 'ListingHome' })
    },
    addProductToCartByPass(qty) {
      let self = this
      let payload = {
        product_id: this.getProductDetails.product_id,
        kitting_id: this.getProductDetails.kitting_id,
        salesTypeId: this.getProductSalesType,
        quantity: qty,
      }
      if (payload.salesTypeId) {
        this.addProductToCart(payload).then(res => {
          if (res === false) {
            if (self.$refs.eshopProductQuantitySelector) {
              self.$refs.eshopProductQuantitySelector.setProductQuantity(self.getProductQuantity)
            }
          }
        })
      }
    },
  },
}
</script>
