import * as echarts from 'echarts'

interface ChartData {
  xData: string[]
  yData: number[]
}

export class PieChart {
  private chart: echarts.ECharts | null = null
  private dom: HTMLElement
  private xData: string[]
  private yData: number[]
  private currentColors: string[] = ['#0A50FF', '#23CAF4', '#E96F69', '#F2F7F8', '#35C75D', '#35C75D', '#E6FA72']
  private scienceColors: string[] = ['#3071EC', '#41B7FD', '#54D360', '#DAE8F7', '#F6A450', '#EA7261', '#CA68F5'] // 科技风
  private businessColors: string[] = ['#6790EA', '#63C8EA', '#88DE95', '#CFEE5F', '#F3D088', '#F99774', '#F17E7E'] // 商务风
  private simpleColors: string[] = ['#0A50FF', '#23CAF4', '#E96F69', '#F2F7F8', '#35C75D', '#35C75D', '#E6FA72'] // 简约风

  constructor(containerId: string, { xData, yData }: ChartData) {
    this.dom = document.getElementById(containerId)!
    this.xData = xData
    this.yData = yData
    this.initChart()
  }

  private initChart(): void {
    this.chart = echarts.init(this.dom)
    this.setChartOptions()
    window.addEventListener('resize', () => this.chart?.resize())
  }

  private setChartOptions(): void {
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        bottom: '10%',
        left: 'center',
        icon: 'rect',
        itemWidth: 10,
        itemHeight: 5,
        textStyle: {
          color: '#C3CAD9',
          fontSize: 12
        },
        data: this.xData
      },
      series: [
        {
          name: '访问来源',
          type: 'pie',
          radius: ['30%', '50%'], // 设置内外半径，形成环形
          center: ['50%', '50%'],
          color: this.currentColors, // 应用颜色配置
          data: this.xData.map((name, index) => ({
            name,
            value: this.yData[index]
          })),
          label: {
            show: false,
            position: 'center'
          }
          //   labelLine: {
          //     show: false
          //   },
          //   emphasis: {

          //     itemStyle: {
          //       shadowBlur: 10,
          //       shadowOffsetX: 0,
          //       shadowColor: 'rgba(0, 0, 0, 0.5)'
          //     }
          //   }
        }
      ]
    }

    this.chart?.setOption(option)
  }

  /**
   * 更换饼图块颜色样式
   * @param newColors 新颜色数组（需与数据项数量一致）
   */
  changeColorStyle(index: number): void {
    if (!this.chart) {
      console.warn('未读取到元素！')
      return
    }
    if (index === 0) {
      this.currentColors = this.simpleColors
    } else if (index === 1) {
      this.currentColors = this.businessColors
    } else if (index === 2) {
      this.currentColors = this.scienceColors
    }
    // 仅更新颜色配置，避免重新初始化图表
    this.chart.setOption({
      series: [
        {
          color: this.currentColors
        }
      ]
    })
  }

  dispose(): void {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
    window.removeEventListener('resize', () => this.chart?.resize())
  }
}
