<template>
  <div>
    <h4>{{ $t('OrderHistory.Detail.eVoucher.Title') }}</h4>
    <div
      v-if="isLoading(['salesDetailsLoading', 'evoucherLoading'])"
      class="vh-50 d-flex justify-content-center align-items-center"
    >
      <icon name="spinner" pulse class="px-3 text-center icon-size-5 py-3" />
    </div>
    <div v-else class="dashboard-panel-element rounded-0 mt-4">
      <div class="row justify-content-between border-bottom py-3 px-1">
        <div class="col">
          <b-btn
            variant="link"
            class="px-0"
            @click="$router.go(-1)"
            :title="$t('OrderHistory.Detail.eVoucher.BackToOrderHistory')"
          >
            <icon class="text-primary icon-size-3 p-0" name="back-icon" />
          </b-btn>
          <b-link @click="$router.go(-1)" :title="$t('OrderHistory.Detail.eVoucher.BackToOrderHistory')">
            <span class="text-dark"> {{ $t('OrderHistory.Detail.eVoucher.TaxInvoiceNo') }} {{ invoiceNo }} </span>
          </b-link>
        </div>
        <div class="col">
          <div class="row justify-content-end mr-2">
            <b-btn variant="primary" class="d-none" ref="activation" v-b-modal.evoucher_activation>
              {{ $t('OrderHistory.Detail.eVoucher.ActivateNow') }}
            </b-btn>
          </div>
        </div>
      </div>
      <div class="px-4 py-3">
        <b-form-checkbox-group v-model="selected">
          <div v-for="(voucher, idx) in evouchers" :key="idx">
            <div class="row small border border-bottom-0 justify-content-between align-items-center mt-4 py-1">
              <div class="col py-2 line-height-1.5">
                <span class="">
                  {{ $t('OrderHistory.Detail.eVoucher.eVoucherNo') }}
                </span>
                <span class="font-weight-bold"> {{ voucher.evoucher_number }} </span><br />
                <span class="font-weight-bold">
                  {{ voucher.product_name }}
                </span>
              </div>
              <div v-if="voucher.activation.is_activated === 0" class="col text-right font-weight-bold text-primary">
                <b-check class="text-nowrap text-uppercase" :true-value="voucher.evoucher_number" :value="voucher">
                  {{ $t('OrderHistory.Detail.eVoucher.ActivateNow') }}
                </b-check>
              </div>
              <div v-else class="col text-right">
                <div v-if="voucher.redemption.is_redeemed === 1">
                  <b-btn variant="primary" @click="getReceipt(voucher.id)">
                    {{ $t('OrderHistory.Detail.eVoucher.RedemptionReceipt') }}
                  </b-btn>
                </div>
                <div v-else>
                  <b-row class="align-items-center justify-content-end">
                    <b-col class="col-9">
                      <div class="text-light">
                        {{ $t('OrderHistory.Detail.eVoucher.PleaseComplete') }}
                      </div>
                      <div class="text-info font-weight-bold">
                        {{
                          $t('OrderHistory.Detail.eVoucher.ActivatedOn', {
                            date: getActivationDate(voucher),
                            ibo: iboId,
                          })
                        }}
                      </div>
                    </b-col>
                    <b-col class="col-auto">
                      <b-btn
                        v-if="isAllSizesSelected(voucher.id)"
                        variant="primary"
                        ref="redeem"
                        @click="showRedemptionModal(voucher)"
                      >
                        {{ $t('Common.Redeem') }}
                      </b-btn>
                      <b-btn v-else variant="light text-white">
                        {{ $t('Common.Redeem') }}
                      </b-btn>
                    </b-col>
                  </b-row>
                </div>
              </div>
            </div>
            <div class="row border bg-light-extra px-3 py-1">
              <div class="row w-100 py-1 small">
                <div class="col-4 col-lg-2 col-sm-2">
                  {{ $t('Common.ProductCode') }}
                </div>
                <div class="col-4">
                  {{ $t('OrderHistory.Detail.TableHeader.ProductDescription') }}
                </div>
                <div v-if="voucher.activation.is_activated === 1" class="col-3 col-md-4">
                  {{ $t('OrderHistory.Detail.eVoucher.Details') }}
                </div>
                <div v-if="voucher.redemption.is_redeemed === 1" class="col-2 col-md-2 d-none d-md-block">
                  {{ $t('OrderHistory.Detail.eVoucher.DeliveryStage') }}
                </div>
              </div>
              <div
                class="row w-100 py-1 small font-weight-bold"
                v-for="(product, index) in getProducts(voucher)"
                :key="index"
              >
                <div class="col-4 col-lg-2 col-sm-2 pt-2">
                  {{ product.product.sku }}
                </div>
                <div class="col-4 pt-2">
                  {{ product.product.name }}
                  <span v-if="product.foc_qty > 0"> ({{ $t('Eshop.Order.FocPwp.FOC') }}) </span>
                </div>
                <div v-if="voucher.activation.is_activated === 1" class="col-3 col-md-4">
                  <div v-if="voucher.redemption.is_redeemed === 0">
                    <b-btn
                      v-if="product.dummy !== null && product.selectable === true"
                      variant="primary"
                      size="sm"
                      class="px-1"
                      :title="$t('OrderHistory.Detail.eVoucher.SelectSize.SelectSizeToRedeem')"
                      @click="openModal(idx, index)"
                    >
                      {{ $t('OrderHistory.Detail.eVoucher.SelectSize') }}
                    </b-btn>
                    <span class="text-nowrap">
                      <b-btn
                        v-if="voucher.redemption.is_redeemed === 0 && getSelectedSizeName(voucher, product) !== ''"
                        class="px-0"
                        variant="link"
                        @click="removeSizes(voucher, product)"
                      >
                        <icon name="remove-icon" class="text-dark icon-size-3 align-middle" />
                      </b-btn>
                      <span class="font-weight-bold align-text-bottom">
                        {{ getSelectedSizeName(voucher, product) }}
                      </span>
                    </span>
                  </div>
                  <div v-else>
                    <div class="font-weight-bold pt-2">
                      {{ getSelectedSizeName(voucher, product) }}
                    </div>
                  </div>
                </div>
                <div v-if="voucher.redemption.is_redeemed === 1" class="col-2 col-md-2 pt-2 d-none d-md-block">
                  {{ $t('OrderHistory.Detail.eVoucher.Processing') }}
                </div>
                <order-history-evoucher-sizing
                  v-if="product.dummy !== null"
                  :evoucher="voucher"
                  :product="product"
                  :identifier="`productSelection${idx}${index}`"
                  @change="saveChanges(voucher.evoucher_number)"
                  :selected-sizes="selectedSizes(product.product.id, null)"
                  ref="productSizeSelection"
                />
              </div>
            </div>
          </div>
        </b-form-checkbox-group>
      </div>
    </div>
    <order-history-evoucher-activation
      :selected="selected"
      :invoice-no="invoiceNo"
      :sale-id="saleId"
      :ibo-id="iboId"
      @change="reloadVouchers"
    />
    <order-history-evoucher-redemption :member-data="getMyAccountMemberDetails" @change="reloadVouchers" />
    <!--TODO: IMPLEMENT IN VERSION 2-->
    <pdf-viewer-modal
      ref="pdf"
      :title="$t('OrderHistory.Detail.eVoucher.RedemptionReceipt')"
      :pdf-link="redemptionPdf"
    ></pdf-viewer-modal>
    <!--<order-history-evoucher-installation :evoucher="getSelectedVoucher" :product="getSelectedProduct" :preferredEmailId="preferredEmailId"/>-->
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import orderHistoryEvoucherActivation from './OrderHistoryEvoucherActivation'
import orderHistoryEvoucherSizing from './OrderHistoryEvoucherSizing'
import orderHistoryEvoucherRedemption from './OrderHistoryEvoucherShipping'
import pdfViewerModal from '@/app/_global/components/elements/pdfViewerModal'
import moment from 'moment'
import _ from 'lodash'

