  <template>
    <div ref="chartRef" class="chart"></div>
  </template>

  <script lang="ts">
  import {
    defineComponent,
    onMounted,
    ref,
    watch,
    onBeforeUnmount,
    PropType,
  } from "vue";
  import * as echarts from "echarts";

  export default defineComponent({
    props: {
      // ✅ zhudata: [{x, h}]
      zhudata: {
        type: Array as PropType<{ x: number; h: number }[]>,
        default: () => [],
      },
      // ✅ heatmapData: [{Xdata, Ydata, Val}]
      heatmapData: {
        type: Array as PropType<{ Xdata: number; Ydata: number; Val: number }[]>,
        default: () => [],
      },
      visualMapColors: {
        type: Array as PropType<string[]>,
        default: () => ["#00FF00", "#FFFF00", "#FFA500"],
      },
      width: { type: String, default: "100%" },
      height: { type: String, default: "300px" },
    },
    setup(props) {
      const chartRef = ref<HTMLDivElement | null>(null);
      let myChart: echarts.ECharts | null = null;

      function renderChart() {
        if (!chartRef.value) return;
        if (!myChart) myChart = echarts.init(chartRef.value);

        // ✅ 转换数据格式
        const heatmapArray = props.heatmapData.map((d) => [
          d.Xdata,
          d.Ydata,
          d.Val,
        ]);

        // ✅ 所有柱子固定高度为 260px
        const fixedHeight = 180; // 60;
        const zhuArray = props.zhudata.map((d) => [d.x, 0, fixedHeight, 10, d.h]); // [x, y, h(px), w, 原始h]

        // ✅ 横纵坐标分类
        const xCategories = Array.from(
          new Set([
            ...heatmapArray.map((d) => d[0]),
            ...zhuArray.map((d) => d[0]),
          ])
        ).sort((a, b) => a - b);

        const yCategories = Array.from(
          new Set([...heatmapArray.map((d) => d[1]), 0])
        ).sort((a, b) => a - b);

        const option: echarts.EChartsOption = {
          grid: { left: 60, right: 30, top: 20, bottom: 40, containLabel: true },
          graphic: [
            {
              type: "text",
              left: 10,
              top: "center",
              rotation: Math.PI / 2,
              style: { text: "回波影像", font: "16px sans-serif", fill: "#000" },
            },
          ],
          tooltip: {
            trigger: "item",
            formatter: (params) => {
              if (params.seriesType === "custom") {
                const [x, , , , hVal] = params.value as [
                  number,
                  number,
                  number,
                  number,
                  number
                ];
                return `X: ${x}<br/>H: ${hVal}`;
              }
              if (params.seriesType === "heatmap") {
                const [x, y, v] = params.value as [number, number, number];
                return `X: ${x}<br/>Y: ${y}<br/>值: ${v.toFixed(3)}`;
              }
              return "";
            },
          },
          // ✅ heatmap 需要两个 category 轴
          xAxis: {
            type: "category",
            data: xCategories,
          },
          yAxis: {
            type: "category",
            data: yCategories,
          },
          visualMap: {
            show: false,
            min: 0,
            max: 1,
            inRange: { color: props.visualMapColors },
          },
          series: [
            {
              name: "Heatmap",
              type: "heatmap",
              data: heatmapArray,
              emphasis: { itemStyle: { borderColor: "#333", borderWidth: 1 } },
              
              progressive: 1000,
              animation: false,
            },
            {
              name: "固定高度柱",
              type: "custom",
              renderItem: (params, api) => {
                const x = api.value(0);
                const y = api.value(1);
                const h = api.value(2);
                const w = api.value(3);
                const hVal = api.value(4);

                const coord = api.coord([x, y]);
                const xPixel = coord[0];

                // ✅ 获取整个绘图区域的像素范围
                const coordSys = params.coordSys as any;

                // ✅ 直接用底部像素位置（绘图区最下边）
                const baseY = coordSys.y + coordSys.height;
                const topY = baseY - h; // 固定高度往上绘制

                return {
                  type: "group",
                  children: [
                    // ✅ 柱子矩形（固定高度）
                    {
                      type: "rect",
                      shape: {
                        x: xPixel - w / 2,
                        y: topY,
                        width: w,
                        height: h,
                      },
                      style: {
                        fill: "rgba(255, 0, 0, 0.3)",
                        stroke: "#FF0000",
                        lineWidth: 2,
                      },
                    },
                    // ✅ 柱子顶部显示 H 值
                    {
                      type: "text",
                      style: {
                        text: `${hVal}`,
                        fill: "#000",
                        font: "12px sans-serif",
                        align: "center",
                        verticalAlign: "bottom",
                      },
                      position: [xPixel, topY - 5],
                    },
                  ],
                };
              },

              data: zhuArray,
              z: 10,
            },
          ],
        };

        myChart.setOption(option);
        myChart.resize();
      }

      onMounted(() => {
        renderChart();
        window.addEventListener("resize", renderChart);
      });

      watch(
        () => [props.visualMapColors, props.zhudata, props.heatmapData],
        () => renderChart(),
        { deep: true }
      );

      onBeforeUnmount(() => {
        window.removeEventListener("resize", renderChart);
        myChart?.dispose();
        myChart = null;
      });

      return { chartRef };
    },
  });
  </script>

  <style>
  .chart {
    width: 100%;
    height: 300px;
  }
  </style>
