<template>
  <div class="content">
    <div class="enrol-personal-data-wrapper">
      <enrol-grid-1>
        <template slot="full-content">
          <b-card no-body class="enrol-card-content">
            <div v-if="enrolmentData">
              <template v-if="!isExpressEnrollment">
                <h4 class="px-4 pt-4 pb-2 m-0 enrol-card-title text-medium">
                  {{ $t('Enrolment.FillInInformation.Title') }}
                </h4>
                <b-tabs
                  card
                  class="pt-0"
                  nav-class="px-3"
                  v-model="tabIndex"
                  active-nav-item-class="bg-white"
                  content-class="bg-white px-2 mt-3"
                >
                  <b-tab
                    id="personalData"
                    title-item-class="pr-1 pt-2"
                    :title="$t('Enrolment.PersonalDetails.Title')"
                    title-link-class="p-3 bg-gray-200 text-muted border-0"
                  >
                    <b-col lg="8" class="px-0">
                      <b-row class="mb-3">
                        <b-col cols="12" lg="3">
                          <label class="required">{{ $t('Enrolment.Nationality.Label') }}</label>
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col>
                              <b-form-select
                                v-validate="'required'"
                                :options="nationalityOptions"
                                :name="$t('Enrolment.Nationality.Label')"
                                :class="fields[$t('Enrolment.Nationality.Label')]"
                                v-model="enrolmentData.member_data.details.nationality_id"
                                data-qa="enrolment-personalDataPage-nationality-select"
                              />
                            </b-col>
                            <b-col v-if="errors.has($t('Enrolment.Nationality.Label'))" cols="12" class="text-danger">
                              <span>{{ errors.first($t('Enrolment.Nationality.Label')) }}</span>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <b-row class="mb-3">
                        <b-col cols="12" lg="3">
                          <label class="required">{{ $t('Enrolment.Identification.Label') }}</label>
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col cols="4" class="pr-0">
                              <b-form-select
                                v-validate="'required'"
                                :options="getOptions('ic_passport_type')"
                                :name="$t('Enrolment.Identification.Type')"
                                :class="fields[$t('Enrolment.Identification.Type')]"
                                v-model="enrolmentData.member_data.details.ic_pass_type_id"
                                data-qa="enrolment-personalDataPage-icPassportType-select"
                              />
                            </b-col>
                            <b-col>
                              <b-form-input
                                debounce="500"
                                :name="$t('Enrolment.Identification.Label')"
                                :class="fields[$t('Enrolment.Identification.Label')]"
                                v-model="enrolmentData.member_data.details.ic_passport_number"
                                v-validate="{
                                  required: true,
                                  idPassportValidChecker: getIcPassportValidationStatusString,
                                }"
                                data-qa="enrolment-personalDataPage-identification-input"
                              />
                            </b-col>
                            <b-col v-if="!this.getIcPassportValidationInProgress" cols="12" class="text-danger">
                              <div v-if="errors.has($t('Enrolment.Identification.Type'))">
                                {{ errors.first($t('Enrolment.Identification.Type')) }}
                              </div>
                              <div v-if="errors.has($t('Enrolment.Identification.Label'))">
                                {{ errors.first($t('Enrolment.Identification.Label')) }}
                              </div>
                            </b-col>
                            <b-col cols="12">
                              <ic-passport-validation
                                :ic-passport-number="enrolmentData.member_data.details.ic_passport_number"
                                :ic-passport-number-type-id="enrolmentData.member_data.details.ic_pass_type_id"
                                :check-cross-sponsoring="enrolmentData.without_sponsor === 0"
                                :validation-conditions="[
                                  {
                                    field: 'nationality_id',
                                    value: enrolmentData.member_data.details.nationality_id,
                                  },
                                  {
                                    field: 'ic_pass_type_id',
                                    value: enrolmentData.member_data.details.ic_pass_type_id,
                                  },
                                ]"
                                data-qa-prefix="enrolment-personalDataPage"
                              />
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <b-row class="mb-3">
                        <b-col cols="12" lg="3">
                          <label class="required">{{ $t('Enrolment.NameAsPer.Label') }}</label>
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col>
                              <b-form-input
                                v-validate="'required'"
                                :name="$t('Enrolment.NameAsPer.Label')"
                                :class="fields[$t('Enrolment.NameAsPer.Label')]"
                                v-model="enrolmentData.member_data.details.name"
                                data-qa="enrolment-personalDataPage-nameAsPerIcPassport-input"
                              />
                            </b-col>
                            <b-col v-if="errors.has($t('Enrolment.NameAsPer.Label'))" cols="12" class="text-danger">
                              <span>{{ errors.first($t('Enrolment.NameAsPer.Label')) }}</span>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <b-row v-if="getOnDemandFieldsConfig('translated_name')" class="mb-3">
                        <b-col cols="12" lg="3">
                          <label class="required">{{ $t('Enrolment.TranslatedName.Label') }}</label>
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col>
                              <b-form-input
                                v-validate="'required'"
                                :name="$t('Enrolment.TranslatedName.Label')"
                                :class="fields[$t('Enrolment.TranslatedName.Label')]"
                                v-model="enrolmentData.member_data.details.translated_name"
                                data-qa="enrolment-personalDataPage-translateName-input"
                              />
                            </b-col>
                            <b-col
                              v-if="errors.has($t('Enrolment.TranslatedName.Label'))"
                              cols="12"
                              class="text-danger"
                            >
                              <span>{{ errors.first($t('Enrolment.TranslatedName.Label')) }}</span>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <b-row class="mb-3">
                        <b-col cols="12" lg="3">
                          <label class="required">{{ $t('Enrolment.Gender.Label') }}</label>
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col>
                              <b-form-radio-group
                                :options="getOptions('gender')"
                                :name="$t('Enrolment.Gender.Label')"
                                :class="fields[$t('Enrolment.Gender.Label')]"
                                v-model="enrolmentData.member_data.information.gender_id"
                                data-qa="enrolment-personalDataPage-gender-radio"
                              />
                            </b-col>
                            <b-col v-if="errors.has($t('Enrolment.Gender.Label'))" cols="12" class="text-danger">
                              <span>{{ errors.first($t('Enrolment.Gender.Label')) }}</span>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <b-row class="mb-3">
                        <b-col cols="12" lg="3">
                          <label :class="{ required: enrolmentData.membershipType === 'EK Smart' }">
                            {{ $t('Enrolment.Upload.Label') }}</label
                          >
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col>
                              <b-button
                                id="enrolUploaderBtn"
                                @click="openUploader()"
                                variant="outline-primary"
                                data-qa="enrolment-personalDataPage-uploadIcPassport-btn"
                              >
                                <b-spinner v-show="isLoading('uploading')" small class="mr-2" />
                                <span v-show="isLoading('uploading')">{{ $t('Common.Uploading') }}</span>
                                <span v-show="!isLoading('uploading')">{{ $t('Common.Browse') }}</span>
                              </b-button>
                              <input
                                id="enrolUploader"
                                type="file"
                                class="mt-3 d-none"
                                @change="startUpload"
                                :accept="getUploadsSettings.client_validate"
                                ref="enrolUploader"
                              />
                              <b-button variant="link" class="ml-2 p-0 text-black" id="popoverIdUploadButton-sync">
                                <icon name="info-circle-icon" />
                              </b-button>
                              <b-popover triggers="hover focus" target="popoverIdUploadButton-sync">
                                {{ $t('Enrolment.SupportDocTooltip.Label') }}
                              </b-popover>
                            </b-col>
                            <b-col cols="12">
                              <div
                                :id="`image-${index}`"
                                class="image-lists mt-3 mb-3"
                                v-for="(list, index) in this.enrolmentData.member_data.verification"
                                :key="index"
                              >
                                <span class="title pr-3"> {{ $t('Common.Image.Label') }}- {{ index + 1 }} </span>
                                <span class="remove c-pointer" @click="removeUploadedImageRow(index)">
                                  <icon name="cancel-icon" />
                                </span>
                                <b-tooltip :target="`image-${index}`" placement="left">
                                  <b-img :src="list.image_link" fluid />
                                </b-tooltip>
                              </div>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <template v-if="getOnDemandFieldsConfig('tin_number')">
                        <b-row class="mb-3">
                          <b-col cols="12" lg="3">
                            <label :class="{ required: getOnDemandFieldsConfig('tin_number_taiwan_required') }">
                              {{ $t('Common.TinNoTaiwan') }}
                            </label>
                          </b-col>
                          <b-col>
                            <b-row>
                              <b-col>
                                <b-form-input
                                  :name="$t('Common.TinNoTaiwan')"
                                  :class="fields[$t('Common.TinNoTaiwan')]"
                                  v-model="enrolmentData.member_data.details.tin_no_taiwan"
                                  v-validate="{
                                    required: getOnDemandFieldsConfig('tin_number_taiwan_required'),
                                  }"
                                  data-qa="enrolment-personalDataPage-tinNoTaiwan-input"
                                />
                              </b-col>
                              <b-col v-if="errors.has($t('Common.TinNoTaiwan'))" cols="12" class="text-danger">
                                <span>{{ errors.first($t('Common.TinNoTaiwan')) }}</span>
                              </b-col>
                            </b-row>
                          </b-col>
                        </b-row>

                        <b-row class="mb-3">
                          <b-col cols="12" lg="3">
                            <label :class="{ required: getOnDemandFieldsConfig('tin_number_philippines_required') }">
                              {{ $t('Common.TinNoPhilippines') }}
                            </label>
                          </b-col>
                          <b-col>
                            <b-row>
                              <b-col>
                                <b-form-input
                                  :name="$t('Common.TinNoPhilippines')"
                                  :class="fields[$t('Common.TinNoPhilippines')]"
                                  v-model="enrolmentData.member_data.details.tin_no_philippines"
                                  v-validate="{
                                    required: getOnDemandFieldsConfig('tin_number_philippines_required'),
                                  }"
                                  data-qa="enrolment-personalDataPage-tinNoPhilippines-input"
                                />
                              </b-col>
                              <b-col v-if="errors.has($t('Common.TinNoPhilippines'))" cols="12" class="text-danger">
                                <span>{{ errors.first($t('Common.TinNoPhilippines')) }}</span>
                              </b-col>
                            </b-row>
                          </b-col>
                        </b-row>
                      </template>

                      <b-row class="mb-3">
                        <b-col cols="12" lg="3">
                          <label class="required">{{ $t('Enrolment.DateOfBirth.Label') }}</label>
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col>
                              <custom-date-picker
                                initial-view="year"
                                :name="$t('Enrolment.DateOfBirth.Label')"
                                :disable-date-range="{ from: new Date() }"
                                :has-error="errors.has($t('Enrolment.DateOfBirth.Label'))"
                                v-validate="{ required: true, ageLimit: getCountryAgeLimit() }"
                                v-model="enrolmentData.member_data.details.date_of_birth"
                                data-qa="enrolment-personalDataPage-dateOfBirth-select"
                              />
                            </b-col>
                            <b-col v-if="errors.has($t('Enrolment.DateOfBirth.Label'))" cols="12" class="text-danger">
                              <span>{{ errors.first($t('Enrolment.DateOfBirth.Label')) }}</span>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <b-row class="mb-3">
                        <b-col cols="12" lg="3">
                          <label class="required">{{ $t('Enrolment.EthnicGroup.Label') }}</label>
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col>
                              <b-form-select
                                v-validate="'required'"
                                :options="getOptions('ethnic_group')"
                                :name="$t('Enrolment.EthnicGroup.Label')"
                                :class="fields[$t('Enrolment.EthnicGroup.Label')]"
                                v-model="enrolmentData.member_data.information.ethnic_group_id"
                                data-qa="enrolment-personalDataPage-ethnicGroup-select"
                              />
                            </b-col>
                            <b-col v-if="errors.has($t('Enrolment.EthnicGroup.Label'))" cols="12" class="text-danger">
                              <span>{{ errors.first($t('Enrolment.EthnicGroup.Label')) }}</span>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <b-row class="mb-3">
                        <b-col cols="12" lg="3">
                          <label class="required">{{ $t('Enrolment.PreferredLanguage.Label') }}</label>
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col>
                              <b-form-select
                                v-validate="'required'"
                                :options="languagesOptions"
                                :name="$t('Enrolment.PreferredLanguage.Label')"
                                :class="fields[$t('Enrolment.PreferredLanguage.Label')]"
                                v-model="enrolmentData.member_data.information.language_id"
                                data-qa="enrolment-personalDataPage-preferredLanguage-select"
                              />
                            </b-col>
                            <b-col
                              v-if="errors.has($t('Enrolment.PreferredLanguage.Label'))"
                              cols="12"
                              class="text-danger"
                            >
                              <span>{{ errors.first($t('Enrolment.PreferredLanguage.Label')) }}</span>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <b-row class="mb-3">
                        <b-col cols="12" lg="3">
                          <label class="required">{{ $t('Enrolment.MaritalStatus.Label') }}</label>
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col>
                              <b-form-select
                                v-validate="'required'"
                                :options="getOptions('martial_status')"
                                :name="$t('Enrolment.MaritalStatus.Label')"
                                :class="fields[$t('Enrolment.MaritalStatus.Label')]"
                                v-model="enrolmentData.member_data.information.martial_status_id"
                                data-qa="enrolment-personalDataPage-maritalStatus-select"
                              />
                            </b-col>
                            <b-col v-if="errors.has($t('Enrolment.MaritalStatus.Label'))" cols="12" class="text-danger">
                              <span>{{ errors.first($t('Enrolment.MaritalStatus.Label')) }}</span>
                            </b-col>
                            <b-col v-if="$appSettings.evo.enable" cols="12">
                              <b-form-text v-show="isMarried">
                                {{ $t('Common.PersonalInfo.SpouseDetailsDisclaimer') }}
                              </b-form-text>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <spouse-info
                        v-if="$appSettings.evo.enable"
                        :is-married="isMarried"
                        :input-col-classes="['']"
                        :row-classes="['mb-3']"
                        :ic-passport-type-col-classes="['col-4']"
                        :label-col-classes="['col-12', 'col-lg-3']"
                        :value="enrolmentData.member_data.information.spouse"
                        :ic-passport-type-options="getOptions('ic_passport_type')"
                        @input="val => (enrolmentData.member_data.information.spouse = val)"
                        data-qa-prefix="enrolment-personalDataPage"
                      />

                      <template v-if="enrolmentData.membershipType === 'EK Smart'">
                        <b-row class="mb-3">
                          <b-col cols="12" lg="3">
                            <label>{{ $t('Enrolment.Occupation.Label') }}</label>
                          </b-col>
                          <b-col>
                            <b-row>
                              <b-col>
                                <b-form-input
                                  :name="$t('Enrolment.Occupation.Label')"
                                  :class="fields[$t('Enrolment.Occupation.Label')]"
                                  v-model="enrolmentData.member_data.details.occupation"
                                  data-qa="enrolment-personalDataPage-occupation-input"
                                />
                              </b-col>
                            </b-row>
                          </b-col>
                        </b-row>

                        <b-row class="mb-3">
                          <b-col cols="12" lg="3">
                            <label>{{ $t('Enrolment.SalaryRange.Label') }}</label>
                          </b-col>
                          <b-col>
                            <b-row>
                              <b-col>
                                <b-form-select
                                  :options="getSalaryRangeSelect"
                                  :name="$t('Enrolment.SalaryRange.Label')"
                                  :class="fields[$t('Enrolment.SalaryRange.Label')]"
                                  v-model="enrolmentData.member_data.details.salary_range"
                                  data-qa="enrolment-personalDataPage-salaryRange-select"
                                />
                              </b-col>
                            </b-row>
                          </b-col>
                        </b-row>
                      </template>
                    </b-col>

                    <div class="mt-4">
                      <hr />
                      <b-row :class="{ 'justify-content-between': !$appSettings.evo.enable }">
                        <b-col cols="auto">
                          <b-button
                            size="lg"
                            class="px-4"
                            @click="prevAction"
                            variant="outline-primary"
                            data-qa="enrolment-personalDataPage-personalDetailsTab-back-btn"
                          >
                            {{ $t('Common.Back') }}
                          </b-button>
                        </b-col>
                        <b-col cols="auto" class="pl-0">
                          <b-button
                            size="lg"
                            class="px-4"
                            variant="primary"
                            @click="tabIndex++"
                            data-qa="enrolment-personalDataPage-personalDetailsTab-next-btn"
                          >
                            {{ $t('Common.Next') }}
                          </b-button>
                        </b-col>
                      </b-row>
                    </div>
                  </b-tab>
                  <b-tab
                    id="contact"
                    title-item-class="pr-1 pt-2"
                    :title="$t('Common.ContactDetails')"
                    title-link-class="p-3 bg-gray-200 text-muted border-0"
                  >
                    <b-col lg="8" class="px-0">
                      <b-row>
                        <b-col cols="12">
                          <b-form-radio-group
                            :name="$t('Enrolment.OnBehalf.Label')"
                            v-model="enrolmentData.on_behalf_enrolment"
                            :class="[fields[$t('Enrolment.OnBehalf.Label')], 'mb-3']"
                            @change="
                              resetError('get_verification_code_failed'), controlInputs('email'), removeVerifications()
                            "
                          >
                            <b-row no-gutters>
                              <b-col cols="6" class="border p-4">
                                <b-form-radio :value="0" data-qa="enrolment-personalDataPage-selfEnrol-radio">
                                  {{ $t('Enrolment.Self.Label') }}
                                </b-form-radio>
                              </b-col>
                              <b-col cols="6" class="border p-4" id="onBehalfRadio">
                                <b-form-radio
                                  :disabled="!allowEnrolOnBehalf"
                                  :value="1"
                                  data-qa="enrolment-personalDataPage-enrolOnBehalf-radio"
                                >
                                  {{ $t('Enrolment.OnBehalf.Label') }}
                                </b-form-radio>
                              </b-col>
                            </b-row>
                            <b-tooltip
                              v-if="!allowEnrolOnBehalf"
                              target="onBehalfRadio"
                              placement="bottom"
                              triggers="hover focus"
                              :title="$t('Enrolment.SponsorNotSelected')"
                            />
                          </b-form-radio-group>
                        </b-col>
                        <b-col v-if="errors.has($t('Enrolment.OnBehalf.Label'))" cols="12" class="text-danger">
                          <span>{{ errors.first($t('Enrolment.OnBehalf.Label')) }}</span>
                        </b-col>
                        <b-col cols="12">
                          <PreferredContact
                            :row-classes="['mb-3']"
                            :col-classes="['col-12']"
                            v-model="preferredContactData"
                            :control-tooltip="controlTooltip"
                            :label-classes="['col-12', 'col-lg-3']"
                            :control-classes="['col-12', 'col-lg-9']"
                            :error-classes="['text-danger', 'col-12']"
                            :mobile-country-code-control-classes="['col-4']"
                            :verification-code-control-classes="['offset-lg-3']"
                            data-qa-prefix="enrolment-personalDataPage"
                          />
                        </b-col>
                      </b-row>

                      <b-row class="mb-3">
                        <b-col cols="12" lg="3">
                          <label>{{ $t('Enrolment.HomePhone.Label') }}</label>
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col cols="4" class="pr-0">
                              <b-form-select
                                :options="getCountriesCallCode"
                                :name="$t('Enrolment.HomePhone.Label')"
                                v-model="enrolmentData.member_data.contact_info.tel_home_1_country_code_id"
                                data-qa="enrolment-personalDataPage-homePhoneCallCode-select"
                              />
                            </b-col>
                            <b-col>
                              <b-input-group
                                :prepend="
                                  countryCodePrefix(enrolmentData.member_data.contact_info.tel_home_1_country_code_id)
                                "
                              >
                                <b-form-input
                                  type="number"
                                  :name="$t('Enrolment.HomePhone.Label')"
                                  v-model="enrolmentData.member_data.contact_info.tel_home_1_num"
                                  placeholder="e.g. 127654321"
                                  :class="{ 'border-danger': errors.has($t('Enrolment.HomePhone.Label')) }"
                                  data-qa="enrolment-personalDataPage-homePhone-input"
                                />
                              </b-input-group>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <b-row class="mb-3">
                        <b-col cols="12" lg="3">
                          <label>{{ $t('Enrolment.OfficePhone.Label') }}</label>
                        </b-col>
                        <b-col>
                          <b-row>
                            <b-col cols="4" class="pr-0">
                              <b-form-select
                                :options="getCountriesCallCode"
                                :name="$t('Enrolment.OfficePhone.Label')"
                                v-model="enrolmentData.member_data.contact_info.tel_office_1_country_code_id"
                                data-qa="enrolment-personalDataPage-officePhoneCallCode-select"
                              />
                            </b-col>
                            <b-col>
                              <b-input-group
                                :prepend="
                                  countryCodePrefix(enrolmentData.member_data.contact_info.tel_office_1_country_code_id)
                                "
                              >
                                <b-form-input
                                  type="number"
                                  :name="$t('Enrolment.OfficePhone.Label')"
                                  v-model="enrolmentData.member_data.contact_info.tel_office_1_num"
                                  placeholder="e.g. 127654321"
                                  :class="{ 'border-danger': errors.has($t('Enrolment.OfficePhone.Label')) }"
                                  data-qa="enrolment-personalDataPage-officePhone-input"
                                />
                              </b-input-group>
                            </b-col>
                          </b-row>
                        </b-col>
                      </b-row>

                      <template v-if="$helpers.getValue(addresses, '[0].fields')">
                        <div v-if="isLoading('getEnrolmentTypes')" class="text-center text-primary mt-4">
                          <b-spinner />
                        </div>
                        <template
                          v-else
                          v-for="(field, index) in sortDynamicFieldsCountryStateCityTop(addresses[0].fields)"
                        >
                          <b-row class="mb-3" :key="index">
                            <b-col cols="12" lg="3">
                              <label :class="{ required: field.required }">
                                {{ (tLabel = $t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label)) }}
                              </label>
                            </b-col>
                            <b-col>
                              <b-row>
                                <b-col>
                                  <b-form-input
                                    v-if="field.type === 'input'"
                                    :name="tLabel"
                                    debounce="500"
                                    :class="fields[field.label]"
                                    v-validate="(field.required && 'required') || ''"
                                    v-model="
                                      addresses[0].fields[setDynamicFieldIndex(addresses[0].fields, field.index)].value
                                    "
                                  />
                                  <b-form-select
                                    v-else-if="
                                      field.type === 'select' ||
                                        (field.type === 'custom-select' && field.type !== 'masters-select')
                                    "
                                    :name="tLabel"
                                    :class="fields[field.label]"
                                    :disabled="isFieldLoading(field)"
                                    :options="getFieldOptionsData(0, field)"
                                    @change="formFieldChanged(field, $event)"
                                    v-validate="(field.required && 'required') || ''"
                                    v-model="
                                      addresses[0].fields[setDynamicFieldIndex(addresses[0].fields, field.index)].value
                                    "
                                  />
                                </b-col>
                                <b-col v-if="errors.has(field.label)" cols="12" class="text-danger">
                                  <span>{{ errors.first(field.label) }}</span>
                                </b-col>
                              </b-row>
                            </b-col>
                          </b-row>
                        </template>
                      </template>
                      <template v-else>
                        <b-row>
                          <b-col cols="auto" class="text-danger">{{ $t('Enrolment.NoData.Info') }}</b-col>
                        </b-row>
                      </template>
                    </b-col>

                    <div class="mt-4">
                      <template v-if="enrolmentData.membershipType === 'EK Smart' || showAccountPreferenceTab">
                        <hr />
                        <div>
                          <b-row :class="{ 'justify-content-between': !$appSettings.evo.enable }">
                            <b-col cols="auto">
                              <b-button
                                size="lg"
                                variant="outline-primary"
                                class="px-4"
                                @click="tabIndex--"
                                data-qa="enrolment-personalDataPage-contactDetailsTab-back-btn"
                              >
                                {{ $t('Common.Back') }}
                              </b-button>
                            </b-col>
                            <b-col cols="auto" class="pl-0">
                              <b-button
                                size="lg"
                                variant="primary"
                                class="px-4"
                                @click="tabIndex++"
                                data-qa="enrolment-personalDataPage-contactDetailsTab-next-btn"
                              >
                                {{ $t('Common.Next') }}
                              </b-button>
                            </b-col>
                          </b-row>
                        </div>
                      </template>
                      <enrolment-stepped-footer-navigation
                        v-else
                        :next="next"
                        :previous="$t('Common.Back')"
                        :next-action="nextAction"
                        :enrolment-data="enrolmentData"
                        :prev-action="() => tabIndex--"
                        :validate-and-save="validateAndSave"
                        :validate-status="enrolmentData.step_states['personal-data']"
                        :footer-navigator-class="[{ 'justify-content-between': !$appSettings.evo.enable }]"
                        data-qa-prefix="enrolment-personalDataPage-contactDetailsTab"
                      />
                    </div>
                  </b-tab>
                  <template v-if="enrolmentData.membershipType === 'EK Smart'">
                    <b-tab
                      v-if="getEmploymentDetailsFields !== null"
                      id="employmentDetailsForm"
                      title-item-class="pr-1 pt-2"
                      :title="$t('Enrolment.EmploymentDetails.Title')"
                      title-link-class="p-3 bg-gray-200 text-muted border-0"
                    >
                      <b-row>
                        <b-col class="px-0">
                          <b-card class="border-0 mt-1 text-center">
                            <component
                              v-for="(element, index) in getEmploymentDetailsFields"
                              :is="fieldMap.get(element.type)"
                              @click="handleClick(element)"
                              :key="index"
                              variant="outline-primary"
                              v-html="
                                element.type === 'textarea'
                                  ? element.value
                                  : $t('Enrolment.Form.' + $helpers.capitalCase(element.label), element.label)
                              "
                            >
                            </component>
                          </b-card>
                        </b-col>
                      </b-row>

                      <div class="mt-4">
                        <hr />
                        <b-row :class="{ 'justify-content-between': !$appSettings.evo.enable }">
                          <b-col cols="auto">
                            <b-button
                              size="lg"
                              variant="outline-primary"
                              class="px-4"
                              @click="tabIndex--"
                              data-qa="enrolment-personalDataPage-employmentDetailsTab-back-btn"
                            >
                              {{ $t('Common.Back') }}
                            </b-button>
                          </b-col>
                          <b-col cols="auto" class="pl-0">
                            <b-button
                              size="lg"
                              class="px-4"
                              variant="primary"
                              @click="tabIndex++"
                              :disabled="!getEmploymentFormStatus"
                              data-qa="enrolment-personalDataPage-employmentDetailsTab-back-btn"
                            >
                              {{ $t('Common.Next') }}
                            </b-button>
                          </b-col>
                        </b-row>
                      </div>
                    </b-tab>
                    <b-tab
                      id="rec"
                      title-item-class="pr-1 pt-2"
                      :title="$t('Enrolment.RecurringInfo.Title')"
                      title-link-class="p-3 bg-gray-200 text-muted border-0"
                    >
                      <div>
                        <b-card class="border-0" no-body>
                          <card-recurring-info
                            id="recurringinfo"
                            :country-id="enrolmentData.region.value"
                            data-qa-prefix="enrolment-personalDataPage"
                            ref="recurringInfo"
                          />
                        </b-card>
                        <b-card>
                          <div class="card-title">
                            {{ $t('Enrolment.SupportingDoc.Label') }}
                          </div>
                          <b-row class="mb-3">
                            <b-col cols="auto" md="3" lg="2" class="text-md-right">
                              <label>{{ $t('Enrolment.UploadSupportDoc.Label') }}</label>
                            </b-col>
                            <b-col class="mb-4">
                              <b-row>
                                <b-col>
                                  <b-button
                                    variant="outline-primary"
                                    @click="openSupportDocUploader"
                                    data-qa="enrolment-personalDataPage-uploadSupportDocument-btn"
                                  >
                                    <b-spinner v-show="isLoading('uploading-supporting')" small class="mr-2" />
                                    <span v-show="isLoading('uploading-supporting')">{{ $t('Common.Uploading') }}</span>
                                    <span v-show="!isLoading('uploading-supporting')">{{ $t('Common.Browse') }}</span>
                                  </b-button>
                                  <input
                                    id="enrolSupportDocUploader"
                                    multiple
                                    type="file"
                                    class="mt-3 d-none"
                                    @change="startUploadSupportDoc"
                                    :accept="getUploadsSettings.client_validate"
                                    ref="enrolSupportDocUploader"
                                  />
                                </b-col>
                                <b-col cols="12">
                                  <div
                                    :id="`support-image-${index}`"
                                    class="image-lists mt-3 mb-3"
                                    v-for="(list, index) in supportingDocs"
                                    :key="index"
                                  >
                                    <span class="title pr-3"> {{ $t('Common.Image.Label') }}- {{ index + 1 }} </span>
                                    <span class="remove c-pointer" @click="removeUploadedSupportDocImageRow(index)">
                                      <icon name="cancel-icon" />
                                    </span>
                                    <b-tooltip :target="`support-image-${index}`" placement="left">
                                      <b-img :src="list.url" fluid />
                                    </b-tooltip>
                                  </div>
                                </b-col>
                              </b-row>
                            </b-col>
                            <b-col cols="12">
                              <span class="pre-wrap text-black-50">{{
                                $t('Enrolment.SupportingDocUpload.SupportingText', { limit: maxFileSize })
                              }}</span>
                            </b-col>
                          </b-row>
                        </b-card>
                      </div>

                      <div class="mt-4">
                        <template v-if="showAccountPreferenceTab">
                          <hr />
                          <div>
                            <b-row :class="{ 'justify-content-between': !$appSettings.evo.enable }">
                              <b-col cols="auto">
                                <b-button
                                  size="lg"
                                  class="px-4"
                                  @click="tabIndex--"
                                  variant="outline-primary"
                                  data-qa="enrolment-personalDataPage-recurringInfoTab-back-btn"
                                >
                                  {{ $t('Common.Back') }}
                                </b-button>
                              </b-col>
                              <b-col cols="auto" class="pl-0">
                                <b-button
                                  size="lg"
                                  class="px-4"
                                  variant="primary"
                                  @click="tabIndex++"
                                  data-qa="enrolment-personalDataPage-recurringInfoTab-next-btn"
                                >
                                  {{ $t('Common.Next') }}
                                </b-button>
                              </b-col>
                            </b-row>
                          </div>
                        </template>
                        <enrolment-stepped-footer-navigation
                          v-else
                          :next="next"
                          :next-action="nextAction"
                          :previous="$t('Common.Back')"
                          :enrolment-data="enrolmentData"
                          :prev-action="() => tabIndex--"
                          :validate-and-save="validateAndSave"
                          :validate-status="enrolmentData.step_states['personal-data']"
                          :footer-navigator-class="[{ 'justify-content-between': !$appSettings.evo.enable }]"
                          data-qa="enrolment-personalDataPage-recurringInfoTab"
                        />
                      </div>
                    </b-tab>
                  </template>
                  <b-tab
                    v-if="showAccountPreferenceTab"
                    id="accountPreference"
                    title-item-class="pr-1 pt-2"
                    :title="$t('MyAccount.AccountPreference.Title')"
                    title-link-class="p-3 bg-gray-200 text-muted border-0"
                  >
                    <b-row>
                      <b-col class="px-0">
                        <b-card class="border-0">
                          <amp-preference
                            class="border border-danger bg-important mb-3"
                            @input="val => (enrolmentData.amp_preference = val)"
                            :value="defaultAmpPreference"
                            :loading="isLoading(['loadingBackendSettings'])"
                            data-qa-prefix="enrolment-personalDataPage"
                          />
                        </b-card>
                      </b-col>
                    </b-row>
                    <div class="mt-4">
                      <enrolment-stepped-footer-navigation
                        :next="next"
                        :next-action="nextAction"
                        :previous="$t('Common.Back')"
                        :enrolment-data="enrolmentData"
                        :prev-action="() => tabIndex--"
                        :validate-and-save="validateAndSave"
                        :validate-status="enrolmentData.step_states['personal-data']"
                        :footer-navigator-class="[{ 'justify-content-between': !$appSettings.evo.enable }]"
                        data-qa-prefix="enrolment-personalDataPage-accountPreferenceTab"
                      />
                    </div>
                  </b-tab>
                </b-tabs>
              </template>

              <template v-else>
                <b-col class="mt-5">
                  <b-row align-h="center">
                    <b-col cols="12" lg="6">
                      <SocialAuthentication
                        v-if="$appSettings.socialAuthentication.enable"
                        v-model="socialAuthentication"
                        :separator-style="{ background: 'white', color: 'black' }"
                      />
                    </b-col>

                    <b-col cols="12">
                      <b-row align-h="center">
                        <b-col cols="12" lg="6">
                          <PreferredContact
                            :col-classes="['col-12']"
                            :row-classes="['mb-3']"
                            :label-classes="['col-12', 'col-lg-3']"
                            :control-classes="['col-12', 'col-lg-9']"
                            :error-classes="['text-danger', 'col-12']"
                            v-model="preferredContactData"
                            :control-tooltip="controlTooltip"
                            :mobile-country-code-control-classes="['col-4']"
                            :verification-code-control-classes="['offset-lg-3']"
                          />
                          <b-row class="mb-3">
                            <b-col cols="12" lg="3">
                              <label class="required">{{ $t('Enrolment.NameAsPer.Label') }}</label>
                            </b-col>
                            <b-col>
                              <b-row>
                                <b-col>
                                  <b-form-input
                                    v-validate="'required'"
                                    :name="$t('Enrolment.NameAsPer.Label')"
                                    :class="fields[$t('Enrolment.NameAsPer.Label')]"
                                    v-model="enrolmentData.member_data.details.name"
                                  />
                                </b-col>
                                <b-col v-if="errors.has($t('Enrolment.NameAsPer.Label'))" cols="12" class="text-danger">
                                  <span>{{ errors.first($t('Enrolment.NameAsPer.Label')) }}</span>
                                </b-col>
                              </b-row>
                            </b-col>
                          </b-row>
                          <div class="enrol-section">
                            <enrolment-stepped-footer-navigation
                              ref="footerNavigation"
                              :enrolment-data="enrolmentData"
                              :next-action="nextAction"
                              :prev-action="prevAction"
                              :previous="previous"
                              :validate-and-save="validateAndSave"
                              :validate-status="enrolmentData.step_states['personal-data']"
                              :next="next"
                              data-qa-prefix="enrolment-personalDataPage"
                            />
                          </div>
                        </b-col>
                      </b-row>
                    </b-col>
                  </b-row>
                </b-col>
              </template>
            </div>
          </b-card>
        </template>
      </enrol-grid-1>
    </div>
  </div>
