<template>
  <div class="device-stats">
    <a-card :bordered="false" title="设备数据统计">
      <div class="stats-summary">
        <div class="stat-item">
          <div class="stat-value">{{ totalDevices }}</div>
          <div class="stat-label">设备总数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value" style="color: #52c41a;">{{ onlineDevices }}</div>
          <div class="stat-label">在线设备</div>
        </div>
        <div class="stat-item">
          <div class="stat-value" style="color: #faad14;">{{ maintenanceDevices }}</div>
          <div class="stat-label">维护设备</div>
        </div>
        <div class="stat-item">
          <div class="stat-value" style="color: #ff4d4f;">{{ offlineDevices }}</div>
          <div class="stat-label">离线设备</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ onlineRate }}%</div>
          <div class="stat-label">在线率</div>
        </div>
      </div>
      
      <a-divider />
      
      <div class="chart-container">
        <e-chart :options="deviceStatusOptions" height="300px" />
      </div>
      
      <a-divider />
      
      <div class="device-table">
        <a-table 
          :dataSource="deviceTableData" 
          :columns="deviceColumns" 
          :pagination="{ pageSize: 5 }"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.originalStatus)">
                {{ record.status }}
              </a-tag>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>
  </div>
</template>

<script setup>
// 设备统计组件 - 显示设备状态分布
import { computed, onMounted, watch } from 'vue'
import { useDataStore } from '../stores'
import EChart from './EChart.vue'

// 使用数据存储
const dataStore = useDataStore()

// 组件挂载时确保数据已加载
onMounted(async () => {
  console.log('=== DeviceStats组件挂载 ===')
  console.log('当前设备数量:', dataStore.devices.length)
  
  try {
    console.log('开始获取设备数据...')
    
    // 直接测试API调用
    console.log('直接测试API调用...')
    const { deviceService } = await import('../utils/dataService')
    const apiResult = await deviceService.getAllDevices()
    console.log('直接API调用结果:', apiResult)
    console.log('API返回数据类型:', typeof apiResult)
    console.log('API返回是否为数组:', Array.isArray(apiResult))
    console.log('API返回数据长度:', apiResult?.length || 0)
    
    await dataStore.fetchDevices()
    console.log('设备数据获取完成:', dataStore.devices.length, '台设备')
    
    // 详细输出设备数据
    console.log('设备数据详情:', dataStore.devices.slice(0, 3))
    
    const statusCount = {}
    dataStore.devices.forEach(device => {
      statusCount[device.status] = (statusCount[device.status] || 0) + 1
    })
    console.log('设备状态分布:', statusCount)
    
    // 输出计算属性的值
    console.log('计算属性值:')
    console.log('- totalDevices:', totalDevices.value)
    console.log('- onlineDevices:', onlineDevices.value)
    console.log('- maintenanceDevices:', maintenanceDevices.value)
    console.log('- offlineDevices:', offlineDevices.value)
    console.log('- onlineRate:', onlineRate.value)
    
    console.log('=== DeviceStats组件挂载完成 ===')
  } catch (error) {
    console.error('获取设备数据失败:', error)
    console.error('错误堆栈:', error.stack)
  }
})

// 监听设备数据变化
watch(() => dataStore.devices, (newDevices) => {
  console.log('设备数据更新:', newDevices.length, '台设备')
  const statusCount = {}
  newDevices.forEach(device => {
    statusCount[device.status] = (statusCount[device.status] || 0) + 1
  })
  console.log('当前状态分布:', statusCount)
  
  // 输出前几个设备的详细信息
  if (newDevices.length > 0) {
    console.log('前3个设备详情:', newDevices.slice(0, 3).map(d => ({ id: d.id, name: d.name, status: d.status })))
  }
}, { deep: true, immediate: true })

// 设备总数
const totalDevices = computed(() => dataStore.devices.length)

// 在线设备数量
const onlineDevices = computed(() => {
  return dataStore.devices.filter(device => device.status === 'online').length
})

// 维护设备数量
const maintenanceDevices = computed(() => {
  return dataStore.devices.filter(device => device.status === 'maintenance').length
})

// 离线设备数量
const offlineDevices = computed(() => {
  return dataStore.devices.filter(device => device.status === 'offline').length
})

