<template>
  <login-form-template v-bind="formTemplateProps" @onBack="logoutUser()">
    <!-- Error Block ------------------------------------------------------------------------------------------------>
    <b-alert
      :show="!getErrorsState('get_verification_code_failed') || !getErrorsState('post_verification_code_failed')"
      variant="danger"
    >
      <span
        v-for="(error, errorIndex) in !getErrorsState('get_verification_code_failed')
          ? getErrorsBreakup('get_verification_code_failed')
          : getErrorsBreakup('post_verification_code_failed')"
        :key="errorIndex"
      >
        {{ error }}
      </span>
    </b-alert>
    <!-- Before Code Sent -------------------------------------------------------------------------------------------->
    <template v-if="!verificationCodeSent" @keyup.13="getVerificationCode">
      <!-- message  ------------------------------------------------------------------------------------------>
      <b-row class="mb-0" v-if="verificationError !== null">
        <b-col cols="12">
          <b-alert variant="danger" class="mr-0" show>{{ verificationError }} </b-alert>
        </b-col>
      </b-row>
      <!-- Preferred Contact ------------------------------------------------------------------------------------------>
      <b-row>
        <b-col cols="auto" lg="auto" :class="{ 'mb-3': namespace === 'byDzyne', 'col-3': namespace !== 'byDzyne' }">
          {{ $t('Common.PreferredContact') }}
        </b-col>
        <b-col>
          <b-form-radio-group
            :name="$t('Common.PreferredContact')"
            :options="preferredContactOptions"
            :value="preferredContactType"
            v-model="preferredContactType"
            ref="preferredContactType"
          />
        </b-col>
      </b-row>
      <!-- EMAIL VERIFICATION --------------------------------------------------------------------------------------->
      <b-row class="mb-1 mt-0" v-if="preferredContactType === preferredEmailId">
        <b-col lg="3" sm="12" md="12" class="text-lg-right p-0 d-flex flex-column justify-content-center p-0">
          <label class="required m-0 m-3 m-lg-0 " :class="{ required: preferredContactType === preferredEmailId }">
            {{ $t('Enrolment.Email.Label', { person: $t('Enrolment.My.Label') }) }}
          </label>
        </b-col>
        <b-col lg="9" sm="12" md="12" class="enrol-section-controls">
          <b-form-input
            size="md"
            type="text"
            :name="$t('Enrolment.Email.Label', { person: '' })"
            @input="resetError('get_verification_code_failed')"
            v-model="contact"
            ref="email"
            v-validate="preferredContactType === preferredEmailId ? 'required|email' : ''"
          />
        </b-col>
        <b-col offset-lg="3" cols="12" class="pt-2">
          <field-errors
            show
            :cerrors="errors"
            :cfields="fields"
            :name="$t('Enrolment.Email.Label', { person: '' })"
            class="text-danger"
          />
        </b-col>
      </b-row>
      <!-- Mobile Verification -------------------------------------------------------------------------------------->
      <b-row class="mb-1 mt-0" v-else>
        <b-col cols="12" lg="3" class="text-lg-right d-flex flex-column justify-content-center p-0">
          <label class="required m-0 m-3 m-lg-0 ">
            {{ $t('Enrolment.MobilePhone.Label', { person: $t('Enrolment.My.Label') }) }}
          </label>
        </b-col>
        <b-col cols="5" lg="3" class="pr-0">
          <b-form-select
            size="md"
            class="font-size-8 h-100"
            :name="$t('Enrolment.MobilePhone.Label', { person: '' })"
            v-model="contryCode"
            ref="countryCode"
            v-validate="preferredContactType === preferredPhoneId ? 'required' : ''"
            :options="getCountriesCallCode"
          />
        </b-col>
        <b-col cols="7" lg="6">
          <b-input-group
            class="col-input-group-min-width-2-plus text-lg-right h-100"
            :prepend="countryCodePrefix(contryCode)"
          >
            <b-form-input
              size="md"
              type="text"
              :name="$t('Enrolment.MobilePhone.Label', { person: '' })"
              @input="resetError('get_verification_code_failed')"
              class="h-100"
              ref="mobile"
              v-model="contact"
              v-validate="preferredContactType === preferredPhoneId ? 'required|numeric' : ''"
            />
          </b-input-group>
        </b-col>
        <b-col offset-lg="3" cols="12" class="pt-2">
          <field-errors
            :cerrors="errors"
            :cfields="fields"
            show
            :name="$t('Enrolment.MobilePhone.Label', { person: '' })"
            class="text-danger"
          />
        </b-col>
      </b-row>
      <!-- Submit --------------------------------------------------------------------------------------------------->
      <b-row class="mt-2 mb-3">
        <b-col cols="12" class="d-flex justify-content-end">
          <b-button
            v-if="getVerifyContactStatus.skipVerification"
            @click="skipPreferredContactVerification"
            :variant="namespace !== 'byDzyne' ? 'outline-light' : 'light'"
            class="text-black border-0 mr-2"
          >
            {{ $t('Common.AskMeLater') }}
          </b-button>
          <b-button
            ref="getVerificationCode"
            @click="getVerificationCode"
            @keyup.13="getVerificationCode"
            variant="primary"
          >
            <b-spinner v-show="isLoading('getEnrolmentCode')" small class="mx-3" />
            <span v-show="!isLoading('getEnrolmentCode')">{{ $t('Enrolment.SendCode.Label') }}</span>
          </b-button>
        </b-col>
      </b-row>
    </template>
    <!-- After Code Sent --------------------------------------------------------------------------------------------->
    <template v-else @keyup.13="postVerificationCode">
      <!-- message  ------------------------------------------------------------------------------------------>
      <b-row class="mb-0">
        <b-col cols="12">
          <b-alert
            v-if="verificationCodeMessage"
            :variant="namespace !== 'byDzyne' ? 'info-green' : 'success'"
            class="mr-0 ml-0"
            show
            >{{
              $t('Enrolment.VerificationSent', {
                contact:
                  preferredContactType === preferredEmailId
                    ? $t('Master.Email').toLowerCase()
                    : $t('Master.Phone').toLowerCase(),
              })
            }}
          </b-alert>
        </b-col>
      </b-row>
      <!-- OTP ------------------------------------------------------------------------------------------------------->
      <b-row class="mb-1 mt-0">
        <b-col lg="3" sm="12" md="12" class="text-lg-right p-0 d-flex flex-column justify-content-center p-0">
          <label class="required m-3 m-lg-0" :class="{ required: true }">
            {{ $t('Common.Security.VerificationCode') }}
          </label>
        </b-col>
        <b-col lg="9" sm="12" md="12" class="enrol-section-controls">
          <b-form-input
            size="md"
            type="text"
            :name="$t('Common.Security.VerificationCode')"
            @input="resetError('post_verification_code_failed')"
            :placeholder="$t('Common.Security.EnterVerificationCode')"
            v-model="verificationCode"
            v-validate="'required'"
            ref="verificationCode"
          />
        </b-col>
        <b-col offset-lg="3" cols="9" class="pt-2">
          <field-errors :cerrors="errors" :cfields="fields" show :name="$t('Common.Security.VerificationCode')" />
        </b-col>
      </b-row>
      <!-- Submit --------------------------------------------------------------------------------------------------->
      <b-row class="mt-2 mb-3">
        <b-col cols="12" class="justify-content-end d-flex">
          <b-button @click="cancelPostVerification" variant="secondary" class="btn-light mr-2">
            {{ $t('Login.LoginForm.Cancel') }}
          </b-button>
          <b-button
            :disabled="!verificationCode"
            ref="postVerificationCode"
            @click="postVerificationCode"
            @keyup.13="postVerificationCode"
            variant="primary"
          >
            <b-spinner v-show="isLoading('postEnrolmentCode')" small class="mx-4" />
            <span v-show="!isLoading('postEnrolmentCode')">{{ $t('Enrolment.Verification1.Info') }}</span>
          </b-button>
        </b-col>
      </b-row>
    </template>
  </login-form-template>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import { mapMasterDataId, PhoneMixin } from '@/app/_global/mixins'
