<template>
  <n-card :bordered="false" class="rainfall-trend-card">
    <div class="card-header">
      <h2 class="card-title">近24小时降雨量变化趋势图</h2>
      <n-button size="small" type="text" class="collapse-btn">
        <n-icon><ChevronUp /></n-icon> 收起
      </n-button>
    </div>
    <div class="chart-container" ref="chartRef"></div>
  </n-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import { ChevronUp } from '@vicons/ionicons5';

const chartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

// 初始化ECharts
const initChart = () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);
  const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`);
  const data = hours.map(() => Math.floor(Math.random() * 150) + 20);
  
  chartInstance.setOption({
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category', data: hours,
      axisLine: { lineStyle: { color: '#4f6b95' } },
      axisLabel: { color: '#a0b3d6', interval: 2 }
    },
    yAxis: {
      type: 'value', max: 300,
      axisLine: { lineStyle: { color: '#4f6b95' } },
      axisLabel: { color: '#a0b3d6' },
      splitLine: { lineStyle: { color: 'rgba(79, 107, 149, 0.2)' } }
    },
    series: [{
      data, type: 'line', smooth: true,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(54, 162, 235, 0.4)' },
          { offset: 1, color: 'rgba(54, 162, 235, 0)' }
        ])
      },
      lineStyle: { color: 'rgba(54, 162, 235, 1)', width: 2 }
    }]
  });
};

// 窗口缩放适配
const resizeChart = () => chartInstance?.resize();

onMounted(() => {
  nextTick(initChart);
  window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  chartInstance?.dispose();
});
</script>

<style scoped lang="scss">
.rainfall-trend-card {
  flex: 1;
  padding: 0.15rem;
  background: var(--n-bg-color-secondary);

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.15rem;

    .card-title {
      font-size: 0.18rem;
      font-weight: 600;
      color: var(--n-text-color-primary);
    }

    .collapse-btn {
      font-size: 0.14rem;
      color: var(--n-primary-color);
    }
  }

  .chart-container {
    width: 100%;
    height: calc(100% - 0.4rem);
    min-height: 1.2rem;
  }
}
</style>