<template>
  <el-form
    :label-position="'right'"
    label-width="120px"
    :model="passwordForm"
    :rules="passwordFormRules"
    ref="passwordRef"
    style="max-width: 90%">
    <el-form-item label="新密码" prop="new_password">
      <el-input type="password" v-model="passwordForm.new_password" />
    </el-form-item>
    <el-form-item label="确认密码" prop="confirm_password">
      <el-input type="password" v-model="passwordForm.confirm_password" />
    </el-form-item>
  </el-form>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
const passwordForm = reactive({
  new_password: "",
  confirm_password: "",
});
const props = defineProps({
});

const validatePass = (rule, value, callback) => {
  if (value !== passwordForm.new_password) {
    callback(new Error("密码输入不一致"));
  } else {
    callback();
  }
};

const passwordFormRules = reactive({
  new_password: [
     { required: true, message: "请输入新密码", trigger: "blur" },
     { min: 8, message: "密码长度不得低于8位", trigger: "blur" },
  ],
  confirm_password: [
    { required: true, message: "请确认密码", trigger: "blur" },
    { validator: validatePass, trigger: "blur" },
  ],
});
const passwordRef = ref(null);
const emit = defineEmits(["action"]);

const submitForm = async () => {
  if (!passwordRef) return;
  await passwordRef.value.validate((valid, fields) => {
    if (valid) {
      emit("action", passwordForm);
    } else {
      emit("action", null);
    }
  });
};
const clearForm = () => {
  if (!passwordRef) return;
  passwordRef.value.resetFields();
};

const setForm = (data) => {
  Object.assign(passwordForm, data);
};

onMounted(() => {});

defineExpose({ submitForm, clearForm, setForm });
</script>
