<template>
  <login-form-template v-bind="formTemplateProps" @onBack="backToLogin">
    <b-container @keyup.13="resetPassword" class="px-0">
      <b-row class="login-text pl-0" v-if="userIdData !== null">
        <b-col class="col-12">
          {{ $t('Login.LoginForm.EnterOTP') }}
        </b-col>
      </b-row>
      <b-row v-if="!isEnterOtp">
        <b-col class="col-12">
          <span>{{ $t('Login.LoginForm.ResetPassword.Note') }}</span>
        </b-col>
      </b-row>
      <div class="my-0">
        <b-col class="px-0 col-12" v-if="userIdData === null">
          <b-alert
            :variant="namespace !== 'byDzyne' ? 'info-green' : 'success'"
            v-if="getResetResponseData !== null"
            show
          >
            {{ isMobile ? $t('Login.LoginForm.MobileResetMessage') : $t('Login.LoginForm.EmailResetMessage') }}
          </b-alert>
          <b-alert variant="danger" v-if="getResetErrorStatus" show>
            <ul class="mb-0" :class="{ 'list-inline': resetErrorMsg.length === 1, 'pl-3': resetErrorMsg.length > 1 }">
              <li v-for="(error, index) in resetErrorMsg" :key="`error-${index}`">
                {{ error }}
              </li>
            </ul>
          </b-alert>
        </b-col>
        <b-col class="px-0 col-12" v-else>
          <b-alert variant="danger" v-if="getResetErrorStatus" show>
            {{ resetErrorMsg }}
          </b-alert>
        </b-col>
      </div>
      <div v-if="isEnterOtp">
        <b-row class="my-2" v-if="userIdData === null">
          <b-col class="col-12">
            <b-form-input v-model="maskingText" disabled name="email" type="text" />
          </b-col>
        </b-row>
        <b-row class="my-2">
          <b-col class="col-12">
            <b-form-input
              trim
              v-model="otp"
              v-validate="'required|digits:6'"
              :class="{ input: true, 'text-danger border-danger': errors.has('OTP') && showValidationErrors }"
              name="OTP"
              type="text"
              ref="otp"
              :placeholder="$t('Login.LoginForm.OTP.Placeholder')"
            />
            <span v-show="errors.has('OTP') && showValidationErrors" class="help text-danger">
              {{ errors.first('OTP') }}
            </span>
          </b-col>
        </b-row>
      </div>
      <div v-else>
        <b-row class="my-2">
          <b-col class="col-12">
            <b-form-input
              trim
              v-model="newPassword"
              ref="newPassword"
              v-validate="'required|alpha_num|min:6|regex:^(.*[A-Z].*)'"
              :class="{ input: true, 'text-danger': errors.has('new-password') }"
              data-vv-as="New Password"
              name="new-password"
              type="password"
              key="password-input"
              :placeholder="$t('Login.LoginForm.NewPassword.Placeholder')"
            />
            <span v-show="errors.has('new-password')" class="help text-danger">
              {{ $t('Login.LoginForm.ResetPassword.Note') }}
            </span>
          </b-col>
        </b-row>
        <b-row class="my-2">
          <b-col class="col-12">
            <b-form-input
              trim
              v-model="retypeNewPassword"
              v-validate="'required|confirmed:newPassword'"
              :class="{ input: true, 'text-danger': errors.has('confirm new password') && showValidationErrors }"
              id="confirm-new-password"
              name="confirm new password"
              type="password"
              key="confirm-password-input"
              ref="confirmNewPassword"
              :placeholder="$t('Login.LoginForm.ConfirmNewPassword.Placeholder')"
            />
            <span v-show="errors.has('confirm new password') && showValidationErrors" class="help text-danger">
              {{ errors.first('confirm new password') }}
            </span>
          </b-col>
        </b-row>
      </div>
      <div class="my-3">
        <b-col align-self="start" class="col-12">
          <b-row :align-h="isEnterOtp ? 'between' : 'end'" class="mt-0">
            <b-link v-if="isEnterOtp" class="" @click="backToLogin">
              <b-button
                @click="() => activateReset(false)"
                :variant="namespace !== 'byDzyne' ? 'outline-light' : 'light'"
                class="mr-2 h-100 text-black border-0"
              >
                {{ $t('Login.LoginForm.Cancel') }}
              </b-button>
            </b-link>
            <b-button
              ref="submitButton"
              @click="resetPassword"
              @keyup.13="resetPassword"
              variant="primary"
              class="px-4 py-2"
            >
              <span v-if="isEnterOtp">
                {{ $t('Login.LoginForm.Confirm') }}
              </span>
              <span v-else>
                {{ $t('Login.LoginForm.SendReset') }}
              </span>
            </b-button>
          </b-row>
        </b-col>
      </div>
      <b-modal
        size="sm"
        ok-only
        hide-header
        class="eshop-model"
        ref="change_pwd_ok"
        centered
        @ok="logoutUser(customLoginUrl)"
      >
        <div>{{ $t('MyAccount.ChangePassword.Response.Success') }}</div>
        <div><br />{{ $t('Login.LoginForm.PleaseRelogin') }}</div>
      </b-modal>
    </b-container>
  </login-form-template>
