<template>
  <div class="analytics-page">
    <a-page-header
      title="数据分析"
      sub-title="宁夏智慧养殖监管平台数据分析"
    >
      <template #extra>
        <a-space>
          <a-button>导出报表</a-button>
          <a-button type="primary" @click="refreshData">
            <template #icon><reload-outlined /></template>
            刷新数据
          </a-button>
        </a-space>
      </template>
    </a-page-header>
    
    <div class="analytics-content">
      <!-- 趋势图表 -->
      <a-card title="月度数据趋势" :bordered="false" class="chart-card">
        <e-chart :options="trendChartOptions" height="350px" @chart-ready="handleChartReady" />
      </a-card>
      
      <div class="analytics-row">
        <!-- 养殖场类型分布 -->
        <a-card title="养殖场类型分布" :bordered="false" class="chart-card">
          <e-chart :options="farmTypeChartOptions" height="300px" />
        </a-card>
        
        <!-- 动物类型分布 -->
        <a-card title="动物类型分布" :bordered="false" class="chart-card">
          <animal-stats />
        </a-card>
      </div>
      
      <div class="analytics-row">
        <!-- 设备类型分布 -->
        <a-card title="设备类型分布" :bordered="false" class="chart-card">
          <device-stats />
          <simple-device-test />
        </a-card>
        
        <!-- 预警类型分布 -->
        <a-card title="预警类型分布" :bordered="false" class="chart-card">
          <alert-stats />
        </a-card>
      </div>
      
      <!-- 数据表格 -->
      <a-card title="养殖场数据统计" :bordered="false" class="data-card">
        <a-table :dataSource="farmTableData" :columns="farmColumns" :pagination="{ pageSize: 5 }">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'animalCount'">
              <a-progress :percent="getPercentage(record.animalCount, maxAnimalCount)" :stroke-color="getProgressColor(record.animalCount, maxAnimalCount)" />
            </template>
            <template v-if="column.key === 'deviceCount'">
              <a-progress :percent="getPercentage(record.deviceCount, maxDeviceCount)" :stroke-color="getProgressColor(record.deviceCount, maxDeviceCount)" />
            </template>
            <template v-if="column.key === 'alertCount'">
              <a-progress :percent="getPercentage(record.alertCount, maxAlertCount)" :stroke-color="{ from: '#108ee9', to: '#ff4d4f' }" />
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { ReloadOutlined } from '@ant-design/icons-vue'
import { useDataStore } from '../stores'
import EChart from '../components/EChart.vue'
import AnimalStats from '../components/AnimalStats.vue'
import DeviceStats from '../components/DeviceStats.vue'
import AlertStats from '../components/AlertStats.vue'
import SimpleDeviceTest from '../components/SimpleDeviceTest.vue'
// 移除模拟数据导入

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

// 图表实例
const charts = reactive({
  trendChart: null
})

// 月度数据趋势
const trendData = ref({
  xAxis: [],
  series: []
})

// 处理图表就绪事件
function handleChartReady(chart, type) {
  if (type === 'trend') {
    charts.trendChart = chart
  }
}

// 获取月度数据趋势
async function fetchMonthlyTrends() {
  try {
    const response = await fetch('/api/stats/public/monthly-trends')
    const result = await response.json()
    
    if (result.success) {
      trendData.value = result.data
      updateChartData()
    } else {
      console.error('获取月度数据趋势失败:', result.message)
    }
  } catch (error) {
    console.error('获取月度数据趋势失败:', error)
  }
}

// 刷新数据
async function refreshData() {
  await dataStore.fetchAllData()
  await fetchMonthlyTrends()
  updateChartData()
}

// 更新图表数据
function updateChartData() {
  // 更新趋势图表数据
  if (charts.trendChart) {
    charts.trendChart.setOption({
      xAxis: { data: trendData.value.xAxis },
      series: trendData.value.series
    })
  }
}

// 趋势图表选项
const trendChartOptions = computed(() => {
  return {
    title: {
      text: '月度数据趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: trendData.value.series.map(item => item.name),
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: trendData.value.xAxis
    },
    yAxis: {
      type: 'value'
    },
    series: trendData.value.series.map(item => ({
      name: item.name,
      type: item.type || 'line',
      data: item.data,
      smooth: true,
      itemStyle: item.itemStyle,
      lineStyle: item.lineStyle,
      areaStyle: item.areaStyle
    }))
  }
})

