<template>
  <uni-collapse>
    <eikon-collapse-item title="主观印象" name="subjectiveImpression" :borderColor="'#FF997C'">
      <div class="collapse-content">
        <!-- 当isPersonal为false时显示图表 -->
        <view v-show="!isPersonal" class="chart-container">
          <view id="subjectiveChart" class="echarts-chart"></view>
        </view>

        <!-- 当isPersonal为true时显示四个关键词评价区块 -->
        <view v-show="isPersonal" class="keyword-evaluation">
          <!-- 自我关键词评价 -->
          <div class="content-item" v-if="selfKeywords.length > 0">
            <div class="item-label">自我关键词评价</div>
          </div>
          <div class="content-item">
            <text-tag :tags="selfKeywords" :showClose="false" />
          </div>

          <!-- 同事关键词评价 -->
          <div class="content-item" v-if="colleagueKeywords.length > 0">
            <div class="item-label">同事关键词评价</div>
          </div>
          <div class="content-item">
            <text-tag :tags="colleagueKeywords" :showClose="false" />
          </div>


          <!-- 上级关键词评价 -->
          <div class="content-item" v-if="superiorKeywords.length > 0">
            <div class="item-label">上级关键词评价</div>
          </div>
          <div class="content-item">
            <text-tag :tags="superiorKeywords" :showClose="false" />
          </div>


          <!-- 下级关键词评价 -->
          <div class="content-item" v-if="!userRoles.includes('SecurityCheck') && subordinateKeywords.length > 0">
            <div class="item-label">下级关键词评价</div>
          </div>
          <div class="content-item">
            <text-tag :tags="subordinateKeywords" :showClose="false" />
          </div>

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

