<template>
  <div class="animal-management">
    <a-page-header
      title="动物管理"
      sub-title="管理动物信息和认领记录"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleRefresh">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
          <a-button 
            v-if="hasPermission('animal:write')" 
            type="primary" 
            @click="showCreateModal"
          >
            <template #icon>
              <PlusOutlined />
            </template>
            新增动物
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
      <a-tab-pane key="animals" tab="动物列表">
        <a-card>
          <!-- 搜索区域 -->
          <div class="search-container">
            <a-form layout="inline" :model="searchForm">
              <a-form-item label="关键词">
                <a-input
                  v-model:value="searchForm.keyword"
                  placeholder="动物名称/编号"
                  allow-clear
                />
              </a-form-item>
              
              <a-form-item label="类型">
                <a-select
                  v-model:value="searchForm.type"
                  placeholder="全部类型"
                  style="width: 120px"
                  allow-clear
                >
                  <a-select-option value="alpaca">羊驼</a-select-option>
                  <a-select-option value="dog">狗狗</a-select-option>
                  <a-select-option value="cat">猫咪</a-select-option>
                  <a-select-option value="rabbit">兔子</a-select-option>
                </a-select>
              </a-form-item>
              
              <a-form-item label="状态">
                <a-select
                  v-model:value="searchForm.status"
                  placeholder="全部状态"
                  style="width: 120px"
                  allow-clear
                >
                  <a-select-option value="available">可认领</a-select-option>
                  <a-select-option value="claimed">已认领</a-select-option>
                  <a-select-option value="reserved">预留中</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 style="margin-left: 8px" @click="handleReset">
                  重置
                </a-button>
              </a-form-item>
            </a-form>
          </div>

          <!-- 动物表格 -->
          <a-table
            :columns="animalColumns"
            :data-source="animalList"
            :loading="loading"
            :pagination="pagination"
            :row-key="record => record.id"
            @change="handleTableChange"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'image'">
                <a-image
                  :width="60"
                  :height="60"
                  :src="record.image_url"
                  :fallback="fallbackImage"
                  style="border-radius: 6px;"
                />
              </template>
              
              <template v-else-if="column.key === 'type'">
                <a-tag :color="getTypeColor(record.type)">
                  {{ getTypeText(record.type) }}
                </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 === 'price'">
                ¥{{ record.price }}
              </template>
              
              <template v-else-if="column.key === 'actions'">
                <a-space :size="8">
                  <a-button size="small" @click="handleViewAnimal(record)">
                    <EyeOutlined />
                    查看
                  </a-button>
                  
                  <a-button 
                    v-if="hasPermission('animal:write')" 
                    size="small" 
                    @click="handleEditAnimal(record)"
                  >
                    <EditOutlined />
                    编辑
                  </a-button>
                  
                  <a-button 
                    v-if="hasPermission('animal:write')" 
                    size="small" 
                    danger 
                    @click="handleDeleteAnimal(record)"
                  >
                    <DeleteOutlined />
                    删除
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="claims" tab="认领记录">
        <a-card>
          <!-- 认领记录搜索 -->
          <div class="search-container">
            <a-form layout="inline" :model="claimSearchForm">
              <a-form-item label="关键词">
                <a-input
                  v-model:value="claimSearchForm.keyword"
                  placeholder="用户/动物名称"
                  allow-clear
                />
              </a-form-item>
              
              <a-form-item label="状态">
                <a-select
                  v-model:value="claimSearchForm.status"
                  placeholder="全部状态"
                  style="width: 120px"
                  allow-clear
                >
                  <a-select-option value="pending">待审核</a-select-option>
                  <a-select-option value="approved">已通过</a-select-option>
                  <a-select-option value="rejected">已拒绝</a-select-option>
                  <a-select-option value="completed">已完成</a-select-option>
                </a-select>
              </a-form-item>
              
              <a-form-item>
                <a-button type="primary" @click="handleClaimSearch">
                  <template #icon>
                    <SearchOutlined />
                  </template>
                  搜索
                </a-button>
                <a-button style="margin-left: 8px" @click="handleClaimReset">
                  重置
                </a-button>
              </a-form-item>
            </a-form>
          </div>

          <!-- 认领记录表格 -->
          <a-table
            :columns="claimColumns"
            :data-source="claimList"
            :loading="claimLoading"
            :pagination="claimPagination"
            :row-key="record => record.id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'animal_image'">
                <a-image
                  :width="40"
                  :height="40"
                  :src="record.animal_image"
                  :fallback="fallbackImage"
                  style="border-radius: 4px;"
                />
              </template>
              
              <template v-else-if="column.key === 'status'">
                <a-tag :color="getClaimStatusColor(record.status)">
                  {{ getClaimStatusText(record.status) }}
                </a-tag>
              </template>
              
              <template v-else-if="column.key === 'actions'">
                <a-space :size="8">
                  <template v-if="record.status === 'pending' && hasPermission('animal:write')">
                    <a-button size="small" type="primary" @click="handleApproveClaim(record)">
                      <CheckOutlined />
                      通过
                    </a-button>
                    <a-button size="small" danger @click="handleRejectClaim(record)">
                      <CloseOutlined />
                      拒绝
                    </a-button>
                  </template>
                  
                  <a-button size="small" @click="handleViewClaim(record)">
                    <EyeOutlined />
                    详情
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-tab-pane>
    </a-tabs>

    <!-- 创建/编辑动物模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="600px"
    >
      <a-form
        ref="animalFormRef"
        :model="currentAnimal"
        :rules="formRules"
        layout="vertical"
      >
        <a-form-item label="动物名称" name="name">
          <a-input v-model:value="currentAnimal.name" placeholder="请输入动物名称" />
        </a-form-item>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="类型" name="type">
              <a-select v-model:value="currentAnimal.type" placeholder="请选择类型">
                <a-select-option value="alpaca">羊驼</a-select-option>
                <a-select-option value="dog">狗狗</a-select-option>
                <a-select-option value="cat">猫咪</a-select-option>
                <a-select-option value="rabbit">兔子</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="品种" name="breed">
              <a-input v-model:value="currentAnimal.breed" placeholder="请输入品种" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="年龄" name="age">
              <a-input-number
                v-model:value="currentAnimal.age"
                :min="0"
                :max="100"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="性别" name="gender">
              <a-select v-model:value="currentAnimal.gender" placeholder="请选择性别">
                <a-select-option value="male">雄性</a-select-option>
                <a-select-option value="female">雌性</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="price">
              <a-input-number
                v-model:value="currentAnimal.price"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select v-model:value="currentAnimal.status" placeholder="请选择状态">
                <a-select-option value="available">可认领</a-select-option>
                <a-select-option value="claimed">已认领</a-select-option>
                <a-select-option value="reserved">预留中</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="图片URL" name="image_url">
          <a-input v-model:value="currentAnimal.image_url" placeholder="请输入图片URL" />
        </a-form-item>
        
        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="currentAnimal.description"
            placeholder="请输入动物描述"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal, type FormInstance } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import {
  ReloadOutlined,
  SearchOutlined,
  PlusOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  CheckOutlined,
  CloseOutlined
} from '@ant-design/icons-vue'
import { useAppStore } from '@/stores/app'
import { getAnimals, deleteAnimal, getAnimalClaims, approveAnimalClaim, rejectAnimalClaim, createAnimal, updateAnimal, getAnimal } from '@/api/animal'
import type { Animal, AnimalClaim, AnimalCreateData, AnimalUpdateData } from '@/api/animal'

