<template>
  <div class="data-center-container">
    <!-- 顶部统计卡片 -->
    <div class="stat-cards">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-header">
              <div class="stat-title">养殖户总数</div>
              <div class="stat-icon">
                <span class="iconfont icon-renyuanguanli"></span>
              </div>
            </div>
            <div class="stat-body">
              <div class="stat-value">{{ 养殖户总数 }}</div>
              <div class="stat-trend">
                <span class="trend-value">+5.2%</span>
                <span class="trend-label">较上月</span>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-header">
              <div class="stat-title">存栏总量</div>
              <div class="stat-icon">
                <span class="iconfont icon-niu"></span>
              </div>
            </div>
            <div class="stat-body">
              <div class="stat-value">{{ 存栏总量 }}</div>
              <div class="stat-trend">
                <span class="trend-value">+2.8%</span>
                <span class="trend-label">较上月</span>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-header">
              <div class="stat-title">交易量</div>
              <div class="stat-icon">
                <span class="iconfont icon-shengzijiaoyi"></span>
              </div>
            </div>
            <div class="stat-body">
              <div class="stat-value">{{ 交易量 }}</div>
              <div class="stat-trend negative">
                <span class="trend-value">-1.5%</span>
                <span class="trend-label">较上月</span>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <div class="stat-header">
              <div class="stat-title">活跃用户</div>
              <div class="stat-icon">
                <span class="iconfont icon-yonghu"></span>
              </div>
            </div>
            <div class="stat-body">
              <div class="stat-value">{{ 活跃用户 }}</div>
              <div class="stat-trend">
                <span class="trend-value">+8.3%</span>
                <span class="trend-label">较上月</span>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>
    
    <!-- 主要图表区域 -->
    <div class="chart-section">
      <a-row :gutter="16">
        <a-col :span="16">
          <a-card class="chart-card" title="月度交易量趋势">
            <div ref="transactionChartRef" class="chart-container"></div>
          </a-card>
        </a-col>
        <a-col :span="8">
          <a-card class="chart-card" title="品类占比分析">
            <div ref="categoryChartRef" class="chart-container"></div>
          </a-card>
        </a-col>
      </a-row>
    </div>
    
    <!-- 第二行图表 -->
    <div class="chart-section">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-card class="chart-card" title="养殖区域分布">
            <div ref="mapChartRef" class="chart-container"></div>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card class="chart-card" title="养殖规模分布">
            <div ref="scaleChartRef" class="chart-container"></div>
          </a-card>
        </a-col>
      </a-row>
    </div>
    
    <!-- 数据更新信息 -->
    <div class="update-section">
      <a-card class="update-card" title="数据更新信息">
        <a-list>
          <a-list-item v-for="(item, index) in updates" :key="index">
            <div class="update-item">
              <div class="update-icon blue"></div>
              <div class="update-content">
                <div class="update-title">数据更新</div>
                <div class="update-time">{{ item.time }}</div>
                <div class="update-desc">{{ item.content }}</div>
              </div>
            </div>
          </a-list-item>
        </a-list>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';

// 数据统计
const 养殖户总数 = ref('0')
const 存栏总量 = ref('0头')
const 交易量 = ref('¥0')
const 活跃用户 = ref('0')
const updates = ref([])

// 图表数据
const monthlyTrends = ref([])
const categoryDistribution = ref([])
const regionDistribution = ref([])
const scaleDistribution = ref([])

// 图表引用
const mapChartRef = ref(null)
const scaleChartRef = ref(null)
const transactionChartRef = ref(null)
const categoryChartRef = ref(null)

