import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Animal, AnimalQueryParams, AnimalStatus, AnimalType, MedicalRecord, AnimalAdoptionRecord } from '../../types/animal'

interface AnimalState {
  animals: Animal[]
  currentAnimal: Animal | null
  loading: boolean
  totalCount: number
  queryParams: AnimalQueryParams
}

export const useAnimalStore = defineStore('animal', () => {
  // 状态
  const animals = ref<Animal[]>([])
  const currentAnimal = ref<Animal | null>(null)
  const loading = ref(false)
  const totalCount = ref(0)
  const queryParams = ref<AnimalQueryParams>({
    page: 1,
    pageSize: 10,
    keyword: '',
    status: undefined,
    animalType: undefined,
    farmId: undefined,
    startDate: '',
    endDate: ''
  })

  // 获取动物列表
  const fetchAnimals = async (params?: AnimalQueryParams) => {
    loading.value = true
    try {
      // 模拟数据
      const mockAnimals: Animal[] = [
        {
          id: 1,
          name: '小白',
          animalType: 'sheep',
          breed: '绵羊',
          age: 2,
          gender: 'male',
          status: 'available',
          farmId: 1,
          farmName: '快乐农场',
          price: 299.00,
          description: '温顺可爱的小绵羊',
          images: ['/images/sheep1.jpg'],
          healthStatus: 'excellent',
          adoptionCount: 5,
          createTime: '2024-01-10 09:00:00',
          features: ['温顺', '亲人', '爱吃草']
        },
        {
          id: 2,
          name: '小花',
          animalType: 'cow',
          breed: '奶牛',
          age: 3,
          gender: 'female',
          status: 'adopted',
          farmId: 1,
          farmName: '快乐农场',
          price: 499.00,
          description: '产奶量高的奶牛',
          images: ['/images/cow1.jpg'],
          healthStatus: 'good',
          adoptionCount: 3,
          createTime: '2024-01-12 14:30:00',
          features: ['产奶量高', '健康', '温顺']
        }
      ]
      
      animals.value = mockAnimals
      totalCount.value = mockAnimals.length
      
      if (params) {
        queryParams.value = { ...queryParams.value, ...params }
      }
    } catch (error) {
      console.error('获取动物列表失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 获取动物详情
  const fetchAnimalDetail = async (animalId: number) => {
    loading.value = true
    try {
      // 模拟数据
      const mockAnimal: Animal = {
        id: animalId,
        name: `动物${animalId}`,
        animalType: 'sheep',
        breed: '品种',
        age: 2,
        gender: 'male',
        status: 'available',
        farmId: 1,
        farmName: '测试农场',
        price: 199.00,
        description: '动物描述',
        images: ['/images/animal.jpg'],
        healthStatus: 'excellent',
        adoptionCount: 0,
        createTime: '2024-01-15 10:00:00',
        features: ['特征1', '特征2']
      }
      
      currentAnimal.value = mockAnimal
      return mockAnimal
    } catch (error) {
      console.error('获取动物详情失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新动物状态
  const updateAnimalStatus = async (animalId: number, status: AnimalStatus) => {
    try {
      // 模拟状态更新
      const animal = animals.value.find((a: Animal) => a.id === animalId)
      if (animal) {
        animal.status = status
      }
      
      if (currentAnimal.value && currentAnimal.value.id === animalId) {
        currentAnimal.value.status = status
      }
      
      return true
    } catch (error) {
      console.error('更新动物状态失败:', error)
      throw error
    }
  }

  // 添加新动物
  const addAnimal = async (animalData: Omit<Animal, 'id' | 'createTime'>) => {
    try {
      // 模拟添加操作
      const newAnimal: Animal = {
        ...animalData,
        id: Date.now(),
        createTime: new Date().toISOString()
      }
      
      animals.value.unshift(newAnimal)
      totalCount.value += 1
      
      return newAnimal
    } catch (error) {
      console.error('添加动物失败:', error)
      throw error
    }
  }

  // 更新动物信息
  const updateAnimal = async (animalId: number, updateData: Partial<Animal>) => {
    try {
      // 模拟更新操作
      const animal = animals.value.find((a: Animal) => a.id === animalId)
      if (animal) {
        Object.assign(animal, updateData)
      }
      
      if (currentAnimal.value && currentAnimal.value.id === animalId) {
        Object.assign(currentAnimal.value, updateData)
      }
      
      return true
    } catch (error) {
      console.error('更新动物信息失败:', error)
      throw error
    }
  }

  // 搜索动物
  const searchAnimals = async (keyword: string) => {
    queryParams.value.keyword = keyword
    return fetchAnimals(queryParams.value)
  }

  // 重置查询参数
  const resetQueryParams = () => {
    queryParams.value = {
      page: 1,
      pageSize: 10,
      keyword: '',
      status: undefined,
      animalType: undefined,
      farmId: undefined,
      startDate: '',
      endDate: ''
    }
  }

  // 获取动物统计
  const getAnimalStatistics = async () => {
    try {
      // 模拟统计数据
      return {
        totalAnimals: 156,
        availableAnimals: 89,
        adoptedAnimals: 67,
        totalAdoptions: 245,
        averageAdoptionPrice: 256.80,
        animalTypeDistribution: {
          sheep: 45,
          cow: 32,
          pig: 28,
          chicken: 51
        },
        statusDistribution: {
          available: 89,
          adopted: 67
        },
        topAnimals: animals.value.slice(0, 5)
      }
    } catch (error) {
      console.error('获取动物统计失败:', error)
      throw error
    }
  }

  return {
    animals,
    currentAnimal,
    loading,
    totalCount,
    queryParams,
    fetchAnimals,
    fetchAnimalDetail,
    updateAnimalStatus,
    addAnimal,
    updateAnimal,
    searchAnimals,
    resetQueryParams,
    getAnimalStatistics
  }
})