<template>
  <el-container class="default-body">
    <el-header>
      <back-box class="detailBack">
        <template slot="title">
          <span class="default-title">
            {{ title }}
          </span>
        </template>
      </back-box>
    </el-header>
    <div class="default-filter">
      已考班级:
      <el-checkbox-group style="display: inline-block" v-model="checkedClassInfos" @change="_handleCheckedClassChange">
        <el-checkbox class="_el-checkbox" v-model="checkAll" @change="_handleCheckAllChange">全选</el-checkbox>
        <el-checkbox class="_el-checkbox" v-for="classItem in classInfos" :key="classItem.classId"
          :label="classItem.className">
          {{ classItem.className }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <el-main>
      <div style="position: relative">
        <el-tabs v-model="tabType" v-loading="queryLoading" type="card" class="default-tabs">
          <el-tab-pane :name="'成绩测验单'" :label="`成绩测验单`" style="padding: 0 20px">
            <div style="height: calc(100% - 80px);">
              <el-row class="row-subfix">
                <div style="float: right;margin-bottom: 20px;">
                  <el-button type="primary" class="opration-btn" icon="el-icon-upload2">导出报表</el-button>
                  <el-button type="primary" class="opration-btn" icon="el-icon-printer">打印报表</el-button>
                </div>
              </el-row>
              <el-row class="row-subfix" :key="index" v-for="(item, index) in titleInfo">
                <div class="row-line">
                  <span class="line-subfix">班级：</span>
                  <span class="line-value">{{ item.className }}</span>
                </div>
                <div class="row-line">
                  <span class="line-subfix">试卷名称：</span>
                  <span class="line-value">{{ item.paperName }}</span>
                </div>
                <div class="row-line">
                  <span class="line-subfix">测验时间：</span>
                  <span class="line-value">{{ item.testTime }}</span>
                </div>
              </el-row>
              <el-row class="row-subfix">
                <el-table class="default-table" style="margin-top: 10px" :data="titleInfo">
                  <el-table-column prop="testCount" label="测验人数" width="120" />
                  <el-table-column prop="avg" label="平均分" width="120" />
                  <el-table-column prop="hight" label="最高分" width="120" />
                  <el-table-column prop="low" label="最低分" width="120" />
                  <el-table-column prop="title" label="缺考名单">
                    <template slot-scope="scoped">
                      {{ scoped.row.miss.join("/") }}
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
              <el-row class="row-subfix">
                <el-table class="default-table" style="margin-top: 10px" :data="studentList">
                  <el-table-column :width="item.label == '学号' ? 120 : 0" :prop="item.prop" :label="item.label"
                    :key="index" v-for="(item, index) in studentHeader" />
                </el-table>
              </el-row>
              <el-row class="row-subfix">
                <el-table class="default-table" style="margin-top: 10px" :data="questionList">
                  <el-table-column :width="item.label == '题号&答案' ? 80 : 0" :prop="item.prop" :label="item.label"
                    :key="index" v-for="(item, index) in questionHeaders" />
                </el-table>
              </el-row>
              <el-row class="row-subfix" v-if="questionOtherList && questionOtherList.length >= 1">
                <el-table class="default-table" style="margin-top: 10px" :data="questionOtherList">
                  <el-table-column :prop="item.prop" :label="item.label" :key="index"
                    v-for="(item, index) in questionOtherHeaders" />
                </el-table>
              </el-row>
              <el-row class="row-subfix">
                <el-table class="default-table" style="margin-top: 10px" :data="questionTotal">
                  <el-table-column prop="quesion" label="题号" width="120" />
                  <el-table-column prop="anwser" label="答案" width="120" />
                  <el-table-column prop="student" label="答错学生">
                    <template slot-scope="scoped">
                      <span>总计 <span style="color:red;">
                          {{ scoped.row.details.filter(item => !item.isRight).length }}</span> 人
                      </span>
                      <span style="margin: 10px 0;"
                        v-for="(item, index) in scoped.row.details.filter(item => !item.isRight)">
                        选{{ item.option }}：{{ item.students.join("/") }}
                      </span>
                      <span></span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
            </div>
            <div style="height: 80px;">
              <el-pagination background layout="prev, pager, next" :total="testTranscriptCount">
              </el-pagination>
            </div> 
          </el-tab-pane>
          <el-tab-pane :name="'班级对比情况'" :label="`班级对比情况`" style="padding: 0 20px">
            <div style="float: right;margin-bottom: 20px;">
              <el-button type="primary" class="opration-btn" icon="el-icon-upload2">导出报表</el-button>
              <el-button type="primary" class="opration-btn" icon="el-icon-printer">打印报表</el-button>
            </div>
            <el-table class="default-table" :data="classdiffExamReport">
              <el-table-column prop="index" label="序号" width="120" />
              <el-table-column prop="className" label="班级" width="120" />
              <el-table-column label="测验人数/班级人数">
                <template slot-scope="scoped">
                  {{ scoped.row.testCount }} / {{ scoped.row.classCount }}
                </template>
              </el-table-column>
              <el-table-column prop="title" label="参与度" width="120">
                <template slot-scope="scoped">
                  {{ scoped.row.testCount / scoped.row.classCount }}
                </template>
              </el-table-column>
              <el-table-column prop="avg" label="班平均分" width="120" />
              <el-table-column prop="hight" label="班最高分" width="120" />
              <el-table-column prop="low" label="班最低分" width="120" />
              <el-table-column prop="front20" label="前20名均分" width="120" />
              <el-table-column prop="last20" label="后20名均分" width="120" />
              <el-table-column prop="excellenRate" label="优秀数(率)" width="120">
                <template slot-scope="scoped">
                  {{ scoped.row.excellenRate }}%
                </template>
              </el-table-column>
              <el-table-column prop="goodRate" label="良好数(率)" width="120">
                <template slot-scope="scoped">
                  {{ scoped.row.goodRate }}%
                </template>
              </el-table-column>
              <el-table-column prop="passRate" label="合格数(率)" width="120">
                <template slot-scope="scoped">
                  {{ scoped.row.passRate }}%
                </template>
              </el-table-column>
              <el-table-column prop="failedRate" label="不合格数(率)" width="120">
                <template slot-scope="scoped">
                  {{ scoped.row.passRate }}%
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane :name="'试题分析表'" :label="`试题分析表`" style="padding: 0 20px">
            <div style="float: right;margin-bottom: 20px;">
              <el-button type="primary" class="opration-btn" icon="el-icon-upload2">导出报表</el-button>
              <el-button type="primary" class="opration-btn" icon="el-icon-printer">打印报表</el-button>
            </div>
            <el-table class="default-table" :data="testPaperExamReport">
              <el-table-column prop="questionIndex" label="题号" width="120" />
              <el-table-column prop="questionType" label="题型" width="100">
                <template slot-scope="scope">
                  {{ setSubPro(scope.row.questionType) }}
                </template>
              </el-table-column>
              <el-table-column prop="score" label="知识点" />
              <el-table-column prop="score" label="满分值" width="120" />
              <el-table-column prop="avgScore" label="年级平均分" width="120" />
              <el-table-column prop="gradeScoringRate" label="年级得分率" width="120" />
              <el-table-column prop="correctAnswer" label="答案" width="120" />
              <el-table-column v-for="(item, index) in testPaperExamReportOptions" :key="index" :label="item.title"
                :prop="'count' + index" width="120">
                <template slot-scope="scope">
                  <p class="persent">
                    {{
              scope.row.questionType == "5"
                ? ""
                : scope.row["option" + index]
                  ? `${scope.row["option" + index]}(${scope.row["persent" + index] ?? "0"
                  })`
                  : ""
            }}
                  </p>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane :name="'学生成绩排行'" :label="`学生成绩排行`" style="padding: 0 20px">
            <div style="float: right;margin-bottom: 20px;">
              <el-button type="primary" class="opration-btn" icon="el-icon-upload2">导出报表</el-button>
              <el-button type="primary" class="opration-btn" icon="el-icon-printer">打印报表</el-button>
            </div>
            <el-table class="default-table" style="margin-top: 10px" :data="testStudentExamReport">
              <el-table-column prop="gradeRank" label="年级排行" />
              <el-table-column prop="code" label="学号" />
              <el-table-column prop="name" label="姓名" />
              <el-table-column prop="className" label="班级" />
              <el-table-column prop="exam" label="分数" />
              <el-table-column prop="title" label="成绩等级" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-main>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      checkAll: true,
      isIndeterminate: true,
      title: "",
      paperId: null,
      classInfos: [],
      checkedClassInfos: [],
      queryLoading: false,
      tabType: "0",
      testTranscriptCount: 0,
      titleInfo: [],
      studentList: [],
      studentHeader: [],
      studentMapping: [
        {
          key: "code",
          label: "学号",
        },
        {
          key: "name",
          label: "姓名",
        },
        {
          key: "gradeRank",
          label: "排名",
        },
        {
          key: "exam",
          label: "总分",
        },
        {
          key: "objective",
          label: "客观分",
        },
        {
          key: "subjective",
          label: "主观分",
        },
      ],
      questionList: [],
      questionHeaders: [],
      questionOtherList: [],
      questionOtherHeaders: [],
      questionTotal: [],
      testPaperExamReport: [],
      testPaperExamReportOptions: [],
      testStudentExamReport: [],
      classdiffExamReport: [],
    };
  },
  watch: {
    async tabType(value) {
      console.log(value);
      this.checkedClassInfos = this.classInfos;
      switch (value) {
        case "成绩测验单":
          await this._testExamReport();
          break;
        case "班级对比情况":
          await this._classdiffExamReport();
          break;
        case "试题分析表":
          await this._testPaperExamReport();
          break;
        case "学生成绩排行":
          await this._testStudentExamReport();
          break;
      }
    },
  },
  async created() {
    this.title = this.$route.query.title || "";

    this.paperId = this.$route.query.paperId;

    this.classInfos = JSON.parse(this.$route.query.classListStr);

    this.checkedClassInfos = this.classInfos;

    this.tabType = "成绩测验单";
  },
  methods: {
    _handleCheckAllChange(val) {
      // this.checkedClassInfos = val ? this.classInfos : [];
      // this.isIndeterminate = false;
    },
    _handleCheckedClassChange(value) {
      // let checkedCount = value.length;
      // this.checkAll = checkedCount === this.cities.length;
      // this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    _detailQ(id) { },
    setSubPro(type) {
      let tit;
      switch (type) {
        case 2:
          tit = "单选题";
          break;
        case 3:
          tit = "多选题";
          break;
        case 4:
          tit = "判断题";
          break;
        case 5:
          tit = "主观题";
          break;
        default:
          tit = "其他";
      }
      return tit;
    },
    async _testExamReport() {

      this.questionTotal = [];

      const request = this.$request.gTestExamReport;

      let response = await request({
        paperId: this.paperId,
        classIds: this.checkedClassInfos.map((item) => item.classId),
      });

      if (response.status != 0) {
        this.$message.error(response.info);
        return;
      }

      this.titleInfo = response.data.titleInfos;
      console.log(this.titleInfo)
      var studentHeaders = [];

      var studentResults = [];

      for (var iheader = 0; iheader < 3; iheader++) {
        for (
          var imapping = 0;
          imapping < this.studentMapping.length;
          imapping++
        ) {
          studentHeaders.push({
            prop: this.studentMapping[imapping].key + "_" + iheader,
            label: this.studentMapping[imapping].label,
            key: this.studentMapping[imapping].key,
          });
        }
      }

      this.studentHeader = [...studentHeaders];

      for (var isp = 0; isp < response.data.gradeExamStudentReports.length; isp++) {

        var item = {};

        for (
          var iamapping = 0;
          iamapping < studentHeaders.length;
          iamapping++
        ) {
          var currentData = response.data.gradeExamStudentReports[isp];

          if (!currentData) continue;

          var currentHeader = studentHeaders[iamapping];

          item[currentHeader.prop] = currentData[currentHeader.key];

          if (
            iamapping >= this.studentMapping.length - 1 &&
            iamapping % this.studentMapping.length == 0
          ) {
            isp += 1;
          }
        }

        studentResults.push(item);
      }

      this.studentList = [...studentResults];

      var otherDatas = [];

      var questionHeaders = [];

      var questionResults = [];

      var questionOtherHeaders = [];

      var questionOtherResults = [];

      var defaultQuestion = 6;

      var defaultCount = 3;

      var defaultQuestionCount = 4;

      var maxQuestionCount = 4;

      var optionSt = 1;

      for (var qheader = 0; qheader < defaultQuestion * defaultCount; qheader++) {
        if (qheader == 0 || qheader % 6 == 0) {
          questionHeaders.push({
            prop: "column_" + qheader,
            label: "题号&答案",
          });
          continue;
        } else if (qheader == 1 || (qheader - 1) % 6 == 0) {
          questionHeaders.push({
            prop: "column_" + qheader,
            label: "得分率",
          });
          optionSt = 1;
          continue;
        } else {
          questionHeaders.push({
            prop: "column_" + qheader,
            label: "选项" + optionSt,
          });
          optionSt += 1;
        }
      }

      var noPassIndex = 0;

      this.questionHeaders = questionHeaders;

      var itema = null;

      response.data.questionInfos = [...response.data.questionInfos]

      for (var qIndex = 0; qIndex < response.data.questionInfos.length; qIndex++) {

        var currentData = response.data.questionInfos[qIndex];

        var filterDetail = currentData.details.filter(fl => fl.option != '未答');

        var correctAnswerValue = currentData.correctAnswer == "1" ? "✓" : currentData.correctAnswer == 2 ? "✗" : currentData.correctAnswer;

        this.questionTotal.push({
          quesion: "Q" + (qIndex + 1),
          anwser: correctAnswerValue ?? "-----",
          details: currentData.details
        })

        if (filterDetail.length > defaultQuestionCount || filterDetail.length > maxQuestionCount) {
          currentData.index = qIndex;
          otherDatas.push(currentData);
          if (filterDetail.length > maxQuestionCount) {
            maxQuestionCount = filterDetail.length;
          }
          continue;
        }
        else {
          if (noPassIndex > defaultCount) {
            questionResults.push(itema)
            itema = null;
            noPassIndex = 0;
          }
          var stPass = noPassIndex * defaultQuestion;
          if (!itema) itema = {}

          var correctAnswerValue = currentData.correctAnswer == "1" ? "✓" : currentData.correctAnswer == 2 ? "✗" : currentData.correctAnswer;

          itema["column_" + (stPass)] = (qIndex + 1) + "" + correctAnswerValue;
          itema["column_" + (stPass + 1)] = (currentData.gradeScoringRate * 100) + "%";

          var value = "------";

          for (var iOption = 0; iOption < defaultQuestion - 2; iOption++) {
            var currentOption = filterDetail[iOption];
            if (currentOption) {
              var optionValue = currentOption.option == "1" ? "✓" : currentOption.option == 2 ? "✗" : currentOption.option;

              itema["column_" + (stPass + iOption + 2)] = optionValue + "(" + (currentOption.persent ?? "0%") + ")";
            }
            else {
              itema["column_" + (stPass + iOption + 2)] = value
            }
          }

          noPassIndex += 1
        }

        if (qIndex >= response.data.questionInfos.length - 1 && noPassIndex != 0) {
          questionResults.push(itema)
          itema = null;
        }
      }

      optionSt = 1;

      maxQuestionCount += 2;

      this.questionList = [...questionResults]

      var otherCount = parseInt(defaultQuestion * defaultCount / maxQuestionCount);

      itema = null;

      for (var qOHeader = 0; qOHeader < maxQuestionCount * otherCount; qOHeader++) {
        if (qOHeader == 0 || qOHeader % (maxQuestionCount) == 0) {
          questionOtherHeaders.push({
            prop: "column_" + qOHeader,
            label: "题号&答案",
          });
          continue;
        } else if (qOHeader == 1 || (qOHeader - 1) % (maxQuestionCount) == 0) {
          questionOtherHeaders.push({
            prop: "column_" + qOHeader,
            label: "得分率",
          });
          optionSt = 1;
          continue;
        } else {
          questionOtherHeaders.push({
            prop: "column_" + qOHeader,
            label: "选项" + optionSt,
          });
          optionSt += 1;
        }
      }

      this.questionOtherHeaders = questionOtherHeaders;

      noPassIndex = 0;

      for (var qOIndex = 0; qOIndex < otherDatas.length; qOIndex++) {

        var currentData = otherDatas[qOIndex];

        var filterDetail = currentData.details.filter(fl => fl.option != '未答');

        if (noPassIndex >= otherCount) {
          questionOtherResults.push(itema)
          itema = null;
          noPassIndex = 0;
        }

        var stPass = noPassIndex * maxQuestionCount;

        if (!itema) itema = {}

        var correctAnswerValue = currentData.correctAnswer == "1" ? "✓" : currentData.correctAnswer == 2 ? "✗" : currentData.correctAnswer;

        itema["column_" + (stPass)] = (Number(currentData.index) + 1) + "" + correctAnswerValue;

        itema["column_" + (stPass + 1)] = (currentData.gradeScoringRate * 100) + "%";

        var value = "------";

        for (var iOption = 0; iOption < maxQuestionCount - 2; iOption++) {

          var currentOption = filterDetail[iOption];

          if (currentOption) {

            var optionValue = currentOption.option == "1" ? "✓" : currentOption.option == 2 ? "✗" : currentOption.option;

            itema["column_" + (stPass + iOption + 2)] = optionValue + "(" + (currentOption.persent ?? "0%") + ")";
          }
          else {
            itema["column_" + (stPass + iOption + 2)] = value
          }
        }

        noPassIndex += 1

        if (qOIndex >= otherDatas.length - 1 && noPassIndex != 0) {

          questionOtherResults.push(itema)
          itema = null;
        }
      }

      this.questionOtherList = [...questionOtherResults]

    },
    async _testPaperExamReport() {
      const request = this.$request.gPaperExamReport;

      let response = await request({
        paperId: this.paperId,
        classIds: this.checkedClassInfos.map((item) => item.classId),
      });

      if (response.status != 0) {
        this.$message.error(response.info);
        return;
      }

      let optionsList = [{}, {}, {}, {}, {}];

      let tableData = response.data?.map((item) => {
        let params = {};
        const detail = item.details;
        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.testPaperExamReport = tableData?.sort((a, b) => {
        return a.questionIndex - b.questionIndex;
      });

      this.testPaperExamReportOptions = [...optionsList];

    },
    async _testStudentExamReport() {
      const request = this.$request.gStudentExamReport;

      let response = await request({
        paperId: this.paperId,
        classIds: this.checkedClassInfos.map((item) => item.classId),
      });

      if (response.status != 0) {
        this.$message.error(response.info);
        return;
      }

      this.testStudentExamReport = response.data;
    },
    async _classdiffExamReport() {
      const request = this.$request.gClassdiffExamReport;

      let response = await request({
        paperId: this.paperId,
        classIds: this.checkedClassInfos.map((item) => item.classId),
      });

      if (response.status != 0) {
        this.$message.error(response.info);
        return;
      }
      var index = 0;

      this.classdiffExamReport = response.data.map((item) => {
        item.index = index + 1;
        index += 1;
        return item;
      });
    },
    _delete() { },
  },
};
</script>
<style lang="scss">
._el-checkbox {
  * {
    height: 15px !important;
    line-height: 15px !important;
  }
}

.default-filter {
  padding: 10px !important;
}

.row-line {
  width: calc(33% - 2px);
  border: 1px solid #ebeef5;
  background: #f5f7fa;
  display: inline-block;
  height: 40px;
  line-height: 40px;

  .line-subfix {
    margin-left: 10px;
  }
}
</style>
