<template>
  <zpa-form ref="Form" :label-width="120">
    <zpa-form-group>
      <zpa-text-input
          label="用户名"
          v-model="data.userName"
          required
          readonly
      />
      <zpa-text-input
          label="登陆名"
          v-model="data.loginName"
          readonly
          required
      />
      <zpa-text-input
          label="旧密码"
          v-model="data.oldpassword"
          required
      />
      <zpa-text-input
          label="新密码"
          v-model="data.newpassword"
          required
      />
      <zpa-text-input
          label="新密码确认"
          v-model="data.newpasswordconf"
          :validators="[compare]"
          validators-message="与新密码不一致！"
          required
      />
    </zpa-form-group>
  </zpa-form>
</template>
<script>
import {
  getUserInfo,
  changePassword,
  checkPassword,
} from '@centit/api-auth'
export default {
  name: 'ChangePwd',

  data () {
    return {
      data: {},
    }
  },

  methods: {
    async afterOpen () {
      this.data = {
        oldpassword: '',
        newpassword: '',
        newpasswordconf: '',
      }
      const _currentuser = await getUserInfo()
      const _data = this.data
      this.data = { ..._currentuser.userInfo, ..._data }
    },

    async beforeSubmit () {
      const _checkpwd = await checkPassword({ password: this.data.oldpassword })
      const _this = this
      if (!_checkpwd) {
        _this.$Message.error('旧密码输入不正确！')
      }
      return this.$refs.Form.validate() && _checkpwd
    },

    submit () {
      const _this = this
      changePassword({ ...this.data, newPassword: this.data.newpassword, password: this.data.oldpassword }).then(function (testData) {
        _this.$Message.success('修改成功！')
      },
      function (reason, testData) {
        _this.$Message.error('修改失败！')
      })
    },

    compare (value) {
      return value === this.data.newpassword
    }
  },
}
</script>
