<template>
  <div>
    <div v-if="isLoaded">
      <div v-if="getDetails === null" class="content-no-data">
        <div class="mt-3" v-if="!simple">
          <b-link class="product-title" @click="$router.go(-1)">
            {{ $t('Eshop.Order.ProductDetail.Home') }}
          </b-link>
        </div>
        <div class="vh-50 d-flex justify-content-center align-items-center" v-if="!isLoading('loadingCart')">
          <h2>{{ $t('Eshop.Order.ProductDetail.NoProductFound') }}</h2>
        </div>
      </div>
      <div v-else class="content-detail">
        <div class="eshop-products-wrapper">
          <div class="my-3" v-if="!simple">
            <span v-if="categories.length > 0" class="product-title">
              {{ $t('Eshop.Order.ProductDetail.Home') }}
            </span>
            <b-link v-else class="product-title" @click="$router.go(-1)">
              {{ $t('Eshop.Order.ProductDetail.Home') }}
            </b-link>
            <span class="text-success" v-for="(category, categoryIndex) in getCategories" :key="categoryIndex">
              >
              <b-link v-if="category.id !== undefined" class="product-title" @click="goToListing(category)">
                {{ category.name }}
              </b-link>
              <span v-else class="text-light">
                {{ category.name }}
              </span>
            </span>
          </div>
          <div class="eshop-products list mx-0">
            <div class="eshop-product-wrapper">
              <div
                class="eshop-product border-0"
                :class="{
                  'border-primary': getCartProductQuantity(product_id, kitting_id) !== 0,
                  'disabled-clear': isDisabled,
                  simple: simple,
                }"
              >
                <!--TODO: IMPLEMENT IN VERSION 2-->
                <!--<div class="product-like pos-absolute-tr" style="min-width: 40px; min-height: 40px;">-->
                <!--<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">
                  <img :src="getImage" />
                </div>
                <div
                  class="product-ribbon"
                  v-if="$helpers.getValue(getDetails, 'label')"
                  :style="`background-color:${getDetails.label.color_hex}`"
                >
                  {{ getDetails.label.name }}
                </div>
                <div class="product-content">
                  <div class="tags font-size-8">
                    <div
                      :class="[['tag', 'colored', 'upgrade'], { 'pos-absolute-br': isDisabled }]"
                      v-if="checkSalesType(baUpgradeSalesTypeId)"
                    >
                      {{ $t('Eshop.Product.Upgrade') }}
                    </div>
                    <div
                      :class="[['tag', 'colored', 'amp'], { 'pos-absolute-br': isDisabled }]"
                      v-if="checkSalesType(autoMaintenanceSalesTypeId)"
                    >
                      {{ $t('Eshop.Product.AMP') }}
                    </div>
                    <div
                      :class="[['tag', 'colored', 'fpp'], { 'pos-absolute-br': isDisabled }]"
                      v-if="checkSalesType(formationSalesTypeId)"
                    >
                      {{ $t('Eshop.Product.FPP') }}
                    </div>
                  </div>
                  <div class="font-weight-bold product-title">
                    {{ getDetails.name }}
                  </div>
                  <div class="tags font-size-8" v-if="!simple">
                    <div class="font-weight-bold tag cv" v-if="getCvBreakDown.eligible !== 0">
                      {{ $t('Eshop.Product.CV') }} {{ getCvBreakDown.eligible }}
                    </div>
                    <div
                      class="font-weight-bold tag amp"
                      v-if="
                        getCvBreakDown.amp !== 0 &&
                          (checkSalesType(autoMaintenanceSalesTypeId) || checkSalesType(formationSalesTypeId))
                      "
                    >
                      {{ $t('Common.Terminology.AmpCv') }} {{ getCvBreakDown.amp }}
                    </div>
                    <div
                      class="font-weight-bold tag upgrade"
                      v-if="
                        getCvBreakDown.welcome_pack !== 0 &&
                          (checkSalesType(baUpgradeSalesTypeId) || checkSalesType(formationSalesTypeId))
                      "
                    >
                      {{ $t('Common.Terminology.WpCv') }} {{ getCvBreakDown.welcome_pack }}
                    </div>
                    <div class="font-weight-bold tag upgrade mr-2" v-if="getCvBreakDown.upgrade !== 0">
                      {{ $t('Common.Terminology.RnkCv') }} {{ getCvBreakDown.upgrade }}
                    </div>
                    <div
                      class="font-weight-bold tag"
                      v-if="
                        getCvBreakDown.amp === 0 &&
                          getCvBreakDown.eligible === 0 &&
                          getCvBreakDown.upgrade === 0 &&
                          getCvBreakDown.welcome_pack === 0
                      "
                    >
                      &nbsp;
                    </div>
                  </div>
                  <div class="font-weight-bold" v-if="getCvBreakDown.amp === 0 && getCvBreakDown.base === 0">
                    &nbsp;
                  </div>
                  <div class="font-weight-bold product-code">
                    {{ getDetails.sku || getDetails.code }}
                  </div>
                  <div
                    class="font-weight-bold-extra product-price"
                    :class="{ 'text-danger': simple }"
                    v-if="!hasRentalPlan(getDetails)"
                  >
                    {{ currency }} {{ getPrice }}
                  </div>
                  <div class="cv" v-if="simple">
                    <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>
                  <div v-if="hasRentalPlan(getDetails)">
                    <div class="font-weight-bold-extra product-price" :class="{ 'text-danger': simple }">
                      {{ currency }} {{ getRentalPlanInfo(getDetails, 'initial_payment') }} ({{
                        $t('Eshop.Product.Initial')
                      }})
                    </div>
                    <div class="font-weight-bold-extra product-price mb-2" :class="{ 'text-danger': simple }">
                      {{ currency }} {{ getRentalPlanInfo(getDetails, 'monthly_repayment') }} x
                      {{ getRentalPlanInfo(getDetails, 'tenure') }} {{ $t('Eshop.Product.Tenure') }}
                    </div>
                  </div>
                  <!-- TODO: IMPLEMENT IN VERSION 2
                  <div class="product-rate">
                      <icon v-for="i in [1,2,3,4,5]" :key="i" :class="productStar(i)" name="star"/>
                  </div>
                  -->
                  <eshop-item-quantity
                    v-if="!($helpers.getValue(this.getDetails, 'label.allow_checkout', '') === false)"
                    class="pt-1"
                    :simple="simple"
                    :short-btn="shortBtn"
                    :product-quantity-getter="getCartProductQuantity"
                    :product-id="product_id"
                    :kitting-id="kitting_id"
                    :sales-type-id="sale_type_id"
                    :quantity="getCartProductQuantity(product_id, kitting_id)"
                    :is-adding="isLoading('productsAddingToCart-' + product_id + '-' + kitting_id)"
                    :process-cart-callback="addProductToCart"
                    :data-qa-prefix="`product-${(getDetails.sku || getDetails.code).toLowerCase()}`"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="bg-white my-4 p-4">
          <div v-if="productType === 'product'">
            <span class="text-primary font-weight-bold">
              {{ $t('Eshop.Order.ProductDetail.Benefits') }}
            </span>
            <p v-html="getDescriptionBenefits" />
            <br /><br />
            <span class="text-primary font-weight-bold">
              {{ $t('Eshop.Order.ProductDetail.ProductSpecification') }}
            </span>
            <p v-html="getDescriptionSpecifications" />
          </div>
          <div v-else>
            <span class="text-primary font-weight-bold">
              {{ $t('Eshop.Order.ProductDetail.Description') }}
            </span>
            <p v-html="getDescriptionMarketing" />
          </div>
        </div>
      </div>
      <!-- TODO: IMPLEMENT IN VERSION 2-->
      <!--<div class="bg-white my-4 p-4">-->
      <!--<related-product-list identifier="products"-->
      <!--:products-getter="getProducts"-->
      <!--:product-quantity-getter="getCartProductQuantity" />-->
      <!--</div>-->
    </div>
    <div v-else class="content-no-data">
      <div class="vh-50 d-flex justify-content-center align-items-center">
        <icon name="spinner" pulse class="icon-size-4" />
      </div>
    </div>
  </div>
