<template>
  <div>
    <div>
      <b-container class="font-size-7 bg-white border">
        <b-row class="align-items-stretch mb-4 m-0">
          <b-col cols="auto" class="bg-primary p-1">
            <icon name="eshop-review" class="icon-size-4 text-white" />
          </b-col>
          <b-col class="text-primary font-size-5 d-flex align-items-center">
            <div>{{ $t('Common.Sales.OrderSummary') }}</div>
          </b-col>
        </b-row>

        <div v-if="showPayCycle && payCycle">
          <b-row class="font-weight-bold">
            <b-col colas="auto">{{ $t('Common.Terminology.PayCycle') }}</b-col>
            <b-col class="text-right">{{ payCycle }}</b-col>
          </b-row>
          <hr class="mt-3 mb-2" />
        </div>

        <div v-if="summaryRedeem.length">
          <div class="font-weight-bolder">{{ $t('Itoken.Title') }}</div>
          <b-row v-for="(item, idx) in summaryRedeem" :key="`r${idx}`" class="pt-1 font-weight-bold">
            <b-col class="col-8 col-md-8 text-capitalize">
              {{ item.label }}
            </b-col>
            <b-col class="col-4 col-md-4 text-right">
              {{ item.value }}
            </b-col>
          </b-row>
          <hr class="mt-3 mb-2" />
        </div>

        <div>
          <b-row
            v-for="(item, idx) in summaryCount"
            :key="'c' + idx"
            class="pt-1 font-weight-bold animated"
            :class="{ flash: changedCountIndexes.includes(idx) }"
          >
            <b-col class="col-8 col-md-8">
              {{ item.label }}
            </b-col>
            <b-col class="col-4 col-md-4 text-right">
              {{ item.value }}
            </b-col>
          </b-row>
          <hr class="mt-3 mb-2" />
        </div>

        <div>
          <b-row>
            <b-col class="text-right font-weight-bold">
              {{ currencySymbol }}
            </b-col>
          </b-row>
          <b-row
            v-for="(item, idx) in summaryAmount"
            :key="'a' + idx"
            class="pt-1 font-weight-bold animated"
            :class="{ flash: changedAmountIndexes.includes(idx) }"
          >
            <b-col class="col-8 col-md-8">
              {{ item.label }}
            </b-col>
            <b-col class="col-4 col-md-4 text-right">
              {{ $helpers.getCurrencyValue(item.value) }}
            </b-col>
          </b-row>
          <hr class="mt-3 mb-2" />
        </div>

        <b-row>
          <b-col offset="9" class="text-right">
            <strong>{{ currencySymbol }}</strong>
          </b-col>
        </b-row>
        <b-row
          class="font-weight-bold-extra border-double-bottom pb-2 mb-2 animated"
          no-gutters
          :class="{ flash: flashGrandTotal }"
        >
          <b-col cols="9" class="pr-0">
            {{ $t('Common.Sales.GrandTotalWithGst') }}
          </b-col>
          <b-col class="text-right">
            {{ $helpers.getCurrencyValue(grandTotal) }}
          </b-col>
        </b-row>
        <div v-if="showContinueButton">
          <b-container fluid>
            <b-row>
              <b-col class="mt-2 mb-3 p-0">
                <button
                  class="btn btn-continue rounded-0 py-2"
                  :disabled="
                    continueDisabled ||
                      isLoading(['loadingCart', 'locationsLoadStockistLocations', 'loadStockistLocationAddressList'])
                  "
                  @click="emitAndContinueAction"
                  data-qa="continue-btn"
                >
                  <icon
                    name="spinner"
                    pulse
                    class="text-white icon-size-2"
                    v-if="
                      continueDisabled ||
                        isLoading([
                          'loadingCart',
                          'locationsLoadStockistLocations',
                          'loadStockistLocationAddressList',
                          'settingEsacSalesCreationData',
                        ])
                    "
                  />
                  <span v-else>
                    {{ continueText }}
                  </span>
                </button>
              </b-col>
            </b-row>
          </b-container>
        </div>
      </b-container>
      <b-container v-if="showPromoCode" class="bg-white mt-3 border">
        <b-row no-gutters class="py-3">
          <b-col class="mr-3">
            <b-form-input
              v-model="localPromoCode"
              v-validate="'required'"
              :class="{ input: true, 'is-danger': errors.has('promocode') }"
              name="promocode"
              size="sm"
              class="placeholder-light promo"
              :placeholder="$t('Eshop.Order.GlobalWords.InsertPromoCodeHere')"
            />
          </b-col>
          <b-col cols="auto">
            <b-button
              @click="applyPromoCode"
              class="font-size-7 text-white"
              :variant="$appSettings.evo.enable ? 'primary' : 'success'"
            >
              {{ $t('Common.Apply') }}
            </b-button>
          </b-col>
        </b-row>
      </b-container>
    </div>
  </div>
</template>
<script>
import _ from 'lodash'
import { mapGetters } from 'vuex'

export default {
  name: 'OrderSummary',
  $_veeValidate: {
    validator: 'new',
  },
  data() {
    return {
      changedAmountIndexes: [],
      changedCountIndexes: [],
      flashGrandTotal: false,
      localPromoCode: '',
    }
  },
  props: {
    summaryRedeem: { type: Array, default: () => [] },
    summaryCount: { type: Array, required: true },
    summaryAmount: { type: Array, required: true },
    showEwallet: { type: Boolean, default: false },
    ewalletAmount: { type: Number, default: 0 },
    grandTotal: { type: [Number, String], required: true },
    showContinueButton: { type: Boolean, required: true },
    continueAction: {
      type: Function,
      default() {
        return () => {}
      },
      required: false,
    },
    continueText: { type: String, required: false },
    continueDisabled: { type: Boolean, default: false },
    showPromoCode: { type: Boolean, default: false },
    promoCode: { type: String, required: false },
    applyPromoCode: { type: Function, required: false },
    currencySymbol: { type: String, required: true },
    showPayCycle: { type: Boolean, default: false },
    payCycle: { type: String, default: '' },
  },
  mounted() {
    this.localPromoCode = this.promoCode
  },
  methods: {
    emitAndContinueAction() {
      this.$emit('continueAction')
      this.continueAction()
    },
    getDifferenceIndex(to, from) {
      var toValue = _.map(to, (object, key) => key + '-' + object.value)
      var fromValue = _.map(from, (object, key) => key + '-' + object.value)
      return _.map(_.difference(toValue, fromValue), i => parseInt(i.split('-')[0]))
    },
    timeoutClearChangedIndexes() {
      let self = this
      setTimeout(function() {
        self.changedAmountIndexes = []
        self.changedCountIndexes = []
        self.flashGrandTotal = false
      }, 3000)
    },
  },
  computed: {
    ...mapGetters(['isLoading']),
  },
  watch: {
    summaryAmount(to, from) {
      if (to !== null && from !== null) {
        if (from[0] !== undefined && parseInt(from[0].value) !== 0) {
          this.changedAmountIndexes = this.getDifferenceIndex(to, from)
          this.timeoutClearChangedIndexes()
        }
      }
    },
    summaryCount(to, from) {
      if (to !== null && from !== null) {
        if (from[0] !== undefined && parseInt(from[0].value) !== 0) {
          this.changedCountIndexes = this.getDifferenceIndex(to, from)
          this.timeoutClearChangedIndexes()
        }
      }
    },
    grandTotal(to, from) {
      if (to !== null && from !== null && to !== from) {
        this.flashGrandTotal = true
        this.timeoutClearChangedIndexes()
      }
    },
  },
}
</script>
