import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useDataStore = defineStore('data', () => {
  // 数据状态
  const farms = ref([])
  const animals = ref([])
  const devices = ref([])
  const alerts = ref([])
  const pens = ref([])
  const cattle = ref([])
  const smartDevices = ref([])
  const smartAlerts = ref({ totalAlerts: 0, eartagAlerts: 0, collarAlerts: 0 })
  const stats = ref({
    farmGrowth: 0,
    animalGrowth: 0,
    alertReduction: 0
  })
  
  // 加载状态
  const loading = ref({
    farms: false,
    animals: false,
    devices: false,
    alerts: false,
    pens: false,
    cattle: false,
    smartDevices: false,
    smartAlerts: false,
    stats: false
  })

  // 计算属性
  const farmCount = computed(() => farms.value.length)
  const animalCount = computed(() => Array.isArray(cattle.value) ? cattle.value.length : 0) // 使用牛只数据
  const deviceCount = computed(() => smartAlerts.value?.eartagDevices || 0) // 使用智能设备统计数据
  const alertCount = computed(() => smartAlerts.value?.eartagAlerts || 0) // 使用智能耳标预警数据
  const penCount = computed(() => Array.isArray(pens.value) ? pens.value.length : 0)
  
  // 在线设备数量
  const onlineDeviceCount = computed(() => {
    if (!Array.isArray(smartDevices.value)) return 0
    return smartDevices.value.filter(device => device.state === 1).length
  })
  
  // 设备在线率
  const deviceOnlineRate = computed(() => {
    if (!Array.isArray(smartDevices.value) || smartDevices.value.length === 0) return 0
    return (onlineDeviceCount.value / smartDevices.value.length * 100).toFixed(1)
  })

  // 获取养殖场数据
  async function fetchFarms() {
    loading.value.farms = true
    console.log('开始获取养殖场数据...')
    
    try {
      // 导入数据服务
      const { farmService } = await import('../utils/dataService')
      console.log('调用 farmService.getAllFarms()...')
      const data = await farmService.getAllFarms()
      
      console.log('养殖场API返回数据:', data)
      
      // farmService.getAllFarms()通过api.get返回的是result.data，直接使用
      farms.value = data || []
      console.log('设置farms.value:', farms.value.length, '条记录')
    } catch (error) {
      console.error('获取养殖场数据失败:', error)
      farms.value = []
    } finally {
      loading.value.farms = false
    }
  }

  // 获取动物数据
  async function fetchAnimals() {
    loading.value.animals = true
    try {
      // 导入数据服务
      const { animalService } = await import('../utils/dataService')
      const data = await animalService.getAllAnimals()
      animals.value = data || []
    } catch (error) {
      console.error('获取动物数据失败:', error)
      animals.value = []
    } finally {
      loading.value.animals = false
    }
  }

  // 获取设备数据
  async function fetchDevices() {
    loading.value.devices = true
    try {
      // 导入数据服务
      const { deviceService } = await import('../utils/dataService')
      const data = await deviceService.getAllDevices()
      devices.value = data || []
    } catch (error) {
      console.error('获取设备数据失败:', error)
      devices.value = []
    } finally {
      loading.value.devices = false
    }
  }

  // 获取预警数据
  async function fetchAlerts() {
    loading.value.alerts = true
    try {
      // 导入数据服务
      const { alertService } = await import('../utils/dataService')
      const data = await alertService.getAllAlerts()
      
      // alertService.getAllAlerts()通过api.get返回的是result.data，直接使用
      alerts.value = data || []
    } catch (error) {
      console.error('获取预警数据失败:', error)
      alerts.value = []
    } finally {
      loading.value.alerts = false
    }
  }

  // 获取栏舍数据（基于cattle_pens表）
  async function fetchPens() {
    loading.value.pens = true
    try {
      console.log('开始获取栏舍数据（cattle_pens表）...')
      // 导入数据服务
      const { penService } = await import('../utils/dataService')
      const data = await penService.getAllPens()
      
      console.log('栏舍API返回数据:', data)
      
      // penService.getAllPens()通过api.get返回的是result.data.list，直接使用
      pens.value = data || []
      console.log('设置pens.value:', pens.value.length, '条记录')
    } catch (error) {
      console.error('获取栏舍数据失败:', error)
      pens.value = []
    } finally {
      loading.value.pens = false
    }
  }

  // 获取牛只数据（基于iot_cattle表）
  async function fetchCattle() {
    loading.value.cattle = true
    try {
      console.log('开始获取牛只数据（iot_cattle表）...')
      // 导入数据服务
      const { cattleService } = await import('../utils/dataService')
      const data = await cattleService.getAllCattle()
      
      console.log('牛只API返回数据:', data)
      
      // cattleService.getAllCattle()通过api.get返回的是result.data.list，直接使用
      cattle.value = data || []
      console.log('设置cattle.value:', cattle.value.length, '条记录')
    } catch (error) {
      console.error('获取牛只数据失败:', error)
      cattle.value = []
    } finally {
      loading.value.cattle = false
    }
  }

  // 获取智能设备数据（基于iot_jbq_client表）
  async function fetchSmartDevices() {
    loading.value.smartDevices = true
    try {
      console.log('开始获取智能设备数据（iot_jbq_client表）...')
      // 导入数据服务
      const { smartDeviceService } = await import('../utils/dataService')
      const data = await smartDeviceService.getAllSmartDevices()
      
      console.log('智能设备API返回数据:', data)
      
      // 确保smartDevices.value始终是数组
      if (Array.isArray(data)) {
        smartDevices.value = data
      } else if (data && Array.isArray(data.list)) {
        smartDevices.value = data.list
      } else {
        console.warn('智能设备数据格式不正确:', data)
        smartDevices.value = []
      }
      console.log('设置smartDevices.value:', smartDevices.value.length, '条记录')
    } catch (error) {
      console.error('获取智能设备数据失败:', error)
      smartDevices.value = []
    } finally {
      loading.value.smartDevices = false
    }
  }

  // 获取智能预警数据
  async function fetchSmartAlerts() {
    loading.value.smartAlerts = true
    try {
      console.log('开始获取智能预警数据...')
      // 导入数据服务
      const { smartAlertService } = await import('../utils/dataService')
      console.log('智能预警服务导入成功')
      const data = await smartAlertService.getSmartAlertStats()
      console.log('智能预警API响应:', data)
      
      // smartAlertService.getSmartAlertStats()通过api.get返回的是result.data，直接使用
      smartAlerts.value = data || { totalAlerts: 0, eartagAlerts: 0, collarAlerts: 0 }
      console.log('智能预警数据设置完成:', smartAlerts.value)
    } catch (error) {
      console.error('获取智能预警数据失败:', error)
      smartAlerts.value = { totalAlerts: 0, eartagAlerts: 0, collarAlerts: 0 }
    } finally {
      loading.value.smartAlerts = false
    }
  }
  
  // 获取统计数据
  async function fetchStats() {
    loading.value.stats = true
    try {
      // 导入数据服务
      const { statsService } = await import('../utils/dataService')
      const data = await statsService.getDashboardStats()
      stats.value = data || {
        farmGrowth: 0,
        animalGrowth: 0,
        alertReduction: 0
      }
    } catch (error) {
      console.error('获取统计数据失败:', error)
      stats.value = {
        farmGrowth: 0,
        animalGrowth: 0,
        alertReduction: 0
      }
    } finally {
      loading.value.stats = false
    }
  }

  // 加载所有数据
  async function fetchAllData() {
    console.log('开始并行加载所有数据...')
    
    try {
      await Promise.all([
        fetchFarms(),
        fetchAnimals(),
        fetchDevices(),
        fetchAlerts(),
        fetchPens(),
        fetchCattle(),
        fetchSmartDevices(),
        fetchSmartAlerts(),
        fetchStats()
      ])
      
      console.log('所有数据加载完成:', {
        farms: farms.value.length,
        animals: animals.value.length,
        devices: devices.value.length,
        alerts: alerts.value.length,
        pens: pens.value.length,
        cattle: cattle.value.length,
        smartDevices: smartDevices.value.length,
        smartAlerts: smartAlerts.value.totalAlerts
      })
    } catch (error) {
      console.error('数据加载过程中出现错误:', error)
      throw error
    }
  }

  // 实时数据更新方法（WebSocket调用）
  // function updateDeviceRealtime(deviceData) {
  //   const index = devices.value.findIndex(device => device.id === deviceData.id)
  //   if (index !== -1) {
  //     // 更新现有设备数据
  //     devices.value[index] = { ...devices.value[index], ...deviceData }
  //     console.log(`设备 ${deviceData.id} 实时数据已更新`)
  //   } else {
  //     // 如果是新设备，添加到列表
  //     devices.value.push(deviceData)
  //     console.log(`新设备 ${deviceData.id} 已添加`)
  //   }
  // }

  // function addNewAlert(alertData) {
  //   // 添加新预警到列表顶部
  //   alerts.value.unshift(alertData)
  //   console.log(`新预警 ${alertData.id} 已添加`)
  // }

  // function updateAnimalRealtime(animalData) {
  //   const index = animals.value.findIndex(animal => animal.id === animalData.id)
  //   if (index !== -1) {
  //     // 更新现有动物数据
  //     animals.value[index] = { ...animals.value[index], ...animalData }
  //     console.log(`动物 ${animalData.id} 实时数据已更新`)
  //   } else {
  //     // 如果是新动物记录，添加到列表
  //     animals.value.push(animalData)
  //     console.log(`新动物记录 ${animalData.id} 已添加`)
  //   }
  // }

  // function updateStatsRealtime(statsData) {
  //   // 更新统计数据
  //   stats.value = { ...stats.value, ...statsData }
  //   console.log('系统统计数据已实时更新')
  // }

  function updateAlertStatus(alertId, status) {
    const index = alerts.value.findIndex(alert => alert.id === alertId)
    if (index !== -1) {
      alerts.value[index].status = status
      if (status === 'resolved') {
        alerts.value[index].resolved_at = new Date()
      }
      console.log(`预警 ${alertId} 状态已更新为: ${status}`)
    }
  }

  return {
    // 状态
    farms,
    animals,
    devices,
    alerts,
    pens,
    cattle,
    smartDevices,
    smartAlerts,
    stats,
    loading,
    
    // 计算属性
    farmCount,
    animalCount,
    deviceCount,
    alertCount,
    penCount,
    onlineDeviceCount,
    deviceOnlineRate,
    
    // 数据获取方法
    fetchFarms,
    fetchAnimals,
    fetchDevices,
    fetchAlerts,
    fetchPens,
    fetchCattle,
    fetchSmartDevices,
    fetchSmartAlerts,
    fetchStats,
    fetchAllData,
    
    // 实时数据更新方法
    // updateDeviceRealtime,
    // addNewAlert,
    // updateAnimalRealtime,
    // updateStatsRealtime,
    updateAlertStatus
  }
})