<template>
  <tabs-template>
    <div v-for="(address, index) in addresses" :key="index">
      <b-card no-body class="mb-2 mx-md-4 mx-0 eshop">
        <b-card-header header-tag="header" class="bg-gray-200 p-0 p-md-1" role="tab">
          <div
            block
            href="#"
            v-b-toggle="errorAddressIndex.includes(index) ? '' : 'accordion-' + index"
            class="pt-2 pl-3 c-pointer"
          >
            <icon
              name="dashboard-arrow-down"
              :class="{ 'mt-2': true, 'text-medium': true, 'rotate-ac-180': index === selectedAddress && expanding }"
              class="mr-2"
            />
            <label class="font-weight-bold c-pointer">
              {{ $t('Dynamic.Address.' + $helpers.capitalCase(address.title)) }}
            </label>
            :
            <label class="c-pointer">
              {{ getAddressString(address) }}
            </label>
          </div>
        </b-card-header>
        <b-collapse
          :id="`accordion-${index}`"
          accordion="my-accordion"
          :class="{ 'd-block': errorAddressIndex.includes(index) }"
          @show="showCollapse(index, `address_${index}`)"
          @hide="hideCollapse"
        >
          <b-card-body>
            <div
              v-for="(field, index2) in sortDynamicFieldsCountryStateCityTop(address.fields)"
              :key="index2"
              class="row pb-2"
            >
              <label
                class="col-8 col-md-2 pl-0 pl-md-4 d-flex align-items-center m-0 text-capitalize"
                :class="{ required: field.required }"
              >
                {{ (tLabel = $t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label)) }}
              </label>
              <component
                :is="fieldTypes.get(field.type)"
                v-bind="fieldComponent(field, index)"
                :data-vv-scope="`address_${index}`"
                v-model="addresses[index].fields[setDynamicFieldIndex(addresses[index].fields, field.index)].value"
                @change="formFieldChanged(field, $event)"
                :options="getFieldOptionsData(index, field)"
                v-validate="fieldValidations(field)"
                :class="{ 'is-danger': errors.has(`address_${index}.` + field.label) }"
                :name="tLabel"
                :disabled="isFieldLoading(field) || addressRulesChecker(index, 'addresses_compulsory_indices')"
                :readonly="isFieldLoading(field) || addressRulesChecker(index, 'addresses_compulsory_indices')"
                class="col-12 col-md-5"
              />
              <component
                :is="'span'"
                v-show="errors.has(`address_${index}.` + field.label)"
                class="col-12 col-md-5 help text-danger pt-2"
              >
                {{ errors.first(`address_${index}.` + field.label) }}
              </component>
            </div>
            <button
              v-if="!addressRulesChecker(index, 'addresses_compulsory_indices') && address.fields.length > 0"
              class="btn btn-primary"
              v-b-toggle="'accordion-' + index"
              @click="handleClickClearAddress(index)"
            >
              {{ $t('Common.Clear') }}
            </button>
          </b-card-body>
        </b-collapse>
      </b-card>
    </div>
    <b-row class="py-3 pr-4" v-if="!isLoading(['myAccountInfo', 'locationStateLoading', 'getDynamicContent'])">
      <b-col class="text-md-right text-left">
        <button class="btn btn-primary" @click="saveAddressData" :disabled="savingAddressData">
          <icon name="spinner" pulse v-if="savingAddressData" />
          <template v-else>
            {{ $t('MyAccount.Address.SaveChanges') }}
          </template>
        </button>
      </b-col>
    </b-row>
    <b-modal ref="changeAddressModal" class="eshop-model" ok-only size="sm" hide-header centered>
      <h5 v-if="responseStatus">
        {{ $t('MyAccount.PersonalInfo.SaveChanges.Success') }}
      </h5>
      <h5 v-else>
        {{ $t('MyAccount.PersonalInfo.SaveChanges.Failed') }}
      </h5>
    </b-modal>

    <b-modal ref="saveAddressModal" class="eshop-model" ok-only size="sm" hide-header centered>
      <h5>{{ $t('MyAccount.EwalletSettings.PleaseFillRequiredFiled') }}</h5>
    </b-modal>
  </tabs-template>
</template>
<script>
import { mapGetters, mapMutations, mapActions } from 'vuex'
import MyAccountTabsTemplate from './templates/MyAccountTabsTemplate'
import { AddressMixin } from '@/app/_global/mixins'

