<template>
  <div class="page_report">
    <div class="report_module">
      <div class="module_title">
        <div class="title_left">成绩总览</div>
      </div>
      <div class="module_table">
        <el-table
          :data="subjectData.tableData"
          v-loading="subjectLoading"
          :element-loading-text="loadingText"
          element-loading-spinner="el-icon-loading"
          element-loading-background="#ffffff"
          border
          stripe
          align="left"
        >
          <!-- 科目列固定在左侧 -->
          <el-table-column
            v-if="subjectNameTitle"
            align="center"
            :label="subjectNameTitle.name"
            fixed="left"
            min-width="100"
          >
            <template slot-scope="scope">
              {{ scope.row?.subjectName || '-' }}
            </template>
          </el-table-column>
          <el-table-column v-for="(title,index) in middleTitleData" :key="`${title.prop}_${index}`" align="center" :label="title.name" min-width="100">
            <template slot-scope="scope">
              <template v-if="title.prop == 'score'">
                <!-- * 1-得分显示分数，小题分显示分数,2-得分显示分数，小题分显示对错
                * 3-得分显示对错，小题分显示分数,4-得分显示对错，小题分显示对错
                * 5-得分显示等级，小题分显示分数,6-得分显示等级，小题分显示对错 -->
                <template v-if="subjectData.studentOpenness == 3 || subjectData.studentOpenness == 4">
                  <template v-if="!isNaN(scope.row?.[title.prop])">
                    <img v-if="scope.row.fullScore == scope.row?.[title.prop]" src="@/assets/stuIcon/icon_right.png" />
                    <img v-else-if="scope.row?.[title.prop] == 0" src="@/assets/stuIcon/icon_error.png" />
                    <img v-else src="@/assets/stuIcon/icon_half_right.png" />
                  </template>
                  <template v-else>{{ scope.row?.[title.prop] ?? '-' }}</template>
                </template>
                <template v-else>{{ scope.row?.[title.prop] ?? '-' }}</template>
              </template>
              <template v-else-if="title.prop == 'groupClassRanks' || title.prop == 'groupClassMaxScoreList' || title.prop == 'groupClassAvgScoreList'">{{ GetGroupClassValue(scope.row?.[title.prop],title.prop,title.code)}}</template>
              <template v-else>{{ scope.row?.[title.prop] ?? '-' }}</template>
            </template>
          </el-table-column>
          <!-- 查看答题卡列固定在右侧 -->
          <el-table-column
            v-if="imgUrlListTitle"
            align="center"
            :label="imgUrlListTitle.name"
            fixed="right"
            width="120"
          >
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.isTotal == 0 && scope.row.subjectGroupType == 0"
                type="text"
                size="small"
                @click="OpenStudentPaper(scope.row.subjectCode)"
                >查看答题卡</el-button
              >
              <template v-else>-</template>
            </template>
          </el-table-column>
        </el-table>
        <div class="module_describe" style="width: 100%;" v-if="gradeNameStatus===0">
          <ExpandableText>
            说明：为了更好地反馈学习情况，将采用等级形式呈现学业结果。以下是学业等级划分的具体计算方式，请知悉。本次考试等级按照<span style="color: #2E64FA;">{{ academicLevelData.scoreType==1?'分数':'排名' }}占比区间</span>划分，<template v-if="academicLevelData.examAcademicLevelStr!=null">共分为{{ academicLevelData.num }}个等级：{{ academicLevelData.examAcademicLevelStr }}</template>等级是动态的，它只描述过去，却指引未来。你的每一次努力，都在为下一个等级重新定义！
          </ExpandableText>
        </div>
        <div class="page_jg_20" v-else></div>
      </div>
    </div>
    <div class="report_module" v-if="suggestionData?.fullScore!='-' && suggestionData?.fullScore!='0' && suggestionData?.fullScore!=null && suggestionData!=null">
      <div class="module_title">
        <div class="title_left">总结建议</div>
      </div>
      <div class="module_describe suggestion">
        <ExpandableText :isExpanded="false" :shouldShowButton="false">
          {{ suggestionData?.studentName }}同学，本次考试{{
            suggestionData?.studentOpenness == 1 || suggestionData?.studentOpenness == 2 ? '总分' : '总分标准分为'
          }}<span style="color: #2e64fa">{{ suggestionData?.fullScore }}</span
          >{{ suggestionData?.studentOpenness == 1 || suggestionData?.studentOpenness == 2 ? '分' : '' }}，整体处于{{
            suggestionData?.summarySuggestionLevel
          }}，<template v-if="suggestionData?.upSubjectData"
            ><span style="color: #3ba272">{{ suggestionData?.upSubjectData }}</span
            >是你的优势学科，建议通过提分练习进行强化，继续保持这类学科的优势性{{
              suggestionData?.downSubjectData ? '；' : '。'
            }}</template
          ><template v-if="suggestionData?.downSubjectData"
            ><span style="color: #f56c6c">{{ suggestionData?.downSubjectData }}</span
            >是你的劣势学科，建议先加强学习，熟练掌握薄弱知识点的基础，然后通过提分练习进行巩固和强化，争取下次考试获得更优异的成绩！</template
          >
        </ExpandableText>
      </div>
    </div>
    <!-- 科目标准分分析 -->
    <div class="report_module" v-if="((subjectData.standardScoreAnalysisStatus == 0 && schoolType == 2) || schoolType == 1)">
      <div class="module_title" style="position: relative">
        <div class="title_left">科目标准分分析</div>
      </div>
      <div class="module_chart" v-if="subjectData.tableData.length > 0">
        <DifferenceChart
          :datax="subjectData.datax"
          :tooltipData="subjectData.tooltipData"
          :datay="subjectData.datay"
          :rate="0"
          :isClick="false"
        ></DifferenceChart>
      </div>
      <div
        class="module_chart no_content_data"
        v-loading="subjectLoading"
        :element-loading-text="loadingText"
        element-loading-spinner="el-icon-loading"
        element-loading-background="#ffffff"
        v-else
      >
        <span>暂无数据</span>
      </div>
      <div class="module_describe">
        <ExpandableText>
          说明：标准分，也称为标准分数或Z分数，是一种由原始分数推导出来的相对地位量数，用于说明原始分数在所属分数群体中的相对位置。其计算公式为：Z = (x - μ)/σ（Z是标准分，X是原始数据的值，μ是该组数据的平均数，σ是该组数据的标准差）。标准分的分数区间通常在-3到+3之间，标准分大于0，表示成绩在平均数之上；标准分数小于0，表示成绩在平均分数之下。
          从标准分情况来看，这次考试<template v-if="subjectData.maxSubject"><span style="color: #3ba272">{{ subjectData.maxSubject }}</span>表现突出，请继续保持</template><template v-if="subjectData.minSubject">；<span style="color: #ee6666">{{ subjectData.minSubject }}</span>标准分明显低于其他学科，可能会对总体排名造成影响，可结合错题梳理核心知识点，精准定位薄弱环节，制定针对性的提升计划，以实现各科均衡发展，进一步巩固整体成绩</template>。
        </ExpandableText>
      </div>
    </div>
    <div class="report_module" v-if="showHistory==1">
      <div class="module_title">
        <div class="title_left">历次考试分析</div>
        <div class="title_right report_button">
          <div class="module_tab">
            <div
              class="tab_item"
              v-for="item in historyExamData.selectNames"
              :class="historyExamData.selectVal == item.prop ? 'tab_active' : ''"
              :key="item.prop"
              @click="ChangeSelectVal(item.prop, item.name)"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
      </div>
      <div class="module_chart" v-if="historyExamData.chartData.length > 0">
        <LineChart
          :extraText="false"
          :showCheckBox="false"
          :showMarkPoint="false"
          :showBackground="false"
          :markNumber="historyExamData.markNumber"
          :datax="historyExamData.datax"
          :datay="historyExamData.datay"
          :title="historyExamData.title"
          :legendList="historyExamData.title"
          :yInverse="
            historyExamData.selectVal == 'examRank' || historyExamData.selectVal == 'schoolRank' ? true : false
          "
          :tooltipData="historyExamData.tooltipData"
          :gridRight="40"
        ></LineChart>
      </div>
      <div
        class="module_chart no_content_data"
        v-loading="historyExamLoading"
        :element-loading-text="loadingText"
        element-loading-spinner="el-icon-loading"
        element-loading-background="#ffffff"
        v-else
      >
        <span>暂无数据</span>
      </div>
      <div class="page_jg_20"></div>
    </div>
    <GotoTop></GotoTop>
    <!-- 学生答题卡预览组件 -->
    <StudentPaper
      v-model="showStudentPaperDialog"
      :paperInfo="paperInfo"
      :currentPageIndex="currentPageIndex"
      :pageTitle="paperTitle"
    ></StudentPaper>
  </div>
