<template>
  <div class="page signup-page complete shipping">
    <div class="container">
      <order-complete
        :wrapper-classes="['p-0']"
        :container-classes="['p-0']"
        payment-message-heading="h5"
        ref="order-complete"
        :show-payment-mode-delivery-details="true"
        :hide-title="true"
      />
      <div class="autoship-area" v-if="isAutoShip && !getSkipEnrolmentPrivilege">
        <div class="autoship" v-if="!isLoggedIn && !getIsAutoshipCreationSuccess && isOrderCompleteWithPayment">
          <b-row align-h="end" class="border-dashed-bottom pb-3 mb-3" no-gutters>
            <b-col cols="auto">
              <b-button size="md" variant="link" class="text-black-50" @click="validateAndSubmit(true)">
                {{ $t('3rdParty.Common.SkipAutoship.Text', { msg: $t('Eshop.Order.GlobalWords.ContinueShopping') }) }}
                <icon name="dashboard-arrow-right"></icon>
              </b-button>
            </b-col>
          </b-row>
          <b-row>
            <b-col cols="12">
              <h5>{{ $t('3rdParty.Checkout.AutoshipProductsProgram.Title') }}</h5>
              <h6>{{ $t('3rdParty.Checkout.AutoshipProductsProgramSub.Title') }}</h6>
            </b-col>
            <b-col cols="12">
              <p v-html="getAutoshipProductsProgramSubTitleTranslation"></p>
            </b-col>
          </b-row>
          <autoship ref="autoship"></autoship>
          <hr class="mb-4" />
          <b-row>
            <b-col cols="12">
              <h5>{{ $t('3rdParty.Checkout.ShippingAndPayment.AutoshipShippingInformation.Title') }}</h5>
            </b-col>
          </b-row>
          <order-page-template
            v-bind="orderProps()"
            :has-cv-transfer="true"
            v-model="orderData"
            :show-continue-button="false"
            :show-promo-code="false"
            :show-remove-cart-item="true"
            :continue-action="validateAndSubmit"
          >
            <hr />
            <SizeSelection :is-container="false" ref="sizesSelection">
              <template slot="title">
                <b-row class="my-2">
                  <b-col cols="12">
                    <h6>{{ $t('3rdParty.Checkout.AutoshipSizesOrInstallaltionSelection.Title') }}</h6>
                  </b-col>
                </b-row>
              </template>
            </SizeSelection>
            <!-- TODO Turn off until further clarification -->
            <!-- Component not reactive for the moment need to fix before turn it on  -->
            <pwp-foc v-if="false" ref="pwpFocSelection">
              <template slot="title">
                <b-row class="my-2">
                  <b-col cols="12">
                    <h6>{{ $t('3rdParty.Checkout.AutoshipPwpFocSelection.Title') }}</h6>
                  </b-col>
                </b-row>
              </template>
            </pwp-foc>
            <autoship-shipping-and-payment
              ref="autoshipShippingAndPayment"
              class="shipping"
            ></autoship-shipping-and-payment>
          </order-page-template>
        </div>
        <div class="autoship-completed" v-if="!isLoggedIn && getIsAutoshipCreationSuccess">
          <b-row>
            <b-col cols="12" class="">
              <b-row
                no-gutters
                align-content="center"
                class="py-1 no-gutters px-sm-d-3 py-sm-d-3 h5 border-sm-d-bottom mb-sm-d-3"
              >
                <b-col class="col-sm-auto mr-sm-3 m-0 d-flex flex-shrink-1 justify-content-center mb-sm-d-1">
                  <icon name="tick-icon" class="icon-size-sm-d-5 icon-size-3" />
                </b-col>
                <div class="w-100 d-sm-none"></div>
                <b-col class="col font-size-sm-d-5 text-sm-d-center">
                  {{ $t('3rdParty.Checkout.AutoshipThankyou.Text') }}
                </b-col>
              </b-row>
            </b-col>
            <b-col cols="12">
              <div class="overflow-x-auto px-sm-d-3">
                <table class="table order-confirmation-table table-transpose-sm-d no-border-sm-d">
                  <thead class="order-table-header">
                    <tr>
                      <th class="align-left">
                        {{ $t('3rdParty.Checkout.AutoshipOrder.Text') }}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr class="order-table-row pl-1">
                      <td class="align-middle" :data-label="$t('3rdParty.Checkout.AutoshipOrder.Text')">
                        {{ getAutoshipSuccessMessage }}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </b-col>
          </b-row>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import OrderComplete from '@/app/_global/components/blocks/OrderComplete'
