<template>
  <div class="echartsDome">
    <div class="echartsDome_title">{{ title }}</div>
    <div class="echartsDome_chart" ref="chartContainer"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
export default {
  name: "EchartsDome",
  props: {
    title: {
      type: String,
      default: "图表标题",
    },
    chartOption: {
      type: Object,
      default: () => ({}), // 使用函数返回默认对象
    },
  },
  data() {
    return {
      chartInstance: null, // 保存ECharts实例引用
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  watch: {
    chartOption: {
      handler(newVal, oldVal) {
        // 检查是否为有效对象
        if (newVal && typeof newVal === "object") {
          this.updateChart(newVal);
        }
      },
      deep: true,
    },
  },
  methods: {
    initChart() {
      // 如果已存在实例，先销毁
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }
      // 创建新实例
      let chartInstance = echarts.init(this.$refs.chartContainer);
      this.chartInstance = chartInstance;
      // 更新图表配置
      this.updateChart(this.chartOption);
    },
    updateChart(option) {
      // 创建新实例
      // 如果已存在实例，先销毁
      if (this.chartInstance) {
        this.chartInstance.dispose();
      }
      // 创建新实例
      let chartInstance = echarts.init(this.$refs.chartContainer);
      this.chartInstance = chartInstance;
      // 深拷贝配置，避免修改原始props
      const mergedOption = JSON.parse(JSON.stringify(option));
      // 绘制图表
      mergedOption.grid = {
        top: 80,
        left: 10, // 核心1：grid左侧距离容器左侧0px
        right: 50, // 核心2：grid右侧距离容器右侧0px
        bottom: 0,
        containLabel: true, // 关键：防止坐标轴标签超出容器（可选，根据需求添加）
      };
      if (!mergedOption.legend) {
        mergedOption.legend = {};
      }
      Object.assign(mergedOption.legend, {
        textStyle: {
          color: "#F2F3F5", // 字体颜色（支持十六进制、RGB、颜色名）
          fontSize: 14, // 可选：字体大小
          fontWeight: "normal", // 可选：字体粗细
        },
      });

      // 合并tooltip配置
      if (!mergedOption.tooltip) {
        mergedOption.tooltip = {};
      }
      Object.assign(mergedOption.tooltip, {
        backgroundColor: "rgba(0, 25, 50, 0.8)",
        borderColor: "#1E90FF",
        textStyle: {
          color: "#fff",
        },
      });
      chartInstance.setOption(mergedOption, true);
      // 添加resize事件监听
      window.addEventListener("resize", () => {
        chartInstance.resize();
      });
    },
  },
};
</script>

<style scoped>
.echartsDome {
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}
.echartsDome_title {
  font-size: 16px;
}
.echartsDome_chart {
  width: 100%;
  height: calc(100% - 40px);
}
</style>
