<template>
  <div class="chart-container">
    <div v-if="jh" class="well-number-display">
      <span class="well-label">井号:</span>
      <span class="well-number">{{ jh }}</span>
    </div>
    <div class="export-button-container">
      <el-button
        class="export-btn"
        @click="exportChart"
        :disabled="loading || !myChart"
        title="导出图表为图片"
        icon="el-icon-download"
      >
        导出
      </el-button>
    </div>
    <div class="chart-layout">
      <div id="mainzft" class="chart" ref="chartRef"></div>
      <aside v-if="legendItems && legendItems.length" class="strata-legend">
        <div class="legend-header">层位图例</div>
        <div class="legend-list">
          <div
            v-for="(item, index) in legendItems"
            :key="item.name || index"
            class="legend-item"
          >
            <div class="legend-icon" :style="getLegendSwatchStyle(item)"></div>
            <span class="legend-label">{{ item.name || "-" }}</span>
          </div>
        </div>
      </aside>
    </div>
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <span>加载中...</span>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { getZft } from "@/api/optimization/initialization";
import { text } from "d3";

export default {
  name: "HistogramGraph",
  props: {
    jh: {
      type: String,
      default: "",
    },
    // 美化配置选项
    theme: {
      type: String,
      default: "modern", // modern, elegant, vibrant
      validator: (value) => ["modern", "elegant", "vibrant"].includes(value),
    },
  },
  data() {
    return {
      mockData: {},
      legendItems: [],
      myChart: null,
      initRetryCount: 0,
      maxRetryCount: 5,
      resizeObserver: null,
      loading: false,
      debounceTimer: null,
      lastStackedAreas: null,
      lastChartConfig: null,
      lastXAxisLabels: null,
    };
  },
  computed: {
    // 根据主题获取颜色配置
    colorScheme() {
      const schemes = {
        modern: {
          primary: "#3B82F6",
          secondary: "#10B981",
          accent: "#F59E0B",
          background: "#F8FAFC",
          text: "#1F2937",
          border: "#E5E7EB",
          gradient: {
            start: "#3B82F6",
            end: "#1D4ED8",
          },
        },
        elegant: {
          primary: "#6366F1",
          secondary: "#8B5CF6",
          accent: "#EC4899",
          background: "#FAFAFA",
          text: "#374151",
          border: "#D1D5DB",
          gradient: {
            start: "#6366F1",
            end: "#4F46E5",
          },
        },
        vibrant: {
          primary: "#EF4444",
          secondary: "#06B6D4",
          accent: "#F97316",
          background: "#FEFEFE",
          text: "#111827",
          border: "#F3F4F6",
          gradient: {
            start: "#EF4444",
            end: "#DC2626",
          },
        },
      };
      return schemes[this.theme];
    },
    legendPanelWidth() {
      return this.legendItems && this.legendItems.length ? 260 : 0;
    },
  },
  watch: {
    jh: {
      handler(newVal) {
        if (newVal) {
          this.refreshChart();
        }
      },
      immediate: true,
    },
    legendItems: {
      handler() {
        this.$nextTick(() => {
          const chartDom = this.$refs.chartRef;
          if (chartDom) {
            this.setChartDimensions(chartDom);
            this.performResize();
          }
        });
      },
      deep: true,
    },
  },
  mounted() {
    this.initChart();
    this.setupEventListeners();
  },
  beforeDestroy() {
    this.cleanup();
  },
  methods: {
    // 初始化图表
    async initChart() {
      try {
        this.loading = true;

        const chartDom = this.$refs.chartRef;
        if (!chartDom) {
          throw new Error("未找到图表容器 DOM");
        }

        this.setChartDimensions(chartDom);

        // 重试机制优化
        if (this.shouldRetry()) {
          this.scheduleRetry();
          return;
        }

        this.resetRetryCount();
        this.disposeChart();
        this.createChart(chartDom);

        const mockData = await this.getList();
        if (!this.hasValidData(mockData)) {
          this.renderEmpty(chartDom);
          return;
        }

        await this.renderRealData(mockData);
      } catch (error) {
        console.error("图表初始化失败:", error);
        this.handleError(error);
      } finally {
        this.loading = false;
      }
    },

    // 设置图表尺寸
    setChartDimensions(chartDom) {
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      const containerWidth = this.$el?.clientWidth || viewportWidth;
      const rect = this.$el?.getBoundingClientRect();
      const topOffset = rect ? rect.top : 0;
      const legendWidth = this.legendPanelWidth || 0;
      const containerPadding = 20;
      const panelGap = legendWidth ? 5 : 0;
      const safetyMargin = 12;
      const widthPadding =
        containerPadding + panelGap + legendWidth + safetyMargin;
      const availableWidth = Math.max(360, containerWidth - widthPadding);
      const verticalPadding = 40;
      const heightByViewport = viewportHeight - topOffset - verticalPadding;
      const fallbackHeight = this.$el?.clientHeight || viewportHeight;
      const availableHeight = Math.max(
        360,
        heightByViewport,
        fallbackHeight - 20
      );
      chartDom.style.width = `${availableWidth}px`;
      chartDom.style.height = `${availableHeight}px`;
      chartDom.offsetHeight; // 强制重排
    },

    // 检查是否需要重试
    shouldRetry() {
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      const availableHeight = viewportHeight - 120;
      const availableWidth = viewportWidth - 80;
      return (
        (availableWidth <= 0 || availableHeight <= 0) &&
        this.initRetryCount < this.maxRetryCount
      );
    },

    // 安排重试
    scheduleRetry() {
      this.initRetryCount++;
      setTimeout(() => this.initChart(), 500);
    },

    // 重置重试计数
    resetRetryCount() {
      this.initRetryCount = 0;
    },

    // 销毁图表
    disposeChart() {
      if (this.myChart) {
        this.myChart.dispose();
      }
    },

    // 创建图表实例
    createChart(chartDom) {
      this.myChart = echarts.init(chartDom, null, {
        renderer: "canvas",
        useDirtyRect: true,
      });
    },

    // 检查数据有效性
    hasValidData(mockData) {
      return (
        mockData &&
        mockData.wellData &&
        mockData.wellData.depthLine &&
        mockData.wellData.depthLine.length > 0
      );
    },

    // 设置事件监听器
    setupEventListeners() {
      window.addEventListener("resize", this.handleResize);
      this.observeParentResize();
    },

    // 清理资源
    cleanup() {
      window.removeEventListener("resize", this.handleResize);
      if (this.myChart) {
        this.myChart.dispose();
      }
      if (this.resizeObserver) {
        this.resizeObserver.disconnect();
      }
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer);
      }
    },

    // 观察父容器大小变化
    observeParentResize() {
      const parentDom = this.$refs.chartRef?.parentElement;
      if (parentDom && window.ResizeObserver) {
        this.resizeObserver = new ResizeObserver(() => {
          this.debouncedResize();
        });
        this.resizeObserver.observe(parentDom);
      }
    },

    // 获取数据
    async getList() {
      try {
        const res = await getZft({ jhe: this.jh });
        this.mockData = res?.mockData || {};
        const legendList = Array.isArray(res?.tlList)
          ? res.tlList
          : Array.isArray(res?.mockData?.tlList)
          ? res.mockData.tlList
          : [];
        this.legendItems = legendList;
        return this.mockData;
      } catch (error) {
        console.error("获取数据失败:", error);
        throw error;
      }
    },

    // 处理窗口大小变化
    handleResize() {
      this.debouncedResize();
    },

    // 防抖处理resize
    debouncedResize() {
      if (this.debounceTimer) {
        clearTimeout(this.debounceTimer);
      }
      this.debounceTimer = setTimeout(() => {
        this.performResize();
      }, 200);
    },

    // 执行resize操作
    performResize() {
      if (this.myChart) {
        const chartDom = this.$refs.chartRef;
        if (chartDom) {
          this.setChartDimensions(chartDom);
        }
        this.myChart.resize();
        // 重新绘制地层标签，确保在缩放/尺寸变化后位置正确
        if (
          this.lastStackedAreas &&
          this.lastChartConfig &&
          this.lastXAxisLabels
        ) {
          this.drawStratumLabels(
            this.lastStackedAreas,
            this.lastChartConfig,
            this.lastXAxisLabels
          );
        }
      }
    },

    // 刷新图表
    async refreshChart() {
      if (this.myChart) {
        await this.initChart();
      }
    },

    // 渲染真实数据
    async renderRealData(mockData) {
      try {
        const { wellData } = mockData;
        // 调试信息：打印深度区间数据
        if (wellData.depthIntervals && wellData.depthIntervals.length > 0) {
          console.log(
            "深度区间数据:",
            wellData.depthIntervals.map((item) => ({
              型号: item.x,
              尺寸: item.ztcc,
              进尺: item.jc,
              深度区间: item.interval,
              占位: item.placeholder,
              计算高度:
                item.jc !== undefined && item.jc !== null
                  ? item.jc
                  : item.interval - item.placeholder,
            }))
          );
        }
        const xAxisLabels = wellData.depthLine.map((point) => point.x);

        // 优化区域系列处理
        const areaSeries = await this.processAreaSeries(wellData.stackedAreas);

        const option = {
          ...this.getDefaultChartOption(),
          xAxis: this.createXAxis(xAxisLabels),
          yAxis: this.createYAxis(mockData.chartConfig),
          series: this.createSeries(wellData, areaSeries),
        };

        this.myChart.setOption(option, true);

        // 确保图表完全渲染后再resize
        this.$nextTick(() => {
          this.myChart.resize();
          // 存储用于重绘的数据并绘制一次
          this.lastStackedAreas = wellData.stackedAreas;
          this.lastChartConfig = mockData.chartConfig;
          this.lastXAxisLabels = xAxisLabels;
          this.drawStratumLabels(
            this.lastStackedAreas,
            this.lastChartConfig,
            this.lastXAxisLabels
          );
        });
      } catch (error) {
        console.error("渲染数据失败:", error);
        this.handleError(error);
      }
    },

    // 获取默认图表配置
    getDefaultChartOption() {
      const colors = this.colorScheme;
      return {
        title: { text: "", subtext: "" },
        aria: { enabled: false },
        backgroundColor: colors.background,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: { backgroundColor: colors.primary },
            crossStyle: { color: colors.border },
          },
          backgroundColor: "rgba(255,255,255,0.95)",
          borderColor: colors.border,
          borderWidth: 1,
          textStyle: { color: colors.text },
          extraCssText:
            "box-shadow: 0 4px 12px rgba(0,0,0,0.15); border-radius: 8px;",
          formatter: (params) => {
            if (!params || params.length === 0) return "";

            const dataIndex = params[0].dataIndex;
            const depthInterval =
              this.mockData?.wellData?.depthIntervals?.[dataIndex];

            if (!depthInterval) {
              // 如果没有depthInterval数据，使用默认格式
              let result = `<div style="font-weight: 600; margin-bottom: 8px; color: ${colors.primary};">${params[0].axisValue}</div>`;
              params.forEach((param) => {
                const color = param.color;
                result += `<div style="margin: 4px 0;">
                                    <span style="display: inline-block; width: 10px; height: 10px; background-color: ${color}; border-radius: 50%; margin-right: 8px;"></span>
                                    <span style="font-weight: 500;">${param.seriesName}:</span>
                                    <span style="margin-left: 8px; font-weight: 600;">${param.value}</span>
                                </div>`;
              });
              return result;
            }

            // 显示井号信息
            let result = `<div style="font-weight: 600; margin-bottom: 8px; color: ${
              colors.primary
            };">${depthInterval.jh || depthInterval.x}</div>`;

            // 计算深度区间显示
            const startDepth = depthInterval.placeholder || 0;
            const height =
              depthInterval.jc !== undefined && depthInterval.jc !== null
                ? depthInterval.jc
                : depthInterval.interval - depthInterval.placeholder;
            const endDepth = startDepth + height;
            const depthRange = `${startDepth}-${endDepth}`;

            // 显示详细信息
            result += `<div style="margin: 4px 0; padding: 4px 0; border-top: 1px solid ${
              colors.border
            };">
                            <div style="margin: 2px 0;"><span style="font-weight: 500;">型号:</span> <span style="margin-left: 8px; font-weight: 600;">${
                              depthInterval.x || "-"
                            }</span></div>
                            <div style="margin: 2px 0;"><span style="font-weight: 500;">尺寸:</span> <span style="margin-left: 8px; font-weight: 600;">${
                              depthInterval.ztcc || "-"
                            }</span></div>
                            <div style="margin: 2px 0;"><span style="font-weight: 500;">进尺m:</span> <span style="margin-left: 8px; font-weight: 600;">${
                              depthInterval.jc !== undefined &&
                              depthInterval.jc !== null
                                ? depthInterval.jc
                                : depthInterval.interval -
                                  depthInterval.placeholder
                            }</span></div>
                            <div style="margin: 2px 0;"><span style="font-weight: 500;">深度区间:</span> <span style="margin-left: 8px; font-weight: 600;">${depthRange}</span></div>
                        </div>`;

            return result;
          },
        },
        grid: {
          top: 10,
          left: "4%",
          right: "4%",
          bottom: "5%",
          containLabel: true,
          show: false,
        },
        animation: true,
        animationDuration: 1500,
        animationEasing: "cubicOut",
        animationDelay: function (idx) {
          return idx * 100;
        },
      };
    },

    // 处理区域系列
    async processAreaSeries(stackedAreas) {
      return await Promise.all(
        stackedAreas
          .filter((area) => area.svg !== null)
          .map(async (area) => {
            let areaStyle = { opacity: 0.6 };
            if (area.svg) {
              try {
                const svgImage = await this.createSvgImage(area.svg);
                areaStyle.color = { image: svgImage, repeat: "repeat" };
              } catch (error) {
                console.error("SVG转换失败:", error);
              }
            }
            return {
              name: area.name,
              type: "line",
              xAxisIndex: 1,
              z: -1,
              stack: "总量",
              symbol: "none",
              showSymbol: false,
              areaStyle: areaStyle,
              lineStyle: { width: 0 },
              data: area.points.map((point) => point.y),
            };
          })
      );
    },

    // 创建X轴配置
    createXAxis(xAxisLabels) {
      const colors = this.colorScheme;
      return [
        {
          type: "category",
          boundaryGap: true,
          position: "top",
          data: xAxisLabels,
          axisLabel: {
            interval: 0,
            rotate: 0,
            margin: 12,
            align: "center",
            fontSize: 13,
            color: colors.text,
            fontWeight: 500,
          },
          axisTick: {
            alignWithLabel: true,
            length: 6,
            lineStyle: { color: colors.border },
          },
          splitLine: { show: false },
          axisLine: {
            show: true,
            lineStyle: {
              color: colors.border,
              width: 2,
            },
          },
        },
        {
          type: "category",
          boundaryGap: false,
          position: "top",
          show: false,
          data: xAxisLabels,
        },
      ];
    },

    // 创建Y轴配置
    createYAxis(chartConfig) {
      const colors = this.colorScheme;
      return [
        {
          type: "value",
          name: "井深(m)",
          nameTextStyle: {
            color: colors.text,
            fontSize: 13,
            fontWeight: 600,
            padding: [0, 0, 0, 8],
          },
          min: chartConfig.yAxis.min,
          max: chartConfig.yAxis.max,
          interval: chartConfig.yAxis.interval,
          inverse: true,
          axisLabel: {
            formatter: "{value}",
            fontSize: 12,
            color: colors.text,
            fontWeight: 500,
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: colors.border,
              type: "dashed",
              opacity: 0.3,
            },
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: colors.border,
              width: 2,
            },
          },
          axisTick: {
            show: true,
            lineStyle: { color: colors.border },
          },
        },
        {
          type: "value",
          name: "深度(m)",
          nameTextStyle: {
            color: colors.text,
            fontSize: 13,
            fontWeight: 600,
            padding: [0, 8, 0, 0],
          },
          min: chartConfig.yAxis2.min,
          max: chartConfig.yAxis2.max,
          interval: chartConfig.yAxis2.interval,
          position: "right",
          axisLabel: {
            formatter: "{value}",
            fontSize: 12,
            color: colors.text,
            fontWeight: 500,
          },
          splitLine: { show: false },
          axisLine: {
            show: true,
            lineStyle: {
              color: colors.border,
              width: 2,
            },
          },
          axisTick: {
            show: true,
            lineStyle: { color: colors.border },
          },
        },
      ];
    },

    // 创建系列配置
    createSeries(wellData, areaSeries) {
      const colors = this.colorScheme;

      return [
        {
          name: "井深数据",
          type: "line",
          yAxisIndex: 1,
          symbol: "circle",
          symbolSize: 10,
          itemStyle: {
            color: colors.accent,
            borderColor: "#fff",
            borderWidth: 3,
            shadowColor: "rgba(0,0,0,0.2)",
            shadowBlur: 8,
          },
          lineStyle: {
            color: colors.accent,
            width: 3,
            type: "solid",
            shadowColor: "rgba(0,0,0,0.1)",
            shadowBlur: 4,
          },
          label: {
            show: true,
            position: "top",
            formatter: "{c}",
            fontSize: 13,
            fontWeight: 600,
            color: colors.accent,
            backgroundColor: "rgba(255,255,255,0.95)",
            padding: [6, 8],
            borderRadius: 6,
            borderColor: colors.accent,
            borderWidth: 2,
            shadowColor: "rgba(0,0,0,0.1)",
            shadowBlur: 4,
          },
          data: wellData.depthLine.map((point) => point.y),
        },
        {
          name: "占位",
          type: "bar",
          stack: "total",
          silent: true,
          barWidth: "8%",
          itemStyle: {
            borderColor: "transparent",
            color: "transparent",
          },
          emphasis: {
            itemStyle: {
              borderColor: "transparent",
              color: "transparent",
            },
          },
          data: wellData.depthIntervals.map((item) => item.placeholder),
        },
        {
          name: "深度区间",
          type: "bar",
          stack: "total",
          barWidth: "6%",
          label: {
            show: true,
            position: "insideTop",
            color: "#fff",
            fontSize: 11,
            fontWeight: 600,
            backgroundColor: "rgba(0,0,0,0.1)",
            padding: [2, 3],
            borderRadius: 4,
            borderColor: "rgba(255,255,255,0.3)",
            borderWidth: 1,
            formatter: (params) => {
              const di = wellData.depthIntervals[params.dataIndex];
              return di && di.ztcc !== undefined ? di.ztcc : params.data;
            },
          },
          itemStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: colors.gradient.start },
                { offset: 1, color: colors.gradient.end },
              ],
            },
            borderRadius: [4, 4, 0, 0],
            shadowColor: "rgba(0,0,0,0.2)",
            shadowBlur: 8,
            shadowOffsetY: 2,
          },
          emphasis: {
            itemStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: this.adjustColor(colors.gradient.start, 1.2),
                  },
                  {
                    offset: 1,
                    color: this.adjustColor(colors.gradient.end, 1.2),
                  },
                ],
              },
              shadowBlur: 12,
              shadowOffsetY: 4,
            },
          },
          // 使用 jc（进尺）作为柱子的高度，如果没有 jc 则使用 interval - placeholder 计算
          data: wellData.depthIntervals.map((item) => {
            // 优先使用 jc（进尺），如果没有则计算 interval - placeholder
            return item.jc !== undefined && item.jc !== null
              ? item.jc
              : item.interval - item.placeholder;
          }),
        },
        // 底部显示 placeholder 数值的透明条，用于放置底部标签
        {
          name: "深度区间-底部标签",
          type: "bar",
          barGap: "-100%",
          barWidth: "6%",
          itemStyle: { color: "transparent", borderColor: "transparent" },
          emphasis: {
            itemStyle: { color: "transparent", borderColor: "transparent" },
          },
          label: {
            show: true,
            position: "insideBottom",
            color: "#fff",
            fontSize: 11,
            fontWeight: 600,
            backgroundColor: "rgba(0,0,0,0.1)",
            padding: [2, 3],
            borderRadius: 4,
            borderColor: "rgba(255,255,255,0.3)",
            borderWidth: 1,
            distance: 0,
            formatter: (params) => {
              const di = wellData.depthIntervals[params.dataIndex];
              // 显示深度区间，格式为：开始深度-结束深度 或 interval值
              if (di && di.placeholder !== undefined && di.jc !== undefined) {
                const endDepth = di.placeholder + di.jc;
                return `${di.placeholder}-${endDepth}`;
              }
              return di && di.interval !== undefined
                ? di.interval
                : params.data;
            },
          },
          // 使用相同的计算方式，确保标签位置正确
          data: wellData.depthIntervals.map((item) => {
            return item.jc !== undefined && item.jc !== null
              ? item.jc
              : item.interval - item.placeholder;
          }),
        },
        ...areaSeries,
      ];
    },

    // 颜色调整工具方法
    adjustColor(color, factor) {
      if (color.startsWith("#")) {
        const r = parseInt(color.slice(1, 3), 16);
        const g = parseInt(color.slice(3, 5), 16);
        const b = parseInt(color.slice(5, 7), 16);
        const newR = Math.min(255, Math.round(r * factor));
        const newG = Math.min(255, Math.round(g * factor));
        const newB = Math.min(255, Math.round(b * factor));
        return `rgb(${newR}, ${newG}, ${newB})`;
      }
      return color;
    },

    // 渲染空状态
    renderEmpty(chartDom) {
      const colors = this.colorScheme;
      chartDom.innerHTML = `
                <div class="empty-state" style="
                    width: 100%; 
                    height: 100%; 
                    display: flex; 
                    flex-direction: column;
                    align-items: center; 
                    justify-content: center; 
                    color: ${colors.text};
                    font-size: 16px;
                    background: ${colors.background};
                    border-radius: 12px;
                    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
                ">
                    <div style="
                        font-size: 48px; 
                        margin-bottom: 16px; 
                        opacity: 0.6;
                        color: ${colors.primary};
                    ">📊</div>
                    <div style="
                        font-size: 18px; 
                        color: ${colors.text};
                        font-weight: 500;
                    ">暂无数据</div>
                    <div style="
                        font-size: 14px; 
                        color: ${colors.text};
                        opacity: 0.6;
                        margin-top: 8px;
                    ">请检查数据配置</div>
                </div>
            `;
    },

    // 处理错误
    handleError(error) {
      console.error("图表错误:", error);
    },

    // 创建SVG图片
    createSvgImage(svgString) {
      return new Promise((resolve, reject) => {
        const svgBlob = new Blob([svgString], {
          type: "image/svg+xml;charset=utf-8",
        });
        const svgUrl = URL.createObjectURL(svgBlob);
        const img = new Image();
        img.onload = () => {
          URL.revokeObjectURL(svgUrl);
          resolve(img);
        };
        img.onerror = (e) => {
          URL.revokeObjectURL(svgUrl);
          reject(e);
        };
        img.src = svgUrl;
      });
    },
    // 为右侧图例生成纹理样式
    getLegendSwatchStyle(item = {}) {
      const baseStyle = {
        backgroundColor: "#d1d5db",
        backgroundRepeat: "repeat",
        backgroundSize: "36px 36px",
      };
      if (!item?.svg) return baseStyle;
      const dataUrl = this.getSvgDataUrl(item.svg);
      if (!dataUrl) return baseStyle;
      return {
        backgroundImage: `url("${dataUrl}")`,
        backgroundRepeat: "repeat",
        backgroundSize: "36px 36px",
        backgroundColor: "transparent",
      };
    },
    getSvgDataUrl(svgString) {
      if (!svgString || typeof svgString !== "string") return "";
      try {
        const compact = svgString.replace(/\s+/g, " ").trim();
        return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(
          compact
        )}`;
      } catch (e) {
        console.warn("SVG 编码失败:", e);
        return "";
      }
    },

    // 图内层位名称整体去除，仅清理旧元素
    drawStratumLabels() {
      if (!this.myChart) return;
      this.myChart.setOption({ graphic: { elements: [] } });
    },

    exportChart() {
      if (!this.myChart) return;
      const img = this.myChart.getDataURL({
        type: "png",
        pixelRatio: 2,
        backgroundColor: "#fff",
      });
      const a = document.createElement("a");
      a.href = img;
      a.download = this.jh + "直方图.png";
      a.click();
    },
  },
};
</script>

<style scoped>
/* 容器样式优化 */
.chart-container {
  width: 100%;
  min-height: calc(100vh - 140px);
  padding: 0 10px;
  margin: 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: auto;
  animation: fadeIn 0.6s ease-out;
}

.chart-layout {
  display: flex;
  flex: 1;
  width: 100%;
  gap: 5px;
  align-items: stretch;
  justify-content: flex-start;
  overflow: hidden;
}

.strata-legend {
  width: 240px;
  min-width: 240px;
  max-height: 100%;
  padding: 16px;
  border-radius: 16px;
  background: #fff;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(15, 23, 42, 0.06);
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.legend-header {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  border-bottom: 1px solid rgba(15, 23, 42, 0.08);
  padding-bottom: 8px;
}

.legend-list {
  overflow-y: auto;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1px;
  padding-right: 4px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 0 4px;
  border-radius: 8px;
  transition: background 0.2s ease;
}

.legend-item:hover {
  background-color: rgba(59, 130, 246, 0.08);
}

.legend-icon {
  width: 40px;
  height: 24px;
  border-radius: 6px;
  border: 1px solid rgba(15, 23, 42, 0.15);
  background-color: #d1d5db;
  background-size: cover !important;
}

.legend-label {
  flex: 1;
  font-size: 13px;
  font-weight: 500;
  color: #1f2937;
}

/* 井号显示样式 */
.well-number-display {
  position: absolute;
  top: 16px;
  left: 16px;
  z-index: 5;
  background: transparent;
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  transition: all 0.3s ease;
  opacity: 0.9;
}

.well-number-display:hover {
  opacity: 1;
}

.well-label {
  color: #6b7280;
  font-size: 13px;
  font-weight: 500;
  white-space: nowrap;
}

.well-number {
  color: #3b82f6;
  font-size: 14px;
  font-weight: 600;
}

/* 图表容器样式 */
.chart {
  flex: 1;
  width: 100%;
  max-width: 100%;
  height: 100%;
  min-height: 400px;
  display: block;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border: 1px solid rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.chart:hover {
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  /* transform: translateY(-2px); */
}

/* 加载状态样式 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.95);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;
  border-radius: 16px;
  backdrop-filter: blur(10px);
}

.loading-spinner {
  width: 48px;
  height: 48px;
  border: 4px solid #f3f4f6;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 响应式优化 */
@media (max-width: 768px) {
  .chart-container {
    padding: 0 10px;
  }

  .chart {
    min-height: 300px;
    border-radius: 12px;
  }

  .well-number-display {
    top: 8px;
    left: 8px;
    padding: 6px 10px;
  }

  .well-label {
    font-size: 11px;
  }

  .well-number {
    font-size: 12px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .chart {
    /* background: linear-gradient(135deg, #1f2937 0%, #111827 100%); */
    /* box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); */
    border: 1px solid rgba(255, 255, 255, 0.1);
  }

  /*     
    .chart:hover {
        box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);
    } */

  .loading-overlay {
    background: rgba(17, 24, 39, 0.95);
  }

  .well-number-display {
    background: transparent;
  }

  .well-number-display:hover {
    background: transparent;
  }

  .well-label {
    color: #6b7280;
  }

  .well-number {
    color: #3b82f6;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 导出按钮样式 */
.export-button-container {
  position: absolute;
  top: 16px;
  right: 16px;
  z-index: 5;
}

.export-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

.export-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
  transform: translateY(-1px);
}

.export-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(59, 130, 246, 0.3);
}

.export-btn:disabled {
  background: #9ca3af;
  cursor: not-allowed;
  opacity: 0.6;
  box-shadow: none;
}

.export-btn svg {
  width: 16px;
  height: 16px;
  stroke: currentColor;
}
</style>
