<template>
  <div class="report-container">
    <paper-header :title="name" :totalScore="totalScore" :gradeName="gradeName"></paper-header>
    <paper-type-card :name="summaryKey" type="type" :columns="[]">
      <template slot="prefix">
        <report-teacher-summary :data="summaryData"></report-teacher-summary>
        <report-teacher-tops :data="topData" class="mt20"></report-teacher-tops>
      </template>
    </paper-type-card>
    <paper-type-card :name="questionData.name" :columns="questionData.columns" :rows="questionData.rows" :autoPageEnable="true" :rowHighlight="questionRowHighlight" v-if="questionData.rows" :rowTemplateConfig="{0:'template-go-question'}" type="type" class="mt20">
      <template #template-go-question="{value, columnName}">
        <div class="mx-question-no">
          <div :class="{'type-table-cell-highlight':shouldQuestionRowHighlight(columnName)}" v-if="value>0" class="mx-question-item" @click="showClassQuestionByNo(columnName)"><span>{{value}}</span></div>
          <div :class="{'type-table-cell-highlight':shouldQuestionRowHighlight(columnName)}" v-else>
            <span>{{value}}</span>
          </div>
        </div>
      </template>
    </paper-type-card>
    <paper-type-card :name="objectiveData.name" :columns="objectiveData.columns" :rows="objectiveData.rows" v-if="objectiveData.rows" :autoPageEnable="true" :autoPageConfig="{
        pagingSize: 5,
        pagingTabNameFormatter: mergePagingTabNameFormatter,
      }" :rowTemplateConfig="{1:'template-option-question'}" type="type" class="mt20">
      <template #template-option-question="{value, columnName, columnIndex, data, $index}">
        <div v-if="columnIndex>0&&Array.isArray(value)" class="type-table-cell-array">
          <div v-for="(item, itemIndex) in value" :key="itemIndex">
            <div class="mx-question-no" @click="showOptionQuestion(columnName, columnIndex, $index, itemIndex, data)">
              <div class="mx-question-item">{{item}}</div>
            </div>
          </div>
        </div>
        <span v-else>{{value}}</span>
      </template>
    </paper-type-card>
    <paper-type-card :name="subjectiveData.name" :columns="subjectiveData.columns" :rows="subjectiveData.rows" v-if="subjectiveData.rows" :autoPageEnable="true" :autoPageConfig="{
          pagingSize: 4,
          pagingTabNameFormatter: mergePagingTabNameFormatter,
        }" :rowTemplateConfig="{1:'template-rate-question'}" type="type" class="mt20">
      <template #template-rate-question="{value, columnName, columnIndex, data, $index}">
        <div v-if="columnIndex>0&&Array.isArray(value)" class="type-table-cell-array">
          <div v-for="(item, itemIndex) in value" :key="itemIndex">
            <div class="mx-question-no" @click="showRateQuestion(columnName, columnIndex, $index, itemIndex, data)">
              <div class="mx-question-item">{{item}}</div>
            </div>
          </div>
        </div>
        <span v-else>{{value}}</span>
      </template>
    </paper-type-card>
    <paper-type-card :name="rateData.name" :columns="rateData.columns" :rows="rateData.rows" v-if="rateData.rows" :columnTemplateConfig="rateColumnTemplateConfig" type="type" class="mt20">
      <template #template-go-question="{value, columnName}">
        <div v-if="value&&value!='--'" class="mx-question-no-list">
          <div class="mx-question-item" v-for="no in value.split('，')" @click="showQuestionByRate2(no, columnName)">
            {{no}}
          </div>
        </div>
        <div v-else>{{value}}</div>
      </template>
    </paper-type-card>
    <paper-type-card :name="knowledgeData.name" :columns="knowledgeData.columns" :rows="knowledgeData.rows" v-if="knowledgeData.rows" :starColumnConfig="{ index: 1 }" :columnTemplateConfig="{'对应题号':'template-go-question'}" type="difficult" class="mt20">
      <template #template-go-question="{value}">
        <div v-if="value&&value!='--'" class="mx-question-no-list">
          <div class="mx-question-item" v-for="no in value.split('，')" @click="showQuestionByNo(no)">{{no}}</div>
        </div>
        <div v-else>{{value}}</div>
      </template>
    </paper-type-card>

    <el-dialog :title="'来源于'+name" :visible.sync="dialogVisible" v-if="dialogVisible" width="80%">
      <report-question-student :quesitonId="analysisQuestionId" :questionNo="analysisQuestionNo" :extraParam="analysisExtra">
      </report-question-student>
    </el-dialog>
  </div>
</template>
<script>
import "@/assets/styles/report.scss";
import paperHeader from "../../evaluating/components/paperHeader.vue";
import PaperTypeCard from "../../evaluating/components/paperTypeCard.vue";
import ReportTeacherSummary from "./reportTeacherSummary.vue";
import ReportTeacherTops from "./reportTeacherTops.vue";
import {
  getClassReportForMaster
} from "@/api/webApi/report";
import reportMixins from "./report-mixins.js"
import reportQuestionStudent from "./reportQuestionStudent.vue"

