<template>
  <div ref="chartContainer" class="realtime-chart"></div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts';

export default {
  name: 'RealtimeChart',
  props: {
    data: {
      type: Object,
      required: true,
    },
    options: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props) {
    const chartContainer = ref(null);
    let chartInstance = null;

    const initChart = () => {
      if (chartContainer.value) {
        chartInstance = echarts.init(chartContainer.value);
        updateChart();
      }
    };

    const updateChart = () => {
      if (chartInstance && props.data) {
        const defaultOptions = {
          title: {
            text: '实时产业数据'
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: props.data.xAxis || []
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: props.data.series || [],
            type: 'line',
            smooth: true
          }]
        };

        const finalOptions = Object.assign({}, defaultOptions, props.options);
        chartInstance.setOption(finalOptions);
      }
    };

    const resizeChart = () => {
      if (chartInstance) {
        chartInstance.resize();
      }
    };

    watch(() => props.data, () => {
      updateChart();
    }, { deep: true });

    onMounted(() => {
      initChart();
      window.addEventListener('resize', resizeChart);
    });

    onBeforeUnmount(() => {
      if (chartInstance) {
        chartInstance.dispose();
      }
      window.removeEventListener('resize', resizeChart);
    });

    return {
      chartContainer
    };
  }
};
</script>

<style scoped>
.realtime-chart {
  width: 100%;
  height: 400px;
}
</style>