<template>
  <div ref="main" class="page-container">
    <back-box>
      <template slot="title">
        <span>单卷分析</span>
      </template>
    </back-box>
    <div class="tips" v-if="paperModifyLog.modifiedTime || status">
      <p class="tips-p">
        <i class="fa fa-bell-o"></i>
        {{
          `${paperModifyLog.modifiedTime} ${paperModifyLog.realName}`
        }}修改了答案，是否重新记分？
      </p>
      <div class="btn-box">
        <el-button type="danger" round @click="_ReScore" size="mini"
          >重新计分</el-button
        >
        <el-button
          type="danger"
          round
          plain
          size="mini"
          @click="paperModifyLog.modifiedTime = ''"
          >暂时不计</el-button
        >
      </div>
    </div>
    <div class="page-content">
      <div class="tab-box">
        <span
          v-for="(item, index) in tabList"
          :key="item"
          class="tab-item"
          :class="type == index + 1 ? 'active' : ''"
          @click="setType(index + 1)"
          >{{ item }}</span
        >
      </div>
      <div id="print-content" class="table-box" v-loading="loading">
        <el-table
          :max-height="tableMaxHeight"
          v-show="type == 1"
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column
            prop="questionIndex"
            label="题号"
            align="center"
            fixed
            width="60"
          ></el-table-column>
          <el-table-column
            prop="questionType"
            label="题型"
            align="center"
            fixed
            width="90"
            ><template slot-scope="scope">{{
              setSubPro(scope.row.questionType)
            }}</template></el-table-column
          >
          <el-table-column
            prop="score"
            width="90"
            label="满分值"
            sortable
            align="center"
          ></el-table-column>
          <el-table-column
            width="100"
            prop="highestScore"
            label="班最高分"
            sortable
            align="center"
          ></el-table-column>
          <el-table-column
            width="100"
            prop="lowestScore"
            label="班最低分"
            sortable
            align="center"
          ></el-table-column>
          <el-table-column
            width="100"
            prop="avgScore"
            label="班平均分"
            sortable
            align="center"
          ></el-table-column>
          <el-table-column
            prop="classScoringRate"
            width="110"
            sortable
            label="班级得分率"
            align="center"
            ><template slot-scope="scoped"
              ><span :class="scoped.row.classScoringRate < 60 ? 'error' : ''"
                >{{ scoped.row.classScoringRate }}%</span
              ></template
            ></el-table-column
          >
          <el-table-column prop="correctAnswer" label="答案" align="center"
            ><template slot-scope="scoped">{{
              scoped.row.correctAnswer == 1
                ? "✓"
                : scoped.row.correctAnswer == 2
                ? "✗"
                : scoped.row.correctAnswer
            }}</template>
          </el-table-column>
          <el-table-column
            v-for="(item, index) in optionsList"
            :key="index"
            :label="item.title"
            :prop="'count' + index"
            align="center"
            width="90"
            ><template slot-scope="scope"
              ><p class="persent">
                {{
                  scope.row.questionType == "5"
                    ? ""
                    : scope.row["option" + index]
                    ? `${scope.row["option" + index]}(${
                        scope.row["persent" + index]
                      })`
                    : ""
                }}
              </p></template
            >
          </el-table-column>
        </el-table>
        <div class="hui-box" v-show="type == 1">
          <span class="s-txt">汇总</span>
          <ul class="hui-ul">
            <li class="hui-li">
              <span class="hui-s s1">主观题</span>
              <span class="hui-s s1">{{ examReport.subjectiveScore }}</span>
              <span class="hui-s s2">{{
                examReport.subjectiveHighestScore
              }}</span>
              <span class="hui-s s2">{{
                examReport.subjectiveLowestScore
              }}</span>
              <span class="hui-s s2">{{ examReport.subjectiveAvgScore }}</span>
              <span
                class="hui-s s3"
                :class="
                  examReport.subjectiveClassScoringRate < 60 ? 'error' : ''
                "
                >{{ examReport.subjectiveClassScoringRate }}%</span
              >
            </li>
            <li class="hui-li">
              <span class="hui-s s1">客观题</span>
              <span class="hui-s s1">{{ examReport.objectiveScore }}</span>
              <span class="hui-s s2">{{
                examReport.objectiveHighestScore
              }}</span>
              <span class="hui-s s2">{{
                examReport.objectiveLowestScore
              }}</span>
              <span class="hui-s s2">{{ examReport.objectiveAvgScore }}</span>
              <span
                class="hui-s s3"
                :class="
                  examReport.objectiveClassScoringRate < 60 ? 'error' : ''
                "
                >{{ examReport.objectiveClassScoringRate }}%</span
              >
            </li>
            <li class="hui-li">
              <span class="hui-s s1">整卷</span>
              <span class="hui-s s1">{{ examReport.examPaperScore }}</span>
              <span class="hui-s s2">{{ examReport.highestScore }}</span>
              <span class="hui-s s2">{{ examReport.lowestScore }}</span>
              <span class="hui-s s2">{{ examReport.avgScore }}</span>
              <span
                class="hui-s s3"
                :class="examReport.classScoringRate < 60 ? 'error' : ''"
                >{{ examReport.classScoringRate }}%</span
              >
            </li>
          </ul>
        </div>
        <el-table
          v-show="type == 2"
          :max-height="tableMaxHeight"
          :data="tableData2"
          border
          style="width: 100%"
          :default-sort="{ prop: 'dadui', order: 'descending' }"
        >
          <el-table-column
            prop="studentCode"
            label="学号"
            align="center"
            fixed
          ></el-table-column>
          <el-table-column
            prop="studentName"
            label="姓名"
            fixed
            align="center"
          ></el-table-column>
          <el-table-column
            prop="examScore"
            label="总分"
            sortable
            align="center"
          ></el-table-column>
          <el-table-column
            prop="scoringRate"
            label="得分率"
            sortable
            align="center"
            ><template slot-scope="scope"
              >{{ scope.row.scoringRate }}%</template
            ></el-table-column
          >
          <el-table-column
            prop="classRank"
            label="班名"
            sortable
            align="center"
          ></el-table-column>
          <el-table-column label="客观题" align="center">
            <el-table-column
              prop="objectiveExamScore"
              label="得分"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="objectiveScoringRate"
              label="得分率"
              align="center"
              ><template slot-scope="scope"
                >{{ scope.row.objectiveScoringRate }}%</template
              ></el-table-column
            >
          </el-table-column>
          <el-table-column label="主观题" align="center">
            <el-table-column
              prop="subjectiveExamScore"
              label="得分"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="subjectiveScoringRate"
              label="得分率"
              align="center"
              ><template slot-scope="scope"
                >{{ scope.row.subjectiveScoringRate }}%</template
              ></el-table-column
            >
          </el-table-column>
        </el-table>
        <el-table
          v-show="type == 3"
          :max-height="tableMaxHeight"
          :data="tableData2"
          border
          style="width: 100%"
          :default-sort="{ prop: '', order: 'descending' }"
        >
          <el-table-column
            prop="studentCode"
            label="学号"
            fixed
            align="center"
          ></el-table-column>
          <el-table-column
            prop="studentName"
            label="姓名"
            fixed
            align="center"
          ></el-table-column>
          <el-table-column
            prop="examScore"
            label="总分"
            sortable
            align="center"
          ></el-table-column>
          <el-table-column label="分数组成" align="center">
            <el-table-column
              prop="objectiveExamScore"
              label="客观题分"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="subjectiveExamScore"
              label="主观题分"
              align="center"
            ></el-table-column>
          </el-table-column>
          <el-table-column
            align="center"
            v-for="(item, index) in questionList"
            :key="index"
            :label="'Q' + item.id"
            :prop="'score' + item.id"
            :width="questionList.length > 9 ? 60 : 'auto'"
          >
          </el-table-column>
        </el-table>
        <el-table
          :max-height="tableMaxHeight"
          v-show="type == 4"
          :data="tableData2"
          border
          style="width: 100%"
          :default-sort="{ prop: '', order: 'descending' }"
        >
          <el-table-column
            prop="studentCode"
            label="学号"
            fixed
            align="center"
            width="110"
          ></el-table-column>
          <el-table-column
            prop="studentName"
            label="姓名"
            fixed
            align="center"
          ></el-table-column>
          <el-table-column
            prop="className"
            label="班级"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="examScore"
            label="总分"
            sortable
            align="center"
          ></el-table-column>
          <el-table-column
            align="center"
            v-for="(item, index) in questionList"
            :key="index"
            :label="'Q' + item.id"
            :width="questionList.length > 9 ? 60 : 'auto'"
          >
            <template slot-scope="scope">
              <span v-if="tableData[index]?.questionType == 5">*</span>
              <span
                v-else-if="scope.row['answer' + item.id]"
                :class="scope.row['isRight' + item.id] ? '' : 'error'"
              >
                {{ scope.row["answer" + item.id] }}
              </span>
              <span
                v-else
                :class="scope.row['questionType' + item.id] == 5 ? '' : 'error'"
                >-</span
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="down">
        <div>
          <el-button
            @click="exportData"
            type="primary"
            plain
            round
            icon="fa fa-cloud-download"
            >导出报表</el-button
          >
          <el-button
            @click="print"
            type="primary"
            plain
            round
            icon="el-icon-printer"
            >打印</el-button
          >
        </div>
        <div v-if="!status">
          <el-button
            v-if="examReport.subjectiveScore != 0"
            @click="diaUp = true"
            type="primary"
            round
            v-loading="exportLoading"
            >导入主观题分数</el-button
          >
          <template v-if="role == 'ROLE_JIAOSHI'">
            <el-button
              @click="edit"
              type="primary"
              v-if="examReport.subjectiveScore != examReport.examPaperScore"
              round
              >查看题目</el-button
            ></template
          >
        </div>
      </div>
      <el-dialog title="导入主观题分数" :visible.sync="diaUp" width="600">
        <up-load :url="url" :examId="id" @upSuccess="upSuccess">
          <template slot="down">
            <p class="down-txt">
              第一步：下载模板并编辑完成学生分数
              <el-link type="danger" @click="downExcel">模板下载</el-link> 。
            </p>
            <p class="down-txt">第二步：上传完成编辑的模板文件并导入。</p>
          </template>
        </up-load>
        <div class="dialog-footer" slot="footer">
          <el-button @click="diaUp = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { downloadFile, tablePrint } from "@/utils";
