<template>
  <uni-collapse>
    <eikon-collapse-item title="标准执行" name="standardExecution" :borderColor="'#48A838'">
      <view class="collapse-content">
        <view class="content-item" v-if="!isZhanZhang">
          <view class="item-label">巡检排名</view>
          <view class="item-value">
            <SwitchTab :tabList="switchOptions" :defaultActive="inspectionSwitchValue"
              @tabChange="handleInspectionTabChange" />
          </view>

        </view>
        <view class="ranking-content" v-if="!isZhanZhang">
          <h-rank-line :percentage="percentage">
            <view class="ranking-text">
              <text class="ranking-rank">第{{ rankData.rank || 0 }}名</text>
              /
              <text class="ranking-count">{{ rankData.rankCount || 0 }}</text>
            </view>
          </h-rank-line>
        </view>

        <view class="content-item">
          <view class="item-label">巡检总问题数</view>
          <view class="item-value">{{ portraitData && portraitData.sumCount ? portraitData.sumCount : 0 }}</view>
        </view>

        <view class="content-item">
          <view class="item-label">问题分布项</view>
        </view>

        <!-- 问题分布雷达图 -->
        <view class="radar-chart">
          <div ref="issueRadarChart" class="chart-container"></div>
        </view>

        <view class="content-item">
          <view class="item-label">整改统计</view>
          <view class="item-value">
            <h-legend :legend-data="rectificationData" :colorSize="20" :textSize="24" />
          </view>
        </view>

        <!-- 整改统计 - 左右布局 -->
        <view class="content-item">
          <h-line :data="rectificationData" :total="rectificationTotal" :itemWidth="300" :lineHeight="'40'" />
        </view>

        <view class="content-item" v-if="!isZhanZhang">
          <view class="item-label">测试排名</view>
          <view class="item-value">
            <SwitchTab :tabList="switchOptions" :defaultActive="testSwitchValue" @tabChange="handleTestTabChange" />
          </view>
        </view>

        <view class="ranking-content" v-if="!isZhanZhang">
          <h-rank-line :percentage="testPercentage">
            <view class="ranking-text"><text class="ranking-rank">第{{ testRankData.rank || 0 }}名</text>/<text
                class="ranking-count">{{
                  testRankData.rankCount || 0 }}</text></view>
          </h-rank-line>
        </view>

        <!-- 测试平均分 - 左右布局 -->
        <view class="content-item">
          <view class="item-label">测试平均分</view>
          <view class="item-value">{{ profileData && profileData.scoreStats && profileData.scoreStats.totalAvgScore
            || profileData && profileData.avgScore || 0 }}</view>
        </view>

        <view class="content-item" v-if="isZhanZhang">
          <view class="item-label">测试总错题数</view>
          <view class="item-value">{{ profileData && profileData.totalErrors ? profileData.totalErrors : 0 }}</view>
        </view>


        <!-- 错题分布雷达图 -->
        <view class="radar-chart">
          <div ref="wrongQuestionRadarChart" class="chart-container"></div>
        </view>
      </view>
    </eikon-collapse-item>
  </uni-collapse>
</template>

<script>
import EikonCollapseItem from "./eikon-collapse-item.vue";
import SwitchTab from "./switch-tab.vue"
import HRankLine from "@/components/h-rank-line/h-rank-line.vue";
import HLine from "@/components/h-line/h-line.vue";
import HLegend from "@/components/h-legend/h-legend.vue";
import * as echarts from 'echarts';
import { mapState, mapGetters } from 'vuex'

