import { MUTICHARTCOLORS } from '../../../../common/constant'

const truncateLabel = (value, maxLen = 6) => {
  if (value === null || value === undefined) return ''
  const str = String(value)
  const chars = Array.from(str)
  if (chars.length <= maxLen) return str
  return `${chars.slice(0, maxLen).join('')}...`
}

const getPieChart = (data, colorList, options = {}) => {
  const showCount = options.showCount !== false
  const chartColors = Array.isArray(colorList) && colorList.length ? colorList : MUTICHARTCOLORS
  let option = {
    color: chartColors,
    tooltip: showCount
      ? undefined
      : {
          formatter: params => {
            const percent = typeof params.percent === 'number' ? params.percent : 0
            return `${params.name}: ${percent}%`
          }
        },
    series: [
      {
        type: 'pie',
        radius: [70, 100],
        height: '100%',
        left: 'center',
        width: '100%',
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          alignTo: 'edge',
          formatter: params => {
            const name = truncateLabel(params?.name, 6)
            const value = params?.value ?? 0
            const percent = typeof params?.percent === 'number' ? params.percent : 0
            const labelText = showCount ? `${value} 条 ${percent}%` : `${percent}%`
            return `{name|${name}}\n{time|${labelText}}`
          },
          minMargin: 5,
          edgeDistance: 10,
          lineHeight: 22,
          rich: {
            name: {
              color: 'rgba(59, 65, 75, 1)',
              fontFamily: 'Microsoft YaHei',
              fontSize: 16,
              fontWeight: 'bold',
              padding: [10, 0, 10, 0]
            },
            time: {
              fontSize: 16,
              fontFamily: 'Microsoft YaHei',
              color: '#rgba(95, 101, 108, 1)',
              padding: [10, 0, 10, 0]
            }
          }

        },
        labelLine: {
          length: 15,
          length2: 0,
          maxSurfaceAngle: 88
        },
        labelLayout: function (params) {
          const isLeft = params.labelRect.x < 556 / 2;
          const points = params.labelLinePoints;
          // Update the end point.
          points[2][0] = isLeft
            ? params.labelRect.x
            : params.labelRect.x + params.labelRect.width;
          return {
            labelLinePoints: points
          };
        },
        data: data
      }]
  }
  return option
}

export default getPieChart;