<template>
  <div class="container">
    <order-page-template
      v-bind="orderProps()"
      show-redeem-summary
      :continue-action="validateAndContinue"
      :has-cv-transfer="true"
      v-model="orderData"
    >
      <div v-if="getITokenCartItems.length">
        <div>{{ $t('Itoken.Redemption.Title') }}</div>
        <i-token-selected-products-table class="bg-white" :currency="currency" :selected-items="getITokenCartItems" />
      </div>

      <shipping-method
        id="shippingMethod"
        class="bg-white my-4 py-4"
        v-model="shippingModel"
        :shipping-info="shippingInfo"
        enable-cross-country
        shipping-method-form-field-row-size-classes="col-lg-12"
        ref="shippingMethod"
        scope="eshopOrderReview"
        data-qa-prefix="eshop-orderReview"
      />
    </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 '@/app/_global/mixins/orderCommonsMixin'
import { GeneralMixin, mapMasterDataId } from '@/app/_global/mixins'
import _ from 'lodash'
import appSettings from '@/config/app-settings'
import ITokenSelectedProductsTable from '@/app/i-token/_global/components/elements/ITokenSelectedProductsTable'

export default {
  name: 'OrderReview',
  mixins: [orderCommonsMixin, GeneralMixin],
  components: {
    ITokenSelectedProductsTable,
    OrderPageTemplate,
    ShippingMethod,
  },
  data() {
    return {
      shippingInfo: {},
      orderData: {},
    }
  },
  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
        .loadMyAccountInfo()
        .then(() => {
          return self.initializeShippingData({
            member: self.getIsOrderingForDownLine ? self.getOrderingFor : self.getMyAccountMemberDetails,
            countryId: self.getSelectedCountry.id,
            isPreferredEmail: self.getMyAccountIsPreferredContactType(self.preferredEmailId),
          })
        })
        .then(() => {
          self.shippingInfo = _.cloneDeep(self.getShippingData)
          if (self.shippingInfo.sale_delivery_method === null) {
            self.shippingInfo.sale_delivery_method = this.shippingMethodDeliveryId
          }
        })
      this.loadCountries()
      if (self.shippingInfo.sale_delivery_method !== null) {
        self.shippingInfo.sale_delivery_method = this.shippingMethodDeliveryId
      }
      if (appSettings.eshop.order_item.cv_transfer_checkbox === true) {
        self.orderData = {
          cvTransferList: self.getCvTransferList,
        }
      }
    })
  },
  methods: {
    ...mapActions('eshop', ['loadCart', 'saveOrderShipping', 'updateCvTransferList']),
    ...mapActions([
      'loadCountries',
      'loadMyAccountInfo',
      'initializeShippingData',
      'loadStockistLocationAddressList',
      'loadMasterDataKeys',
    ]),
    generateStockistAddressLists(payload) {
      return this.loadStockistLocationAddressList({
        country_id: this.getSelectedCountry.id,
        location_id: payload.location_id,
      })
    },
    validateAndContinue: function() {
      let self = this
      self.$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', 'getCvTransferList']),
    ...mapMasterDataId({
      PREFERRED_CONTACT: {
        preferredEmailId: 'EMAIL',
      },
      SALE_DELIVERY_METHOD: {
        shippingMethodWithoutShippingId: 'WITHOUT_SHIPPING',
        shippingMethodDeliveryId: 'DELIVERY',
        shippingMethodSelfCollectionId: 'SELF_PICKUP',
      },
    }),
  },
  watch: {
    orderData: {
      handler() {
        this.updateCvTransferList(this.orderData.cvTransferList)
      },
      deep: true,
    },
  },
}
</script>
