<template>
  <div class="table-box" ref="main" v-loading="loading">
    <div id="print-content">
      <!-- 多科多卷 -->
      <el-table :data="tableData" :max-height="tableMaxHeight" border style="width: 100%">
        <el-table-column prop="studentCode" label="学号" align="center" fixed></el-table-column>

        <el-table-column prop="studentName" label="姓名" fixed align="center">
          <template slot-scope="scoped"><span class="click-b" @click="toPortrait(scoped.row)">
              {{ scoped.row.studentName }}
            </span></template>
        </el-table-column>
        <el-table-column align="center" v-for="(item, index) in answerList" :key="index" :label="item">
          <el-table-column :prop="'examCount' + item" label="测练数" align="center"
            :class-name="index % 2 == 0 ? 'bg' : ''"></el-table-column>
          <el-table-column :prop="'participationCount' + item" label="参与数" align="center"
            :class-name="index % 2 == 0 ? 'bg' : ''"></el-table-column>
          <el-table-column :prop="'score' + item" label="总分" align="center"
            :class-name="index % 2 == 0 ? 'bg' : ''"></el-table-column>
          <el-table-column :prop="'classRank' + item" label="班名" align="center"
            :class-name="index % 2 == 0 ? 'bg' : ''"></el-table-column>
        </el-table-column>
        <el-table-column label="查看雷达图" align="center">
          <template slot-scope="scoped">
            <el-button @click="openChart(scoped.row)" type="primary" size="mini" circle
              icon="el-icon-arrow-right"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="down">
      <el-button @click="openDown" type="primary" plain round icon="fa fa-cloud-download">导出报表</el-button>
      <el-button v-if="!this.$store.getters.code" @click="print" type="primary" plain round
        icon="el-icon-printer">打印</el-button>
    </div>
    <el-dialog class="chart-dia" :visible.sync="chartDia" :title="chartTitle" width="800">
      <div class="chart-box">
        <RadarChart id="radarChart" :params="chartData" />
      </div>
    </el-dialog>
    <ExportDia :exportStudent="exportStudent" :diaShow="diaShow" @cancel="cancel" @exportData="exportData" />
  </div>
</template>
<script>
import RadarChart from "@/components/charts/radarChart"

