<template>
  <div class="animal-management">
    <a-page-header
      title="动物管理"
      subtitle="管理认养动物信息"
      :breadcrumb="{ routes: [{ path: '/dashboard', breadcrumbName: '首页' }, { path: '', breadcrumbName: '动物管理' }] }"
    >
      <template #extra>
        <a-button type="primary" @click="showCreateModal">
          <template #icon><PlusOutlined /></template>
          新增动物
        </a-button>
      </template>
    </a-page-header>

    <a-card class="mt-4">
      <!-- 搜索区域 -->
      <div class="search-section mb-4">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="动物名称">
            <a-input v-model:value="searchForm.name" placeholder="请输入动物名称" />
          </a-form-item>
          <a-form-item label="动物类型">
            <a-select v-model:value="searchForm.animalType" placeholder="请选择类型" style="width: 120px">
              <a-select-option value="dog">狗狗</a-select-option>
              <a-select-option value="cat">猫咪</a-select-option>
              <a-select-option value="sheep">小羊</a-select-option>
              <a-select-option value="cow">奶牛</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="状态">
            <a-select v-model:value="searchForm.status" placeholder="请选择状态" style="width: 120px">
              <a-select-option value="available">可认养</a-select-option>
              <a-select-option value="adopted">已认养</a-select-option>
              <a-select-option value="pending">审核中</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="handleSearch">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button class="ml-2" @click="resetSearch">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 表格区域 -->
      <a-table
        :columns="columns"
        :data-source="animalList"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'animalType'">
            <a-tag :color="getAnimalTypeColor(record.animalType)">
              {{ getAnimalTypeText(record.animalType) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button size="small" @click="handleView(record)">查看</a-button>
              <a-button size="small" type="primary" @click="handleEdit(record)">编辑</a-button>
              <a-button size="small" danger @click="handleDelete(record)">删除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建/编辑模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      width="600px"
      :confirm-loading="confirmLoading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        :rules="rules"
      >
        <a-form-item label="动物名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入动物名称" />
        </a-form-item>
        <a-form-item label="动物类型" name="animalType">
          <a-select v-model:value="formState.animalType" placeholder="请选择动物类型">
            <a-select-option value="dog">狗狗</a-select-option>
            <a-select-option value="cat">猫咪</a-select-option>
            <a-select-option value="sheep">小羊</a-select-option>
            <a-select-option value="cow">奶牛</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="品种" name="breed">
          <a-input v-model:value="formState.breed" placeholder="请输入品种" />
        </a-form-item>
        <a-form-item label="年龄" name="age">
          <a-input-number v-model:value="formState.age" :min="0" :max="30" placeholder="请输入年龄" />
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="formState.status" placeholder="请选择状态">
            <a-select-option value="available">可认养</a-select-option>
            <a-select-option value="adopted">已认养</a-select-option>
            <a-select-option value="pending">审核中</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="formState.description"
            placeholder="请输入动物描述"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

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

interface Animal {
  id: number
  name: string
  animalType: string
  breed: string
  age: number
  status: string
  description: string
  createTime: string
}

interface SearchForm {
  name?: string
  animalType?: string
  status?: string
}

interface FormState {
  name: string
  animalType: string
  breed: string
  age: number
  status: string
  description: string
}

// 表格列配置
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '动物名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '动物类型',
    key: 'animalType',
    width: 120
  },
  {
    title: '品种',
    dataIndex: 'breed',
    key: 'breed'
  },
  {
    title: '年龄',
    dataIndex: 'age',
    key: 'age',
    width: 80
  },
  {
    title: '状态',
    key: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 响应式数据
const animalList = ref<Animal[]>([])
const loading = ref(false)
const modalVisible = ref(false)
const confirmLoading = ref(false)
const formRef = ref<FormInstance>()
const isEdit = ref(false)
const editingId = ref<number>()

const searchForm = reactive<SearchForm>({})
const formState = reactive<FormState>({
  name: '',
  animalType: '',
  breed: '',
  age: 0,
  status: '',
  description: ''
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const rules = {
  name: [{ required: true, message: '请输入动物名称', trigger: 'blur' }],
  animalType: [{ required: true, message: '请选择动物类型', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const modalTitle = computed(() => isEdit.value ? '编辑动物' : '新增动物')

// 方法
const getAnimalTypeText = (type: string) => {
  const map: Record<string, string> = {
    dog: '狗狗',
    cat: '猫咪',
    sheep: '小羊',
    cow: '奶牛'
  }
  return map[type] || type
}

const getAnimalTypeColor = (type: string) => {
  const map: Record<string, string> = {
    dog: 'blue',
    cat: 'pink',
    sheep: 'green',
    cow: 'orange'
  }
  return map[type] || 'default'
}

const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    available: '可认养',
    adopted: '已认养',
    pending: '审核中'
  }
  return map[status] || status
}

const getStatusColor = (status: string) => {
  const map: Record<string, string> = {
    available: 'green',
    adopted: 'red',
    pending: 'orange'
  }
  return map[status] || 'default'
}

const fetchAnimals = async () => {
  loading.value = true
  try {
    // 模拟数据
    animalList.value = [
      {
        id: 1,
        name: '小白',
        animalType: 'dog',
        breed: '萨摩耶',
        age: 2,
        status: 'available',
        description: '温顺可爱的萨摩耶',
        createTime: '2024-01-15 10:30:00'
      },
      {
        id: 2,
        name: '小花',
        animalType: 'cat',
        breed: '英短',
        age: 1,
        status: 'adopted',
        description: '活泼好动的英短猫',
        createTime: '2024-01-16 14:20:00'
      }
    ]
    pagination.total = animalList.value.length
  } catch (error) {
    message.error('获取动物列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  fetchAnimals()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    name: undefined,
    animalType: undefined,
    status: undefined
  })
  handleSearch()
}

const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchAnimals()
}

const showCreateModal = () => {
  isEdit.value = false
  editingId.value = undefined
  Object.assign(formState, {
    name: '',
    animalType: '',
    breed: '',
    age: 0,
    status: '',
    description: ''
  })
  modalVisible.value = true
}

const handleEdit = (record: Animal) => {
  isEdit.value = true
  editingId.value = record.id
  Object.assign(formState, record)
  modalVisible.value = true
}

const handleView = (record: Animal) => {
  // 查看详情逻辑
  message.info(`查看动物: ${record.name}`)
}

const handleDelete = (record: Animal) => {
  // 删除逻辑
  message.warning(`删除动物: ${record.name}`)
}

const handleModalOk = async () => {
  try {
    await formRef.value?.validate()
    confirmLoading.value = true
    
    if (isEdit.value) {
      // 编辑逻辑
      message.success('编辑成功')
    } else {
      // 新增逻辑
      message.success('新增成功')
    }
    
    modalVisible.value = false
    fetchAnimals()
  } catch (error) {
    console.error('表单验证失败', error)
  } finally {
    confirmLoading.value = false
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
}

// 生命周期
onMounted(() => {
  fetchAnimals()
})
</script>

<style scoped>
.animal-management {
  padding: 20px;
}

.search-section {
  background: #fafafa;
  padding: 16px;
  border-radius: 6px;
}

.mt-4 {
  margin-top: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}

.ml-2 {
  margin-left: 8px;
}
</style>