<script setup lang="ts">
import { defineModel } from 'vue';

// 定义组件的 props
const props = defineProps(['propName', 'placeholder']);

// 使用 defineModel 定义与父组件 v-model 绑定的变量
const password = defineModel('password');
const confirmPassword = defineModel('confirmPassword');

// 定义表单项的验证规则数组
const formItemRules: any = [
  // 规则1: 必填验证
  { required: true, message: '请输入你的密码' },
  // 规则2: 密码长度验证
  { min: 6, message: '密码长度过低' }
];

// 如果是确认密码项，添加一条自定义验证规则
if (props.propName === 'confirmPassword') {
  formItemRules.push({
    // 自定义验证规则，异步验证两次密码是否一致
    validator: async (rule: any, value: string, callback: Function) => {
      console.log(rule);
      if (value === confirmPassword.value) {
        callback(); // 验证通过
      } else {
        callback(new Error('两次密码输入不一致')); // 验证不通过，返回错误提示
      }
    }
  });
}
const buttonLoading = defineModel('buttonLoading', {type: Boolean, required:  true} )
const emits = defineEmits(['submitClick'])

const handleButtonClick = () => {
  // 设置loading状态
  buttonLoading.value = true;
  emits('submitClick', () => {
    // 操作完成后重置loading状态
    buttonLoading.value = false;
  });
};
</script>

<template>
  <!-- 使用 el-form-item 包裹 el-input，绑定验证规则 -->
  <el-form-item :prop="props.propName" :rules="formItemRules">
    <el-input
        v-model.trim="password"
        @keydown.enter="handleButtonClick"
        minlength="6"
        type="password"
        show-password
        clearable
        :placeholder="props.placeholder || '请输入登陆密码'"
    />
  </el-form-item>
</template>

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