<template>
  <div>
    <b-container class="overflow-x-auto overflow-y-auto">
      <b-row class="my-2 mt-4">
        <b-col class="col-lg-3 col-sm-12 pt-2 text-nowrap">
          <label class="required">
            {{ $t('Eshop.Order.Shipping.Method.Delivery.RecipientName') }}
          </label>
        </b-col>
        <b-col class="col-lg-6 col-sm-10 col-12">
          <b-form-input
            v-validate="'required'"
            name="Recipient Name"
            v-model="recipientName"
            :class="{ input: true, 'text-danger': errors.has('Recipient Name') }"
            type="text"
          />
          <span v-show="errors.has('Recipient Name')" class="text-danger small">
            {{ errors.first('Recipient Name') }}
          </span>
        </b-col>
      </b-row>
      <b-row class="my-2 mb-4">
        <b-col class="col-lg-3 col-sm-12 col-10 pt-2 text-nowrap">
          <label class="required">
            {{ $t('Eshop.Order.Shipping.Method.Delivery.RecipientContact') }}
          </label>
        </b-col>
        <b-col class="pl-lg-3 col-lg-2 col-md-5 col-5">
          <b-form-select v-model="mobileCode">
            <option value="null" disabled>
              {{ $t('OrderHistory.Detail.eVoucher.Select') }}
            </option>
            <option v-for="(code, idx) in getMobileCountriesCodes" :value="code.value" :key="idx">
              {{ code.text }}
            </option>
          </b-form-select>
        </b-col>
        <b-col class="pl-1 pr-3 col-lg-4 col-sm-5 col-7">
          <b-form-input
            v-validate="'required|numeric'"
            name="Recipient Contact"
            v-model="phoneNumber"
            :class="{ input: true, 'text-danger': errors.has('Recipient Contact') }"
            placeholder="e.g. 123456789"
            type="number"
          />
          <span v-show="errors.has('Recipient Contact')" class="text-danger small">
            {{ errors.first('Recipient Contact') }}
          </span>
        </b-col>
      </b-row>
      <div class="row small">
        <div class="col voucher-address-list">
          <b-list-group class="py-1">
            <div
              v-for="(address, idx) in getExistingAddress"
              :key="idx"
              :id="address.addressId"
              class="row no-gutters w-100 justify-content-between"
            >
              <b-list-group-item
                button
                :class="{ active: address.addressId == selected }"
                @click="setRecipientData(address.addressId)"
                class=""
                :title="getTooltip(address)"
              >
                <icon v-if="selected === address.addressId" class="text-primary border-primary" name="selected-icon" />
                <icon v-else class="text-hide" name="selected-icon" />
                <span class="pl-2">
                  {{ address.streetName }}, {{ address.postCode }} {{ address.city }}, {{ address.state }}
                </span>
              </b-list-group-item>
              <b-btn variant="link" @click="removeAddress(address.addressId)" class="text-dark">
                <icon name="remove-icon" class="icon-size-3" />
              </b-btn>
            </div>
          </b-list-group>
        </div>
      </div>
      <b-row class="my-4">
        <b-col>
          <div class="font-weight-bold">
            <b-link @click="toggleActive()">
              <icon v-if="activate" name="eshop-minus" class="icon-size-3 align-middle pr-1" />
              <icon v-else name="eshop-plus" class="icon-size-3 align-middle pr-1" />
              {{ $t('Eshop.Order.Shipping.Method.Delivery.AddAnotherAddress') }}
            </b-link>
          </div>
        </b-col>
      </b-row>
      <div v-if="activate">
        <b-row class="my-1 pt-2">
          <b-col>
            <label class="required">
              {{ $t('Eshop.Order.Shipping.Method.Delivery.AddressLine1') }}
            </label>
          </b-col>
          <b-col sm="6">
            <b-form-input
              v-validate="'required'"
              name="Address Line 1"
              v-model="address1"
              :class="{ input: true, 'text-danger': errors.has('Address Line 1') }"
              type="text"
            />
            <span v-show="errors.has('Address Line 1')" class="text-danger small text-nowrap">
              {{ errors.first('Address Line 1') }}
            </span>
          </b-col>
        </b-row>
        <b-row class="my-1 pt-2">
          <b-col>
            <label> {{ $t('Eshop.Order.Shipping.Method.Delivery.AddressLine2') }}</label>
          </b-col>
          <b-col sm="6">
            <b-form-input name="Address Line 2" v-model="address2" type="text" />
          </b-col>
        </b-row>
        <b-row class="my-1 pt-2">
          <b-col>
            <label> {{ $t('Eshop.Order.Shipping.Method.Delivery.AddressLine3') }}</label>
          </b-col>
          <b-col sm="6">
            <b-form-input name="Address Line 3" v-model="address3" type="text" />
          </b-col>
        </b-row>
        <b-row class="my-1 pt-2">
          <b-col>
            <label> {{ $t('Eshop.Order.Shipping.Method.Delivery.AddressLine4') }}</label>
          </b-col>
          <b-col sm="6">
            <b-form-input name="Address Line 4" v-model="address4" type="text" />
          </b-col>
        </b-row>
        <b-row class="my-1 pt-2">
          <b-col>
            <label class="required">
              {{ $t('Eshop.Order.Shipping.Method.Delivery.ZipCode') }}
            </label>
          </b-col>
          <b-col sm="6">
            <b-form-input
              v-validate="'required|numeric'"
              name="Zip Code"
              v-model="zipcode"
              :class="{ input: true, 'text-danger': errors.has('Zip Code') }"
              type="text"
            />
            <span v-show="errors.has('Zip Code')" class="text-danger small text-nowrap">
              {{ errors.first('Zip Code') }}
            </span>
          </b-col>
        </b-row>
        <b-row class="my-1">
          <b-col class="address-lbl">
            <label class="required">
              {{ $t('Eshop.Order.Shipping.Method.Delivery.Country') }}
            </label>
          </b-col>
          <b-col sm="6">
            <b-form-select
              v-validate="'required'"
              v-model="country"
              name="Country"
              :class="{ 'text-danger': errors.has('Country') }"
              @change="setStates"
            >
              <option value="null" disabled>
                {{ $t('Eshop.Order.GlobalWords.SelectCountry') }}
              </option>
              <option v-for="(countryData, countryIdx) in getCountries" :value="countryData.value" :key="countryIdx">
                {{ countryData.text }}
              </option>
            </b-form-select>
            <span v-show="errors.has('Country')" class="text-danger small text-nowrap">
              {{ errors.first('Country') }}
            </span>
          </b-col>
        </b-row>
        <b-row class="my-1">
          <b-col class="address-lbl">
            <label class="required">
              {{ $t('Eshop.Order.Shipping.Method.Delivery.State') }}
            </label>
          </b-col>
          <b-col sm="6">
            <b-form-select
              v-validate="'required'"
              v-model="state"
              name="State"
              :class="{ 'text-danger': errors.has('State') }"
              @change="setCities"
            >
              <option value="null" disabled>
                {{ $t('Eshop.Order.GlobalWords.SelectState') }}
              </option>
              <option v-for="(stateData, stateIdx) in states" :value="stateData.id" :key="stateIdx">
                {{ stateData.name }}
              </option>
            </b-form-select>
            <span v-show="errors.has('State')" class="text-danger small text-nowrap">
              {{ errors.first('State') }}
            </span>
          </b-col>
        </b-row>
        <b-row class="my-1">
          <b-col class="address-lbl">
            <label class="required">
              {{ $t('Eshop.Order.Shipping.Method.Delivery.City') }}
            </label>
          </b-col>
          <b-col sm="6">
            <b-form-select
              v-validate="'required'"
              v-model="city"
              name="City"
              :class="{ 'text-danger': errors.has('City') }"
            >
              <option value="null" disabled>
                {{ $t('Eshop.Order.GlobalWords.SelectCity') }}
              </option>
              <option v-for="(cityData, cityIdx) in cities" :value="cityData.id" :key="cityIdx">
                {{ cityData.name }}
              </option>
            </b-form-select>
            <span v-show="errors.has('City')" class="text-danger small text-nowrap">
              {{ errors.first('City') }}
            </span>
          </b-col>
        </b-row>
        <b-row class="my-3">
          <b-col class="address-lbl" />
          <b-col sm="6">
            <b-btn
              v-model="saveCheck"
              variant="primary"
              @click="validateInputs"
              :disabled="getExistingAddress.length === 4"
            >
              {{ $t('Eshop.Order.Shipping.Method.Delivery.SaveShippingAddress') }}
            </b-btn>
            <div v-if="this.getExistingAddress.length === 4" class="text-danger small text-nowrap">
              {{ $t('Eshop.Order.GlobalWords.ShippingAddressMaxReached', { max: 4 }) }}
            </div>
          </b-col>
        </b-row>
      </div>
    </b-container>
  </div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'OrderHistoryEvoucherShippingDelivery',
  components: {},
  props: ['memberData'],
  data() {
    return {
      recipientName: '',
      mobileCode: 60,
      phoneNumber: '',
      selected: null,
      activate: false,
      saveCheck: false,
      address1: '',
      address2: '',
      address3: '',
      address4: '',
      zipcode: '',
      country: null,
      state: null,
      city: null,
      states: [],
      cities: [],
    }
  },
  methods: {
    ...mapActions('orderhistory', ['setSalesVoucherRedemptionStatus']),
    ...mapActions(['addShippingAddress', 'setRecipientDetail', 'removeShippingAddress']),
    getTooltip(address) {
      return address.streetName + ', ' + address.postCode + ', ' + address.city + ', ' + address.state
    },
    removeAddress: function(addressId) {
      this.removeShippingAddress(addressId)
    },
    setRecipientData(addressId) {
      this.$validator.validateAll().then(valid => {
        if (valid) {
          this.selected = addressId
          let addr = []
          this.getExistingAddress.forEach(address => {
            if (address.addressId === addressId) {
              addr = address
            }
          })
          let data = {
            name: this.recipientName,
            contact: this.mobileCode + this.phoneNumber,
            address: addr,
          }
          this.setRecipientDetail(data)
        }
      })
    },
    toggleActive: function() {
      this.activate = !this.activate
    },
    resetAll() {
      this.address1 = ''
      this.address2 = ''
      this.address3 = ''
      this.address4 = ''
      this.zipCode = ''
      this.country = this.getSelectedCountry.id
      this.state = null
      this.city = null
      this.cities = []
      this.activate = false
      this.errors.clear()
    },
    setStates: function(val) {
      this.states = this.getStateListByCountryId(val)
      this.state = null
      this.errors.clear()
    },
    setCities: function(val) {
      this.cities = null
      let states = this.getStateListByCountryId(this.country)
      states.forEach(state => {
        if (state.id === val) {
          this.cities = state.cities
        }
      })
      this.city = null
      this.errors.clear()
    },
    validateInputs: function() {
      this.$validator.validateAll().then(valid => {
        if (valid) {
          let data = {
            addressId: this.getExistingAddress.length + 1,
            streetName: this.address1 + ', ' + this.address2,
            postCode: this.zipcode,
            city: this.getCityName(this.city),
            state: this.getStateName(this.state),
            countryId: this.country,
          }
          this.addShippingAddress(data)
          this.resetAll()
        }
      })
    },
    getStateName: function(stateId) {
      this.states.forEach(state => {
        if (state.id === stateId) {
          return state.name
        }
      })
    },
    getCityName: function(cityId) {
      this.cities.forEach(city => {
        if (city.id === cityId) {
          return city.name
        }
      })
    },
    setPrefillRecipientDetails() {
      if (this.memberData !== null || typeof this.memberData !== 'undefined') {
        this.recipientName = this.memberData.details.translated_name
        if (this.memberData.contact_info.preferred_contact_id === 248) {
          this.phoneNumber = this.memberData.contact_info.mobile_1_num
          this.selected = this.getExistingAddress[0].addressId
          this.setRecipientData(this.getExistingAddress[0].addressId)
        }
      }
    },
  },
  mounted() {
    this.country = this.getSelectedCountry.id
    this.setStates(this.country)
    this.setPrefillRecipientDetails()
  },
  computed: {
    ...mapGetters([
      'getCountries',
      'getSelectedCountry',
      'getStates',
      'getStateListByCountryId',
      'getExistingAddress',
      'getMobileCountriesCodes',
    ]),
    ...mapGetters(['getMemberDetails']),
  },
}
</script>
