/**
 * 养殖管理状态管理模块
 * 管理养殖相关的数据和状态
 */

import { defineStore } from 'pinia'
import { farmingApi } from '@/common/api/farming'

export const useFarmingStore = defineStore('farming', {
  state: () => ({
    // 养殖场列表
    farmList: [],
    
    // 当前选中的养殖场
    currentFarm: null,
    
    // 牲畜列表
    livestockList: [],
    
    // 当前选中的牲畜
    currentLivestock: null,
    
    // 养殖记录
    records: [],
    
    // 健康监测数据
    healthData: [],
    
    // 饲料管理数据
    feedData: [],
    
    // 疫苗管理数据
    vaccineData: [],
    
    // 统计数据
    statistics: {
      totalFarms: 0,
      totalLivestock: 0,
      healthyCount: 0,
      sickCount: 0,
      feedConsumption: 0,
      vaccineCount: 0
    },
    
    // 加载状态
    loading: {
      farmList: false,
      livestockList: false,
      records: false,
      healthData: false,
      feedData: false,
      vaccineData: false
    },
    
    // 分页信息
    pagination: {
      farmList: { page: 1, size: 20, total: 0 },
      livestockList: { page: 1, size: 20, total: 0 },
      records: { page: 1, size: 20, total: 0 }
    },
    
    // 筛选条件
    filters: {
      farmType: '',
      livestockType: '',
      healthStatus: '',
      dateRange: []
    }
  }),

  getters: {
    // 获取健康牲畜列表
    healthyLivestock: (state) => {
      return state.livestockList.filter(item => item.healthStatus === 'healthy')
    },
    
    // 获取生病牲畜列表
    sickLivestock: (state) => {
      return state.livestockList.filter(item => item.healthStatus === 'sick')
    },
    
    // 获取需要疫苗的牲畜列表
    needVaccineLivestock: (state) => {
      return state.livestockList.filter(item => {
        const lastVaccine = item.lastVaccineDate
        if (!lastVaccine) return true
        
        const daysSinceVaccine = (Date.now() - new Date(lastVaccine).getTime()) / (1000 * 60 * 60 * 24)
        return daysSinceVaccine > 180 // 6个月
      })
    },
    
    // 获取今日饲料消耗
    todayFeedConsumption: (state) => {
      const today = new Date().toDateString()
      return state.feedData
        .filter(item => new Date(item.date).toDateString() === today)
        .reduce((total, item) => total + item.amount, 0)
    },
    
    // 获取本月疫苗接种数量
    monthlyVaccineCount: (state) => {
      const currentMonth = new Date().getMonth()
      const currentYear = new Date().getFullYear()
      
      return state.vaccineData.filter(item => {
        const vaccineDate = new Date(item.date)
        return vaccineDate.getMonth() === currentMonth && 
               vaccineDate.getFullYear() === currentYear
      }).length
    },
    
    // 获取养殖场类型统计
    farmTypeStats: (state) => {
      const stats = {}
      state.farmList.forEach(farm => {
        stats[farm.type] = (stats[farm.type] || 0) + 1
      })
      return stats
    },
    
    // 获取牲畜类型统计
    livestockTypeStats: (state) => {
      const stats = {}
      state.livestockList.forEach(livestock => {
        stats[livestock.type] = (stats[livestock.type] || 0) + 1
      })
      return stats
    }
  },

  actions: {
    /**
     * 获取养殖场列表
     * @param {Object} params 查询参数
     */
    async fetchFarmList(params = {}) {
      this.loading.farmList = true
      
      try {
        const response = await farmingApi.getFarmList({
          page: this.pagination.farmList.page,
          size: this.pagination.farmList.size,
          ...params
        })
        
        const { data, total } = response.data
        
        if (params.page === 1) {
          this.farmList = data
        } else {
          this.farmList.push(...data)
        }
        
        this.pagination.farmList.total = total
        this.statistics.totalFarms = total
        
        return response
      } catch (error) {
        console.error('获取养殖场列表失败:', error)
        throw error
      } finally {
        this.loading.farmList = false
      }
    },

    /**
     * 获取牲畜列表
     * @param {Object} params 查询参数
     */
    async fetchLivestockList(params = {}) {
      this.loading.livestockList = true
      
      try {
        const response = await farmingApi.getLivestockList({
          page: this.pagination.livestockList.page,
          size: this.pagination.livestockList.size,
          farmId: this.currentFarm?.id,
          ...params
        })
        
        const { data, total } = response.data
        
        if (params.page === 1) {
          this.livestockList = data
        } else {
          this.livestockList.push(...data)
        }
        
        this.pagination.livestockList.total = total
        this.statistics.totalLivestock = total
        
        // 更新健康统计
        this.updateHealthStats()
        
        return response
      } catch (error) {
        console.error('获取牲畜列表失败:', error)
        throw error
      } finally {
        this.loading.livestockList = false
      }
    },

    /**
     * 获取养殖记录
     * @param {Object} params 查询参数
     */
    async fetchRecords(params = {}) {
      this.loading.records = true
      
      try {
        const response = await farmingApi.getRecords({
          page: this.pagination.records.page,
          size: this.pagination.records.size,
          ...params
        })
        
        const { data, total } = response.data
        
        if (params.page === 1) {
          this.records = data
        } else {
          this.records.push(...data)
        }
        
        this.pagination.records.total = total
        
        return response
      } catch (error) {
        console.error('获取养殖记录失败:', error)
        throw error
      } finally {
        this.loading.records = false
      }
    },

    /**
     * 获取健康监测数据
     * @param {Object} params 查询参数
     */
    async fetchHealthData(params = {}) {
      this.loading.healthData = true
      
      try {
        const response = await farmingApi.getHealthData(params)
        this.healthData = response.data
        
        return response
      } catch (error) {
        console.error('获取健康监测数据失败:', error)
        throw error
      } finally {
        this.loading.healthData = false
      }
    },

    /**
     * 获取饲料数据
     * @param {Object} params 查询参数
     */
    async fetchFeedData(params = {}) {
      this.loading.feedData = true
      
      try {
        const response = await farmingApi.getFeedData(params)
        this.feedData = response.data
        
        // 更新饲料消耗统计
        this.updateFeedStats()
        
        return response
      } catch (error) {
        console.error('获取饲料数据失败:', error)
        throw error
      } finally {
        this.loading.feedData = false
      }
    },

    /**
     * 获取疫苗数据
     * @param {Object} params 查询参数
     */
    async fetchVaccineData(params = {}) {
      this.loading.vaccineData = true
      
      try {
        const response = await farmingApi.getVaccineData(params)
        this.vaccineData = response.data
        
        // 更新疫苗统计
        this.updateVaccineStats()
        
        return response
      } catch (error) {
        console.error('获取疫苗数据失败:', error)
        throw error
      } finally {
        this.loading.vaccineData = false
      }
    },

    /**
     * 添加养殖场
     * @param {Object} farmData 养殖场数据
     */
    async addFarm(farmData) {
      try {
        const response = await farmingApi.createFarm(farmData)
        const newFarm = response.data
        
        this.farmList.unshift(newFarm)
        this.statistics.totalFarms++
        
        return response
      } catch (error) {
        console.error('添加养殖场失败:', error)
        throw error
      }
    },

    /**
     * 更新养殖场
     * @param {number} id 养殖场ID
     * @param {Object} farmData 养殖场数据
     */
    async updateFarm(id, farmData) {
      try {
        const response = await farmingApi.updateFarm(id, farmData)
        const updatedFarm = response.data
        
        const index = this.farmList.findIndex(farm => farm.id === id)
        if (index > -1) {
          this.farmList[index] = updatedFarm
        }
        
        if (this.currentFarm?.id === id) {
          this.currentFarm = updatedFarm
        }
        
        return response
      } catch (error) {
        console.error('更新养殖场失败:', error)
        throw error
      }
    },

    /**
     * 删除养殖场
     * @param {number} id 养殖场ID
     */
    async deleteFarm(id) {
      try {
        const response = await farmingApi.deleteFarm(id)
        
        const index = this.farmList.findIndex(farm => farm.id === id)
        if (index > -1) {
          this.farmList.splice(index, 1)
          this.statistics.totalFarms--
        }
        
        if (this.currentFarm?.id === id) {
          this.currentFarm = null
        }
        
        return response
      } catch (error) {
        console.error('删除养殖场失败:', error)
        throw error
      }
    },

    /**
     * 添加牲畜
     * @param {Object} livestockData 牲畜数据
     */
    async addLivestock(livestockData) {
      try {
        const response = await farmingApi.createLivestock(livestockData)
        const newLivestock = response.data
        
        this.livestockList.unshift(newLivestock)
        this.statistics.totalLivestock++
        this.updateHealthStats()
        
        return response
      } catch (error) {
        console.error('添加牲畜失败:', error)
        throw error
      }
    },

    /**
     * 更新牲畜信息
     * @param {number} id 牲畜ID
     * @param {Object} livestockData 牲畜数据
     */
    async updateLivestock(id, livestockData) {
      try {
        const response = await farmingApi.updateLivestock(id, livestockData)
        const updatedLivestock = response.data
        
        const index = this.livestockList.findIndex(livestock => livestock.id === id)
        if (index > -1) {
          this.livestockList[index] = updatedLivestock
        }
        
        if (this.currentLivestock?.id === id) {
          this.currentLivestock = updatedLivestock
        }
        
        this.updateHealthStats()
        
        return response
      } catch (error) {
        console.error('更新牲畜信息失败:', error)
        throw error
      }
    },

    /**
     * 删除牲畜
     * @param {number} id 牲畜ID
     */
    async deleteLivestock(id) {
      try {
        const response = await farmingApi.deleteLivestock(id)
        
        const index = this.livestockList.findIndex(livestock => livestock.id === id)
        if (index > -1) {
          this.livestockList.splice(index, 1)
          this.statistics.totalLivestock--
        }
        
        if (this.currentLivestock?.id === id) {
          this.currentLivestock = null
        }
        
        this.updateHealthStats()
        
        return response
      } catch (error) {
        console.error('删除牲畜失败:', error)
        throw error
      }
    },

    /**
     * 添加养殖记录
     * @param {Object} recordData 记录数据
     */
    async addRecord(recordData) {
      try {
        const response = await farmingApi.createRecord(recordData)
        const newRecord = response.data
        
        this.records.unshift(newRecord)
        
        return response
      } catch (error) {
        console.error('添加养殖记录失败:', error)
        throw error
      }
    },

    /**
     * 设置当前养殖场
     * @param {Object} farm 养殖场对象
     */
    setCurrentFarm(farm) {
      this.currentFarm = farm
      
      // 重置牲畜列表分页
      this.pagination.livestockList.page = 1
      
      // 获取该养殖场的牲畜列表
      if (farm) {
        this.fetchLivestockList({ farmId: farm.id })
      } else {
        this.livestockList = []
      }
    },

    /**
     * 设置当前牲畜
     * @param {Object} livestock 牲畜对象
     */
    setCurrentLivestock(livestock) {
      this.currentLivestock = livestock
    },

    /**
     * 更新健康统计
     */
    updateHealthStats() {
      this.statistics.healthyCount = this.healthyLivestock.length
      this.statistics.sickCount = this.sickLivestock.length
    },

    /**
     * 更新饲料统计
     */
    updateFeedStats() {
      this.statistics.feedConsumption = this.feedData.reduce((total, item) => total + item.amount, 0)
    },

    /**
     * 更新疫苗统计
     */
    updateVaccineStats() {
      this.statistics.vaccineCount = this.vaccineData.length
    },

    /**
     * 设置筛选条件
     * @param {Object} filters 筛选条件
     */
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters }
    },

    /**
     * 重置筛选条件
     */
    resetFilters() {
      this.filters = {
        farmType: '',
        livestockType: '',
        healthStatus: '',
        dateRange: []
      }
    },

    /**
     * 刷新数据
     */
    async refreshData() {
      try {
        await Promise.all([
          this.fetchFarmList({ page: 1 }),
          this.currentFarm ? this.fetchLivestockList({ page: 1, farmId: this.currentFarm.id }) : Promise.resolve(),
          this.fetchRecords({ page: 1 })
        ])
      } catch (error) {
        console.error('刷新数据失败:', error)
        throw error
      }
    },

    /**
     * 清除数据
     */
    clearData() {
      this.farmList = []
      this.currentFarm = null
      this.livestockList = []
      this.currentLivestock = null
      this.records = []
      this.healthData = []
      this.feedData = []
      this.vaccineData = []
      
      // 重置分页
      Object.keys(this.pagination).forEach(key => {
        this.pagination[key].page = 1
        this.pagination[key].total = 0
      })
      
      // 重置统计
      this.statistics = {
        totalFarms: 0,
        totalLivestock: 0,
        healthyCount: 0,
        sickCount: 0,
        feedConsumption: 0,
        vaccineCount: 0
      }
    }
  }
})