<template>
  <div class="content">
    <div class="d-flex justify-content-start align-items-center mt-3 pl-3">
      <h2>{{ $t('Esac.EsacVoucherRedemption.Title') }}</h2>
    </div>
    <div class="p-3">
      <div class="p-3 bg-white">
        <b-container fluid class="px-0">
          <b-row :no-gutters="true">
            <b-col cols="6">
              <div class="mx-2 mt-0 mb-2">
                <h6 class="mt-0 font-weight-normal">
                  {{ $t('Esac.EsacVoucherRedemption.SubTitle') }}
                </h6>
              </div>
            </b-col>
            <b-col cols="6">
              <div class="d-flex justify-content-end align-items-center">
                <b-btn
                  class="col-12 col-md-5 col-lg-3"
                  variant="primary"
                  @click="clickEsacProductSelectionRedeem"
                  :disabled="
                    getEsacTotalPurchaseQuantity === 0 || getEsacMinPurchaseAmount > getEsacTotalPurchaseAmount
                  "
                >
                  <icon class="text-center" name="spinner" pulse v-if="isLoading('esacSaleCreationDataLoading')" />
                  <span v-else
                    >({{ getEsacTotalPurchaseQuantity }}) {{ $t('Esac.EsacVoucherRedemption.Button.Continue') }}</span
                  >
                </b-btn>
              </div>
            </b-col>
          </b-row>
          <b-row :no-gutters="true" class="mb-2">
            <b-col cols="12" sm="12" md="6" lg="6" xl="6">
              <template v-for="(item, index) in getEsacVoucherData">
                <div
                  class="esac-selected-voucher"
                  v-if="item.visible"
                  @click="toggleEsacVoucherSelection({ id: item.id, sender: 'ProductSelection' })"
                  :key="index"
                >
                  <div class="esac-left-content">
                    <div class="esac-content-code">
                      {{ item.voucher_number }}
                    </div>
                    <div class="esac-content-value">{{ getEsacCurrencyCode }} {{ item.voucher_value }}</div>
                  </div>
                  <div class="esac-right-content">
                    <div class=" esac-content-active" v-if="item.selected">
                      <icon class="esac-icon" name="check" />
                    </div>
                    <div class="esac-content-inactive" v-if="!item.selected" />
                  </div>
                </div>
              </template>
            </b-col>
            <b-col cols="12" sm="12" md="6" lg="6" xl="6">
              <div class="esac-voucher-summary">
                <div class="esac-container">
                  <div class="esac-currency">
                    {{ getEsacCurrencyCode }}
                  </div>
                  <div class="esac-row">
                    <div class="esac-lable">
                      {{ $t('Esac.EsacVoucherRedemption.Section.VoucherSummary.OrderAmount') }}
                    </div>
                    <div class="esac-value">
                      {{ getEsacTotalPurchaseAmount.toFixed(2) }}
                    </div>
                  </div>
                  <div class="esac-row">
                    <div class="esac-lable">
                      {{ $t('Esac.EsacVoucherRedemption.Section.VoucherSummary.VoucherValue') }}
                    </div>
                    <div class="esac-value">
                      {{ getEsacTotalVoucherValue.toFixed(2) }}
                    </div>
                  </div>
                  <div class="esac-row">
                    <div class="esac-lable">
                      {{ $t('Esac.EsacVoucherRedemption.Section.VoucherSummary.Payable') }}
                    </div>
                    <div class="esac-value">
                      {{ getPayableAmount.toFixed(2) }}
                    </div>
                  </div>
                </div>
              </div>
            </b-col>
          </b-row>
        </b-container>
        <div class="d-flex justify-content-center align-items-center vh-50" v-if="isLoading('esacProductListLoading')">
          <icon class="icon-size-4" name="spinner" pulse />
        </div>
        <div v-else>
          <div v-if="getEntitledByProductCategory">
            <div
              class="d-flex flex-column-reverse flex-sm-row justify-content-start justify-content-sm-between align-items-start align-items-sm-center py-2"
            >
              <b-btn variant="primary" @click="clickEsacProductSelectionBrowseProduct">
                {{ $t('Esac.EsacVoucherRedemption.Button.BrowseProduct') }}
              </b-btn>
              <div class="text-danger font-italic my-2">
                {{ $t('Esac.EsacVoucherRedemption.Section.VoucherSummary.MinPurchaseAmount') }}
                {{ getEsacCurrencyCode }} {{ getEsacMinPurchaseAmount.toFixed(2) }}
              </div>
            </div>
          </div>
          <div v-else>
            <div
              class="d-flex flex-column flex-sm-row justify-content-start justify-content-sm-end align-items-start align-items-sm-center py-2"
              xv-else
            >
              <div class="text-danger font-italic mr-5">
                {{ $t('Esac.EsacVoucherRedemption.Section.VoucherSummary.MaxPurchaseQuantity') }}
                : {{ getEsacMaxPurchaseQuantity }}
              </div>
              <div class="text-danger font-italic">
                {{ $t('Esac.EsacVoucherRedemption.Section.VoucherSummary.MinPurchaseAmount') }}
                {{ getEsacCurrencyCode }} {{ getEsacMinPurchaseAmount.toFixed(2) }}
              </div>
            </div>
          </div>
          <table class="table d-none d-md-table">
            <thead>
              <tr>
                <th scope="col" class="text-left">
                  {{ $t('Common.Table.No') }}
                </th>
                <th scope="col" class="text-left">
                  &nbsp;
                </th>
                <th scope="col" class="text-left">
                  {{ $t('Common.ProductCode') }}
                </th>
                <th scope="col" class="text-left">
                  {{ $t('Common.Product.ProductName') }}
                </th>
                <th scope="col" class="text-left">
                  {{ $t('Common.Quantity') }}
                </th>
                <th scope="col" class="text-right">
                  {{ $t('Common.Sales.UnitPrice') }}<br />({{ getEsacCurrencyCode }})
                </th>
                <th scope="col" class="text-right">{{ $t('Common.TotalAmount') }}<br />({{ getEsacCurrencyCode }})</th>
              </tr>
            </thead>
            <tbody>
              <template v-for="(item, index) in getEsacProductData">
                <tr v-if="item.visible" :key="index">
                  <td class="text-left">
                    {{ getLineNumber(index) }}
                  </td>
                  <td class="text-left">
                    <div class="esac-product-image-container">
                      <img :src="getImage(item.item_image)" class="esac-product-image" />
                    </div>
                  </td>
                  <td class="text-left">
                    {{ item.item_code }}
                  </td>
                  <td class="text-left">
                    {{ item.item_name }}
                  </td>
                  <td class="text-left">
                    <eshop-item-quantity
                      :quantity="getItemPurchaseQuantity(item.item_type, item.item_id)"
                      :product-id="item.product_id"
                      :kitting-id="item.kitting_id"
                      :process-cart-callback="updateQuantityCallback"
                      :max="getBalanceQuantity(item)"
                      ref="eshopItemQuantity"
                      variant="side"
                      :data-qa-prefix="`product-${item.item_code}`"
                    />
                  </td>
                  <td class="text-right">
                    {{ item.item_price.toFixed(2) }}
                  </td>
                  <td class="text-right">
                    {{ item.amount.toFixed(2) }}
                  </td>
                </tr>
              </template>
            </tbody>
          </table>
          <div class="d-block d-md-none">
            <template v-for="(item, index) in getEsacProductData">
              <div class="row border-top py-4" v-if="item.visible" :key="index">
                <div class="col-3 col-md-2">
                  <div class="esac-product-image-container">
                    <img :src="getImage(item.item_image)" class="esac-product-image" />
                  </div>
                </div>
                <div class="col-9 col-md-10">
                  <h6 class="mt-0">
                    {{ item.item_name }}
                  </h6>
                  <h6 class="mt-0 text-light">
                    {{ item.item_code }}
                  </h6>
                  <h6 class="mt-0">{{ getEsacCurrencyCode }} {{ item.item_price.toFixed(2) }}</h6>
                  <div>
                    <eshop-item-quantity
                      :quantity="getItemPurchaseQuantity(item.item_type, item.item_id)"
                      :product-id="item.product_id"
                      :kitting-id="item.kitting_id"
                      :process-cart-callback="updateQuantityCallback"
                      :max="getBalanceQuantity(item)"
                      ref="eshopItemQuantity"
                      variant="side"
                      :data-qa-prefix="`product-${item.item_code}`"
                    />
                  </div>
                </div>
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
    <b-modal
      size="xl"
      body-class="esac-modal-body"
      centered
      :no-close-on-backdrop="true"
      :no-close-on-esc="false"
      :hide-header="true"
      :hide-footer="true"
      :hide-header-close="true"
      :hide-backdrop="false"
      :busy="true"
      :visible="getEsacProductSearchVisible"
    >
      <component :is="'ProductSearch'" />
    </b-modal>
  </div>
