<template>
  <div class="dashboard-container">
    <!-- 数据卡片区域 -->
    <a-row :gutter="24">
      <a-col :span="6">
        <a-card class="data-card">
          <a-statistic
            title="用户总数"
            :value="totaluser"
            :precision="0"
            style="text-align: center"
          >
            <template #prefix>
              <a-icon type="user" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="data-card">
          <a-statistic
            title="教师人数"
            :value="totalteacher"
            :precision="0"
            style="text-align: center"
          >
            <template #prefix>
              <a-icon type="team" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="data-card">
          <a-statistic
            title="学生人数"
            :value="totalstudent"
            :precision="0"
            style="text-align: center"
          >
            <template #prefix>
              <a-icon type="solution" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="data-card">
          <a-statistic
            title="比赛总数"
            :value="totalmatch"
            :precision="0"
            style="text-align: center"
          >
            <template #prefix>
              <a-icon type="trophy" />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 趋势图和热门比赛区域 -->
    <a-row :gutter="24" style="margin-top: 24px">
      <!-- 报名趋势图 -->
      <a-col :span="16">
        <a-card title="学生报名比赛趋势" :bordered="false">
          <div ref="registrationTrend" style="height: 400px"></div>
        </a-card>
      </a-col>

      <!-- 热门比赛列表 -->
      <a-col :span="8">
        <a-card title="热门比赛" :bordered="false">
          <a-list
            itemLayout="horizontal"
            :dataSource="hotCompetitions"
            :loading="loading"
          >
            <a-list-item slot="renderItem" slot-scope="item">
              <a-list-item-meta>
                <template slot="title">
                  <a href="javascript:;">{{ item.competitionName }}</a>
                </template>
                <template slot="description">
                  <span>报名人数: {{ item.registrationCount }}</span>
                  <span style="margin-left: 16px">
                    状态: {{ getCompetitionStatus(item.competitionStatus) }}
                  </span>
                </template>
                <a-avatar
                  slot="avatar"
                  style="background-color: #1890ff"
                  icon="trophy"
                />
              </a-list-item-meta>
            </a-list-item>
          </a-list>
        </a-card>
      </a-col>
    </a-row>

    <!-- 获奖情况统计 -->
    <a-row :gutter="24" style="margin-top: 24px">
      <a-col :span="24">
        <a-card title="获奖情况统计" :bordered="false">
          <div ref="awardChart" style="height: 300px"></div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "Console",
  data() {
    return {
      loading: false,
      // 用户统计数据
      totaluser: 0,
      totalteacher: 0,
      totalstudent: 0,
      totalmatch: 0,

      // 获奖数据
      firstlevel: 0,
      secondlevel: 0,
      thirdlevel: 0,

      // 报名趋势数据
      registrationTrendData: [],

      // 热门比赛列表
      hotCompetitions: [],

      // 其他统计数据
      totalinfo: 0,
      totalsuccess: 0,
      totalday: 0,
      totaldays: 0,

      // 图表实例
      registrationTrendChart: null,
      awardChart: null,

      // 是否使用模拟数据
      useMockData: false,
    };
  },
  mounted() {
    this.fetchAllData();
  },
  beforeDestroy() {
    // 销毁图表实例，避免内存泄漏
    if (this.registrationTrendChart) {
      this.registrationTrendChart.dispose();
    }
    if (this.awardChart) {
      this.awardChart.dispose();
    }
  },
  methods: {
    // 获取所有数据
    async fetchAllData() {
      this.loading = true;
      try {
        // 优先获取基础统计数据
        await this.fetchStatistics();
        // 获取其他数据
        await Promise.all([
          this.fetchAwardStats(),
          this.fetchRegistrationTrend(),
          this.fetchHotCompetitions(),
        ]);

        this.$nextTick(() => {
          this.initRegistrationTrendChart();
          this.initAwardChart();
        });
      } catch (error) {
        console.error("获取数据失败", error);
        this.$message.error("获取数据失败");
      } finally {
        this.loading = false;
      }
    },

    // 获取统计数据
    async fetchStatistics() {
      try {
        // this.$api.getWinCountByLevel
        const response = await this.$api.getCountTotal();
        console.log("response", response);
        if (response.code === 200) {
          console.log("response.data", response.data);
          const stats = response.data;
          // 直接使用接口返回的数据
          this.totaluser = stats.totalUsers;
          this.totalteacher = stats.teacherCount;
          this.totalstudent = stats.studentCount;
          this.totalmatch = stats.competitionCount;
        }
      } catch (error) {
        console.error("获取统计数据失败:", error);
        this.$message.error("获取统计数据失败");
        // 发生错误时重置数据为0
        this.totaluser = 0;
        this.totalteacher = 0;
        this.totalstudent = 0;
        this.totalmatch = 0;
      }
    },

    // 加载模拟数据
    loadMockData() {
      // 模拟用户统计数据
      this.totaluser = 1256;
      this.totalteacher = 128;
      this.totalstudent = 1128;
      this.totalmatch = 45;

      // 模拟获奖数据
      this.firstlevel = 56;
      this.secondlevel = 112;
      this.thirdlevel = 235;

      // 模拟其他统计数据
      this.totalinfo = 89;
      this.totalsuccess = 876;
      this.totalday = 32;
      this.totaldays = 5;

      // 模拟报名趋势数据
      this.generateMockTrendData();

      // 模拟热门比赛数据
      this.generateMockHotCompetitions();
    },

    // 生成模拟趋势数据
    generateMockTrendData() {
      const dates = [];
      const counts = [];
      const today = new Date();

      for (let i = 29; i >= 0; i--) {
        const date = new Date(today);
        date.setDate(date.getDate() - i);
        const dateStr = this.formatDate(date);
        dates.push(dateStr);

        // 生成随机报名数量，呈现波动上升趋势
        const baseCount = 5 + Math.floor((30 - i) / 3);
        const randomFactor = Math.floor(Math.random() * 10) - 3;
        const count = Math.max(0, baseCount + randomFactor);

        counts.push(count);
      }

      this.registrationTrendData = {
        dates,
        counts,
      };
    },

    // 生成模拟热门比赛数据
    generateMockHotCompetitions() {
      const competitionNames = [
        "全国大学生数学建模竞赛",
        "互联网+创新创业大赛",
        "ACM程序设计大赛",
        "挑战杯创新创业大赛",
        "全国大学生机器人大赛",
      ];

      this.hotCompetitions = competitionNames.map((name, index) => {
        // 生成随机报名人数，排名越前报名人数越多
        const baseCount = 200 - index * 30;
        const randomFactor = Math.floor(Math.random() * 20);

        return {
          competitionId: `comp-${index + 1}`,
          competitionName: name,
          registrationCount: baseCount + randomFactor,
          competitionStatus: Math.random() > 0.3 ? 0 : 1,
        };
      });
    },

    // 获取用户统计数据
    async fetchUserStats() {
      // 获取用户总数
      await this.$api.getCount().then((res) => {
        if (res.code == 200) {
          this.totaluser = res.data;
        }
      });

      // 获取教师总人数
      await this.$api.getTeacherCount().then((res) => {
        if (res.code == 200) {
          this.totalteacher = res.data;
        }
      });

      // 获取学生总人数
      await this.$api.getStudentCount().then((res) => {
        if (res.code == 200) {
          this.totalstudent = res.data;
        }
      });
    },

    // 获取比赛统计数据
    async fetchCompetitionStats() {
      // 获取所有比赛数量
      await this.$api.AllCompetition().then((res) => {
        if (res.code == 200) {
          this.totalmatch = res.data.length;

          // 处理热门比赛数据
          this.processCompetitionData(res.data);
        }
      });

      // 获取所有资料
      await this.$api.Allinformation().then((res) => {
        if (res.code == 200) {
          this.totalinfo = res.data.length;
        }
      });

      // 获取七天内比赛的数量
      const currentDate = new Date();
      const sevenDaysAgo = new Date(currentDate);
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

      await this.$api.AllCompetition().then((res) => {
        if (res.code == 200) {
          this.totaldays = res.data.filter((item) => {
            const registrationEndTime = new Date(item.registrationEndTime);
            return (
              registrationEndTime >= sevenDaysAgo &&
              registrationEndTime <= currentDate
            );
          }).length;
        }
      });
    },

    // 获取获奖统计数据
    async fetchAwardStats() {
      // 一等奖人数
      await this.$api.getWinCountByLevel({ level: "一等奖" }).then((res) => {
        if (res.code == 200) {
          this.firstlevel = res.data;
        }
      });

      // 二等奖人数
      await this.$api.getWinCountByLevel({ level: "二等奖" }).then((res) => {
        if (res.code == 200) {
          this.secondlevel = res.data;
        }
      });

      // 三等奖
      await this.$api.getWinCountByLevel({ level: "三等奖" }).then((res) => {
        if (res.code == 200) {
          this.thirdlevel = res.data;
        }
      });
    },

    // 获取报名趋势数据
    async fetchRegistrationTrend() {
      // 获取报名记录
      await this.$api.RegistrationAll().then((res) => {
        if (res.code == 200) {
          // 处理报名趋势数据
          this.processRegistrationTrendData(res.data);

          // 获取成功报名数量
          this.totalsuccess = res.data.filter(
            (item) => item.registrationStatus == "成功报名"
          ).length;

          // 获取七天内成功报名的数量
          const currentDate = new Date();
          const sevenDaysAgo = new Date(currentDate);
          sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

          this.totalday = res.data.filter((item) => {
            const registrationTime = new Date(item.registrationTime);
            return (
              registrationTime >= sevenDaysAgo &&
              registrationTime <= currentDate
            );
          }).length;
        }
      });
    },

    // 获取热门比赛数据
    async fetchHotCompetitions() {
      // 获取报名记录和比赛数据
      const [registrationRes, competitionRes] = await Promise.all([
        this.$api.RegistrationAll(),
        this.$api.AllCompetition(),
      ]);

      if (registrationRes.code == 200 && competitionRes.code == 200) {
        const registrations = registrationRes.data;
        const competitions = competitionRes.data;

        // 计算每个比赛的报名人数
        const competitionCounts = {};
        registrations.forEach((reg) => {
          if (!competitionCounts[reg.competitionId]) {
            competitionCounts[reg.competitionId] = 0;
          }
          competitionCounts[reg.competitionId]++;
        });

        // 将比赛数据与报名人数合并
        const competitionsWithCount = competitions.map((comp) => ({
          ...comp,
          registrationCount: competitionCounts[comp.competitionId] || 0,
        }));

        // 按报名人数排序，取前5个
        this.hotCompetitions = competitionsWithCount
          .sort((a, b) => b.registrationCount - a.registrationCount)
          .slice(0, 5);
      }
    },

    // 处理报名趋势数据
    processRegistrationTrendData(registrations) {
      // 获取最近30天的日期
      const dates = [];
      const counts = [];
      const today = new Date();

      for (let i = 29; i >= 0; i--) {
        const date = new Date(today);
        date.setDate(date.getDate() - i);
        const dateStr = this.formatDate(date);
        dates.push(dateStr);

        // 计算当天的报名数量
        const count = registrations.filter((reg) => {
          const regDate = new Date(reg.registrationTime);
          return this.formatDate(regDate) === dateStr;
        }).length;

        counts.push(count);
      }

      this.registrationTrendData = {
        dates,
        counts,
      };
    },

    // 处理比赛数据
    processCompetitionData(competitions) {
      // 在这里可以添加更多的数据处理逻辑
    },

    // 初始化报名趋势图表
    initRegistrationTrendChart() {
      const chartDom = this.$refs.registrationTrend;
      this.registrationTrendChart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: this.registrationTrendData.dates,
          axisLabel: {
            rotate: 45,
          },
        },
        yAxis: {
          type: "value",
          name: "报名人数",
        },
        series: [
          {
            name: "报名人数",
            type: "line",
            data: this.registrationTrendData.counts,
            smooth: true,
            areaStyle: {
              opacity: 0.3,
            },
            itemStyle: {
              color: "#1890ff",
            },
          },
        ],
      };

      this.registrationTrendChart.setOption(option);

      // 响应窗口大小变化
      window.addEventListener("resize", () => {
        this.registrationTrendChart.resize();
      });
    },

    // 初始化获奖情况图表
    initAwardChart() {
      const chartDom = this.$refs.awardChart;
      this.awardChart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "horizontal",
          bottom: "bottom",
          data: ["一等奖", "二等奖", "三等奖"],
        },
        series: [
          {
            name: "获奖情况",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: "#fff",
              borderWidth: 2,
            },
            label: {
              show: false,
              position: "center",
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "18",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: [
              {
                value: this.firstlevel,
                name: "一等奖",
                itemStyle: { color: "#ff4d4f" },
              },
              {
                value: this.secondlevel,
                name: "二等奖",
                itemStyle: { color: "#faad14" },
              },
              {
                value: this.thirdlevel,
                name: "三等奖",
                itemStyle: { color: "#52c41a" },
              },
            ],
          },
        ],
      };

      this.awardChart.setOption(option);

      // 响应窗口大小变化
      window.addEventListener("resize", () => {
        this.awardChart.resize();
      });
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },

    // 获取比赛状态文本
    getCompetitionStatus(status) {
      const statusMap = {
        0: "进行中",
        1: "已终止",
      };
      return statusMap[status] || "未知状态";
    },
  },
};
</script>

<style lang="less" scoped>
.dashboard-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100%;
}

.data-card {
  margin-bottom: 24px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.07);
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
  }

  :deep(.ant-statistic-title) {
    font-size: 16px;
    color: rgba(0, 0, 0, 0.65);
    margin-bottom: 16px;
  }

  :deep(.ant-statistic-content) {
    font-size: 28px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
  }

  :deep(.ant-statistic-content-prefix) {
    margin-right: 8px;
    font-size: 24px;
    color: #1890ff;
  }
}

.ant-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.07);

  :deep(.ant-card-head) {
    border-bottom: 1px solid #f0f0f0;
    padding: 0 24px;

    .ant-card-head-title {
      font-size: 16px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.85);
    }
  }
}
</style>
