<template>
  <el-card class="rpm-forgot">
    <el-form
      ref="resetPwdForm"
      :model="resetPwdForm"
      :rules="resetPwdRules"
      label-width="0"
    >
      <el-form-item prop="email">
        <el-input ref="email" v-model="resetPwdForm.email" placeholder="Email Address" />
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="resetPwdForm.code" placeholder="Verify Code" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="resetPwdForm.password" placeholder="Set a New Password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.native.prevent="handleResetPwd">
          Reset password
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="$emit('show-form', 'signIn')">
          Back to Sign in
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { resetPassword } from '@/api/auth'
import { validateEmail, validatePassword } from '@/utils/validate'
import md5 from '@/utils/md5'

export default {
  name: 'ResetPwdForm',
  data() {
    return {
      resetPwdForm: {
        email: '',
        code: '',
        password: ''
      },
      resetPwdRules: {
        email: [{ required: true, trigger: 'blur', validator: validateEmail }],
        code: [{ required: true, trigger: 'blur'}],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loading: false
    }
  },

  mounted() {
    if (this.resetPwdForm.email === '') {
      this.$refs.email.focus()
    }
  },
  methods: {
    handleResetPwd() {
      this.$refs.resetPwdForm.validate(async valid => {
        if (valid) {
          this.loading = true
          await resetPassword({ email: this.resetPwdForm.email, code: this.resetPwdForm.code, password: md5(this.resetPwdForm.password) })
          this.loading = false
          this.$notify({
            title: 'Success',
            message: 'reset password successfully.',
            type: 'success',
            duration: 3000
          })
          this.$emit('show-form', 'signIn')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>


<style lang="scss" scoped>
.el-button {
  width: 100% !important;
}
.rpm-forgot {
  position: absolute;
  top: 200px;
  right: 100px;
  width: 350px;
}
</style>