interface SearchForm {
  keyword: string
  type: string
  status: string
}

interface ClaimSearchForm {
  keyword: string
  status: string
}

const appStore = useAppStore()

// 权限检查方法
const hasPermission = (permission: string) => {
  return appStore.hasPermission(permission)
}

const activeTab = ref('animals')
const loading = ref(false)
const claimLoading = ref(false)

const searchForm = reactive<SearchForm>({
  keyword: '',
  type: '',
  status: ''
})

const claimSearchForm = reactive<ClaimSearchForm>({
  keyword: '',
  status: ''
})

const animalList = ref<Animal[]>([])
const claimList = ref<AnimalClaim[]>([])

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

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

const animalColumns = [
  {
    title: '图片',
    key: 'image',
    width: 80,
    align: 'center'
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: 100
  },
  {
    title: '类型',
    key: 'type',
    width: 100,
    align: 'center'
  },
  {
    title: '品种',
    dataIndex: 'breed',
    key: 'breed',
    width: 120
  },
  {
    title: '年龄',
    dataIndex: 'age',
    key: 'age',
    width: 80,
    align: 'center',
    customRender: ({ text }: { text: number }) => `${text}岁`
  },
  {
    title: '价格',
    key: 'price',
    width: 100,
    align: 'center'
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 120
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    align: 'center'
  }
]

