<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 style="margin-right:15px;" class="_el-checkbox" :checked="checkAll"
        @change="_handleCheckAllChange">全选</el-checkbox>
      <el-checkbox-group style="display: inline-block" v-model="checkedClassInfos" @change="_handleCheckedClassChange">
        <el-checkbox class="_el-checkbox" v-for="classItem in classInfos" :key="classItem.classId"
          :label="classItem.classId">
          {{ classItem.className }}
        </el-checkbox>
      </el-checkbox-group>
      <el-button type="primary" style='float: right;' @click="_anys">分析</el-button>
    </div>
    <el-main>
      <div style="position: relative" Id="print-content">
        <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 print-hidden">
                <div style="float: right;margin-bottom: 20px;">
                  单题低分率：
                  <el-input-number class="parent-number" v-model="lowLevel" :min="1" :max="100" label="低分率">
                  </el-input-number>
                  <el-button style="margin-left:10px;" @click="_import" type="primary" class="opration-btn"
                    icon="el-icon-upload2">导出报表</el-button>
                  <el-button @click="_print" 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 testTranscript.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>
                  <el-tooltip effect="dark" :content="item.paperName" placement="left">
                    <span class="line-value">{{ item.paperName }}</span>
                  </el-tooltip> 
                </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="testTranscript.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="testTranscript.studentList || []">
                  <el-table-column :width="item.label == '学号' ? 120 : 0" :prop="item.prop" :label="item.label"
                    :key="index" v-for="(item, index) in testTranscript.studentHeader || []" />
                </el-table>
              </el-row>
              <el-row class="row-subfix" style="margin-top:10px">
                <el-table class="default-table"
                  v-if="testTranscript && testTranscript.question4List && testTranscript.question4List.length >= 1"
                  :data="testTranscript.question4List">
                  <el-table-column prop="column0" label="题号&答案" />
                  <el-table-column prop="column1" label="得分率">
                    <template slot-scope="scoped">
                      <div :class="Number(scoped.row.column1?.replace('%', '')) <= lowLevel ? 'lowLevelClass' : ''">
                        {{ scoped.row.column1 }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="column2" label="选项1" />
                  <el-table-column prop="column3" label="选项2" />
                  <el-table-column prop="column4" label="选项3" />
                  <el-table-column prop="column5" label="选项4" />
                  <el-table-column prop="column6" label="题号&答案" />
                  <el-table-column prop="column7" label="得分率">
                    <template slot-scope="scoped">
                      <div :class="Number(scoped.row.column7?.replace('%', '')) <= lowLevel ? 'lowLevelClass' : ''">
                        {{ scoped.row.column7 }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="column8" label="选项1" />
                  <el-table-column prop="column9" label="选项2" />
                  <el-table-column prop="column10" label="选项3" />
                  <el-table-column prop="column11" label="选项4" />
                  <el-table-column prop="column12" label="题号&答案" />
                  <el-table-column prop="column13" label="得分率">
                    <template slot-scope="scoped">
                      <div :class="Number(scoped.row.column13?.replace('%', '')) <= lowLevel ? 'lowLevelClass' : ''">
                        {{ scoped.row.column13 }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="column14" label="选项1" />
                  <el-table-column prop="column15" label="选项2" />
                  <el-table-column prop="column16" label="选项3" />
                  <el-table-column prop="column17" label="选项4" />
                </el-table>
              </el-row>
              <el-row class="row-subfix" style="margin-top:10px">
                <el-table class="default-table"
                  v-if="testTranscript && testTranscript.question7List && testTranscript.question7List.length >= 1"
                  :data="testTranscript.question7List">
                  <el-table-column prop="column0" label="题号&答案" />
                  <el-table-column prop="column1" label="得分率">
                    <template slot-scope="scoped">
                      <div :class="Number(scoped.row.column1?.replace('%', '')) <= lowLevel ? 'lowLevelClass' : ''">
                        {{ scoped.row?.column1 }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="column2" label="选项1" />
                  <el-table-column prop="column3" label="选项2" />
                  <el-table-column prop="column4" label="选项3" />
                  <el-table-column prop="column5" label="选项4" />
                  <el-table-column prop="column6" label="选项5" />
                  <el-table-column prop="column7" label="选项6" />
                  <el-table-column prop="column8" label="选项7" />
                  <el-table-column prop="column9" label="题号&答案" />
                  <el-table-column prop="column10" label="得分率">
                    <template slot-scope="scoped">
                      <div :class="Number(scoped.row.column10?.replace('%', '')) <= lowLevel ? 'lowLevelClass' : ''">
                        {{ scoped.row?.column10 }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="column11" label="选项1" />
                  <el-table-column prop="column12" label="选项2" />
                  <el-table-column prop="column13" label="选项3" />
                  <el-table-column prop="column14" label="选项4" />
                  <el-table-column prop="column15" label="选项5" />
                  <el-table-column prop="column16" label="选项6" />
                  <el-table-column prop="column17" label="选项7" />
                </el-table>
              </el-row>
              <el-row class="row-subfix">
                <el-table class="default-table"
                  v-if="testTranscript && testTranscript.question10List && testTranscript.question10List.length >= 1"
                  :data="testTranscript.question10List">
                  <el-table-column prop="column0" label="题号&答案" />
                  <el-table-column prop="column1" label="得分率">
                    <template slot-scope="scoped">
                      <div :class="Number(scoped.row.column1?.replace('%', '')) <= lowLevel ? 'lowLevelClass' : ''">
                        {{ scoped.row?.column1 }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="column2" label="选项1" />
                  <el-table-column prop="column3" label="选项2" />
                  <el-table-column prop="column4" label="选项3" />
                  <el-table-column prop="column5" label="选项4" />
                  <el-table-column prop="column6" label="选项5" />
                  <el-table-column prop="column7" label="选项6" />
                  <el-table-column prop="column8" label="选项7" />
                  <el-table-column prop="column9" label="选项8" />
                  <el-table-column prop="column10" label="选项9" />
                  <el-table-column prop="column11" label="选项10" />
                </el-table>
              </el-row>
              <el-row class="row-subfix">
                <el-table class="default-table" style="margin-top: 10px" :data="testTranscript.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.missPeopleNumber }}</span> 人
                      </span>
                      <span style="margin: 10px 0;"
                        v-for="(item, index) in scoped.row.details.filter(item => !item.right)">
                        选{{ item.option }}：{{ item.students.join("/") }}
                      </span>
                      <span></span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
            </div>
            <div style="height: 80px; width:240px;margin:20px auto;" class="print-hidden">
              <el-button type="default" :size="'small'" @click="_changePage('prev')">
                上一页</el-button>
              {{ currentPage || 0 }}/{{ totalPage || 0 }}
              <el-button type="default" style="margin-left:0px" :size="'small'"
                @click="_changePage('next')">下一页</el-button>
            </div>
            <div style="display: none;">
              <div id="test-print">
                <div v-for="(testTranscript, index) in testTranscriptDatas">
                  <div style="margin-top:20px">
                    <el-row class="row-subfix" :key="index" v-for="(item, index) in testTranscript.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="testTranscript.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="testTranscript.studentList || []">
                        <el-table-column :width="item.label == '学号' ? 120 : 0" :prop="item.prop" :label="item.label"
                          :key="index" v-for="(item, index) in testTranscript.studentHeader || []" />
                      </el-table>
                    </el-row>
                    <el-row class="row-subfix" style="margin-top:10px">
                      <el-table class="default-table"
                        v-if="testTranscript && testTranscript.question4List && testTranscript.question4List.length >= 1"
                        :data="testTranscript.question4List">
                        <el-table-column prop="column0" label="题号&答案" />
                        <el-table-column prop="column1" label="得分率" />
                        <el-table-column prop="column2" label="选项1" />
                        <el-table-column prop="column3" label="选项2" />
                        <el-table-column prop="column4" label="选项3" />
                        <el-table-column prop="column5" label="选项4" />
                        <el-table-column prop="column6" label="题号&答案" />
                        <el-table-column prop="column7" label="得分率" />
                        <el-table-column prop="column8" label="选项1" />
                        <el-table-column prop="column9" label="选项2" />
                        <el-table-column prop="column10" label="选项3" />
                        <el-table-column prop="column11" label="选项4" />
                        <el-table-column prop="column12" label="题号&答案" />
                        <el-table-column prop="column13" label="得分率" />
                        <el-table-column prop="column14" label="选项1" />
                        <el-table-column prop="column15" label="选项2" />
                        <el-table-column prop="column16" label="选项3" />
                        <el-table-column prop="column17" label="选项4" />
                      </el-table>
                    </el-row>
                    <el-row class="row-subfix" style="margin-top:10px">
                      <el-table class="default-table"
                        v-if="testTranscript && testTranscript.question7List && testTranscript.question7List.length >= 1"
                        :data="testTranscript.question7List">
                        <el-table-column prop="column0" label="题号&答案" />
                        <el-table-column prop="column1" label="得分率" />
                        <el-table-column prop="column2" label="选项1" />
                        <el-table-column prop="column3" label="选项2" />
                        <el-table-column prop="column4" label="选项3" />
                        <el-table-column prop="column5" label="选项4" />
                        <el-table-column prop="column6" label="选项5" />
                        <el-table-column prop="column7" label="选项6" />
                        <el-table-column prop="column8" label="选项7" />
                        <el-table-column prop="column9" label="题号&答案" />
                        <el-table-column prop="column10" label="得分率" />
                        <el-table-column prop="column11" label="选项1" />
                        <el-table-column prop="column12" label="选项2" />
                        <el-table-column prop="column13" label="选项3" />
                        <el-table-column prop="column14" label="选项4" />
                        <el-table-column prop="column15" label="选项5" />
                        <el-table-column prop="column16" label="选项6" />
                        <el-table-column prop="column17" label="选项7" />
                      </el-table>
                    </el-row>
                    <el-row class="row-subfix">
                      <el-table class="default-table"
                        v-if="testTranscript && testTranscript.question10List && testTranscript.question10List.length >= 1"
                        :data="testTranscript.question10List">
                        <el-table-column prop="column0" label="题号&答案" />
                        <el-table-column prop="column1" label="得分率" />
                        <el-table-column prop="column2" label="选项1" />
                        <el-table-column prop="column3" label="选项2" />
                        <el-table-column prop="column4" label="选项3" />
                        <el-table-column prop="column5" label="选项4" />
                        <el-table-column prop="column6" label="选项5" />
                        <el-table-column prop="column7" label="选项6" />
                        <el-table-column prop="column8" label="选项7" />
                        <el-table-column prop="column9" label="选项8" />
                        <el-table-column prop="column10" label="选项9" />
                        <el-table-column prop="column11" label="选项10" />
                      </el-table>
                    </el-row>
                    <el-row class="row-subfix">
                      <el-table class="default-table" style="margin-top: 10px"
                        :data="testTranscript.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.missPeopleNumber }}</span> 人
                            </span>
                            <span style="margin: 10px 0;"
                              v-for="(item, index) in scoped.row.details.filter(item => !item.right)">
                              选{{ item.option }}：{{ item.students.join("/") }}
                            </span>
                            <span></span>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-row>
                  </div>
                </div>
              </div>
            </div>

          </el-tab-pane>
          <el-tab-pane :name="'班级对比情况'" :label="`班级对比情况`" style="padding: 0 20px">
            <div style="float: right;margin-bottom: 20px;">
              <el-button @click="_studentLevelSet" class="green-el-button" type="primary">
                设置学生成绩等级
              </el-button>
              <el-button @click="_import" type="primary" class="opration-btn" icon="el-icon-upload2">导出报表</el-button>
              <el-button @click="_print" 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="60" />
              <el-table-column prop="className" label="班级" width="80" />
              <el-table-column label="测验人数/班级人数" width="180">
                <template slot-scope="scoped">
                  {{ scoped.row.testCount }} / {{ scoped.row.classCount }}
                </template>
              </el-table-column>
              <el-table-column prop="title" label="参与度" width="100">
                <template slot-scope="scoped">
                  {{ Number(scoped.row.testCount * 100 / scoped.row.classCount).toFixed(2) }}%
                </template>
              </el-table-column>
              <el-table-column prop="avg" label="班平均分" width="100" />
              <el-table-column prop="hight" label="班最高分" width="100" />
              <el-table-column prop="low" label="班最低分" width="100" />
              <el-table-column prop="front20" label="前20名均分" width="120" />
              <el-table-column prop="last20" label="后20名均分" width="120" />
              <el-table-column v-for="(item, index) in defaultLevels.levels" :key="index"
                :label="item[0] ? item[0] + '数(率)' : ''">
                <template slot-scope="scoped">
                  {{ scoped.row.leverValues[item[0]] }}
                </template>
              </el-table-column>
              <!-- <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-input-number class="parent-number" v-model="lowLevel" :min="1" :max="100" label="低分率">
              </el-input-number>
              <el-button @click="_import" type="primary" style="margin-left:10px" class="opration-btn"
                icon="el-icon-upload2">导出报表</el-button>
              <el-button @click="_print" type="primary" class="opration-btn" icon="el-icon-printer">打印报表</el-button>
            </div>
            <el-table class="default-table" :data="testPaperExamReport" :span-method="arraySpanMethod">
              <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="knowledge" label="知识点">
                <template slot-scope="scoped">
                  <el-tooltip effect="dark" :content="scoped.row.knowledge" placement="left">
                    <span class="overflowText">
                      {{ scoped.row.knowledge }}
                    </span>
                  </el-tooltip>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="满分值" width="120">
                <template slot-scope="scoped">
                  <div v-if="scoped.row.type == 'colspan'">
                    {{ Number(scoped.row.score).toFixed(2) }}
                  </div>
                  <div v-else>
                    {{ scoped.row.score }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="avgScore" label="年级平均分" width="120">
                <template slot-scope="scoped">
                  <div v-if="scoped.row.type == 'colspan' && scoped.row.questionType != '客观题'"
                    :class="Number(scoped.row.avgScore) < lowLevel ? 'lowLevelClass' : ''">
                    {{ Number(scoped.row.avgScore).toFixed(2) }} %
                  </div>
                  <div v-else>
                    {{ scoped.row.avgScore }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="gradeScoringRate" label="年级得分率" width="120">
                <template slot-scope="scoped">
                  <div v-if="scoped.row.type == 'colspan'"
                    :class="scoped.row.gradeScoringRate < lowLevel ? 'lowLevelClass' : ''">
                    {{ scoped.row.gradeScoringRate }} %
                  </div>
                  <div v-else="scoped.row.gradeScoringRate"
                    :class="Number(scoped.row.gradeScoringRate * 100) < lowLevel ? 'lowLevelClass' : ''">
                    {{ Number(scoped.row.gradeScoringRate * 100).toFixed(2) }} %
                  </div>
                </template>
              </el-table-column>
              <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["option" + index] == "?" ? "未答" : 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 @click="_import" type="primary" class="opration-btn" icon="el-icon-upload2">导出报表</el-button>
              <el-button @click="_print" 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="lever" label="成绩等级" />
            </el-table>
          </el-tab-pane>

        </el-tabs>
      </div>
    </el-main>
    <el-dialog :append-to-body="true" :close-on-click-modal="false" title="学生等级设置" :visible.sync="studentLevelDialog"
      width="900px" @closed="_studentLevelClose">
      <el-container class="default-body" style="background: transparent !important;">
        <el-main>
          <div class="default-main">
            <el-form class="use-form">
              <el-form-item class="use-form-item-box">
                <el-form-item label="等级设置模式" class="use-form-item">
                  <el-select size="small" v-model="fromData.levelType">
                    <el-option label="按分数比例" :value="0"></el-option>
                    <el-option label="按已考人数比例" :value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-form-item>
              <el-form-item>
                <div class="dia-tab-box">
                  <p class="dia-tab-tit">
                    <span class="item1 boxitem">序号</span>
                    <span class="item2 boxitem"><i>*</i>等级名称</span>
                    <span class="item3 boxitem"><i>*</i>等级最高</span>
                    <span class="item3 boxitem"><i>*</i>等级最低</span>
                    <span class="item boxitem">操作</span>
                  </p>
                  <div class="dia-tab-item" v-for="(item, index) in fromData.levels" :key="index">
                    <span class="item1 boxitem">{{ index + 1 }}</span>
                    <p class="item2 boxitem">
                      <el-input class="score-ipt" v-model="item[0]" :maxlength="12"
                        @keydown.native="keydownRange($event)"></el-input>
                    </p>
                    <p class="item3 boxitem">
                      <el-input class="score-ipt" type="number" v-model="item[1]" :min="item[2]"
                        :max="index == 0 ? 100 : fromData.levels[index - 1][2]"
                        @keydown.native="keydownRange($event)"></el-input>
                      <span class="descption">
                        %
                        <template v-if="fromData.levelType == 0">
                          (
                          {{ index != 0 ? "不含" : "" }}
                          {{ Number(((item[1] / 100) * examPaperScore).toFixed(1)) }}分
                          )
                        </template>
                        <template v-else>{{ index != 0 ? "不含" : "" }}</template>
                      </span>
                    </p>
                    <p class="item3 boxitem">
                      <el-input class="score-ipt" type="number" v-model="item[2]" :min="0" :max="item[1]"
                        @keydown.native="keydownRange($event)"></el-input>
                      <span class="descption">
                        %
                        <template v-if="fromData.levelType == 0">
                          ({{ Number(((item[2] / 100) * examPaperScore).toFixed(1)) }}分)
                        </template>
                      </span>
                    </p>
                    <p class="item boxitem">
                      <el-link type="danger" :underline="false" @click="fromData.levels.splice(index, 1)">删除</el-link>
                    </p>
                  </div>
                  <div class="add">
                    <p @click="fromData.levels.push(['', '', ''])">
                      <el-button size="mini" icon="el-icon-plus" circle type="primary"></el-button>添加一行
                    </p>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-main>
      </el-container>
      <div class="dialog-footer" slot="footer" align="right">
        <el-button type="info" :size="'small'" @click="studentLevelDialog = false">取 消</el-button>
        <el-button type="primary" class="green-el-button" :size="'small'" @click="_savefrom">保存</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { formatDate, downloadFile, tablePrint } from "utils";
export default {
  data() {
    return {
      studentLevelDialog: false,
      checkAll: true,
      isIndeterminate: true,
      title: "",
      defaultLevels: [],
      paperId: null,
      lowLevel: 20,
      anyLowLevel: 20,
      classInfos: [],
      examIds: [],
      testTranscriptDatas: [],
      testTranscript: {
        titleInfo: [],
        studentList: [],
        studentHeader: [],
        question4List: [],
        question7List: [],
        question10List: [],
        questionTotal: [],
      },
      currentPage: 0,
      totalPage: 0,
      checkedClassInfos: [],
      queryLoading: false,
      tabType: "0",
      examPaperScore: 100, //卷面最高分
      fromData: {
        levelType: 0,
        levels: [
          ["优秀", 100, 90],
          ["良好", 89.9, 70],
          ["合格", 69.9, 60],
          ["不合格", 59.9, 0],
        ],
      },
      studentMapping: [
        {
          key: "code",
          label: "学号",
        },
        {
          key: "name",
          label: "姓名",
        },
        {
          key: "gradeRank",
          label: "排名",
        },
        {
          key: "exam",
          label: "总分",
        },
        {
          key: "objective",
          label: "客观分",
        },
        {
          key: "subjective",
          label: "主观分",
        },
      ],
      testPaperExamReport: [],
      testPaperExamReportOptions: [],
      testStudentExamReport: [],
      classdiffExamReport: [],
    };
  },
  watch: {
    async tabType() {
      await this._anys();
    },
    async checkedClassInfos(value) {
      if (value?.length >= 1) {
        this.currentPage = 1;
        this.totalPage = value.length;
      } else {
        this.currentPage = 0;
        this.totalPage = 0;
      }
      this.tabType = '成绩测验单';
      this.checkAll = value.length >= this.classInfos.length;
      await this._anys();
    },
    async currentPage(value) {
      await this._testExamReport(value - 1);
    }
  },
  async created() {
    this.title = this.$route.query.title || "";
    this.paperId = this.$route.query.paperId;
    this.classInfos = JSON.parse(this.$route.query.classListStr);
    this.examIds = this.$route.query.examIds.split(',') || [];
    this.checkedClassInfos = this.classInfos?.map(item => item.classId);
    this.tabType = "成绩测验单";
    await this._queryDefaultLevels();
  },
  methods: {
    async _anys() {
      this.queryLoading = true;
      switch (this.tabType) {
        case "成绩测验单":
          await this._testExamReport(0);
          break;
        case "班级对比情况":
          await this._classdiffExamReport();
          break;
        case "试题分析表":
          await this._testPaperExamReport();
          break;
        case "学生成绩排行":
          await this._testStudentExamReport();
          break;
      }
      this.queryLoading = false;
    },
    async _queryDefaultLevels() {

      const { data, info, status } = await this.$request.gdefaultLevels();

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

      this.defaultLevels = { ...data } || {
        levelType: 0,
        levels: [
          ["优秀", 100, 90],
          ["良好", 89.9, 70],
          ["合格", 69.9, 60],
          ["不合格", 59.9, 0],
        ],
      };

      this.defaultLevels.type = 0

      this.fromData.levelType = this.defaultLevels.levelType;

      this.fromData.levels = [...this.defaultLevels.levels];

      sessionStorage.setItem(
        "levelFromData",
        JSON.stringify(this.defaultLevels)
      );
    },
    async _savefrom() {
      for (let i = 0; i < this.fromData.levels.length; i++) {
        if (this.fromData.levels[i].includes("")) {
          this.$message.warning("请补全编号" + (i + 1) + "设置信息！");
          return;
        }
      }
      if (this.fromData.levels.length == 0) {
        this.$message.warning("请添加等级设置！");
        return;
      }
      let nums = [];
      let ERR_OK = false;
      this.fromData.levels.map((item) => {
        nums.push(Number(item[1]));
        nums.push(Number(item[2]));
      });
      for (let i = 0; i < nums.length; i++) {
        if (nums[i + 1] && nums[i + 1] > nums[i]) {
          ERR_OK = true;
          this.$message.warning("高等级比例不能低于低等级比例！请检查");
          break;
        }
      }
      if (ERR_OK) return;
      this.tableData = [];
      this.tableData2 = [];
      this.defaultLevels.type = this.fromData.type;
      this.defaultLevels.levelType = this.fromData.levelType;
      this.defaultLevels.levels = [...this.fromData.levels];
      sessionStorage.setItem("levelFromData", JSON.stringify(this.fromData));
      this.studentLevelDialog = false;
      await this._anys();
      // await this._classdiffExamReport();
    },
    _studentLevelSet() {
      this.studentLevelDialog = true;
    },
    _studentLevelClose() {
      let levelFromData = sessionStorage.getItem("levelFromData");
      if (levelFromData) {
        levelFromData = JSON.parse(levelFromData);
        this.fromData.type = levelFromData.type;
        this.fromData.levelType = levelFromData.levelType;
        this.fromData.levels = [...levelFromData.levels];
      } else {
        this.fromData.type = 0;
        this.fromData.levelType = this.defaultLevels.levelType;
        this.fromData.levels = [...this.defaultLevels.levels];
      }
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (rowIndex == this.testPaperExamReport?.length - 3) {
        if (columnIndex == 0) {
          return [3, 1];
        }
        else if (columnIndex == 6) {
          return [3, 1];
        }
        else if (columnIndex == 7) {
          return [3, 5];
        }
        else {
          return [1, 1]
        }
      }
      else {
        return [1, 1]
      }

    },
    keydownRange(event) {
      if (event.key == "-" || event.key == "e") {
        event.returnValue = "";
      }
    },
    _changePage(status) {
      if (status == "next") {
        if (this.currentPage < this.checkedClassInfos.length) {
          this.currentPage += 1;
        }
      }
      else if (status == "prev") {
        if (this.currentPage > 1) {
          this.currentPage -= 1;
        }
      }
      else {
        this.$message.error('异常操作');
      }
    },
    _handleCheckAllChange(val) {
      this.checkAll = val;
      if (val) this.checkedClassInfos = this.classInfos.map(item => item.classId);
      else this.checkedClassInfos = [];
    },
    _handleCheckedClassChange(value) {

    },
    async _print() {
      if (this.tabType == '成绩测验单') {
        if (this.checkedClassInfos.length <= 0) {
          this.$message.error('请选中班级');
          return;
        }

        this.testTranscriptDatas = [];
        for (var page = 0; page < this.checkedClassInfos.length; page++) {
          this.testTranscriptDatas.push(await this._testExamReport(page));
        }
        setTimeout(() => {
          tablePrint("test-print", this.tabType);
        }, 500);
      }
      else {
        tablePrint("print-content", this.tabType);
      }
    },
    async _import() {
      let importRequest;
      switch (this.tabType) {
        case "成绩测验单": {
          importRequest = this.$request.tgexportPhaseExamReport;
        } break;
        case "班级对比情况": {
          importRequest = this.$request.tgexportPhaseExamReport2;
        } break;
        case "试题分析表": {
          importRequest = this.$request.tgexportPhaseExamReport3;
        } break;
        case "学生成绩排行": {
          importRequest = this.$request.tgexportPhaseExamReport4;
        } break;
      }

      let paramObj = JSON.parse(JSON.stringify(this.fromData))

      if (paramObj.levelType == 0) {
        paramObj.levels = paramObj.levels.map((item) => {
          item[1] = ((item[1] / 100) * this.examPaperScore).toFixed(1);
          item[2] = ((item[2] / 100) * this.examPaperScore).toFixed(1);
          return item;
        });
      }
      var data = await importRequest({
        paperId: this.paperId,
        classIds: this.checkedClassInfos ?? [],
        examIds: this.classInfos.
          filter(item =>
            this.checkedClassInfos.includes(item.classId)).map(ida => ida.examId),
        reportRange: paramObj
      })

      if (data) {
        let blob = new Blob([data], {
          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        });

        downloadFile(this.tabType + ".xlsx", blob);
      } else {
        this.$message.error("下载失败");
      }
    },
    _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 = type;
      }
      return tit;
    },
    async _testExamReport(page, type) {
      let demoTestTranscript = {
        titleInfo: [],
        studentList: [],
        studentHeader: [],
        question4List: [],
        question7List: [],
        question10List: [],
        questionTotal: [],
      };

      if (type != 1) {
        this.testTranscript = demoTestTranscript;
      }


      if (!this.checkedClassInfos || this.checkedClassInfos?.length <= 0) return;

      const request = this.$request.gTestExamReport;

      let response = await request({
        paperId: this.paperId,
        classIds: [this.checkedClassInfos[page]],
      });

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

      demoTestTranscript.titleInfo = response.data.titleInfos;

      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,
          });
        }
      }

      demoTestTranscript.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);
      }

      demoTestTranscript.studentList = [...studentResults];

      var show4Area = true;  //显示4选项区域

      var show7Area = true;  //显示7选项区域

      var show10Area = true;  //显示10选项区域

      var optionNumList = [];

      var maxOptions = 4;

      var minOptions = 10;  //最多10个选项

      var questionList = response.data.questionInfos;

      questionList = questionList.sort((prev, next) => { return prev.questionIndex - next.questionIndex });

      for (var i = 0; i < questionList.length; i++) {

        var correctAnswerValue = questionList[i].correctAnswer == "1" ? "✓" : questionList[i].correctAnswer == 2 ? "✗" : questionList[i].correctAnswer;

        var missCount = 0;

        var missI = questionList[i].details.filter(item => !item.right);

        missI.forEach(itemsa => {
          missCount = Number(missCount) + Number(itemsa.students?.length ?? 0)
        });

        demoTestTranscript.questionTotal.push({
          quesion: "Q" + (questionList[i].questionIndex),
          anwser: correctAnswerValue ?? "-----",
          details: questionList[i].details,
          missPeopleNumber: missCount
        })
        if ((questionList[i].questionType == 2)) {
          //单选题可能有超过4个选项，多选题是固定的
          if (questionList[i].details?.length > maxOptions) {
            maxOptions = questionList[i].details.filter(iam => { return iam.option.indexOf('未答') < 0 })?.length;
          }
          //单选题可能有超过4个选项，多选题是固定的
          if (questionList[i].details?.length < minOptions) {
            minOptions = questionList[i].details.filter(iam => { return iam.option.indexOf('未答') < 0 })?.length;
          }

          optionNumList.push(questionList[i].details.filter(iam => { return iam.option.indexOf('未答') < 0 })?.length);
        }

        if (questionList[i].questionType == 4) {
          minOptions = 2;
          optionNumList.push(2);
        }
      }

      console.log(demoTestTranscript.questionTotal)

      show4Area = minOptions <= 4;

      show7Area = optionNumList.filter(o => o > 4 && o <= 7);

      show10Area = optionNumList.filter(o => o > 7);


      var currentRow = {};

      if (show4Area) {

        var areaList = [];

        var quesRow = Math.ceil(questionList?.length * 1.00 / 3);

        for (var irow = 0; irow < quesRow; irow++) {
          areaList.push({});
        }

        for (var i = 0; i < questionList?.length; i++) {

          var col = parseInt(i / quesRow);

          var row = parseInt(i % quesRow);

          var question = questionList[i];

          var currentRow = areaList[row];

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

          var details = question.details.filter(fl => {
            return fl.option.indexOf('未答') < 0;
          });


          for (var ilr = 0; ilr < 6; ilr++) {

            if (ilr == 0) {
              currentRow['column' + Number(6 * col + ilr)] = question.questionIndex + correctAnswerValue;
            }
            else if (ilr == 1) {
              currentRow['column' + Number(6 * col + ilr)] = (question.gradeScoringRate * 100).toFixed(2) + '%';
            }
            else {

              var questionDetail = details[ilr - 2];

              var questionColumn = 'column' + Number(6 * col + ilr);

              if (details.length <= 4) {

                var questionOption = questionDetail ? (questionDetail.option == "1" ? "✓" : questionDetail.option == "2" ? "✗" : questionDetail.option) : "- -"

                if (questionOption != "- -") questionOption += "(" + questionDetail.persent + ")";

                currentRow[questionColumn] = questionOption;
              }
              else {
                currentRow[questionColumn] = "--";
              }
            }
          }
        }

        demoTestTranscript.question4List = [...areaList]

      }


      if (show7Area && show7Area.length > -1) {

        var areaList = [];

        var quesRow = Math.ceil(show7Area.length * 1.00 / 2);

        var num = 0;

        for (var irow = 0; irow < quesRow; irow++) {
          areaList.push({});
        }

        for (var i = 0; i < questionList?.length; i++) {

          var question = questionList[i];

          var details = question.details.filter(fl => {
            return fl.option.indexOf('未答') < 0;
          });

          if (question.questionType == 2 && details.length > 4 && details.length <= 7) {

            var col = parseInt(num / quesRow);

            var row = parseInt(num % quesRow);

            var currentRow = areaList[row];

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

            for (var ilr = 0; ilr < 9; ilr++) {

              if (ilr == 0) {
                currentRow['column' + Number(9 * col + ilr)] = question.questionIndex + correctAnswerValue;
              }
              else if (ilr == 1) {
                currentRow['column' + Number(9 * col + ilr)] = (question.gradeScoringRate * 100).toFixed(2) + '%';
              }
              else {

                var questionDetail = details[ilr - 2];

                var questionColumn = 'column' + Number(9 * col + ilr);

                currentRow[questionColumn] = questionDetail ? questionDetail.option + "(" + questionDetail.persent + ")" : "- -";
              }
            }

            num = num + 1;
          }

        }

        demoTestTranscript.question7List = [...areaList]
      }


      if (show10Area && show10Area.length > -1) {

        var areaList = [];

        var quesRow = show10Area.length;

        var num = 0;

        for (var irow = 0; irow < quesRow; irow++) {
          areaList.push({});
        }

        for (var i = 0; i < questionList?.length; i++) {

          var question = questionList[i];

          var details = question.details.filter(fl => {
            return fl.option.indexOf('未答') < 0;
          });

          if (question.questionType == 2 && details.length > 7) {
            var col = parseInt(num / quesRow);

            var row = num;

            var currentRow = areaList[row];

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

            for (var ilr = 0; ilr < 12; ilr++) {

              if (ilr == 0) {
                currentRow['column' + Number(12 * col + ilr)] = question.questionIndex + correctAnswerValue;
              }
              else if (ilr == 1) {
                currentRow['column' + Number(12 * col + ilr)] = (question.gradeScoringRate * 100).toFixed(2) + '%';
              }
              else {

                var questionDetail = details[ilr - 2];

                var questionColumn = 'column' + Number(12 * col + ilr);

                currentRow[questionColumn] = questionDetail ? questionDetail.option + "(" + questionDetail.persent + ")" : "- -";
              }
            }

            num = num + 1;
          }

        }

        demoTestTranscript.question10List = [...areaList]
      }


      return demoTestTranscript;

    },
    async _testPaperExamReport() {

      this.testPaperExamReport = [];

      this.testPaperExamReportOptions = [];

      if (!this.checkedClassInfos || this.checkedClassInfos?.length <= 0) return;

      const request = this.$request.gPaperExamReport;

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

      if (response.status != 0) {
        this.$message.error(response.info);
        return;
      }
      var maxOption = 0;
      response.data.forEach((item) => {
        if (item.details) {
          if (maxOption < item.details.length) {
            maxOption = item.details.length;
          }
        }

      })

      let optionsList = [];

      for (var io = 0; io < maxOption; io++) {
        optionsList.push({})
      }
      //主观
      var subjective = {
        sum: 0.0,
        avg: 0.0,
        rate: 0.0,
        number: 0
      };

      //客观
      var objective = {
        sum: 0.0,
        avg: 0.0,
        rate: 0.0,
        number: 0
      };

      //汇总
      var summary = {
        sum: 0.0,
        avg: 0.0,
        rate: 0.0,
        number: 0
      };

      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] = "?";
          }
        });

        summary.sum += parseFloat(item.score);
        summary.avg += parseFloat(item.avgScore);
        summary.rate += parseFloat(item.gradeScoringRate);
        summary.number += 1;
        if (item.questionType == 5) {
          subjective.sum += parseFloat(item.score);
          subjective.rate += parseFloat(item.gradeScoringRate);
          subjective.avg += parseFloat(item.avgScore);
          subjective.number += 1;
        }
        else {
          objective.sum += parseFloat(item.score);
          objective.rate += parseFloat(item.gradeScoringRate);
          objective.avg += parseFloat(item.avgScore);
          objective.number += 1;
        }
        return {
          ...item,
          ...params,
        };
      });

      this.testPaperExamReport = tableData?.sort((a, b) => {
        return Number(a.questionIndex) - Number(b.questionIndex);
      });

      this.testPaperExamReportOptions = [...optionsList];

      console.log(objective, subjective, summary, Number(objective.avg / objective.sum))
      this.testPaperExamReport.push({
        questionIndex: "汇总",
        questionType: "客观题",
        type: "colspan",
        score: objective.sum,
        avgScore: objective.avg == 0 ? 0 : Number(objective.avg).toFixed(2),
        gradeScoringRate: objective.avg == 0 ? 0 : Number(objective.avg * 100 / objective.sum).toFixed(2),
        correctAnswer: "备注"
      })

      this.testPaperExamReport.push({
        questionIndex: "主观题",
        type: "colspan",
        knowledge: subjective.sum,
        score: subjective.avg == 0 ? 0 : Number(subjective.avg).toFixed(2),
        avgScore: subjective.avg == 0 ? 0 : Number(subjective.avg * 100 / subjective.sum).toFixed(2)
      })

      this.testPaperExamReport.push({
        questionIndex: "合计",
        type: "colspan",
        knowledge: summary.sum,
        score: summary.avg == 0 ? 0 : Number(summary.avg).toFixed(2),
        avgScore: summary.avg == 0 ? 0 : Number(summary.avg * 100 / summary.sum).toFixed(2)
      })
    },
    async _testStudentExamReport() {
      this.testStudentExamReport = [];
      if (!this.checkedClassInfos || this.checkedClassInfos?.length <= 0) return;

      const request = this.$request.gStudentExamReport;

      let paramObj = JSON.parse(JSON.stringify(this.fromData))
      if (paramObj.levelType == 0) {
        paramObj.levels = paramObj.levels.map((item) => {
          item[1] = ((item[1] / 100) * this.examPaperScore).toFixed(1);
          item[2] = ((item[2] / 100) * this.examPaperScore).toFixed(1);
          return item;
        });
      }

      let response = await request({
        paperId: this.paperId,
        classIds: this.checkedClassInfos,
        reportRange: paramObj
      });

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

      this.testStudentExamReport = response.data;
    },
    async _classdiffExamReport() {

      this.classdiffExamReport = [];

      if (!this.checkedClassInfos || this.checkedClassInfos?.length <= 0) return;

      const request = this.$request.gClassdiffExamReport;

      let paramObj = JSON.parse(JSON.stringify(this.fromData))
      if (paramObj.levelType == 0) {
        paramObj.levels = paramObj.levels.map((item) => {
          item[1] = ((item[1] / 100) * this.examPaperScore).toFixed(1);
          item[2] = ((item[2] / 100) * this.examPaperScore).toFixed(1);
          return item;
        });
      }

      let response = await request({
        paperId: this.paperId,
        classIds: this.checkedClassInfos,
        reportRange: paramObj
      });

      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 {
  overflow: hidden; //超出宽度隐藏
  white-space: nowrap; //强制文字在一行
  text-overflow: ellipsis; //文字溢出显示省略号
  width: calc(33% - 2px);
  border: 1px solid #ebeef5;
  background: #f5f7fa;
  display: inline-block;
  height: 40px;
  line-height: 40px;

  .line-subfix {
    margin-left: 10px;
  }

}

.dia-tab-box {
  font-size: 14px;

  .boxitem {
    border: 1px solid #DCDFE6;
    margin: 0px !important;

    * {
      border: none;
    }
  }

  .dia-tab-tit,
  .dia-tab-item {


    i {
      color: #f30;
      padding-right: 5px;
    }

    display: flex;

    .item {
      width: 80px;
    }

    .item1 {
      padding-left: 10px;
      width: 10%;
    }

    .item2 {
      width: 18%;
    }

    .item3 {
      padding-left: 12px;
      flex: 1;
    }

    .score-ipt {
      width: 100px;
    }
  }

  .dia-tab-tit {
    background: rgb(245, 247, 250) !important
  }

  .add {
    display: flex;
    justify-content: center;
    margin: 0 auto;

    p {
      cursor: pointer;
    }

    .el-button {
      margin-right: 6px;
    }
  }
}
</style>
