<template>
  <el-dialog title="修改密码" v-model="visible" width="400px" @close="reset">
    <el-form :model="form" ref="refForm" :rules="rules">
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="form.newPwd" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPwd">
        <el-input v-model="form.confirmPwd" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="reset">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import sysUserApi from "@/api/account/sysUser";
const visible = ref(false);
const form = reactive({
  oldPwd: "",
  newPwd: "",
  confirmPwd: "",
});
const rules = {
  newPwd: [{ required: true, message: "请输入新密码", trigger: "blur" }],
  confirmPwd: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== form.newPwd) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};
const emit = defineEmits(["update:visible"]);
function reset() {
  visible.value = false;
  form.oldPwd = "";
  form.newPwd = "";
  form.confirmPwd = "";
  form.id = "";
}
const refForm = ref();
function submit() {
  refForm.value.validate((valid) => {
    if (valid) {
      sysUserApi
        .pwd({
          id: form.id,
          checkPassword: form.confirmPwd,
          password: form.confirmPwd,
        })
        .then(() => {
          ElMessage.success("修改成功");
          close();
        });
    }
  });
}
function open(data) {
  visible.value = true;
  form.id = data.id;
}
function close() {
  visible.value = false;
}
defineExpose({
  open,
  close,
});
</script>