<template>
  <div class="table-con" style="width: 450px;">
    <el-form ref="form" :model="form" :rules="loginRules" label-width="120px">
      <el-form-item label="旧密码">
        <el-input v-model="form.oldPassword"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword"></el-input>
      </el-form-item>
      <el-form-item label="重复新密码" prop="newPassword1">
        <el-input v-model="form.newPassword1"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {changeMyPassword} from '@/api/changePassword/index.js'

export default {
  name: "ChangePassword",
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error('请输入不少于4位数的密码'))
      } else {
        callback()
      }
    }

    return {
      form: {
        oldPassword: '',
        newPassword: '',
        newPassword1: ''
      },
      loginRules: {
        newPassword: [{required: true, trigger: 'blur', validator: validatePassword}],
        newPassword1: [{required: true, trigger: 'blur', validator: validatePassword}]
      }
    }
  },
  mounted() {

  },
  methods: {
    //获取表格数据
    onSubmit() {
      const _that = this;

      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!_that.form.oldPassword) {
            _that.$message("旧密码不能为空");
            return
          }
          if (!_that.form.newPassword) {
            _that.$message("新密码不能为空");
            return
          }
          if (_that.form.newPassword != _that.form.newPassword1) {
            _that.$message("两次密码输入的不一致");
            return
          }
          var data = {
            "oldPassword": _that.form.oldPassword,
            "newPassword": _that.form.newPassword
          }

          changeMyPassword(data).then(response => {
            _that.$message.success("密码修改成功")
            _that.logout();
          }).catch(err => {
            _that.$message.error(err)
            _that.listLoading = false
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    async logout() {
      await this.$store.dispatch('logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background-color: #f0f2f5;
  padding: 30px;
  min-height: calc(100vh - 84px);
}
.filter-container {
  margin-bottom: 15px;
}
</style>
