<template>
  <div class="animal-stats">
    <a-card :bordered="false" title="动物数据统计">
      <div class="stats-summary">
        <div class="stat-item">
          <div class="stat-value">{{ totalAnimals }}</div>
          <div class="stat-label">动物总数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ animalTypes.length }}</div>
          <div class="stat-label">动物种类</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ averagePerFarm }}</div>
          <div class="stat-label">平均数量/场</div>
        </div>
      </div>
      
      <a-divider />
      
      <div class="chart-container">
        <e-chart :options="typeDistributionOptions" height="300px" />
      </div>
      
      <a-divider />
      
      <div class="animal-table">
        <a-table 
          :dataSource="animalTableData" 
          :columns="animalColumns" 
          :pagination="{ pageSize: 5 }"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'count'">
              <a-progress 
                :percent="getPercentage(record.count, maxCount)" 
                :stroke-color="getProgressColor(record.count, maxCount)" 
              />
            </template>
          </template>
        </a-table>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { computed, onMounted } from 'vue'
import { useDataStore } from '../stores'
import EChart from './EChart.vue'

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

// 组件挂载时加载数据
onMounted(async () => {
  console.log('AnimalStats: 组件挂载，开始加载数据')
  await dataStore.fetchAllData()
  console.log('AnimalStats: 数据加载完成')
  console.log('farms数据:', dataStore.farms)
  console.log('animals数据:', dataStore.animals)
})

// 动物总数
const totalAnimals = computed(() => {
  return dataStore.animals.reduce((total, animal) => total + (animal.count || 0), 0)
})

// 动物种类
const animalTypes = computed(() => {
  const types = new Set(dataStore.animals.map(animal => getTypeText(animal.type)))
  return Array.from(types)
})

// 平均每个养殖场的动物数量
const averagePerFarm = computed(() => {
  if (dataStore.farms.length === 0) return 0
  return Math.round(totalAnimals.value / dataStore.farms.length)
})

// 动物类型分布图表选项
const typeDistributionOptions = computed(() => {
  // 按类型分组统计
  const typeCount = {}
  dataStore.animals.forEach(animal => {
    const chineseType = getTypeText(animal.type)
    typeCount[chineseType] = (typeCount[chineseType] || 0) + (animal.count || 0)
  })
  
  // 转换为图表数据格式
  const data = Object.keys(typeCount).map(type => ({
    value: typeCount[type],
    name: type
  }))
  
  return {
    title: {
      text: '动物类型分布',
      left: 'center'
    },
    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: data
      }
    ]
  }
})

// 动物表格数据
const animalTableData = computed(() => {
  // 按类型和养殖场分组统计
  const groupMap = new Map()
  
  dataStore.animals.forEach(animal => {
    const key = `${animal.farm_id}-${animal.type}`
    if (!groupMap.has(key)) {
      const farm = dataStore.farms.find(f => f.id === animal.farm_id)
      groupMap.set(key, {
        key: key,
        farmId: animal.farm_id,
        farmName: farm ? farm.name : `养殖场 #${animal.farm_id}`,
        type: getTypeText(animal.type),
        count: 0
      })
    }
    groupMap.get(key).count += (animal.count || 0)
  })
  
  // 转换为数组并按数量降序排序
  return Array.from(groupMap.values()).sort((a, b) => b.count - a.count)
})

// 最大数量
const maxCount = computed(() => {
  if (animalTableData.value.length === 0) return 1
  return Math.max(...animalTableData.value.map(item => item.count))
})

// 动物表格列定义
const animalColumns = [
  {
    title: '养殖场',
    dataIndex: 'farmName',
    key: 'farmName'
  },
  {
    title: '动物类型',
    dataIndex: 'type',
    key: 'type'
  },
  {
    title: '数量',
    dataIndex: 'count',
    key: 'count',
    sorter: (a, b) => a.count - b.count,
    defaultSortOrder: 'descend'
  }
]

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

// 获取类型文本（英文转中文）
function getTypeText(type) {
  const texts = {
    pig: '猪',
    chicken: '鸡',
    cow: '牛',
    sheep: '羊',
    duck: '鸭',
    goose: '鹅',
    fish: '鱼',
    shrimp: '虾',
    cattle: '牛',
    poultry: '家禽',
    swine: '猪',
    livestock: '牲畜',
    other: '其他'
  }
  return texts[type] || type
}

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

<style scoped>
.animal-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;
}

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