<template>
  <el-dialog v-model="visible" title="创建账号" width="500px">
    <el-form ref="form" label-width="100px">
      <el-form-item label="用户名" prop="username" required>
        <el-input 
          :model-value="formData.username"
          @update:model-value="val => formData.username = val"
          placeholder="4-20位字母数字或下划线"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email" required>
        <el-input 
          :model-value="formData.email"
          @update:model-value="val => formData.email = val"
          placeholder="请输入有效邮箱地址"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'

const visible = ref(false)
const formData = reactive({
  username: '',
  email: ''
})

const emit = defineEmits(['success'])

const show = () => {
  visible.value = true
  formData.username = ''
  formData.email = ''
}

const handleSubmit = async () => {
  if (!/^[a-zA-Z0-9_]{4,20}$/.test(formData.username)) {
    ElMessage.error('用户名必须为4-20位字母数字或下划线')
    return
  }
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
    ElMessage.error('请输入有效的邮箱地址')
    return
  }
  emit('success', { ...formData })
  visible.value = false
}

defineExpose({ show })
</script>