</template>
<script>
import { mapActions, mapGetters } from 'vuex'
import { PhoneMixin } from '@/app/_global/mixins'
import { RouteHasPath } from '@/helpers/routing'
import { LOGIN_URL } from '@/config/defaults'
import LoginFormTemplate from './templates/FormTemplate'
import LoginRoutingMixin from './mixins/loginRoutingMixin'

export default {
  name: 'ChangePassword',
  mixins: [PhoneMixin, LoginRoutingMixin],
  components: {
    LoginFormTemplate,
  },
  data() {
    return {
      otp: '',
      inputMemberIdEmail: '',
      mobileCountryCodeId: null,
      mobilePhoneNumber: '',
      newPassword: '',
      retypeNewPassword: '',
      changePasswordStatus: true,
      showValidationErrors: false,
      resetErrorMsg: [],
      isEnterOtp: true,
      isMobile: null,
      userIdData: null,
      maskingText: '',
      isEvo: this.$appSettings.evo.enable,
    }
  },
  inject: ['$validator'],
  props: {
    userId: {
      type: String,
      default: null,
    },
    namespace: { type: String, default: 'eshop' },
    customLoginUrl: { type: String },
  },
  watch: {
    getResetResponseData: {
      handler() {
        if (this.getResetResponseData !== null) {
          this.isMobile = this.$helpers.isEmpty(this.getResetResponseData, 'email')
        }
        this.getIdEmailMobileText()
      },
      immediate: true,
    },
    userId: {
      handler() {
        if (!isNaN(parseInt(this.userId))) {
          this.setResetResponseData({
            user_id: this.userId,
          })
        }
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters([
      'getMemberDetails',
      'getErrors',
      'getResetErrorStatus',
      'getResetResponseData',
      'getCountries',
      'getPreferedContact',
    ]),
    formTemplateProps() {
      let props = {
        showBack: true,
        namespace: this.namespace,
        showLogo: true,
        title: this.$t('Login.LoginForm.ResetPassword.Title'),
        'form-class': "['justify-content-start']",
      }

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

      return props
    },
  },
  methods: {
    ...mapActions(['changePassword', 'sendResetPassword', 'logoutUser', 'setResetResponseData', 'activateReset']),
    getIdEmailMobileText() {
      if (this.getResetResponseData !== null) {
        if (typeof this.getResetResponseData.mobile_num !== 'undefined') {
          this.maskingText = this.mobileNumberMasking(this.getResetResponseData)
        } else if (typeof this.getResetResponseData.email !== 'undefined') {
          this.maskingText = this.emailMasking(this.getResetResponseData.email)
        } else if (this.getResetResponseData.user_id !== undefined) {
          this.userIdData = this.getResetResponseData.user_id
        }
      } else if (this.getPreferedContact !== null) {
        if (typeof this.getPreferedContact.mobile_num !== 'undefined') {
          this.maskingText = this.mobileNumberMasking(this.getPreferedContact)
        } else if (typeof this.getPreferedContact.email !== 'undefined') {
          this.maskingText = this.emailMasking(this.getPreferedContact.email)
        }
      }
      if (this.maskingText === '') {
        this.$router.push({ name: 'ForgotPassword' })
      }
    },
    resetPassword() {
      this.$validator.validateAll().then(valid => {
        this.showValidationErrors = true
        this.resetErrorMsg = []
        if (valid) {
          this.showValidationErrors = false
          if (this.isEnterOtp) {
            let temp = {
              otp: this.otp,
              request_type: 'validate',
              email: this.inputMemberIdEmail,
            }
            if (this.isMobile) {
              temp = {
                otp: this.otp,
                request_type: 'validate',
                mobile_country_code_id: this.mobileCountryCodeId,
                mobile_num: this.mobilePhoneNumber,
              }
            }
            if (this.userIdData !== null) {
              temp = {
                otp: this.otp,
                user_id: this.userIdData,
                request_type: 'validate',
              }
            }
            this.sendResetPassword(temp).then(() => {
              let errorObj = this.getErrors('resetPassword')
              if (errorObj) {
                if (typeof errorObj !== 'undefined') {
                  Object.keys(errorObj).forEach(errType => {
                    this.resetErrorMsg.push(errorObj[errType][0])
                  })
                }
              } else {
                this.isEnterOtp = false
                this.setResetResponseData(null)
              }
            })
          } else {
            let temp = {
              otp: this.otp,
              request_type: 'reset-password',
              email: this.inputMemberIdEmail,
              password: this.newPassword,
              password_confirmation: this.retypeNewPassword,
            }
            if (this.isMobile) {
              temp = {
                otp: this.otp,
                request_type: 'reset-password',
                mobile_country_code_id: this.mobileCountryCodeId,
                mobile_num: this.mobilePhoneNumber,
                password: this.newPassword,
                password_confirmation: this.retypeNewPassword,
              }
            }
            if (this.userIdData !== null) {
              temp = {
                otp: this.otp,
                user_id: this.userIdData,
                request_type: 'reset-password',
                password: this.newPassword,
                password_confirmation: this.retypeNewPassword,
              }
            }
            this.sendResetPassword(temp).then(() => {
              let errorObj = this.getErrors('resetPassword')
              if (errorObj) {
                if (errorObj.otp !== undefined) {
                  Object.keys(errorObj).forEach(errType => {
                    this.resetErrorMsg.push(errorObj[errType][0])
                  })
                } else {
                  this.resetErrorMsg = errorObj.error.message
                }
              } else {
                this.$refs.change_pwd_ok.show()
              }
            })
          }
        }
      })
    },
    backToLogin() {
      this.activateReset(false)
      if (!RouteHasPath(this.$router.currentRoute.path, LOGIN_URL)) {
        this.$router.replace({ name: 'Login' })
      }
    },
    emailMasking(email) {
      this.inputMemberIdEmail = email
      let username = email.substr(0, email.indexOf('@'))
      let domain = email.substr(email.indexOf('@'))
      return username.substr(0, 1) + username.slice(-1).padStart(username.length - 1, '*') + domain
    },
    mobileNumberMasking(mobileObj) {
      this.mobileCountryCodeId = mobileObj.mobile_country_code_id
      this.mobilePhoneNumber = mobileObj.mobile_num
      let mobileNumber = this.phoneNumber(this.mobileCountryCodeId, this.mobilePhoneNumber).split(' ')
      if (mobileNumber.length > 1) {
        return mobileNumber[0] + ' ' + this.mobilePhoneNumber.slice(-4).padStart(this.mobilePhoneNumber.length, 'x')
      } else {
        let country = this.getCountries.find(country => {
          return this.mobileCountryCodeId === country.value
        })
        if (country) {
          return (
            '(+' +
            country.call_code +
            ') ' +
            this.mobilePhoneNumber.slice(-4).padStart(this.mobilePhoneNumber.length, 'x')
          )
        }
        return this.mobilePhoneNumber.slice(-4).padStart(this.mobilePhoneNumber.length, 'x')
      }
    },
  },
}
</script>
