import * as echarts from 'echarts'
import { MUTICHARTCOLORS } from '@/common/constant'

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) => `{name|${node.name}}\n{time|${node.value}项 ${ node.percent||0}%}`,
          minMargin: 5,
          edgeDistance: 10,
          lineHeight: 26,
          rich: {
            name: {
              color: 'rgba(59, 65, 75, 1)',
              fontFamily: 'Source Han Sans CN',
              fontSize: 16,
              fontWeight: 'bold',
              padding: [10, 0, 10, 0]
            },
            time: {
              color: 'rgba(95, 101, 108, 1)',
              fontFamily: 'Source Han Sans CN',
              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;