<template>
  <div class="animals-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>动物管理</h1>
      <p>管理平台上的所有动物信息</p>
    </div>

    <!-- 数据统计 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="总动物数"
            :value="statistics.totalAnimals"
            :value-style="{ color: '#3f8600' }"
          >
            <template #prefix>
              <HeartOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="可领养"
            :value="statistics.availableAnimals"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix>
              <SmileOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="已领养"
            :value="statistics.claimedAnimals"
            :value-style="{ color: '#722ed1' }"
          >
            <template #prefix>
              <HomeOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="今日新增"
            :value="statistics.newAnimalsToday"
            :value-style="{ color: '#cf1322' }"
          >
            <template #prefix>
              <PlusOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 高级搜索 -->
    <AdvancedSearch
      search-type="animal"
      :status-options="statusOptions"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 批量操作 -->
    <BatchOperations
      :data-source="animals as any[]"
      :selected-items="selectedAnimals as any[]"
      operation-type="animal"
      :status-options="statusOptionsWithColor"
      :export-fields="exportFields"
      @selection-change="(items: any[]) => handleSelectionChange(items as Animal[])"
      @batch-action="(action: string, items: any[], params?: any) => handleBatchAction(action, items as Animal[], params)"
    />

    <!-- 动物列表表格 -->
    <a-card class="table-card">
      <a-table
        :columns="columns"
        :data-source="animals"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        :scroll="{ x: 1200 }"
        row-key="id"
        @change="handleTableChange"
      >
        <!-- 动物图片 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar
              :src="record.avatar"
              :alt="record.name"
              size="large"
              shape="square"
            >
              {{ record.name?.charAt(0) }}
            </a-avatar>
          </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 === 'type'">
            <a-tag color="blue">{{ record.type }}</a-tag>
          </template>

          <!-- 年龄 -->
          <template v-else-if="column.key === 'age'">
            {{ record.age }}岁
          </template>

          <!-- 创建时间 -->
          <template v-else-if="column.key === 'createdAt'">
            {{ formatDate(record.createdAt) }}
          </template>

          <!-- 操作按钮 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleViewAnimal(record)">
                查看
              </a-button>
              <a-button type="link" size="small" @click="handleEditAnimal(record)">
                编辑
              </a-button>
              <a-dropdown>
                <a-button type="link" size="small">
                  更多 <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item 
                      key="activate" 
                      v-if="record.status !== 'available'"
                      @click="handleUpdateStatus(record, 'available')"
                    >
                      <CheckCircleOutlined />
                      设为可领养
                    </a-menu-item>
                    <a-menu-item 
                      key="deactivate" 
                      v-if="record.status !== 'unavailable'"
                      @click="handleUpdateStatus(record, 'unavailable')"
                    >
                      <LockOutlined />
                      设为不可领养
                    </a-menu-item>
                    <a-menu-divider />
                    <a-menu-item key="delete" @click="handleDeleteAnimal(record)">
                      <DeleteOutlined />
                      删除
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 动物详情弹窗 -->
    <AnimalDetail
      :animal="currentAnimal"
      :visible="showAnimalDetail"
      @update:visible="showAnimalDetail = $event"
    />

    <!-- 动物表单弹窗 -->
    <AnimalForm
      :animal="currentAnimal"
      :visible="showAnimalForm"
      :is-editing="isEditing"
      @update:visible="showAnimalForm = $event"
      @submit="handleAnimalSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import type { TableColumnsType } from 'ant-design-vue'