// 初始化交易量趋势图表
const initTransactionChart = () => {
  if (!transactionChartRef.value || !monthlyTrends.value.length) return
  
  const chart = echarts.init(transactionChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: monthlyTrends.value.map(item => item.month)
    },
    yAxis: {
      type: 'value',
      name: '交易额(亿元)'
    },
    series: [
      {
        name: '交易量',
        type: 'line',
        stack: 'Total',
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(58, 77, 233, 0.8)' },
            { offset: 1, color: 'rgba(58, 77, 233, 0.1)' }
          ])
        },
        emphasis: {
          focus: 'series'
        },
        data: monthlyTrends.value.map(item => item.value / 10000),
        itemStyle: {
          color: '#3a4de9'
        },
        lineStyle: {
          width: 3,
          color: '#3a4de9'
        },
        symbol: 'circle',
        symbolSize: 8
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化品类占比图表
const initCategoryChart = () => {
  if (!categoryChartRef.value || !categoryDistribution.value.length) return
  
  const chart = echarts.init(categoryChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '5%',
      left: 'center'
    },
    series: [
      {
        name: '品类占比',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '40%'],
        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: categoryDistribution.value
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化养殖区域分布图表
const initMapChart = () => {
  if (!mapChartRef.value || !regionDistribution.value.length) return
  
  const chart = echarts.init(mapChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '5%',
      left: 'center',
      data: regionDistribution.value.map(item => item.name)
    },
    series: [
      {
        name: '养殖区域分布',
        type: 'pie',
        radius: ['40%', '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: regionDistribution.value
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化养殖规模分布图表
const initScaleChart = () => {
  if (!scaleChartRef.value || !scaleDistribution.value.length) return
  
  const chart = echarts.init(scaleChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: scaleDistribution.value.map(item => item.name)
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '养殖场数量',
        type: 'bar',
        barWidth: '60%',
        data: scaleDistribution.value.map(item => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#3a4de9' },
            { offset: 1, color: '#8c7ae6' }
          ])
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 从API获取数据（统一封装）
import api from '@/utils/api-redesigned'

const fetchData = async () => {
  try {
    const data = await api.dashboard.getDataCenter();
    
    // 更新统计数据
    养殖户总数.value = data.totalFarmers.toLocaleString();
    存栏总量.value = `${data.totalAnimals.toLocaleString()}头`;
    交易量.value = `¥${(data.totalTransactions / 10000).toFixed(2)}亿`;
    活跃用户.value = data.activeUsers.toLocaleString();
    
    // 更新图表数据
    monthlyTrends.value = data.monthlyTrends;
    categoryDistribution.value = data.categoryDistribution;
    regionDistribution.value = data.regionDistribution;
    scaleDistribution.value = data.scaleDistribution;
    updates.value = data.updates;
    
    // 初始化所有图表
    setTimeout(() => {
      initTransactionChart();
      initCategoryChart();
      initMapChart();
      initScaleChart();
    }, 100);
  } catch (error) {
    console.error('获取数据失败:', error);
  }
}

// 组件挂载时获取数据并初始化图表
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.data-center-container {
  padding: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.stat-title {
  font-size: 16px;
  color: #666;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #3a4de9;
  font-size: 20px;
}

.stat-body {
  padding: 16px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.stat-trend {
  display: flex;
  align-items: center;
  color: #52c41a;
}

.stat-trend.negative {
  color: #f5222d;
}

.trend-value {
  font-weight: bold;
  margin-right: 5px;
}

.trend-label {
  font-size: 12px;
  color: #999;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.chart-container {
  height: 300px;
}

.update-section {
  margin-bottom: 20px;
}

.update-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.update-item {
  display: flex;
  align-items: flex-start;
  padding: 8px 0;
}

.update-icon {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 16px;
  margin-top: 5px;
}

.update-icon.blue {
  background-color: #1890ff;
}

.update-icon.green {
  background-color: #52c41a;
}

.update-icon.orange {
  background-color: #fa8c16;
}

.update-icon.red {
  background-color: #f5222d;
}

.update-content {
  flex: 1;
}

.update-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 4px;
}

.update-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.update-desc {
  font-size: 13px;
  color: #666;
}
</style>