<template>
  <div :class="shippingMethodDeliveryClasses">
    <b-container class="p-0">
      <!-- Address error notice -->
      <b-row class="empty-address mb-3" v-if="showShippingEmptyAddressInfo && noSelectableAddressOnInit">
        <b-col>
          {{ $t('Eshop.Order.Shipping.Method.Delivery.EmptyAddress') }}
        </b-col>
      </b-row>
      <!-- End Address error notice -->
      <!-- Box Style -->
      <b-row v-if="!isAddressStyleList" no-gutters class="my-3">
        <b-col
          cols="12"
          lg="12"
          class="address-preview-box bg-note border-dashed p-3 animated flipInX z-1000"
          ref="address-preview-box"
          :style="getBoxStyle"
          :class="{ 'd-none': addAddressFormVisible || hideAddressSelection }"
        >
          <b-row align-h="between">
            <b-col
              lg="auto"
              md="12"
              class="m-0"
              v-html="getSelectedAddressPreview !== '' ? getSelectedAddressPreview : 'No Address Data Available'"
            />
            <b-col cols="auto">
              <b-row align-v="center" no-gutters>
                <b-col class="my-2">
                  <b-button-toolbar v-if="availableAddress.length > 0">
                    <b-button-group>
                      <b-dropdown
                        left
                        :text="getAddressString(availableAddress[selectedAddressIndex], false, true)"
                        variant="remove"
                      >
                        <b-dropdown-item
                          v-for="(address, idx) in availableAddress"
                          v-show="address.exclude === undefined || !address.exclude"
                          :active="selectedAddressIndex === idx"
                          :key="`address-menu-${idx}`"
                          @click="selectCurrentAddress(idx)"
                        >
                          {{ getAddressString(address, false, true) }}</b-dropdown-item
                        >
                      </b-dropdown>
                      <b-button
                        v-show="
                          (hasEditableAddress.custom.status &&
                            availableAddress[hasEditableAddress.custom.index] !== undefined &&
                            selectedAddressIndex === hasEditableAddress.custom.index) ||
                            (hasEditableAddress.unselected.status &&
                              availableAddress[hasEditableAddress.custom.index] !== undefined &&
                              selectedAddressIndex === hasEditableAddress.custom.index)
                        "
                        variant="outline-primary"
                        block
                        size="sm"
                        @click="toggleAddAddressForm()"
                        >{{ $t('Common.Edit') }}</b-button
                      >
                    </b-button-group>
                  </b-button-toolbar>
                </b-col>
              </b-row>
            </b-col>
          </b-row>
        </b-col>
      </b-row>
      <!-- End Box Style -->
      <!-- List Style -->
      <b-row v-if="isAddressStyleList">
        <b-col class="mb-4 mt-2" :class="{ 'd-none': addAddressFormVisible || hideAddressSelection }">
          <span>{{ $t('Common.MyAddresses') }}</span>
          <b-list-group class="py-2">
            <b-list-group-item
              v-for="(address, idx) in availableAddress"
              button
              :key="idx"
              @click="selectCurrentAddress(idx)"
              class="pre-wrap animated flipInX h-100 w-100"
              :class="{ active: selectedAddressIndex === idx }"
            >
              <b-row align-h="between" align-v="center">
                <b-col cols="1" align-self="center">
                  <icon name="check-circle" class="icon-size-3" />
                </b-col>
                <b-col cols="9">
                  <b-row class="ml-0">
                    <b-col cols="12" class="mb-2">
                      <span class="font-weight-bold">{{
                        $t('Dynamic.Address.' + $helpers.capitalCase(address.title))
                      }}</span>
                    </b-col>
                    <b-col>
                      <span class="font-weight-bold-semi">{{ getAddressString(address) }}</span>
                    </b-col>
                  </b-row>
                </b-col>
                <b-col cols="2" align-self="center">
                  <b-button
                    v-show="
                      (hasEditableAddress.custom.status && hasEditableAddress.custom.index === idx) ||
                        (hasEditableAddress.unselected.status && hasEditableAddress.unselected.index === idx)
                    "
                    block
                    size="sm"
                    variant="outline"
                    @click="toggleAddAddressForm"
                  >
                    {{ $t('Common.Edit') }}
                  </b-button>
                </b-col>
              </b-row>
            </b-list-group-item>
          </b-list-group>
        </b-col>
      </b-row>
      <!-- End List Style -->
      <!-- Address form -->
      <b-container fluid class="p-0 pb-2">
        <b-row v-if="!hideAddBtn && !addAddressFormVisible">
          <b-col>
            <div class="text-primary" v-if="!hasEditableAddress.status">
              <b-link @click="toggleAddAddressForm()" data-qa="add-new-address-btn">
                <icon name="add-icon" class="icon-size-3 pr-2 align-middle" />
                <span class="h6 font-weight-bold-extra">
                  {{ $t('Eshop.Order.Shipping.Method.Delivery.AddAnotherAddress') }}
                </span>
              </b-link>
            </div>
          </b-col>
        </b-row>
        <b-row v-if="addAddressFormVisible" class="no-overflow mt-2">
          <b-col cols="12" :class="shippingMethodFormFieldRowSizeClasses">
            <div class="form-group mt-3" :class="{ 'slideInDown animated': addAddressFormVisible }">
              <b-row
                class="my-1"
                v-for="(field, index) in sortDynamicFieldsCountryStateCityTop(unselectedAddress.fields)"
                :key="index"
              >
                <b-col sm="12">
                  <b-form-row class="text-capitalize ">
                    <b-col lg="3" sm="12" md="12" class="d-flex align-items-center">
                      <label :class="{ required: field.required, 'm-0': true }">
                        {{ (tLabel = $t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label)) }}
                      </label>
                    </b-col>
                    <b-col>
                      <!--                      the LAZY Props for future purpose will be apply once upgrade to bootstrap 2.1 and above-->
                      <b-form-input
                        lazy
                        :class="fields[tLabel]"
                        type="text"
                        :name="tLabel"
                        v-if="field.type === 'input'"
                        v-model="field.value"
                        v-validate="field.required ? 'required' : ''"
                        :disabled="field.disabled"
                        :data-qa="`${$helpers.kebabCase(field.label)}-input`"
                      />
                      <b-form-select
                        v-if="
                          field.type === 'select' || (field.type === 'custom-select' && field.type !== 'masters-select')
                        "
                        :class="fields[tLabel]"
                        v-model="field.value"
                        @change="formFieldChanged(field, $event, false)"
                        :name="tLabel"
                        :options="
                          getFieldOptionsData(getSelectedAddressIndex(), field, {
                            countriesFilter: allowedShippingCountries,
                          })
                        "
                        v-validate="field.required ? 'required' : ''"
                        :disabled="
                          isCrossCountryDeliveryAvailable ? false : field.key === 'countries' ? true : field.disabled
                        "
                        :data-qa="`${$helpers.kebabCase(field.label)}-select`"
                      />
                      <span v-show="errors.has(field.label)" class="small text-danger">
                        {{ errors.first(field.label) }}
                      </span>
                    </b-col>
                  </b-form-row>
                </b-col>
              </b-row>
              <b-row class="mt-3" align-h="end">
                <b-col cols="auto">
                  <b-tooltip
                    v-if="disableSaving"
                    :target="() => $refs.saveAddress"
                    :enabled="true"
                    placement="bottom"
                    :delay="{ hide: 3000 }"
                  >
                    <span
                      v-html="
                        $t('Eshop.Order.Shipping.Method.Delivery.PreventSave', {
                          link: myAccountLink,
                          text: $t('MyAccount.Title'),
                        })
                      "
                    />
                  </b-tooltip>
                  <span ref="saveAddress" v-if="allowSaveShippingAddress">
                    <b-btn
                      v-model="saveCheck"
                      variant="primary"
                      @click="saveNewShippingAddress"
                      :disabled="disableSaving"
                      data-qa="save-shipping-address-btn"
                    >
                      {{ $t('Eshop.Order.Shipping.Method.Delivery.SaveShippingAddress') }}
                    </b-btn>
                  </span>
                  <b-btn
                    variant="outline"
                    @click="cancelShippingAddress"
                    v-if="totalAddressLength > 0 && getSelectedAddressPreview"
                    data-qa="cancel-shipping-address-btn"
                  >
                    {{ $t('Common.Close') }}
                  </b-btn>
                </b-col>
              </b-row>
            </div>
          </b-col>
        </b-row>
      </b-container>
      <!-- End Address form -->
      <!-- Recipient info-->
      <b-row no-gutters class="my-1">
        <b-col class="col-12 p-0">
          <b-row>
            <b-col class="col-12 col-md-3">
              <label class="required pt-2">
                {{ $t('Eshop.Order.Shipping.Method.Delivery.RecipientName') }}
              </label>
            </b-col>
            <b-col>
              <b-form-input
                name="Recipient Name"
                :disabled="isLoading('CountryRelationRecipientCrossCountryLoading')"
                v-validate="'required'"
                v-model="shippingInfo.recipient_name"
                :class="{ input: true, 'border-danger': errors.has('Recipient Name') }"
                type="text"
                data-qa="recipient-name-input"
              />
              <span v-show="errors.has(`Recipient Name`)" class="help text-danger small">
                {{ errors.first('Recipient Name') }}
              </span>
            </b-col>
          </b-row>
        </b-col>
      </b-row>
      <b-row no-gutters class="my-2">
        <b-col class="p-0">
          <b-row>
            <b-col class="col-12 col-md-3">
              <label class="required pt-2">
                {{ $t('Eshop.Order.Shipping.Method.Delivery.RecipientContact') }}
              </label>
            </b-col>
            <b-col class="col-12 col-md-4 mb-2">
              <b-form-select
                name="Mobile country code"
                :disabled="isLoading('CountryRelationRecipientCrossCountryLoading')"
                v-model="shippingInfo.recipient_mobile_country_code_id"
                :class="{ 'input font-size-sm-d-8': true, 'border-danger': errors.has('Mobile country code') }"
                v-validate="'required'"
                data-qa="recipient-mobile-country-code-select"
              >
                <option value="null" disabled selected>
                  --Select Country--
                </option>
                <option v-for="(item, idx) in recipientContactOptions" :value="item.value" :key="idx">
                  {{ item.text }}
                </option>
              </b-form-select>
              <span v-show="errors.has('Mobile country code')" class="help text-danger small">
                {{ errors.first('Mobile country code') }}
              </span>
            </b-col>
            <b-col class="col-12 col-md-5 pl-md-0">
              <b-input-group :prepend="countryCodePrefix(shippingInfo.recipient_mobile_country_code_id)">
                <b-form-input
                  :disabled="isLoading('CountryRelationRecipientCrossCountryLoading')"
                  v-validate="'required|numeric'"
                  name="Recipient Contact"
                  v-model="shippingInfo.recipient_mobile_phone_number"
                  :class="{ input: true, 'border-danger': errors.has('Recipient Contact') }"
                  placeholder="e.g. 127654321"
                  type="number"
                  data-qa="recipient-mobile-number-input"
                />
              </b-input-group>
              <span v-show="errors.has('Recipient Contact')" class="help text-danger small">
                {{ errors.first('Recipient Contact') }}
              </span>
            </b-col>
          </b-row>
        </b-col>
      </b-row>
      <!-- End Recipient info-->
    </b-container>
    <b-modal
      size="sm"
      hide-header
      ok-only
      no-close-on-backdrop
      no-close-on-esc
      class="eshop-model"
      centered
      v-model="showSaveNotice"
    >
      <div>{{ saveNoticeMessage }}</div>
    </b-modal>
  </div>
