<template>
  <div class="analysis-container page-container">
    <div class="toolbar" style="margin-bottom: 20px;">
      <a-radio-group v-model="period" type="button" @change="fetchData as any">
        <a-radio value="day">今日 (按小时)</a-radio>
        <a-radio value="month">本月 (按日)</a-radio>
      </a-radio-group>
    </div>

    <a-card :bordered="false">
      <div ref="chartRef" style="height: 500px;"></div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import { getEnergyAnalysis } from '../api/monitor';
import { Message } from '@arco-design/web-vue';

const period = ref<'day' | 'month'>('day');
const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

const fetchData = async () => {
  try {
    const data = await getEnergyAnalysis(period.value);
    updateChart(data);
  } catch (error) {
    Message.error('获取分析数据失败');
  }
};

const updateChart = (data: any[]) => {
  if (!chartInstance && chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
  }
  
  if (!chartInstance) return;

  // Process data for Stacked Bar Chart
  const categories = [...new Set(data.map(item => item.time))];
  const types = [...new Set(data.map(item => item.type))];
  
  const series = types.map(type => {
    return {
      name: type,
      type: 'bar',
      stack: 'total',
      emphasis: { focus: 'series' },
      data: categories.map(time => {
        const found = data.find(d => d.time === time && d.type === type);
        return found ? found.value : 0;
      })
    };
  });

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: types
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: categories
    },
    yAxis: {
      type: 'value',
      name: 'kWh'
    },
    series: series
  };

  chartInstance.setOption(option);
};

onMounted(() => {
  nextTick(() => {
    fetchData();
  });
  window.addEventListener('resize', handleResize);
});

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

const handleResize = () => {
  chartInstance?.resize();
};
</script>

<style scoped>
.page-container {
  padding: 20px;
}
</style>
