<template>
  <b-container class="my-4">
    <div v-show="isLoading('productOrKittingDetails')" ref="loader" class="loader loading"></div>
    <b-row v-if="getProductCode" class="m-0">
      <b-col cols="12" lg="5">
        <b-carousel
          class="custom-carousel"
          v-bind="{ controls: getProductImages.length > 1, indicators: getProductImages.length > 1 }"
        >
          <b-carousel-slide v-for="(image, index) in getProductImages" :key="index">
            <template v-slot:img>
              <b-img-lazy
                fluid
                center
                :src="image"
                blank-width="400"
                blank-height="400"
                blank-color="lightgray"
                class="product-image text-center"
                :alt="`${productInfo.name.toLowerCase()} ${$t('Common.Image.Label')}`"
              />
            </template>
          </b-carousel-slide>
        </b-carousel>
        <hr class="d-lg-none" />
      </b-col>

      <b-col class="border-lg-left px-4">
        <h5 class="mb-0">{{ productInfo.name }}</h5>
        <div class="text-black-50">{{ getProductCode }}</div>
        <div v-if="getProductBv">{{ `${$t('Common.Terminology.Bv')} ${getProductBv}` }}</div>
        <h6 class="text-danger mb-0">{{ getProductPrice }}</h6>

        <div>
          <b-row class="align-items-center mt-4">
            <b-col cols="auto">
              <quantity-selector v-model="productQuantity" squared />
            </b-col>
            <b-col>
              <b-button
                squared
                block
                size="lg"
                variant="primary"
                @click="addToCart"
                :disabled="isAddingCart"
                class="d-flex align-items-center justify-content-center"
              >
                <b-spinner v-show="isAddingCart" small class="mr-2 m-1" />
                <span v-show="!isAddingCart">{{ $t('Eshop.AddToCart.Label') }}</span>
              </b-button>
            </b-col>
          </b-row>
        </div>

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

<script>
import { mapActions, mapGetters } from 'vuex'
import { getValue } from '@/helpers/variable-handling'
import ProductPlaceholderImage from '@@/assets/images/product-placeholder.svg'
import QuantitySelector from '@@/app/_global/components/blocks/QuantitySelector'
import { mapMasterData } from '@/app/_global/mixins'
import AppSettings from '@/config/app-settings'
import lottie from 'lottie-web'
import Loader from '@@/app/_global/components/elements/lottie/loader.json'
export default {
  name: 'ProductViewer',
  components: { QuantitySelector },
  props: {
    id: { type: String, required: true },
    type: { type: String, required: true },
  },
  data() {
    return {
      productQuantity: 1,
      productInfo: {},
      addingCart: false,
    }
  },
  computed: {
    ...mapMasterData({
      SALE_TYPES: {
        repurchaseSalesTypeId: 'RE_PURCHASE',
      },
    }),
    ...mapGetters(['getAppLocationCountry', 'getSelectedLanguage', 'isLoading']),
    getProductImages() {
      let imageSrc = getValue(this.productInfo, 'images.list', [])
      imageSrc = (imageSrc.length && [...imageSrc]) || [{ image_link: ProductPlaceholderImage }]
      return imageSrc.sort((a, b) => b.default - a.default).map(obj => obj.image_link)
    },
    getProductPrice() {
      let priceType = (this.type === 'kitting' && 'kitting_price') || 'base_price'
      let currency = getValue(this.productInfo, 'currency.code')
      let price = getValue(this.productInfo, priceType + '.gmp_price_tax')

      return (currency && price && `${currency} ${price}`) || ''
    },
    getProductBv() {
      return getValue(this.productInfo, 'unit_cv.sales_types.repurchase.eligible')
    },
    getProductCode() {
      return this.productInfo.sku || this.productInfo.code
    },
    getProductContext() {
      let descriptions = this.productInfo.description

      if (descriptions && descriptions.length) {
        let content = descriptions.find(context => context.language_id === (this.getSelectedLanguage.id || 1))
        content = content || descriptions[0]

        return [
          { title: this.$t('Eshop.Order.ProductDetail.ProductSpecification'), body: content.specification },
          { title: this.$t('Eshop.Order.ProductDetail.Description'), body: content.marketing_description },
          { title: this.$t('Eshop.Order.ProductDetail.Benefits'), body: content.benefits },
        ]
      }
      return []
    },
    getProductMeta() {
      let product_id = this.type === 'product' ? this.id : null
      let kitting_id = this.type === 'kitting' ? this.id : null

      return { product_id, kitting_id }
    },
    isAddingCart() {
      return this.addingCart
    },
  },
  async mounted() {
    let self = this
    this.$nextTick(async () => {
      await lottie.loadAnimation({
        container: this.$refs.loader,
        renderer: 'svg',
        loop: true,
        animationData: Loader,
      })
    })
    await this.resolveMasters
    let payload = {
      country_id: this.getAppLocationCountry.countryId,
      location_id: this.getAppLocationCountry.locationId,
      ...this.getProductMeta,
    }
    this.loadProductOrKittingDetails(payload).then(res => {
      self.productInfo = (res && res.details) || {}
    })
  },
  methods: {
    ...mapActions('eshop', ['loadProductOrKittingDetails']),
    async addToCart() {
      this.addingCart = true
      if (typeof window[AppSettings.productViewerApp.addToCartCallBack] === 'function') {
        let payload = {
          country_id: this.getAppLocationCountry.countryId,
          location_id: this.getAppLocationCountry.locationId,
          sales_type_id: this.repurchaseSalesTypeId,
          quantity: this.productQuantity,
          ...this.getProductMeta,
        }
        await window[AppSettings.productViewerApp.addToCartCallBack](payload)
      } else {
        this.$swal({
          type: 'error',
          titleText: this.$t('Eshop.AddCart.Error.Title'),
          text: this.$t('Common.Error.ActionFailure.HelpText'),
        })
      }
      this.addingCart = false
    },
  },
}
</script>