</template>
<script>
import DifferenceChart from '@/views/analysisReport/components/dCharts/differenceChart' //率差图
import ExpandableText from '@/views/analysisReport/components/ExpandableText' //文本内容展开收缩组件
import LineChart from '@/views/analysisReport/components/dCharts/lineChart' //折线图
import GotoTop from '@/views/analysisReport/components/GotoTop' //分析报告页面底部回到顶部组件
import StudentPaper from '@/components/StudentPaper.vue' //学生答题卡预览组件
import {getApiName} from '@/utils/common';
import { mapGetters } from 'vuex'
export default {
  name: 'subjectQuality',
  props: {},
  components: {
    DifferenceChart,
    ExpandableText,
    LineChart,
    GotoTop,
    StudentPaper
  },
  data() {
    return {
      academicLevelData:{
        examAcademicLevelStr:'',
        scoreType:'',
        num:''
      },
      subjectData: {
        standardScoreAnalysisStatus: 0,
        titleData: [],
        studentOpenness: '', //学生信息
        tableData: [],
        datax: [], //图数据
        datay: [], //图数据
        tooltipData: [],
        maxSubject: '',
        minSubject: ''
      },
      subjectLoading: false, //加载状态
      historyExamLoading: false,
      loadingText: '加载中,请稍后……',
      historyExamData: {
        chartData: [],
        datax: [],
        datay: [],
        title: [],
        colors: ['#5470C6'],
        markNumber: [],
        selectNames: [],
        selectVal: 'standardScore'
      }, //线面积图
      suggestionData: null,
      showStudentPaperDialog: false, //显示答题卡弹框
      paperInfo: {},
      paperTitle: '', //答题卡弹框标题
      currentPageIndex: 0, //当前选中的答题卡第几页
      showHistory:0,
      gradeNameStatus:1//学业等级文案
    }
  },
  watch: {
    reportParam() {
      this.PageInit() //初始加载数据
    } //监听筛选数据变化
  },
  computed: {
    ...mapGetters(['userInfo']),
    pageName() {
      return this.$store.state.report.examSelectItem.examName
    }, //考试名称
    reportParam() {
      return {
        examLevel: this.$store.state.report.filterObject.examLevel, //1-联考 2-单校
        contrastExamIds: this.$store.state.report.filterObject.contrastExamIds, //多次考试任务对比ID，不包含当前任务ID
        examId: this.$store.state.report.filterObject.examId, //考试id
        subjectCode: this.$store.state.report.filterObject.subjectCode, //科目code
        subjectGroupType: this.$store.state.report.filterObject.subjectGroupType, //是否为组合科目 1为组合科目 0为非组合科目
        isTotal: this.$store.state.report.filterObject.isTotal //是否为总分科目 1为总分 0为非总分
      }
    }, //分析报告公共参数变量
    getSubjectName() {
      return this.$store.state.report.filterObject.subjectName
    },
    // 获取科目列的表头数据
    subjectNameTitle() {
      return this.subjectData.titleData.find(t => t.prop === 'subjectName')
    },
    // 过滤掉subjectName和imgUrlList列的中间表头数据
    middleTitleData() {
      return this.subjectData.titleData.filter(t => t.prop !== 'imgUrlList' && t.prop !== 'subjectName')
    },
    // 获取imgUrlList列的表头数据
    imgUrlListTitle() {
      return this.subjectData.titleData.find(t => t.prop === 'imgUrlList')
    },
    schoolType() {
      return sessionStorage.getItem('schoolType') //1:单校 2:联校
    },
  },
  created() {},
  mounted() {
    this.PageInit() //页面初始加载数据
  },
  methods: {
    PageInit() {
      this.QueryOneSubjectData() //学生端查询单科-我的成绩
      this.QueryMultiSubjectData() //多科成绩总览-科目标准分分析
      this.QueryHistoryExamData() //学生端查询总分，多科历次信息
      this.QuerySuggestionData() //学生端查询总分，多科总结建议信息
    },
    GetGroupClassValue(data,prop,code){
      const obj = data.find(item=>item.classGroupCode==code);
      const val = prop=='groupClassRanks'?obj?.classGroupRank:obj?.groupClassResultScore;
      return val ?? '-'
    },
    //学生端查询单科-我的成绩
    QueryOneSubjectData() {
      this.$api.reportStudent[getApiName()].queryOneSubjectData(this.reportParam).then(res => {
          if (res.code == 200 && res.data) {
            const levelList = res.data?.academicLevelData?.examAcademicLevelList || [];
            const scoreType = res.data?.academicLevelData?.scoreType;
            this.academicLevelData.examAcademicLevelStr = '';
            const lens = levelList.length;
            this.academicLevelData.num = lens;
            levelList.forEach((item,index)=>{
              const gradeName = item.gradeName || '';
              const level = gradeName.replace(/等级/g, '');
              const startScore = String(item.startScore).replace(/\.0*$/, '');
              const endScore = String(item.endScore).replace(/\.0*$/, '');
              this.academicLevelData.examAcademicLevelStr +=`${level}${index==0?'[':'('}${startScore}%-${endScore}%]${index==lens -1?'。':'；'}`;
            })
            this.academicLevelData.scoreType = scoreType;
            this.showHistory = res?.data?.showHistory ?? 0;
            this.gradeNameStatus = res?.data?.gradeNameStatus ?? 1;
          } else {
            this.academicLevelData.examAcademicLevelStr = '';
            this.academicLevelData.scoreType = '';
            this.academicLevelData.num = '';
            this.gradeNameStatus = 1;
            this.showHistory = 0;
          }
        })
    },
    //多科成绩总览-科目标准分分析
    QueryMultiSubjectData() {
      //  获取表格数据
      this.subjectLoading = true
      this.$api.reportStudent[getApiName()].queryMultiSubjectData(this.reportParam).then(res => {
          if (res.code == 200 && res.data) {
            this.subjectData.tableData = res.data.tableData || []
            this.subjectData.studentOpenness = res.data.studentOpenness ?? ''
            this.subjectData.titleData = res.data.titleData || []
            this.subjectData.datax = []
            this.subjectData.datay = []
            this.subjectData.tooltipData = []
            this.subjectData.standardScoreAnalysisStatus = res.data.standardScoreAnalysisStatus
            //总分
            const totalScore = this.subjectData.tableData.filter(item => item.isTotal == 1)
            //组合
            const subjectGroup = this.subjectData.tableData.filter(
              item => item.isTotal == 0 && item.subjectGroupType == 1
            )
            //单科
            const singleSubject = this.subjectData.tableData.filter(
              item => item.isTotal == 0 && item.subjectGroupType == 0
            )
            const chartData = [...totalScore, ...subjectGroup, ...singleSubject]
            let datax = [],
              datay = []
            chartData.forEach(item => {
              this.subjectData.datax.push(item?.subjectName ?? '-')
              this.subjectData.datay.push(!item?.standardScore || item?.standardScore == '-' ? 0 : item?.standardScore)
              if (item.isTotal == 0 && item.subjectGroupType == 0) {
                datax.push(item?.subjectName ?? '')
                datay.push(item?.standardScore ?? 0)
              }
              this.subjectData.tooltipData.push({
                list: [
                  {
                    name: '标准分',
                    value: item.standardScore ?? '-'
                  }
                ],
                name: item.subjectName
              })
            })
            let maxSubject = [],
              minSubject = []
            datay.forEach((item, k) => {
              if (Number(item) > 0) {
                maxSubject.push(datax[k])
              }
              if (Number(item) < 0) {
                minSubject.push(datax[k])
              }
            })
            this.subjectData.maxSubject = maxSubject.join('、')
            this.subjectData.minSubject = minSubject.join('、')
          } else {
            this.subjectData.tableData = []
            this.subjectData.studentOpenness = ''
            this.subjectData.titleData = []
            this.subjectData.datax = []
            this.subjectData.datay = []
            this.subjectData.tooltipData = []
            this.subjectData.maxSubject = ''
            this.subjectData.minSubject = ''
          }
        })
        .finally(() => {
          this.subjectLoading = false
        })
    },
    //学生端查询总分，多科历次信息
    QueryHistoryExamData() {
      this.historyExamLoading = true
      let param = {
        ...this.reportParam
      }
      if (this.reportParam.subjectGroupType == 1 && this.reportParam.isTotal == 0) {
        //学生端查询总分，多科历次信息,组合科目时，一定要传组合科目的名称，组合科目的历次是按照组合科目名称来查询
        param.subjectName = this.getSubjectName
      }
      this.$api.reportStudent[getApiName()].queryHistoryExamData({ ...param }).then(res => {
          if (res.code == 200 && res.data) {
            const detailData = (res.data?.detailData || []).reverse()
            this.historyExamData.chartData = detailData
            this.historyExamData.selectNames = res.data.selectNames || []
            this.historyExamData.selectVal = this.historyExamData?.selectNames?.[0]?.prop ?? ''
            this.historyExamData.datax = []
            let datay = [],
              tooltipData = []
            detailData.forEach(item => {
              this.historyExamData.datax.push(item.examName)
              datay.push(item[this.historyExamData.selectVal])
              tooltipData.push({
                name: this.historyExamData?.selectNames?.[0]?.name ?? '',
                value: item[this.historyExamData.selectVal]
              })
            })
            this.historyExamData.datay = [datay]
            this.historyExamData.tooltipData = [tooltipData]
          } else {
            this.historyExamData.chartData = []
            this.historyExamData.datax = []
            this.historyExamData.datay = []
            this.historyExamData.selectNames = []
            this.historyExamData.tooltipData = []
            this.historyExamData.selectVal = ''
          }
        })
        .finally(() => {
          this.historyExamLoading = false
        })
    },
    ChangeSelectVal(prop, name) {
      this.historyExamData.selectVal = prop
      let datay = [],
        tooltipData = []
      this.historyExamData.chartData.forEach(item => {
        datay.push(item[prop])
        tooltipData.push({
          name: name,
          value: item[prop]
        })
      })
      this.historyExamData.datay = [datay]
      this.historyExamData.tooltipData = [tooltipData]
    },
    //学生端查询总分，多科总结建议信息
    QuerySuggestionData() {
      this.$api.reportStudent[getApiName()].querySuggestionData(this.reportParam).then(res => {
        if (res.code == 200 && res.data) {
          const data = res.data
          this.suggestionData = data
          this.suggestionData.upSubjectData = data.upSubjectData
            .map(item => {
              if (data.studentOpenness == 1 || data.studentOpenness == 2) {
                return `${item.subjectName}(得分${item.score})`
              } else {
                return `${item.subjectName}(${item.score})`
              }
            })
            .join('、')
          this.suggestionData.downSubjectData = data.downSubjectData
            .map(item => {
              if (data.studentOpenness == 1 || data.studentOpenness == 2) {
                return `${item.subjectName}(得分${item.score})`
              } else {
                return `${item.subjectName}(${item.score})`
              }
            })
            .join('、')
        } else {
          this.suggestionData = null
        }
      })
    },
    //答题卡预览
    OpenStudentPaper(subjectCode) {
      this.paperTitle = `${this.pageName}_${this.userInfo.userName}`
      this.paperInfo = { examId: this.reportParam.examId, subjectCode: subjectCode }
      this.showStudentPaperDialog = true
    }
  }
}
</script>
<style lang="scss" scoped>
.module_tab {
  width: auto !important;
  height: auto !important;
  padding: 0 10px !important;

  .tab_item {
    padding-bottom: 0 !important;

    &.tab_active {
      border-bottom: 0 !important;
    }
  }
}

.module_describe {
  &.suggestion {
    padding-top: 0 !important;
  }
}
</style>