import Autoship from '@@/app/_global/components/blocks/Autoship'
import AutoshipShippingAndPayment from '@@/app/_global/components/blocks/AutoshipShippingAndPaymet'
import PwpFoc from '@/app/eshop/focpwp/components/FocPwp'
import OrderPageTemplate from '@/app/_global/components/templates/OrderPageTemplate'
import orderCommonsMixin from '@/app/_global/mixins/orderCommonsMixin'
import { customRoutingMixin } from '@@/app/_global/mixins'
import SizeSelection from '@@/app/checkout/sizes/components/SizesSelectionPage'
import { GeneralMixin } from '@/app/_global/mixins'
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'CompletePage',
  components: { OrderComplete, Autoship, AutoshipShippingAndPayment, OrderPageTemplate, SizeSelection, PwpFoc },
  mixins: [orderCommonsMixin, GeneralMixin, customRoutingMixin],
  $_veeValidate: {
    validator: 'new',
  },
  watch: {
    getCartTotal: {
      handler(to) {
        if (to > 0) {
          this.resetError('cartError')
        }
      },
      immediate: true,
    },
  },
  provide() {
    let self = this
    return {
      _general_selected_country_id: function() {
        return self.$helpers.getValue(self.getAppLocationCountry, 'countryId')
      },
    }
  },
  props: {
    isLoggedIn: {
      type: Boolean,
    },
  },
  data() {
    return {
      orderData: {},
    }
  },
  beforeMount() {
    window.addEventListener('beforeunload', this.beforePageDestroyed)
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('beforeunload', this.beforePageDestroyed)
    })
  },
  computed: {
    ...mapGetters([
      'getAppLocationCountry',
      'getCurrentSaleId',
      'getIsAutoshipCreationSuccess',
      'getAutoshipSuccessMessage',
      'isOrderCompleteWithPayment',
    ]),
    ...mapGetters('eshop', [
      'getCartNeedSizeSelection',
      'getCartNeedAddressSelection',
      'getCartTotal',
      'getSelectedFocPwpItems',
      'getEligiblePromotion',
    ]),
    ...mapGetters('3rdPartyCheckoutShippingAndPayment', ['getShippingAndPaymentInfo']),
    ...mapGetters('3rdPartyCheckoutAutoship', ['getAutoshipInfo', 'isAutoShip']),
    ...mapGetters('3rdPartyCheckoutEnrolment', ['getSkipEnrolmentPrivilege']),
    getAutoshipProductsProgramSubTitleTranslation() {
      return this.$t('3rdParty.Checkout.AutoshipProductsProgram.SubTitle', {
        trademark: '<sup class="trademark">' + this.$t('3rdParty.Common.Trademark.Text') + '</sup>',
        options:
          '<div class="row mt-1"><div class="col-3"><div>' +
          this.$t('3rdParty.Checkout.AutoshipProductsProgram.Obption1') +
          '</div>' +
          '<div>' +
          this.$t('3rdParty.Checkout.AutoshipProductsProgram.Obption2') +
          '</div></div>' +
          '<div class="col-9"><div>' +
          this.$t('3rdParty.Checkout.AutoshipProductsProgram.Obption3') +
          '</div>' +
          '<div>' +
          this.$t('3rdParty.Checkout.AutoshipProductsProgram.Obption4') +
          '</div></div>',
      })
    },
  },
  methods: {
    ...mapActions('enrolment', ['resetMemberSponsor']),
    ...mapActions(['clearShoppingData', 'createAutoshipSales', 'logError', 'resetError', 'clearUserIdentifier']),
    ...mapActions('3rdPartyCheckoutGlobal', ['clearData']),
    validateAndSubmit: async function(cancelAutoship = false) {
      let self = this
      let validators = []

      if (self.$refs.autoshipShippingAndPayment !== undefined) {
        validators = [self.$refs.autoshipShippingAndPayment.validate()]
      }
      if (self.getCartNeedSizeSelection || self.getCartNeedAddressSelection) {
        if (self.$refs.sizesSelection !== undefined) {
          validators.push(self.$refs.sizesSelection.validateAndSubmit())
        }
      }
      if (self.isAutoShip && !cancelAutoship && validators.length > 0) {
        await self.resetError('cartError')
        if (self.getCartTotal < 1) {
          self.logError({ cartError: self.$t('3rdParty.Common.ChooseProducts') })
          return false
        }
        // TODO Disabled
        // validators.push(self.$refs.pwpFocSelection.preCheckout(false, true))
        return await Promise.all([...validators]).then(async function(validation) {
          if (validation.indexOf(false) === -1 && validation.indexOf(undefined) === -1) {
            let payload = {
              selected: {
                subscription: {
                  recurring_frequency: self.getAutoshipInfo.autoshipBillingCycle.value,
                  start_date: self.getAutoshipInfo.autoshipBillOn,
                  card: self.getShippingAndPaymentInfo.autoshipCardInfo,
                },
                shipping: self.getShippingAndPaymentInfo.shippingModel,
                billing: self.getShippingAndPaymentInfo.shippingModel,
                promotions: self.getSelectedFocPwpItems,
              },
              countryId: self.getAppLocationCountry.countryId,
              locationId: self.getAppLocationCountry.locationId,
              sale_id: self.getCurrentSaleId,
            }
            await self.createAutoshipSales(payload)
            return true
          } else {
            if (self.errors.items.length > 0) {
              self.$scrollTo('[name="' + self.errors.items[0].field + '"]')
            }
          }
        })
      } else {
        self.doCustomRoute()
      }
    },
    async beforePageDestroyed() {
      await this.clearShoppingData()
      await this.clearData()
      await this.clearUserIdentifier()
      await this.resetMemberSponsor()
    },
  },
}
</script>
