<template>
  <tabs-template>
    <div class="eshop">
      <b-row class="m-0 pt-3">
        <b-col cols="12" md="auto" class="text-center text-md-left">
          <img :src="getProfilePicture" class="rounded-circle object-fit-cover" />
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pt-3 px-0">
          <input type="file" id="avatarFile" ref="avatarFile" class="mt-3" accept="image/*" @change="handleClickFile" />
        </b-col>
        <b-col v-if="uploadFileStatus" class="col-12 col-md-5 pt-4 text-right pl-md-5 pl-2 pb-2 ">
          <b-button variant="link" @click="cancelAvatarUpload">{{ $t('Common.Cancel') }}</b-button>
          <b-button variant="primary" @click="savePInfo">{{ $t('Common.SaveChanges') }}</b-button>
        </b-col>
      </b-row>
      <b-row class="title ma-title mt-4 mt-md-2h">
        {{ $t('MyAccount.PersonalInfo.PersonalDetails') }}
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
          <label> {{ $t('MyAccount.PersonalInfo.Nationality') }} </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-select v-model="localMemberDetails.details.nationality_id" disabled :options="getNationalityList" />
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-0 pt-lg-2">
          <label> {{ $t('MyAccount.PersonalInfo.NamePerIDPassport') }} </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-input disabled :value="localMemberDetails.details.name" />
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0" v-if="getOnDemandFieldsConfig('translated_name')">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
          <label class="required">
            {{ $t('MyAccount.PersonalInfo.TranslatedName') }}
          </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-input disabled :value="localMemberDetails.details.translated_name" />
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
          <label> {{ $t('Common.MemberID') }} </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-input
            disabled
            :value="localMemberDetails.details.user.old_member_id || localMemberDetails.details.user.old_ibs_user_id"
          />
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0">
          <label class="required">
            {{ $t('MyAccount.PersonalInfo.Gender') }}
          </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-radio-group v-model="localMemberDetails.information.gender_id" name="Gender">
            <b-form-radio v-for="(temp, idx) in genderTypeOptions" :key="idx" :value="temp.value">
              {{ temp.text }}
            </b-form-radio>
          </b-form-radio-group>
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
          <label class="required">
            {{ $t('MyAccount.PersonalInfo.IDPassportNo') }}
          </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-input :value="localMemberDetails.details.ic_passport_number" disabled />
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-3">
          <label> {{ $t('MyAccount.PersonalInfo.UploadIDPassport') }} </label>
        </b-col>
        <b-col cols="12" md="auto" class="pl-0 pl-md-3">
          <input
            type="file"
            id="passportFile"
            ref="passportFile"
            class="mt-3"
            accept="image/*"
            @change="handleClickPassportFile"
            :placeholder="$t('MyAccount.PersonalInfo.PlaceHolder.ChangePicture')"
          />
        </b-col>
        <b-col v-if="uploadPassportStatus" class="text-right text-md-left pt-3">
          <button class="btn btn-primary" @click="savePInfo">
            {{ $t('MyAccount.PersonalInfo.SaveChanges') }}
          </button>
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-sm-3" />
        <b-col cols="12" md="7" class="text-sm-left text-md-right pl-md-3 pl-0">
          <b-row v-for="(item, idx) in localMemberDetails.verification" :key="idx" class="pl-3">
            <img :src="item.image_link" class="object-fit-cover" />
            <button type="button" class="close ml-4" aria-label="Close" @click="removePassport(idx)">
              <span aria-hidden="true">
                &times;
              </span>
            </button>
          </b-row>
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
          <label> {{ $t('MyAccount.PersonalInfo.DateOfBirth') }} </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <custom-date-picker :value="localMemberDetails.details.date_of_birth" disabled :clear-button="false" />
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
          <label class="required">
            {{ $t('MyAccount.PersonalInfo.EthnicGroup') }}
          </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-select v-model="localMemberDetails.information.ethnic_group_id" :options="ethnicGroupOptions" />
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
          <label class="required">
            {{ $t('MyAccount.PersonalInfo.PreferredLanguage') }}
          </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-select
            v-model="localMemberDetails.information.language_id"
            v-validate="'required'"
            :class="{ 'is-danger': errors.has('Preferred Language') }"
            name="Preferred Language"
            :options="getLanguageList"
          />
          <span v-show="errors.has('Preferred Language')" class="help is-danger">
            {{ errors.first('Preferred Language') }}
          </span>
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
          <label class="required">
            {{ $t('MyAccount.PersonalInfo.MaritalStatus') }}
          </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-select
            v-model="localMemberDetails.information.martial_status_id"
            v-validate="'required'"
            :class="{ 'is-danger': errors.has('Marital Status') }"
            name="Marital Status"
            :options="maritalStatusOptions"
          />
          <span v-show="errors.has('Marital Status')" class="help is-danger">
            {{ errors.first('Marital Status') }}
          </span>
          <b-form-text v-if="$appSettings.evo.enable">
            <span v-show="isMarried">{{ $t('Common.PersonalInfo.SpouseDetailsDisclaimer') }}</span>
          </b-form-text>
        </b-col>
      </b-row>

      <spouse-info
        v-if="$appSettings.evo.enable"
        :is-married="isMarried"
        :ic-passport-type-col-classes="['col-4']"
        :row-classes="['pt-3', 'ml-md-3', 'ml-0']"
        :value="localMemberDetails.information.spouse"
        :ic-passport-type-options="icPassportTypeOption"
        @input="val => (localMemberDetails.information.spouse = val)"
        :input-col-classes="['col-12', 'col-md-8', 'col-lg-5', 'pl-0', 'pl-md-3']"
        :label-col-classes="['col-11', 'col-md-2', 'text-sm-left', 'text-md-right', 'pl-md-3', 'pl-0', 'pt-md-2']"
        data-qa-prefix="myAccount-personalInfo"
      />

      <b-row
        class="pt-3 ml-md-3 ml-0"
        v-if="getOnDemandFieldsConfig($const.masterKey.MEMBER_DEPENDENT_REQUIRED, 'getMasterDataOptionsByKey')"
      >
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
          <label class="required">
            {{ $t('MyAccount.PersonalInfo.Dependent') }}
          </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-select
            v-model="localMemberDetails.information.dependent_id"
            v-validate="'required'"
            :class="{ 'is-danger': errors.has('Tax Dependent Status') }"
            name="Tax Dependent Status"
            :options="getDependentList"
          />
          <span v-show="errors.has('Tax Dependent Status')" class="help is-danger">
            {{ errors.first('Tax Dependent Status') }}
          </span>
        </b-col>
      </b-row>
      <b-row v-if="!$appSettings.evo.enable" class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
          <label> {{ $t('Common.TinNoTaiwan') }} </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-input
            name="TIN No Taiwan"
            :disabled="localMemberDetails.details.tin_no_taiwan_verified === 1"
            v-validate="{
              required:
                getOnDemandFieldsConfig($const.masterKey.MEMBER_TIN_NUMBER_TAIWAN_REQUIRED) &&
                localMemberDetails.details.tin_no_taiwan_verified === 0,
            }"
            v-model="localMemberDetails.details.tin_no_taiwan"
          />
          <span v-show="errors.has('TIN No Taiwan')" class="help is-danger">
            {{ errors.first('Tax Dependent Status') }}
          </span>
        </b-col>
      </b-row>
      <b-row v-if="!$appSettings.evo.enable" class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-sm-left text-md-right pl-md-3 pl-0 pt-md-2">
          <label> {{ $t('Common.TinNoPhilippines') }} </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-input
            name="TIN No Philippines"
            v-validate="{
              required:
                getOnDemandFieldsConfig($const.masterKey.MEMBER_TIN_NUMBER_PHILIPPINES_REQUIRED) &&
                localMemberDetails.details.tin_no_philippines_verified === 0,
            }"
            :disabled="localMemberDetails.details.tin_no_philippines_verified === 1"
            v-model="localMemberDetails.details.tin_no_philippines"
          />
          <span v-show="errors.has('TIN No Philippines')" class="help is-danger">
            {{ errors.first('Tax Dependent Status') }}
          </span>
        </b-col>
      </b-row>
      <b-row class="title ma-title mt-4">
        {{ $t('Common.ContactDetails') }}
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-left text-md-right pl-0 pl-md-3">
          <label class="required">
            {{ $t('Common.PreferredContact') }}
          </label>
        </b-col>
        <b-col cols="12" md="7" lg="5" class="pl-0 pl-md-3">
          <b-form-radio-group
            v-model="localMemberDetails.contact_info.preferred_contact_id"
            :disabled="showCancel || showCancelEmail || showUpdate || showUpdateEmail"
            name="radioContact"
          >
            <b-form-radio v-for="(temp, idx) in preferredContactOptions" :key="idx" :value="temp.value">
              {{ temp.text }}
            </b-form-radio>
          </b-form-radio-group>
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-left text-md-right pl-0 pl-md-3 pt-md-2">
          <label :class="{ required: isUserPreferPhoneContact }">
            {{ $t('EWallet.GlobalWords.MobilePhone') }}
          </label>
        </b-col>
        <b-col cols="12" md="4" lg="2" class="pl-0 pl-md-3">
          <b-form-select
            v-model="mobile1Code"
            :disabled="showCancel || showCancelEmail || showUpdateEmail || isUserPreferEmailContact"
            :options="getCountriesCallCode"
            @change="checkMobileCallCodeChange"
          >
          </b-form-select>
        </b-col>
        <b-col cols="12" md="4" lg="3" class="pl-0 pt-2 pt-md-0">
          <b-input-group class="col-input-group-min-width-3 text-right" :prepend="countryCodePrefix(mobile1Code)">
            <b-form-input
              v-model="mobile1Num"
              :disabled="showCancel || showCancelEmail || showUpdateEmail || isUserPreferEmailContact"
              v-validate="'numeric'"
              :v-validate="{ required: isUserPreferPhoneContact }"
              name="Mobile Phone"
              :class="{ input: true, 'is-danger': errors.has('Mobile Phone') }"
              @input="checkMobileChange"
            >
            </b-form-input>
            <span v-show="errors.has('Mobile Phone')" class="help is-danger">
              {{ errors.first('Mobile Phone') }}
            </span>
          </b-input-group>
        </b-col>
        <b-col cols="4" md="2" class="pl-0 pt-3 pt-md-0">
          <button v-if="showUpdate" class="btn btn-primary text-primary bg-transparent" @click="handleShowUpdate">
            {{ $t('EWallet.GlobalWords.Update') }}
          </button>
          <button v-if="showCancel" class="btn btn-primary text-primary bg-transparent" @click="handleCancel">
            {{ $t('EWallet.GlobalWords.Cancel') }}
          </button>
        </b-col>
      </b-row>
      <b-row v-if="showSendCode" class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-left text-md-right pl-3 pt-md-2" />
        <b-col class="col-md-2 col-5 pl-0 pl-md-3">
          <button class="btn btn-primary filled" :disabled="requestCodeStatus" @click="handleSendCode">
            {{ $t('MyAccount.PersonalInfo.SendCode') }}
          </button>
        </b-col>
        <b-col cols="7" md="2" lg="3" class="pl-0">
          <b-form-input
            v-model="verificationCode"
            :placeholder="$t('MyAccount.PersonalInfo.Placeholder.VerificationCode')"
          />
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-left text-md-right pl-0 pl-md-3 pt-md-2">
          <label :class="{ required: isUserPreferEmailContact }">
            {{ $t('Master.Email') }}
          </label>
        </b-col>
        <b-col cols="12" md="8" lg="5" class="pl-0 pl-md-3">
          <b-form-input
            v-model="retypeEmailTemp"
            @input="handleEmailChange"
            name="Email"
            v-validate="'email'"
            :v-validate="{ required: isUserPreferEmailContact }"
            :disabled="showCancel || showCancelEmail || showUpdate || isUserPreferPhoneContact"
            :class="{ 'is-danger': emailNotSame }"
          />
          <span v-show="emailNotSame" class="help is-danger">
            {{ $t('MyAccount.PersonalInfo.EmailNotSame') }}
          </span>
          <span v-show="errors.has('Email')" class="help is-danger">
            {{ errors.first('Email') }}
          </span>
        </b-col>
        <b-col cols="4" md="2" class="pl-0 pt-3 pt-md-0">
          <button
            v-if="showUpdateEmail"
            class="btn btn-primary text-primary bg-transparent"
            @click="handleShowUpdateEmail"
          >
            {{ $t('EWallet.GlobalWords.Update') }}
          </button>
          <button v-if="showCancelEmail" class="btn btn-primary text-primary bg-transparent" @click="handleCancelEmail">
            {{ $t('EWallet.GlobalWords.Cancel') }}
          </button>
        </b-col>
      </b-row>
      <b-row v-if="showSendCodeEmail" class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-left text-md-right pl-0 pl-md-3 pt-md-2" />
        <b-col class="col-md-2 col-5 pl-0 pl-md-3">
          <button class="btn btn-primary filled" :disabled="requestCodeStatusEmail" @click="handleSendCodeEmail">
            {{ $t('MyAccount.PersonalInfo.SendCode') }}
          </button>
        </b-col>
        <b-col cols="7" md="2" lg="3" class="pl-0 pl-md-0">
          <b-form-input
            v-model="verificationCodeEmail"
            :placeholder="$t('MyAccount.PersonalInfo.Placeholder.VerificationCode')"
          />
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-left text-md-right pl-0 pl-md-3 pt-md-2">
          <label> {{ $t('MyAccount.PersonalInfo.HomePhone') }} </label>
        </b-col>
        <b-col cols="12" md="4" lg="2" class="pl-0 pl-md-3">
          <b-form-select
            v-model="localMemberDetails.contact_info.tel_home_1_country_code_id"
            :options="getCountriesCallCode"
          />
        </b-col>
        <b-col cols="12" md="4" lg="3" class="pl-0 mt-2 mt-md-0">
          <b-input-group
            class="col-input-group-min-width-3 text-right"
            :prepend="countryCodePrefix(localMemberDetails.contact_info.tel_home_1_country_code_id)"
          >
            <b-form-input v-model="localMemberDetails.contact_info.tel_home_1_num"> </b-form-input>
          </b-input-group>
        </b-col>
      </b-row>
      <b-row class="pt-3 ml-md-3 ml-0">
        <b-col cols="11" md="2" class="text-left text-md-right pl-0 pl-md-3 pt-md-2">
          <label> {{ $t('MyAccount.PersonalInfo.OfficePhone') }} </label>
        </b-col>
        <b-col cols="12" md="4" lg="2" class="pl-0 pl-md-3">
          <b-form-select
            v-model="localMemberDetails.contact_info.tel_office_1_country_code_id"
            :options="getCountriesCallCode"
          />
        </b-col>
        <b-col cols="12" md="4" lg="3" class="pl-0 mt-2 mt-md-0">
          <b-input-group
            class="col-input-group-min-width-3 text-right"
            :prepend="countryCodePrefix(localMemberDetails.contact_info.tel_office_1_country_code_id)"
          >
            <b-form-input v-model="localMemberDetails.contact_info.tel_office_1_num"> </b-form-input>
          </b-input-group>
        </b-col>
      </b-row>
      <b-row class="py-3" v-if="!isLoading('myAccountInfo')">
        <b-col class="text-md-right text-left offset-md-10">
          <button
            class="btn btn-primary w-100"
            @click="savePInfo"
            :disabled="(!requestCodeStatus && showCancel) || (!requestCodeStatusEmail && showCancelEmail) || savingData"
          >
            <icon name="spinner" pulse v-if="savingData" />
            <span v-else>
              {{ $t('MyAccount.PersonalInfo.SaveChanges') }}
            </span>
          </button>
        </b-col>
      </b-row>
      <b-modal ref="changePersonalInfoModal" class="eshop-model" ok-only size="sm" hide-header centered @ok="handleOk">
        <h5 v-if="responseStatus">
          {{ $t('MyAccount.PersonalInfo.SaveChanges.Success') }}
        </h5>
        <h5 v-else>
          {{ $t('MyAccount.PersonalInfo.SaveChanges.Failed') }}
        </h5>
      </b-modal>
      <b-modal
        ref="verifyMobileNumber"
        class="eshop-model"
        ok-only
        size="sm"
        hide-header
        centered
        @ok="handleVerifyMobileNumberOk"
      >
        <h5>{{ mobileMessage }}</h5>
      </b-modal>
    </div>
  </tabs-template>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import Vue from 'vue'
