<template>
  <div>
    <b-card-title class="mb-4 text-black">{{ $t('Common.Sales.PreCheckout') }}</b-card-title>
    <div id="basic-autoship-info">
      <b-row>
        <b-col cols="12" md="5" lg="4">
          <label class="col">{{ $t('Autoship.NextBillDate') }} (yyyy-mm-dd)</label>
          <b-col class="pb-3">
            <b-form-input readonly size="sm" :value="nextBillDate" />
          </b-col>
        </b-col>
        <b-col cols="12" md="4" lg="3">
          <label class="col">{{ $t('Autoship.BillingCycle') }}</label>
          <b-col class="pb-3">
            <b-form-input readonly size="sm" :value="shipCycle" />
          </b-col>
        </b-col>
      </b-row>
      <label class="col">{{ $t('Common.Payment.CreditCard') }}</label>
      <b-col cols="12" md="7" lg="5" class="pb-3">
        <b-form-input readonly size="sm" :value="getCreditCard" />
      </b-col>
      <label class="col">{{ $t('Common.ShippingAddress') }}</label>
      <b-col cols="12" lg="9" class="pb-3">
        <b-form-input readonly size="sm" :value="shippingAddressString" />
      </b-col>
      <label class="col">{{ $t('Autoship.BillingAddress.Label') }}</label>
      <b-col cols="12" lg="9" class="pb-2">
        <b-form-input readonly size="sm" :value="billingAddress" />
      </b-col>
    </div>
    <hr />
    <div class="pt-2">
      <b-col class="table-responsive">
        <table class="table border-bottom mb-2">
          <thead>
            <tr class="bg-transparent">
              <th scope="col" class="align-middle">
                {{ $t('Common.Table.No') }}
              </th>
              <th scope="col" class="align-middle">
                {{ $t('Common.ProductCode') }}
              </th>
              <th scope="col" class="align-middle">
                {{ $t('Common.Product.ProductName') }}
              </th>
              <th scope="col" class="align-middle text-center">
                {{ $t('Common.Quantity') }}
              </th>
              <th scope="col" class="align-middle text-right">
                {{ $t('Common.Terminology.TotalBV') }}
              </th>
              <th scope="col" class="align-middle text-right">
                {{ $t('Common.TotalAmount.WithCurrency', { currency: currency }) }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in getCartDisplayItemsWithMemberKit" :key="index">
              <td class="align-middle">
                {{ index + 1 }}
              </td>
              <td class="align-middle">
                {{ item.sku }}
              </td>
              <td class="align-middle">
                {{ item.name }}
              </td>
              <td class="text-center align-middle">
                {{ item.quantity }}
              </td>
              <td class="text-right align-middle">
                {{ item.total_cv.eligible }}
              </td>
              <td class="text-right align-middle">
                {{ $helpers.getCurrencyValue(item.total_prices.nmp_price) }}
              </td>
            </tr>
          </tbody>
          <tfoot>
            <tr class="font-weight-bold border-bottom-double">
              <td colspan="4" class="text-primary align-middle text-right font-weight-bold-extra">
                {{ $t('Common.Sales.GrandTotal') }}
              </td>
              <td class="text-primary align-middle text-right font-weight-bold-extra">
                {{ getTotalCv }}
              </td>
              <td class="text-primary align-middle text-right font-weight-bold-extra no-wrap">
                {{ getCartTotalPriceFormatted }} *
              </td>
            </tr>
          </tfoot>
        </table>
        <span class="text-black-50">{{ $t('Common.Sales.PreSalesDeclaimer') }}</span>
      </b-col>
    </div>
    <div>
      <b-col class="mb-3">
        <div class="bg-note border p-3">
          <strong>{{ $t('Autoship.Agreement.Title') }}</strong>
          <div v-if="hasError" class="text-danger pt-2 animated flash">{{ $t('Autoship.Agreement.Error') }}</div>
          <b-form-checkbox
            v-for="(message, messageIndex) in getCheckoutAgreement"
            v-model="additionalAgreements[messageIndex]"
            class="mt-3 ml-3"
            :key="`agreement-message-${messageIndex}`"
            :data-qa="`autoship-summary-agreement-message-${messageIndex + 1}`"
          >
            <span class="text-dark c-pointer" v-html="message"></span>
          </b-form-checkbox>
        </div>
      </b-col>
    </div>
  </div>
</template>

<script>
import { AddressMixin, CurrencyMixin } from '@/app/_global/mixins'
import { mapGetters, mapActions } from 'vuex'
import _ from 'lodash'
import { AUTOSHIP_SUBSCRIPTION_DETAIL } from '@/config/url-prefix'
export default {
  name: 'Checkout',
  mixins: [CurrencyMixin, AddressMixin],
  data() {
    return {
      additionalAgreements: [],
      hasError: false,
      shippingAddressString: '-',
    }
  },
  computed: {
    ...mapGetters([
      'getCheckoutAgreement',
      'getShippingCycleDetail',
      'getPaymentInfo',
      'getAutoshipShippingInfo',
      'getAutoshipBillingInfo',
      'getAppLocationCountry',
      'getAutoshipCountry',
    ]),
    ...mapGetters('eshop', [
      'getCartTotalPriceFormatted',
      'getCartCv',
      'getCartDisplayItemsWithMemberKit',
      'getCartNeedSizeSelection',
      'getCartIsAllDummiesSelectedForSales',
      'getCartTotalDeliveryFeeFormatted',
      'getCartTotalAdminFeeFormatted',
      'getCartTotalPriceRoundingAdjustmentFormatted',
      'getCartTotalTaxFormatted',
    ]),
    nextBillDate() {
      return this.getShippingCycleDetail.billOn || ''
    },
    shipCycle() {
      return this.$helpers.getValue(this.getShippingCycleDetail, 'billingCycle.text') || ''
    },
    getCreditCard() {
      let cardString = ''
      if (this.getPaymentInfo !== null) {
        let card = this.getPaymentInfo
        cardString = `[${card.card_type}]  ${card.card_number}  Exp: ${card.card_expiry}`
      }
      return cardString
    },
    billingAddress() {
      let address = this.$helpers.getValue(this.getAutoshipBillingInfo, 'recipient_addresses[0]')
      if (this.getAutoshipBillingInfo !== null && address) {
        return this.getAddressString(address) || ''
      }
      return ''
    },
    getTotalCv() {
      return this.$helpers.getValue(this.getCartCv, 'break_down.base') || '-'
    },
  },
  async mounted() {
    await this.generateShippingAddress()
  },
  methods: {
    ...mapActions(['createAutoshipSales', 'loadStockistLocationAddressList']),
    async generateShippingAddress() {
      let address = '-'
      if (this.getAutoshipShippingInfo.hasOwnProperty('self_collection_city_id')) {
        await this.loadStockistLocationAddressList({
          country_id: this.getAutoshipCountry,
          location_id: this.getAutoshipShippingInfo.self_collection_city_id,
        }).then(data => {
          data = data.find(location => location.id === this.getAutoshipShippingInfo.self_collection_point_id)
          address = (data.address_data && data.address_data[0]) || '-'
        })
      } else {
        address = this.$helpers.getValue(this.getAutoshipShippingInfo, 'recipient_addresses[0]', '-')
      }
      this.shippingAddressString = address !== '-' ? this.getAddressString(address) : address
    },
    storeDataValidation() {
      return (
        !_.isEmpty(this.getPaymentInfo) &&
        !_.isEmpty(this.getShippingCycleDetail) &&
        !_.isEmpty(this.getAutoshipShippingInfo) &&
        !_.isEmpty(this.getAutoshipBillingInfo) &&
        this.getAutoshipShippingInfo.validated === true &&
        this.getAutoshipBillingInfo.validated === true &&
        this.getCartNeedSizeSelection + _.isEmpty(this.getCartIsAllDummiesSelectedForSales.sizes) === 1
      )
    },
    validateUserAgreementField() {
      let list = Object.keys(_.groupBy(this.additionalAgreements))
      return list.length === 1 && list.includes('true')
    },
    validateAndSubmit() {
      this.hasError = false
      let self = this
      return Promise.resolve(this.validateUserAgreementField()).then(valid => {
        if (valid && self.storeDataValidation()) {
          let payload = {
            countryId: this.getAppLocationCountry.countryId,
            locationId: this.getAppLocationCountry.locationId,
          }
          this.createAutoshipSales(payload)
            .then(response => {
              if (response.subscription_id !== undefined) {
                this.$swal({
                  title: this.$t('Autoship.Popup.CreateSalesSuccess.title'),
                  type: 'success',
                  timer: '2300',
                })
                this.$router.push(AUTOSHIP_SUBSCRIPTION_DETAIL + '/' + response.subscription_id)
              } else {
                this.$swal({
                  title: this.$t('Autoship.Popup.CreateSalesFail.title'),
                  text: this.$t('Common.Error.ActionFailure.HelpText'),
                  type: 'warning',
                })
              }
            })
            .catch(e => {
              this.$swal({
                title: this.$t('Autoship.Popup.CreateSalesFail.title'),
                text: this.$t('Common.Error.ActionFailure.HelpText'),
                type: 'error',
              })
            })
        } else if (valid) {
          this.$swal({
            title: this.$t('Autoship.Popup.CreateSalesFail.title'),
            text: this.$t('Autoship.Popup.CreateSalesFail.msg'),
            type: 'warning',
          })
        } else {
          this.hasError = true
        }
        return valid
      })
    },
  },
}
</script>
