<template>
  <div class="page signup-page account-info">
    <div class="container">
      <div id="account-info-data-form">
        <div class="main-title">
          <h5>{{ $t('3rdParty.Checkout.AccountInfo.MembershipInformation.Title') }}</h5>
          <p v-html="getMembershipSubTitleTranslation"></p>
          <p>{{ $t('Enrolment.FillInInformation.Title') }}</p>
        </div>
        <!-- Normal Enrollment -->
        <b-row class="mt-3" v-if="isDataLoaded && !isExpressEnrollment">
          <div class="col">
            <div class="section">
              <div class="section-content text-capitalize">
                <b-container fluid="">
                  <b-row class="mb-3">
                    <b-col lg="9" md="12" sm="12">
                      <b-form-row class="controls-holder">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label class="required">
                            {{ $t('Enrolment.Nationality.Label') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="12" md="12" class="section-controls">
                          <b-form-select
                            size="md"
                            :name="$t('Enrolment.Nationality.Label')"
                            v-validate="'required'"
                            :class="fields[$t('Enrolment.Nationality.Label')]"
                            v-model="enrolmentData.member_data.details.nationality_id"
                            :options="nationalityOptions"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="12" class="section-controls-errors">
                          <field-errors :cerrors="errors" :cfields="fields" :name="$t('Enrolment.Nationality.Label')" />
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder">
                        <b-col cols="12" lg="3" class="section-label">
                          <label class="required">
                            {{ $t('Enrolment.Identification.Label') }}
                          </label>
                        </b-col>
                        <b-col cols="5" lg="3" class="section-controls pr-0">
                          <b-form-select
                            size="md"
                            cols="3"
                            lg="3"
                            tab-index="0"
                            :name="$t('Enrolment.Identification.Type')"
                            :class="fields[$t('Enrolment.Identification.Type')]"
                            v-validate="'required'"
                            v-model="enrolmentData.member_data.details.ic_pass_type_id"
                            :options="getOptions('ic_passport_type')"
                            :disabled="!isNationalitySelected"
                          />
                        </b-col>
                        <b-col cols="7" lg="6" class="section-controls">
                          <b-form-input
                            size="md"
                            type="text"
                            :name="$t('Enrolment.Identification.Label')"
                            :class="fields[$t('Enrolment.Identification.Label')]"
                            :disabled="!isNationalitySelected"
                            v-model="enrolmentData.member_data.details.ic_passport_number"
                            v-validate="{
                              required: true,
                              idPassportValidChecker: getIcPassportValidationStatusString,
                            }"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="12" class="section-controls-errors">
                          <field-errors
                            v-if="!this.getIcPassportValidationInProgress"
                            :cerrors="errors"
                            :cfields="fields"
                            :name="$t('Enrolment.Identification.Type')"
                          ></field-errors>
                          <field-errors
                            v-if="!this.getIcPassportValidationInProgress"
                            :cerrors="errors"
                            :cfields="fields"
                            :name="$t('Enrolment.Identification.Label')"
                          ></field-errors>
                        </b-col>
                        <b-col offset-lg="3" cols="12" lg="9">
                          <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 },
                            ]"
                          />
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label class="required">
                            {{ $t('Enrolment.NameAsPer.Label') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="12" md="12" class="section-controls">
                          <b-form-input
                            size="md"
                            type="text"
                            :name="$t('Enrolment.NameAsPer.Label')"
                            v-validate="'required'"
                            :class="fields[$t('Enrolment.NameAsPer.Label')]"
                            v-model="enrolmentData.member_data.details.name"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="12" class="section-controls-errors">
                          <field-errors :cerrors="errors" :cfields="fields" :name="$t('Enrolment.NameAsPer.Label')" />
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder" v-if="getOnDemandFieldsConfig('translated_name')">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label class="required">
                            {{ $t('Enrolment.TranslatedName.Label') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="12" md="12" class="section-controls">
                          <b-form-input
                            size="md"
                            type="text"
                            :name="$t('Enrolment.TranslatedName.Label')"
                            :class="fields[$t('Enrolment.TranslatedName.Label')]"
                            v-validate="'required'"
                            v-model="enrolmentData.member_data.details.translated_name"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="9" class="section-controls-errors">
                          <field-errors
                            :cerrors="errors"
                            :cfields="fields"
                            :name="$t('Enrolment.TranslatedName.Label')"
                          ></field-errors>
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label>
                            {{ $t('Enrolment.Gender.Label') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="12" md="12" class="section-controls">
                          <b-form-radio-group
                            :options="getOptions('gender')"
                            :class="fields[$t('Enrolment.Gender.Label')]"
                            :name="$t('Enrolment.Gender.Label')"
                            v-model="enrolmentData.member_data.information.gender_id"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="9" class="section-controls-errors">
                          <field-errors :cerrors="errors" :cfields="fields" :name="$t('Enrolment.Gender.Label')" />
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label :class="enrolmentData.membershipType === 'EK Smart' ? 'required' : ''">
                            {{ $t('Enrolment.Upload.Label') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="12" md="12" class="section-controls">
                          <b-button variant="outline-primary" size="md" @click="openUploader()" id="enrolUploaderBtn">
                            <icon name="spinner" pulse v-if="isLoading('uploading')" />
                            {{ isLoading('uploading') ? $t('Common.Uploading') : $t('Common.Browse') }}
                          </b-button>
                          <input
                            type="file"
                            v-show="false"
                            id="enrolUploader"
                            ref="enrolUploader"
                            :accept="getUploadsSettings.client_validate"
                            class="mt-3"
                            @change="startUpload"
                          />
                          <i class="ml-2" id="popoverIdUploadButton-sync">
                            <icon name="info-circle-icon" />
                          </i>
                          <b-popover :show.sync="uploadIcShow" target="popoverIdUploadButton-sync">
                            {{ $t('Enrolment.SupportDocTooltip.Label') }}
                          </b-popover>
                        </b-col>
                        <b-col offset-lg="3" cols="9" sm="9" md="9">
                          <div
                            :id="`image-${index}`"
                            class="image-lists mt-3 mb-3"
                            v-for="(list, index) in this.enrolmentData.member_data.verification"
                            :key="`image-${index}`"
                          >
                            <span class="remove c-pointer" @click="removeUploadedImageRow(index)">
                              <icon name="cancel-icon" />
                            </span>
                            <span class="title"> {{ $t('Common.Image.Label') }}- {{ index + 1 }} </span>
                            <b-tooltip :target="`image-${index}`" placement="left">
                              <b-img :src="list.image_link" fluid />
                            </b-tooltip>
                          </div>
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder" v-if="getOnDemandFieldsConfig('tin_number')">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label :class="{ required: getOnDemandFieldsConfig('tin_number_taiwan_required') }">
                            {{ $t('Common.TinNoTaiwan') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="12" md="12" class="section-controls">
                          <b-form-input
                            size="md"
                            type="text"
                            :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') }"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="9" class="section-controls-errors">
                          <field-errors :cerrors="errors" :cfields="fields" :name="$t('Common.TinNoTaiwan')" />
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder" v-if="getOnDemandFieldsConfig('tin_number')">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label
                            :class="{
                              required: getOnDemandFieldsConfig('tin_number_philippines_required'),
                            }"
                          >
                            {{ $t('Common.TinNoPhilippines') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="12" md="12" class="section-controls">
                          <b-form-input
                            size="md"
                            type="text"
                            :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'),
                            }"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="9" class="section-controls-errors">
                          <field-errors :cerrors="errors" :cfields="fields" :name="$t('Common.TinNoPhilippines')" />
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label class="required">
                            {{ $t('Enrolment.DateOfBirth.Label') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="12" md="12" class="section-controls">
                          <custom-date-picker
                            :name="$t('Enrolment.DateOfBirth.Label')"
                            :has-error="errors.has($t('Enrolment.DateOfBirth.Label'))"
                            initial-view="year"
                            v-validate="{ required: true, ageLimit: getCountryAgeLimit() }"
                            v-model="enrolmentData.member_data.details.date_of_birth"
                          ></custom-date-picker>
                        </b-col>
                        <b-col offset-lg="3" cols="9" class="section-controls-errors">
                          <field-errors :cerrors="errors" :cfields="fields" :name="$t('Enrolment.DateOfBirth.Label')" />
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label class="required">
                            {{ $t('Enrolment.EthnicGroup.Label') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="12" md="12" class="section-controls">
                          <b-form-select
                            size="md"
                            :name="$t('Enrolment.EthnicGroup.Label')"
                            v-validate="'required'"
                            :class="fields[$t('Enrolment.EthnicGroup.Label')]"
                            v-model="enrolmentData.member_data.information.ethnic_group_id"
                            :options="getOptions('ethnic_group')"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="9" class="section-controls-errors">
                          <field-errors :cerrors="errors" :cfields="fields" :name="$t('Enrolment.EthnicGroup.Label')" />
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label class="required">
                            {{ $t('Enrolment.PreferredLanguage.Label') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="12" md="12" class="section-controls">
                          <b-form-select
                            size="md"
                            :name="$t('Enrolment.PreferredLanguage.Label')"
                            v-validate="'required'"
                            :class="fields[$t('Enrolment.PreferredLanguage.Label')]"
                            v-model="enrolmentData.member_data.information.language_id"
                            :options="languagesOptions"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="9" class="section-controls-errors">
                          <field-errors
                            :cerrors="errors"
                            :cfields="fields"
                            :name="$t('Enrolment.PreferredLanguage.Label')"
                          />
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label class="required">
                            {{ $t('Enrolment.MaritalStatus.Label') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="6" md="6" class="section-controls">
                          <b-form-select
                            size="md"
                            :name="$t('Enrolment.MaritalStatus.Label')"
                            v-validate="'required'"
                            :class="fields[$t('Enrolment.MaritalStatus.Label')]"
                            v-model="enrolmentData.member_data.information.martial_status_id"
                            :options="getOptions('martial_status')"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="9" class="section-controls-errors">
                          <field-errors
                            :cerrors="errors"
                            :cfields="fields"
                            :name="$t('Enrolment.MaritalStatus.Label')"
                          />
                        </b-col>
                      </b-form-row>
                      <!--                      Hide for normal enrolment-->
                      <b-form-row class="controls-holder" v-if="false">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label>
                            {{ $t('Enrolment.Occupation.Label') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="6" md="6" class="section-controls">
                          <b-form-input
                            size="md"
                            type="text"
                            :name="$t('Enrolment.Occupation.Label')"
                            :class="fields[$t('Enrolment.Occupation.Label')]"
                            v-model="enrolmentData.member_data.details.occupation"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="9" class="section-controls-errors">
                          <field-errors :cerrors="errors" :cfields="fields" :name="$t('Enrolment.Occupation.Label')" />
                        </b-col>
                      </b-form-row>
                      <!--                      Hide for normal enrolment-->
                      <b-form-row class="controls-holder" v-if="false">
                        <b-col lg="3" sm="12" md="12" class="section-label">
                          <label>
                            {{ $t('Enrolment.SalaryRange.Label') }}
                          </label>
                        </b-col>
                        <b-col lg="9" sm="6" md="6" class="section-controls">
                          <b-form-select
                            v-model="enrolmentData.member_data.details.salary_range"
                            :options="getOptions('salary_range')"
                            :class="fields[$t('Enrolment.SalaryRange.Label')]"
                            :name="$t('Enrolment.SalaryRange.Label')"
                          />
                        </b-col>
                        <b-col offset-lg="3" cols="9" class="section-controls-errors">
                          <field-errors
                            :cerrors="errors"
                            :cfields="fields"
                            :name="$t('Enrolment.SalaryRange.Label')"
                          ></field-errors>
                        </b-col>
                      </b-form-row>
                    </b-col>
                  </b-row>
                </b-container>
              </div>
            </div>
            <div class="section">
              <div class="section-content text-capitalize">
                <b-container fluid="">
                  <PreferredContact v-model="preferredContactData" :control-tooltip="controlTooltip"></PreferredContact>
                  <b-row>
                    <!-- Forms -->
                    <b-col lg="9" md="12" sm="12">
                      <b-form-row class="controls-holder">
                        <b-col cols="12" lg="3" class="section-label">
                          <label>
                            {{ $t('Enrolment.HomePhone.Label') }}
                          </label>
                        </b-col>
                        <b-col class="section-controls col-12 col-md-5 col-lg-3 mb-2 mb-md-0">
                          <b-form-select
                            :name="$t('Enrolment.HomePhone.Label')"
                            size="md"
                            v-model="enrolmentData.member_data.contact_info.tel_home_1_country_code_id"
                            :options="getCountriesCallCode"
                          />
                        </b-col>
                        <b-col class="section-controls col-12 col-md-7 col-lg-6">
                          <b-input-group
                            class="col-input-group-min-width-2-plus text-right"
                            :prepend="
                              countryCodePrefix(enrolmentData.member_data.contact_info.tel_home_1_country_code_id)
                            "
                          >
                            <b-form-input
                              :name="$t('Enrolment.HomePhone.Label')"
                              v-model="enrolmentData.member_data.contact_info.tel_home_1_num"
                              :class="{
                                input: true,
                                'border-danger': errors.has($t('Enrolment.HomePhone.Label')),
                              }"
                              placeholder="e.g. 127654321"
                              type="number"
                            />
                          </b-input-group>
                        </b-col>
                      </b-form-row>
                      <b-form-row class="controls-holder">
                        <b-col cols="12" lg="3" class="section-label">
                          <label>
                            {{ $t('Enrolment.OfficePhone.Label') }}
                          </label>
                        </b-col>
                        <b-col class="section-controls col-12 col-md-5 col-lg-3 mb-2 mb-md-0">
                          <b-form-select
                            size="md"
                            :name="$t('Enrolment.OfficePhone.Label')"
                            v-model="enrolmentData.member_data.contact_info.tel_office_1_country_code_id"
                            :options="getCountriesCallCode"
                          />
                        </b-col>
                        <b-col class="section-controls col-12 col-md-7 col-lg-6">
                          <b-input-group
                            class="col-input-group-min-width-2-plus text-right"
                            :prepend="
                              countryCodePrefix(enrolmentData.member_data.contact_info.tel_office_1_country_code_id)
                            "
                          >
                            <b-form-input
                              :name="$t('Enrolment.OfficePhone.Label')"
                              v-model="enrolmentData.member_data.contact_info.tel_office_1_num"
                              :class="{
                                input: true,
                                'border-danger': errors.has($t('Enrolment.OfficePhone.Label')),
                              }"
                              placeholder="e.g. 127654321"
                              type="number"
                            />
                          </b-input-group>
                        </b-col>
                      </b-form-row>
                      <div class="address-holder" v-if="$helpers.getValue(addresses, '[0].fields')">
                        <icon name="spinner" pulse v-if="isLoading('getEnrolmentTypes')" />
                        <template v-else="">
                          <div
                            :key="`address-${index}`"
                            v-for="(field, index) in sortDynamicFieldsCountryStateCityTop(addresses[0].fields)"
                          >
                            <b-form-row class="controls-holder text-capitalize">
                              <b-col lg="3" sm="12" md="12" class="section-label">
                                <label :class="{ required: field.required }">
                                  <!-- Convert the label to upper case and replace spaces with `-` -->
                                  {{
                                    (tLabel = $t('Dynamic.Address.' + $helpers.capitalCase(field.label), field.label))
                                  }}
                                </label>
                              </b-col>
                              <b-col lg="9" sm="12" md="12" class="section-controls">
                                <b-form-input
                                  size="md"
                                  type="text"
                                  :name="tLabel"
                                  :class="fields[field.label]"
                                  v-if="field.type === 'input'"
                                  v-model="
                                    addresses[0].fields[setDynamicFieldIndex(addresses[0].fields, field.index)].value
                                  "
                                  v-validate="field.required ? 'required' : ''"
                                />
                                <b-form-select
                                  v-if="
                                    field.type === 'select' ||
                                      (field.type === 'custom-select' && field.type !== 'masters-select')
                                  "
                                  v-model="
                                    addresses[0].fields[setDynamicFieldIndex(addresses[0].fields, field.index)].value
                                  "
                                  @change="formFieldChanged(field, $event)"
                                  :name="tLabel"
                                  :disabled="isFieldLoading(field)"
                                  size="md"
                                  :class="fields[field.label]"
                                  v-validate="field.required ? 'required' : ''"
                                  :options="getFieldOptionsData(0, field)"
                                />
                              </b-col>
                              <b-col offset-lg="3" cols="12" class="section-controls-errors">
                                <field-errors :cerrors="errors" :cfields="fields" :name="field.label" />
                              </b-col>
                            </b-form-row>
                          </div>
                        </template>
                      </div>
                      <div class="empty-address-holder p-4 text-danger" v-else>
                        <b-form-row align-h="center">
                          <b-col cols="auto">
                            {{ $t('Enrolment.NoData.Info') }}
                          </b-col>
                        </b-form-row>
                      </div>
                    </b-col>
                    <!-- Forms end -->
                  </b-row>
                </b-container>
              </div>
            </div>
          </div>
        </b-row>
        <!-- Express Enrollment -->
        <b-row v-else>
          <b-col>
            <div class="section">
              <div class="section-content text-capitalize">
                <b-row align-h="center" class="mt-2">
                  <b-col cols="12" lg="6">
                    <SocialAuthentication
                      v-if="$appSettings.socialAuthentication.enable"
                      v-model="socialAuthentication"
                    />
                  </b-col>
                  <b-col cols="12">
                    <b-row align-h="center">
                      <b-col cols="12" lg="6">
                        <PreferredContact
                          :col-classes="[]"
                          v-model="preferredContactData"
                          :control-tooltip="controlTooltip"
                        ></PreferredContact>
                        <b-form-row class="controls-holder">
                          <b-col lg="3" sm="12" md="12" class="section-label">
                            <label class="required">
                              {{ $t('Enrolment.NameAsPer.Label') }}
                            </label>
                          </b-col>
                          <b-col lg="9" sm="12" md="12" class="section-controls">
                            <b-form-input
                              size="md"
                              type="text"
                              :name="$t('Enrolment.NameAsPer.Label')"
                              v-validate="'required'"
                              :class="fields[$t('Enrolment.NameAsPer.Label')]"
                              v-model="enrolmentData.member_data.details.name"
                            />
                          </b-col>
                          <b-col offset-lg="3" cols="12" class="section-controls-errors">
                            <field-errors :cerrors="errors" :cfields="fields" :name="$t('Enrolment.NameAsPer.Label')" />
                          </b-col>
                        </b-form-row>
                      </b-col>
                    </b-row>
                  </b-col>
                  <b-col
                    v-if="getSkipEnrolmentPrivilege && Number.parseFloat(getCartAllTotalPrices.rp_price_tax || 0) > 0"
                    cols="12"
                    lg="6"
                    class="mt-5"
                  >
                    <div class="border-top">
                      <!-- show button when the prefer contact data finish loaded to avoid validation error-->
                      <b-button
                        block
                        size="lg"
                        variant="outline-light"
                        @click="proceedWithGuest"
                        class="mt-2 text-underline border-0"
                        v-show="
                          preferredContactData.contact_info && preferredContactData.contact_info.preferred_contact_id
                        "
                      >
                        {{ $t('3rdparty.Checkout.Account.SkipEnrolmentStep.Label') }}
                      </b-button>
                    </div>
                  </b-col>
                </b-row>
              </div>
            </div>
          </b-col>
        </b-row>
      </div>
    </div>
  </div>
</template>
<script>
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 { APP_ENROLMENT_FORM } from '@@/store/localStorageKeys'
import FieldErrors from '@/elements/common/components/FieldErrors'
import PreferredContact from '@/app/enrolment/_global/components/elements/PreferredContact'
import SocialAuthentication from '@/app/_global/components/elements/SocialAuthentication'

export default {
  name: 'AccountInfoPage',
  components: {
    IcPassportValidation,
    CustomDatePicker,
    FieldErrors,
    PreferredContact,
    SocialAuthentication,
  },
  mixins: [AddressMixin, GeneralMixin, UploaderMixin, PhoneMixin],
  inject: ['$validator'],
  props: {
    navigateNext: {
      type: Function,
    },
  },
  watch: {
    enrolmentData: {
      handler(to) {
        this.setLocalForm({ namespace: '3rdPartyCheckoutEnrolment/', key: APP_ENROLMENT_FORM, formData: to })
      },
      deep: true,
    },
    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')) {
          this.fieldResetAndProceed()
        }
      },
    },
  },
  data: () => ({
    enrolmentData: {},
    uploadIcShow: false,
    uploadCardShow: false,
    supportingDocs: [],
    showEmail: false,
    uploadFiles: null,
    allowEnrolOnBehalf: true,
    isEmploymentFormClicked: false,
    tabIndex: 0,
    content1: '',
    content2: '',
    content3: '',
    fieldMap: new Map([
      ['textarea', 'div'],
      ['link', 'b-button'],
    ]),
    preferredContactData: {},
    socialAuthentication: false,
    skipEnrolmentStep: false,
  }),
  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',
      getAppLocationCountry: 'getAppLocationCountry',
    }),
    ...mapGetters('enrolment', {
      getEnrolAddress: 'getEnrolAddress',
      getBankFormSelect: 'getBankFormSelect',
      getBankSwiftCode: 'getBankSwiftCode',
      getSupportingDocDetails: 'getSupportingDocDetails',
      getSelectedRecurringInfoType: 'getSelectedRecurringInfoType',
      getRentalCardDetails: 'getRentalCardDetails',
      getEnrolCountryId: 'getEnrolCountryId',
      getEmploymentDetailsFields: 'getEmploymentDetailsFields',
      getIsExpressEnrollment: 'getIsExpressEnrollment',
      getEnrolmentTypes: 'getEnrolmentTypes',
    }),
    ...mapGetters('3rdPartyCheckoutEnrolment', ['getEnrolmentInfo', 'getSkipEnrolmentPrivilege']),
    ...mapGetters('3rdPartyCheckoutMembership', ['getMembershipInfo']),
    ...mapGetters('eshop', ['getCartAllTotalPrices']),
    getIcPassportValidationStatusString() {
      if (this.getIcPassportValidationPassed) {
        return 'true'
      }
      return 'false'
    },
    getMembershipSubTitleTranslation() {
      return this.$t('3rdParty.Checkout.AccountInfo.MembershipInformation.SubTitle', {
        trademark: '<sup class="trademark">' + this.$t('3rdParty.Common.Trademark.Text') + '</sup>',
      })
    },
    isDataLoaded() {
      return Object.keys(this.enrolmentData).length > 0
    },
    getCountryId() {
      return this.$helpers.getValue(this.getAppLocationCountry, 'countryId')
    },
    isNationalitySelected() {
      return this.enrolmentData.member_data.details.nationality_id !== ''
    },
    isExpressEnrollment() {
      return this.getIsExpressEnrollment(this.getEnrolmentInfo.enrolment_type)
    },
  },
  async created() {
    this.enrolmentData = _.cloneDeep(this.getEnrolmentInfo)
  },
  async mounted() {
    this.setSkipEnrolmentStatus(false)
    await this.loadMasterDataKeysEnrolment({
      country_id: this.getCountryId,
      keys: [
        'sale_types',
        'gender',
        'ethnic_group',
        'martial_status',
        'ic_passport_type',
        'age_for_enrollment',
        '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.information.gender_id === '') {
        if (this.getOptions('gender').length > 0) {
          this.enrolmentData.member_data.information.gender_id = await this.getOptions('gender')[0].value
        }
      }
    })
    await this.loadAllCountries()
    this.setDefaultAddress()
    if (this.getCountryId !== false) {
      let query = {
        country_id: this.getCountryId,
      }
      await this.loadLanguages(query).then(() => {
        // Set default value
        if (this.languagesOptions.length > 0) {
          if (this.enrolmentData.language === null) {
            this.enrolmentData.language = this.languagesOptions[0]
          }
        }
      })
    }
    if (this.enrolmentData.without_sponsor === 1) {
      this.allowEnrolOnBehalf = false
      this.enrolmentData.on_behalf_enrolment = 0
    }
    if (this.getCountriesCallCode.length > 0) {
      let callCode = this.getCountriesCallCode.find(data => {
        return data.value === this.getCountryId
      })
      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
      }
    }
    this.preferredContactData = {
      contact_info: _.cloneDeep(this.enrolmentData.member_data.contact_info),
      verification: _.cloneDeep(this.enrolmentData.verification),
    }
    if (!this.isExpressEnrollment) {
      this.$validator.extend('ageLimit', ageLimit)
      this.$validator.extend('idPassportValidChecker', idPassportValidChecker)
      await this.getUploaderSettings()
      await this.loadBankList()
      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
      }
    } else if (this.getSkipEnrolmentPrivilege) {
      // Fill up missing enrolment data after bypass proper enrolment process
      let { medium, reference } = this.$route.query
      let self = this
      if (medium && reference) {
        let payload = { key: medium, reference: reference }
        await this.setExternalSponsorDetails(payload).then(result => {
          self.enrolmentData['sponsor_name'] = (result && result.sponsorName) || ''
          self.enrolmentData['sponsor_user_id'] = (result && result.sponsorId) || ''
          self.enrolmentData['without_sponsor'] = result && result.withoutSponsor
          self.enrolmentData['sponsor_member_id'] = (result && result.sponsorMemberId) || ''
        })
      } else {
        self.enrolmentData['sponsor_name'] = ''
        self.enrolmentData['without_sponsor'] = 1
        self.enrolmentData['sponsor_user_id'] = ''
      }
      self.enrolmentData['member_data']['details']['nationality_id'] = self.getCountryId
      self.enrolmentData['region'] = self.getCountries.find(country => country.value === self.getCountryId)

      await self.getEnrolmentsTypes({
        country_id: self.getCountryId,
        sort: 'id',
        order: 'desc',
      })
      self.enrolmentData['enrolment_type'] = self.getEnrolmentTypes.find(
        type => type.title && type.title.toLowerCase() === 'preferred customer'
      ).id
    }
  },
  methods: {
    ...mapActions('3rdPartyCheckoutGlobal', ['setLocalForm']),
    ...mapActions('3rdPartyCheckoutEnrolment', ['setSkipEnrolmentStatus', 'setExternalSponsorDetails']),
    ...mapActions([
      'loadMasterDataKeysEnrolment',
      'getDynamicContent',
      'resetError',
      'loadLanguages',
      'loadAllCountries',
      'resetAllErrors',
    ]),
    ...mapActions('enrolment', [
      'postTempEnrolment',
      'loadBankList',
      'loadSalaryRangeList',
      'getDynamicRecurringInfo',
      'getDynamicPayeeInfo',
      'setSupportingDocDetails',
      'getEnrolmentsTypes',
    ]),
    ...mapActions('eshop', ['isRetailPrice']),
    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.getCountryId) {
          // Sequence is important
          this.setSelectedAddress(0) // Selected address can be call from function
          this.selectedCountry = countryId || this.getCountryId
          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() {
      if (this.getCountryId) {
        let checkExist = null
        if (this.enrolmentData.member_data.address.address_data.length > 0) {
          checkExist = this.enrolmentData.member_data.address.address_data[0]['fields'].find(x => x.key === 'countries')
        }
        if (checkExist === undefined || checkExist === null) {
          let names = []
          if (this.getOptions('address_names').length > 0) {
            names = await _.sortBy(this.getOptions('address_names'), 'sort')
          }
          let defaultEmptyAddress = [
            {
              title: names[0] !== undefined ? names[0].text : 'Shipping 1',
              fields: [],
            },
            {
              title: names[1] !== undefined ? names[1].text : 'Shipping 2',
              fields: [],
            },
            {
              title: names[2] !== undefined ? names[2].text : 'Shipping 3',
              fields: [],
            },
            {
              title: names[3] !== undefined ? names[3].text : 'Shipping 4',
              fields: [],
            },
          ]
          if (!this.isExpressEnrollment) {
            let query = {
              country_id: this.getCountryId,
              types: ['address'],
            }
            await this.getDynamicContent(query).then(async () => {
              if (this.userSelectedAddress !== undefined && this.userSelectedAddress.length > 0) {
                let selectedAddress = JSON.parse(this.userSelectedAddress)
                selectedAddress[0]['title'] = names[0] !== undefined ? names[0].text : 'Shipping 1'
                defaultEmptyAddress.splice(0, 1)
                this.enrolmentData.member_data.address.address_data = [...selectedAddress, ...defaultEmptyAddress]
                await this.applyMixinAddress()
              }
            })
          } else {
            this.enrolmentData.member_data.address.address_data = [...defaultEmptyAddress]
          }
        } else {
          await this.applyMixinAddress(checkExist.value)
        }
      }
    },
    controlTooltip(type, elements = []) {
      elements.forEach(element => {
        let string = 'bv::' + type + '::tooltip'
        this.$root.$emit(string, element)
      })
    },
    openUploader() {
      jQuery('#enrolUploader').trigger('click')
    },
    openSupportDocUploader() {
      jQuery('#enrolSupportDocUploader').trigger('click')
    },
    openBankCardUploader(ref) {
      let value = '#' + ref
      jQuery(value).trigger('click')
    },
    startUploadSupportDoc() {
      this.files = this.$refs.enrolSupportDocUploader.files
      this.params.file_type = this.getUploadsSettings.file_type
      this.uploader('supporting').then(() => {
        if (this.getUploads) {
          this.getUploads.forEach(item => {
            this.supportingDocs.push({
              file_type_id: this.fileTypeImageId,
              name: item.name,
              url: item.link,
            })
          })
          this.setInfo()
        }
      })
    },
    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
      })
    },
    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')
      if (!this.isEmploymentFormClicked) {
        setTimeout(() => {
          this.isEmploymentFormClicked = 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).catch(async () => {
        await this.$swal({
          title: 'Attention !!',
          text: this.getErrorsBreakup('saveTempEnrolment'),
          type: 'error',
          timer: '5000',
          confirmButtonClass: 'outline-primary',
        })
        this.enrolmentData.status = false
        this.isExpressEnrollment = false
        throw false
      })
    },
    async validateAndSubmit() {
      let skipFieldValidationProcess =
        this.skipEnrolmentStep || !this.$helpers.getValue(this.socialAuthentication, 'error', true)

      this.setSkipEnrolmentStatus(this.skipEnrolmentStep)

      if (!skipFieldValidationProcess) {
        return await this.$validator.validate().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.member_data.verification.length > 0 ||
                this.enrolmentData.membershipType === 'Standard'
              ) {
                if (this.enrolmentData.member_data.address.address_data.length > 0) {
                  this.enrolmentData.member_data.address.address_data[1].fields = this.enrolmentData.member_data.address.address_data[0].fields
                }

                await this.saveEnrollmentTempData()
              } else {
                this.$scrollTo('#enrolUploaderBtn')
                await this.$swal({
                  title: 'Attention !!',
                  text: this.$t('Enrolment.ICUploadrequired.Msg'),
                  type: 'error',
                  timer: '5000',
                  confirmButtonClass: 'outline-primary',
                })
                this.enrolmentData.status = false
                // set retail price display to {value} when condition meet
                this.setRetailPriceDisplayOption(true, this.getSkipEnrolmentPrivilege)
                throw result
              }
            } else {
              this.$scrollTo('#verification-area')
              this.controlTooltip('show', ['verification1', 'verification2'])
              this.enrolmentData.status = false
              this.setRetailPriceDisplayOption(true, this.getSkipEnrolmentPrivilege)
              throw result
            }
          } else {
            this.$scrollTo('[name="' + this.errors.items[0].field + '"]')
            this.enrolmentData.status = false
            this.setRetailPriceDisplayOption(true, this.getSkipEnrolmentPrivilege)
            throw result
          }
          this.enrolmentData.status = true
          this.setRetailPriceDisplayOption(false, this.getSkipEnrolmentPrivilege)
          return true
        })
      } else {
        if (!this.skipEnrolmentStep) {
          // save enrolment data for express checkout
          await this.saveEnrollmentTempData(this.socialAuthentication)
        }
        // checkout as guest will not get member price
        this.setRetailPriceDisplayOption(this.skipEnrolmentStep, this.getSkipEnrolmentPrivilege)
        this.enrolmentData.status = true
        return true
      }
    },
    fieldResetAndProceed() {
      // reset
      this.preferredContactData = false
      this.enrolmentData.member_data.details.name = ''
      // Move next
      this.navigateNext(false)
    },
    proceedWithGuest() {
      this.skipEnrolmentStep = true
      this.fieldResetAndProceed()
    },
    setRetailPriceDisplayOption(value, condition = true) {
      if (condition) {
        this.isRetailPrice(value)
      }
    },
  },
}
</script>
