<template>
  <div class="wrapper">
    <h2 class="card-title">近24小时降雨量变化趋势图</h2>
    <div class="chart-wrapper">
      <div class="chart-container" ref="chartRef"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import * as echarts from "echarts";
import { debounce } from "lodash-es"; // 防抖函数，避免频繁触发resize

import { getRainCurve } from '@/api/index-dp';
  import {
  useMessage
} from 'naive-ui';
const message = useMessage();


// 设备状态数据列表
var warningLines = ref([]);
var xAxisData = ref([]);
var yAxisData = ref([]);

// 模拟接口请求函数
const fetchRainCurve = async () => {
    const response = await getRainCurve();
    console.log('降雨量',response.data)
    const result = response.data
    if (result.code == 200) {
      yAxisData.value = result.data.ydata
      xAxisData.value = result.data.xdata
      warningLines.value = result.data.alarm
    } else {
      message.error(result.msg)
    }
 
};


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);
  console.log(hours, data)

 // 定义警戒线值
  // const warningLines = [
  //    { value: 50, name: '蓝色警戒线', color: '#409EFF' },
  //   { value: 100, name: '黄色警戒线', color: '#FFD700' },
  //   { value: 150, name: '橙色警戒线', color: '#FF8C00' },
  //   { value: 200, name: '红色警戒线', color: '#FF0000' }
  // ];

  chartInstance.setOption({
    grid: { left: "3%", right: "4%", bottom: "3%", containLabel: true },
     tooltip: {
    trigger: 'axis'
  },
    xAxis: {
      type: "category",
      data: xAxisData.value,
      axisLine: { lineStyle: { color: "#4f6b95" } },
      axisLabel: { color: "#fff", interval: 2 },
    },
    yAxis: {
      name:'mm',
      nameTextStyle: {
        color: "white",
        padding: [0, 38, 0, 0],
      },
      type: "value",
      // max: 300,
      axisLine: { lineStyle: { color: "#4f6b95" } },
      axisLabel: { color: "white"},
      splitLine: { lineStyle: { color: "rgba(79, 107, 149, 0.2)" } },
    },
    
    series: [
      {
        data: yAxisData.value,
        type: "line",
        smooth: true,
        showSymbol: false,
        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 },
        markLine: {
          symbol: 'none',
          data: warningLines.value.map(line => ({
            label: {
              show: false
            },
            name: line.name,
            yAxis: line.value,
            lineStyle: {
              color: line.color,
              width: 1,
              type: 'dashed',
            }
          }))
        }
      },
    ],
  });
};

// 使用防抖优化resize性能
const resizeChart = debounce(() => {
  if (chartInstance) {
    chartInstance.resize({
      animation: {
        duration: 300
      }
    });
  }
}, 300);

// 监听容器尺寸变化（更精确的自适应）
const observeContainerResize = () => {
  if (!chartRef.value) return;
  
  const resizeObserver = new ResizeObserver(entries => {
    // 使用防抖函数处理尺寸变化
    resizeChart();
  });
  
  resizeObserver.observe(chartRef.value);
  
  // 返回清理函数
  return () => resizeObserver.disconnect();
};

let cleanupObserver: (() => void) | null = null;

onMounted(() => {
  fetchRainCurve().then(() => {
    nextTick(() => {
      initChart();
      // 添加窗口大小改变事件监听器
      window.addEventListener("resize", resizeChart);
      // 添加容器尺寸观察器
      cleanupObserver = observeContainerResize();
    });
  });
});

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

<style scoped lang="scss">
.wrapper {
  overflow: visible;
  width: 4.6rem;
  height: 3rem;
  position: relative;
  padding: 0.15rem;
  width: 100%;
  margin-top: 0.3rem;
  background-image: url("@/assets/jinrun/module-bg.png");
  background-size: cover;
  background-repeat: no-repeat;
  
  .card-title {
    position: absolute;
    left: 0.25rem;
    top: -0.15rem;
    font-weight: 500;
    font-size: 0.2rem;
    color: #ffffff;
    text-shadow: 0rem 0rem 0rem rgba(5, 38, 68, 0.5);
  }
  
  .chart-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 100%;
  }
  
  .chart-container {
    width: 100%;
    height: 100%;
  }
}
</style>