import * as echarts from 'echarts'
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 formatLabel = (node, type) => {
  if (type==1) {
    const name = truncateLabel(node.name, 6)
    return `{name|${name}}\n{time|${ node.percent||0}%}`
  }
  return `{name|${node.name}}  {time| ${node.value}项 ${ node.percent||0}%}\n`
}

const createPieChart = (chartDom, data=[], option={}) => {
  if (!chartDom.value) return;

  // 先销毁之前的实例
  const existingChart = echarts.getInstanceByDom(chartDom.value);
  if (existingChart) existingChart.dispose();

  // 获取容器宽度
  const containerWidth = chartDom.value.clientWidth;

  const myChart = echarts.init(chartDom.value);
  myChart.setOption({
    color: MUTICHARTCOLORS,
    tooltip: {
      formatter: node => `${node.name}: ${node.value}项 (${node.percent || 0}%)`,
    },
    series: [
      {
        type: 'pie',
        radius: [70, 100],
        height: '100%',
        width: '100%',
        left: 'center',
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          alignTo: 'edge',
          formatter: (node) => formatLabel(node, option.labelType),
          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: {
              color: 'rgba(95, 101, 108, 1)',
              fontFamily: 'Microsoft YaHei',
              fontSize: 16,
              padding: [10, 0, 10, 0]
            }
          }
        },
        labelLine: {
          length: 15,
          length2: 0,
          maxSurfaceAngle: 88
        },
        labelLayout: function (params) {
          const isLeft = params.labelRect.x < containerWidth / 2;
          const points = params.labelLinePoints;
          
          // 调整引导线终点
          if (isLeft) {
            points[2][0] = params.labelRect.x;  // 左对齐
          } else {
            points[2][0] = params.labelRect.x + params.labelRect.width;  // 右对齐
          }
          
          return { labelLinePoints: points };
        },
        data: data
      }
    ]
  });
  return myChart
}

export default createPieChart;