// 养殖场类型分布图表选项
const farmTypeChartOptions = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0
    },
    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: [
          { value: 5, name: '牛养殖场' },
          { value: 7, name: '羊养殖场' },
          { value: 3, name: '混合养殖场' },
          { value: 2, name: '其他养殖场' }
        ]
      }
    ]
  }
})

// 动物类型分布图表选项
const animalTypeChartOptions = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0
    },
    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: []
      }
    ]
  }
})

// 设备类型分布图表选项
const deviceTypeChartOptions = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0
    },
    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: []
      }
    ]
  }
})

// 预警类型分布图表选项
const alertTypeChartOptions = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0
    },
    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: []
      }
    ]
  }
})

// 养殖场表格数据
const farmTableData = computed(() => {
  console.log('计算farmTableData:', {
    farms: dataStore.farms.length,
    animals: dataStore.animals.length,
    devices: dataStore.devices.length,
    alerts: dataStore.alerts.length
  })
  
  return dataStore.farms.map(farm => {
    // 获取该养殖场的动物数量
    const animals = dataStore.animals.filter(animal => animal.farm_id === farm.id)
    const animalCount = animals.reduce((sum, animal) => sum + (animal.count || 0), 0)
    
    // 获取该养殖场的设备数量
    const devices = dataStore.devices.filter(device => device.farm_id === farm.id)
    const deviceCount = devices.length
    
    // 获取该养殖场的预警数量
    const alerts = dataStore.alerts.filter(alert => alert.farm_id === farm.id)
    const alertCount = alerts.length
    
    console.log(`养殖场 ${farm.name} (ID: ${farm.id}):`, {
      animalCount,
      deviceCount,
      alertCount
    })
    
    return {
      key: farm.id,
      id: farm.id,
      name: farm.name,
      animalCount,
      deviceCount,
      alertCount
    }
  }).filter(farm => farm.animalCount > 0 || farm.deviceCount > 0 || farm.alertCount > 0)
})

// 养殖场表格列定义
const farmColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '养殖场名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '动物数量',
    dataIndex: 'animalCount',
    key: 'animalCount',
    sorter: (a, b) => a.animalCount - b.animalCount
  },
  {
    title: '设备数量',
    dataIndex: 'deviceCount',
    key: 'deviceCount',
    sorter: (a, b) => a.deviceCount - b.deviceCount
  },
  {
    title: '预警数量',
    dataIndex: 'alertCount',
    key: 'alertCount',
    sorter: (a, b) => a.alertCount - b.alertCount
  }
]

// 获取最大值
const maxAnimalCount = computed(() => {
  const counts = farmTableData.value.map(farm => farm.animalCount)
  return Math.max(...counts, 1)
})

const maxDeviceCount = computed(() => {
  const counts = farmTableData.value.map(farm => farm.deviceCount)
  return Math.max(...counts, 1)
})

const maxAlertCount = computed(() => {
  const counts = farmTableData.value.map(farm => farm.alertCount)
  return Math.max(...counts, 1)
})

// 计算百分比
function getPercentage(value, max) {
  return Math.round((value / max) * 100)
}

// 获取进度条颜色
function getProgressColor(value, max) {
  const percentage = getPercentage(value, max)
  if (percentage < 30) return '#52c41a'
  if (percentage < 70) return '#1890ff'
  return '#ff4d4f'
}

// 组件挂载时加载数据
onMounted(async () => {
  console.log('Analytics页面开始加载数据...')
  
  try {
    // 加载数据
    console.log('调用 dataStore.fetchAllData()...')
    await dataStore.fetchAllData()
    
    console.log('数据加载完成:', {
      farms: dataStore.farms.length,
      animals: dataStore.animals.length,
      devices: dataStore.devices.length,
      alerts: dataStore.alerts.length
    })
    
    // 获取月度数据趋势
    console.log('获取月度数据趋势...')
    await fetchMonthlyTrends()
    
    console.log('Analytics页面数据加载完成')
  } catch (error) {
    console.error('Analytics页面数据加载失败:', error)
  }
})
</script>

<style scoped>
.analytics-page {
  padding: 0 16px;
}

.analytics-content {
  margin-top: 16px;
}

.chart-card {
  margin-bottom: 16px;
}

.analytics-row {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}

.data-card {
  margin-bottom: 16px;
}

@media (max-width: 1200px) {
  .analytics-row {
    grid-template-columns: 1fr;
  }
}
</style>