// 在线率
const onlineRate = computed(() => {
  if (totalDevices.value === 0) return 0
  return Math.round((onlineDevices.value / totalDevices.value) * 100)
})

// 设备状态分布图表选项
const deviceStatusOptions = computed(() => {
  console.log('计算图表选项，当前设备数量:', dataStore.devices.length)
  
  // 如果没有设备数据，显示空状态
  if (dataStore.devices.length === 0) {
    console.log('没有设备数据，显示空状态图表')
    return {
      title: {
        text: '设备状态分布',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      series: [
        {
          name: '设备状态',
          type: 'pie',
          radius: ['50%', '70%'],
          data: [
            {
              value: 1,
              name: '暂无数据',
              itemStyle: {
                color: '#d9d9d9'
              }
            }
          ]
        }
      ]
    }
  }
  
  // 按状态分组统计
  const statusCount = {}
  dataStore.devices.forEach(device => {
    const chineseStatus = getStatusText(device.status)
    statusCount[chineseStatus] = (statusCount[chineseStatus] || 0) + 1
  })
  
  console.log('状态统计:', statusCount)
  
  // 定义状态颜色映射
  const statusColors = {
    '在线': '#52c41a',
    '维护中': '#faad14', 
    '离线': '#ff4d4f'
  }
  
  // 转换为图表数据格式，并添加颜色
  const data = Object.keys(statusCount).map(status => ({
    value: statusCount[status],
    name: status,
    itemStyle: {
      color: statusColors[status] || '#d9d9d9'
    }
  }))
  
  console.log('图表数据:', data)
  
  return {
    title: {
      text: '设备状态分布',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}台 ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      itemGap: 20
    },
    series: [
      {
        name: '设备状态',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
})

// 设备表格数据
const deviceTableData = computed(() => {
  return dataStore.devices.map(device => {
    const farm = dataStore.farms.find(f => f.id === device.farm_id || f.id === device.farmId)
    return {
      key: device.id,
      id: device.id,
      name: device.name,
      type: getTypeText(device.type),
      farmId: device.farm_id || device.farmId,
      farmName: farm ? farm.name : `养殖场 #${device.farm_id || device.farmId}`,
      status: getStatusText(device.status),
      originalStatus: device.status,
      lastUpdate: device.last_maintenance || device.lastUpdate || '未知'
    }
  })
})

// 设备表格列定义
const deviceColumns = [
  {
    title: '设备名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '设备类型',
    dataIndex: 'type',
    key: 'type'
  },
  {
    title: '养殖场',
    dataIndex: 'farmName',
    key: 'farmName'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    filters: [
      { text: '在线', value: '在线' },
      { text: '维护中', value: '维护中' },
      { text: '离线', value: '离线' }
    ],
    onFilter: (value, record) => record.status === value
  },
  {
    title: '最后更新',
    dataIndex: 'lastUpdate',
    key: 'lastUpdate',
    sorter: (a, b) => new Date(a.lastUpdate) - new Date(b.lastUpdate),
    defaultSortOrder: 'descend'
  }
]

// 获取类型文本（英文转中文）
function getTypeText(type) {
  const texts = {
    temperature_sensor: '温度传感器',
    humidity_sensor: '湿度传感器',
    feed_dispenser: '饲料分配器',
    water_system: '水系统',
    ventilation_system: '通风系统',
    sensor: '传感器',
    camera: '摄像头',
    feeder: '喂食器',
    monitor: '监控器',
    controller: '控制器',
    other: '其他'
  }
  return texts[type] || type
}

// 获取状态文本（英文转中文）
function getStatusText(status) {
  switch (status) {
    case 'online': return '在线'
    case 'offline': return '离线'
    case 'maintenance': return '维护中'
    default: return status
  }
}

// 获取状态颜色（支持英文状态）
function getStatusColor(status) {
  switch (status) {
    case 'online':
    case '在线': return 'success'
    case 'offline':
    case '离线': return 'error'
    case 'maintenance':
    case '维护中': return 'processing'
    default: return 'default'
  }
}
</script>

<style scoped>
.device-stats {
  width: 100%;
}

.stats-summary {
  display: flex;
  justify-content: space-around;
  margin-bottom: 16px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
}

.stat-label {
  font-size: 14px;
  color: #8c8c8c;
}

.chart-container {
  margin: 16px 0;
}

.device-table {
  margin-top: 16px;
}
</style>