<script setup lang="ts">
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { updatePassword } from '../api'

const formRef = $ref<FormInstance>()
const form = reactive({
  old_password: '',
  password: '',
  password_r: ''
})
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== form.password) {
    callback(new Error('两次密码输入不一致'))
  } else {
    callback()
  }
}
const rules = ref<FormRules>({
  old_password: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位字符', trigger: 'blur' }
  ],
  password_r: [{ validator: validatePass2, trigger: 'blur' }]
})

// 提交
function handleSubmit() {
  formRef?.validate().then(update)
}
// 修改
const update = () => {
  updatePassword(form).then(() => {
    // 重置表单
    formRef?.resetFields()
    ElMessage({ message: '修改成功', type: 'success' })
  })
}
</script>

<template>
  <el-form
    ref="formRef"
    :model="form"
    :rules="rules"
    hide-required-asterisk
    label-width="100px"
    label-position="left"
    style="max-width: 360px"
  >
    <el-form-item label="旧密码" prop="old_password">
      <el-input type="password" v-model="form.old_password" />
    </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="password_r">
      <el-input type="password" v-model="form.password_r" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
    </el-form-item>
  </el-form>
</template>