export default {
  name: "StandardExecution",
  components: {
    EikonCollapseItem,
    SwitchTab,
    HRankLine,
    HLine,
    HLegend
  },
  data() {
    return {
      rankData: {
        rank: 0,
        rankCount: 0
      },
      testRankData: {
        rank: 0,
        rankCount: 0
      },
      // switch-tab配置
      inspectionSwitchValue: 'station',
      testSwitchValue: 'station',

      // 测试排名数据
      testRanking: {
        percentage: 92
      },
      // 测试平均分
      testAverageScore: 88.5,
      // 整改统计数据
      rectificationData: [],
      rectificationTotal: 0
    }
  },
  computed: {
    ...mapState({
      portraitData: state => state.eikonLevel.portraitData,
      profileData: state => state.eikonLevel.profileData,
      isPersonal: state => state.eikonLevel.isPersonal,
      isBanZuZhang: state => state.eikonLevel.isBanZuZhang,
      isKeZhang: state => state.eikonLevel.isKeZhang,
      isZhanZhang: state => state.eikonLevel.isZhanZhang,
      currentLevel: state => state.eikonLevel.currentLevel,
    }),
    ...mapGetters('eikonLevel', ['isZhanZhang', 'isPersonal', 'isJingLi', 'isKeZhang', 'isBanZuZhang']),
    switchOptions() {
      if (this.isKeZhang) {
        return [
          { value: 'station', label: '全站' },
          { value: 'brigade', label: '本大队' },
        ]
      }
      if (this.isBanZuZhang) {
        return [
          { value: 'station', label: '全站' },
          { value: 'brigade', label: '本大队' },
          { value: 'department', label: '本主管' },
        ]
      }
      if (this.isPersonal) {
        return [
          { value: 'station', label: '全站' },
          { value: 'brigade', label: '本大队' },
          { value: 'department', label: '本主管' },
          { value: 'team', label: '本班' }
        ]
      }

      return []
    },
    percentage() {
      return this.rankData.rankCount > 0 ? Number((this.rankData.rank / this.rankData.rankCount * 100).toFixed(2)) : 0;
    },
    testPercentage() {
      return this.testRankData.rankCount > 0 ? Number((this.testRankData.rank / this.testRankData.rankCount * 100).toFixed(2)) : 0;
    }
  },
  watch: {
    portraitData: {
      handler(newData) {
        if (newData && Object.keys(newData).length > 0) {
          this.$nextTick(() => {
            this.handleInspectionTabChange({ value: this.inspectionSwitchValue });
            if (this.issueRadarChart) {
              this.issueRadarChart.dispose();
              this.issueRadarChart = null;
            }
            this.initIssueRadarChart();
            this.initLine();
          });
        }
      },
    },
    profileData: {
      handler(newData) {
        if (newData && Object.keys(newData).length > 0) {
          this.$nextTick(() => {
            this.handleTestTabChange({ value: this.testSwitchValue });
            if (this.wrongQuestionRadarChart) {
              this.wrongQuestionRadarChart.dispose();
              this.wrongQuestionRadarChart = null;
            }
            this.initWrongQuestionRadarChart();
          });
        }
      },
    }
  },
  mounted() {
    this.$nextTick(() => {
      try {
        this.handleInspectionTabChange({ value: this.inspectionSwitchValue });
        this.handleTestTabChange({ value: this.testSwitchValue });

        this.initLine()
      } catch (error) {
        console.error('Error in nextTick:', error);
      }
    });
  },

  methods: {

    initLine() {
      // 安全地处理portraitData可能为undefined的情况
      const portraitData = this.portraitData || {};
      const onTimeCompletedCount = portraitData.onTimeCompletedCount || 0;
      const overTimeCompletedCount = portraitData.overTimeCompletedCount || 0;

      // 确保rectificationData是数组
      if (!Array.isArray(this.rectificationData)) {
        this.rectificationData = [];
      }

      this.rectificationData = [
        { value: onTimeCompletedCount, color: '#FA8C16', name: '按期整改' },
        { value: overTimeCompletedCount, color: '#FFB30F', name: '超期整改' },
      ]
      this.rectificationTotal = onTimeCompletedCount + overTimeCompletedCount
    },




    // 初始化问题分布雷达图
    initIssueRadarChart() {
      const chartDom = this.$refs.issueRadarChart;
      if (!chartDom) return;

      // 清除容器内容
      chartDom.innerHTML = '';

      const chart = echarts.init(chartDom);
      this.issueRadarChart = chart;

      // 安全地处理portraitData可能为undefined的情况
      const portraitData = this.portraitData || {};
      const checkLargeScreenCommonDtoList = portraitData.checkLargeScreenCommonDtoList || [];
      let maxTotal = 0;
      let indicator = [];
      let seriesData = [];
      if (this.currentLevel === 'station') {
        let res = checkLargeScreenCommonDtoList.filter((item) => {
          return item && item.deptName !== '总数'
        });

        // 获取所有不重复的name作为雷达图维度
        const uniqueNames = [...new Set(res.map(item => item.name))];
        maxTotal = res.length > 0 ? Math.max(...res.map(item => item.total || 0)) : 1;
        indicator = uniqueNames.map(name => ({
          name: name,
          max: maxTotal
        }));
        let obj = {};

        res.forEach((item) => {
          if (obj[item.deptName]) {
            obj[item.deptName].push(item.total || 0);
          } else {
            obj[item.deptName] = [item.total || 0];
          }
        })


        Object.keys(obj).forEach((key, index) => {

          seriesData.push({
            value: obj[key],
            name: key,
            // areaStyle: {
            //   color: color.area
            // },

            // itemStyle: {
            //   color: color.line
            // }
          })
        })

      } else {

        let res = checkLargeScreenCommonDtoList.filter((item) => {
          return item && item.deptName === '总数'
        });



        maxTotal = res.length > 0 ? Math.max(...res.map(item => item.total || 0)) : 1;
        indicator = res.map((item) => {
          return { name: item.name, max: maxTotal || 1 }
        })
        seriesData = [{
          value: res.map((item) => {
            return item.total || 0
          }),
          name: '问题分布',
          // areaStyle: {
          //   color: 'rgba(72, 115, 227, 0.3)'
          // },
          lineStyle: {
            color: '#4873E3'
          },
          // itemStyle: {
          //   color: '#4873E3'
          // }
        }]
      }


      // console.log('雷达图数据:', indicator, seriesData)

      const option = {
        ...(this.currentLevel === 'station' ? {
          legend: {
            data: seriesData.map(item => item.name),
            top: 0,
            textStyle: {
              color: '#666',
              fontSize: 12
            }
          }
        } : {
          legend: {
            show: false
          }
        })
        ,
        radar: {
          indicator: indicator,
          shape: 'polygon',
          splitNumber: 4,
          radius: '50%',
          center: ['50%', '60%'], // 缩小雷达图并居中，为label留出空间
          axisName: {
            color: '#666',
            fontSize: 12
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(0, 0, 0, 0.1)'
            }
          },
          splitArea: {
            show: true,
            areaStyle: {
              color: ['rgba(255, 255, 255, 0.8)', 'rgba(255, 255, 255, 0.4)']
            }
          }
        },
        series: [{
          type: 'radar',
          data: seriesData,
          symbol: 'none',
          emphasis: {
            lineStyle: {
              width: 4
            }
          }
        }],
        tooltip: {
          trigger: 'item'
        }
      };

      chart.setOption(option);

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

    // 初始化错题分布雷达图
    initWrongQuestionRadarChart() {
      const chartDom = this.$refs.wrongQuestionRadarChart;
      if (!chartDom) return;

      // 清除容器内容
      chartDom.innerHTML = '';

      const chart = echarts.init(chartDom);
      this.wrongQuestionRadarChart = chart;
      // 定义六个固定的雷达图维度
      const radarDimensions = [
        '操作执行',
        '传达学习',
        '班组管理',
        '工作纪律',
        '设施设备',
        '通道样貌'
      ];

      // 从profileData获取错题分类数据
      const profileData = this.profileData || {};
      let categoryErrors = [];
      let indicator = [];
      let seriesData = [];
      let legend = [];

      if (this.currentLevel == 'station') {
        categoryErrors = (profileData.deptCategoryErrors || []).map(item => {
          return {
            ...item,
            categoryErrors: (item.categoryErrors || []).filter(childItem => childItem.categoryName !== '未分类')
          }
        });

        const maxErrorCount = Math.max(...categoryErrors.map(dept => {
          const matchedCategory = dept.categoryErrors.map(cat => cat.errorCount);
          return Math.max(...matchedCategory);
        }));
        // 构建indicator数据 - 使用固定的六个维度
        indicator = radarDimensions.map(dimension => {
          return {
            name: dimension,
            max: maxErrorCount
          };
        });
        legend = categoryErrors.map(item => item.deptName);

        // 构建series数据 - 每个部门一条数据线
        const colorPalette = [
          { area: 'rgba(72, 115, 227, 0.3)', line: '#4873E3' }, // 蓝色
          { area: 'rgba(255, 107, 107, 0.3)', line: '#FF6B6B' }, // 红色
          { area: 'rgba(76, 175, 80, 0.3)', line: '#4CAF50' },   // 绿色
          { area: 'rgba(255, 152, 0, 0.3)', line: '#FF9800' },   // 橙色
          { area: 'rgba(156, 39, 176, 0.3)', line: '#9C27B0' },  // 紫色
          { area: 'rgba(0, 188, 212, 0.3)', line: '#00BCD4' },   // 青色
          { area: 'rgba(244, 67, 54, 0.3)', line: '#F44336' },   // 深红色
          { area: 'rgba(139, 195, 74, 0.3)', line: '#8BC34A' }   // 浅绿色
        ];

        seriesData = categoryErrors.map((dept, index) => {
          const colorIndex = index % colorPalette.length;
          const color = colorPalette[colorIndex];

          // 为每个维度获取该部门的错误数量
          const values = radarDimensions.map(dimension => {
            const matchedCategory = dept.categoryErrors.find(cat => cat.categoryName === dimension);
            return matchedCategory ? matchedCategory.errorCount : 0;
          });

          return {
            value: values,
            name: dept.deptName,

            // lineStyle: {
            //   color: color.line,

            // },
            // itemStyle: {
            //   color: color.line
            // },
            label: {
              show: true, // 在每个角上显示数值
              formatter: function (params) {
                return params.value;
              },
              // color: color.line,
              fontSize: 10
            }
          };
        });

      } else {
        categoryErrors = (profileData.categoryErrors || []).filter(item =>
          item.categoryName !== '未分类'
        );
        // 构建indicator数据
        indicator = radarDimensions.map(dimension => {
          // 查找对应维度的错误数量
          const matchedCategory = categoryErrors.find(item => item.categoryName === dimension);
          const errorCount = matchedCategory ? matchedCategory.errorCount : 0;

          // 计算最大值（当前错误数量的1.5倍，最小为10）
          const maxValue = Math.max(errorCount * 1.5, 10);

          return {
            name: dimension,
            max: maxValue
          };
        });
        // 构建series数据
        seriesData = [{
          value: radarDimensions.map(dimension => {
            const matchedCategory = categoryErrors.find(item => item.categoryName === dimension);
            return matchedCategory ? matchedCategory.errorCount : 0;
          }),
          name: '错题分布',
          // areaStyle: {
          //   show: false // 去掉面积遮盖
          // },
          lineStyle: {
            color: '#FF6B6B',
            width: 2
          },
          // itemStyle: {
          //   color: '#FF6B6B'
          // },
          label: {
            show: true, // 在每个角上显示数值
            formatter: function (params) {
              return params.value;
            },
            color: '#FF6B6B',
            fontSize: 10
          }
        }];
      }

      const option = {
        ...(this.currentLevel == 'station' ? {
          legend: {
            data: legend,
            top: 0,
            textStyle: {
              color: '#666',
              fontSize: 12
            }
          }
        } : { legend: { show: false } }),
        radar: {
          indicator: indicator,
          shape: 'polygon',
          splitNumber: 4,
          radius: '50%',
          center: ['50%', '60%'], // 缩小雷达图并居中，为label留出空间
          axisName: {
            color: '#666',
            fontSize: 12
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(0, 0, 0, 0.1)'
            }
          },
          splitArea: {
            show: true,
            areaStyle: {
              color: ['rgba(255, 255, 255, 0.8)', 'rgba(255, 255, 255, 0.4)']
            }
          }
        },
        series: [{
          type: 'radar',
          data: seriesData,
          symbol: 'none',
          emphasis: {
            lineStyle: {
              width: 4
            }
          }
        }],
        ...(this.currentLevel == 'station' ? {
          tooltip: {
            trigger: 'item',
            formatter: function (params) {
              const values = params.value;
              const dimensionLabels = radarDimensions.map((dimension, index) => {
                return `${dimension}: ${values[index]}题`;
              });
              return `${params.name}<br/>${dimensionLabels.join('<br/>')}`;

            }.bind(this),
            extraCssText: 'white-space: pre-line; max-width: 300px;'
          }
        } : {
          tooltip: {
            trigger: 'item'
          }
        })

      };

      chart.setOption(option);

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

    // 巡检排名切换处理
    handleInspectionTabChange(event) {
      console.log('巡检排名切换:', event);
      this.inspectionSwitchValue = event.value;
      // 安全地处理portraitData可能为undefined的情况
      const portraitData = this.portraitData || {};
      const stationRanking = portraitData.stationRanking || 0;
      const stationTotal = portraitData.stationTotal || 0;
      const departmentRanking = portraitData.departmentRanking || 0;
      const departmentTotal = portraitData.departmentTotal || 0;
      const teamRanking = portraitData.teamRanking || 0;
      const teamTotal = portraitData.teamTotal || 0;
      const brigadeTotal = portraitData.brigadeTotal || 0;
      const brigadeRanking = portraitData.brigadeRanking || 0;
      console.log('portraitData:', this.portraitData);
      if (this.inspectionSwitchValue == 'station') {
        this.rankData = {
          rank: stationRanking,
          rankCount: stationTotal
        }
      } else if (this.inspectionSwitchValue == 'brigade') {
        this.rankData = {
          rank: brigadeRanking,
          rankCount: brigadeTotal
        }
      } else if (this.inspectionSwitchValue == 'department') {
        this.rankData = {
          rank: departmentRanking,
          rankCount: departmentTotal
        }
      } else if (this.inspectionSwitchValue == 'team') {
        this.rankData = {
          rank: teamRanking,
          rankCount: teamTotal
        }
      }
    },

    // 测试排名切换处理
    handleTestTabChange(event) {
      console.log('测试排名切换:', event);
      this.testSwitchValue = event.value;
      const { rankingStats } = this.profileData || {};


      if (this.testSwitchValue == 'station') {
        this.testRankData = {
          rank: rankingStats?.siteRanking || 0,
          rankCount: this.isKeZhang ? rankingStats?.siteTotalDepts || 0 : rankingStats?.siteTotalUsers || 0
        }
      } else if (this.testSwitchValue == 'brigade') {
        this.testRankData = {
          rank: rankingStats?.deptRanking || 0,
          rankCount: rankingStats?.deptTotalTeams || 0
        }
      } else if (this.testSwitchValue == 'department') {
        this.testRankData = {
          rank: rankingStats?.deptRanking || 0,
          rankCount: rankingStats?.deptTotalUsers || 0
        }
      } else if (this.testSwitchValue == 'team') {
        this.testRankData = {
          rank: rankingStats?.teamRanking || 0,
          rankCount: rankingStats?.teamTotalUsers || 0
        }
      }
    },
  }
}
</script>

<style scoped lang="scss">
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;

  .loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;

    .loading-spinner {
      width: 40rpx;
      height: 40rpx;
      border: 4rpx solid #f3f3f3;
      border-top: 4rpx solid #48A838;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20rpx;
    }

    .loading-text {
      font-size: 26rpx;
      color: #999;
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

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





.ranking-content {
  margin: 30rpx 0;

  .ranking-text {
    font-size: 26rpx;
    color: #999999;
    font-weight: 500;

    .ranking-rank {
      font-size: 26rpx;
      font-weight: 500;
      color: #333333;
    }

    .ranking-count {
      font-size: 26rpx;
      font-weight: 500;
      color: #999999;
    }
  }
}



.issues-distribution {
  margin-bottom: 30rpx;

  .distribution-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16rpx 20rpx;
    margin-bottom: 12rpx;
    background: #fff;
    border-radius: 8rpx;

    .distribution-name {
      font-size: 26rpx;
      color: #666;
    }

    .distribution-value {
      font-size: 26rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

.radar-chart {
  height: 550rpx;
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;

  .chart-container {
    width: 100%;
    height: 100%;
  }
}
</style>