export default {
  mixins: [reportMixins],
  components: {
    paperHeader,
    PaperTypeCard,
    ReportTeacherSummary,
    ReportTeacherTops,
    reportQuestionStudent
  },
  props: {
    studentGradeId: {
      type: Number | String,
      default: ''
    },
    evaluationId: {
      type: Number | String,
      default: "",
    },
    name: {
      type: String,
      default: "",
    },
    gradeName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      analysisQuestionId: 0,
      analysisQuestionNo: 0,
      analysisExtra: {},
      totalScore: "",
      rawData: {},
      summaryKey: "考试情况分析",
      topKeys: ["大幅进步", "大幅退步", "年级前五名", "年级后五名"],
      questionKey: "考题情况分析",
      objectiveKey: "客观题得分",
      subjectiveKey: "主观题得分",
      rateKey: "得分率分级",
      knowledgeKey: "知识点分析",
      summaryData: [],
      topData: [],
      questionData: {},
      objectiveData: {},
      subjectiveData: {},
      rateData: {},
      rateColumnTemplateConfig: {},
      knowledgeData: {},
    };
  },
  created() {
    getClassReportForMaster({
      studentGradeId: this.studentGradeId,
      evaluationId: this.evaluationId,
    }).then((res) => {
      console.log("getClassReportForMaster res", res);
      if (res.code == 200 || res.code == 0) {
        this.rawData = res.data;
        this.resolveReportHeader();
        this.resolveReportSummary();
        this.resolveReportTops();
        this.resolveReportQuestions();
        this.resolveReportObjectives();
        this.resolveReportSubjectives();
        this.resolveReportRates();
        this.resolveReportKnowledges();
      } else {
        this.msgError(res.msg || "getClassReportForMaster 请求异常");
      }
    });
  },
  methods: {
    resolveReportHeader() {
      this.totalScore = this.rawData[this.summaryKey].options["总分"];
    },
    resolveReportSummary() {
      const summarySource = this.rawData[this.summaryKey].options;
      this.summaryData = [{
        titles: [{
          label: "参加考试人数：",
        },
        {
          label: summarySource["参加考试人数"],
          highlight: true,
        },
        ],
        subTitles: [{
          label: summarySource["缺考人数"],
          highlight: true,
        },
        {
          label: "人缺考",
        },
        ],
      },
      {
        titles: [{
          label: "平均得分率：",
        },
        {
          label: summarySource["平均得分率"],
          highlight: true,
        },
        ],
        subTitles: [{
          label: "较上次考试：",
        },
        {
          label: summarySource["较上次考试"],
          highlight: true,
        },
        ],
      },
      {
        titles: [{
          label: "平均分：",
        },
        {
          label: summarySource["平均分"],
          highlight: true,
        },
        ],
        subTitles: [{
          label: "最高分",
        },
        {
          label: summarySource["最高分"],
          highlight: true,
        },
        {
          label: "最低分",
        },
        {
          label: summarySource["最低分"],
          highlight: true,
        },
        ],
      },
      {
        titles: [],
        subTitles: [
          [{
            label: "优秀率：",
          },
          {
            label: summarySource["优秀率"],
            highlight: true,
          }
          ],
          [{
            label: "合格率：",
          },
          {
            label: summarySource["合格率"],
            highlight: true,
          }
          ],
          [{
            label: "低分率：",
          },
          {
            label: summarySource["低分率"],
            highlight: true,
          }
          ],
        ],
      },
      ];
    },
    resolveReportTops() {
      this.topData = this.topKeys.map((key) => ({
        label: key,
        tableData: this.rawData[key],
      }));
    },
    resolveReportQuestions() {
      this.questionData = this.rawData[this.questionKey];
      this.questionData.name = this.questionData.name || this.questionKey
    },
    questionRowHighlight(row) {
      const val = row[2].replace("%", "") * 1;
      return val > 50;
    },
    shouldQuestionRowHighlight(columnName) {
      const row = this.questionData.rows.find(r => r[0] == columnName)
      if (!row || row.length < 2) return false
      return this.questionRowHighlight(row)
    },
    resolveReportObjectives() {
      const objRawData = this.rawData[this.objectiveKey];
      this.objectiveData = this.mergeAnswerColumns(objRawData, "题号", "选项", "正确答案", "人数")
      this.objectiveData.name = this.objectiveData.name || this.objectiveKey
    },
    resolveReportSubjectives() {
      const subData = this.rawData[this.subjectiveKey]
      this.subjectiveData = this.mergeAnswerColumns(subData, "题号", "得分率", "正确答案", "人数")
      this.subjectiveData.name = this.subjectiveData.name || this.subjectiveKey
    },
    resolveReportRates() {
      this.rateData = this.rawData[this.rateKey];
      this.rateData.name = this.rateData.name || this.rateKey
      this.rateColumnTemplateConfig = {}
      this.rateData.columns.forEach((col, idx) => {
        if (idx > 0) this.rateColumnTemplateConfig[col] = "template-go-question"
      })
    },
    resolveReportKnowledges() {
      this.knowledgeData = this.rawData[this.knowledgeKey];
      this.knowledgeData.name = this.knowledgeData.name || this.knowledgeKey
    },
    showClassQuestionByNo(questionNo) {
      const questionId = this._mappingQuestionId(questionNo);
      if (!questionId) {
        this.msgError(`未匹配到题号'${questionNo}'的题目编号`)
        return
      }
      this.analysisQuestionId = questionId
      this.analysisQuestionNo = questionNo
      this.analysisExtra = {
        wrong: true,
        evaluationId: this.evaluationId,
        studentGradeId: this.studentGradeId,
      }
      this.dialogVisible = true
    },
    showOptionQuestion(columnName, columnIndex, rowIndex, itemIndex, data) {
      let option = null;
      if (rowIndex - 1 < data.length) {
        const prevRow = data[rowIndex - 1]
        if (columnIndex < prevRow.length) {
          const prevColumn = prevRow[columnIndex]
          if (Array.isArray(prevColumn) && itemIndex < prevColumn.length)
            option = prevColumn[itemIndex]
        }
      }
      const questionNo = this._regexFilterQuestionNo(columnName)
      const questionId = this._mappingQuestionId(questionNo);
      if (!questionId) {
        this.msgError(`未匹配到题号'${questionNo}'的题目编号`)
        return
      }

      this.analysisQuestionId = questionId
      this.analysisQuestionNo = questionNo
      this.analysisExtra = {
        answer: option,
        evaluationId: this.evaluationId,
        studentGradeId: this.studentGradeId,
      }
      this.dialogVisible = true
    },
    showRateQuestion(columnName, columnIndex, rowIndex, itemIndex, data) {
      let option = null;
      if (rowIndex - 1 < data.length) {
        const prevRow = data[rowIndex - 1]
        if (columnIndex < prevRow.length) {
          const prevColumn = prevRow[columnIndex]
          if (Array.isArray(prevColumn) && itemIndex < prevColumn.length)
            option = prevColumn[itemIndex]
        }
      }
      const questionNo = this._regexFilterQuestionNo(columnName)
      const questionId = this._mappingQuestionId(questionNo);
      if (!questionId) {
        this.msgError(`未匹配到题号'${questionNo}'的题目编号`)
        return
      }

      this.analysisQuestionId = questionId
      this.analysisQuestionNo = questionNo
      this.analysisExtra = {
        evaluationId: this.evaluationId,
        studentGradeId: this.studentGradeId,
      }
      if (option.includes('-')) {
        const minMax = option.split('-')
        this.analysisExtra.rateMin = minMax[0]
        this.analysisExtra.rateMax = minMax[1]
      } else {
        if (option.includes('以下'))
          this.analysisExtra.rateMax = option.replace('以下', '')
        if (option.includes('以上'))
          this.analysisExtra.rateMin = option.replace('以上', '')
      }
      this.dialogVisible = true
    },
    showQuestionByRate2(questionNo, columnName) {
      const questionId = this._mappingQuestionId(questionNo);
      if (!questionId) {
        this.msgError(`未匹配到题号'${questionNo}'的题目编号`)
        return
      }

      this.analysisQuestionId = questionId
      this.analysisQuestionNo = questionNo
      this.analysisExtra = {
        evaluationId: this.evaluationId,
        studentGradeId: this.studentGradeId,
      }
      let option = columnName.replace('得分率|', "")
      if (option.includes('-')) {
        option = option.replace('以上', '').replace('以下', '')
        const minMax = option.split('-')
        this.analysisExtra.rateMin = minMax[0] || 0
        this.analysisExtra.rateMax = minMax[1] || 1
      } else {
        if (option.includes('以下'))
          this.analysisExtra.rateMax = option.replace('以下', '')
        if (option.includes('以上'))
          this.analysisExtra.rateMin = option.replace('以上', '')
      }
      this.dialogVisible = true
    },
    showQuestionByNo(questionNo, wrong = true) {
      const questionId = this._mappingQuestionId(questionNo);
      if (!questionId) {
        this.msgError(`未匹配到题号'${no}'的题目编号`)
        return
      }
      this.analysisQuestionId = questionId
      this.analysisQuestionNo = questionNo
      this.analysisExtra = {
        evaluationId: this.evaluationId,
        studentGradeId: this.studentGradeId,
      }
      this.dialogVisible = true
    },
    _mappingQuestionId(questionNo) {
      const questionIdMapping = this.rawData.questionSeqId.options;
      const questionId = questionIdMapping[questionNo];
      return questionId
    }
  },
};
</script>
<style lang="scss" scoped>
.mx-question-no,
.mx-question-no-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}

.mx-question-item {
  margin: 0 5px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;

  width: 20px;
  height: 20px;
  border: 1px solid #555555;
  color: #555555;
  border-radius: 10px;
}

.mx-question-item.type-table-cell-highlight {
  border: 1px solid #f5ab86;
  color: #f5ab86;
}
</style>
