<template>
  <div class="app-container">
    <el-form
      ref="resetForm"
      :model="resetForm"
      :rules="resetRules"
      label-width="80px"
    >
      <el-form-item label="原密码" prop="old">
        <el-input
          v-model="resetForm.old"
          autofocus
          minlength="6"
          maxlength="12"
          style="width:350px"
        />
      </el-form-item>
      <el-form-item label="新密码" prop="new">
        <el-input
          v-model="resetForm.new"
          minlength="6"
          maxlength="12"
          show-password
          style="width:350px"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          size="mini"
          @click="handleCancel"
        >
          取消
        </el-button>
        <el-button
          type="primary"
          size="mini"
          @click="handleReset"
        >
          修改
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>

import {
  resetPwd
} from '@/api/login'

export default {
  data() {
    return {
      resetRules: {
        old: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度为6到12个字符', trigger: 'blur' }
        ],
        new: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度为6到12个字符', trigger: 'blur' }
        ]
      },
      resetForm: {
        old: '',
        new: ''
      }
    }
  },
  methods: {
    // 取消
    handleCancel() {
      this.$refs.resetForm.resetFields()
      this.$emit('update:cancel')
    },
    // 重置
    reset() {
      this.$refs.resetForm.resetFields()
    },
    // 修改密码
    handleReset() {
      this.$refs.resetForm.validate((valid) => {
        if (valid) {
          const data = {
            oldpassword: this.resetForm.old,
            password: this.resetForm.new
          }
          this.resetPwd(data)
        } else {
          return false
        }
      })
    },
    async resetPwd(data) {
      const res = await resetPwd(data)
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message({
            message: '修改密码成功,请您重新登陆',
            type: 'success'
          })
          this.$refs.resetForm.resetFields()
          this.$emit('update:success')
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        let message = res.message ? res.message : e.message
        message = e.message ? e.message : '请求失败'
        this.$message.error(message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