import { SearchOutlined, PlusOutlined, ExportOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import type { Animal } from '@/api/animal'
import animalAPI from '@/api/animal'
import AdvancedSearch from '@/components/AdvancedSearch.vue'
import BatchOperations from '@/components/BatchOperations.vue'
import AnimalForm from './components/AnimalForm.vue'
import AnimalDetail from './components/AnimalDetail.vue'

// 移除重复的Animal接口定义，使用api中的接口

interface Statistics {
  totalAnimals: number
  availableAnimals: number
  newAnimalsToday: number
  claimedAnimals: number
}

// 临时格式化函数，直到utils/date模块可用
const formatDate = (date: string | null | undefined): string => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

// 响应式数据
const loading = ref(false)
const animals = ref<Animal[]>([])
const selectedAnimals = ref<Animal[]>([])
const currentAnimal = ref<Animal | null>(null)

// 计算属性
const selectedRowKeys = computed(() => selectedAnimals.value.map(animal => animal.id))

// 统计数据
const statistics = reactive<Statistics>({
  totalAnimals: 0,
  availableAnimals: 0,
  newAnimalsToday: 0,
  claimedAnimals: 0
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) => 
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 搜索参数
const searchParams = reactive({
  keyword: '',
  type: '',
  status: '',
  age_range: [] as number[],
  date_range: [] as string[]
})

// 模态框状态
const showAnimalDetail = ref(false)
const showAnimalForm = ref(false)
const isEditing = ref(false)

// 搜索字段配置
const searchFields = [
  {
    key: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '请输入动物名称或描述'
  },
  {
    key: 'type',
    label: '动物类型',
    type: 'select',
    options: [
      { label: '狗', value: '狗' },
      { label: '猫', value: '猫' },
      { label: '兔子', value: '兔子' },
      { label: '鸟类', value: '鸟类' }
    ]
  },
  {
    key: 'status',
    label: '状态',
    type: 'select',
    options: [
      { label: '可领养', value: 'available' },
      { label: '已领养', value: 'adopted' },
      { label: '不可领养', value: 'unavailable' }
    ]
  }
]

// 状态选项
const statusOptions = [
  { label: '可领养', value: 'available', color: 'green' },
  { label: '已领养', value: 'adopted', color: 'blue' },
  { label: '不可领养', value: 'unavailable', color: 'red' }
]

// 批量操作用的状态选项
const statusOptionsWithColor = [
  { label: '可领养', value: 'available', color: 'green' },
  { label: '已领养', value: 'adopted', color: 'blue' },
  { label: '不可领养', value: 'unavailable', color: 'red' }
]

// 导出字段
const exportFields = [
  { key: 'name', label: '动物名称' },
  { key: 'species', label: '物种' },
  { key: 'breed', label: '品种' },
  { key: 'age', label: '年龄' },
  { key: 'gender', label: '性别' },
  { key: 'price', label: '价格' },
  { key: 'status', label: '状态' },
  { key: 'merchant_name', label: '商家' },
  { key: 'created_at', label: '创建时间' }
]

// 表格列配置
const columns: TableColumnsType<Animal> = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
    sorter: true
  },
  {
    title: '图片',
    dataIndex: 'image',
    key: 'image',
    width: 80
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: 120
  },
  {
    title: '物种',
    dataIndex: 'species',
    key: 'species',
    width: 100
  },
  {
    title: '品种',
    dataIndex: 'breed',
    key: 'breed',
    width: 120
  },
  {
    title: '年龄',
    dataIndex: 'age',
    key: 'age',
    width: 80,
    sorter: true
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender',
    width: 80
  },
  {
    title: '价格',
    dataIndex: 'price',
    key: 'price',
    width: 100,
    sorter: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '商家',
    dataIndex: 'merchant_name',
    key: 'merchant_name',
    width: 150
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 160,
    sorter: true
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 表格行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedAnimals.value.map(item => item.id),
  onChange: (selectedRowKeys: any[]) => {
    selectedAnimals.value = animals.value.filter(item => 
      selectedRowKeys.includes(item.id)
    )
  }
})) as any

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    available: 'green',
    adopted: 'blue',
    unavailable: 'red'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    available: '可领养',
    adopted: '已领养',
    unavailable: '不可领养'
  }
  return textMap[status] || status
}