const claimColumns = [
  {
    title: '动物',
    key: 'animal_image',
    width: 60,
    align: 'center'
  },
  {
    title: '动物名称',
    dataIndex: 'animal_name',
    key: 'animal_name',
    width: 100
  },
  {
    title: '用户',
    dataIndex: 'user_name',
    key: 'user_name',
    width: 100
  },
  {
    title: '联系电话',
    dataIndex: 'user_phone',
    key: 'user_phone',
    width: 120
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '申请时间',
    dataIndex: 'applied_at',
    key: 'applied_at',
    width: 120
  },
  {
    title: '处理时间',
    dataIndex: 'processed_at',
    key: 'processed_at',
    width: 120
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    align: 'center'
  }
]

const fallbackImage = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjYwIiBoZWlnaHQ9IjYwIiBmaWxsPSIjRkZGIi8+CjxwYXRoIGQ9Ik0zMCAxNUMzMS42NTY5IDE1IDMzIDE2LjM0MzEgMzMgMThDMzMgMTkuNjU2OSAzMS42NTY5IDIxIDMwIDIxQzI4LjM0MzEgMjEgMjcgMTkuNjU2OSAyNyAxOEMyNyAxNi4zNDMxIDI4LjM0MzEgMTUgMzAgMTVaIiBmaWxsPSIjQ0NDQ0NDIi8+CjxwYXRoIGQ9Ik0yMi41IDI1QzIyLjUgMjUuODI4NCAyMS44Mjg0IDI2LjUgMjEgMjYuNUgxOEMxOC4xNzE2IDI2LjUgMTcuNSAyNS44Mjg0IDE3LjUgMjVDMTcuNSAyNC4xNzE2IDE4LjE3MTYgMjMuNSAxOSAyMy45SDIxQzIxLjgyODQgMjMuNSAyMi41IDI0LjE3MTYgMjIuNSAyNVoiIGZpbGw9IiNDQ0NDQ0MiLz4KPHBhdGggZD0iTTQyLjUgMjVDNDIuNSAyNS44Mjg0IDQxLjgyODQgMjYuNSA0MSAyNi41SDM5QzM4LjE3MTYgMjYuNSAzNy41IDI1LjgyODQgMzcuNSAyNUMzNy41IDI0LjE3MTYgMzguMTcxNiAyMy41IDM5IDIzLjVMNDEgMjMuNUM0MS44Mjg0IDIzLjUgNDIuNSAyNC4xNzE2IDQyLjUgMjVaIiBmaWxsPSIjQ0NDQ0NDIi8+Cjwvc3ZnPgo='

// 类型映射
const getTypeColor = (type: string) => {
  const colors = {
    alpaca: 'pink',
    dog: 'orange',
    cat: 'blue',
    rabbit: 'green'
  }
  return colors[type as keyof typeof colors] || 'default'
}

const getTypeText = (type: string) => {
  const texts = {
    alpaca: '羊驼',
    dog: '狗狗',
    cat: '猫咪',
    rabbit: '兔子'
  }
  return texts[type as keyof typeof texts] || '未知'
}

// 状态映射
const getStatusColor = (status: string) => {
  const colors = {
    available: 'green',
    claimed: 'blue',
    reserved: 'orange'
  }
  return colors[status as keyof typeof colors] || 'default'
}

const getStatusText = (status: string) => {
  const texts = {
    available: '可认领',
    claimed: '已认领',
    reserved: '预留中'
  }
  return texts[status as keyof typeof texts] || '未知'
}

const getClaimStatusColor = (status: string) => {
  const colors = {
    pending: 'orange',
    approved: 'green',
    rejected: 'red',
    completed: 'blue'
  }
  return colors[status as keyof typeof colors] || 'default'
}

const getClaimStatusText = (status: string) => {
  const texts = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    completed: '已完成'
  }
  return texts[status as keyof typeof texts] || '未知'
}

// 添加模态框相关状态
const modalVisible = ref(false)
const modalLoading = ref(false)
const modalTitle = ref('新增动物')
const isEditing = ref(false)
const animalFormRef = ref<FormInstance>()

// 当前动物数据
const currentAnimal = ref<Partial<Animal>>({})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入动物名称' }
  ],
  type: [
    { required: true, message: '请选择类型' }
  ],
  breed: [
    { required: true, message: '请输入品种' }
  ],
  age: [
    { required: true, message: '请输入年龄' }
  ],
  gender: [
    { required: true, message: '请选择性别' }
  ],
  price: [
    { required: true, message: '请输入价格' }
  ],
  status: [
    { required: true, message: '请选择状态' }
  ]
}

// 生命周期
onMounted(() => {
  loadAnimals()
  loadClaims()
})

