<template>
  <a-modal
    v-model:open="visible"
    :title="isEditing ? '编辑用户' : '新增用户'"
    width="600px"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="用户名" name="username">
            <a-input 
              v-model:value="formData.username" 
              placeholder="请输入用户名"
              :disabled="isEditing"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="昵称" name="nickname">
            <a-input 
              v-model:value="formData.nickname" 
              placeholder="请输入昵称"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="邮箱" name="email">
            <a-input 
              v-model:value="formData.email" 
              placeholder="请输入邮箱"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="手机号" name="phone">
            <a-input 
              v-model:value="formData.phone" 
              placeholder="请输入手机号"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16" v-if="!isEditing">
        <a-col :span="12">
          <a-form-item label="密码" name="password">
            <a-input-password 
              v-model:value="formData.password" 
              placeholder="请输入密码"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="确认密码" name="confirmPassword">
            <a-input-password 
              v-model:value="formData.confirmPassword" 
              placeholder="请确认密码"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="性别" name="gender">
            <a-select 
              v-model:value="formData.gender" 
              placeholder="请选择性别"
              allow-clear
            >
              <a-select-option :value="1">男</a-select-option>
              <a-select-option :value="2">女</a-select-option>
              <a-select-option :value="0">未知</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="生日" name="birthday">
            <a-date-picker 
              v-model:value="formData.birthday" 
              placeholder="请选择生日"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="状态" name="status">
            <a-select 
              v-model:value="formData.status" 
              placeholder="请选择状态"
            >
              <a-select-option value="active">正常</a-select-option>
              <a-select-option value="inactive">禁用</a-select-option>
              <a-select-option value="pending">待审核</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注" name="remark">
            <a-input 
              v-model:value="formData.remark" 
              placeholder="请输入备注"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import type { FormInstance, Rule } from 'ant-design-vue/es/form'
import type { User } from '@/api/user'
import dayjs, { type Dayjs } from 'dayjs'

interface Props {
  user: User | null
  visible: boolean
  isEditing: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', data: any): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)

const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单数据
const formData = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  gender: undefined as number | undefined,
  birthday: undefined as Dayjs | undefined,
  status: 'active',
  remark: ''
})

// 表单验证规则
const rules: Record<string, Rule[]> = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度为3-20个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: !props.isEditing, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: !props.isEditing, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string) => {
        if (!props.isEditing && value !== formData.password) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}

// 监听用户数据变化，初始化表单
watch(() => props.user, (user) => {
  if (user && props.isEditing) {
    formData.username = user.username
    formData.nickname = user.nickname
    formData.email = user.email
    formData.phone = user.phone
    formData.gender = user.gender
    formData.birthday = user.birthday ? dayjs(user.birthday) : undefined
    formData.status = user.status
    formData.remark = user.remark
  }
}, { immediate: true })

// 监听弹窗显示状态，重置表单
watch(() => props.visible, (visible) => {
  if (visible && !props.isEditing) {
    resetForm()
  }
})

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    username: '',
    nickname: '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: '',
    gender: undefined,
    birthday: undefined,
    status: 'active',
    remark: ''
  })
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true
    
    const submitData: any = {
      username: formData.username,
      nickname: formData.nickname,
      email: formData.email,
      phone: formData.phone,
      gender: formData.gender,
      birthday: formData.birthday?.format('YYYY-MM-DD'),
      status: formData.status,
      remark: formData.remark
    }
    
    if (!props.isEditing) {
      submitData.password = formData.password
    }
    
    emit('submit', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  resetForm()
}
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 16px;
}
</style>