<template>
  <div class="assign-score-action-try">
    <div class="page-head">
      <h2>
        <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>
      </h2>
    </div>

    <div class="part-box part-box-pad">
      <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 }}</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 class="summary-info-item">
            <i class="summary-info-icon"><i class="icon icon-full"></i></i>
            <p>满分</p>
            <p>{{ summary.fullScore }}</p>
          </div>
          <div class="summary-info-item">
            <i class="summary-info-icon"><i class="icon icon-users"></i></i>
            <p>有效(实考)人数</p>
            <p>{{ summary.realityCount }}</p>
          </div>
          <div class="summary-info-item">
            <i class="summary-info-icon"><i class="icon icon-users"></i></i>
            <p>考查学院</p>
            <p>{{ summary.inspectCollegeCount }}</p>
          </div>
          <div class="summary-info-item">
            <i class="summary-info-icon"><i class="icon icon-absent"></i></i>
            <p>缺考/违纪</p>
            <p>{{ summary.absentCount }}</p>
          </div>
        </div>
      </div>
      <div class="summary-school">
        <p>
          <span>赋分系数：</span
          ><span v-if="IS_UNCOMPUTE || filter.coefficient === ''">#</span
          ><span v-else>{{ filter.coefficient }}</span>
        </p>
        <p>
          <span>开课学院：</span><span>{{ summary.teachCollegeName }}</span>
        </p>
        <p>
          <span>考查学院：</span><span>{{ summary.inspectCollegeNames }}</span>
        </p>
      </div>
    </div>

    <div class="page-head page-head-flex">
      <h2>
        <span>赋分试算快速结果比对</span>
        <el-popover
          popper-class="el-popper-dark"
          placement="right-start"
          width="400"
          trigger="hover"
        >
          <i class="el-icon-question" slot="reference"></i>
          <div>
            <p>
              1.当卷面成绩为满分时，赋分对卷面成绩没有影响；
            </p>
            <p>
              2.当卷面成绩相同时赋分系数越大，赋分对卷面成绩影响越小；
            </p>
            <p>
              3.当赋分系数相同时，卷面成绩越高，赋分对卷面成绩影响越小；
            </p>
            <p>
              4.若卷面成绩不需要额外赋分，请将赋分系数填“0”。
            </p>
          </div>
        </el-popover>
      </h2>
      <el-button
        icon="icon icon-export"
        round
        :disabled="loading || !IS_COMPUTE"
        @click="toExport"
        >导出赋分成绩明细</el-button
      >
    </div>

    <div class="part-box part-box-pad">
      <table class="table mb-4">
        <tr>
          <th rowspan="2">对比项</th>
          <th colspan="3" class="text-center">
            总体有效人数：<span>{{ calcResult.totalCount }}</span
            >人
          </th>
          <th colspan="3" class="text-center">
            应届有效人数：<span>{{ calcResult.currentCount }}</span
            >人
          </th>
        </tr>
        <tr>
          <th>平均分</th>
          <th>不及格率</th>
          <th>不及格人数</th>
          <th>平均分</th>
          <th>不及格率</th>
          <th>不及格人数</th>
        </tr>
        <tr>
          <td>赋分前</td>
          <td>{{ calcResult.avgScore }}</td>
          <td>{{ calcResult.failRate | percentFilter }}</td>
          <td>{{ calcResult.failCount }}</td>
          <td>{{ calcResult.currentAvgScore }}</td>
          <td>{{ calcResult.currentFailRate | percentFilter }}</td>
          <td>{{ calcResult.currentFailCount }}</td>
        </tr>
        <tr>
          <td>赋分后</td>
          <td>{{ calcResult.avgScoreAssign | defaultFieldFilter }}</td>
          <td>{{ calcResult.failRateAssign | percentFilter }}</td>
          <td>{{ calcResult.failCountAssign | defaultFieldFilter }}</td>
          <td>{{ calcResult.currentAvgScoreAssign | defaultFieldFilter }}</td>
          <td>{{ calcResult.currentFailRateAssign | percentFilter }}</td>
          <td>{{ calcResult.currentFailCountAssign | defaultFieldFilter }}</td>
        </tr>
      </table>

      <div class="part-box-flex">
        <div class="part-box-filter">
          <el-form
            ref="FilterForm"
            label-position="left"
            label-width="80px"
            inline
          >
            <el-form-item label="赋分系数：">
              <el-input-number
                v-model="coefficient"
                :min="-999"
                :max="999"
                :controls="false"
                placeholder="请输入赋分系数"
              ></el-input-number>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :disabled="loading" @click="toCalc"
                >开始试算</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="part-box-action">
          <el-button @click="toCancel">取消</el-button>
          <el-button type="info" @click="toSave" :disabled="loading || !canSave"
            >保存结果</el-button
          >
        </div>
      </div>
      <p class="tips-info mb-4">
        <i class="icon icon-tips-red"></i>
        温馨提示：若试算的数据较大，可能需要您耐心等待10秒~3分钟！
      </p>

      <div class="chart-table">
        <table class="table">
          <tr>
            <th rowspan="3">分数段</th>
            <th colspan="4" class="text-center">赋分前</th>
            <th colspan="4" class="text-center">赋分后</th>
          </tr>
          <tr class="text-center">
            <th colspan="2">总体</th>
            <th colspan="2">应届</th>
            <th colspan="2">总体</th>
            <th colspan="2">应届</th>
          </tr>
          <tr>
            <th>有效人数</th>
            <th>占比</th>
            <th>有效人数</th>
            <th>占比</th>
            <th>有效人数</th>
            <th>占比</th>
            <th>有效人数</th>
            <th>占比</th>
          </tr>
          <tr v-for="(grade, index) in scoreAnalyseList" :key="index">
            <td>{{ grade.describe }}</td>
            <td>{{ grade.allCountBefore }}</td>
            <td>{{ grade.allCountRateBefore }}%</td>
            <td>{{ grade.currentCountBefore }}</td>
            <td>{{ grade.currentCountRateBefore }}%</td>
            <template v-if="IS_UNCOMPUTE">
              <td class="color-primary">计算中...</td>
              <td class="color-primary">计算中...</td>
              <td class="color-primary">计算中...</td>
              <td class="color-primary">计算中...</td>
            </template>
            <template v-else>
              <td>{{ grade.allCountAfter }}</td>
              <td>{{ grade.allCountRateAfter }}%</td>
              <td>{{ grade.currentCountAfter }}</td>
              <td>{{ grade.currentCountRateAfter }}%</td>
            </template>
          </tr>
          <tr>
            <td>小计</td>
            <td>{{ scoreAnalyseListSum.allCountBefore }}</td>
            <td></td>
            <td>{{ scoreAnalyseListSum.currentCountBefore }}</td>
            <td></td>
            <template v-if="IS_UNCOMPUTE">
              <td class="color-primary">计算中...</td>
              <td></td>
              <td class="color-primary">计算中...</td>
              <td></td>
            </template>
            <template v-else>
              <td>{{ scoreAnalyseListSum.allCountAfter }}</td>
              <td></td>
              <td>{{ scoreAnalyseListSum.currentCountAfter }}</td>
              <td></td>
            </template>
          </tr>
        </table>
      </div>
    </div>

    <el-row :gutter="20">
      <el-col :span="12">
        <QuestionDifficultScoreAnalysis ref="QuestionDifficultScoreAnalysis" />
        <TeacherClazzScore ref="TeacherClazzScore" :filter="filter" />
      </el-col>
      <el-col :span="12">
        <DifficultLevelAnalysis ref="DifficultLevelAnalysis" />

        <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，为无区分作用。
                  </p>
                </div>
              </el-popover>
            </h3>
            <!-- modules -->
            <div class="module-select">
              <div
                v-for="mod in distinctionList"
                :key="mod.id"
                :class="[
                  'module-select-item',
                  {
                    'module-select-item-act': mod.id === curDistinction.id
                  }
                ]"
                @click="distinctionChange(mod)"
              >
                {{ mod.paperType }}
              </div>
            </div>
          </div>
          <div class="chart-box chart-qfdnd">
            <v-chart
              :option="curDistinction.chartOption"
              v-if="curDistinction.chartOption"
            ></v-chart>
          </div>
        </div>
      </el-col>
    </el-row>

    <MistakeAnalysis v-if="mistakeDatas" :datas="mistakeDatas" />
  </div>