// 方法
const loadAnimals = async () => {
  loading.value = true
  try {
    const response = await getAnimals({
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      type: searchForm.type,
      status: searchForm.status
    })
    
    animalList.value = response.data
    pagination.total = response.pagination?.total || 0
  } catch (error) {
    message.error('加载动物列表失败')
  } finally {
    loading.value = false
  }
}

const loadClaims = async () => {
  claimLoading.value = true
  try {
    const response = await getAnimalClaims({
      page: claimPagination.current,
      pageSize: claimPagination.pageSize,
      keyword: claimSearchForm.keyword,
      status: claimSearchForm.status
    })
    
    claimList.value = response.data
    claimPagination.total = response.pagination?.total || 0
  } catch (error) {
    message.error('加载认领记录失败')
  } finally {
    claimLoading.value = false
  }
}

const handleTabChange = (key: string) => {
  if (key === 'animals') {
    loadAnimals()
  } else if (key === 'claims') {
    loadClaims()
  }
}

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

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    type: '',
    status: ''
  })
  pagination.current = 1
  loadAnimals()
}

const handleClaimSearch = () => {
  claimPagination.current = 1
  loadClaims()
}

const handleClaimReset = () => {
  Object.assign(claimSearchForm, {
    keyword: '',
    status: ''
  })
  claimPagination.current = 1
  loadClaims()
}

const handleRefresh = () => {
  if (activeTab.value === 'animals') {
    loadAnimals()
  } else {
    loadClaims()
  }
  message.success('数据已刷新')
}

const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current!
  pagination.pageSize = pag.pageSize!
  loadAnimals()
}

const handleViewAnimal = (record: Animal) => {
  message.info(`查看动物: ${record.name}`)
}

const handleEditAnimal = async (record: Animal) => {
  try {
    modalLoading.value = true
    modalTitle.value = '编辑动物'
    isEditing.value = true
    
    // 获取动物详情
    const response = await getAnimal(record.id)
    currentAnimal.value = response.data
    modalVisible.value = true
  } catch (error) {
    message.error('获取动物详情失败')
  } finally {
    modalLoading.value = false
  }
}

const handleDeleteAnimal = async (record: Animal) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除动物 "${record.name}" 吗？`,
    okText: '确定',
    okType: 'danger',
    onOk: async () => {
      try {
        await deleteAnimal(record.id)
        message.success('动物已删除')
        loadAnimals()
      } catch (error) {
        message.error('删除失败')
      }
    }
  })
}

const handleApproveClaim = async (record: AnimalClaim) => {
  Modal.confirm({
    title: '确认通过',
    content: `确定要通过用户 "${record.user_name}" 的认领申请吗？`,
    onOk: async () => {
      try {
        await approveAnimalClaim(record.id)
        message.success('认领申请已通过')
        loadClaims()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleRejectClaim = async (record: AnimalClaim) => {
  Modal.confirm({
    title: '确认拒绝',
    content: `确定要拒绝用户 "${record.user_name}" 的认领申请吗？`,
    onOk: async () => {
      try {
        await rejectAnimalClaim(record.id, '拒绝原因')
        message.success('认领申请已拒绝')
        loadClaims()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleViewClaim = (record: AnimalClaim) => {
  message.info(`查看认领详情: ${record.animal_name}`)
}

const showCreateModal = () => {
  modalTitle.value = '新增动物'
  isEditing.value = false
  currentAnimal.value = {
    age: 1,
    price: 0,
    status: 'available'
  }
  modalVisible.value = true
}

const handleModalOk = () => {
  animalFormRef.value
    ?.validate()
    .then(() => {
      if (isEditing.value) {
        handleUpdateAnimal()
      } else {
        handleCreateAnimal()
      }
    })
    .catch((error: any) => {
      console.error('表单验证失败:', error)
    })
}

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

const handleCreateAnimal = async () => {
  try {
    modalLoading.value = true
    await createAnimal(currentAnimal.value as AnimalCreateData)
    message.success('创建动物成功')
    modalVisible.value = false
    loadAnimals()
  } catch (error) {
    message.error('创建动物失败')
  } finally {
    modalLoading.value = false
  }
}

const handleUpdateAnimal = async () => {
  try {
    modalLoading.value = true
    await updateAnimal(currentAnimal.value.id!, currentAnimal.value as AnimalUpdateData)
    message.success('更新动物成功')
    modalVisible.value = false
    loadAnimals()
  } catch (error) {
    message.error('更新动物失败')
  } finally {
    modalLoading.value = false
  }
}

</script>

<style scoped lang="less">
.animal-management {
  .search-container {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
    
    :deep(.ant-form-item) {
      margin-bottom: 16px;
    }
  }
}
</style>