<template>
  <el-dialog
    title="修改密码"
    :visible.sync="visible"
    @close="cancel"
    width="700px"
    :close-on-click-modal="false"
  >
    <el-form ref="form" :model="form" label-width="100px" :rules="rules">
      <el-form-item label="用户名:" prop="userName">
        <el-input v-model="form.userName" />
      </el-form-item>
      <el-form-item label="原密码:" prop="originPwd">
        <el-input type="password" v-model="form.originPwd" />
      </el-form-item>
      <el-form-item label="新密码:" prop="password">
        <el-input type="password" v-model="form.password" />
      </el-form-item>
      <el-form-item label="确认新密码:" prop="sureNewPwd">
        <el-input type="password" v-model="form.sureNewPwd" />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confrim">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { formInitPwd } from '../../const'
import { updatePwd } from '../../api'

export default {
  name: 'editPwd',
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        userName: { required: true, message: '请输入用户名', trigger: 'blur' },
        originPwd: { required: true, message: '请输入原密码', trigger: 'blur' },
        password: { required: true, message: '请输入新密码', trigger: 'blur' },
        sureNewPwd: [{ required: true, validator: validatePass2, trigger: 'blur' }]
      },
      form: formInitPwd(),
      visible: false
    }
  },
  props: {
    flag1: {
      type: Number,
      default: 0
    },
    curInfo: {
      type: Object,
      default: () => { }
    }
  },
  watch: {
    flag1: {
      immediate: true,
      handler(newV) {
        this.visible = !!newV
        this.form = formInitPwd(this.curInfo)
      },
    },
  },
  computed: {
  },
  methods: {
    cancel() {
      this.form = formInitPwd()
      this.$emit('reset')
    },
    confrim() {
      this.$refs['form'].validate(valid => {
        let params = {
          ...this.form
        }
        if (valid) {
          updatePwd(params).then(() => {
            this.$message.success('操作成功')
            this.$emit('reset', true)
          })
        }
      })
    }
  }
  
}
</script>
