index.tsx 8.28 KB
import { FC, useState, useRef, useEffect, useMemo } from 'react'
import ReactECharts from 'echarts-for-react'
import cn from '@/utils/classnames'
import s from './chart.module.scss'
type ChartProps = {
  content: any | null
}

const formatValue = (value: number) => {
  if (value >= 100000000) {
    return `${(Math.floor(value / 100000000 * 100) / 100).toFixed(2)}亿`
  }
  if (value >= 1000) {
    return `${(Math.floor(value / 10000 * 100) / 100).toFixed(2)}万`
  }
  return `${value}`
}

const Chart: FC<ChartProps> = ({ content }) => {
  const chartData = content
  if (!chartData || !chartData.chart?.[0]) {
    return null
  }
  if (chartData.is_chart == 'N') return null
  let [data_1, data_2] = chartData.chart
  let { type, metric } = data_1
  let option: any = {}
  let title = ''
  let legendData = [metric]
  if (data_2) legendData = [metric, data_2.metric]
  const chartRef = useRef<any>(null)
  const [visibleItems, setVisibleItems] = useState<Set<string>>(new Set())
  // 存储原始数据
  const originalDataRef = useRef<any[]>([])
  if (type == 'bar' || type == 'line') {
    option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: (params: any) => {
          let result = params[0].axisValue + '<br/>'
          params.forEach((item: any) => {
            result += `${item.marker} ${item.seriesName}: ${formatValue(item.value)}<br/>`
          })
          return result
        }
      },
      grid: {
        left: '20%',
        right: '5%',
        top: '10%',
        bottom: '30%',
      },
      legend: {
        data: legendData,
        bottom: '0%',
        itemWidth: 12,
        itemHeight: 8,
        textStyle: {
          fontSize: 12,
          color: '#133368',
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: type == 'bar',
        data: data_1.name,
        splitLine: {
          show: true,
          lineStyle: {
            color: '#E5E7EB',
            type: 'dashed',
          },
        },
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: (value: number) => {
            if (value >= 10000) {
              return `${(value / 10000).toFixed(2)}w`
            }
            return value.toString()
          },
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#E5E7EB',
            type: 'dashed',
          },
        },
      },
      series: [
        {
          name: metric,
          data: data_1.data || [],
          type,
          barMaxWidth: 20,
          lineStyle: {
            color: '#2C66F7',
            width: 2,
          },
          itemStyle: {
            color: '#2C66F7',
            borderWidth: 2,
            borderColor: '#fff',
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(44, 102, 247, 0.3)' },
                { offset: 1, color: 'rgba(44, 102, 247, 0)' },
              ],
            },
          },
        },
      ],
    }
    if (data_2)
      option.series = [
        ...option.series,
        {
          name: data_2.metric,
          data: data_2.data || [],
          type,
          barMaxWidth: 20,
          lineStyle: {
            color: '#FF8D1A',
            width: 2,
          },
          itemStyle: {
            color: '#FF8D1A',
            borderWidth: 2,
            borderColor: '#fff',
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(255, 141, 26, 0.2)' },
                { offset: 1, color: 'rgba(255, 141, 26, 0)' },
              ],
            },
          },
        },
      ] as any
    title = type == 'bar' ? '柱状图' : '折线图'
  }
  const pieColor = ['#2A82E4', '#00BAAD', '#43CF7C', '#A5D63F', '#FF8D1A', '#FFC300', '#7948EA', '#C6C6C6']
  if (type == 'pie') {
    option = {
      color: pieColor,
      // legend: {
      //   left: '52%',
      //   top: 'center',
      //   orient: 'vertical',
      //   itemWidth: 8,
      //   itemHeight: 8,
      //   textStyle: {
      //     fontSize: 12,
      //     color: '#133368',
      //     overflow: 'truncate',
      //     width: 130,
      //   },
      //   itemGap: 8,
      // },
      series: [
        {
          type: 'pie',
          radius: ['70%', '100%'],
          center: ['50%', '50%'],
          padAngle: 3,
          label: {
            show: false,
            position: 'center',
          },
          labelLine: {
            show: false,
          },
          emphasis: {
            disabled: true,
          },
          data: (() => {
            const dataArray = data_1.data || []
            const nameArray = data_1.name || []

            if (dataArray.length <= 7) {
              return dataArray.map((item: any, index: number) => ({ value: item, name: nameArray[index] }))
            }

            const top7 = dataArray.slice(0, 7).map((item: any, index: number) => ({
              value: item,
              name: nameArray[index],
            }))

            const otherSum = dataArray.slice(7).reduce((sum: number, val: number) => sum + val, 0 as number)

            return [...top7, { value: otherSum, name: '其他' }]
          })(),
        },
      ],
    }
    title = '饼状图'
    // 保存原始数据
    originalDataRef.current = option.series[0].data
  }
  if (!title) return null

  // 初始化可见项状态
  useEffect(() => {
    if (type === 'pie' && visibleItems.size === 0) {
      const allNames = new Set<string>(option.series[0].data.map((item: any) => item.name))
      setVisibleItems(allNames)
    }
  }, [type])

  // 计算当前显示的图表数据
  const currentOption = useMemo(() => {
    if (type !== 'pie') return option
    const updatedData = option.series[0].data.map((item: any) => {
      const original = originalDataRef.current.find((d: any) => d.name === item.name)
      return {
        ...item,
        value: visibleItems.has(item.name) ? original.value : 0
      }
    })
    return {
      ...option,
      series: [{ ...option.series[0], data: updatedData }]
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visibleItems, type, option.series[0]?.data?.length])

  // 切换图例项显示/隐藏
  const handleToggleLegend = (name: string) => {
    setVisibleItems(prev => {
      const next = new Set(prev)
      if (next.has(name)) {
        next.delete(name)
      } else {
        next.add(name)
      }
      return next
    })
  }
  return (
    <div className="chart-container">
      <div className="chart-title">{title}</div>
      <div className={cn('chart-box flex', type == 'pie' && s['chart-box-pie'])}>
        <div className={cn(s['chart-canvas'])}>
          <ReactECharts ref={chartRef} option={currentOption} style={{ height: 240 }} />
        </div>
        {type == 'pie' && option.series[0]?.data && (
          <div className={cn(s['chart-legend'])}>
            {option.series[0].data.map((item: any, index: number) => (
              <div 
                key={item.name} 
                className={cn(s['chart-legend-item'], !visibleItems.has(item.name) && s['chart-legend-item-hidden'])}
                onClick={() => handleToggleLegend(item.name)}
              >
                <div
                  className={cn(s['chart-legend-color'])}
                  style={{ backgroundColor: pieColor[index] }}></div>
                <div className={cn(s['chart-legend-text-box'])}>
                  <span className={cn(s['chart-legend-text'])}>{item.name}</span>
                </div>
                <div className={cn(s['chart-legend-line'])}></div>
                <div className={cn(s['chart-legend-value'])}>{formatValue(item.value)}</div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export default Chart