<template>
    <div ref="chartRef" style="width: 100%; height: 800px;"></div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as echarts from 'echarts';
  
  const chartRef = ref(null);
  let chartInstance = null;
  
  // --- 数据定义 ---
  const indicators = [
    // 目的与动机 (5)
    { name: '享受', max: 50 }, { name: '对齐', max: 50 }, { name: '清晰度', max: 50 }, { name: '支持与协作', max: 50 }, { name: '热情与贡献', max: 50 },
    // 领导力 (5)
    { name: '启发性领导力', max: 50 }, { name: '领导勇气', max: 50 }, { name: '人际领导力', max: 50 }, { name: '协作赋能型领导力', max: 50 }, { name: '愿景与背景', max: 50 },
    // 学习 (5)
    { name: '反思性学习', max: 50 }, { name: '发展导向', max: 50 }, { name: '嵌入式学习', max: 50 }, { name: '学习相关性', max: 50 }, { name: '发展规划', max: 50 },
    // 内部流程及系统与架构 (5)
    { name: '合理资源配置', max: 50 }, { name: '团队决策', max: 50 }, { name: '问责机制', max: 50 }, { name: '系统效能', max: 50 }, { name: '团队效能', max: 50 },
    // 关系 (5)
    { name: '技能与专业知识', max: 50 }, { name: '价值观多样性与包容性', max: 50 }, { name: '尊重与信任', max: 50 }, { name: '安全沟通', max: 50 }, { name: '团队精神与凝聚力', max: 50 },
    // 外部流程及系统与架构 (5)
    { name: '环境意识', max: 50 }, { name: '利益相关者与客户协同', max: 50 }, { name: '人才与资源获取', max: 50 }, { name: '利益相关者与客户沟通', max: 50 }, { name: '关系中的信任与诚信', max: 50 },
  ].reverse();
  
  const categoryData = [
        { name: '目的与动机', color: '#823479',color2: '#5B2454' },
      { name: '领导力', color: '#898989',color2: '#606060' },
      { name: '学习', color: '#AECDF3',color2: '#7A8FAB' },
      { name: '内部流程及系统与架构', color: '#FFD64E',color2: '#B29638' },
      { name: '关系', color: '#193D59',color2: '#112B3E' },
      { name: '外部流程及系统与架构', color: '#009191',color2: '#006464' },
  ];
  const reversedCategoryData = [...categoryData].reverse();
  
  const teamData = [
    {
      name: '团队A',
      value: [42, 38, 45, 30, 35, 48, 32, 25, 40, 33, 22, 38, 41, 36, 29, 45, 31, 39, 27, 43, 25, 47, 33, 46, 28, 37, 44, 26, 49, 34].reverse(),
      lineStyle: { color: '#FDD13A' },
      itemStyle: { color: '#FDD13A' },
      areaStyle: { color: 'rgba(255, 255, 255, 0.5)' },
    },
    {
      name: '团队B',
      value: [35, 45, 33, 42, 28, 30, 41, 46, 29, 38, 48, 27, 39, 43, 31, 36, 47, 25, 40, 32, 44, 26, 49, 34, 37, 22, 41, 30, 45, 38].reverse(),
      lineStyle: { color: '#01949A' },
      itemStyle: { color: '#01949A' },
      areaStyle: { color: 'rgba(255, 255, 255, 0.5)' },
    },
  ];
  
  // --- 辅助函数 ---
  const generateBackgroundSeries = () => {
      const series = [];
      let current = 0;
      reversedCategoryData.forEach((cat) => {
          const data = new Array(indicators.length).fill('-');
          for (let i = 0; i < 5; i++) {
              data[current + i] = 50;
          }
          series.push({
              type: 'bar', 
              coordinateSystem: 'polar', 
              stack: 'background',
              silent: true, data: data,
              barCategoryGap: '0%',
              itemStyle: {
                  color: cat.color2,
                  borderColor: 'transparent',
                  borderWidth: 0
              }
          });
          current += 5;
      });
      return series;
  };
  
  const initChart = () => {
    if (chartRef.value) {
      chartInstance = echarts.init(chartRef.value);
  
      const radarChartRadius = '60%';
      const outerRingRadius = ['60%', '75%'];
      const angleOffset = 360 / (indicators.length * 2);
  
      const baseOption = {
        tooltip: { trigger: 'item' },
        legend: { bottom: 20, data: teamData.map(d => d.name) },
        polar: { center: ['50%', '50%'], radius: radarChartRadius },
        radar: {
          indicator: indicators,
          shape: 'circle',
          center: ['50%', '50%'],
          radius: radarChartRadius,
          startAngle: 90,
          splitNumber: 5,
          axisName: { show: false }, // 隐藏默认的 axisName，我们将使用 graphic 自定义
          splitArea: { show: false },
          axisLine: { lineStyle: { color: 'rgba(0,0,0,0.1)' } },
          splitLine: { lineStyle: { color: 'rgba(0,0,0,0.1)' } },
        },
        angleAxis: {
          type: 'category',
          data: indicators.map(i => i.name),
          boundaryGap: false,
          axisTick: { show: false }, axisLabel: { show: false }, axisLine: { show: false },
        },
        radiusAxis: {
          min: 0, max: 50, interval: 10,
          axisLine: { show: false }, axisTick: { show: false }, axisLabel: { show: false },
          splitLine: { lineStyle: { color: 'rgba(0,0,0,0.1)' } },
        },
        // **优化3: 使用 graphic 组件在中心添加带阴影的白色圆形**
        graphic: {
            elements: [
                {
                    type: 'group',
                    left: 'center',
                    top: 'center',
                    children: [
                        {
                            type: 'circle',
                            shape: { r: 30 }, // 圆形按钮的半径
                            style: {
                                fill: '#FFFFFF',
                                shadowBlur: 20,
                                shadowColor: 'rgba(0, 0, 0, 0.25)',
                                shadowOffsetX: 0,
                                shadowOffsetY: 4
                            },
                            z: 20
                        }
                    ]
                }
            ]
        },
        series: [
          {
            name: '外部环', type: 'pie', 
            radius: outerRingRadius, center: ['50%', '50%'],
            silent: true,
            startAngle: 90 + angleOffset,
            data: reversedCategoryData.map((item, index) => {
              const total = reversedCategoryData.length;
              const anglePerItem = 360 / total;
              const centerAngle = -anglePerItem * index - anglePerItem / 2;
              let rotation = centerAngle+5;
              if (centerAngle < -90 && centerAngle > -270) {
                rotation += 180;
              }
              return {
                value: 1, name: item.name, itemStyle: { color: item.color },
                label: { rotate: rotation }
              };
            }),
            label: {
              show: true, position: 'inside', formatter: '{b}',
              color: '#FFFFFF', fontSize: 14, fontWeight: 'bold',
            },
            labelLine: { show: false },
            itemStyle: { borderWidth: 0 },
            z: 5,
          },
          { name: '能力评估', type: 'radar', data: teamData, symbol: 'circle', symbolSize: 8, z: 10 },
          ...generateBackgroundSeries()
        ],
      };
  
      chartInstance.setOption(baseOption);
  
      // **优化1: 重写指标文字的旋转和对齐逻辑，确保文字始终正向易读**
      const graphicLabels = indicators.map((indicator, index) => {
          // 将文字放在半径为47的位置，比雷达图最大值50略小，比数据区大
          const point = chartInstance.convertToPixel({ polarIndex: 0 }, [22, index]);
          const x = point[0];
          const y = point[1];
  
          const total = indicators.length;
          const angleStep = 360 / total;
          // 计算当前指标的角度, 90度为顶部, 顺时针递减
          const angleInDegrees = 90 - (index * angleStep);
  
          let rotationAngle = angleInDegrees;
          let textAlign = 'left';
          
          // 判断指标在圆的左半部分还是右半部分
          // 左半部分: 角度 > 90 或 < -90
          if (angleInDegrees <= -90 || angleInDegrees >= 90) {
              // 左侧文字，旋转180度使其正向，并设置为右对齐
              rotationAngle = angleInDegrees + 180;
              textAlign = 'right';
          } else if (angleInDegrees === 90 || angleInDegrees === -90) {
              // 顶部或底部文字，居中对齐
              textAlign = 'center';
          }
          // 右侧文字，保持默认左对齐即可
  
          // ECharts 的 rotation 是弧度制，需要转换
          const rotationInRadians = rotationAngle * (Math.PI / 180);
  
          return {
              type: 'text',
              style: {
                  text: indicator.name,
                  font: '10px "Microsoft YaHei"',
                  fill: '#333',
                  align: textAlign, // 根据位置动态设置对齐方式
                  verticalAlign: 'middle',
              },
              x: x, y: y,
              rotation: rotationInRadians, // 应用计算好的旋转角度
              z: 15
          };
      });
  
      // 将计算好的文字元素添加到图表中
      chartInstance.setOption({
          graphic: {
              elements: [
                  ...baseOption.graphic.elements, // 保留中心的圆形按钮
                  ...graphicLabels // 添加指标文字
              ]
          }
      });
    }
  };
  
  const resizeChart = () => {
    // dispose后重建，确保graphic元素能重新计算位置
    chartInstance?.dispose();
    initChart();
  };
  
  onMounted(() => {
    // 使用 Promise.resolve().then() 确保 DOM 已完全渲染
    Promise.resolve().then(() => {
      initChart();
      window.addEventListener('resize', resizeChart);
    });
  });
  
  onUnmounted(() => {
    chartInstance?.dispose();
    window.removeEventListener('resize', resizeChart);
  });
  </script>