<template>
  <uni-collapse>
    <eikon-collapse-item title="协同配合" name="collaboration" :borderColor="'#2C80FF'">
      <div class="collapse-content">
        <!-- isPersonal为false时显示原有内容 -->
        <div v-if="!isPersonal">
          <!-- 团队配合 -->
          <div class="content-item" v-if="teamData && teamData.length > 0">
            <div class="item-label">团队配合</div>
          </div>


          <statistic-table v-if="teamData && teamData.length > 0" :columns="teamColumns" :data="teamData" />


          <!-- 性格特征 -->
          <div class="content-item" style="margin-top: 30rpx;">
            <div class="item-label">性格特征</div>
          </div>

          <!-- 圆形布局 -->
          <div class="scatter-chart">
            <canvas ref="characterCanvas" class="character-canvas"></canvas>
          </div>

          <!-- 工作风格 -->
          <div class="content-item">
            <div class="item-label">工作风格</div>
          </div>
          <!-- 饼图 -->
          <div class="pie-chart">
            <div ref="workStylePieChart" class="chart-container"></div>
          </div>


          <!-- 性别分布 - 左右布局 -->
          <div class="content-item" style="margin-bottom: 0;">
            <div class="item-label">性别</div>
            <div class="item-value"> <h-legend :legend-data="genderData" :colorSize="20" :textSize="24" /></div>
          </div>
          <div class="content-item" style="margin-bottom: 30rpx;">
            <h-line :data="genderData" :total="genderData.reduce((acc, cur) => acc + cur.value, 0)" :itemWidth="300"
              :lineHeight="'40'" />
          </div>

          <!-- <div class="content-item">
            <div class="item-label">生肖</div>
          </div> -->

          <!-- 生肖统计表格 -->
          <!-- <statistic-table :columns="zodiacColumns" :data="zodiacData" /> -->



          <!-- 血型分布 - 左右布局 -->
          <!-- <div class="content-item" style="margin-bottom: 0;margin-top: 30rpx;">
            <div class="item-label">血型</div>
            <div class="item-value"> <h-legend :legend-data="bloodTypeData" :colorSize="20" :textSize="24" />
            </div>
          </div> -->

          <!-- 
          <div class="content-item" style="margin-bottom: 30rpx;">
            <h-line :data="bloodTypeData" :total="bloodTypeData.reduce((acc, cur) => acc + cur.value, 0)"
              :itemWidth="300" :lineHeight="'40'" />
          </div> -->

          <!-- <div class="content-item">
            <div class="item-label">星座</div>
          </div> -->


          <!-- 星座统计表格 -->
          <!-- <statistic-table :columns="constellationColumns" :data="constellationData" /> -->






        </div>

        <!-- isPersonal为true时显示左右布局的六个部分 -->
        <div v-else class="personal-layout">
          <!-- 团队配合 -->
          <div class="content-item">
            <div class="item-label">团队配合</div>
            <div class="item-value">{{(localCollaborationData.teamCooperationList
              && localCollaborationData.teamCooperationList.length > 0) &&
              localCollaborationData.teamCooperationList.map(item => item.nickName).join('、')}}</div>
          </div>

          <!-- 性格特征 -->
          <div class="content-item">
            <div class="item-label">性格特征</div>
            <div class="item-value">{{ localCollaborationData.characterCharacteristics }}</div>
          </div>
          <!-- 工作风格 -->
          <div class="content-item">
            <div class="item-label">工作风格</div>
            <div class="item-value">{{ localCollaborationData.workingStyle }}</div>
          </div>
          <!-- 性别 -->
          <div class="content-item">
            <div class="item-label">性别</div>
            <div class="item-value">{{ localCollaborationData.sex }}</div>
          </div>



          <!-- 生肖 -->
          <!-- <div class="content-item">
            <div class="item-label">生肖</div>
            <div class="item-value">{{ localCollaborationData.zodiac }}</div>
          </div> -->

          <!-- 星座 -->
          <!-- <div class="content-item">
            <div class="item-label">星座</div>
            <div class="item-value">{{ localCollaborationData.constellation }}</div>
          </div> -->





        </div>
      </div>
    </eikon-collapse-item>
  </uni-collapse>
