<template>
  <div :class="shippingMethodSelfCollectionClasses">
    <b-container fluid class="p-0">
      <b-row>
        <b-col>
          <label class="required">
            {{ $t('Eshop.Order.Shipping.Method.SelfCollection.CollectionPoint') }}
          </label>
        </b-col>
      </b-row>
      <b-row no-gutters v-if="isLoading(['locationsLoadStockistLocations'])" class="justify-content-center">
        <icon class="icon-size-3" name="spinner" pulse />
      </b-row>
      <b-row no-gutters v-else>
        <b-col class="col-12 col-md-7 pl-0">
          <b-form-select
            v-validate="'required'"
            v-model="state"
            name="area"
            id="select-state"
            data-qa="self-collection-point-select"
            :state="!errors.has('area') && null"
          >
            <option value="null" disabled>
              {{ $t('Eshop.Order.GlobalWords.SelectCollectionPoint') }}
            </option>
            <option v-for="(stateData, idx) in states" :value="stateData.location_id" :key="idx">
              {{ stateData.name }}
            </option>
          </b-form-select>
          <span v-show="errors.has('area')" class="help text-danger small">
            {{ errors.first('area') }}
          </span>
        </b-col>
        <b-col class="d-flex justify-content-center flex-column align-items-start">
          <icon v-if="loadingCities" name="spinner" pulse class="text-primary icon-size-2 ml-2" />
        </b-col>
      </b-row>
      <b-row v-if="getEformLinkData !== undefined">
        <b-col md="8" class="mt-3 text-weight-bold">
          <b-button variant="link" @click="checkLocationPointList" class="p-0">
            {{ $t('Eshop.Order.Shipping.Method.SelfCollection.CheckLocationPointList') }}
          </b-button>
        </b-col>
      </b-row>
      <div class="d-flex justify-content-center align-items-center py-3" v-if="loadingAddresses">
        <icon class="icon-size-4" name="spinner" pulse />
      </div>
      <div v-else>
        <span class="help text-danger small"> {{ errors.first('collection point') }}&nbsp; </span>
        <b-list-group class="mt-2">
          <b-row
            class="no-gutters list-group-row mb-4"
            v-for="(point, idx) in addresses"
            :key="idx"
            @click="selectCollectionPoint(point)"
          >
            <b-col class="pl-0">
              <b-list-group-item
                button
                :class="{ active: point.id === selected, 'border-danger': errors.has('collection point') }"
                class="animated fadeIn bg-transparent text-black"
              >
                <div class="no-gutters">
                  <div class="p-1">
                    <strong v-if="point.name !== ''" class="text-uppercase"> [ {{ point.name }} ]<br /> </strong>
                  </div>
                  <div class="p-1 wrap text-uppercase">
                    {{ getAddressString(point) }}
                  </div>
                  <div class="p-1 pt-3 wrap text-uppercase">
                    {{ $t('Eshop.Order.OrderConfirmationList.Tel') }} : {{ phoneString(point) }}
                  </div>
                </div>
              </b-list-group-item>
            </b-col>
          </b-row>
        </b-list-group>
      </div>
    </b-container>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import { AddressMixin, PhoneMixin } from '../../mixins'
import helpers from '@/helpers'
import _ from 'lodash'