</template>
<script>
import EshopItemQuantity from '@/app/_global/components/elements/EshopItemQuantity'
import ProductSearch from './ProductSearch'
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'EsacRedemptionFormProductSelection',
  components: {
    ProductSearch,
    EshopItemQuantity,
  },
  data() {
    return {
      image: '/static/products/img-placeholder.svg',
    }
  },
  methods: {
    ...mapActions([
      'toggleEsacVoucherSelection',
      'updateEsacPurchaseQuantity',
      'clickEsacProductSelectionBrowseProduct',
      'clickEsacProductSelectionBack',
      'clickEsacProductSelectionRedeem',
    ]),
    getImage(productImage) {
      if (
        typeof productImage === 'undefined' ||
        productImage === null ||
        productImage === '' ||
        productImage.length === 0
      ) {
        return this.image
      }
      return productImage
    },
    updateQuantityCallback(payload) {
      let item = this.getEsacProductData.find(product => {
        return (
          (payload.product_id && product.product_id === payload.product_id) ||
          (payload.kitting_id && product.kitting_id === payload.kitting_id)
        )
      })
      this.updateEsacPurchaseQuantity({
        item_type: item.item_type,
        item_id: item.item_id,
        update_type: (payload.quantity > item.quantity && '+') || (payload.quantity < item.quantity && '-') || '',
        update_value: 1,
      })
    },
  },
  computed: {
    ...mapGetters(['isLoading']),
    ...mapGetters([
      'getEsacVoucherData',
      'getEsacProductData',
      'getEntitledByProductCategory',
      'getEsacMaxPurchaseQuantity',
      'getEsacMinPurchaseAmount',
      'getEsacTotalVoucherValue',
      'getEsacTotalPurchaseQuantity',
      'getEsacTotalPurchaseAmount',
      'getEsacProductSearchVisible',
      'getEsacCurrencyCode',
    ]),
    getPayableAmount: vue => {
      let payableAmount = vue.getEsacTotalPurchaseAmount - vue.getEsacTotalVoucherValue
      if (payableAmount < 0) {
        payableAmount = 0
      }
      return payableAmount
    },
    getBalanceQuantity: vue => item => {
      let totalSelectableQuantity = vue.getEsacMaxPurchaseQuantity
      if (totalSelectableQuantity <= 0) {
        return undefined
      } else {
        let totalSelectedQuantity = vue.getEsacTotalPurchaseQuantity
        totalSelectableQuantity = totalSelectableQuantity + item.quantity
        return totalSelectableQuantity - totalSelectedQuantity
      }
    },
    getItemPurchaseQuantity: vue => (itemType, itemId) => {
      let productData = JSON.parse(JSON.stringify(vue.getEsacProductData))
      let product = productData.find(item => item.item_type === itemType && item.item_id === itemId)
      if (typeof product !== 'undefined' && product !== null) {
        return product.quantity
      } else {
        return 0
      }
    },
    getLineNumber: vue => index => {
      let productData = JSON.parse(JSON.stringify(vue.getEsacProductData))
      let lineNumber = 0
      for (var i = 0; i <= index; i++) {
        if (productData[i].visible) {
          lineNumber++
        }
      }
      return lineNumber
    },
  },
}
</script>
