<template>
  <div class="container">
    <order-page-template v-bind="orderProps()" :continue-action="validateAndContinue">
      <shipping-method
        id="shippingMethod"
        class="bg-white my-4 p-4"
        v-model="shippingModel"
        :shipping-info="shippingInfo"
        data-qa-prefix="virel-review"
        ref="shippingMethod"
      />
    </order-page-template>
  </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import OrderPageTemplate from '@/app/_global/components/templates/OrderPageTemplate'
import ShippingMethod from '@/app/_global/components/blocks/ShippingMethod'
import orderCommonsMixin from '../mixins/orderCommonsMixin'
import { GeneralMixin, mapMasterDataId } from '@/app/_global/mixins'

export default {
  name: 'OrderReview',
  mixins: [orderCommonsMixin, GeneralMixin],
  components: {
    OrderPageTemplate,
    ShippingMethod,
  },
  data() {
    return {
      shippingInfo: {},
    }
  },
  provide() {
    let self = this
    return {
      get _shipping_countries() {
        return self.getCountries
      },
      _self_pickup_load_stockist_address_list: self.generateStockistAddressLists,
    }
  },
  mounted() {
    let self = this
    this.resolveMasters.then(() => {
      self.shippingInfo = {
        recipient_name: '',
        recipient_mobile_country_code_id: '',
        recipient_mobile_phone_number: '',
        member_addresses: [
          {
            title: 'Shipping 1',
            fields: [],
          },
        ],
      }
    })
  },
  methods: {
    ...mapActions('eshop', ['loadCart', 'saveOrderShipping']),
    ...mapActions([
      'loadCountries',
      'loadMyAccountInfo',
      'initializeShippingData',
      'loadStockistLocationAddressList',
      'loadMasterDataKeys',
    ]),
    generateStockistAddressLists(payload) {
      return this.loadStockistLocationAddressList({
        country_id: this.countryId,
        location_id: payload.location_id,
      })
    },
    validateAndContinue: function() {
      let self = this
      this.$refs.shippingMethod.validate().then(shippingMethodValidation => {
        if (shippingMethodValidation) {
          self.continueToNextStep()
        } else {
          self.$scrollTo('[name="' + self.$refs.shippingMethod.$validator.errors.items[0].field + '"]')
        }
      })
    },
    continueToNextStep() {
      let data = this.$refs.shippingMethod.getData()
      data.validated = true
      this.saveOrderShipping(data)
      this.next()
    },
  },
  computed: {
    ...mapGetters([
      'getMyAccountMemberDetails',
      'getShippingData',
      'getCountries',
      'getSelectedCountry',
      'getStockistStatesByCountry',
      'getMyAccountIsPreferredContactType',
    ]),
    ...mapGetters('eshop', ['getOrderingFor', 'getIsOrderingForDownLine']),
    ...mapMasterDataId({
      PREFERRED_CONTACT: {
        preferredEmailId: 'EMAIL',
      },
    }),
  },
}
</script>