import LoginFormTemplate from './templates/FormTemplate'
import LoginRoutingMixing from './mixins/loginRoutingMixin'
import FieldErrors from '@/elements/common/components/FieldErrors'

export default {
  name: 'PreferredContact',
  components: {
    LoginFormTemplate,
    FieldErrors,
  },
  mixins: [LoginRoutingMixing, PhoneMixin],
  props: {
    namespace: { type: String, default: 'eshop' },
  },
  data() {
    return {
      preferredContactType: '',
      contact: '',
      contryCode: '',
      verificationCodeSent: false,
      verificationCodeMessage: false,
      verificationCodeVerified: false,
      verificationCode: '',
      verificationError: null,
      isEvo: this.$appSettings.evo.enable,
    }
  },
  inject: ['$validator'],
  mounted() {
    let vue = this
    this.resolveMasters.then(() => {
      vue.preferredContactType = vue.preferredEmailId
    })
    this.loadCountries()
    this.resetError('get_verification_code_failed')
    this.resetError('post_verification_code_failed')
  },
  computed: {
    ...mapGetters([
      'getLoggedInUser',
      'getErrors',
      'getCountriesCallCode',
      'isLoading',
      'getErrorsState',
      'getErrorsBreakup',
      'getVerifyContactStatus',
      'getChangePasswordStatus',
    ]),
    ...mapGetters('enrolment', ['getVerificationResponse', 'postVerificationResponse']),
    ...mapMasterDataId({
      PREFERRED_CONTACT: {
        preferredEmailId: 'EMAIL',
        preferredPhoneId: 'PHONE',
        preferredContactOptions: 'options',
      },
    }),
    formTemplateProps() {
      let props = {
        showBack: true,
        namespace: this.namespace,
        showLogo: true,
        text: this.$t('Login.LoginForm.OnBehalfWelcome.Message'),
        'form-class': "['justify-content-start']",
      }

      if (this.isEvo) {
        props['showLogo'] = false
        props['namespace'] = 'evo'
      }

      return props
    },
  },
  methods: {
    ...mapActions([
      'loadCountries',
      'resetError',
      'logError',
      'resetFirstTimeLogin',
      'setPreferredContactVerificationStatus',
      'logoutUser',
    ]),
    ...mapActions('enrolment', ['getCode', 'postCode', 'removeVerificationGetCode', 'postTempEnrolment']),
    getVerificationCode() {
      if (!this.isLoading('getEnrolmentCode')) {
        let self = this
        self.verificationError = null
        this.$validator.validateAll().then(valid => {
          if (valid) {
            self.resetError('get_verification_code_failed')
            let query = {
              user_id: self.getLoggedInUser.id,
            }
            if (self.preferredContactType === self.preferredEmailId) {
              query.type = 'email'
              query.verification_email = self.contact
            } else {
              query.type = 'phone'
              query.call_code_id = self.contryCode
              query.verification_mobile = self.contact
            }
            self.getCode(query).then(() => {
              if (!this.verificationCodeSent) {
                if (self.getVerificationResponse.status !== undefined) {
                  self.verificationError = self.getVerificationResponse.status
                } else if (Object.keys(self.getVerificationResponse).length > 0) {
                  self.verificationCodeSent = true
                  self.verificationCodeMessage = true
                }
              }
            })
          }
        })
      }
    },
    cancelPostVerification() {
      this.resetError('post_verification_code_failed')
      this.verificationCodeSent = false
    },
    postVerificationCode() {
      if (!this.isLoading('postEnrolmentCode')) {
        let self = this
        this.verificationCodeMessage = false
        this.$validator.validateAll().then(valid => {
          if (valid) {
            let query = {
              user_id: self.getLoggedInUser.id,
              preferred_contact_id: self.preferredContactType,
              on_behalf_enrolment: 1,
            }
            if (self.preferredContactType === self.preferredEmailId) {
              query.type = 'email'
              query.verification_email = self.contact
              query.verification_code = self.verificationCode
            } else {
              query.type = 'phone'
              query.verification_code = self.verificationCode
              query.call_code_id = self.contryCode
              query.verification_mobile = self.contact
            }
            self.postCode(query).then(() => {
              if (
                Object.keys(self.postVerificationResponse).length > 0 &&
                self.postVerificationResponse.verified === 1
              ) {
                self.setPreferredContactVerificationStatus({ requires: false })
                if (!this.getChangePasswordStatus) {
                  this.$nextTick(() => {
                    this.$router.push({ name: 'DashboardHome' })
                  })
                }
              } else {
                self.logError({
                  post_verification_code_failed: [self.postVerificationResponse.status],
                })
              }
            })
          }
        })
      }
    },
    skipPreferredContactVerification() {
      if (this.getChangePasswordStatus) {
        this.setPreferredContactVerificationStatus({ requires: false })
      } else {
        this.$router.push({ name: 'DashboardHome' })
      }
    },
  },
  watch: {
    preferredContactType() {
      this.$nextTick(() => {
        this.contact = ''
      })
    },
  },
}
</script>
