<template>
  <div class="page signup-page shipping">
    <div class="container">
      <b-row>
        <custom-alert
          :is-display="getCheckoutErrors.length > 0"
          variant="warning"
          class="w-100"
          :title="$t('Common.Warning')"
          :items="getCheckoutErrors"
        />
      </b-row>
      <b-row>
        <b-col lg="12">
          <b-row>
            <b-col lg="12">
              <h5>{{ $t('3rdParty.Checkout.ShippingAndPayment.ShippingInformation.Title') }}</h5>
              <p v-html="getShippingInformationSubTitleTranslation"></p>
            </b-col>
            <b-col lg="6">
              <shipping-method
                class="p-1 bg-white"
                :hide-title="true"
                :wrapper-classes="['shipping-wrapper']"
                :shipping-method-delivery-classes="['shipping-delivery-method']"
                :shipping-method-self-collection-classes="['shipping-self-collection-method']"
                :shipping-info="shippingInfo"
                v-model="shippingModel"
                :allow-save-shipping-address="false"
                shipping-method-form-field-row-size-classes="col-lg-12"
                :show-shipping-empty-address-info="true"
                :enable-cross-country="true"
                data-qa-prefix="checkout-shippingPage"
                ref="shippingMethod"
              ></shipping-method>
            </b-col>
          </b-row>
        </b-col>
      </b-row>
    </div>
  </div>
</template>
<script>
import ShippingMethod from '@/app/_global/components/blocks/ShippingMethod'
import CustomAlert from '@/elements/common/components/CustomAlert'
import { mapActions, mapGetters } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import _ from 'lodash'
import appSettings from '@/config/app-settings'
import { DefaultProvider } from '@/providers'
import { APP_SHIPPING_AND_PAYMENT_FORM } from '@@/store/localStorageKeys'
import { IS_LOGGED_IN_GETTER_NAME } from '@/config/defaults'