import MyAccountTabsTemplate from './templates/MyAccountTabsTemplate'
import { mapMasterDataId, PhoneMixin, UploaderMixin } from '@/app/_global/mixins'
import { getValue } from '@/helpers/variable-handling'
import SpouseInfo from '@/app/_global/components/blocks/SpouseInfo'
import CustomDatePicker from '@/elements/common/components/CustomDatePicker'

export default {
  name: 'PersonalInfo',
  components: {
    CustomDatePicker,
    SpouseInfo,
    TabsTemplate: MyAccountTabsTemplate,
  },
  mixins: [PhoneMixin, UploaderMixin],
  $_veeValidate: {
    validator: 'new',
  },
  data() {
    return {
      profilePicture: '/static/misc/img-avatar-default.png',
      profilePictureMale: '/static/misc/img-default-male.png',
      profilePictureFemale: '/static/misc/img-default-female.png',
      mobileMessage: '',
      uploadFileStatus: false,
      uploadPassportStatus: false,
      avatarLink: null,
      namePerIdPassport: null,
      tinTaiwan: null,
      tinPhilips: null,
      responseStatus: true,
      showUpdate: false,
      showUpdateEmail: false,
      showCancel: false,
      showCancelEmail: false,
      showSendCode: false,
      showSendCodeEmail: false,
      requestCodeStatus: false,
      requestCodeStatusEmail: false,
      tempMobileNumber: '',
      verificationCode: '',
      verificationCodeEmail: '',
      retypeEmailTemp: '',
      userTypedEmail: null,
      showRetypeEmail: false,
      emailNotSame: false,
      mobile1Code: null,
      mobile1Num: '',
      tempAvatarInfo: {},
      localMemberDetails: {
        details: {
          avatar_image_link: null,
          avatar_image_path: null,
          user_id: null,
          name: null,
          nationality_id: null,
          ic_passport_number: null,
          date_of_birth: null,
          tin_no_taiwan: null,
          tin_no_philippines: null,
          translated_name: null,
          user: {
            name: null,
            old_ibs_user_id: null,
            old_member_id: null,
            email: null,
          },
        },
        information: {
          user_id: null,
          gender_id: null,
          ethnic_group_id: null,
          language_id: null,
          martial_status_id: null,
          spouse: {
            spouse_elken_member: 0,
            spouse_ibo_id: '',
            ic_pass_type_id: null,
            ic_pass_type_number: '',
            spouse_name: '',
            dob: null,
          },
          dependent_id: null,
        },
        contact_info: {
          preferred_contact_id: null,
          mobile_1_country_code_id: null,
          mobile_1_num: null,
          mobile_1_activated: false,
          tel_home_1_country_code_id: null,
          tel_home_1_num: null,
          tel_office_1_country_code_id: null,
          tel_office_1_num: null,
        },
        verification: [],
      },
      savingData: false,
    }
  },
  methods: {
    ...mapActions([
      'loadCountryDynamicContent',
      'loadMyAccountCountries',
      'loadBankList',
      'loadLanguages',
      'loadPreferredContact',
      'loadAllCountries',
      'fetchCountryList',
      'loadGenderList',
      'updateMemberDetails',
      'requestNewCode',
      'activateMobileCode',
      'validateEmail',
      'loadMasterDataKeysEnrolment',
      'loadCountryRelation',
    ]),
    cancelAvatarUpload() {
      // cancel here upload avatar
      this.avatarLink = this.getMyAccountMemberDetails.details.avatar_image_link
      document.getElementById('avatarFile').value = null
      this.uploadFileStatus = false
    },
    async handleClickFile(e) {
      let self = this
      this.files = this.$refs.avatarFile.files
      this.params = { file_type: 'member_avatar' }
      this.uploader('profile-avatar').then(() => {
        if (self.getUploads.length > 0) {
          self.getUploads.forEach(item => {
            self.localMemberDetails.details.avatar_image_path = item.name
            self.avatarLink = item.link
            self.uploadFileStatus = true
          })
        } else {
          self.$refs.avatarFile.value = null
          self.uploadFileStatus = false
        }
      })
    },
    handleClickPassportFile(e) {
      let self = this
      this.files = this.$refs.passportFile.files
      this.params = { file_type: 'member_ic_passport' }
      this.uploader('ic-passport').then(() => {
        if (self.getUploads.length > 0) {
          self.getUploads.forEach(item => {
            self.localMemberDetails.verification.push({
              image_link: item.link,
              image_path: item.name,
              type: 'IC',
              user_id: this.localMemberDetails.details.user_id,
            })
            self.uploadPassportStatus = true
          })
        } else {
          self.$refs.passportFile.value = null
          self.uploadPassportStatus = false
        }
      })
    },
    removePassport(index) {
      this.localMemberDetails.verification.splice(index, 1)
    },
    savePInfo() {
      let parent = this
      this.$validator.validateAll().then(valid => {
        if (valid) {
          if (!this.requestCodeStatusEmail && !this.requestCodeStatus) {
            // Save personal info
            this.savingData = true
            if (parent.localMemberDetails.information.user_id === null) {
              parent.localMemberDetails.information.user_id = parent.localMemberDetails.details.user_id
            }
            this.updateMemberDetails(parent.localMemberDetails).then(result => {
              if (!result) {
                this.responseStatus = false
              }
              this.uploadFileStatus = false
              this.uploadPassportStatus = false
              this.$refs.changePersonalInfoModal.show()
              this.savingData = false
            })
          }

          if (this.requestCodeStatus) {
            // Todo handler for mobile change
            let data = {
              code: this.verificationCode,
              mobile_1_country_code_id: this.mobile1Code,
              mobile_1_num: this.mobile1Num,
              request_type: 'activate',
            }
            this.activateMobileCode(data).then(res => {
              if (res.status === 'ok') {
                this.localMemberDetails.contact_info.mobile_1_activated = 1
                this.localMemberDetails.contact_info.mobile_1_country_code_id = this.mobile1Code
                this.localMemberDetails.contact_info.mobile_1_num = this.mobile1Num
                this.updateMemberDetails(this.localMemberDetails).then(result => {
                  if (result) {
                    this.requestCodeStatus = false
                    this.showCancel = false
                    this.showSendCode = false
                    this.responseStatus = true
                    this.mobileMessage = Vue.i18n.translate('MyAccount.PersonalInfo.SaveChanges.Success')
                    this.verificationCode = ''
                  }
                })
              } else {
                this.mobileMessage = res.message
                this.responseStatus = false
              }
              this.$refs.verifyMobileNumber.show()
            })
          }

          if (this.requestCodeStatusEmail) {
            // handle email here
            let data = {
              email: this.retypeEmailTemp,
              code: this.verificationCodeEmail,
            }
            this.validateEmail(data).then(res => {
              if (res.status === 'ok') {
                parent.localMemberDetails.details.user.email = this.retypeEmailTemp
                parent.localMemberDetails.contact_info.email = parent.localMemberDetails.details.user.email
                parent.updateMemberDetails(parent.localMemberDetails).then(result => {
                  if (result) {
                    parent.requestCodeStatusEmail = false
                    parent.showCancelEmail = false
                    parent.showSendCodeEmail = false
                    parent.responseStatus = true
                    parent.mobileMessage = Vue.i18n.translate('MyAccount.PersonalInfo.SaveChanges.Success')
                    parent.verificationCodeEmail = ''
                  }
                })
              } else if (res.status === 'already_verified') {
                parent.mobileMessage = res.message
                parent.requestCodeStatusEmail = false
                parent.showCancelEmail = false
                parent.showSendCodeEmail = false
                parent.responseStatus = true
                parent.verificationCodeEmail = ''
                parent.showUpdateEmail = false
                parent.localMemberDetails.details.user.email = this.retypeEmailTemp
              } else {
                parent.mobileMessage = res.message
                parent.responseStatus = false
              }
              this.$refs.verifyMobileNumber.show()
            })
          }
        }
      })
    },
    handleOk() {
      if (!this.responseStatus) {
        this.cancelAvatarUpload()
      }
    },
    checkMobileCallCodeChange(val) {
      this.showUpdate = val !== this.localMemberDetails.contact_info.mobile_1_country_code_id
    },
    checkMobileChange(val) {
      this.showUpdate = val !== this.localMemberDetails.contact_info.mobile_1_num && val.length > 3
    },
    handleShowUpdate() {
      this.showUpdate = false
      this.showCancel = true
      this.showSendCode = true
    },
    handleShowUpdateEmail() {
      this.showUpdateEmail = false
      this.showCancelEmail = true
      this.showSendCodeEmail = true
    },
    handleCancel() {
      this.showCancel = false
      this.showSendCode = false
      this.requestCodeStatus = false
      this.mobile1Code = this.localMemberDetails.contact_info.mobile_1_country_code_id
      this.mobile1Num = this.localMemberDetails.contact_info.mobile_1_num
    },
    handleCancelEmail() {
      this.showCancelEmail = false
      this.showSendCodeEmail = false
      this.requestCodeStatusEmail = false
      this.retypeEmailTemp = this.localMemberDetails.details.user.email
    },
    handleSendCode() {
      let data = {
        mobile_1_country_code_id: this.mobile1Code,
        mobile_1_num: this.mobile1Num,
      }
      this.requestNewCode(data).then(res => {
        if (res.status === 'ok') {
          this.mobileMessage = Vue.i18n.translate('MyAccount.PersonalInfo.VerificationCode')
          this.requestCodeStatus = true
        } else if (res.status === 'already_verified') {
          this.mobileMessage = Vue.i18n.translate('MyAccount.PersonalInfo.MobileAlreadyVerified')
          this.requestCodeStatus = true
        } else {
          this.mobileMessage = res.message
        }
        this.$refs.verifyMobileNumber.show()
      })
    },
    handleSendCodeEmail() {
      this.userTypedEmail = this.retypeEmailTemp
      let data = {
        email: this.userTypedEmail,
      }
      this.validateEmail(data).then(res => {
        if (res.status === 'ok') {
          this.mobileMessage = Vue.i18n.translate('MyAccount.PersonalInfo.VerificationCodeEmail')
          this.requestCodeStatusEmail = true
        } else if (res.status === 'already_verified') {
          this.mobileMessage = Vue.i18n.translate('MyAccount.PersonalInfo.MobileAlreadyVerified')
          this.requestCodeStatusEmail = true
        } else if (res.status === 'already sent') {
          this.requestCodeStatusEmail = true
          this.mobileMessage = res.message
        } else {
          this.mobileMessage = res.message
        }
        this.$refs.verifyMobileNumber.show()
      })
    },
    handleVerifyMobileNumberOk() {
      this.mobileMessage = ''
      if (this.userTypedEmail !== null && !this.requestCodeStatusEmail) {
        this.handleCancelEmail()
        this.retypeEmailTemp = this.userTypedEmail
        this.handleEmailChange(this.userTypedEmail)
      }
    },
    handleEmailChange(val) {
      if (val !== this.localMemberDetails.details.user.email && val.length > 3) {
        this.showUpdateEmail = true
      } else {
        this.showUpdateEmail = false
      }
    },
    setDefaultValue() {
      if (this.localMemberDetails.information.gender_id === null) {
        this.localMemberDetails.information.gender_id = this.maleId
      }
      if (this.localMemberDetails.information.ethnic_group_id === null) {
        this.localMemberDetails.information.ethnic_group_id = this.ethnicOthersId
      }
      if (this.localMemberDetails.contact_info.preferred_contact_id === null) {
        this.localMemberDetails.contact_info.preferred_contact_id = this.preferredEmailId
      }
    },
    getOnDemandFieldsConfig(key, dataFrom = 'getEnrolmentMasterDataOptionsByKey') {
      if (this[dataFrom](key).length > 0) {
        if (this[dataFrom](key)[0].text !== undefined) {
          if (this[dataFrom](key)[0].text === 'True' || this[dataFrom](key)[0].text === 'true') {
            return true
          }
        }
      }
      return false
    },
  },
  watch: {
    getMyAccountMemberDetails(to) {
      if (typeof to !== 'undefined') {
        this.loadCountryDynamicContent()
        this.loadMyAccountCountries()
        this.loadBankList(to.details.nationality_id)
        this.loadLanguages({ country_id: to.details.nationality_id })
        this.loadAllCountries()
        this.setDefaultValue()
        this.loadCountryRelation({ country_id: this.getMemberCountryId, relations: ['MemberDependentConfig'] })
        this.localMemberDetails = {
          details: { ...(to.details || {}) },
          information: {
            ...{
              ...to.information,
              ethnic_group_id: to.information.ethnic_group_id || this.ethnicGroupOptions[0].value,
            },
          },
          contact_info: {
            ...{
              ...to.contact_info,
              preferred_contact_id: to.contact_info.preferred_contact_id || this.preferredEmailId,
            },
          },
          verification: [...(to.verification || [])],
        }

        this.retypeEmailTemp = getValue(to, 'details.user.email', '')
        this.avatarLink = getValue(to, 'details.avatar_image_link', null)
        this.mobile1Num = getValue(to, 'contact_info.mobile_1_num', null)
        this.mobile1Code = getValue(to, 'contact_info.mobile_1_country_code_id', null)
      }
    },
  },
  computed: {
    ...mapGetters([
      'isLoading',
      'getCountriesCallCode',
      'getCountriesList',
      'getLanguageList',
      'getAvatarFile',
      'getMyAccountMemberDetails',
      'getPreferredContactNameById',
      'getNationalityList',
      'getEnrolmentMasterDataOptionsByKey',
      'getMasterDataOptionsByKey',
      'getMemberCountryId',
      'getDependentList',
      'getUploads',
    ]),
    ...mapMasterDataId({
      PREFERRED_CONTACT: {
        preferredEmailId: 'EMAIL',
        preferredPhoneId: 'PHONE',
        preferredContactOptions: 'options',
      },
      GENDER: {
        maleId: 'MALE',
        femaleId: 'FEMALE',
        genderTypeOptions: 'options',
      },
      ETHNIC_GROUP: {
        ethnicOthersId: 'ETHNIC_OTHERS',
        ethnicGroupOptions: 'options',
      },
      IC_PASSPORT_TYPE: {
        icPassportTypeOption: 'options',
      },
      martial_status: {
        maritalStatusOptions: 'options',
      },
      MEMBER_DEPENDENT_REQUIRED: {},
      MEMBER_TIN_NUMBER_TAIWAN_REQUIRED: {},
      MEMBER_TIN_NUMBER_PHILIPPINES_REQUIRED: {},
      MEMBER_TRANSLATED_NAME_REQUIRED: {},
    }),
    getProfilePicture() {
      let image = this.profilePicture

      if (this.avatarLink) {
        image = this.avatarLink
      } else if (this.getMyAccountMemberDetails.information) {
        let userGender = getValue(this.localMemberDetails, 'information.gender_id')
        image =
          (userGender === this.maleId && this.profilePictureMale) ||
          (userGender === this.femaleId && this.profilePictureFemale) ||
          this.profilePicture
      }

      return image
    },
    isMarried() {
      let marriedOption = (this.maritalStatusOptions || []).find(val => val.key === 'married') || {}
      return this.localMemberDetails.information.martial_status_id === marriedOption.value
    },
    isUserPreferEmailContact() {
      return this.localMemberDetails.contact_info.preferred_contact_id === this.preferredEmailId
    },
    isUserPreferPhoneContact() {
      return this.localMemberDetails.contact_info.preferred_contact_id === this.preferredPhoneId
    },
  },
}
</script>