<script>
import EikonCollapseItem from "./eikon-collapse-item.vue";
import * as echarts from 'echarts';
import TextTag from "@/components/text-tag/text-tag.vue";
import { mapGetters, mapState } from 'vuex'
import useDictMixin from '@/utils/dict'
export default {
  name: "SubjectiveImpression",
  components: {
    EikonCollapseItem,
    TextTag
  },
  mixins: [useDictMixin],
  computed: {
    ...mapState({
      collaborationData: state => state.eikonLevel.collaborationData,
      userRoles: state => state.user.roles || [],
    }),
    ...mapGetters('eikonLevel', ['isPersonal'])
  },
  data() {
    return {
      chartData: [
        { name: '工作态度', value: 92 },
        { name: '责任心', value: 95 },
        { name: '创新意识', value: 88 },
        { name: '团队协作', value: 90 },
        { name: '沟通能力', value: 85 }
      ],
      chartInstance: null,
      // 关键词评价数据
      selfKeywords: [],
      colleagueKeywords: [],
      superiorKeywords: [],
      subordinateKeywords: []
    }
  },
  watch: {
    collaborationData: {
      handler(newVal, oldVal) {
        
        if (newVal) {
          
          if (this.isPersonal) {
            this.handlePersonalData(newVal)
          } else {
            this.handleDeptData(newVal)
          }
        }
      },
    }
  },

  methods: {
    handleDeptData(newVal) {
      if (!newVal || !newVal.subjectiveImpressionList) {
        return;
      }


      // 处理主观印象数据，转换为图表格式
      const impressionList = newVal.subjectiveImpressionList;

      // 提取所有子项数据，用于外层环形图
      const allChildrenData = [];

      // 提取主分类数据，用于内层环形图
      const mainCategoryData = [];

      impressionList.forEach(category => {
        // 主分类数据（使用count作为值）
        mainCategoryData.push({
          value: category.count || 0,
          name: category.name
        });

        // 子项数据
        if (category.children && category.children.length > 0) {
          category.children.forEach(child => {
            allChildrenData.push({
              value: child.count || 0,
              name: child.name
            });
          });
        }
      });

      // 更新图表数据
      // this.$nextTick(() => {
        this.updateChartData(mainCategoryData, allChildrenData);
      // })
    },

    updateChartData(innerData, outerData) {
      const chartDom = document.getElementById('subjectiveChart');
      if (!chartDom) return;

      try {
        console.log(this.chartInstance,"this.chartInstance")
        // 如果图表实例不存在，先初始化
        if (!this.chartInstance) {
          this.chartInstance = echarts.init(chartDom);

          // 监听窗口变化，重新渲染图表
          window.addEventListener('resize', () => {
            if (this.chartInstance) {
              this.chartInstance.resize();
            }
          });
        }

        // 清除图表之前的状态，确保不会残留缺省图
        this.chartInstance.clear();

        // 设置图表配置 - 嵌套环形图
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c}次 ({d}%)'
          },
          legend: {
            show: false
          },
          series: [
            {
              type: 'pie',
              selectedMode: 'single',
              radius: [0, '50%'],
              label: {
                position: 'inner',
                fontSize: 14,
                show: true,
                formatter: function (params) {
                  // 对四个字的中文分类名称进行折行处理
                  const name = params.name;
                  if (name && name.length === 4) {
                    return name.substring(0, 2) + '\n' + name.substring(2, 4);
                  }
                  return name;
                }
              },
              labelLine: {
                show: false
              },
              itemStyle: {
                borderWidth: 2,
                borderColor: '#fff'
              },
              data: innerData
            },
            {
              type: 'pie',
              radius: ['55%', '75%'],
              label: {
                position: 'outer',
                show: true,
                formatter: '{b}: {c}'
              },
              labelLine: {
                show: true,
                length: 10,
                length2: 10
              },
              itemStyle: {
                borderWidth: 2,
                borderColor: '#fff'
              },
              data: outerData
            }
          ]
        }

        this.chartInstance.setOption(option, true); // 使用true参数确保不合并配置
      } catch (error) {
        console.error('更新主观印象图表失败:', error);
      }
    },
    async handlePersonalData(newVal) {
      // 安全地处理newVal可能为null的情况
      const safeNewVal = newVal || {};

      const dict = await this.useDict(
        'sys_user_personality_trait',
        'sys_user_capability_performance',
        'sys_user_interpersonal_interaction',
        'sys_user_growth_potential',
      )
      let dictArr = Object.values(dict).reduce((prev, cur) => prev.concat(cur), []);
      let tagTextStyle = { marginRight: '0', fontSize: '21rpx' }
      // 处理自我关键词评价
      let self = ['selfAssessmentCapabilityPerformance', 'selfAssessmentGrowthPotential', 'selfAssessmentInterpersonalInteraction', 'selfAssessmentPersonalityTrait']
      this.selfKeywords = self.map(item => {
        const dictItem = dictArr.find(d => d.value === safeNewVal[item]);
        return {
          label: dictItem ? dictItem.label : '',
          tagItemStyle: { backgroundColor: '#0D995B1A', color: '#48A838', borderRadius: '0' },
          tagTextStyle
        }
      }).filter(item => item.label);

      // 处理同事关键词评价
      let colleague = ['colleagueCommentsCapabilityPerformance', 'colleagueCommentsGrowthPotential', 'colleagueCommentsInterpersonalInteraction', 'colleagueCommentsPersonalityTrait']
      this.colleagueKeywords = colleague.map(item => {
        const dictItem = dictArr.find(d => d.value === safeNewVal[item]);
        return {
          label: dictItem ? dictItem.label : '',
          tagItemStyle: { backgroundColor: '#F6A9661A', color: '#ED8D1A', borderRadius: '0' },
          tagTextStyle
        }
      }).filter(item => item.label);

      // 处理上级关键词评价
      let superior = ['superiorEvaluationCapabilityPerformance', 'superiorEvaluationGrowthPotential', 'superiorEvaluationInterpersonalInteraction', 'superiorEvaluationPersonalityTrait']
      this.superiorKeywords = superior.map(item => {
        const dictItem = dictArr.find(d => d.value === safeNewVal[item]);
        return {
          label: dictItem ? dictItem.label : '',
          tagItemStyle: { backgroundColor: '#02A6BD1A', color: '#00A5BC', borderRadius: '0' },
          tagTextStyle
        }
      }).filter(item => item.label);

      // 处理下级关键词评价
      let subordinate = ['subordinateEvaluationCapabilityPerformance', 'subordinateEvaluationGrowthPotential', 'subordinateEvaluationInterpersonalInteraction', 'subordinateEvaluationPersonalityTrait']
      this.subordinateKeywords = subordinate.map(item => {
        const dictItem = dictArr.find(d => d.value === safeNewVal[item]);
        return {
          label: dictItem ? dictItem.label : '',
          tagItemStyle: { backgroundColor: '#2E81FF1A', color: '#2C80FF', borderRadius: '0' },
          tagTextStyle
        }
      }).filter(item => item.label);

    },

  },
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
    }
  }
}
</script>

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

.chart-container {
  height: 400rpx;
  padding: 16rpx 0;

  .echarts-chart {
    width: 100%;
    height: 100%;
  }
}

.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;
}

/* 关键词评价区块样式 */
.keyword-evaluation {}

.evaluation-section {
  background: #f8f9fa;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333333;
  margin-bottom: 16rpx;
  padding-bottom: 8rpx;
  border-bottom: 2rpx solid #e8e8e8;
}
</style>