</template>

<script>
import EikonCollapseItem from "./eikon-collapse-item.vue";
import HLegend from "@/components/h-legend/h-legend.vue";
import HLine from "@/components/h-line/h-line.vue";
import StatisticTable from "@/components/statistic-table/statistic-table.vue";
import * as echarts from 'echarts';
import { mapGetters, mapState } from 'vuex'
import { getDictLabelByValue } from "@/utils/common"
import useDictMixin from '@/utils/dict'
export default {
  name: "Collaboration",
  components: {
    EikonCollapseItem,
    HLegend,
    HLine,
    StatisticTable
  },
  mixins: [useDictMixin],
  computed: {
    ...mapState('eikonLevel', ['collaborationData']),
    ...mapGetters('eikonLevel', ['isPersonal'])
  },
  data() {
    return {
      localCollaborationData: {},
      // 性别分布数据
      genderData: [],
      bloodTypeData: [],
      // 生肖统计表格数据
      zodiacColumns: [
        { props: 'zodiac', title: '生肖' },
        { props: 'count', title: '人数' }
      ],
      zodiacData: [],
      // 星座统计表格数据
      constellationColumns: [
        { props: 'constellation', title: '星座' },
        { props: 'count', title: '人数' }
      ],
      constellationData: [],
      // 团队配合统计表格数据
      teamColumns: [
        { props: 'name', title: '姓名' },
        { props: 'collaborator', title: '最佳配合人员' },
      ],
      teamData: [],
      // 性格特征圆形数据
      characterCircles: []
    }
  },

  watch: {
    collaborationData(newVal, oldVal) {
      if (newVal) {

        if (this.isPersonal) {
          this.handlePersonalData(newVal)
        } else {
          this.handleDeptData(newVal)
        }
      }
    }
  },
  mounted() {
    // 添加窗口大小变化监听器，用于重绘canvas
    this.handleResize = () => {
      if (this.characterCircles && this.characterCircles.length > 0) {
        this.drawCharacterCircles(this.characterCircles);
      }
    };

    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 移除监听器
    if (this.handleResize) {
      window.removeEventListener('resize', this.handleResize);
    }
  },
  methods: {
    async handleDeptData(newVal) {
      const { teamCooperationList, sexList, constellationList, blooGroupList, zodiacList, characterCharacteristicsList, workingStyleList } = newVal;

      // 获取生肖字典
      const dict = await this.useDict('sys_user_zodiac');
      const zodiacDict = dict['sys_user_zodiac'] || [];

      this.genderData = sexList.map(item => ({
        name: item.name,
        value: item.count,
        color: item.name === '男' ? '#7AA3F5' : '#B68FF7'
      }))
      this.constellationData = constellationList.map(item => ({
        constellation: item.name,
        count: item.count,
      }))
      this.bloodTypeData = blooGroupList.map(item => ({
        name: item.name,
        value: item.count,
        color: item.name === 'A型' ? '#B68FF7' : item.name === 'B型' ? '#FFB30F' : item.name === 'O型' ? '#7AA3F5' : '#FA5238'
      }))
      this.initWorkStylePieChart(workingStyleList.map(item => ({
        value: item.count,
        name: item.name
      })));

      // 处理性格特征圆形数据
      this.handleCharacterCircles(characterCharacteristicsList || []);

      // 处理生肖数据，将name转换为中文
      if (zodiacList && Array.isArray(zodiacList)) {
        this.zodiacData = zodiacList.map(item => {
          // 在字典中查找对应的中文名称
          const dictItem = zodiacDict.find(d => d.value === item.name);
          return {
            zodiac: dictItem ? dictItem.label : item.name,
            count: item.count
          };
        });
      } else {
        this.zodiacData = [];
      }
      // 添加空值检查
      if (!teamCooperationList || !Array.isArray(teamCooperationList)) {
        this.teamData = [];
        return;
      }

      this.teamData = teamCooperationList.map(item => {
        // 检查item和teamCooperationList是否存在
        if (!item || !item.teamCooperationList || !Array.isArray(item.teamCooperationList)) {
          return {
            name: item?.nickName || '未知',
            collaborator: '无'
          };
        }

        return {
          name: item.nickName || '未知',
          collaborator: item.teamCooperationList.map(team => team.nickName).join(',') || '无'
        };
      });

      console.log(this.teamData, "this.teamData");
    },
    async handlePersonalData(newVal) {
      const res = { ...newVal };

      res.sex = await getDictLabelByValue('sys_user_sex', newVal && newVal.sex)
      res.zodiac = await getDictLabelByValue('sys_user_zodiac', newVal && newVal.zodiac)
      res.constellation = await getDictLabelByValue('sys_user_constellation', newVal && newVal.constellation)
      res.characterCharacteristics = await getDictLabelByValue('sys_user_character_characteristics', newVal && newVal.characterCharacteristics)
      res.workingStyle = await getDictLabelByValue('sys_user_working_style', newVal && newVal.workingStyle)

      this.localCollaborationData = res
    },

    // 处理性格特征圆形数据 - 使用canvas绘制
    handleCharacterCircles(characterCharacteristicsList) {
      if (!characterCharacteristicsList || characterCharacteristicsList.length === 0) {
        this.characterCircles = [];
        this.drawCharacterCircles([]);
        return;
      }

      // 计算圆形布局
      const circles = this.generateCircleLayout(characterCharacteristicsList);
      this.characterCircles = circles;

      // 使用canvas绘制圆形
      this.$nextTick(() => {
        this.drawCharacterCircles(circles);
      });
    },

    // 生成圆形布局算法 - 使用力导向布局确保不重叠
    generateCircleLayout(data) {
      if (!data || data.length === 0) return [];

      // 获取容器尺寸
      const container = document.querySelector('.scatter-chart');
      if (!container) return [];

      const containerWidth = container.clientWidth || 400;
      const containerHeight = container.clientHeight || 300;
      const centerX = containerWidth / 2;
      const centerY = containerHeight / 2;
      const maxRadius = Math.min(containerWidth, containerHeight) / 2.5; // 增加可用空间

      // 计算总人数
      const totalCount = data.reduce((sum, item) => sum + (item.count || 0), 0);
      if (totalCount === 0) return [];

      // 按人数排序
      const sortedData = [...data].sort((a, b) => (b.count || 0) - (a.count || 0));

      const circles = [];
      const goldenAngle = Math.PI * (3 - Math.sqrt(5)); // 黄金角度

      // 初始化圆形位置（使用黄金角度分布）
      for (let i = 0; i < sortedData.length; i++) {
        const item = sortedData[i];
        const count = item.count || 0;

        // 计算半径（基于人数比例）- 增加最小半径确保文字完全展示
        const radiusRatio = count / totalCount;
        const baseRadius = Math.max(35, Math.min(80, 35 + (radiusRatio * 50)));
        const circleRadius = baseRadius;

        // 根据性格特征类型生成颜色
        const color = this.generateCharacterColor(item.code);

        // 计算初始位置（使用黄金角度分布）
        let angle = i * goldenAngle;
        let distance = Math.min(0.8, 0.15 + i * 0.1) * maxRadius;
        let x = centerX + distance * Math.cos(angle);
        let y = centerY + distance * Math.sin(angle);

        // 确保初始位置在边界内
        x = Math.max(circleRadius + 5, Math.min(containerWidth - circleRadius - 5, x));
        y = Math.max(circleRadius + 5, Math.min(containerHeight - circleRadius - 5, y));

        circles.push({
          name: item.name || '未知',
          count: count,
          code: item.code || '', // 添加code属性
          x: x,
          y: y,
          radius: circleRadius,
          vx: 0, // x方向速度
          vy: 0,  // y方向速度
          color: color // 添加颜色属性
        });
      }

      // 力导向布局迭代（500次最大迭代）
      const maxIterations = 500;
      const extraSpacing = 20; // 额外间距增加到20px
      const repulsionForce = 30; // 排斥力大小
      const boundaryForce = 10; // 边界排斥力
      const damping = 0.95; // 阻尼因子，避免震荡

      for (let iteration = 0; iteration < maxIterations; iteration++) {
        let hasOverlap = false;

        // 计算每个圆形之间的排斥力
        for (let i = 0; i < circles.length; i++) {
          const circleA = circles[i];
          circleA.vx = 0;
          circleA.vy = 0;

          // 与其他圆形的排斥力
          for (let j = 0; j < circles.length; j++) {
            if (i === j) continue;

            const circleB = circles[j];
            const dx = circleA.x - circleB.x;
            const dy = circleA.y - circleB.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            const minDistance = circleA.radius + circleB.radius + extraSpacing;

            if (distance < minDistance) {
              hasOverlap = true;
              // 计算排斥力（与距离成反比）
              const force = repulsionForce * (minDistance - distance) / distance;
              circleA.vx += force * dx / distance;
              circleA.vy += force * dy / distance;
            }
          }

          // 边界排斥力
          const leftBoundary = circleA.radius + 5;
          const rightBoundary = containerWidth - circleA.radius - 5;
          const topBoundary = circleA.radius + 5;
          const bottomBoundary = containerHeight - circleA.radius - 5;

          if (circleA.x < leftBoundary) {
            circleA.vx += boundaryForce * (leftBoundary - circleA.x);
          } else if (circleA.x > rightBoundary) {
            circleA.vx += boundaryForce * (rightBoundary - circleA.x);
          }

          if (circleA.y < topBoundary) {
            circleA.vy += boundaryForce * (topBoundary - circleA.y);
          } else if (circleA.y > bottomBoundary) {
            circleA.vy += boundaryForce * (bottomBoundary - circleA.y);
          }
        }

        // 应用速度和位置更新
        for (let i = 0; i < circles.length; i++) {
          const circle = circles[i];

          // 应用阻尼
          circle.vx *= damping;
          circle.vy *= damping;

          // 更新位置
          circle.x += circle.vx;
          circle.y += circle.vy;

          // 确保位置在边界内
          circle.x = Math.max(circle.radius + 5, Math.min(containerWidth - circle.radius - 5, circle.x));
          circle.y = Math.max(circle.radius + 5, Math.min(containerHeight - circle.radius - 5, circle.y));
        }

        // 如果没有重叠，提前结束迭代
        if (!hasOverlap && iteration > 100) {
          break;
        }
      }

      // 最终检查并处理任何剩余的重叠（使用网格布局作为备用）
      const gridSize = Math.ceil(Math.sqrt(circles.length));
      const cellWidth = containerWidth / (gridSize + 1);
      const cellHeight = containerHeight / (gridSize + 1);

      for (let i = 0; i < circles.length; i++) {
        const circle = circles[i];

        // 检查是否还有重叠
        let hasOverlap = false;
        for (let j = 0; j < circles.length; j++) {
          if (i === j) continue;

          const otherCircle = circles[j];
          const dx = circle.x - otherCircle.x;
          const dy = circle.y - otherCircle.y;
          const distance = Math.sqrt(dx * dx + dy * dy);

          if (distance < circle.radius + otherCircle.radius + 5) {
            hasOverlap = true;
            break;
          }
        }

        // 如果仍有重叠，使用网格布局
        if (hasOverlap) {
          const row = Math.floor(i / gridSize);
          const col = i % gridSize;
          circle.x = (col + 1) * cellWidth;
          circle.y = (row + 1) * cellHeight;
        }

        // 计算字体大小 - 使用固定字体大小，不随圆形大小变化
        const fontSize = 14;

        // 转换为最终格式
        circles[i] = {
          name: circle.name,
          count: circle.count,
          code: circle.code, // 保留code属性
          left: (circle.x / containerWidth) * 100,
          top: (circle.y / containerHeight) * 100,
          size: circle.radius * 2,
          fontSize: fontSize,
          color: circle.color // 保留颜色属性
        };
      }

      return circles;
    },

    // 创建canvas元素的方法
    createCanvasElement() {
      // 创建新的canvas元素
      const newCanvas = document.createElement('canvas');
      newCanvas.className = 'character-canvas';
      newCanvas.style.width = '100%';
      newCanvas.style.height = '100%';

      // 查找容器
      const container = document.querySelector('.scatter-chart');
      if (!container) {
        console.warn('无法找到canvas容器');
        return null;
      }

      // 清空容器并添加新的canvas
      container.innerHTML = '';
      container.appendChild(newCanvas);

      // 更新ref引用
      this.$refs.characterCanvas = newCanvas;

      // 检查新的canvas是否支持getContext
      if (newCanvas.getContext && typeof newCanvas.getContext === 'function') {
        console.log('新的canvas元素创建成功，支持getContext方法');
        return newCanvas;
      } else {
        console.warn('新的canvas元素仍然不支持getContext方法');
        return null;
      }
    },

    initWorkStylePieChart(data) {
      const chartDom = this.$refs.workStylePieChart;
      if (!chartDom) return;

      const chart = echarts.init(chartDom);
      const option = {

        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: '工作风格',
          type: 'pie',
          radius: '40%',
          avoidLabelOverlap: false,
          label: {
            show: true,
            formatter: function (params) {
              // 支持折行显示，将名称和百分比分开显示
              return '{b|' + params.name + '}\n{d|' + params.percent + '%}';
            },
            rich: {
              b: {
                fontSize: 12,
                lineHeight: 16,
                align: 'center'
              },
              d: {
                fontSize: 14,
                fontWeight: 'bold',
                color: '#333',
                lineHeight: 16,
                align: 'center'
              }
            }
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: true
          },
          data: data
        }]
      };

      chart.setOption(option);

      // 响应式调整
      window.addEventListener('resize', () => {
        chart.resize();
      });
    },

    // 根据性格特征类型生成颜色
    generateCharacterColor(code) {
      // 外向型(E)使用橙色#FF8000，内向型(I)使用蓝色#4371FF
      if (code && code.startsWith('E')) {
        return '#FF8000'; // 外向型 - 橙色
      } else if (code && code.startsWith('I')) {
        return '#4371FF'; // 内向型 - 蓝色
      } else {
        // 默认颜色（如果code为空或不匹配）
        return '#999999'; // 灰色
      }
    },

    // 使用canvas绘制性格特征圆形
    drawCharacterCircles(circles) {
      // 检查数据是否有效
      if (!circles || circles.length === 0) {
        console.warn('圆形数据为空，清空画布', { circlesLength: circles ? circles.length : 0 });

        // 清空画布
        this.clearCharacterCanvas();
        return;
      }

      // 确保canvas元素存在且是有效的DOM元素
      let canvas = this.$refs.characterCanvas;

      // 如果通过ref获取失败，尝试通过选择器获取（兼容移动端环境）
      if (!canvas || typeof canvas !== 'object') {
        canvas = document.querySelector('.character-canvas');
      }

      // 检查canvas元素是否有效
      if (!canvas || typeof canvas !== 'object') {
        console.warn('Canvas元素不存在或类型不正确，尝试创建新的canvas元素', {
          canvasExists: !!canvas,
          canvasType: typeof canvas
        });

        // 创建新的canvas元素
        canvas = this.createCanvasElement();
        if (!canvas) {
          console.warn('无法创建canvas元素，跳过绘制');
          return;
        }
      }

      // 检查canvas是否支持2D上下文（移动端兼容性处理）
      if (!canvas.getContext || typeof canvas.getContext !== 'function') {
        console.warn('Canvas不支持getContext方法，尝试创建新的canvas元素', {
          hasGetContext: !!canvas.getContext,
          getContextType: typeof canvas.getContext
        });

        // 创建新的canvas元素
        canvas = this.createCanvasElement();
        if (!canvas) {
          console.warn('无法创建canvas元素，跳过绘制');
          return;
        }
      }

      try {
        // 获取canvas上下文
        const ctx = canvas.getContext('2d');

        // 设置canvas尺寸，确保圆形是正圆
        const container = canvas.parentElement;
        if (container) {
          // 获取容器尺寸
          const containerWidth = container.clientWidth;
          const containerHeight = container.clientHeight;

          // 设置设备像素比，提高canvas分辨率以解决文字模糊问题
          const devicePixelRatio = window.devicePixelRatio || 1;

          // 设置canvas的实际尺寸（考虑设备像素比）
          canvas.width = containerWidth * devicePixelRatio;
          canvas.height = containerHeight * devicePixelRatio;

          // 设置canvas的CSS尺寸为容器尺寸
          canvas.style.width = containerWidth + 'px';
          canvas.style.height = containerHeight + 'px';

          // 缩放上下文以匹配设备像素比
          ctx.scale(devicePixelRatio, devicePixelRatio);
        }

        const width = container ? container.clientWidth : canvas.width;
        const height = container ? container.clientHeight : canvas.height;

        // 清除画布
        ctx.clearRect(0, 0, width, height);

        // 设置字体渲染质量
        ctx.imageSmoothingEnabled = true;
        ctx.imageSmoothingQuality = 'high';

        // 绘制每个圆形
        circles.forEach(circle => {
          // 计算canvas中的位置（将百分比转换为像素）
          const x = (circle.left / 100) * width;
          const y = (circle.top / 100) * height;
          const radius = circle.size / 2;

          // 绘制圆形背景
          ctx.beginPath();
          ctx.arc(x, y, radius, 0, Math.PI * 2);

          // 使用圆形对象中的颜色属性
          ctx.fillStyle = circle.color + 'B8'; // B8表示72%透明度
          ctx.fill();

          // 添加边框
          ctx.strokeStyle = 'rgba(255, 255, 255, 0.8)';
          ctx.lineWidth = 2;
          ctx.stroke();

          // 设置文字样式
          ctx.fillStyle = 'white';
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';

          // 优化字体渲染质量
          ctx.fontKerning = 'normal';
          ctx.textRendering = 'geometricPrecision';

          // 分三行显示：第一行显示前四个字符，第二行显示剩余字符，第三行显示人数
          const namePart1 = circle.name.substring(0, 4); // 前四个字符
          const namePart2 = circle.name.substring(4);   // 剩余字符
          const countText = `${circle.count}人`;

          // 设置字体大小 - 根据圆形大小自适应（放大字号）
          const baseFontSize = Math.min(circle.fontSize, radius * 0.7);
          const nameFontSize = baseFontSize;
          const countFontSize = baseFontSize * 0.8;

          // 设置字体
          ctx.font = `bold ${nameFontSize}px -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif`;

          // 测量各段文字宽度
          const part1Metrics = ctx.measureText(namePart1);
          const part2Metrics = ctx.measureText(namePart2);
          const countMetrics = ctx.measureText(countText);

          // 检查文字宽度是否超出圆形直径的80%
          const maxWidth = radius * 1.6;
          let actualNameFontSize = nameFontSize;
          let actualCountFontSize = countFontSize;

          if (part1Metrics.width > maxWidth || part2Metrics.width > maxWidth) {
            actualNameFontSize = nameFontSize * (maxWidth / Math.max(part1Metrics.width, part2Metrics.width));
          }

          if (countMetrics.width > maxWidth) {
            actualCountFontSize = countFontSize * (maxWidth / countMetrics.width);
          }

          // 确保最小字体大小
          actualNameFontSize = Math.max(8, actualNameFontSize);
          actualCountFontSize = Math.max(6, actualCountFontSize);

          // 计算行高
          const lineHeight = actualNameFontSize * 1.2;

          // 计算三行的垂直位置（整体向上移动）
          const totalHeight = lineHeight * 2.5; // 三行总高度
          const startY = y - totalHeight / 2 + lineHeight * 0.3;

          // 绘制第一行（前四个字符）
          ctx.font = `bold ${actualNameFontSize}px -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif`;
          ctx.fillText(namePart1, x, startY);

          // 绘制第二行（剩余字符）
          if (namePart2) {
            ctx.fillText(namePart2, x, startY + lineHeight);
          }

          // 绘制第三行（人数）
          ctx.font = `${actualCountFontSize}px -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif`;
          ctx.fillText(countText, x, startY + lineHeight * 2);
        });
      } catch (error) {
        console.error('绘制canvas圆形时出错:', error);
      }
    },

    // 清空性格特征画布
    clearCharacterCanvas() {
      // 获取canvas元素
      let canvas = this.$refs.characterCanvas;

      // 如果通过ref获取失败，尝试通过选择器获取
      if (!canvas || typeof canvas !== 'object') {
        canvas = document.querySelector('.character-canvas');
      }

      // 检查canvas元素是否有效
      if (!canvas || typeof canvas !== 'object') {
        console.warn('Canvas元素不存在，无法清空画布');
        return;
      }

      // 检查canvas是否支持2D上下文
      if (!canvas.getContext || typeof canvas.getContext !== 'function') {
        console.warn('Canvas不支持getContext方法，无法清空画布');
        return;
      }

      try {
        // 获取canvas上下文
        const ctx = canvas.getContext('2d');

        // 获取canvas尺寸
        const width = canvas.width || canvas.clientWidth;
        const height = canvas.height || canvas.clientHeight;

        // 清除整个画布
        ctx.clearRect(0, 0, width, height);

        console.log('性格特征画布已清空');
      } catch (error) {
        console.error('清空画布时出错:', error);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.collapse-content {
  padding: 20rpx;
}

.content-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.item-label {
  font-size: 26rpx;
  color: #333333;
  font-weight: 500;
}

.item-value {
  font-size: 26rpx;
  color: #999999;
  font-weight: 500;
}


/* 性别分布布局 */
.gender-layout {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.gender-left {
  flex: 1;
}

.gender-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
}

.gender-label {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

/* 血型分布布局 */
.blood-type-layout {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.blood-type-left {
  flex: 1;
}

.blood-type-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
}

.blood-type-label {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

/* 生肖和星座展示 */
.zodiac-section,
.constellation-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20rpx 0;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 10rpx;
}

.zodiac-label,
.constellation-label {
  font-size: 28rpx;
  color: #666666;
  font-weight: 500;
}

.zodiac-value,
.constellation-value {
  font-size: 28rpx;
  color: #2C80FF;
  font-weight: 600;
}

/* 性格特征和工作风格 */
.personality-traits,
.work-style {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.trait-item,
.style-item {
  padding: 12rpx 24rpx;
  background-color: #e6f7ff;
  border: 1rpx solid #91d5ff;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #1890ff;
  font-weight: 500;
}

/* 图表容器样式 */
.scatter-chart,
.pie-chart {
  height: 600rpx;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.scatter-chart {
  width: 100%;
  padding: 50rpx;
  /* 大幅增加内边距提供更多安全距离 */
  position: relative;
  min-height: 800rpx;
  /* 大幅增加最小高度提供更多空间 */
  box-sizing: border-box;
}

.character-canvas {
  width: 100%;
  height: 100%;
  display: block;
}

.chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 统计表格样式 */
.statistic-table {
  margin-top: 20rpx;
}
</style>