export default {
  data() {
    return {
      role: "",
      status: 0,
      tableMaxHeight: 600,
      loading: false,
      exportLoading: false,
      diaUp: false,
      url: "/api_html/personal/importSubjectiveScore",
      id: "",
      title: "",
      score: "",
      type: 1,
      tabList: ["试题分析", "成绩排名", "小题分报表", "作答明细表"],
      paperModifyLog: {
        realName: "",
        modifiedTime: "",
      },
      examReport: {
        subjectiveScore: 0,
        subjectiveHighestScore: "",
        subjectiveLowestScore: "",
        subjectiveAvgScore: "",
        subjectiveClassScoringRate: "",
        objectiveScore: "",
        objectiveHighestScore: "",
        objectiveLowestScore: "",
        objectiveAvgScore: "",
        objectiveClassScoringRate: "",
        examPaperScore: "",
        highestScore: "",
        lowestScore: "",
        avgScore: "",
        classScoringRate: "",
      },
      tableData: [],
      optionsList: [],
      tableData2: [],
      questionList: [],
      page: 1,
      size: 20,
      total: 0,
    };
  },
  created() {
    this.role =
      this.$store.getters.info.showRole ||
      this.$store.getters.info.permissions[0].role;
    this.id = this.$route.query.id;
    this.status = this.$route.query.status ? this.$route.query.status : 0;
    this.title = this.$route.query.title || "";
    this._QueryData();
  },
  methods: {
    print() {
      tablePrint("print-content", this.title + this.tabList[this.type - 1]);
    },
    upSuccess(res) {
      //导入成功
      this.$message.success("导入成功");
      this.diaUp = false;
      this._QueryData();
    },
    setType(type) {
      console.log(this.$refs.main.offsetHeight - 50);
      this.tableMaxHeight = this.$refs.main.offsetHeight;
      this.type = type;
    },
    setSubPro(type) {
      let tit;
      switch (type) {
        case 2:
          tit = "单选题";
          break;
        case 3:
          tit = "多选题";
          break;
        case 4:
          tit = "判断题";
          break;
        case 5:
          tit = "主观题";
          break;
      }
      return tit;
    },
    edit() {
      this.$router.push({
        path: "/examinationPaperEdit",
        query: {
          paperId: this.id,
          title: this.title,
          type: 2,
        },
      });
    },
    changePage(page) {
      this.page = page;
      this.examQuestionReport();
    },
    async downExcel() {
      let data = await this.$request.pSubjectiveScoreTemplate({
        examId: this.id,
      });
      if (data && !data.code) {
        let blob = new Blob([data], {
          type: "application/vnd.ms-excel;charset=utf-8",
        });
        downloadFile(`主观题模版.xlsx`, blob);
      } else {
        this.$message.error(data.info);
      }
    },
    async _QueryData() {
      this.examDetail();
      this.examStudentReport();
      this.examQuestionReport();
    },
    async examDetail() {
      //详情
      this.loading = true;
      let { data, info, status } = await this.$request.pExamDetail({
        examId: this.id,
      });
      this.loading = false;
      if (status === 0) {
        if (data.paperModifyLog) {
          this.paperModifyLog = { ...data?.paperModifyLog };
        }
        this.examReport = { ...data?.examReport };
      } else {
        this.$message.error(info);
      }
    },
    async _ReScore() {
      //重新记分
      this.loading = true;
      let { data, info, status } = await this.$request.pReScore({
        examId: this.id,
      });
      this.loading = false;
      if (status === 0) {
        this.$message.success(info);
        this._QueryData();
        this.paperModifyLog.modifiedTime = "";
        this.paperModifyLog.realName = "";
      } else {
        this.$message.error(info);
      }
    },
    async examStudentReport() {
      //成绩排名-小题分-作答明细
      this.loading = true;
      let { data, info, status } = await this.$request.pExamStudentReport({
        examId: this.id,
      });
      this.loading = false;
      if (status === 0) {
        let optionsList = [];
        this.tableData2 = data?.list.map((item) => {
          let params = {};

          const detail = JSON.parse(item.detail);
          if (detail.length > optionsList.length) {
            optionsList = [...detail];
          }
          detail.map((items, index) => {
            params["que" + items.id] = items.id;
            params["score" + items.id] = String(items.score).includes(".")
              ? Number(items.score).toFixed(2)
              : items.score;
            params["answer" + items.id] =
              items.answer == 1 ? "✓" : items.answer == 2 ? "✗" : items.answer;
            params["isRight" + items.id] = items.isRight;
            params["questionType" + items.id] = items.questionType;
          });
          return {
            ...item,
            ...params,
          };
        });
        console.log();
        this.questionList = optionsList.sort((a, b) => {
          return a.id - b.id;
        });
      } else {
        this.$message.error(info);
      }
    },
    async examQuestionReport() {
      //试题分析
      this.loading = true;
      let { data, info, status } = await this.$request.pExamQuestionReport({
        examId: this.id,
        page: this.page,
        // size: this.size,
        size: 9999,
      });
      this.loading = false;
      if (status === 0) {
        let optionsList = [{}, {}, {}, {}, {}];
        let tableData = data?.list.map((item) => {
          let params = {};
          const detail = JSON.parse(item.detail);
          let lastOPtion = detail?.find((item) => {
            return item.option == "未答";
          });
          let defaultArr = detail?.filter((item) => {
            return item.option != "未答";
          });

          optionsList.map((items, index) => {
            if (index != 4) {
              params["count" + index] =
                defaultArr[index]?.option != "未答"
                  ? defaultArr[index]?.count
                  : "";
              params["persent" + index] =
                defaultArr[index]?.option != "未答"
                  ? defaultArr[index]?.persent
                  : "";
              params["option" + index] =
                defaultArr[index]?.option != "未答"
                  ? defaultArr[index]?.option == 1
                    ? "✓"
                    : defaultArr[index]?.option == 2
                    ? "✗"
                    : defaultArr[index]?.option
                  : "";
              items["title"] = "选项" + (index + 1);
            } else {
              items["title"] = "未答";
              params["count" + index] = lastOPtion.count;
              params["persent" + index] = lastOPtion.persent;
              params["option" + index] = "?";
            }
          });
          return {
            ...item,
            ...params,
          };
        });
        this.tableData = tableData.sort((a, b) => {
          return a.questionIndex - b.questionIndex;
        });
        this.optionsList = [...optionsList];
        this.total = data.count;
        this.setType(1);
      } else {
        this.$message.error(info);
      }
    },
    //导出
    async exportData() {
      if (this.exportLoading == true) return;
      this.exportLoading = true;
      const data = await this.$request.pExportExamReport({
        examId: this.id,
      });
      this.exportLoading = false;
      if (data) {
        let blob = new Blob([data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });
        downloadFile("即时测-单卷测练报表.xlsx", blob);
      } else {
        this.$message.error("下载失败");
      }
    },
  },
};
</script>
<style>
div::-webkit-scrollbar {
  width: 3px;
  height: 10px;
}
div::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color: #ccc;
}
</style>
<style lang="scss" scoped>
.page-container {
  position: relative;
  height: 100%;
  .table-box {
    min-height: 100%;
  }
}
.print-box {
  display: none;
}
.persent {
  white-space: nowrap;
  font-size: 14px;
}
.error {
  color: #f30;
}
.page-content {
  padding: 20px 20px 0;
}
.tips {
  height: 48px;
  box-sizing: border-box;
  line-height: 48px;
  padding: 0 16px;
  border: 1px solid #fac7cc;
  border-radius: 5px;
  background-color: #ffebec;
  font-size: 14px;
  color: #fd9795;
  margin: 10px 20px 0 20px;
  display: flex;
  &-p {
    flex: 1;
  }
  .fa-bell-o {
    font-size: 18px;
    margin-right: 5px;
  }
}
.tab-box {
  width: 800px;
  margin: 0 auto 12px;
  background: #f8f8f8;
  border-radius: 20px;
  display: flex;
  user-select: none;
  .tab-item {
    flex: 1;
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 16px;
    color: #666;
    font-weight: 500;
    background: transparent;
    border-radius: 20px;
    cursor: pointer;
    &.active {
      background: #667ffd;
      color: #fff;
    }
  }
}
.down {
  padding-top: 20px;
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.hui-box {
  display: flex;
  text-align: center;
  .s-txt {
    width: 61px;
    line-height: 144px;
    background: #e2e2e2;
    font-size: 16px;
    color: #fff;
    font-weight: 700;
  }
  .hui-ul {
    border-top: 1px solid #e2e2e2;
  }
  .hui-li {
    display: flex;
    .hui-s {
      height: 48px;
      line-height: 48px;
      border-right: 1px solid #e2e2e2;
      border-bottom: 1px solid #e2e2e2;
      box-sizing: border-box;
    }
    .s1 {
      width: 90px;
    }
    .s2 {
      width: 100px;
    }
    .s3 {
      width: 110px;
    }
  }
}
</style>