<template>
  <div>
    <div class="d-flex justify-content-center align-items-center vh-50" v-if="loadingData">
      <icon class="icon-size-4" name="spinner" pulse />
    </div>
    <order-steps-template
      v-else
      :steps="selectedOrder"
      :steps-callback="stepCallback"
      :content-wrapper-class="{ content: true }"
    >
      <order-page-template v-bind="orderProps()" @continueAction="validateAndContinue">
        <shipping-method
          id="shippingMethod"
          class="bg-white my-4 p-4"
          v-model="shippingInfoModel"
          :shipping-info="shippingInfo"
          enable-cross-country
          data-qa-prefix="esac-reviewAndShipping"
          ref="shippingMethod"
        />
      </order-page-template>
    </order-steps-template>
  </div>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import ShippingMethod from '@/app/_global/components/blocks/ShippingMethod'
import OrderPageTemplate from '@/app/_global/components/templates/OrderPageTemplate'
import OrderStepsTemplate from '@/app/_global/components/templates/OrderStepsTemplate'
import orderCommonsMixin from '../../mixins/orderCommonsMixin'
import _ from 'lodash'

export default {
  name: 'EsacReviewAndShipping',
  mixins: [orderCommonsMixin],
  components: {
    OrderPageTemplate,
    ShippingMethod,
    OrderStepsTemplate,
  },
  data() {
    return {
      shippingInfo: {},
      shippingInfoModel: {},
      loadingData: true,
    }
  },
  provide() {
    let self = this
    return {
      get _shipping_countries() {
        return self.getCountries
      },
      _member_country_id: function() {
        return self.$helpers.getValue(self.getMyAccountMemberDetails, 'details.country_id')
      },
      _self_pickup_load_stockist_address_list: self.generateStockistAddressLists,
    }
  },
  mounted() {
    let self = this
    // TODO: handle this inside the shipping component
    self
      .loadMyAccountInfo()
      .then(() => {
        return self.initializeShippingData({
          member: self.getMyAccountMemberDetails,
          countryId: self.getMyAccountMemberDetails.details.country_id,
          // isPreferredEmail: self.getMyAccountIsPreferredContactType(self.preferredEmailId)
        })
      })
      .then(() => {
        self.shippingInfo = _.cloneDeep(self.getShippingData)
        this.loadingData = false
      })
    this.loadCountries()
    // this.shippingInfo = JSON.parse(JSON.stringify(this.getEsacShippingData))
    // this.loadingData = false
  },
  methods: {
    ...mapActions([
      'clickEsacReviewAndShippingContinue',
      'loadMyAccountInfo',
      'initializeShippingData',
      'loadCountries',
      'loadStockistLocationAddressList',
      'clickEsacProductSelectionRedeem',
      'saveOrderShipping',
    ]),
    async validateAndContinue() {
      await this.$refs.shippingMethod.$validator.validateAll().then(shippingMethodValidation => {
        if (shippingMethodValidation) {
          this.clickEsacReviewAndShippingContinue(this.shippingInfoModel)
        } else {
          this.$scrollTo('[name="' + this.$refs.shippingMethod.$validator.errors.items[0].field + '"]')
        }
      })
    },
    // TODO: handle this inside the shipping component
    generateStockistAddressLists(payload) {
      return this.loadStockistLocationAddressList({
        country_id: this.$helpers.getValue(this.getMyAccountMemberDetails, 'details.country_id'),
        location_id: payload.location_id,
      })
    },
  },
  computed: {
    ...mapGetters(['getMyAccountMemberDetails', 'getShippingData', 'getCountries', 'getStockistStatesByCountry']),
  },
  watch: {
    shippingInfoModel: function(to) {
      if (to !== null) {
        if (typeof to.self_collection_point_id !== 'undefined' || typeof to.recipient_addresses !== 'undefined') {
          let shippingModel = _.cloneDeep(this.shippingInfoModel)
          shippingModel.validate = true
          this.saveOrderShipping(shippingModel)
          this.clickEsacProductSelectionRedeem()
        }
      }
    },
  },
}
</script>
