<template>
  <div>
    <el-form ref="form" :model="formData" :rules="formRules" label-width="80px" class="form">
      <el-form-item label="旧密码" prop="oldPassword">
        <el-input v-model="formData.oldPassword" type="password" placeholder="请输入旧密码" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="formData.newPassword" type="password" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPwd">
        <el-input v-model="formData.confirmPwd" type="password" placeholder="请再次输入密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit()">确认</el-button>
        <el-button type="warning" @click="$_back()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { modifyPassword } from '@/api/user'
import { validPassword } from '@/utils/validate'
export default {
  data() {
    var confirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formData.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var validPwd = (rule, value, callback) => {
      if (this.formData.oldPassword === value) {
        callback(new Error('新密码与旧密码相同'))
      } else if (!validPassword(value)) {
        callback(new Error('请输入字母与数字组合的8-12位密码'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        oldPassword: '',
        newPassword: '',
        confirmPwd: ''
      },
      formRules: {
        oldPassword: [
          { required: true, message: '请输入原来的密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, trigger: ['change', 'blur'], validator: validPwd }
        ],
        confirmPwd: [
          { required: true, message: '请再次输入密码' },
          { validator: confirmPassword, trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    submit() {
      const that = this
      this.$refs.form.validate(valide => {
        if (!valide) return
        const authUserId = this.$store.getters.authUserId
        modifyPassword({ authUserId, ...that.formData }).then(res => {
          if (res.code === 0) {
            this.$refs.form.resetFields()
            this.$message.success('密码修改成功,请重新登录')
            this.logout()
          }
        }).catch(err => {
          console.log(err)
        })
      })
    },
    async logout() {
      setTimeout(() => {
        // 退出登录重置用户信息
        this.$store.dispatch('user/logout')
        // 重置相关state
        this.$store.dispatch('resetState')
        this.$router.replace('/login')
      }, 500)
    }
  }
}
</script>

<style lang="scss" scoped>
  .form{
    width: 600px;
    margin: 80px auto;
    .el-button{
      width: 120px;
    }
  }
</style>