</template>
<script>
import enrolGrid1 from '@/app/enrolment/_global/components/templates/layouts/enrol-grid-1'
import EnrolmentSteppedFooterNavigation from '@/app/enrolment/_global/components/elements/enrolmentSteppedfooterNavigation'
import cardRecurringInfo from '@/app/_global/components/blocks/cardRecurringInfo'
import { AddressMixin, GeneralMixin, UploaderMixin, PhoneMixin } from '@/app/_global/mixins'
import ageLimit from '@/validators/_age_limit'
import idPassportValidChecker from '@/validators/_id_passport_valid_checker'
import _ from 'lodash'
import IcPassportValidation from '@/app/_global/components/elements/icPassportValidation'
import { mapActions, mapGetters, mapState } from 'vuex'
import { mapMasterDataId } from '@/app/_global/mixins'
import CustomDatePicker from '@/elements/common/components/CustomDatePicker'
import PreferredContact from '@/app/enrolment/_global/components/elements/PreferredContact'
import SocialAuthentication from '@/app/_global/components/elements/SocialAuthentication'
import ampPreference from '@/app/_global/components/blocks/AmpPreference'
import SpouseInfo from '@/app/_global/components/blocks/SpouseInfo'
import AppSettings from '@/config/app-settings'

export default {
  name: 'EnrolmentPersonalDataPage',
  mixins: [AddressMixin, GeneralMixin, UploaderMixin, PhoneMixin],
  components: {
    SpouseInfo,
    enrolGrid1,
    EnrolmentSteppedFooterNavigation,
    cardRecurringInfo,
    IcPassportValidation,
    CustomDatePicker,
    PreferredContact,
    SocialAuthentication,
    ampPreference,
  },
  $_veeValidate: {
    validator: 'new',
  },
  props: {
    enrolmentData: {
      type: Object,
      required: true,
    },
    previous: {
      type: String,
    },
    next: {
      type: String,
    },
    prevAction: {
      type: Function,
    },
    nextAction: {
      type: Function,
    },
    steps: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    // Todo temp fix to reload uploader config based on tab
    tabIndex(to) {
      if (to === 0) {
        this.getUploaderSettings()
      }
    },
    preferredContactData: {
      handler(to) {
        this.socialAuthentication = false
        this.enrolmentData.member_data.contact_info = _.merge(to.contact_info)
        this.enrolmentData.verification = _.merge(to.verification)
        this.$set(this.enrolmentData, 'skip_contact_verification', to.skip_contact_verification)
      },
      deep: true,
    },
    socialAuthentication: {
      handler(to) {
        if (!this.$helpers.getValue(to, 'error')) {
          // reset
          this.preferredContactData = false
          this.enrolmentData.member_data.details.name = ''
          // Move next
          this.$refs.footerNavigation.conditionNext()
        }
      },
    },
  },
  data: () => ({
    uploadCardShow: false,
    supportingDocs: [],
    showEmail: false,
    uploadFiles: null,
    allowEnrolOnBehalf: true,
    tabIndex: 0,
    content1: '',
    content2: '',
    content3: '',
    fieldMap: new Map([
      ['textarea', 'div'],
      ['link', 'b-button'],
    ]),
    maxFileSize: process.env.VUE_APP_UPLOAD_FILE_SIZE_LIMIT,
    preferredContactData: {},
    socialAuthentication: false,
    accountPreferenceConfigList: {
      ampPreference: AppSettings.myAccount.ampPreference,
    },
  }),
  computed: {
    ...mapMasterDataId({
      FILE_TYPE: {
        fileTypeImageId: 'IMAGE',
        fileTypePdfId: 'PDF',
      },
    }),
    ...mapState({
      userSelectedAddress: state => state.locationModule.dynamicContentData.data.address,
    }),
    ...mapGetters({
      getErrors: 'getErrors',
      getErrorsBreakup: 'getErrorsBreakup',
      getErrorsState: 'getErrorsState',
      nationalityOptions: 'getNationalityList',
      getOptions: 'getEnrolmentMasterDataOptionsByKey',
      languagesOptions: 'getLanguageList',
      getCountriesCallCode: 'getCountriesCallCode',
      getUploadsSettings: 'getUploadsSettings',
      getUploads: 'getUploads',
      isLoading: 'isLoading',
      countriesListOptions: 'getCountries',
      getIcPassportValidationPassed: 'getIcPassportValidationPassed',
      getIcPassportValidationInProgress: 'getIcPassportValidationInProgress',
      getBackendSetting: 'getBackendSetting',
    }),
    ...mapGetters('enrolment', {
      getEnrolAddress: 'getEnrolAddress',
      getVerificationResponse: 'getVerificationResponse',
      postVerificationResponse: 'postVerificationResponse',
      getBankFormSelect: 'getBankFormSelect',
      getSalaryRangeSelect: 'getSalaryRangeSelect',
      getBankSwiftCode: 'getBankSwiftCode',
      getSupportingDocDetails: 'getSupportingDocDetails',
      getSelectedRecurringInfoType: 'getSelectedRecurringInfoType',
      getRentalCardDetails: 'getRentalCardDetails',
      getEnrolCountryId: 'getEnrolCountryId',
      getEmploymentDetailsFields: 'getEmploymentDetailsFields',
      getEmploymentFormStatus: 'getEmploymentFormStatus',
      getIsExpressEnrollment: 'getIsExpressEnrollment',
    }),
    getIcPassportValidationStatusString() {
      if (this.getIcPassportValidationPassed) {
        return 'true'
      }
      return 'false'
    },
    isExpressEnrollment() {
      return this.getIsExpressEnrollment(this.enrolmentData.enrolment_type)
    },
    defaultAmpPreference() {
      let defaultSetting = this.getBackendSetting('default_member_amp_preference') || { data: null }

      return this.$helpers.isNull(this.enrolmentData.amp_preference)
        ? defaultSetting.data
        : this.enrolmentData.amp_preference
    },
    isMarried() {
      let marriedOption = (this.getOptions('martial_status') || []).find(val => val.key === 'married') || {}
      return this.enrolmentData.member_data.information.martial_status_id === marriedOption.value
    },
    showAccountPreferenceTab() {
      return Object.entries(this.accountPreferenceConfigList).filter(data => data[1]).length
    },
  },
  async created() {
    if (this.$helpers.getValue(this.enrolmentData, 'region.value')) {
      this.$validator.extend('ageLimit', ageLimit)
      this.$validator.extend('idPassportValidChecker', idPassportValidChecker)
      await this.loadMasterDataKeysEnrolment({
        country_id: this.enrolmentData.region.value,
        keys: [
          'sale_types',
          'gender',
          'ethnic_group',
          'martial_status',
          'ic_passport_type',
          'age_for_enrollment',
          'preferred_contact',
          'translated_name',
          'tin_number',
          'tin_number_taiwan_required',
          'tin_number_philippines_required',
          'address_names',
          'salary_range',
          'card_type',
          'card_company',
          'countries_bank',
          'product_additional_requirements',
          'bank_account_type',
          'file_types',
        ],
      }).then(async () => {
        if (this.enrolmentData.member_data.contact_info.preferred_contact_id === '') {
          this.enrolmentData.member_data.contact_info.preferred_contact_id = await this.getMasterDataEnrolementIdByKeyAndTitle(
            this.$const.masterKey.PREFERRED_CONTACT,
            this.$const.masterData.EMAIL
          )
        }
        if (this.enrolmentData.member_data.information.gender_id === '') {
          if (this.getOptions('gender').length > 0) {
            this.enrolmentData.member_data.information.gender_id = await this.getOptions('gender')[0].value
          }
        }
      })
      this.setDefaultAddress()
    }
  },
  async mounted() {
    if (this.$helpers.getValue(this.enrolmentData, 'region.value')) {
      this.getUploaderSettings()
      let countryId = this.$helpers.getValue(this.enrolmentData, 'region.value')
      if (countryId !== false) {
        let query = {
          country_id: this.enrolmentData.region.value,
        }
        await this.loadLanguages(query).then(() => {
          // Set default value
          if (this.languagesOptions.length > 0) {
            if (this.enrolmentData.language === null) {
              this.enrolmentData.language = this.languagesOptions[0]
            }
          }
        })
      }

      await this.loadAllCountries()
      await this.loadBankList()
      await this.loadSalaryRangeList()
      await this.loadBackendSetting(['default_member_amp_preference'])

      if (this.enrolmentData.without_sponsor === 1) {
        this.allowEnrolOnBehalf = false
        this.enrolmentData.on_behalf_enrolment = 0
      }
      if (this.enrolmentData.membershipType === 'EK Smart') {
        this.content1 = 'Enrolment.Agreement.Content1.Title.EkSmart'
        this.content2 = 'Enrolment.Agreement.Content1.Title2.EkSmart'
        this.content3 = 'Enrolment.Agreement.Content2.Title.EkSmart'
      } else {
        this.content1 = 'Enrolment.Agreement.Content1.Title'
        this.content2 = 'Enrolment.Agreement.Content1.Title2'
        this.content3 = 'Enrolment.Agreement.Content2.Title'
      }
      let data = this.getSupportingDocDetails
      let isEmptyObj = _.isEmpty(data)

      if (!isEmptyObj) {
        this.supportingDocs = data
      }
      if (this.getCountriesCallCode.length > 0) {
        let callCode = this.getCountriesCallCode.find(data => {
          return data.value === this.getEnrolCountryId
        })
        if (callCode !== undefined) {
          this.enrolmentData.member_data.contact_info.mobile_1_country_code_id = callCode.value
          this.enrolmentData.member_data.contact_info.tel_home_1_country_code_id = callCode.value
          this.enrolmentData.member_data.contact_info.tel_office_1_country_code_id = callCode.value
        }
      }
      let query = {
        country_id: this.enrolmentData.region.value,
        types: ['employment_details'],
        membership_type: this.enrolmentData.membershipType,
      }
      await this.getDynamicEmploymentDetails(query)
      this.preferredContactData = {
        contact_info: _.cloneDeep(this.enrolmentData.member_data.contact_info),
        verification: _.cloneDeep(this.enrolmentData.verification),
      }
    }
  },
  methods: {
    ...mapActions([
      'loadMasterDataKeysEnrolment',
      'getDynamicContent',
      'resetError',
      'loadLanguages',
      'loadAllCountries',
      'resetAllErrors',
      'loadBackendSetting',
    ]),
    ...mapActions('enrolment', [
      'getCode',
      'postCode',
      'removeVerificationGetCode',
      'postTempEnrolment',
      'loadBankList',
      'loadSalaryRangeList',
      'getDynamicRecurringInfo',
      'getDynamicPayeeInfo',
      'setSupportingDocDetails',
      'getDynamicEmploymentDetails',
      'updateEmploymentFormStatus',
    ]),
    handleClick(element) {
      if (this.$helpers.capitalCase(element.label) === 'FillUpHere') {
        this.openEmploymentForm(element.value)
      }
    },
    getCountryAgeLimit() {
      let limit = 18
      if (this.getOptions('age_for_enrollment').length > 0) {
        if (this.getOptions('age_for_enrollment')[0].text !== undefined) {
          limit = this.getOptions('age_for_enrollment')[0].text
        }
      }
      return limit
    },
    getOnDemandFieldsConfig(key) {
      if (this.getOptions(key).length > 0) {
        if (this.getOptions(key)[0].text !== undefined) {
          if (this.getOptions(key)[0].text === 'True' || this.getOptions(key)[0].text === 'true') {
            return true
          }
        }
      }
      return false
    },
    applyMixinAddress(countryId) {
      if (this.enrolmentData.member_data.address.address_data.length > 0) {
        this.addresses = this.enrolmentData.member_data.address.address_data
        if (this.enrolmentData.region !== null) {
          // Sequence is important
          this.setSelectedAddress(0) // Selected address can be call from function
          this.selectedCountry = countryId || this.enrolmentData.region.value
          this.setCountrySelectionOnSelectedAddress()
        }
      }
    },
    isFoundInfo(list, key) {
      var found = -1
      for (let i = 0; i < list.length; i++) {
        key = key.toUpperCase()
        list[i].title = list[i].title.toUpperCase()
        if (list[i].title === key) {
          found = i
        }
      }
      return found
    },
    async setDefaultAddress(forceUpdate = false) {
      if (typeof this.enrolmentData.region.value === 'number') {
        const enrolmentCountryId = this.enrolmentData.region.value

        // Check is there any address_data in dynamic content state
        let existingAddress = undefined
        if (this.enrolmentData.member_data.address.address_data.length > 0) {
          existingAddress = this.enrolmentData.member_data.address.address_data[0]['fields'].find(
            x => x.key === 'countries'
          )
        }

        // Set default address object
        let addressTypeName = []
        if (this.getOptions('address_names').length > 0) {
          addressTypeName = await _.sortBy(this.getOptions('address_names'), 'sort')
        }
        let defaultEmptyAddress = [
          {
            title: this.$helpers.getValue(addressTypeName, '[0].text', 'Shipping 1'),
            fields: [],
          },
          {
            title: this.$helpers.getValue(addressTypeName, '[1].text', 'Shipping 2'),
            fields: [],
          },
          {
            title: this.$helpers.getValue(addressTypeName, '[2].text', 'Shipping 3'),
            fields: [],
          },
          {
            title: this.$helpers.getValue(addressTypeName, '[3].text', 'Shipping 4'),
            fields: [],
          },
        ]

        // if NO complete address_data in dynamic content && is express enrolment
        if (!existingAddress && this.isExpressEnrollment) {
          this.enrolmentData.member_data.address.address_data = [...defaultEmptyAddress]
        } else {
          // if NO complete address_data in dynamic content or the address_data doesn't match with the current selected enrol country
          if (!existingAddress || enrolmentCountryId !== existingAddress.value || forceUpdate) {
            let query = {
              country_id: enrolmentCountryId,
              types: ['address'],
            }
            await this.getDynamicContent(query).then(async () => {
              if (this.userSelectedAddress !== undefined && this.userSelectedAddress.length > 0) {
                let selectedAddress = JSON.parse(this.userSelectedAddress)
                // Merge with the default address
                selectedAddress[0]['title'] = addressTypeName[0] !== undefined ? addressTypeName[0].text : 'Shipping 1'
                defaultEmptyAddress.splice(0, 1)
                this.enrolmentData.member_data.address.address_data = [...selectedAddress, ...defaultEmptyAddress]
              }
            })
          }
          await this.applyMixinAddress()
        }
      }
    },
    controlTooltip(type, elements = []) {
      elements.forEach(element => {
        let string = 'bv::' + type + '::tooltip'
        this.$root.$emit(string, element)
      })
    },
    controlInputs(name) {
      if (name === 'email') {
        this.showEmail =
          this.getMasterDataEnrolementIdByKeyAndTitle(
            this.$const.masterKey.PREFERRED_CONTACT,
            this.$const.masterData.EMAIL
          ) === this.enrolmentData.member_data.contact_info.preferred_contact_id
      }
    },
    openUploader() {
      jQuery('#enrolUploader').trigger('click')
    },
    openSupportDocUploader() {
      jQuery('#enrolSupportDocUploader').trigger('click')
    },
    openBankCardUploader(ref) {
      let value = '#' + ref
      jQuery(value).trigger('click')
    },
    startUploadSupportDoc() {
      let self = this
      this.files = this.$refs.enrolSupportDocUploader.files
      this.params.file_type = this.getUploadsSettings.file_type
      this.uploader('supporting').then(() => {
        if (self.getUploads.length > 0) {
          self.getUploads.forEach(item => {
            self.supportingDocs.push({
              file_type_id: self.fileTypeImageId,
              name: item.name,
              url: item.link,
            })
          })
          self.setInfo()
        }
        self.$refs.enrolSupportDocUploader.value = null
      })
    },
    startUpload() {
      let self = this
      this.files = this.$refs.enrolUploader.files
      this.params.file_type = this.getUploadsSettings.file_type
      this.uploader('ic-passport').then(() => {
        if (self.getUploads.length > 0) {
          self.getUploads.forEach(item => {
            self.enrolmentData.member_data.verification.push({
              type: 'IC',
              image_path: item.name,
              image_link: item.link,
            })
          })
        }
        self.$refs.enrolUploader.value = null
      })
    },
    getTabIndex(label) {
      let tabIndex = 0
      if (
        label === this.$t('Enrolment.Nationality.Label') ||
        label === this.$t('Enrolment.NameAsPer.Label') ||
        label === this.$t('Enrolment.TranslatedName.Label') ||
        label === this.$t('Enrolment.Identification.Label') ||
        label === this.$t('Enrolment.Upload.Label') ||
        label === this.$t('Common.TinNoTaiwan') ||
        label === this.$t('Common.TinNoPhilippines') ||
        label === this.$t('Enrolment.DateOfBirth.Label') ||
        label === this.$t('Enrolment.EthnicGroup.Label') ||
        label === this.$t('Enrolment.MaritalStatus.Label') ||
        label === this.$t('Enrolment.PreferredLanguage.Label') ||
        label === this.$t('Enrolment.Identification.Type') ||
        label === this.$t('Common.PersonalInfo.SpouseName') ||
        label === this.$t('Common.PersonalInfo.SpouseIdentification.Type') ||
        label === this.$t('Common.PersonalInfo.SpouseIDPassportNo') ||
        label === this.$t('Common.PersonalInfo.SpouseDateOfBirth')
      ) {
        tabIndex = 0
      } else if (
        label === 'card_network' ||
        label === 'card_type' ||
        label === 'issued_bank' ||
        label === 'card_number' ||
        label === 'name_on_card' ||
        label === 'expired_date' ||
        label === 'rental_card_status'
      ) {
        tabIndex = 3
      } else {
        tabIndex = 1
      }

      return tabIndex
    },
    isValidCardInfoFields() {
      let isValid = false
      if (this.enrolmentData.membershipType === 'EK Smart') {
        let selectedType = this.getSelectedRecurringInfoType
        let value = this.getRentalCardDetails

        if (selectedType === 'CARD') {
          if (
            value.card_type_id !== '' &&
            value.card_company_id !== '' &&
            value.country_bank_id !== '' &&
            value.card_holder_name !== '' &&
            value.card_number !== '' &&
            value.card_expiry_date !== '' &&
            value.credit_card_photocopy.length > 0
          ) {
            isValid = true
          }
        } else {
          isValid = true
        }
      } else {
        isValid = true
      }

      return isValid
    },
    setInfo() {
      let docs = _.cloneDeep(this.supportingDocs)
      this.setSupportingDocDetails(docs)
    },
    removeUploadedImageRow(index) {
      this.enrolmentData.member_data.verification.splice(index, 1)
    },
    removeUploadedSupportDocImageRow(index) {
      this.supportingDocs.splice(index, 1)
      this.setInfo()
    },
    async getUploaderSettings() {
      this.params.file_type = 'member_ic_passport'
      await this.uploaderSettings()
    },
    openEmploymentForm(url) {
      window.open(url, '_blank')
      setTimeout(() => {
        this.updateEmploymentFormStatus(true)
      }, 10000)
    },
    async saveEnrollmentTempData(data = false) {
      let payload = _.cloneDeep(this.enrolmentData)
      // If social data exist update enrollment payload before save
      if (data && !this.$helpers.getValue(data, 'error')) {
        payload.member_data.contact_info.email = this.$helpers.getValue(this.socialAuthentication, 'data.email', '')
        payload.member_data.details.name = this.$helpers.getValue(this.socialAuthentication, 'data.name', '')
      }
      if (this.isExpressEnrollment) {
        // Express enrollment identifier
        payload.is_express_checkout = true
      }

      await this.postTempEnrolment(payload)
        .then(async () => {
          this.enrolmentData.step_states['personal-data'] = true
        })
        .catch(async () => {
          this.enrolmentData.step_states['personal-data'] = false
          await this.$swal({
            title: 'Attention !!',
            text: this.getErrorsBreakup('saveTempEnrolment'),
            type: 'error',
            timer: '5000',
            confirmButtonClass: 'outline-primary',
          })
        })
    },
    async validateAndSave() {
      if (this.$helpers.getValue(this.socialAuthentication, 'error', true)) {
        if (this.$refs.recurringInfo) {
          this.$refs.recurringInfo.checkUploadedDocumentStatus()
        }
        await this.$validator.validateAll().then(async result => {
          if (result) {
            this.resetAllErrors()
            if (
              (Object.keys(this.enrolmentData.verification.post).length > 0 &&
                this.enrolmentData.verification.post.verified === 1) ||
              this.enrolmentData.skip_contact_verification
            ) {
              if (
                (this.enrolmentData.membershipType === 'EK Smart' &&
                  this.enrolmentData.member_data.verification.length > 0) ||
                this.enrolmentData.membershipType === 'Standard'
              ) {
                if (this.enrolmentData.member_data.address.address_data.length > 0) {
                  if (this.$helpers.isSet(this.enrolmentData, 'member_data.address.address_data[1]')) {
                    this.enrolmentData.member_data.address.address_data[1].fields = this.enrolmentData.member_data.address.address_data[0].fields
                  } else {
                    // If missing default addresses reset again with throwing error
                    await this.setDefaultAddress(true)
                    await this.$swal({
                      title: 'Attention !!',
                      text: this.$t('Enrolment.AddressError.Msg'),
                      type: 'error',
                      timer: '5000',
                      confirmButtonClass: 'outline-primary',
                    })
                    throw false
                  }
                }

                if (this.isValidCardInfoFields() === true) {
                  await this.saveEnrollmentTempData()
                } else {
                  this.enrolmentData.step_states['personal-data'] = false
                  throw result
                }
              } else {
                this.tabIndex = 0
                this.$scrollTo('#enrolUploaderBtn')
                this.enrolmentData.step_states['personal-data'] = result
                await this.$swal({
                  title: 'Attention !!',
                  text: this.$t('Enrolment.ICUploadrequired.Msg'),
                  type: 'error',
                  timer: '5000',
                  confirmButtonClass: 'outline-primary',
                })
                throw result
              }
            } else {
              this.$scrollTo('#verification-area')
              this.tabIndex = 1
              this.controlTooltip('show', ['verification1', 'verification2'])
              this.enrolmentData.step_states['personal-data'] = false
              throw result
            }
            if (this.enrolmentData.membershipType === 'EK Smart' && !this.getEmploymentFormStatus) {
              this.tabIndex = 2
              await this.$swal({
                title: this.$t('Enrolment.Form.EmploymentDetail.ErrorMessage.Title'),
                type: 'error',
                timer: '5000',
                confirmButtonClass: 'outline-primary',
              })
              throw false
            }
          } else {
            this.tabIndex = this.getTabIndex(this.errors.items[0].field)
            this.$scrollTo('[name="' + this.errors.items[0].field + '"]')
            this.enrolmentData.step_states['personal-data'] = result
            throw result
          }
        })
      } else {
        this.enrolmentData.step_states['personal-data'] = true
        await this.saveEnrollmentTempData(this.socialAuthentication)
        return true
      }
    },
  },
}
</script>