export default {
  name: 'OrderHistoryEvoucher',
  components: {
    pdfViewerModal,
    orderHistoryEvoucherActivation,
    orderHistoryEvoucherSizing,
    orderHistoryEvoucherRedemption,
  },
  inject: ['$validator'],
  props: {
    saleId: { type: String, required: true },
  },
  data() {
    return {
      evouchers: null,
      iboId: '',
      selected: [],
      invoiceNo: '',
      redemptionPdf: '',
      voucherToRedeem: [],
      selectedDummies: {
        sizes: [],
        evoucher: [],
      },
    }
  },
  watch: {
    selected(checkedVoucher) {
      let button = this.$refs.activation
      if (checkedVoucher.length === 0) {
        button.classList.add('d-none')
      } else {
        button.classList.remove('d-none')
      }
    },
  },
  computed: {
    ...mapGetters([
      'getErrors',
      'isLoading',
      'getSaleEvouchers',
      'getRedemptionReceipt',
      'getSalesDetails',
      'getCurrentSaleId',
      'getMyAccountMemberDetails',
    ]),
    ...mapGetters('orderhistory', [
      'getSalesVoucherActivationStatus',
      'getSalesVoucherRedemptionStatus',
      'getSelectedVoucher',
      'getSelectedProduct',
      'getAllSelectedDummies',
    ]),
  },
  async mounted() {
    this.selectEvoucherProductsSizes({
      sizes: [],
      evoucher: [],
    })
    this.evouchers = this.getSaleEvouchers
    if (this.evouchers.length === 0) {
      await this.loadSalesDetailsData({ saleId: parseInt(this.saleId) })
      await this.loadEvoucherBySale().then(() => {
        this.evouchers = this.getSaleEvouchers
      })
    }
    this.iboId = this.$helpers.getValue(this.evouchers[0], 'ibo_member_id', '')
    this.invoiceNo = this.$helpers.getValue(this.evouchers[0], 'invoice_number', '')
    this.isAllSizesSelected()
  },

  methods: {
    ...mapActions(['loadRedemptionReceipt', 'loadSalesDetailsData', 'loadEvoucherBySale']),
    ...mapActions('orderhistory', [
      'setSelectedProduct',
      'setSelectedVoucher',
      'setShowRedemptionModal',
      'selectEvoucherProductsSizes',
    ]),
    getActivationDate(voucher) {
      return moment(voucher.activation.activation_date).format('DD/MM/YYYY') || ''
    },
    selectedSizes(productId, kittingId) {
      let selectedSizes = []
      if (this.$helpers.isSet(this.getAllSelectedDummies, 'sizes')) {
        selectedSizes =
          this.getAllSelectedDummies['sizes'].filter(size => {
            return (
              (size.kitting_id !== null && size.kitting_id !== null && size.kitting_id === kittingId) ||
              (size.product_id !== null && size.product_id !== null && size.product_id === productId)
            )
          }) || []
      }
      return selectedSizes
    },
    validate() {
      this.$refs.productSizeSelection.forEach(product => {
        if (typeof product.validate === 'function') {
          this.errors.items = product.validate().items
        }
      })
      if (this.errors.items.length === 0) {
        this.logError({ cartError: '' })
        this.saveChanges()
        return true
      } else {
        this.$scrollTo('[data-vv-scope="' + this.errors.items[0].scope + '"]', { offset: -100 })
        this.logError({ cartError: this.errors.first('cartError') })
        return false
      }
    },
    saveChanges(voucherNo) {
      let self = this
      let productSelectionComponent = this.$refs.productSizeSelection
      if (voucherNo) {
        productSelectionComponent = this.$refs.productSizeSelection.filter(
          element => element.evoucher.evoucher_number === voucherNo
        )
      }
      self.selectedDummies = _.cloneDeep(self.selectedDummies)
      self.selectedDummies.evoucher = []
      productSelectionComponent.forEach(product => {
        if (product.evoucher.activation.is_activated === 1) {
          if (typeof product.getSelectedDummies === 'function') {
            let dummySelection = _.cloneDeep(product.getSelectedDummies())

            let similarSizesItemIndex = -1
            if (dummySelection.sizes.length > 0) {
              similarSizesItemIndex = self.selectedDummies.sizes.findIndex(
                x =>
                  x.product_id === dummySelection.sizes[0].product_id &&
                  x.kitting_id === dummySelection.sizes[0].kitting_id
              )
            }

            if (similarSizesItemIndex !== -1) {
              self.selectedDummies.sizes[similarSizesItemIndex] = dummySelection.sizes[0]
            } else {
              self.selectedDummies.sizes = _.union(self.selectedDummies.sizes, dummySelection.sizes)
            }

            if (dummySelection.evoucher.length > 0) {
              self.selectedDummies.evoucher.push(dummySelection.evoucher[0])
            }
          }
        }
      })
      this.selectEvoucherProductsSizes(self.selectedDummies)
    },
    reloadVouchers() {
      this.evouchers = this.getSaleEvouchers
    },
    getSelectedSizeName(voucher, product) {
      let result = []
      if (voucher.redemption.is_redeemed === 0) {
        this.getAllSelectedDummies.sizes.forEach(sizes => {
          if (sizes.voucher_id === voucher.id && sizes.product_id === product.product_id) {
            sizes.data.forEach(size => {
              if (
                size.quantity > 0 &&
                product.dummy.dummy_products.find(product => product.id === size.product_id) !== undefined
              ) {
                let productName = product.dummy.dummy_products.find(product => product.id === size.product_id).name
                if (productName.substr(product.product.name.length + 1) !== '') {
                  productName = productName.substr(product.product.name.length + 1)
                }
                result.push(productName)
              }
            })
          }
        })
      } else {
        if (voucher.sales_exchange !== null) {
          if (voucher.sales_exchange.exchange_kitting.length > 0) {
            if (
              voucher.sales_exchange.exchange_kitting[0].kitting_products.find(
                prod => prod.dummy.dmy_code === product.dummy.dmy_code
              ) !== undefined
            ) {
              result.push(
                voucher.sales_exchange.exchange_kitting[0].kitting_products.find(
                  prod => prod.dummy.dmy_code === product.dummy.dmy_code
                ).product.name
              )
            }
          } else {
            //exchange_products
            if (
              voucher.sales_exchange.exchange_products.find(prod => prod.dummy.dmy_code === product.dummy.dmy_code) !==
              undefined
            ) {
              result.push(
                voucher.sales_exchange.exchange_products.find(prod => prod.dummy.dmy_code === product.dummy.dmy_code)
                  .name
              )
            }
          }
        }
      }
      return result.join()
    },
    removeSizes(voucher, product) {
      let selectedDummies = _.cloneDeep(this.getAllSelectedDummies)
      selectedDummies.evoucher = selectedDummies.evoucher.filter(
        size =>
          !(
            size.voucher_id === voucher.id &&
            size.product_id === product.product_id &&
            size.kitting_id === product.kitting_id
          )
      )
      selectedDummies.sizes = selectedDummies.sizes.filter(
        size => !(size.voucher_id === voucher.id && size.product_id === product.product_id)
      )
      this.selectEvoucherProductsSizes(selectedDummies)
    },
    getProducts(voucher) {
      let result = []
      if (this.getSalesDetails !== undefined && this.getSalesDetails !== null) {
        this.getSalesDetails.products.forEach(product => {
          if (product.evoucher !== null && product.evoucher.id === voucher.id) {
            result.push({ ...product, product: product })
          }
        })
        this.getSalesDetails.kittings.forEach(kitting => {
          if (kitting.evoucher !== null && kitting.evoucher.id === voucher.id) {
            kitting.kitting_products.forEach(product => {
              if (product.dummy !== null) {
                result.push(product)
              }
            })
          }
        })
      }
      if (result.length === 0) {
        result.push({
          product: { sku: '', name: '' },
          dummy: { dummy_products: [] },
          quantity: 0,
        })
      }
      return result
    },
    isAllSizesSelected(evoucherId) {
      if (this.evouchers !== null) {
        let products = []
        let selectedSizes = []
        this.getAllSelectedDummies.sizes.forEach(sizes => {
          if (sizes.voucher_id === evoucherId) {
            if (sizes.data.find(size => size.quantity > 0) !== undefined) {
              selectedSizes.push(sizes.product_id)
            }
          }
        })
        this.evouchers.forEach(evoucher => {
          if (evoucher.id === evoucherId) {
            this.getSalesDetails.products.forEach(product => {
              if (product.evoucher !== null && product.evoucher.id === evoucherId) {
                if (product.dummy !== null) {
                  products.push(product.id)
                }
              }
            })
            this.getSalesDetails.kittings.forEach(kitting => {
              if (kitting.evoucher !== null && kitting.evoucher.id === evoucherId) {
                kitting.kitting_products.forEach(product => {
                  if (product.dummy !== null) {
                    products.push(product.id)
                  }
                })
              }
            })
          }
        })
        return products.length === selectedSizes.length
      }
      return false
    },
    showRedemptionModal(voucher) {
      this.setSelectedVoucher(voucher)
      this.setShowRedemptionModal(true)
    },
    getReceipt(voucherId) {
      this.redemptionPdf = ''
      this.loadRedemptionReceipt(voucherId).then(() => {
        if (!this.getErrors('redemptionReceipt')) {
          this.redemptionPdf = this.getRedemptionReceipt.download_link
          this.$refs.pdf.show()
        }
      })
    },
    openModal(id, index) {
      this.errors.items = []
      this.$bvModal.show(`productSelection${id}${index}`)
    },
  },
}
</script>