</template>

<script>
import {
  courseSurveyTeacherView,
  courseSurveyAspointsSave,
  courseSurveyAspointsCalculation,
  courseSurveyTeacherCourseExport
} from "../../api";
import {
  getScoreAnalyseOption,
  getDistinctionAnalyseOption
} from "../../chartOption";
import QuestionDifficultScoreAnalysis from "../owner-course-exam-analysis/QuestionDifficultScoreAnalysis";
import DifficultLevelAnalysis from "../owner-course-exam-analysis/DifficultLevelAnalysis";
import TeacherClazzScore from "../owner-course-exam-analysis/TeacherClazzScore";
import MistakeAnalysis from "../owner-course-exam-analysis/MistakeAnalysis";
import { calcSum } from "@/plugins/utils";
import { downloadByApi } from "@/plugins/download";

const initFilter = {
  semesterId: "",
  examId: "",
  courseCode: "",
  coefficient: "",
  status: "",
  again: false
};

export default {
  name: "assign-score-action-try",
  components: {
    QuestionDifficultScoreAnalysis,
    DifficultLevelAnalysis,
    TeacherClazzScore,
    MistakeAnalysis
  },
  data() {
    return {
      filter: {
        ...initFilter
      },
      setReady: false,
      coefficient: undefined,
      summary: {},
      orgName: "",
      calcResult: {},
      calcCoefficient: null,
      loading: false,
      // report
      scoreAnalyse: [],
      scoreAnalyseSummary: {},
      scoreAnalyseList: [],
      scoreAnalyseListSum: {},
      scoreAnalyseOption: null,
      distinctionList: [],
      curDistinction: {},
      mistakeDatas: null
    };
  },
  computed: {
    IS_UNCOMPUTE() {
      return this.filter.status === "WILL_COMPUTE";
    },
    IS_COMPUTE() {
      return ["UN_PUBLISH", "PUBLISH"].includes(this.filter.status);
    },
    canSave() {
      return this.coefficient || this.coefficient === 0;
    }
  },
  mounted() {
    const assignSet = this.$ls.get("assignSet");
    if (!assignSet) {
      this.$message.error("科目数据丢失，请返回上一页面");
      return;
    }

    this.filter = this.$objAssign(initFilter, assignSet);
    if (this.filter.coefficient === "" || this.filter.coefficient === "#") {
      this.coefficient = undefined;
    } else {
      this.coefficient = this.filter.coefficient * 1;
      this.filter.coefficient = this.coefficient;
      this.calcCoefficient = this.coefficient;
    }
    this.setReady = true;
    this.$nextTick(() => {
      this.search();
    });
  },
  methods: {
    search() {
      this.mistakeDatas = null;
      this.getData();
      this.getCalcResult(this.filter.coefficient);
      // 教师各课堂成绩排名
      this.$refs.TeacherClazzScore.getData();
      // 试题难度得分情况分析
      this.$refs.QuestionDifficultScoreAnalysis.initData(this.filter);
      // 各难度水平题目上的作答分析
      this.$refs.DifficultLevelAnalysis.initData(this.filter);
    },
    async getData() {
      const datas = {
        semesterId: this.filter.semesterId,
        examId: this.filter.examId,
        courseCode: this.filter.courseCode
      };
      const data = await courseSurveyTeacherView(datas);
      this.initData(data);
    },
    initData(datas) {
      this.summary = datas.teachCourseSurveyResult;
      // 赋分分数段分布情况
      this.scoreAnalyse = [
        {
          name: "总体",
          datas: datas.gradeDistribution.map(item => {
            return {
              name: item.describe,
              value: item.allCountAfter
            };
          })
        },
        {
          name: "应届",
          datas: datas.gradeDistribution.map(item => {
            return {
              name: item.describe,
              value: item.currentCountAfter
            };
          })
        }
      ];
      this.scoreAnalyseOption = getScoreAnalyseOption(this.scoreAnalyse);
      this.scoreAnalyseSummary = datas.surveyTeacher;
      this.scoreAnalyseList = datas.gradeDistribution;
      this.scoreAnalyseListSum.allCountBefore = calcSum(
        this.scoreAnalyseList.map(item => item.allCountBefore)
      );
      this.scoreAnalyseListSum.allCountAfter = calcSum(
        this.scoreAnalyseList.map(item => item.allCountAfter)
      );
      this.scoreAnalyseListSum.currentCountBefore = calcSum(
        this.scoreAnalyseList.map(item => item.currentCountBefore)
      );
      this.scoreAnalyseListSum.currentCountAfter = calcSum(
        this.scoreAnalyseList.map(item => item.currentCountAfter)
      );
      // 区分度及难度分析情况
      this.distinctionList = datas.questionInfo.questionList.map(
        (item, index) => {
          const dataList = item.cellList.map(elem => {
            return {
              name: `${elem.mainNumber}-${elem.subNumber}`,
              detailName: elem.questionName,
              validity: elem.validity,
              scoreRate: elem.scoreRate / 100
            };
          });

          return {
            id: `distinction${index}`,
            paperType: item.paperType,
            chartOption: getDistinctionAnalyseOption(dataList)
          };
        }
      );
      this.distinctionChange(this.distinctionList[0]);
      // 考生错题难度
      this.mistakeDatas = datas.questionInfo.questionList[0];
    },
    distinctionChange(mod) {
      this.curDistinction = mod;
    },
    async toExport() {
      if (!this.IS_COMPUTE) {
        this.$message.error("赋分计算还未完成，请稍后再试！");
        return;
      }
      if (this.loading) return;

      this.loading = true;
      const res = await downloadByApi(() => {
        return courseSurveyTeacherCourseExport(this.filter);
      }, `导出赋分成绩明细.xlsx`).catch(() => {});

      this.loading = false;

      if (res) {
        this.$message.success("文件下载成功！");
      } else {
        this.$message.error("文件下载失败，请重新尝试！");
      }
    },
    async toCalc() {
      if (
        this.coefficient === null ||
        this.coefficient === "" ||
        this.coefficient === undefined
      ) {
        this.$message.error("请输入赋分系数");
        return;
      }
      if (this.loading) return;
      this.loading = true;
      let res = true;
      await this.getCalcResult(this.coefficient).catch(() => {
        res = false;
      });
      this.loading = false;
      if (!res) return;
      this.calcCoefficient = this.coefficient;
      this.$message.success("计算成功！");
    },
    async getCalcResult(coefficient) {
      this.calcResult = await courseSurveyAspointsCalculation({
        examId: this.filter.examId,
        courseCode: this.filter.courseCode,
        coefficient: coefficient
      });
    },
    toSave() {
      if (this.loading) return;
      this.$confirm(
        `确定保存赋分系数为【${this.coefficient}】的计算结果吗？`,
        "提示",
        {
          cancelButtonClass: "el-button--danger is-plain",
          confirmButtonClass: "el-button--primary",
          type: "warning"
        }
      )
        .then(() => {
          this.save();
        })
        .catch(() => {});
    },
    async save() {
      this.loading = true;
      const res = await courseSurveyAspointsSave({
        examId: this.filter.examId,
        courseCode: this.filter.courseCode,
        coefficient:
          this.coefficient === this.filter.coefficient ? "#" : this.coefficient
      }).catch(() => {});
      this.loading = false;
      if (!res) return;
      this.$message.success("操作成功");
      this.toCancel();
    },
    toCancel() {
      this.$router.go(-1);
    }
  }
};
</script>
