<template>
  <div>
    <div
      class="nh-75 no-overflow d-flex flex-column justify-content-between align-items-stretch align-content-stretch eshop"
    >
      <div class="no-flex-grow">
        <b-container fluid class="px-0">
          <b-row>
            <b-col cols="12" sm="6" lg="3" class="text-left pr-3 pr-sm-0 pb-3 pb-lg-0">
              <b-input-group>
                <b-form-input v-model="productSearch.codeName" :placeholder="$t('Common.Product.SearchProduct')" />
                <b-input-group-append>
                  <div class="d-flex justify-content-between">
                    <b-btn
                      variant="primary"
                      class="bg-transparent text-success border-light rounded-0"
                      @click="resetSearch"
                      :class="{ 'd-none': productSearch.codeName === '' }"
                    >
                      <icon name="clear-icon" />
                    </b-btn>
                    <b-btn
                      variant="primary"
                      class="bg-transparent text-success border-light rounded-0"
                      @click="clickEsacProductSearchSearch(productSearch), handlePaginationChange(1)"
                      :disable="productSearch.codeName === ''"
                    >
                      <icon name="search" />
                    </b-btn>
                  </div>
                </b-input-group-append>
              </b-input-group>
            </b-col>
            <b-col cols="12" sm="6" lg="3" class="text-left pb-3 pb-lg-0">
              <b-form-select
                :options="getEsacProductCategoryData.options"
                v-model="productSearch.category"
                @input="clickEsacProductSearchSearch(productSearch), handlePaginationChange(1)"
              />
            </b-col>
            <b-col cols="12" lg="6" class="text-right">
              <div class="d-inline-block font-italic text-danger pb-2">
                {{ $t('Esac.EsacVoucherRedemption.Section.VoucherSummary.MinPurchaseAmount') }}
                {{ getEsacCurrencyCode }} {{ getEsacMinPurchaseAmount.toFixed(2) }}
              </div>
              <div class="d-block d-sm-inline-block ml-3">
                <b-btn
                  class="px-3 mr-3"
                  variant="outline-medium"
                  @click="clickEsacProductSearchCancel"
                  :disable="isLoading('esacProductSearchUpdate')"
                >
                  {{ $t('Esac.EsacVoucherRedemption.Button.Cancel') }}
                </b-btn>
                <b-btn
                  class="px-3"
                  variant="primary"
                  @click="clickEsacProductSearchNext"
                  :disabled="getEsacTotalSearchQuantity === 0 || isLoading('esacProductSearchUpdate')"
                >
                  ({{ getEsacTotalSearchQuantity }}) {{ $t('Esac.EsacVoucherRedemption.Button.Continue') }}
                </b-btn>
              </div>
            </b-col>
          </b-row>
          <hr />
        </b-container>
      </div>
      <div class="no-overflow overflow-y-auto flex-grow-1">
        <div class="d-flex justify-content-center align-items-center" v-if="isLoading('esacProductSearchUpdate')">
          <icon class="icon-size-4" name="spinner" pulse />
        </div>
        <div class="w-100" v-else>
          <table class="table d-none d-md-table">
            <thead>
              <tr>
                <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-left">
                  {{ $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.searchedPaging" :key="index">
                  <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="getItemSearchQuantity(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.searchAmount.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.searchedPaging" :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="getItemSearchQuantity(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 class="no-flex-grow pt-2" v-if="getEsacProductSearchTotalItem > getEsacProductSearchPaginationSize">
        <b-pagination
          align="center"
          :total-rows="getEsacProductSearchTotalItem"
          v-model="productSearch.currentPage"
          @change="handlePaginationChange"
          :per-page="getEsacProductSearchPaginationSize"
        />
      </div>
    </div>
  </div>
</template>
<script>
import EshopItemQuantity from '@/app/_global/components/elements/EshopItemQuantity'
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'EsacRedemptionFormProductSearch',
  components: {
    EshopItemQuantity,
  },
  data() {
    return {
      image: '/static/products/img-placeholder.svg',
      productSearch: {
        codeName: '',
        category: null,
        currentPage: 1,
      },
    }
  },
  mounted() {
    let esacVouchers = []
    this.getEsacVoucherData.forEach(item => {
      if (item.selected) {
        esacVouchers.push(item.id)
      }
    })
    this.handlePaginationChange(1)
  },
  methods: {
    ...mapActions([
      'clickEsacProductSearchSearch',
      'updateEsacProductSearchQuantity',
      'updateEsacProductSearchPaging',
      'clickEsacProductSearchNext',
      'clickEsacProductSearchCancel',
    ]),
    getImage(productImage) {
      if (
        typeof productImage === 'undefined' ||
        productImage === null ||
        productImage === '' ||
        productImage.length === 0
      ) {
        return this.image
      }
      return productImage
    },
    handlePaginationChange(page) {
      this.productSearch.currentPage = page
      this.updateEsacProductSearchPaging({ currentPage: page })
    },
    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.updateEsacProductSearchQuantity({
        item_type: item.item_type,
        item_id: item.item_id,
        update_type:
          (payload.quantity > item.searchQuantity && '+') || (payload.quantity < item.searchQuantity && '-') || '',
        update_value: 1,
      })
    },
    resetSearch() {
      this.productSearch = { codeName: '', category: null, currentPage: 1 }
      this.clickEsacProductSearchSearch(this.productSearch)
      this.handlePaginationChange(1)
    },
  },
  computed: {
    ...mapGetters(['isLoading']),
    ...mapGetters([
      'getEsacVoucherData',
      'getEsacProductCategoryData',
      'getEsacProductData',
      'getEsacMaxPurchaseQuantity',
      'getEsacMinPurchaseAmount',
      'getEsacTotalVoucherValue',
      'getEsacTotalPurchaseQuantity',
      'getEsacProductSearchVisible',
      'getEsacTotalSearchQuantity',
      'getEsacProductSearchTotalItem',
      'getEsacProductSearchPaginationSize',
      'getEsacCurrencyCode',
    ]),
    getItemSearchQuantity: 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.searchQuantity
      } else {
        return 0
      }
    },
    getBalanceQuantity: vue => item => {
      let totalSelectableQuantity = vue.getEsacMaxPurchaseQuantity
      if (totalSelectableQuantity <= 0) {
        return undefined
      } else {
        return totalSelectableQuantity
      }
    },
  },
}
</script>
