<template>
  <div class="inspect-course-exam-analysis">
    <div class="page-head page-head-flex">
      <h2>
        <span>考查课程考试分析</span>
      </h2>
      <div v-if="orgName">
        <i class="icon icon-sign"></i>考查学院：{{ orgName }}
      </div>
    </div>
    <div class="part-box part-box-filter" v-if="setReady">
      <el-form ref="FilterForm" label-position="left" label-width="60px" inline>
        <el-form-item label="学期：">
          <semester-select
            v-model="filter.semesterId"
            :select-default="selectDefault"
            :clearable="false"
            @change="semesterChange"
          ></semester-select>
        </el-form-item>
        <el-form-item label="考试：">
          <exam-select
            ref="ExamSelect"
            v-model="filter.examId"
            :select-default="selectDefault"
            :clearable="false"
            :semester-id="filter.semesterId"
            @change="examChange"
          ></exam-select>
        </el-form-item>
        <el-form-item label="课程：">
          <course-select
            ref="CourseSelect"
            v-model="filter.courseCode"
            :exam-id="filter.examId"
            :select-default="selectDefault"
            :clearable="false"
            inspect
            @change="courseChange"
          ></course-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" round @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20" type="flex">
      <el-col :span="12">
        <div class="part-box part-box-pad">
          <div class="part-box-head">
            <h3>
              <span>考试概况</span>
              <el-popover
                popper-class="el-popper-dark"
                placement="right-start"
                width="300"
                trigger="hover"
              >
                <i class="el-icon-question" slot="reference"></i>
                <div>
                  <p>1.统计成绩范围包含应届、非应届类型的考生数据；</p>
                  <p>
                    2.有效人数：成绩有效的实考人数
                  </p>
                </div>
              </el-popover>
            </h3>
          </div>
          <div class="summary-info">
            <div class="summary-info-row">
              <div class="summary-info-item">
                <i class="summary-info-icon"><i class="icon icon-start"></i></i>
                <p>考试时间</p>
                <p>{{ summary.examTime | timestampFilter }}</p>
              </div>
              <div class="summary-info-item">
                <i class="summary-info-icon"
                  ><i class="icon icon-course"></i
                ></i>
                <p>课程</p>
                <p>{{ summary.courseName }}</p>
              </div>
            </div>
            <div class="summary-info-row">
              <div class="summary-info-item">
                <i class="summary-info-icon"><i class="icon icon-full"></i></i>
                <p>满分</p>
                <p>{{ summary.totalScore }}</p>
              </div>
              <div class="summary-info-item">
                <i class="summary-info-icon"><i class="icon icon-users"></i></i>
                <p>全校应届实考</p>
                <p>{{ summary.schRealityCount }}人</p>
              </div>
              <div class="summary-info-item">
                <i class="summary-info-icon"><i class="icon icon-users"></i></i>
                <p>本院应届实考</p>
                <p>{{ summary.colRealityCount }}人</p>
              </div>
              <div class="summary-info-item">
                <i class="summary-info-icon"
                  ><i class="icon icon-absent"></i
                ></i>
                <p>本院应届缺考/违纪</p>
                <p>{{ summary.colAbsentCount }}人</p>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="part-box part-box-pad">
          <div class="part-box-head">
            <h3>
              <span>本院与全校成绩分布</span>
              <el-popover
                popper-class="el-popper-dark"
                placement="right-start"
                width="300"
                trigger="hover"
              >
                <i class="el-icon-question" slot="reference"></i>
                <div>
                  <p>
                    若成绩趋势相对集中，且处于“正态分布”，说明本次考试基本达到了教学要求。相反，若考试成绩趋势相对集中，但呈现“正偏态分布”或“负偏态分布”，则说明考试总体难度过低或过高。
                  </p>
                  <p>
                    注意：若成绩趋势相对离散（各分数段人数分布相对均衡，或差异很大），则建议结合成绩变异指标进行分析。
                  </p>
                </div>
              </el-popover>
            </h3>
          </div>
          <div class="chart-box chart-cjfb">
            <v-chart
              :option="scoreAnalyseOption"
              v-if="scoreAnalyseOption"
            ></v-chart>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <AnswerRateAnalysis
          ref="AnswerRateAnalysis"
          :data-list="dimensionAnalyzeList"
        />
      </el-col>
      <el-col :span="12">
        <div class="part-box part-box-pad">
          <div class="part-box-head">
            <h3>
              <span>本院与全校成绩对比分析</span>
              <!-- <el-popover
                popper-class="el-popper-dark"
                placement="right-start"
                width="300"
                trigger="hover"
              >
                <i class="el-icon-question" slot="reference"></i>
                <div>
                  <p>
                    平均分：受极端数值（例如：最低分或最高分）的影响较大，受极大值影响更大，从而影响其代表性大小；
                  </p>
                  <p>
                    中位数：若参与本学科考试的学生数量不多，成绩分布偏斜程度不太大，但各考生之间成绩差异度较大或存在极端数值时，中位数具有较高代表性；
                  </p>
                  <p>
                    众数：当参与本学科考试的学生的成绩较为集中（为同一个成绩）或成绩分布偏态严重时，众数可代表大部分学生所处的水平；
                  </p>
                  <p>
                    标准差系数：消除了同一门学科在不同学院平均水平高低影响，反映了不同水平的学院成绩的相对离散程度。
                  </p>
                </div>
              </el-popover> -->
            </h3>
          </div>
          <div class="chart-box chart-cjdbfx">
            <v-chart
              :option="scoreCompareAnalyseOption"
              v-if="scoreCompareAnalyseOption"
            ></v-chart>
          </div>
        </div>
        <div class="part-box part-box-pad">
          <div class="part-box-head">
            <h3>
              <span>本院与全校难题作答情况分析</span>
              <el-popover
                popper-class="el-popper-dark"
                placement="right-start"
                width="300"
                trigger="hover"
              >
                <i class="el-icon-question" slot="reference"></i>
                <div>
                  <p>
                    1.题目难易度是以参加本次考试的学生平均得分率为指标，与参加本次考试的学生水平有关。因此，这里计算出来的题目难度大小，只是对本次考试测评的学生相对而言的难易度评估。
                  </p>
                  <p>
                    2.难题：难度值在[0-0.3）之间；中等难度题：难度值在[0.3-0.7)之间；容易题：难度值在0.7以上。
                  </p>
                </div>
              </el-popover>
            </h3>
            <!-- modules -->
            <div class="module-select">
              <div
                v-for="mod in difficultyAnalyseList"
                :key="mod.id"
                :class="[
                  'module-select-item',
                  {
                    'module-select-item-act': mod.id === curDifficulty.id
                  }
                ]"
                @click="difficultyChange(mod)"
              >
                {{ mod.paperType }}
              </div>
            </div>
          </div>
          <div class="chart-box chart-ntzdqk">
            <v-chart
              :option="curDifficulty.chartOption"
              v-if="curDifficulty.chartOption"
            ></v-chart>
          </div>
        </div>
      </el-col>
    </el-row>
    <div class="part-box part-box-pad">
      <div class="part-box-head">
        <h3>
          <span>教师维度对比分析</span>
          <el-popover
            popper-class="el-popper-dark"
            placement="right-start"
            width="300"
            trigger="hover"
          >
            <i class="el-icon-question" slot="reference"></i>
            <div>
              <p>1.本院当前课程的全部任课教师进行横向对比；</p>
              <p>
                2.同一任课教师本院的学生考试情况与其它学院考试情况进行对比。
              </p>
            </div>
          </el-popover>
        </h3>
      </div>
      <div class="chart-box chart-jswddb">
        <v-chart
          :option="studentScoreOption"
          v-if="studentScoreOption"
        ></v-chart>
      </div>
      <table class="table table-fixed">
        <tr>
          <th rowspan="2">教师</th>
          <th colspan="6" class="text-center bg">本院</th>
          <th colspan="6" class="text-center">其他学院</th>
        </tr>
        <tr>
          <th class="bg">有效人数</th>
          <th class="bg">平均分</th>
          <th class="bg">最低分</th>
          <th class="bg">最高分</th>
          <th class="bg">中位数</th>
          <th class="bg">众数</th>
          <th>有效人数</th>
          <th>平均分</th>
          <th>最低分</th>
          <th>最高分</th>
          <th>中位数</th>
          <th>众数</th>
        </tr>
        <tr v-for="(item, index) in studentScoreList" :key="index">
          <td>{{ item.teacherName }}</td>
          <td class="bg">{{ item.colRealityCount }}</td>
          <td class="bg">{{ item.colAvgScore }}</td>
          <td class="bg">{{ item.colMinScore }}</td>
          <td class="bg">{{ item.colMaxScore }}</td>
          <td class="bg">{{ item.colMedian }}</td>
          <td class="bg">{{ item.colMode }}</td>
          <td>{{ item.schRealityCount }}</td>
          <td>{{ item.schAvgScore }}</td>
          <td>{{ item.schMinScore }}</td>
          <td>{{ item.schMaxScore }}</td>
          <td>{{ item.schMedian }}</td>
          <td>{{ item.schMode }}</td>
        </tr>
      </table>
    </div>
    <MistakeAnalysis v-if="mistakeDatas" :datas="mistakeDatas" />
  </div>
