<template>
  <div class="wrapper">
    <h2 class="card-title">近24小时降雨量变化趋势图</h2>
    <div class="chart-wrapper">
      <div class="chart-container" ref="chartRef"></div>
      <div v-show="showNoData" class="no-data-overlay">
        <div class="no-data-text">暂无数据</div>
      </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();

// 轮询定时器
let pollingTimer: number | null = null;
// 轮询间隔时间（毫秒）
const POLLING_INTERVAL = 10000; // 10秒

// 设备状态数据列表
var warningLines = ref([]);
var xAxisData = ref([]);
var yAxisData = ref([]);
// 控制是否显示"暂无数据"提示
const showNoData = ref(false);

// 默认坐标轴配置
const DEFAULT_X_AXIS_DATA = Array.from({ length: 24 }, (_, i) => `${i}:00`);
const DEFAULT_Y_AXIS_MAX = 250; // Y轴最大值
const DEFAULT_Y_AXIS_MIN = 0;   // Y轴最小值

// 模拟接口请求函数
const fetchRainCurve = async () => {
    const response = await getRainCurve();
    console.log('降雨量',response.data)
    const result = response.data
    if (result.code == 200) {
      // 处理空数据情况
      if (!result.data || !result.data.ydata || result.data.ydata.length === 0) {
        // 如果没有数据，设置默认空数组
        yAxisData.value = new Array(24).fill(null);
        xAxisData.value = DEFAULT_X_AXIS_DATA;
        warningLines.value = result.data?.alarm || [];
        // 显示"暂无数据"提示
        showNoData.value = true;
      } else {
        yAxisData.value = result.data.ydata
        xAxisData.value = result.data.xdata
        warningLines.value = result.data.alarm
        // 隐藏"暂无数据"提示
        showNoData.value = false;
      }
      
      // 更新图表数据
      updateChartData();
    } else {
      message.error(result.msg)
    }
};

// 启动轮询
const startPolling = () => {
  // 先清除已存在的定时器
  if (pollingTimer) {
    clearInterval(pollingTimer);
  }
  
  // 设置新的轮询定时器
  pollingTimer = window.setInterval(() => {
    fetchRainCurve();
  }, POLLING_INTERVAL);
};

// 停止轮询
const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer);
    pollingTimer = null;
  }
};

// 更新图表数据
const updateChartData = () => {
  if (chartInstance) {
    chartInstance.setOption({
      xAxis: {
        data: xAxisData.value
      },
      yAxis: {
        min: DEFAULT_Y_AXIS_MIN,
        max: DEFAULT_Y_AXIS_MAX
      },
      series: [{
        data: yAxisData.value,
        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',
            }
          }))
        }
      }]
    });
  }
};

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

// 初始化ECharts
const initChart = () => {
  if (!chartRef.value) return;
  chartInstance = echarts.init(chartRef.value);
  
  chartInstance.setOption({
    grid: { left: "3%", right: "4%", bottom: "3%", containLabel: true },
     tooltip: {
    trigger: 'axis'
  },
    xAxis: {
      type: "category",
      data: DEFAULT_X_AXIS_DATA, // 使用默认X轴数据
      axisLine: { lineStyle: { color: "#4f6b95" } },
      axisLabel: { color: "#fff", interval: 2 },
    },
    yAxis: {
      name:'mm',
      nameTextStyle: {
        color: "white",
        padding: [0, 38, 0, 0],
      },
      type: "value",
      min: DEFAULT_Y_AXIS_MIN,   // 设置Y轴最小值
      max: DEFAULT_Y_AXIS_MAX,   // 设置Y轴最大值
      axisLine: { lineStyle: { color: "#4f6b95" } },
      axisLabel: { color: "white"},
      splitLine: { lineStyle: { color: "rgba(79, 107, 149, 0.2)" } },
    },
    
    series: [
      {
        data: new Array(24).fill(null), // 初始为空数据
        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: [] // 初始无警戒线
        }
      },
    ],
  });
};

// 使用防抖优化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();
      
      // 启动轮询
      startPolling();
    });
  });
});

onUnmounted(() => {
  // 清理轮询定时器
  stopPolling();
  
  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%;
    position: relative;
  }
  
  .chart-container {
    width: 100%;
    height: 100%;
  }
  
  .no-data-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    // background-color: rgba(0, 0, 0, 0.3);
    z-index: 10;
    
    .no-data-text {
      font-size: 0.18rem;
      color: #ffffff;
      text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
    }
  }
}
</style>