<template>
  <el-container style="min-height: 100vh">
    <!-- 左侧导航 -->
    <el-aside :width="sideWidth + 'px'" style="background-color: #f4f6f9; box-shadow: 2px 0 6px rgba(0, 21, 41, 0.1)">
      <Aside :isCollapse="isCollapse" :logoTextShow="logoTextShow" />
    </el-aside>
    <!-- 右侧内容 -->
    <el-container>
      <!-- 顶部导航 -->
      <el-header style="border-bottom: 1px solid #e0e0e0; background-color: #ffffff; padding: 10px;">
        <Header :collapseBtnClass="collapseBtnClass" :collapse="collapse" />
      </el-header>
      <!-- 主内容 -->
      <el-main style="padding: 20px; background-color: #f9f9f9;">
        <div class="dashboard">
          <!-- 统计卡片 -->
          <el-row :gutter="20">
            <el-col :span="6" v-for="(item, index) in summaryData" :key="index">
              <el-card class="card-box" :body-style="{ padding: '20px' }" shadow="hover">
                <div slot="header" class="card-header">
                  <i :class="item.icon" class="card-icon"></i> <!-- 图标 -->
                  <span>{{ item.title }}</span>
                </div>
                <div class="card-content">
                  <span class="value-text">{{ item.value }}</span>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <!-- 图表展示区域 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="chart-card">
                <h3 class="chart-title">班级人数分布</h3>
                <div ref="genderPieChart" class="chart-container" style="height: 300px; border-radius: 10px; border: 2px solid #f0f0f0;"></div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-card">
                <h3 class="chart-title">班级试卷分布</h3>
                <div ref="examPaperPieChart" class="chart-container" style="height: 300px; border-radius: 10px; border: 2px solid #f0f0f0;"></div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import Header from "@/components/Teacher/Header.vue";
import Aside from "@/components/Teacher/Aside.vue";
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  name: "HomePage",
  components: { Aside, Header },
  data() {
    return {
      userId: "",
      collapseBtnClass: "el-icon-s-fold",
      isCollapse: false,
      sideWidth: 200,
      logoTextShow: true,
      summaryData: [
        { title: "班级总数", icon: "el-icon-user", value: "" },
        { title: "班级总人数", icon: "el-icon-s-custom", value: "" },
        { title: "试卷总数", icon: "el-icon-folder-checked", value: "" },
        { title: "题目总数", icon: "el-icon-tickets", value: "" }
      ],
      classsize: {},
      examPaperSize: {}
    };
  },
  mounted() {
    this.fetchSummaryData();
    this.$nextTick(() => {
      this.initCharts();
    });
  },
  created() {
    this.userId = this.$route.query.userId;
  },
  methods: {
    collapse() {
      this.isCollapse = !this.isCollapse;
      if (this.isCollapse) {
        this.sideWidth = 64;
        this.collapseBtnClass = "el-icon-s-unfold";
        this.logoTextShow = false;
      } else {
        this.sideWidth = 200;
        this.collapseBtnClass = "el-icon-s-fold";
        this.logoTextShow = true;
      }
    },
    async fetchSummaryData() {
      try {
        const token = this.$store.state.tokens[this.userId];
        if (!token) {
          alert("用户未登录，请重新登录！");
          this.$router.push("/login");
          return;
        }
        const response = await axios.get('http://localhost:8080/teacher/homepage/homepagesuju', {
          headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'application/json',
          }
        });

        const data = response.data.data;

        // 更新 summaryData 中的值
        this.summaryData = this.summaryData.map(item => {
          switch (item.title) {
            case "班级总数":
              item.value = data.sumclass || "0";
              break;
            case "班级总人数":
              item.value = data.sunnumclass || "0";
              break;
            case "试卷总数":
              item.value = data.exampapersum || "0";
              break;
            case "题目总数":
              item.value = data.sumtimu || "0";
              break;
            default:
              break;
          }
          return item;
        });

        this.classsize = data.classsize;
        this.examPaperSize = data.examPaperSize;

        this.initCharts();  // 数据更新后重新初始化图表
      } catch (error) {
        console.error('获取数据失败', error);
      }
    },

    initCharts() {
      const classsizeData = Object.entries(this.classsize).map(([key, value]) => ({
        name: key,
        value: value
      }));

      const examPaperData = Object.entries(this.examPaperSize).map(([key, value]) => ({
        name: key,
        value: value
      }));

      // 班级人数分布
      let genderPieChart = echarts.getInstanceByDom(this.$refs.genderPieChart);
      if (genderPieChart) {
        genderPieChart.dispose();
      }
      genderPieChart = echarts.init(this.$refs.genderPieChart);

      genderPieChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: Object.keys(this.classsize),
          top: 'middle',
          textStyle: {
            fontSize: 14
          }
        },
        series: [
          {
            name: '班级人数分布',
            type: 'pie',
            radius: ['50%', '70%'], // 设置内外半径，形成环形效果
            data: classsizeData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'outside', // 将标签放到外侧
              formatter: '{b}: {c} ({d}%)', // 显示分类名称和数值
              fontSize: 14,
              fontWeight: 'bold',
              color: '#333'
            },
            labelLine: {
              show: true, // 显示连接线
              length: 15, // 调整连接线的长度
              lineStyle: {
                width: 2,
                type: 'solid',
                color: '#333'
              }
            }
          }
        ],
      });

      // 试卷分布
      let examPaperPieChart = echarts.getInstanceByDom(this.$refs.examPaperPieChart);
      if (examPaperPieChart) {
        examPaperPieChart.dispose();
      }
      examPaperPieChart = echarts.init(this.$refs.examPaperPieChart);

      examPaperPieChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: Object.keys(this.examPaperSize),
          top: 'middle',
          textStyle: {
            fontSize: 14
          }
        },
        series: [
          {
            name: '试卷分布',
            type: 'pie',
            radius: ['50%', '70%'], // 设置内外半径，形成环形效果
            data: examPaperData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'outside', // 将标签放到外侧
              formatter: '{b}: {c} ({d}%)', // 显示分类名称和数值
              fontSize: 14,
              fontWeight: 'bold',
              color: '#333'
            },
            labelLine: {
              show: true, // 显示连接线
              length: 15, // 调整连接线的长度
              lineStyle: {
                width: 2,
                type: 'solid',
                color: '#333'
              }
            }
          }
        ],
      });
    }

  }
}
</script>

<style scoped>
.card-box {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
}

.card-box:hover {
  transform: translateY(-5px);
}

.card-header {
  font-size: 18px;
  color: #333;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.card-icon {
  font-size: 24px;
  margin-right: 10px;
}

.value-text {
  font-size: 22px;
  font-weight: bold;
  color: #409eff;
}

.chart-title {
  font-size: 18px;
  color: #333;
  font-weight: bold;
  margin-bottom: 10px;
}

.chart-container {
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}
</style>
