<template>
  <el-dialog v-model="visible" title="修改密码" width="420px" :close-on-click-modal="false">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
      <el-form-item label="用户">
        <span>{{ currentUser.name || currentUser.account || "-" }}</span>
      </el-form-item>

      <el-form-item label="新密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入新密码"
          show-password
          clearable
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          placeholder="请再次输入新密码"
          show-password
          clearable
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { changePassword } from "@/api/user";

const emit = defineEmits<{
  (e: "submit"): void;
}>();

const visible = ref(false);
const submitLoading = ref(false);
const formRef = ref<FormInstance>();
const currentUser = ref<any>({});

const form = reactive({
  password: "",
  confirmPassword: "",
});

const validateConfirmPassword = (_rule: any, value: string, callback: (error?: Error) => void) => {
  if (!value) {
    callback(new Error("请再次输入新密码"));
    return;
  }

  if (value !== form.password) {
    callback(new Error("两次输入的密码不一致"));
    return;
  }

  callback();
};

const rules: FormRules = {
  password: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于 6 位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" },
  ],
};

const resetForm = () => {
  form.password = "";
  form.confirmPassword = "";
  formRef.value?.clearValidate();
};

const openChangePass = (row: any) => {
  currentUser.value = row || {};
  resetForm();
  visible.value = true;
};

const handleSubmit = async () => {
  if (!currentUser.value?.id) {
    ElMessage.error("用户 ID 不存在");
    return;
  }

  await formRef.value?.validate();

  submitLoading.value = true;
  try {
    await changePassword(currentUser.value.id, {
      newPassword: form.password,
    });

    ElMessage.success("密码修改成功");
    visible.value = false;
    emit("submit");
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || e?.message || "密码修改失败");
  } finally {
    submitLoading.value = false;
  }
};

defineExpose({
  openChangePass,
  open: openChangePass,
});
</script>

<style lang="less" scoped></style>