// 获取动物列表
const fetchAnimals = async () => {
  try {
    loading.value = true
    // 模拟数据 - 使用类型断言避免类型检查
    const mockAnimals = [
      {
        id: 1,
        name: '小白',
        species: '狗',
        breed: '金毛',
        age: 2,
        gender: '雄性',
        description: '温顺可爱的金毛犬，性格友善，适合家庭饲养',
        image: 'https://example.com/dog1.jpg',
        merchant_id: 1,
        merchant_name: '爱心宠物店',
        price: 1500,
        status: 'available',
        created_at: '2024-01-15T10:30:00Z',
        updated_at: '2024-01-15T10:30:00Z'
      },
      {
        id: 2,
        name: '小花',
        species: '猫',
        breed: '英短',
        age: 1,
        gender: '雌性',
        description: '活泼可爱的英短猫，毛色纯正，健康活泼',
        image: 'https://example.com/cat1.jpg',
        merchant_id: 2,
        merchant_name: '温馨宠物之家',
        price: 2000,
        status: 'adopted',
        created_at: '2024-01-14T14:20:00Z',
        updated_at: '2024-01-16T09:15:00Z'
      },
      {
        id: 3,
        name: '小黑',
        species: '狗',
        breed: '拉布拉多',
        age: 3,
        gender: '雄性',
        description: '聪明忠诚的拉布拉多，训练有素，适合陪伴',
        image: 'https://example.com/dog2.jpg',
        merchant_id: 1,
        merchant_name: '爱心宠物店',
        price: 1800,
        status: 'available',
        created_at: '2024-01-13T16:45:00Z',
        updated_at: '2024-01-13T16:45:00Z'
      },
      {
        id: 4,
        name: '咪咪',
        species: '猫',
        breed: '波斯猫',
        age: 2,
        gender: '雌性',
        description: '优雅的波斯猫，毛发柔顺，性格温和',
        image: 'https://example.com/cat2.jpg',
        merchant_id: 3,
        merchant_name: '宠物乐园',
        price: 2500,
        status: 'unavailable',
        created_at: '2024-01-12T11:20:00Z',
        updated_at: '2024-01-17T14:30:00Z'
      },
      {
        id: 5,
        name: '小灰',
        species: '兔子',
        breed: '荷兰兔',
        age: 1,
        gender: '雄性',
        description: '可爱的荷兰兔，毛色灰白相间，性格活泼',
        image: 'https://example.com/rabbit1.jpg',
        merchant_id: 2,
        merchant_name: '温馨宠物之家',
        price: 800,
        status: 'available',
        created_at: '2024-01-16T09:10:00Z',
        updated_at: '2024-01-16T09:10:00Z'
      }
    ] as Animal[]

    const mockData = {
      list: mockAnimals,
      total: mockAnimals.length,
      statistics: {
        totalAnimals: 156,
        availableAnimals: 89,
        newAnimalsToday: 3,
        claimedAnimals: 45
      }
    }
    
    animals.value = mockData.list
    pagination.total = mockData.total
    
    // 更新统计数据
    Object.assign(statistics, mockData.statistics)
  } catch (error) {
    message.error('获取动物列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = (params: any) => {
  Object.assign(searchParams, params)
  pagination.current = 1
  fetchAnimals()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchParams, {
    keyword: '',
    type: '',
    status: '',
    age_range: [],
    date_range: []
  })
  pagination.current = 1
  fetchAnimals()
}

// 刷新数据
const handleRefresh = () => {
  fetchAnimals()
}

// 查看动物详情
const handleViewAnimal = (animal: Animal) => {
  currentAnimal.value = animal
  showAnimalDetail.value = true
}

// 编辑动物
const handleEditAnimal = (animal: Animal) => {
  currentAnimal.value = animal
  isEditing.value = true
  showAnimalForm.value = true
}

// 新增动物
const handleAddAnimal = () => {
  currentAnimal.value = null
  isEditing.value = false
  showAnimalForm.value = true
}

// 删除动物
const handleDeleteAnimal = (animal: Animal) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除动物 "${animal.name}" 吗？`,
    onOk: async () => {
      try {
        // 模拟API调用
        message.success('删除成功')
        fetchAnimals()
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}

// 更新动物状态
const handleUpdateStatus = async (animal: Animal, status: string) => {
  try {
    // 模拟API调用
    message.success('状态更新成功')
    fetchAnimals()
  } catch (error) {
    message.error('状态更新失败')
  }
}

// 批量选择处理
const handleSelectionChange = (items: Animal[]) => {
  selectedAnimals.value = items
}

// 批量操作处理
const handleBatchAction = async (action: string, items: Animal[], params?: any) => {
  try {
    const animalIds = items.map(animal => animal.id)
    
    switch (action) {
      case 'updateStatus':
        message.success(`批量${params?.status === 'available' ? '设为可领养' : '更新状态'}成功`)
        break
      case 'delete':
        message.success('批量删除成功')
        break
      case 'export':
        message.success('导出成功')
        break
      default:
        message.warning('未知操作')
        return
    }
    
    selectedAnimals.value = []
    fetchAnimals()
  } catch (error) {
    message.error('批量操作失败')
  }
}

// 表格变化处理
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  
  // TODO: 处理排序和筛选
  fetchAnimals()
}

// 动物表单提交
const handleAnimalSubmit = async (animalData: any) => {
  try {
    if (isEditing.value && currentAnimal.value) {
      message.success('更新成功')
    } else {
      message.success('创建成功')
    }
    showAnimalForm.value = false
    fetchAnimals()
  } catch (error) {
    message.error(isEditing.value ? '更新失败' : '创建失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAnimals()
})
</script>

<style scoped>
.animals-page {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  h2 {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.statistics-cards {
  margin-bottom: 24px;
}

.table-card {
  margin-top: 16px;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}
</style>