export default {
  name: 'ShippingMethodSelfCollection',
  mixins: [AddressMixin, PhoneMixin],
  props: {
    shippingInfo: {
      type: Object,
      required: true,
    },
    shippingMethodSelfCollectionClasses: {
      type: Array,
      default: () => [],
    },
  },
  $_veeValidate: {
    validator: 'new',
  },
  inject: {
    /**
     * Get cities for a given state
     *
     * @param stateId
     * @return function ({ state_id: int }) : Promise() :
     * [
     *  {
     *    value: int id,
     *    text: string name
     *  }
     *  ...
     * ]
     */
    _self_pickup_load_cities_for_state: {
      default: () => {
        return function(payload) {
          return Promise.resolve(this.getStockistCitiesByState(payload.state_id))
        }
      },
    },
    /**
     * Load stockist address list
     * @typedef {
     *     {int}    id           Id of the address
     *     {int}    state_id     Name of the state
     *     {int}    city_id      Name of the city
     *     {string} mobileNo     Mobile number
     *     {string} telNo        Tell number
     *     {object} address_data Address object
     * } Address
     * @param {object} payload
     * @param {int}    payload.state_id The state id
     * @param {int}    payload.city_id  The city id
     * @return Promise<Array<Address>>
     */
    _self_pickup_load_stockist_address_list: {},
    // $validator: {},
  },
  data() {
    return {
      loadingCities: false,
      loadingAddresses: false,
      localShippingInfo: null,
      state: null,
      city: null,
      states: [],
      cities: [],
      allCities: [],
      collectionPoint: [],
      selected: null,
    }
  },
  async mounted() {
    let self = this
    await this.resolveMasters.then(() => {
      this.getEformLink([self.stockistListId])
    })
    this.localShippingInfo = JSON.parse(JSON.stringify(this.shippingInfo))
    this.loadStockistStateAndCities(this.getAppLocationCountry.countryId)
      .then(() => {
        self.states = _.orderBy(self.getStockistStatesByCountry(self.getAppLocationCountry.countryId), 'name', 'asc')
      })
      .then(() => {
        if (helpers.isSet(this.localShippingInfo, 'self_collection_city_id')) {
          self.state = this.localShippingInfo.self_collection_city_id
        }
        if (helpers.isSet(this.localShippingInfo, 'self_collection_location_id')) {
          this.selected = this.localShippingInfo.self_collection_location_id
        }
      })
  },
  methods: {
    ...mapActions(['loadStockistStateAndCities', 'getEformLink']),
    stateChange: function(stateId) {
      this.cities = []
      this.city = null
      this.loadingCities = true
      this._self_pickup_load_cities_for_state({ state_id: stateId }).then(cities => {
        this.cities = cities
        this.loadingCities = false
      })
    },
    phoneString: function(point) {
      return [
        this.phoneNumber(point.mobile_phone_code_id, point.mobile_phone_num),
        this.phoneNumber(point.telephone_code_id, point.telephone_num),
      ]
        .filter(num => !this.$helpers.isEmpty(num))
        .join(', ')
    },
    getData: function() {
      return {
        self_collection_point_id: this.selected,
        self_collection_city_id: this.state,
      }
    },
    selectCollectionPoint: function(collectionPoint) {
      if (collectionPoint === null) {
        this.localShippingInfo.self_collection_location_id = null
      } else {
        this.selected = collectionPoint.id
        this.localShippingInfo.self_collection_location_id = collectionPoint.id
      }
    },
    checkLocationPointList: function() {
      if (this.getEformLinkData !== undefined) {
        window.open(this.getEformLinkData.link)
      }
    },
  },
  computed: {
    ...mapGetters(['isLoading', 'getEformLinkData']),
    ...mapGetters([
      'getSelectedCountry',
      'getEsacStateCityData',
      'getEsacLocationAddressData',
      'getEsacActiveCountryData',
      'getStockistCitiesByState',
      'getStockistStatesByCountry',
      'getAppLocationCountry',
    ]),
    ...mapMasterDataId({
      SMART_LIBRARY_EFORM_FILE_TYPE: {
        stockistListId: 'STOCKIST_LIST',
      },
    }),
  },
  watch: {
    _self_pickup_states(to) {
      this.state = this._self_pickup_states
    },
    state() {
      let self = this
      if (!this.$helpers.isEmpty(this.state)) {
        self.selected = null
        this.loadingAddresses = true
        this._self_pickup_load_stockist_address_list({
          location_id: this.state,
        }).then(addresses => {
          if (addresses.length > 0) {
            self.selected = addresses[0].id
            self.addresses = _.map(addresses, address => {
              address.fields = self.$helpers.getValue(address, 'address_data[0].fields') || []
              return address
            })
            self.initMixin(true, false)
          }
          this.loadingAddresses = false
        })
      } else {
        self.addresses = []
      }
    },
    selected() {
      this.errors.remove('collection point')
      this.$emit('input', this.getData())
    },
  },
}
</script>
