<template>
  <el-form 
    ref="registerFormRef" 
    :model="registerForm" 
    :rules="registerRules" 
    class="register-form"
  >
    <el-form-item prop="username">
      <el-input 
        v-model="registerForm.username" 
        :placeholder="$t('auth.usernamePlaceholder')"
        prefix-icon="User"
      ></el-input>
    </el-form-item>
    
    <el-form-item prop="password">
      <el-input 
        v-model="registerForm.password" 
        :placeholder="$t('auth.passwordPlaceholder')"
        type="password"
        prefix-icon="Lock"
      ></el-input>
    </el-form-item>
    
    <el-form-item prop="confirmPassword">
      <el-input 
        v-model="registerForm.confirmPassword" 
        :placeholder="$t('auth.confirmPasswordPlaceholder')"
        type="password"
        prefix-icon="Lock"
      ></el-input>
    </el-form-item>
    
    <!-- 使用额外的容器包裹按钮 -->
    <el-form-item class="form-actions">
      <div class="button-wrapper">
        <el-button 
          type="primary" 
          @click="handleSubmit"
        >
          {{ $t('auth.registerBtn') }}
        </el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, defineEmits } from 'vue';
import { useI18n } from 'vue-i18n';

// 表单数据
const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: ''
});

// 表单引用
const registerFormRef = ref(null);

// 国际化
const { t } = useI18n();

// 表单验证规则
const registerRules = ref({
  username: [
    { required: true, message: t('auth.username'), trigger: 'blur' },
    { min: 6, max: 12, message: t('auth.usernameRule'), trigger: 'blur' }
  ],
  password: [
    { required: true, message: t('auth.password'), trigger: 'blur' },
    { min: 6, message: t('auth.passwordRule'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: t('auth.confirmPassword'), trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error(t('auth.confirmRule')));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 定义事件
const emit = defineEmits(['submit-form']);

// 提交表单
const handleSubmit = () => {
  registerFormRef.value.validate((valid) => {
    if (valid) {
      // 表单验证通过，提交数据
      const formData = {
        username: registerForm.value.username,
        password: registerForm.value.password
      };
      emit('submit-form', formData);
    } else {
      console.log('表单验证失败');
      return false;
    }
  });
};
</script>

<style scoped>
.register-form {
  width: 100%;
}

.form-actions {
  margin-top: 20px;
  /* 移除 Element Plus 表单项的默认内边距 */
  padding: 0 !important;
  margin-bottom: 0 !important;
}

/* 使用额外容器并穿透 scoped 样式限制 */
.form-actions :deep(.button-wrapper) {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

/* 可选：设置按钮宽度，与登录按钮保持一致 */
.el-button {
  width: 120px;
}
</style>
    