<template>
  <div class="cattle-chart">
    <a-card title="牛只统计分析" :bordered="false">
      <div class="chart-controls">
        <a-space>
          <a-select v-model:value="timeRange" @change="handleTimeRangeChange" style="width: 120px">
            <a-select-option value="7d">近7天</a-select-option>
            <a-select-option value="30d">近30天</a-select-option>
            <a-select-option value="90d">近3个月</a-select-option>
            <a-select-option value="1y">近1年</a-select-option>
          </a-select>
          <a-select v-model:value="chartType" @change="handleChartTypeChange" style="width: 120px">
            <a-select-option value="line">折线图</a-select-option>
            <a-select-option value="bar">柱状图</a-select-option>
            <a-select-option value="area">面积图</a-select-option>
          </a-select>
        </a-space>
      </div>
      <div ref="chartContainer" class="chart-container"></div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { cattleAPI } from '../../services/api.js';

const chartContainer = ref(null);
const timeRange = ref('30d');
const chartType = ref('line');
let chartInstance = null;

const chartData = ref({
  dates: [],
  totalCattle: [],
  newCattle: [],
  soldCattle: [],
  healthyCattle: [],
  sickCattle: []
});

const loading = ref(false);

// 初始化图表
const initChart = () => {
  if (chartContainer.value) {
    chartInstance = echarts.init(chartContainer.value);
    updateChart();
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);
  }
};

// 更新图表
const updateChart = () => {
  if (!chartInstance || !chartData.value.dates.length) return;

  const option = {
    title: {
      text: '牛只数量趋势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      },
      formatter: function(params) {
        let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].axisValue}</div>`;
        params.forEach(param => {
          result += `<div style="margin: 2px 0;">
            <span style="display: inline-block; width: 10px; height: 10px; background-color: ${param.color}; border-radius: 50%; margin-right: 5px;"></span>
            ${param.seriesName}: ${param.value}头
          </div>`;
        });
        return result;
      }
    },
    legend: {
      data: ['总数量', '新增', '出售', '健康', '患病'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: chartData.value.dates,
      axisLabel: {
        formatter: function(value) {
          return echarts.format.formatTime('MM-dd', new Date(value));
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 头'
      }
    },
    series: [
      {
        name: '总数量',
        type: chartType.value,
        stack: chartType.value === 'area' ? 'Total' : null,
        areaStyle: chartType.value === 'area' ? {} : null,
        emphasis: {
          focus: 'series'
        },
        data: chartData.value.totalCattle,
        itemStyle: {
          color: '#1890ff'
        }
      },
      {
        name: '新增',
        type: chartType.value,
        stack: chartType.value === 'area' ? 'Total' : null,
        areaStyle: chartType.value === 'area' ? {} : null,
        emphasis: {
          focus: 'series'
        },
        data: chartData.value.newCattle,
        itemStyle: {
          color: '#52c41a'
        }
      },
      {
        name: '出售',
        type: chartType.value,
        stack: chartType.value === 'area' ? 'Total' : null,
        areaStyle: chartType.value === 'area' ? {} : null,
        emphasis: {
          focus: 'series'
        },
        data: chartData.value.soldCattle,
        itemStyle: {
          color: '#faad14'
        }
      },
      {
        name: '健康',
        type: chartType.value,
        emphasis: {
          focus: 'series'
        },
        data: chartData.value.healthyCattle,
        itemStyle: {
          color: '#73d13d'
        }
      },
      {
        name: '患病',
        type: chartType.value,
        emphasis: {
          focus: 'series'
        },
        data: chartData.value.sickCattle,
        itemStyle: {
          color: '#ff4d4f'
        }
      }
    ]
  };

  chartInstance.setOption(option);
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const response = await cattleAPI.getChartData({
      timeRange: timeRange.value,
      type: 'statistics'
    });

    if (response.success) {
      chartData.value = response.data;
      await nextTick();
      updateChart();
    } else {
      // 使用模拟数据
      generateMockData();
    }
  } catch (error) {
    console.error('加载牛只统计数据失败:', error);
    generateMockData();
  } finally {
    loading.value = false;
  }
};

// 生成模拟数据
const generateMockData = () => {
  const days = timeRange.value === '7d' ? 7 : timeRange.value === '30d' ? 30 : timeRange.value === '90d' ? 90 : 365;
  const dates = [];
  const totalCattle = [];
  const newCattle = [];
  const soldCattle = [];
  const healthyCattle = [];
  const sickCattle = [];

  let baseTotal = 1200;
  
  for (let i = days - 1; i >= 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    dates.push(date.toISOString().split('T')[0]);
    
    // 模拟数据变化
    const dailyNew = Math.floor(Math.random() * 20) + 5;
    const dailySold = Math.floor(Math.random() * 15) + 2;
    baseTotal = baseTotal + dailyNew - dailySold;
    
    totalCattle.push(baseTotal);
    newCattle.push(dailyNew);
    soldCattle.push(dailySold);
    healthyCattle.push(Math.floor(baseTotal * 0.92) + Math.floor(Math.random() * 20));
    sickCattle.push(Math.floor(baseTotal * 0.08) + Math.floor(Math.random() * 10));
  }

  chartData.value = {
    dates,
    totalCattle,
    newCattle,
    soldCattle,
    healthyCattle,
    sickCattle
  };

  updateChart();
};

// 处理时间范围变化
const handleTimeRangeChange = () => {
  loadData();
};

// 处理图表类型变化
const handleChartTypeChange = () => {
  updateChart();
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

onMounted(() => {
  nextTick(() => {
    initChart();
    loadData();
  });
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  window.removeEventListener('resize', handleResize);
});

// 监听数据变化
watch(() => chartData.value, () => {
  updateChart();
}, { deep: true });
</script>

<style scoped>
.cattle-chart {
  width: 100%;
  height: 100%;
}

.chart-controls {
  margin-bottom: 16px;
  text-align: right;
}

.chart-container {
  width: 100%;
  height: 400px;
}

:deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.ant-card-body) {
  padding: 20px;
}
</style>