import { downloadFile, tablePrint } from "@/utils";
export default {
  components: {
    RadarChart,
  },
  props: {
    role: "",
    ids: Array,
    classId: String,
    subjectName: String,
  },
  data() {
    return {
      tableMaxHeight: null,
      answerList: [], //设置多卷内容供tableStage表格数据用
      tableData: [],
      loading: false,
      exportLoading: false,
      chartData: {
        indicator: [
          {
            name: '', max: 100,
            axisLabel: {
              show: true,
              showMaxLabel: true,
            },
          },
        ],
        seriesData: []
      },
      chartDia: false,
      chartTitle: "",

      //导出相关
      diaShow: false,
      exportStudent: []
    }
  },
  computed: {
    subjectList: function () {
      return this.subjectName?.split(",")
    }
  },
  created() {
    this.phaseExamReport()
  },
  mounted() {
    this.tableMaxHeight = this.$refs.main.offsetHeight;
  },
  methods: {
    print() {
      tablePrint("print-content", this.title + this.tabList[this.type]);
    },
    toPortrait(obj) {
      //暂时不上线
      return;
      if (this.$store.getters.code) {
        return;
      }
      let subjectNames = [];
      subjectNames =
        this.role == "ROLE_BANZHUREN"
          ? [...this.query["subjectNames"]]
          : [this.query["subjectNames"]];
      if (
        this.query["subjectNames"] &&
        this.query["subjectNames"]?.length == 1 &&
        this.query["subjectNames"][0] == "全部"
      ) {
        subjectNames = this.subjectList.map((item) => {
          return item.value;
        });
        subjectNames?.shift();
      }
      //去学生画像
      this.$router.push({
        path: "/portraitDetail",
        query: {
          id: obj.studentId,
          classId: this.query.classId,
          subjectNames: subjectNames.join(","),
          studentName: obj.studentName,
          studentCode: obj.studentCode,
          startDay: this.query.startDay,
          endDay: this.query.endDay,
          date: this.date,
        },
      });
    },
    //查看雷达图
    openChart(obj) {

      this.chartTitle = obj.studentName + '-多科-多课时作答表现图'
      let max = 0;
      const dataList = obj.dataList.slice(1, obj.dataList.length)
      let subjectList = dataList.map(item => {
        let score = Number(item.highestScore || item.score)
        max = score > max ? score : max
        return item.subjectName
      })
      max += 10
      max = max > 150 ? 150 : max
      this.chartData = {
        indicator: [
          {
            name: '', max: max,
            axisLabel: {
              show: true,
              showMaxLabel: true,
            },
          },
        ],
        seriesData: []
      }
      subjectList.map((item, index) => {
        if (index < 1) {
          this.chartData.indicator[index].name = item
          this.chartData.indicator[index].max = max
        } else {
          this.chartData.indicator.push({ name: item, max: max })
        }
      })
      // 为了美观
      if (this.chartData.indicator.length < 3) {
        let num = this.chartData.indicator.length
        for (let i = 0; i < 6; i++) {
          if (i >= num) {
            this.chartData.indicator.push({ name: "", max: max })
          }
        }
      }
      this.chartData.seriesData = [
        {
          value: dataList.map(item => item.highestScore),
          name: '班级最高分'
        },
        {
          value: dataList.map(item => item.avgScore),
          name: '班平均分'
        },
        {
          value: dataList.map(item => item.score),
          name: '本人得分'
        },
      ]
      this.chartDia = true


    },
    async phaseExamReport() {
      this.loading = true;
      const { data, status, info } = await this.$request.cTPhaseExamReport({
        classId: this.classId,
        examIds: this.ids,
        subjectNames: this.subjectList,
      });
      this.loading = false;
      if (status === 0) {
        this.total = data.count;
        let subjectName = [];
        this.tableData = data?.list.map((item) => {
          let params = {};
          item.dataList.map((items, index) => {
            if (!subjectName.includes(items.subjectName)) {
              subjectName.push(items.subjectName);
            }
            params["examCount" + items.subjectName] = items.examCount;
            params["participationCount" + items.subjectName] =
              items.participationCount;
            params["score" + items.subjectName] = items.score;
            params["classRank" + items.subjectName] = items.classRank;
          });
          return {
            ...item,
            ...params,
          };
        });
        this.answerList = [...subjectName];
        this.exportStudent = [...this.tableData]
      } else {
        this.$message.error(info);
      }
    },
    //导出
    openDown() {
      this.diaShow = true;
    },
    cancel() {
      this.diaShow = false;
    },
    async exportData(arr) {
      if (this.exportLoading == true) return;
      this.exportLoading = true;
      let studentIds = arr
      let query = {};
      if (studentIds.length == this.exportStudent.length) {
        query.studentIds = []
      } else if (studentIds.length > 0) {
        query.studentIds = studentIds
      }
      const data = await this.$request.exportExamReport({
        classId: this.classId,
        examIds: this.ids,
        ...query
      });
      this.exportLoading = false;
      if (data) {
        let blob = new Blob([data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        downloadFile(
          this.status
            ? "即时测-已归档单卷测练报表.xlsx"
            : "即时测-单卷测练报表.xlsx",
          blob
        );
        this.$message.error("下载成功");
        this.cancel()
      } else {
        this.$message.error("下载失败");
      }
    },
  }
};
</script>
<style lang="scss" scoped>
.table-box {
  padding: 20px;
}

.down {
  padding-top: 20px;
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.chart-dia {
  .chart-box {
    width: 100%;
    height: 400px;
  }

  :deep(.el-dialog__body) {
    padding: 0 0 20px 0;
  }
}
</style>