</template>

<script>
import { courseSurveyInspectAnalyseView } from "../../api";
import {
  getScoreAnalyseOption,
  getScoreCompareAnalyseOption,
  getAnswerAnalyseOption,
  getDifficultyAnalyseOption,
  getDistinctionAnalyseOption
} from "../../chartOption";
import AnswerRateAnalysis from "./AnswerRateAnalysis";
import MistakeAnalysis from "../owner-course-exam-analysis/MistakeAnalysis";

export default {
  name: "inspect-course-exam-analysis",
  components: { AnswerRateAnalysis, MistakeAnalysis },
  data() {
    return {
      isInit: false,
      setReady: false,
      selectDefault: false,
      filter: {
        semesterId: "",
        examId: "",
        courseCode: ""
      },
      summary: {},
      orgName: "",
      // info
      scoreAnalyse: [],
      scoreRateList: [],
      scoreRateData: [],
      scoreCompare: [],
      moduleName: "",
      dimensionAnalyzeList: [],
      difficultyAnalyseList: [],
      curDifficulty: {},
      studentScoreList: [],
      distinctionList: [],
      mistakeDatas: null,
      // chart
      scoreAnalyseOption: null,
      scoreAnalyseRateOption: null,
      scoreCompareAnalyseOption: null,
      studentScoreOption: null
    };
  },
  created() {
    const orgInfo = this.$ls.get("user", { orgInfo: { name: "" } }).orgInfo;
    if (orgInfo) this.orgName = orgInfo.name;
    this.initPage();
  },
  methods: {
    initPage() {
      const inspectCourseSet = this.$ls.get("inspectCourseSet");
      if (inspectCourseSet) {
        this.filter = this.$objAssign(
          { semesterId: "", examId: "", courseCode: "" },
          inspectCourseSet
        );
        this.isInit = true;
        this.setReady = true;
        this.$nextTick(async () => {
          await this.$refs.ExamSelect.search();
          await this.$refs.CourseSelect.search();
          this.search();
          this.selectDefault = true;
          this.$ls.remove("inspectCourseSet");
        });
      } else {
        this.setReady = true;
        this.selectDefault = true;
      }
    },
    search() {
      this.mistakeDatas = null;
      this.getData();
    },
    async getData() {
      if (
        !this.filter.semesterId ||
        !this.filter.examId ||
        !this.filter.courseCode
      ) {
        this.$message.error("学期、考试和课程都必须选择！");
        return;
      }
      const schoolId = this.$ls.get("schoolId");
      const datas = {
        schoolId,
        ...this.filter
      };
      const data = await courseSurveyInspectAnalyseView(datas);
      this.initData(data);
    },
    semesterChange() {
      this.filter.examId = null;
      this.examChange();
    },
    examChange() {
      this.filter.courseCode = null;
    },
    courseChange() {
      // 初次载入页面加载默认数据
      if (
        !this.isInit &&
        this.filter.examId &&
        this.filter.semesterId &&
        this.filter.courseCode
      ) {
        this.isInit = true;
        this.search();
      }
    },
    initData(datas) {
      this.summary = {
        examTime:
          datas.courseInfo.descriptiveStatistics.schoolDescriptiveStatistics
            .examTime,
        courseName: datas.courseInfo.courseProfile.courseName,
        totalScore: datas.courseInfo.courseProfile.totalScore,
        schRealityCount:
          datas.courseInfo.descriptiveStatistics.schoolDescriptiveStatistics
            .realityCount,
        colRealityCount:
          datas.courseInfo.descriptiveStatistics.collegeDescriptiveStatistics
            .realityCount,
        colAbsentCount:
          datas.courseInfo.descriptiveStatistics.collegeDescriptiveStatistics
            .absentCount,
        colTotalCount:
          datas.courseInfo.descriptiveStatistics.collegeDescriptiveStatistics
            .totalCount
      };
      // score analyse
      this.scoreAnalyse = [
        {
          name: "全校",
          datas: datas.gradeDistributionInfo.gradeDistributionList.map(item => {
            return {
              name: item.describe + "分",
              value: item.schCount
            };
          })
        },
        {
          name: "本院",
          datas: datas.gradeDistributionInfo.gradeDistributionList.map(item => {
            return {
              name: item.describe + "分",
              value: item.colCount
            };
          })
        }
      ];
      this.scoreAnalyseOption = getScoreAnalyseOption(this.scoreAnalyse);
      this.scoreRateList =
        datas.gradeDistributionInfo.piecewiseDistributionList;
      this.scoreRateData = this.scoreRateList
        .filter(item => item.name !== "TOP10")
        .map(item => {
          return {
            name: item.name,
            remark: item.remark,
            value: (item.colCountRate / 100).toFixed(4) * 1
          };
        });

      // score compare
      const compareConfig = [
        { name: "全校", param: "schoolDescriptiveStatistics" },
        { name: "本院", param: "collegeDescriptiveStatistics" }
      ];
      this.scoreCompare = compareConfig.map(conf => {
        const data = datas.courseInfo.descriptiveStatistics[conf.param];
        return {
          name: conf.name,
          realityCount: data.realityCount,
          avg: data.avgScore,
          min: data.minScore,
          max: data.maxScore,
          median: data.median,
          mode: data.mode ? data.mode.split(",").join("，") : "",
          q1: data.lowerQuartile,
          q3: data.upperQuartile,
          sd: data.standardDeviation
        };
      });
      this.scoreCompareAnalyseOption = getScoreCompareAnalyseOption(
        this.scoreCompare
      );
      // modules
      if (datas.dimensionInfo) {
        const serials = { 知识: 0, 能力: 1 };
        if (datas.dimensionInfo.dimensionAnalyzeList.length > 1) {
          datas.dimensionInfo.dimensionAnalyzeList.sort(
            (a, b) => serials[a.moduleName] - serials[b.moduleName]
          );
        }
        this.moduleName = datas.dimensionInfo.dimensionAnalyzeList
          .map(item => item.moduleName + "模块")
          .join("、");
        const dimensionConfig = [
          { name: "全校", param: "schScoreRate" },
          { name: "本院", param: "colScoreRate" }
        ];
        this.dimensionAnalyzeList = datas.dimensionInfo.dimensionAnalyzeList.map(
          (item, index) => {
            const answerAnalyse = dimensionConfig.map(conf => {
              item.dioList.sort((a, b) =>
                a.dimensionCode > b.dimensionCode ? 1 : -1
              );
              let dioList = item.dioList.map(elem => {
                return {
                  name: elem.dimensionCode,
                  value: elem[conf.param] * 1
                };
              });

              return {
                name: conf.name,
                datas: dioList
              };
            });
            item.id = `dimension${index}`;
            item.answerAnalyseOption = getAnswerAnalyseOption(answerAnalyse);
            item.worseThanAllCodes = item.worseThanAll
              .map(elem => elem.dimensionCode)
              .sort((a, b) => (a > b ? 1 : -1))
              .join("、");
            item.batterThanAllCodes = item.batterThanAll
              .map(elem => elem.dimensionCode)
              .sort((a, b) => (a > b ? 1 : -1))
              .join("、");
            return item;
          }
        );
      }
      // all difficulty
      this.difficultyAnalyseList = datas.answerInfo.questionInfoList.map(
        (item, index) => {
          const scoreConfig = [
            { name: "全校", param: "schAvgScoreRate" },
            { name: "本院", param: "colAvgScoreRate" }
          ];
          const chartData = item.cellList.map(elem => {
            return {
              xaxisLabel: `${elem.interpret}题(${elem.count}道)`,
              list: scoreConfig.map(config => {
                return {
                  legendLabel: config.name,
                  num: elem[config.param]
                };
              })
            };
          });

          return {
            id: `difficulty${index}`,
            paperType: item.paperType,
            // desc无
            descs: item.cellList.map(elem => {
              return {
                type: elem.interpret,
                scope: elem.scope
              };
            }),
            chartOption: getDifficultyAnalyseOption(chartData)
          };
        }
      );
      this.difficultyChange(this.difficultyAnalyseList[0]);
      // teacher: answer rate
      this.studentScoreList = datas.teacherInfo.teacherInfoList.map(item => {
        item.colMode = item.colMode.split(",").join("，");
        item.schMode = item.schMode.split(",").join("，");
        return item;
      });
      const studentScore = this.studentScoreList.map(item => {
        return {
          name: item.teacherName,
          min: item.colMinScore,
          max: item.colMaxScore,
          median: item.colMedian,
          q1: item.colLowerQuartile,
          q3: item.colUpperQuartile
        };
      });
      this.studentScoreOption = getScoreCompareAnalyseOption(studentScore);
      // distinction-无
      this.distinctionList = datas.questionInfo.questionList.map(
        (item, index) => {
          const dataList = item.cellList.map(elem => {
            return {
              name: `${elem.numberType}${elem.mainNumber}-${elem.subNumber}`,
              detailName: elem.questinName,
              value: elem.validity
            };
          });

          return {
            id: `distinction${index}`,
            paperType: item.paperType,
            chartOption: getDistinctionAnalyseOption(dataList)
          };
        }
      );
      // 考生错题难度
      this.mistakeDatas = datas.questionInfo.questionList[0];
    },
    difficultyChange(mod) {
      this.curDifficulty = mod;
    }
  }
};
</script>