import _ from 'lodash'
export default {
  name: 'AddressInfo',
  mixins: [AddressMixin],
  components: {
    TabsTemplate: MyAccountTabsTemplate,
  },
  $_veeValidate: {
    validator: 'new',
  },
  data() {
    return {
      markDefault: 'not_accepted',
      profilePicture: '/static/misc/img-default-male.png',
      activeAddressIndex: 0,
      sameAddressStatus: false,
      selectedShipping: '',
      responseStatus: true,
      savingAddressData: false,
      localMemberDetails: {
        address: {
          id: null,
          user_id: null,
          address_data: null,
        },
      },
      fieldTypes: new Map([
        ['input', 'b-form-input'],
        ['select', 'b-form-select'],
      ]),
      collapsed: false,
      collapsing: false,
      expanding: false,
      filledAddresses: null,
      unfilledIndex: null,
      unfilled: [],
      currentScopeName: 'address_0',
      errorAddressIndex: [],
    }
  },
  created() {
    this.master.keys = ['addresses_compulsory_indices']
    this.master.country_id = this.getSelectedCountryId
    this.loadCities()
  },
  methods: {
    ...mapActions([
      'loadMyAccountCountries',
      'loadStates',
      'loadCities',
      'updateMemberDetailsAddress',
      'loadCountryDynamicContent',
    ]),
    ...mapMutations(['SET_MY_ACCOUNT_COUNTRY_ID']),
    handleClickClearAddress(index) {
      this.addresses[index].fields = []
    },
    showCollapse(index, scopename) {
      this.selectedAddress = index
      this.expanding = true
      this.currentScopeName = scopename
      this.errors.items = []
      if (this.addresses[index].fields.length <= 0) {
        this.formFieldChanged({ key: 'countries' }, this.getMyAccountMemberDetails.details.country_id)
      }
    },
    hideCollapse() {
      this.expanding = false
    },
    fieldChangedLocal(field, value) {
      this.initMixin(true, false)
      this.formFieldChanged(field, value)
    },
    async saveAddressData() {
      this.savingAddressData = true
      this.errorAddressIndex = []
      this.localMemberDetails.address.user_id = this.getMyAccountMemberDetails.address.user_id
      this.localMemberDetails.address.address_data = this.addresses
      let hasNoError = false
      for (let i = 0; i < this.addresses.length; i++) {
        let doValidation = false
        for (let x = 0; x < this.addresses[i].fields.length; x++) {
          if (this.addresses[i].fields[x].value !== '') {
            doValidation = true
          }
        }
        if (doValidation) {
          hasNoError = await this.$validator.validate('address_' + i + '.*')
          if (!hasNoError) {
            this.errorAddressIndex.push(i)
          }
        }
      }
      if (!this.errorAddressIndex.length > 0) {
        if (this.currentScopeName === 'unfilledScope') {
          hasNoError = await this.$validator.validate('unfilledScope.*')
          if (hasNoError) {
            this.saveAddress()
          } else {
            this.errorAddressIndex.push(this.unfilledIndex)
            this.$refs.saveAddressModal.show()
            this.savingAddressData = false
          }
        } else {
          this.saveAddress()
        }
      } else {
        this.$refs.saveAddressModal.show()
        this.savingAddressData = false
      }
    },
    saveAddress() {
      this.updateMemberDetailsAddress(this.localMemberDetails).then(result => {
        this.savingAddressData = false
        if (!result) {
          this.responseStatus = false
        } else {
          this.addresses = []
          this.localMemberDetails.address.id = this.getMyAccountMemberDetails.address.id
          this.localMemberDetails.address.user_id = this.getMyAccountMemberDetails.address.user_id
          this.localMemberDetails.address.address_data = _.cloneDeep(
            this.getMyAccountMemberDetails.address.address_data
          )
          this.initAddressMixin()
        }
        this.$refs.changeAddressModal.show()
      })
    },
    initAddressMixin() {
      if (Array.isArray(this.localMemberDetails.address.address_data) && this.addresses.length === 0) {
        this.addresses = this.localMemberDetails.address.address_data
        this.selectedAddress = 0
        this.unfilledIndex = this.getNexUnfilledAddressIndex()
        this.unfilled = this.addresses[this.unfilledIndex]
        this.initMixin(true, false)
        this.filledAddresses = this.getFilledAddresses()
      }
    },
    fieldComponent(field, index) {
      return {
        value: field.value,
        disabled: field.disabled,
      }
    },
    fieldValidations(field) {
      return field.required ? { required: true } : {}
    },
    handleClickAddress(index, scopename, e) {
      this.$validator.validateAll(scopename).then(result => {
        if (result) {
          this.selectedAddress = index
          this.expanding = true
          this.currentScopeName = scopename
        } else {
          // @Todo: handle if there is a validation error
        }
      })
      this.selectedAddress = index
    },
    isFieldsEmpty(fields) {
      let address1Field = fields.find(x => x.label === 'Address 1')
      if (typeof address1Field !== 'undefined' && address1Field.value === '') {
        return false
      }
      return true
    },
    addressRulesChecker(addressIndex, key) {
      let configs = this.masterDataConfigOptionsCreator(key)
      if (configs.length > 0) {
        let confIndex = configs.findIndex(x => x.config === addressIndex.toString())
        if (confIndex !== -1) {
          return true
        }
      }
      return false
    },
  },
  computed: {
    ...mapGetters([
      'isLoading',
      'getCountriesList',
      'getSelectedCountryId',
      'getStateList',
      'getStateListByCountryIdFormSelect',
      'getCityByCountryIdStateId',
      'getMyAccountMemberDetails',
      'getCountryNameById',
      'getStateNameById',
    ]),
  },
  watch: {
    getMyAccountMemberDetails() {
      this.localMemberDetails.address.id = this.getMyAccountMemberDetails.address.id
      this.localMemberDetails.address.user_id = this.getMyAccountMemberDetails.address.user_id
      this.localMemberDetails.address.address_data = _.cloneDeep(this.getMyAccountMemberDetails.address.address_data)
      this.initAddressMixin()
    },
  },
}
</script>
