import { Component, Prop, Element, Watch, h } from '@stencil/core';
import * as echarts from 'echarts';

@Component({
  tag: 'internal-echarts-renderer',
  styleUrl: 'echarts-renderer.css',
  shadow: true
})
export class InternalEchartsRenderer {
  @Prop() content: any;
  @Prop() width: string = '100%';
  @Prop() height: string = '300px';
  @Prop() theme: string = 'default';
  @Prop() responsive: boolean = true;
  @Prop() showLoading: boolean = true;

  @Element() el: HTMLElement;
  private chart: echarts.ECharts | null = null;
  private resizeHandler: (() => void) | null = null;

  async componentDidLoad() {
    await this.renderChart();
  }

  @Watch('content')
  async contentChanged() {
    await this.renderChart();
  }

  disconnectedCallback() {
    this.disposeChart();
  }

  private async renderChart() {
    if (!this.content) return;

    try {
      // 设置容器样式
      this.el.style.width = this.width;
      this.el.style.height = this.height;

      // 创建图表实例
      this.chart = echarts.init(this.el, this.theme);

      // 显示加载动画
      if (this.showLoading) {
        this.chart.showLoading();
      }

      // 设置配置
      this.chart.setOption(this.content);

      // 隐藏加载动画
      if (this.showLoading) {
        this.chart.hideLoading();
      }

      // 响应式处理
      if (this.responsive) {
        this.resizeHandler = () => {
          if (this.chart) {
            this.chart.resize();
          }
        };
        window.addEventListener('resize', this.resizeHandler);
      }
    } catch (error) {
      console.error('ECharts rendering error:', error);
    }
  }

  private disposeChart() {
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
    if (this.resizeHandler) {
      window.removeEventListener('resize', this.resizeHandler);
      this.resizeHandler = null;
    }
  }

  render() {
    return (
      <div class="echarts-container"></div>
    );
  }
}
