<template>
  <el-container>
    <el-header class="header">
      <h3>修改密码</h3>
    </el-header>
    <el-main class="main">
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="150px">
        <el-form-item label="用户名:">
          <el-input :value="username" :disabled="true" />
        </el-form-item>
        <el-form-item label="原密码:" :required="true" prop="oldpass">
          <el-input v-model="form.oldpass" type="password" />
        </el-form-item>
        <el-form-item label="新密码:" :required="true"  prop="newpass">
          <el-input v-model="form.newpass" type="password" />
        </el-form-item>
        <el-form-item label="密码确认:" :required="true" prop="confirm">
          <el-input v-model="form.confirm" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存密码</el-button>
        </el-form-item>
      </el-form>
    </el-main>
  </el-container>
</template>

<script>
import { mapActions, mapState } from 'vuex'
export default {
  name: 'passwd',
  data () {
    const checkConfirm = () => {
      return (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.form.newpass) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
    }
    return {
      form: { },
      rules: {
        oldpass: [
          { required: true, message: '请输入原密码' }
        ],
        newpass: [
          { required: true, message: '请输入新密码' }
        ],
        confirm: [
          { required: true, message: '请重新输入新密码' },
          { validator: checkConfirm(), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapActions(['changepass']),
    // 提交数据
    async onSubmit () {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return false
        const res = await this.changepass({ ...this.form, userName: this.username })
        if (res && res.errcode === 0) {
          this.$message.success('修改密码成功')
        }
      })
    }
  },
  computed: {
    ...mapState(['username'])
  }
}
</script>
<style lang="less" scoped>
h3 {
  width: 90%;
  text-align: left;
  text-indent: 1em;
  line-height: 3em;
  border-bottom: 2px solid #999;
}
.main {
  width: 80%;
  margin: 5% auto;
  .el-input {
    width: 200px;
  }
}
</style>
