<template>
  <div class="real-time-status">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <text>加载中...</text>
    </div>

    <!-- 统计表格区域 - 遍历分组后的数据 -->
    <div v-else class="statistics-section">
      <div v-for="(group, index) in groupedData" :key="index" class="statistic-table-wrapper">
        <!-- 每个统计表格的标题 - 使用deptName -->
        <h2 class="table-title">{{ group.title }}</h2>

        <!-- statistic-table组件 -->
        <statistic-table :columns="tableColumns" :data="group.data">
          <template #column-progress="{ row, index }">
            <view class="progress-container">
              <u-line-progress :percentage="Math.round(row.progress * 100)" :showText="false"
                :activeColor="getProgressColor(row.progress * 100)" height="20rpx"
                width="200rpx"></u-line-progress>
              <text class="progress-text">{{ Math.round(row.progress * 100) }}%</text>
            </view>
          </template>
        </statistic-table>
      </div>

      <!-- 无数据提示 -->
      <div v-if="groupedData.length === 0" class="no-data">
        <text>暂无统计数据</text>
      </div>
    </div>
  </div>
</template>

<script>
import StatisticTable from "@/components/statistic-table/statistic-table.vue";
import { getDailyAllUsersRanking } from "@/api/questionStatistics/questionStatistics";

export default {
  name: 'RealTimeStatus',
  components: {
    StatisticTable
  },
  props: {
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 固定的表格列配置
      tableColumns: [
        { props: 'userName', title: '姓名' },
        { props: 'completedTasks', title: '答题进度' },
        { props: 'avgScore', title: '平均分' },
        { props: 'progress', title: '完成率', slot: true }
      ],
      // 分组后的数据
      groupedData: [],
      // 原始接口数据
      apiData: []
    };
  },
  mounted() {
    this.getDailyAllUsersRanking();
  },
  methods: {
    async getDailyAllUsersRanking() {
      this.$emit('update:loading', true);
      
      try {
        const res = await getDailyAllUsersRanking({
          pageNum: 1,
          pageSize: 100
        });
        
        if (res.code === 200) {
          this.apiData = res.data.rows || [];
          this.groupDataByDept();
        } else {
          uni.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取数据失败:', error);
        uni.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      } finally {
        this.$emit('update:loading', false);
      }
    },
    // 按照deptName分组数据
    groupDataByDept() {
      if (!this.apiData || this.apiData.length === 0) {
        this.groupedData = [];
        return;
      }

      // 使用Map来分组数据
      const deptMap = new Map();

      this.apiData.forEach(item => {
        const deptName = item.deptName || '未知部门';

        if (!deptMap.has(deptName)) {
          deptMap.set(deptName, []);
        }

        // 格式化数据，确保包含所有需要的字段
        const formattedItem = {
          userName: item.userName || '未知用户',
          completedTasks: item.completedTasks,
          avgScore: item.avgScore || 0,
          progress: item.completedTasks == 0 ? 0 : item.completedTasks / item.totalTasks
        };

        deptMap.get(deptName).push(formattedItem);
      });

      // 转换为数组格式
      this.groupedData = Array.from(deptMap.entries()).map(([deptName, data]) => ({
        title: deptName,
        data: data
      }));

      console.log('分组后的数据:', this.groupedData);
    },
    // 根据完成比例返回对应的颜色
    getProgressColor(percentage) {
      if (percentage >= 100) {
        return '#2B7BFF'; // 大于等于100%时使用蓝色
      } else if (percentage > 0 && percentage < 100) {
        return '#03AF43'; // 0-100%之间使用绿色
      } else {
        return '#E40808'; // 0%时使用红色
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.real-time-status {
  margin-top: 20rpx;
  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200rpx;
    font-size: 28rpx;
    color: #999;
  }

  .statistics-section {
    .statistic-table-wrapper {
      margin-bottom: 32rpx;
      
      .table-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 24rpx;
        padding-left: 16rpx;
        border-left: 8rpx solid #2B7BFF;
      }
    }

    .progress-container {
      display: flex;
      align-items: center;
      gap: 16rpx;

      .progress-text {
        font-size: 24rpx;
        color: #666;
        min-width: 60rpx;
      }
    }

    .no-data {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200rpx;
      font-size: 28rpx;
      color: #999;
    }
  }
}
</style>