import { Component, ElementRef, Input, SimpleChanges, ViewChild } from '@angular/core';
import * as echarts from 'echarts';
import { CommonNzModule } from '../../../../../common.nz.module';

const createGradient = (startColor: string, endColor: string) => {
  return new echarts.graphic.LinearGradient(0, 1, 1, 0, [
    {
      offset: 0,
      color: startColor,
    },
    {
      offset: 1,
      color: endColor,
    },
  ]);
};

// const redColor = createGradient('#FF7E75', '#FE6257');
// const blueColor = createGradient('#508FFE', '#1E70FF');
// const whiteColor = createGradient('#D9EFFF', '#B6D2E6');
// const yellowColor = createGradient('#FDD568', '#F7C335');
// const greenColor = createGradient('#53EFCD', '#24D3AC');

@Component({
  selector: 'datav-pie-chart',
  standalone: true,
  imports: [CommonNzModule],
  templateUrl: './pie-chart.component.html',
  styleUrl: './pie-chart.component.less',
})
export class PieChartComponent {
  @ViewChild('dom') chartDom!: ElementRef<HTMLDivElement>;
  @Input() height = 200;
  @Input() title = '';
  @Input() data: { value: number; name: string; colors: [string, string] }[] = [];
  @Input() total = 0;
  @Input() static = false;
  pieChart?: echarts.ECharts;
  ngAfterViewInit() {
    const dom = this.chartDom?.nativeElement;
    if (dom) {
      this.pieChart = echarts.init(dom);
      this.static && this.setOption();
      // this.bindListen(this.pieChart);
    }
  }
  ngOnChanges(changes: SimpleChanges) {
    if (changes['data']) {
      if (this.data.length > 0) {
        this.setOption();
      }
    }
  }
  setOption() {
    const colors = this.data.map(item => item.colors);
    const gradientColors = colors.map(item => createGradient(item[0], item[1]));
    this.pieChart?.setOption({
      tooltip: {
        trigger: 'item',
      },
      legend: {
        show: false,
      },
      color: gradientColors,
      series: [
        {
          type: 'pie',
          // center: ['50%', '50%'],
          radius: ['80%', '95%'],
          avoidLabelOverlap: true,
          padAngle: 2,
          // itemStyle: {
          //   borderRadius: 1,
          //   borderColor: 'transparent',
          //   borderWidth: 1,
          // },
          label: {
            show: false,
            position: 'center',
          },
          labelLine: {
            show: false,
          },
          data: this.data.map(item => ({ value: item.value, name: item.name })),
        },
      ],
    });
  }
}
