import { MUTICHARTCOLORS } from "@/common/constant.js";

const getPieChart = (data) => {
  const seriesData = (Array.isArray(data) ? data : []).map((d, index) => {
    const color = d?.color || MUTICHARTCOLORS[index % MUTICHARTCOLORS.length]
    return {
      ...d,
      itemStyle: { ...(d?.itemStyle || {}), color },
      // “飞线”（labelLine）跟随领域色
      labelLine: {
        ...(d?.labelLine || {}),
        lineStyle: { ...(d?.labelLine?.lineStyle || {}), color }
      }
    }
  })

  let option = {
    series: [
      {
        type: 'pie',
        // grid: {
        //   top: '15%',
        //   right: '15%',
        //   bottom: '5%',
        //   left: '15%',
        //   containLabel: true
        // },
        // 使用百分比半径，避免固定像素导致饼图“看起来没铺满容器”
        radius: ['45%', '60%'],
        height: '100%',
        left: 'center',
        width: '100%',
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          alignTo: 'edge',
 formatter: params => {
  const name = params.name || "";
  const value = Number(params.value ?? 0) || 0;
  const rawPercent =
    params?.data?.percent != null
      ? params.data.percent
      : params.percent;
  const percent = rawPercent != null ? Number(rawPercent).toFixed(2) : "0.00";

  // 第二行：数值 + 百分比（同一行、同一文字样式），保持与旧版一致的两行结构
  return `{name|${name}}\n{time|${value}项  ${percent}%}`;
},
          minMargin: 5,
          edgeDistance: 10,
          lineHeight: 20,
          rich: {
            name: {
              fontSize: 16,
              color: 'rgba(59, 65, 75, 1)',
              fontFamily: 'Microsoft YaHei',
              fontWeight: 700
            },
            time: {
              fontSize: 16,
              color: 'rgba(95, 101, 108, 1)',
              fontFamily: 'Microsoft YaHei',
            }
          }
        },
        labelLine: {
          length: 15,
          length2: 0,
          maxSurfaceAngle: 80
        },
        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: seriesData
      }]
  }
  return option
}

export default getPieChart;