<template>
  <a-modal
    v-model:open="visible"
    :title="isEditing ? '编辑动物' : '新增动物'"
    width="800px"
    :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="name">
            <a-input 
              v-model:value="formData.name" 
              placeholder="请输入动物名称"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="动物类型" name="type">
            <a-select 
              v-model:value="formData.type" 
              placeholder="请选择动物类型"
            >
              <a-select-option value="狗">狗</a-select-option>
              <a-select-option value="猫">猫</a-select-option>
              <a-select-option value="兔子">兔子</a-select-option>
              <a-select-option value="鸟类">鸟类</a-select-option>
              <a-select-option value="其他">其他</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="品种" name="breed">
            <a-input 
              v-model:value="formData.breed" 
              placeholder="请输入品种"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="年龄" name="age">
            <a-input-number 
              v-model:value="formData.age" 
              placeholder="请输入年龄"
              :min="0"
              :max="30"
              style="width: 100%"
            />
          </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="请选择性别"
            >
              <a-select-option value="雄性">雄性</a-select-option>
              <a-select-option value="雌性">雌性</a-select-option>
              <a-select-option value="未知">未知</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="颜色" name="color">
            <a-input 
              v-model:value="formData.color" 
              placeholder="请输入颜色"
            />
          </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="available">可领养</a-select-option>
              <a-select-option value="adopted">已领养</a-select-option>
              <a-select-option value="unavailable">不可领养</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="健康状态" name="health_status">
            <a-select 
              v-model:value="formData.health_status" 
              placeholder="请选择健康状态"
            >
              <a-select-option value="健康">健康</a-select-option>
              <a-select-option value="轻微疾病">轻微疾病</a-select-option>
              <a-select-option value="需要治疗">需要治疗</a-select-option>
              <a-select-option value="康复中">康复中</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="位置" name="location">
        <a-input 
          v-model:value="formData.location" 
          placeholder="请输入当前位置"
        />
      </a-form-item>

      <a-form-item label="头像" name="avatar">
        <a-upload
          v-model:file-list="fileList"
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :before-upload="beforeUpload"
          @change="handleChange"
        >
          <div v-if="formData.avatar">
            <img :src="formData.avatar" alt="avatar" style="width: 100%" />
          </div>
          <div v-else>
            <PlusOutlined />
            <div style="margin-top: 8px">上传头像</div>
          </div>
        </a-upload>
      </a-form-item>

      <a-form-item label="描述" name="description">
        <a-textarea 
          v-model:value="formData.description" 
          placeholder="请输入动物描述"
          :rows="4"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import type { FormInstance, UploadChangeParam } from 'ant-design-vue'

interface Animal {
  id: number
  name: string
  type: string
  breed: string
  age: number
  gender: string
  color: string
  avatar: string
  description: string
  status: 'available' | 'adopted' | 'unavailable'
  health_status: string
  location: string
  createdAt: string
  updatedAt: string
  [key: string]: any
}

interface Props {
  animal: Animal | 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 fileList = ref([])

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

// 表单数据
const formData = reactive({
  name: '',
  type: '',
  breed: '',
  age: 0,
  gender: '',
  color: '',
  status: 'available' as 'available' | 'adopted' | 'unavailable',
  health_status: '健康',
  location: '',
  avatar: '',
  description: ''
})

// 表单验证规则
const rules: Record<string, any[]> = {
  name: [
    { required: true, message: '请输入动物名称', trigger: 'blur' },
    { min: 1, max: 50, message: '名称长度为1-50个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择动物类型', trigger: 'change' }
  ],
  breed: [
    { required: true, message: '请输入品种', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 0, max: 30, message: '年龄必须在0-30之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入位置', trigger: 'blur' }
  ]
}

// 监听动物数据变化，初始化表单
watch(() => props.animal, (animal) => {
  if (animal && props.isEditing) {
    formData.name = animal.name
    formData.type = animal.type
    formData.breed = animal.breed
    formData.age = animal.age
    formData.gender = animal.gender
    formData.color = animal.color
    formData.status = animal.status
    formData.health_status = animal.health_status
    formData.location = animal.location
    formData.avatar = animal.avatar
    formData.description = animal.description
  }
}, { immediate: true })

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

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    type: '',
    breed: '',
    age: 0,
    gender: '',
    color: '',
    status: 'available',
    health_status: '健康',
    location: '',
    avatar: '',
    description: ''
  })
  fileList.value = []
  formRef.value?.resetFields()
}

// 文件上传前验证
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return false
  }
  return false // 阻止自动上传
}

// 文件上传变化处理
const handleChange = (info: UploadChangeParam) => {
  if (info.file.originFileObj) {
    // 创建预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      formData.avatar = e.target?.result as string
    }
    reader.readAsDataURL(info.file.originFileObj)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true
    
    const submitData = {
      name: formData.name,
      type: formData.type,
      breed: formData.breed,
      age: formData.age,
      gender: formData.gender,
      color: formData.color,
      status: formData.status,
      health_status: formData.health_status,
      location: formData.location,
      avatar: formData.avatar,
      description: formData.description
    }
    
    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;
}

.avatar-uploader {
  :deep(.ant-upload) {
    width: 128px;
    height: 128px;
  }
  
  :deep(.ant-upload-select-picture-card) {
    width: 128px;
    height: 128px;
  }
}
</style>