</template>
<script>
/* eslint-disable vue/no-side-effects-in-computed-properties */
// TODO: Fix 'vue/no-side-effects-in-computed-properties' lint issue
import { mapGetters, mapActions } from 'vuex'
import _ from 'lodash'
import { AddressMixin, PhoneMixin } from '../../mixins'
import md5 from 'md5'

export default {
  name: 'ShippingMethodDelivery',
  mixins: [AddressMixin, PhoneMixin],
  props: {
    shippingInfo: {
      type: Object,
      required: true,
    },
    allowSaveShippingAddress: {
      default: function() {
        return this._shipping_methods_allow_save_shipping_address()
      },
    },
    enableCrossCountry: {
      type: Boolean,
      default: false,
    },
    isAllowedAllCountries: {
      type: Boolean,
      default: false,
    },
    editAddressIndex: {
      type: Number,
    },
    value: {
      type: Object,
    },
    shippingMethodDeliveryClasses: {
      type: Array,
      default: () => [],
    },
    shippingMethodFormFieldRowSizeClasses: {
      type: [Array, String],
      default: () => ['col-lg-8'],
    },
    showShippingEmptyAddressInfo: {
      type: Boolean,
      default: false,
    },
    enableRecipientCrossCountry: {
      type: Boolean,
      default: true,
    },
    addressStyle: {
      type: String,
      default: 'list',
    },
    enableAllCallCodeOption: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      enableMixinInitCheck: false,
      unselectedAddress: { fields: [] },
      localShippingInfo: {},
      addAddressFormVisible: false,
      selectedAddress: { id: null },
      selectedAddressIndex: false,
      countries: [],
      states: [],
      cities: [],
      allCities: [],
      currentAddresses: [],
      addressFields: [],
      loadingAddressFormatData: false,
      loadingData: true,
      totalAddressLength: 0,
      noSelectableAddressOnInit: false,
      saveCheck: false,
      showSaveNotice: false,
      saveNoticeMessage: '',
      preventSaving: false,
      addressesFull: false,
      hideAddBtn: false,
      hideAddressSelection: false,
      initialAddress: null,
      selectInitialAddress: false,
      preSelectedAddressIndex: false,
      recipientContactOptions: [],
      totalAddressExcludeCustomLength: 0,
      oldAddress: {},
    }
  },
  inject: [
    '_shipping_countries',
    '_shipping_methods_allow_save_shipping_address',
    '_general_selected_country_id',
    '_member_country_id',
  ],
  $_veeValidate: {
    validator: 'new', // give new validator scope.
  },
  created() {
    let self = this
    this.$validator.attach({
      name: 'Delivery Method',
      rules: 'required',
      getter: () => {
        let data = self.getData()
        return data !== undefined && data.recipient_addresses !== undefined && data.recipient_addresses.length > 0
      },
    })
  },
  async mounted() {
    this.countries = this._shipping_countries
    this.currentAddresses = []
    this.loadingData = false
    // Enable cross country delivery based on component
    if (this.enableCrossCountry) {
      let query = {
        country_id: this.getAppLocationCountry.countryId,
        relations: ['crossCountry'],
      }
      await this.loadCountryRelation(query)
    }
  },
  methods: {
    ...mapActions([
      'updateMemberDetailsAddress',
      'loadCountryRelation',
      'setShippingMethodBoxHeight',
      'loadCountryRelationRecipientCrossCountry',
    ]),
    collectStyles() {
      this.$nextTick(() => {
        if (this.$refs['address-preview-box'] !== undefined) {
          let height = this.$refs['address-preview-box'].clientHeight
          this.setShippingMethodBoxHeight(height)
        }
      })
    },
    cancelShippingAddress: function() {
      this.addAddressFormVisible = false
    },
    getData: function() {
      let shippingData = _.chain(this.shippingInfo)
        .cloneDeep()
        .pick('recipient_name', 'recipient_mobile_country_code_id', 'recipient_mobile_phone_number')
        .merge({
          recipient_addresses: [this.availableAddress[this.selectedAddressIndex]],
          recipient_selected_shipping_index: this.selectedAddressIndex,
        })
        .value()

      let country =
        shippingData.recipient_addresses[0] === undefined
          ? false
          : shippingData.recipient_addresses[0].fields.find(field => field.key === 'countries')
      if (country && this.allowedShippingCountries.includes(country.value)) {
        return shippingData
      } else {
        shippingData.recipient_addresses = []
        return shippingData
      }
    },
    saveNewShippingAddress: function() {
      this.$validator.validate('*').then(valid => {
        if (valid) {
          let query = {
            address: {
              id: this.shippingInfo.member_addresses_id,
              user_id: this.shippingInfo.user_id,
              address_data: this.shippingInfo.member_addresses,
            },
          }
          this.updateMemberDetailsAddress(query).then(result => {
            if (!result) {
              this.saveNoticeMessage = this.$t('Eshop.Order.Shipping.Method.Delivery.NewAddressSaveErrorNotice')
            } else {
              this.saveNoticeMessage = this.$t('Eshop.Order.Shipping.Method.Delivery.NewAddressSaveSuccessful')
              this.addAddressFormVisible = false
            }
            this.showSaveNotice = true
          })
        }
      })
    },
    toggleAddAddressForm: async function() {
      // look to see if an unselected address was already used before, if not use the unfilled address from the address list
      let unselectedIndex =
        this.editAddressIndex > -1
          ? this.editAddressIndex
          : this.addresses.findIndex(address => address.unselected === true)

      if (unselectedIndex === -1) {
        if (this.allowSaveShippingAddress) {
          unselectedIndex = this.getNexUnfilledAddressIndex()
        }
      }
      // if all addresses are filled use a temporary address
      if (unselectedIndex === -1) {
        // all addresses are filled, cannot save address anymore
        this.addressesFull = true
        await this.loadDynamicAddress(this._general_selected_country_id())
        unselectedIndex = this.selectedAddress
      }
      if (unselectedIndex !== -1) {
        this.unselectedAddress = this.addresses[unselectedIndex]
        // make the address unselected to use next time when the address is attached
        this.unselectedAddress.unselected = true
        this.setSelectedAddress(unselectedIndex)
        let unselectedAddressCountry = this.unselectedAddress.fields.find(field => {
          return field.key === 'countries' && (field.value !== '' || field.value !== null)
        })
        if (unselectedAddressCountry) {
          this.selectedCountry = unselectedAddressCountry.value
        } else {
          this.selectedCountry = this._general_selected_country_id()
          this.formFieldChanged({ key: 'countries' }, this.selectedCountry)
        }
        this.addAddressFormVisible = !this.addAddressFormVisible
        this.collectStyles()
      }
    },
    selectCurrentAddress: function(index) {
      this.selectInitialAddress = false
      this.selectedAddressIndex = index
    },
    async setRecipientCountries(index = false) {
      let currentAddressSelectedCountryID = this.findAddressCountryId(
        this.$helpers.getValue(this.availableAddress, `[${index || this.selectedAddressIndex}]`)
      )
      if (this.enableRecipientCrossCountry && currentAddressSelectedCountryID) {
        let query = {
          country_id: currentAddressSelectedCountryID,
          relations: ['recipientCrossCountry'],
        }
        if (
          this.shippingInfo.recipient_mobile_country_code_id !== '' &&
          this.shippingInfo.recipient_mobile_country_code_id !== currentAddressSelectedCountryID &&
          !this.enableAllCallCodeOption
        ) {
          this.shippingInfo.recipient_mobile_phone_number = ''
          this.shippingInfo.recipient_mobile_country_code_id = null
        }
        await this.loadCountryRelationRecipientCrossCountry(query)
      }
      let ids = [currentAddressSelectedCountryID, ...this.crossCountryRecipientCountryIDs]
      // wait for country list fully loaded
      await this.initPhoneMixin()
      let callCode = [...this.callCountryList]
      if (!this.enableAllCallCodeOption) {
        // filter call code as per address
        callCode = callCode.filter(x => ids.includes(x.value))
      }
      this.recipientContactOptions = callCode
    },
  },
  computed: {
    ...mapGetters([
      'getAppLocationCountry',
      'crossCountryDeliveryCountryIDs',
      'getAllCountries',
      'getShippingMethodBoxHeight',
      'crossCountryRecipientCountryIDs',
      'isLoading',
      'hasLoaded',
    ]),
    memberAddresses() {
      // Get initial address if updatable component using this component
      if (this.initialAddress === null) {
        let selectedAddress = this.$helpers.getValue(this.shippingInfo, 'selected_address')
        if (selectedAddress) {
          this.initialAddress = _.cloneDeep(selectedAddress)
          this.oldAddress = _.cloneDeep(this.initialAddress)
          this.selectInitialAddress = true
        }
      }
      if (Array.isArray(this.shippingInfo.member_addresses)) {
        this.addresses = this.shippingInfo.member_addresses
        if (this.initialAddress) {
          let initAddressIndex = null
          let initialAddress = this.getAddressString(this.initialAddress)
          if (initialAddress !== '') {
            initAddressIndex = _.findIndex(this.addresses, address => {
              let currentAddress = this.getAddressString(address)
              return md5(currentAddress) === md5(initialAddress)
            })
          }
          if (initAddressIndex === -1) {
            this.initialAddress.title = 'Custom Address'
            this.addresses.push({ ...this.initialAddress, unselected: true, initAddress: true, custom: true })
          } else if (initAddressIndex !== null) {
            this.addresses[initAddressIndex].initAddress = true
          }
        }
        this.initMixin(true, false)
        return this.getFilledAddresses()
      }
      return this.currentAddresses
    },
    availableAddress() {
      let self = this

      // Copying member default addresses
      let addresses = self.memberAddresses

      // Filtering allowed countries by marking as exclude=true if not qualified
      addresses.forEach((address, idx) => {
        if (
          !self.isLoading('CountryRelationStateLoading') &&
          self.hasLoaded('CountryRelationStateLoading') &&
          self.allowedShippingCountries.includes(self.findAddressCountryId(address)) === false
        ) {
          addresses[idx].exclude = true
        } else {
          if (addresses[idx].exclude !== undefined) {
            // revert back if eligible address has exclude key
            addresses[idx].exclude = false
          }
        }
      })

      // Setting initial address index by identifying initAddress= true
      let initAddressIndex = _.findIndex(addresses, function(address) {
        return address.initAddress === true && (address.exclude === undefined || address.exclude !== true)
      })

      // From above exclusion check how many selectable addresses available
      let selectableAddress = addresses.filter(address => address.exclude === undefined || !address.exclude)
      this.totalAddressLength = selectableAddress.length

      // Applying detailed conditions by separating possible available conditions to select
      // correct selected index based various cases
      // ** Main logic to apply selectedAddressIndex
      if (this.selectInitialAddress && initAddressIndex !== -1) {
        this.selectInitialAddress = false
      } else {
        if (this.selectedAddressIndex === false) {
          this.selectedAddressIndex = initAddressIndex !== -1 ? initAddressIndex : false
        }
      }

      // If selectedAddressIndex falL under excluded address change back to available address
      if (this.$helpers.getValue(addresses, `[${this.selectedAddressIndex}].exclude`) === true) {
        this.selectedAddressIndex = _.findIndex(addresses, function(address) {
          return address.exclude === undefined || !address.exclude
        })
      }

      // if custom address selected this index will be applied to selectedAddressIndex
      if (this.addAddressFormVisible === true) {
        let currentCustomAddressIndex = _.findIndex(addresses, function(address) {
          return (
            (((address.custom !== undefined && address.custom === true) ||
              (address.unselected !== undefined && address.unselected === true)) &&
              address.exclude === undefined) ||
            address.exclude === false
          )
        })
        if (currentCustomAddressIndex !== -1) {
          this.totalAddressExcludeCustomLength = this.totalAddressLength - 1
          this.selectedAddressIndex = currentCustomAddressIndex
        } else {
          // do if old address exists & is a custom address
          if (Object.keys(this.oldAddress).length > 0 && this.oldAddress.custom) {
            // update to old selected address if user made changes but close the address form with validation error
            let oldAddress = { ..._.cloneDeep(this.oldAddress), unselected: true, initAddress: true, custom: true }
            // Push old address to local addresses array
            this.selectedAddressIndex = addresses.push(oldAddress) - 1
            let editedCustomAddressIndex = _.findIndex(this.addresses, { custom: true })
            if (editedCustomAddressIndex !== -1) {
              // Remove edited address from mixin addresses & push old address
              this.addresses.splice(editedCustomAddressIndex, 1)
              this.addresses.push(oldAddress)
            }
          }
        }
      }

      // If all other conditions skipped or default case where initial address not available or
      // no address being selected this will apply selectedAddressIndex
      let hasSelectableAddressIndex = _.findIndex(addresses, function(address) {
        return (
          address.initAddress === true ||
          (address.custom === true && (address.exclude === undefined || !address.exclude))
        )
      })

      if (
        this.selectedAddressIndex === false &&
        hasSelectableAddressIndex === -1 &&
        initAddressIndex === -1 &&
        this.addressMixinInitialized
      ) {
        this.selectedAddressIndex = _.findIndex(addresses, function(address) {
          return address.exclude === undefined || !address.exclude
        })
      } else if (
        this.selectedAddressIndex === false &&
        hasSelectableAddressIndex !== -1 &&
        addresses[hasSelectableAddressIndex].custom === true
      ) {
        this.selectedAddressIndex = hasSelectableAddressIndex
      }

      // Handling custom form visibility and custom form assignments
      if (this.addressMixinInitialized && this.addAddressFormVisible === false && this.totalAddressLength === 0) {
        this.toggleAddAddressForm()
        this.noSelectableAddressOnInit = true
      }
      return addresses
    },
    isCrossCountryDeliveryAvailable() {
      if (this.isAllowedAllCountries) {
        return true
      }
      return this.allowedShippingCountries.length > 1
    },
    allowedShippingCountries() {
      if (this.isAllowedAllCountries) {
        return _.map(this.getAllCountries, 'id')
      } else {
        return [this.getAppLocationCountry.countryId, ...this.crossCountryDeliveryCountryIDs]
      }
    },
    disableSaving() {
      return (
        this.preventSaving ||
        this.$helpers.getValue(this.addresses, `[${this.selectedAddressIndex}].title`, '') === 'Custom Address'
      )
    },
    myAccountLink() {
      return this.$router.resolve({ name: 'MyAccount' }).route.path
    },
    getSelectedAddress() {
      return this.$helpers.getValue(this.availableAddress, `[${this.selectedAddressIndex}]`, {})
    },
    getSelectedAddressPreview() {
      return this.getAddressString(this.getSelectedAddress, true)
    },
    getBoxStyle() {
      return { minHeight: this.getShippingMethodBoxHeight + 'px' }
    },
    isAddressStyleList() {
      return this.addressStyle === 'list'
    },
    hasEditableAddress() {
      let hasCustomIndex = this.availableAddress.findIndex(address => address.custom === true)
      let hasUnselectedIndex = this.availableAddress.findIndex(address => address.unselected === true)
      return {
        status: hasCustomIndex !== -1 || hasUnselectedIndex !== -1,
        custom: { status: hasCustomIndex !== -1, index: hasCustomIndex },
        unselected: { status: hasUnselectedIndex !== -1, index: hasUnselectedIndex },
      }
    },
  },
  watch: {
    shippingInfo: {
      handler() {
        // Prevent saving if address full
        this.preventSaving = this.addressesFull
        this.$emit('input', this.getData())
        this.collectStyles()
      },
      deep: true,
    },
    selectedAddressIndex: {
      async handler() {
        this.$emit('input', this.getData())
        await this.setRecipientCountries()
        this.collectStyles()
      },
      deep: true,
    },
    async currentSelectedCountryId() {
      await this.setRecipientCountries()
    },
  },
}
</script>