</template>
<script>
/* eslint-disable vue/no-side-effects-in-computed-properties */
// TODO: Fix 'vue/no-side-effects-in-computed-properties' lint issue
import { mapGetters, mapActions } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import currencyMixin from '@/app/_global/mixins/currencyMixin'
import EshopItemQuantity from '@/app/_global/components/elements/EshopItemQuantity'
import _ from 'lodash'
import { ESHOP_LISTING } from '@/config/url-prefix'

export default {
  name: 'ProductDetail',
  mixins: [currencyMixin],
  components: { EshopItemQuantity },
  props: {
    pid: { type: String, default: '' },
    saleType: { type: String, default: '' },
    productType: { type: String, default: '' },
    simple: { type: Boolean, default: false },
    shortBtn: { type: Boolean, default: false },
    wpCv: { type: Number, default: 0 },
    salesTypes: { type: Array, default: () => [] },
  },
  data() {
    return {
      isLoaded: false,
      liked: false,
      sale_type_id: 0,
      product_id: null,
      kitting_id: null,
      categories: [],
    }
  },
  mounted() {
    if (this.pid !== null) {
      this.loadData()
    }
  },
  watch: {
    getShowProductDetailModal(to) {
      if (to === true) {
        this.loadData()
      }
    },
  },
  methods: {
    ...mapActions('eshop', [
      'loadCart',
      'addProductToCart',
      'loadProductOrKittingDetails',
      'productChangeCurrentCategory',
      'filterProductsSubCategory',
    ]),
    hasRentalPlan(detailData) {
      let v = false
      if (typeof detailData.rental_plan !== 'undefined') {
        if (detailData.rental_plan !== null && detailData.rental_plan.length > 0) {
          v = true
        }
      }
      return v
    },
    getRentalPlanInfo(product, key) {
      let value = ''
      if (typeof product.rental_plan !== 'undefined') {
        if (product.rental_plan !== null && product.rental_plan.length > 0) {
          value = product.rental_plan[0][key] + ''
        }
      }
      return value
    },
    async loadData() {
      this.isLoaded = false
      if (this.getAppStatus('enrolment') === true) {
        await this.loadCart({
          countryId: this.getEnrolmentRegion.id,
          locationId: this.getEnrolmentRegion.entity.locations[0].id,
        })
        if (this.productType === 'product') {
          this.product_id = parseInt(this.pid)
          await this.loadProductOrKittingDetails({
            product_id: this.product_id,
            country_id: this.getEnrolmentRegion.id,
            location_id: this.getEnrolmentRegion.entity.locations[0].id,
          })
        } else {
          this.kitting_id = parseInt(this.pid)
          await this.loadProductOrKittingDetails({
            kitting_id: this.kitting_id,
            country_id: this.getEnrolmentRegion.id,
            location_id: this.getEnrolmentRegion.entity.locations[0].id,
          })
        }
      } else {
        await this.loadCart()
        if (this.productType === 'product') {
          this.product_id = parseInt(this.pid)
          await this.loadProductOrKittingDetails({
            product_id: this.product_id,
            country_id: this.getSelectedCountry.id,
            location_id: this.getSelectedCountryLocation.id,
          }).then(() => {
            this.getCategoryParent(this.getDetails.categories)
          })
        } else {
          this.kitting_id = parseInt(this.pid)
          await this.loadProductOrKittingDetails({
            kitting_id: this.kitting_id,
            country_id: this.getSelectedCountry.id,
            location_id: this.getSelectedCountryLocation.id,
          }).then(() => {
            this.getCategoryParent(this.getDetails.kitting_products[0].product.category)
          })
        }
      }
      this.isLoaded = true
    },
    toggleLike() {
      this.liked = !this.liked
    },
    goToListing(category = null) {
      if (category !== null) {
        if (category.code.length > 3) {
          this.productChangeCurrentCategory(category.id)
        }
        if (category.code.length > 5) {
          this.filterProductsSubCategory([category.id])
        }
      }
      this.$router.push(ESHOP_LISTING)
    },
    getCategoryParent(categoryObject) {
      if (categoryObject.parent !== undefined && categoryObject.parent !== null) {
        if (categoryObject.parent.parent !== null) {
          this.categories.push(categoryObject.parent)
          this.getCategoryParent(categoryObject.parent)
        }
      }
    },
    setDefaultSaleType(types, keys) {
      let id = null
      if (keys !== undefined && keys.length > 0) {
        types.find(x => {
          if (x === this.getMasterDataIdByKeyAndTitle('sale_types', keys[0])) {
            id = x
          } else {
            if (x === this.getMasterDataIdByKeyAndTitle('sale_types', keys[1])) {
              id = x
            }
          }
        })
      }
      return id
    },
  },
  computed: {
    ...mapGetters([
      'isLoading',
      'getAppStatus',
      'getSelectedCountry',
      'getSelectedCountryLocation',
      'getMasterDataIdByKeyAndTitle',
      'getSelectedLanguage',
      'getEnrolmentRegion',
    ]),
    ...mapGetters('eshop', [
      'getProducts',
      'getCartProductQuantity',
      'getProductOrKittingDetails',
      'getCartProductEligibleSalesType',
      'getCartProductEligibleAsBaUpgrade',
      'getShowProductDetailModal',
    ]),
    ...mapGetters('enrolment', ['getEnrolmentLanguage']),
    ...mapMasterDataId({
      SALE_TYPES: {
        formationSalesTypeId: 'FORMATION',
        baUpgradeSalesTypeId: 'BA_UPGRADE',
        autoMaintenanceSalesTypeId: 'AUTO_MAINTENANCE',
        repurchaseSalesTypeId: 'RE_PURCHASE',
      },
    }),
    getDescriptionMarketing() {
      if (this.getDetails !== null) {
        if (this.getAppStatus('enrolment') === true) {
          let description = this.getDetails.description.find(
            data => data.language_id === JSON.parse(this.getEnrolmentLanguage).value
          )
          return typeof description !== 'undefined' ? description.marketing_description : ''
        } else {
          let description = this.getDetails.description.find(data => data.language_id === this.getSelectedLanguage.id)
          return typeof description !== 'undefined' ? description.marketing_description : ''
        }
      }
      return ''
    },
    getDescriptionBenefits() {
      if (this.getDetails !== null) {
        if (this.getAppStatus('enrolment') === true) {
          let description = this.getDetails.description.find(
            data => data.language_id === JSON.parse(this.getEnrolmentLanguage).value
          )
          return typeof description !== 'undefined' ? description.benefits : ''
        } else {
          let description = this.getDetails.description.find(data => data.language_id === this.getSelectedLanguage.id)
          return typeof description !== 'undefined' ? description.benefits : ''
        }
      }
      return ''
    },
    getDescriptionSpecifications() {
      if (this.getDetails !== null) {
        if (this.getAppStatus('enrolment') === true) {
          let description = this.getDetails.description.find(
            data => data.language_id === JSON.parse(this.getEnrolmentLanguage).value
          )
          return typeof description !== 'undefined' ? description.specification : ''
        } else {
          let description = this.getDetails.description.find(data => data.language_id === this.getSelectedLanguage.id)
          return typeof description !== 'undefined' ? description.specification : ''
        }
      }
      return ''
    },
    getImage() {
      let fullUrl = ''
      if (this.getDetails !== null) {
        let url = '/static/products/img-placeholder.svg'
        if (this.getDetails.images.list.length > 0) {
          let image = this.getDetails.images.list.find(img => img.default === 1)
          if (image) {
            url = image.image_link
          }
        }
        fullUrl = process.env.VUE_APP_HTTPS === 'true' ? url.replace('http:', 'https:') : url
      }
      return fullUrl
    },
    getDetails() {
      let detailData = this.getProductOrKittingDetails(this.product_id, this.kitting_id)
      if (detailData !== undefined) {
        let saleTypeId = this.getMasterDataIdByKeyAndTitle('sale_types', this.saleType)
        if (detailData.details.general.sale_types.find(type => type === saleTypeId) === undefined) {
          saleTypeId = this.setDefaultSaleType(detailData.details.general.sale_types, this.salesTypes)
        }
        this.sale_type_id = detailData.details.general.sale_types.find(type => type === saleTypeId)

        return detailData.details
      }
      return null
    },
    getCvBreakDown() {
      if (this.getDetails !== null && typeof this.getDetails.unit_cv !== 'undefined') {
        if (typeof this.getDetails.unit_cv.sales_types[this.saleType.toLowerCase()] !== 'undefined') {
          return this.getDetails.unit_cv.sales_types[this.saleType.toLowerCase()]
        }
      }
      return { amp: 0, base: 0, eligible: 0, upgrade: 0, welcome_pack: 0 }
    },
    getPrice() {
      if (this.getDetails !== null) {
        if (this.productType === 'product') {
          return this.$helpers.getValue(this.getDetails, 'base_price.gmp_price_tax', '0.00')
        } else {
          return this.$helpers.getValue(this.getDetails, 'kitting_price.gmp_price_tax', '0.00')
        }
      }
      return '0.00'
    },
    checkSalesType: vue => salesType => {
      let productCartEligibleSalesTypes = vue.getCartProductEligibleSalesType(vue.product_id, vue.kitting_id)
      if (productCartEligibleSalesTypes) {
        return (
          productCartEligibleSalesTypes.id === salesType &&
          vue.getDetails.general.sale_types.includes(salesType) &&
          vue.sale_type_id === salesType
        )
      } else {
        return vue.getDetails.general.sale_types.includes(salesType) && vue.sale_type_id === salesType
      }
    },
    isDisabled: vue => {
      let productCartEligibleSalesTypes = vue.getCartProductEligibleSalesType(vue.product_id, vue.kitting_id)
      return (
        typeof productCartEligibleSalesTypes !== 'undefined' &&
        productCartEligibleSalesTypes !== false &&
        vue.sale_type_id !== productCartEligibleSalesTypes.id
      )
    },
    getCategories() {
      if (this.getDetails !== null) {
        if (this.productType === 'product') {
          return _.union(_.orderBy(this.categories, 'code', 'asc'), [{ name: this.getDetails.categories.name }])
        } else {
          return _.union(_.orderBy(this.categories, 'code', 'asc'), [
            { name: this.getDetails.kitting_products[0].product.category.name },
          ])
        }
      }
      return []
    },
  },
}
</script>
