import React, { useRef } from 'react';
import { Badge, Flex, Space } from 'antd';
import * as echarts from 'echarts';
import EChartsReact from 'echarts-for-react';
import styles from './index.less';
import CountUp from 'react-countup';
import EmptySpace from '@/components/EmptySpace';
import classNames from 'classnames';
export interface ChartDataItem {
  name: string;
  value: number;
  percentage?: number;
  count?: number;
  unit?: string;
}

export interface ChartWithLegendProps {
  data: ChartDataItem[];
  title?: string;
  colors?: string[];
  chartWidth?: number;
  chartHeight?: number;
  unit?: string;
  showPercentage?: boolean;
  showCount?: boolean;
  isThinLayout?: boolean;
  legendHeight?: number;
  fullCountOfLegend?: number;
  showLabel?: boolean;
  labelFormatter?: string;
  labelFormatterParams?: {};
  isShortLegendItem?: boolean;
}

const ChartWithLegend: React.FC<ChartWithLegendProps> = ({
  data = [],
  title,
  colors = ['rgb(49, 198, 250)', 'rgb(255, 227, 53)', 'rgb(255, 155, 93)', 'rgb(71, 223, 155)', 'rgb(170, 145, 255)', 'rgb(97, 141, 255)'],
  // colors = ['rgb(209, 133, 255)', 'rgb(255, 155, 93)', 'rgb(71, 223, 155)', 'rgb(170, 145, 255)', 'rgb(97, 141, 255)', 'rgb(49, 198, 250)', 'rgb(49, 198, 250)'],
  chartWidth = 200,
  chartHeight = 200,
  unit = '件',
  showPercentage = true,
  showCount = true,
  isThinLayout = false,
  legendHeight = 120,
  fullCountOfLegend = 3,
  showLabel = false,
  labelFormatter = [
    `{b|${15.21}}`,`{a|万辆}`
  ].join('\n'),
  labelFormatterParams = {
    a: {
        fontFamily: '微软雅黑',
        fontSize: 16,
        fontWeight: 400,
        color: '#BCCEE9',
    },
    b: {
        fontFamily: 'D-DIN',
        fontSize: 24,
        fontWeight: 700,
        color: '#FFFFFF',
        lineHeight: 36,
        // padding: [8, 8, 0, 0]
    },
  },
  isShortLegendItem = false,
}) => {
  const chartRef = useRef<EChartsReact>(null);

  const pieOption = {
    color: colors,
    tooltip: {
      borderWidth: '0',
      backgroundColor: 'rgba(73,81,92,.95)',
      textStyle: {
        color: '#fff',
      },
      confine: true,
      formatter: function(params: any) {
        // 自定义 tooltip 格式，确保文本和数值在同一行
        const { name, value, percent } = params;
        const valueText = showCount ? value + unit : '';
        // const percentText = showPercentage ? percent.toFixed(2) + '%' : '';
        // console.log(params);
        
        // return `<div style="max-width: 150px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
        // 可以分行展示，设置最大宽度并使用省略号
        // return `<div style="max-width: 150px; white-space: wrap;">
        //   ${name}: ${valueText} 
        // </div>`;
        // ${name}: ${valueText} ${percentText}

        return `<div style="max-width: 150px; white-space: wrap;">
          <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background-color: ${params.color}; margin-right: 4px;"></span>
          ${name}: ${valueText} 
        </div>`;
        // return `<span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background-color: ${params.color}; margin-right: 4px;"></span>${name}: ${valueText}`;

        // return `<div style="max-width: 150px;">
        //   <div>${name}</div>
        //   <div>${valueText} ${percentText}</div>
        // </div>`;
      }
    },
    series: [
      {
        type: 'pie',
        padAngle: 5,
        radius: ['55%', '78%'],
        label: {
            show: showLabel,
            position: 'center'
        },
        // label: {
        //   show: false,
        // },
        data: data.map(item => ({
          name: item.name,
          value: item.value,
        })),
      },
    ],
    label: {
        formatter: labelFormatter,
        rich: labelFormatterParams,
    }
  };

  const onChartReady = (instance: echarts.ECharts) => {
    instance.resize();
  };

  return (
    <div className={styles.container}>
      {title && <div className={styles.title}>{title}</div>}
      
      <Flex className={styles.content}>
        <div className={classNames(styles.chart, { [styles.chartThin]: isThinLayout, [styles.chartThinShortLegend]: isShortLegendItem && isThinLayout })} style={{ height: legendHeight }}>
          <EChartsReact
            ref={chartRef}
            option={pieOption}
            style={{ height: chartHeight, width: chartWidth }}
            onChartReady={onChartReady}
          />
        </div>

        {/* <div className={styles.legend} style={{ 
          height: legendHeight,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: data.length === 1 ? 'center' : 'flex-start'
        }}> */}
        {/* <div className={styles.legend} style={{ height: 210 }}> */}
        <div className={styles.legend} style={{ height: legendHeight , justifyContent: data.length <= fullCountOfLegend ? 'center' : 'flex-start' }}>
        {/* <div className={styles.legend} style={{ height: legendHeight , display: 'flex', flexDirection: 'column', justifyContent: data.length === 1 ? 'center' : 'flex-start' }}> */}
          {data.map((item, index) => (
            <div key={index} className={classNames(styles.legendItem, { [styles.shortLegendItem]: isShortLegendItem })}>
              <div className={styles.legendItemContent}>
                <Badge color={colors[index % colors.length]} />
                <span className={classNames(styles.name, { [styles.shortName]: isShortLegendItem })}>{item.name}</span>
                
                <div className={styles.valueSection}>
                  {showCount && (
                    <>
                      <span className={classNames(styles.value, { [styles.shortValue]: isShortLegendItem })}>
                        <CountUp
                          end={Number(item.value)}
                          separator=","
                          decimals={0}
                        />
                        {/* {item.value} */}
                      </span>
                      <span className={styles.unit} style={{ marginRight: '18px' }}>{unit}</span>
                    </>
                  )}
                  
                  {showPercentage && (
                    <>
                      <span className={classNames(styles.value, { [styles.shortValue]: isShortLegendItem })}>
                        <CountUp
                          end={Number(item.percentage?.toFixed(2) || ((item.value / data.reduce((acc, curr) => acc + curr.value, 0)) * 100).toFixed(2))}
                          separator=","
                          decimals={2}
                        />
                        {/* {item.percentage?.toFixed(2) || ((item.value / data.reduce((acc, curr) => acc + curr.value, 0)) * 100).toFixed(2)} */}
                      </span>
                      <span className={styles.unit}>%</span>
                    </>
                  )}
                </div>
              </div>
            </div>
          ))}
          {data.length === 0 && (
            <EmptySpace describe="暂无数据" style={{ height: '160px' }} />
          )}
        </div>
      </Flex>
    </div>
  );
};

export default ChartWithLegend; 