export default DefaultProvider.extend({
  name: 'ShippingPage',
  components: { ShippingMethod, CustomAlert },
  mixins: [],
  $_veeValidate: {
    validator: 'new',
  },
  provide() {
    let self = this
    return {
      get _shipping_countries() {
        return self.getCountries
      },
      _self_pickup_load_stockist_address_list: self.generateStockistAddressLists,
    }
  },
  data() {
    return {
      shippingInfo: {
        status: false,
      },
      loadingData: true,
      shippingModel: {},
      enableCrossCountry: {
        normalShipping: false,
      },
    }
  },
  watch: {
    shippingInfo: {
      handler() {
        this.setLocalForm({
          namespace: '3rdPartyCheckoutShippingAndPayment/',
          key: APP_SHIPPING_AND_PAYMENT_FORM,
          formData: { shippingInfo: this.shippingInfo },
        })
      },
      deep: true,
    },
    shippingModel: {
      handler() {
        this.setLocalForm({
          namespace: '3rdPartyCheckoutShippingAndPayment/',
          key: APP_SHIPPING_AND_PAYMENT_FORM,
          formData: { shippingModel: this.shippingModel },
        })
        // this.loadCart()
      },
      deep: true,
    },
  },
  computed: {
    ...mapGetters([
      'getMyAccountMemberDetails',
      'getShippingData',
      'getCountries',
      'getSelectedCountry',
      'getStockistStatesByCountry',
      'getEnrolmentRegion',
      'getAppLocationCountry',
      'getLoggedInUser',
    ]),
    ...mapGetters('3rdPartyCheckoutEnrolment', ['getEnrolmentInfo']),
    ...mapGetters('3rdPartyCheckoutShippingAndPayment', ['getShippingAndPaymentInfo']),
    ...mapGetters('eshop', ['getCartDisplayItems', 'getCvTransferList', 'getCheckoutErrors', 'getCheckout']),
    ...mapGetters({
      isLoggedIn: [IS_LOGGED_IN_GETTER_NAME],
    }),
    ...mapMasterDataId({
      SALE_DELIVERY_METHOD: {
        shippingMethodWithoutShippingId: 'WITHOUT_SHIPPING',
        shippingMethodDeliveryId: 'DELIVERY',
        shippingMethodSelfCollectionId: 'SELF_PICKUP',
      },
    }),
    getShippingInformationSubTitleTranslation() {
      return this.$t('3rdParty.Checkout.ShippingAndPayment.ShippingInformation.SubTitle', {
        trademark: '<sup class="trademark">' + this.$t('3rdParty.Common.Trademark.Text') + '</sup>',
      })
    },
  },
  async mounted() {
    let self = this
    await this.resolveMasters
    let memberData = {}
    if (self.isLoggedIn) {
      await this.loadMyAccountInfo({ user_id: this.getLoggedInUser.id })
      memberData = self.getMyAccountMemberDetails
    } else {
      memberData = self.getEnrolmentInfo.member_data
    }
    await self
      .initializeShippingData({
        member: memberData,
        countryId: self.getAppLocationCountry.countryId,
      })
      .then(async () => {
        self.shippingInfo = _.cloneDeep(self.getShippingData)
        let localStorageShippingInfo = _.chain(self.getShippingAndPaymentInfo.shippingInfo)
          .cloneDeep()
          .merge({
            member_country_id: self.getAppLocationCountry.countryId,
            self_collection_country_id: self.getAppLocationCountry.countryId,
            sale_delivery_method: !self.$helpers.isSet(
              self.getShippingAndPaymentInfo,
              'shippingModel.sale_delivery_method'
            )
              ? self.shippingMethodDeliveryId
              : self.getShippingAndPaymentInfo.shippingModel.sale_delivery_method,
            self_collection_point_id: self.getShippingAndPaymentInfo.shippingModel
              ? self.getShippingAndPaymentInfo.shippingModel.self_collection_point_id
              : null,
            self_collection_city_id: self.getShippingAndPaymentInfo.shippingModel
              ? self.getShippingAndPaymentInfo.shippingModel.self_collection_city_id
              : null,
          })
          .value()
        self.shippingInfo = _.cloneDeep({ ...self.shippingInfo, ...localStorageShippingInfo })
        if (!self.isLoggedIn) {
          // Todo temp hack to match member primary address
          self.shippingInfo.member_addresses[0].fields =
            self.getEnrolmentInfo.member_data.address.address_data[0].fields
          self.shippingInfo.member_addresses[1].fields =
            self.getEnrolmentInfo.member_data.address.address_data[0].fields
        }
        // Todo temp hack remove wrong country from address list
        let shippingCountryField = self.$helpers
          .getValue(self.shippingInfo.member_addresses[2], 'fields', [])
          .find(field => field.key === 'countries')

        if (shippingCountryField && shippingCountryField.value !== self.shippingInfo.member_country_id) {
          self.shippingInfo.member_addresses[2].fields = []
        }
      })

    if (appSettings.eshop.order_item.cv_transfer_checkbox === true) {
      self.orderData = {
        cvTransferList: self.getCvTransferList,
      }
    }
    this.errors.clear()
  },
  methods: {
    ...mapActions('3rdPartyCheckoutGlobal', ['setLocalForm']),
    ...mapActions('eshop', ['loadCart', 'updateCvTransferList']),
    ...mapActions('enrolment', ['getIsEnrolTypeIsMember']),
    ...mapActions([
      'loadCountries',
      'loadMyAccountInfo',
      'initializeShippingData',
      'loadStockistLocationAddressList',
      'clearLoadedData',
    ]),
    generateStockistAddressLists(payload) {
      return this.loadStockistLocationAddressList({
        country_id: this.getAppLocationCountry.countryId,
        state_id: payload.state_id,
        location_id: payload.location_id,
      })
    },
    validateAndSubmit: async function() {
      let self = this
      return await this.$refs.shippingMethod.validate().then(shippingMethodValidation => {
        if (shippingMethodValidation) {
          return true
        } else {
          self.$scrollTo('[name="' + self.errors.items[0].field + '"]')
        }
      })
    },
  },
})
</script>
