<template>
  <div>
    <custom-alert
      :is-display="getCheckoutErrors.length > 0"
      variant="warning"
      class="mt-3"
      :title="$t('Common.Warning')"
      :items="getCheckoutErrors"
    >
    </custom-alert>
    <div class="content">
      <div class="enrol-review-order-wrapper">
        <order-page-template
          class="w-100"
          v-bind="orderProps()"
          :continue-action="validateAndContinue"
          :continue-disabled="!getCheckout.status"
          :has-cv-transfer="true"
          v-model="orderData"
        >
          <shipping-method
            class="py-3 bg-white my-4"
            :shipping-info="shippingInfo"
            id="shippingMethod"
            v-if="getCartDisplayItems.length > 0"
            enable-cross-country
            :allow-save-shipping-address="false"
            v-model="shippingModel"
            data-qa-prefix="enrolment-orderReviewPage"
            ref="shippingMethod"
          />
        </order-page-template>
      </div>
    </div>
  </div>
</template>
<script>
import orderCommonsMixin from '@/app/_global/mixins/orderCommonsMixin'
import OrderPageTemplate from '@/app/_global/components/templates/OrderPageTemplate'
import ShippingMethod from '@/app/_global/components/blocks/ShippingMethod'
import { mapActions, mapGetters } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import _ from 'lodash'
import appSettings from '@/config/app-settings'
import CustomAlert from '@/elements/common/components/CustomAlert'

export default {
  name: 'EnrolmentOrderReviewPage',
  mixins: [orderCommonsMixin],
  props: {
    enrolmentData: {
      type: Object,
      required: true,
    },
  },
  $_veeValidate: {
    validator: 'new',
  },
  components: {
    CustomAlert,
    OrderPageTemplate,
    ShippingMethod,
  },
  data() {
    return {
      shippingInfo: {},
      localShippingInfo: {
        continueDisabled: true,
      },
      loadingData: true,
      orderData: {},
    }
  },
  provide() {
    let self = this
    return {
      get _shipping_countries() {
        return self.getCountries
      },
      _self_pickup_load_stockist_address_list: self.generateStockistAddressLists,
    }
  },
  async mounted() {
    let self = this
    await self
      .initializeShippingData({
        member: self.getEnrolForm.member_data,
        countryId: self.getEnrolmentRegion.id,
      })
      .then(() => {
        self.shippingInfo = _.cloneDeep(self.getShippingData)
        if (self.shippingInfo.sale_delivery_method === null) {
          self.shippingInfo.sale_delivery_method = this.shippingMethodDeliveryId
        }
        if (this.enrolmentData.on_behalf_enrolment === 1) {
          self.shippingInfo.recipient_mobile_phone_number = ''
        }
      })
    if (appSettings.eshop.order_item.cv_transfer_checkbox === true) {
      self.orderData = {
        cvTransferList: self.getCvTransferList,
      }
    }
    await this.loadCountries()
    await this.loadCart({
      ekSmart: this.isEkSmart,
    })
    this.clearLoadedData(['order'])
  },
  methods: {
    ...mapActions('eshop', ['loadCart', 'saveOrderShipping', 'updateCvTransferList']),
    ...mapActions('enrolment', ['getIsEnrolTypeIsMember']),
    ...mapActions([
      'loadCountries',
      'loadMyAccountInfo',
      'initializeShippingData',
      'loadStockistLocationAddressList',
      'clearLoadedData',
    ]),
    generateStockistAddressLists(payload) {
      return this.loadStockistLocationAddressList({
        country_id: this.getEnrolmentRegion.id,
        state_id: payload.state_id,
        location_id: payload.location_id,
      })
    },
    validateAndContinue: async function() {
      let self = this
      if (this.getCartDisplayItems.length > 0) {
        this.$refs.shippingMethod.validate().then(shippingMethodValidation => {
          if (shippingMethodValidation) {
            self.enrolmentData.step_states['review-order'] = true
            self.continueToNextStep()
          } else {
            self.$scrollTo('[name="' + self.$refs.shippingMethod.$validator.errors.items[0].field + '"]')
            self.enrolmentData.step_states['review-order'] = false
          }
        })
      } else {
        self.enrolmentData.step_states['review-order'] = true
        self.continueToNextStep()
      }
    },
    continueToNextStep() {
      let data = {}
      if (this.getCartDisplayItems.length === 0) {
        this.resolveMasters.then(() => {
          data = {
            sale_delivery_method: this.shippingMethodWithoutShippingId,
          }
          this.saveOrderShipping(data)
          this.next()
        })
      } else {
        data = this.$refs.shippingMethod.getData()
        this.saveOrderShipping(data)
        this.next()
      }
    },
  },
  computed: {
    ...mapGetters([
      'getMyAccountMemberDetails',
      'getShippingData',
      'getCountries',
      'getSelectedCountry',
      'getStockistStatesByCountry',
      'getEnrolmentRegion',
    ]),
    ...mapGetters('enrolment', ['getEnrolForm']),
    ...mapGetters('eshop', ['getCartDisplayItems', 'getCvTransferList', 'getCheckout', 'getCheckoutErrors']),
    ...mapMasterDataId({
      SALE_DELIVERY_METHOD: {
        shippingMethodWithoutShippingId: 'WITHOUT_SHIPPING',
        shippingMethodDeliveryId: 'DELIVERY',
        shippingMethodSelfCollectionId: 'SELF_PICKUP',
      },
    }),
  },
  watch: {
    orderData: {
      handler() {
        this.updateCvTransferList(this.orderData.cvTransferList)
      },
      deep: true,
    },
  },
}
</script>
