<template>
  <div class="result-container">
    <el-card>
      <template #header>
        <page-header>
          <template #actions>
            <el-button @click="download">
              下载成绩单
            </el-button>
            <el-button @click="downloadDetailed">
              下载详细成绩单
            </el-button>
          </template>
          结果列表
        </page-header>
      </template>
      <paper shadow="sm" style="margin-bottom: 20px">
        <echarts style="width: 100%" :options="chartOptions" />
        <el-descriptions>
          <el-descriptions-item label="总计人数">
            {{ totalStudents }}
          </el-descriptions-item>
          <el-descriptions-item label="总计平均成绩">
            {{ totalAverage }}
          </el-descriptions-item>
          <el-descriptions-item label="有效人数">
            {{ committedStudents }}
          </el-descriptions-item>
          <el-descriptions-item label="有效平均成绩">
            {{ committedAverage }}
          </el-descriptions-item>
          <el-descriptions-item label="满分人数">
            {{ fullScoreStudents }}
          </el-descriptions-item>
          <el-descriptions-item label="满分比例">
            {{ fullScoreRatio }}
          </el-descriptions-item>
          <el-descriptions-item label="及格人数">
            {{ passedStudents }}
          </el-descriptions-item>
          <el-descriptions-item label="及格比例">
            {{ passedRatio }}
          </el-descriptions-item>
        </el-descriptions>
      </paper>
      <el-table :data="resultList">
        <el-table-column prop="id" label="#" width="200" />
        <el-table-column label="用户名">
          <template #default="scope">
            <span>{{ scope.row.owner.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最后提交时间">
          <template #default="scope">
            <span v-if="!scope.row.lastCommitAt">没有提交记录</span>
            <span v-else>{{ formatTimestamp(scope.row.lastCommitAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="成绩" width="200" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="text" @click="jumpToCodemirror" disabled>源码</el-button>
            |
            <el-button type="text" @click="jumpToResultDetail(scope.row.id)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import PageHeader from "@/components/PageHeader";
import Paper from "@/views/ProblemPage/components/Paper";
import Echarts from "@/components/Echarts";
import {ElMessage} from "element-plus";
import {formatTimestamp} from "@/utils/coder-utils";

export default {
  name: "ResultDetail",
  components: {Echarts, Paper, PageHeader},
  props: {},
  mounted() {
    this.fetchData();
  },
  data() {
    return {
      resultList: [],
      chartOptions: {
        tooltip: {
          show: true
        },
        xAxis: {
          data: [
            "未提交",
            "0-9",
            "10-19",
            "20-29",
            "30-39",
            "40-49",
            "50-59",
            "60-69",
            "70-79",
            "80-89",
            "90-99",
            "100"
          ]
        },
        yAxis: {
          name: "人数"
        },
        series: [
          {
            type: "bar",
            data: [],
            tooltip: {
              formatter: "{c}人"
            }
          }
        ]
      }
    };
  },
  computed: {
    summary() {
      return this.resultList
          .map((result) => result.score)
          .reduce((a = 0, b = 0) => a + b, 0) ?? 0;
    },
    totalStudents() {
      return this.resultList.length;
    },
    totalAverage() {
      return (this.summary / Math.max(this.totalStudents, 1)).toFixed(2);
    },
    committedStudents() { //该同学有提交历史就算有效提交
      return this.resultList
          .map(result => result.lastCommitAt ? 1 : 0)
          .reduce((a, b) => a + b, 0);
    },
    committedAverage() { //注意：无效提交成绩为0
      return (this.summary / Math.max(this.committedStudents, 1)).toFixed(2);
    },
    fullScoreStudents() {
      return this.resultList
          .map(result => result.score === 100)
          .reduce((a, b) => a + b, 0);
    },
    fullScoreRatio() {
      return (
          (
              (this.fullScoreStudents * 100) /
              Math.max(this.committedStudents, 1)
          ).toFixed(2) + "%"
      );
    },
    passedStudents() { //
      return this.resultList
          .map(result => result?.score ?? 0 >= 60)
          .reduce((a, b) => a + b, 0);
    },
    passedRatio() {
      return (
          (
              (this.passedStudents * 100) /
                  Math.max(this.committedStudents, 1)
          ).toFixed(2) + "%"
      );
    }
  },
  methods: {
    formatTimestamp,
    //根据考试Id， 获取考试成绩数据
    fetchData() {
      const { examId } = this.$route.params;
      this.$apis.getCoderResultByExamId(examId)
          .then(_res => {
            this.resultList = _res.data.res ?? [];
            console.log(this.resultList);
            //下面是两步操作
            //1 按照分数段分类
            //2 根据分数段，获取每个分数段的人数（返回数组）
            this.chartOptions.series[0].data = this.resultList.map(
                result => (result.lastCommitAt ? Math.floor((result.score ?? 0) / 10) : -1) + 1
            ).reduce((a, b) => {
              a[b]++;
              return a;
            }, new Array(12).fill(0));
          }).catch(_err => {
        ElMessage.error(_err);
      });
    },

    //TODO 下载考试成绩的认证过程，信息安全问题
    //下载考试成绩单
    download() {
      const { examId } = this.$route.params;
      window.open(`https://coder.seec.seecoder.cn/api/file/result/${examId}`);
    },
    //下载考试详细成绩单
    downloadDetailed() {
      const { examId } = this.$nuxt.$route.params;
      window.open(`https://coder.seec.seecoder.cn/api/file/result/${examId}/detailed`);
    },
    jumpToCodemirror() {
    },
    jumpToResultDetail(resultId) { //跳转到具体结果信息页
      this.$router.push(`${this.$route.path}/${resultId}`);
    }
  }

};
</script>

<style lang="scss" scoped>
.result-container {
  margin: 40px 10vw 80px 10vw;
  min-height: calc(100vh - 100px);
}

</style>
