<template>
  <div class="myGradeHistory">
    <div class="chart_title">
      <h3 class="title">我的历次成绩</h3>
      <!-- <el-button type="primary" size="small" class="compare_btn" @click="showExamCompareDialog">
        <img src="../../../assets/studentAnalysis/echarts.svg" alt="图表" class="btn_icon">
        历次考试对比
      </el-button> -->
      <button class="export_btn" @click="$emit('export-knowledge-paps')">
        <i class="iconfont icon_export"></i>
        导出精准提升试题
      </button>
    </div>

    <div class="content"
      v-if="gradeHistoryData && (Array.isArray(gradeHistoryData) ? gradeHistoryData.length > 0 : (gradeHistoryData.records && gradeHistoryData.records.length > 0))">
      <el-table ref="gradeTable" :data="tableData" style="width: 100%" border :header-cell-style="headerCellStyle"
        :cell-style="cellStyle" stripe @selection-change="handleSelectionChange" width="55" align="center">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column type="index" label="序号" width="70" align="center">
          <template slot-scope="scope">
            {{ scope.$index < 10 ? '0' + (scope.$index + 1) : scope.$index + 1 }} </template>
        </el-table-column>
        <template v-for="(header, index) in tableHeaders">
          <el-table-column v-if="header.display" :key="index" :prop="header.prop" :label="header.label"
            :width="header.prop === 'examName' ? '225' : ''" align="center">
            <template slot-scope="scope">
              {{ scope.row[header.prop] != null ? scope.row[header.prop] : '-' }}
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="viewDetails(scope.row)">查看答题卡</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination background layout="prev, pager, next, total" :total="total" :page-size="pageSize"
          :current-page="currentPage" @current-change="handleCurrentChange" />
      </div>

    </div>

    <!-- 暂无数据 -->
    <div class="noData" v-else>
      <div class="module_chart no_content_data no_data" element-loading-background="#ffffff">
        <span>暂无数据</span>
      </div>
    </div>

    <!-- 学生答题卡预览组件 -->
    <StudentPaper v-model="showStudentPaperDialog" :paperInfo="paperInfo" :currentPageIndex="currentPageIndex"
      :pageTitle="paperTitle"></StudentPaper>

    <!-- 历次考试对比弹窗 - 使用公共组件 -->
    <!-- <BenchTaskSelect v-if="showBenchTaskSelect" :showDialog.sync="showBenchTaskSelect" :isMultiple="isMultiple"
      :title="benchTaskTitle" :before="1" @GetSelectId="GetSelectId"></BenchTaskSelect> -->
  </div>
</template>

<script>
import StudentPaper from '@/components/StudentPaper.vue' //学生答题卡预览组件
import { mapGetters } from 'vuex'
// 导入公共组件
//import BenchTaskSelect from '@/views/analysisReport/components/benchTaskSelectSchool';

export default {
  components: {
    StudentPaper,
    // BenchTaskSelect
  },
  name: "MyGradeHistory",
  props: {
    mode: {
      type: String,
      default: 'grade'
    },
    // 接收历次成绩数据
    gradeHistoryData: {
      type: [Array, Object],
      default: () => { }
    },
    // 接收个人画像数据
    portraitData: {
      type: Object,
      default: () => { }
    }
  },
  data() {
    return {
      showStudentPaperDialog: false, //显示答题卡弹框
      paperInfo: {},
      paperTitle: '', //答题卡弹框标题
      currentPageIndex: 0,//当前选中的答题卡第几页
      // 控制弹窗显示/隐藏
      showBenchTaskSelect: false,
      // 是否允许多选
      isMultiple: true,
      // 弹窗标题
      benchTaskTitle: '历次考试对比',
      // 是否正在初始化全选
      isInitializing: false,
      // 分页相关数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
    };
  },
  watch: {
    // 监听gradeHistoryData变化，数据加载完成后默认全选
    gradeHistoryData: {
      handler(newVal) {
        // 检查数据是否有效
        const hasData = newVal && (Array.isArray(newVal) ? newVal.length > 0 : (newVal.records && newVal.records.length > 0));

        if (hasData) {
          // 如果gradeHistoryData是一个对象，可能包含total属性
          if (typeof newVal === 'object' && newVal.total !== undefined) {
            this.total = Number(newVal.total);
          } else if (Array.isArray(newVal) && this.$parent && this.$parent.gradeHistoryData && this.$parent.gradeHistoryData.total !== undefined) {
            // 尝试从父组件获取total值
            this.total = Number(this.$parent.gradeHistoryData.total);
          }

          this.$nextTick(() => {
            if (this.$refs.gradeTable) {
              // 设置初始化标志，避免触发selection-change事件
              this.isInitializing = true;
              // 先清空所有选择，再重新全选
              this.$refs.gradeTable.clearSelection();
              // 遍历表格数据，手动选中每一行
              this.tableData.forEach(row => {
                this.$refs.gradeTable.toggleRowSelection(row, true);
              });
              // 完成后重置标志
              this.isInitializing = false;
            }
          });
        }
      },
      immediate: true
    }
  },
  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为非总分
      }
    }, //分析报告公共参数变量
    // 根据displayType获取表头标签
    displayTypeLabel() {
      // 获取第一个数据行的displayType
      const firstRow = this.tableData[0];
      if (!firstRow) return '';

      switch (firstRow.displayType) {
        case 0:
          return '分数';
        case 1:
          return '对错';
        case 2:
          return '等级';
        default:
          return '';
      }
    },
    // 获取表头配置
    tableHeaders() {
      if (Array.isArray(this.gradeHistoryData)) {
        return this.gradeHistoryData[0]?.headers || [];
      }
      const records = this.gradeHistoryData.records || [];
      return records[0]?.headers || [];
    },
    // 处理数据，映射接口字段到表格字段
    tableData() {
      if (Array.isArray(this.gradeHistoryData)) {
        return this.gradeHistoryData.map(item => ({
          id: item.id || Math.random(),
          examName: item.examName || '',
          fullScore: item.fullScore,
          originalScore: item.originalScore,
          rawScore: item.originalScore,
          classRank: item.classRank,
          gradeRank: item.gradeRank,
          standardScore: item.standardScore,
          scoreRate: item.scoreRate ? item.scoreRate+'%': '',
          examId: item.examId,
          subjectId: item.subjectId,
          displayType: item.displayType,
          displayName: item.displayName || '',
          correctType: item.correctType,
        }));
      }
      const records = this.gradeHistoryData.records || [];
      const firstRecord = records[0];
      const data = firstRecord?.data || [];
      return data.map(item => ({
        id: item.id || Math.random(),
        examName: item.examName || '',
        fullScore: item.fullScore,
        originalScore: item.originalScore,
        rawScore: item.originalScore,
        classRank: item.classRank,
        gradeRank: item.gradeRank,
        standardScore: item.standardScore,
        scoreRate: item.scoreRate ? item.scoreRate+'%': '',
        examId: item.examId,
        subjectId: item.subjectId,
        displayType: item.displayType,
        displayName: item.displayName || '',
        correctType: item.correctType,
      }));
    },
    // 表头样式
    headerCellStyle() {
      return {
        backgroundColor: '#F5F7FA',
        color: '#303133',
        height: '50px',
        padding: '0',
        margin: '0',
        lineHeight: '50px'
      };
    },
    // 表格内容样式
    cellStyle() {
      return {
        color: '#606266',
        height: '50px',
        padding: '0',
        margin: '0',
        lineHeight: '50px'
      };
    },
  },
  methods: {
    // 处理选择变化
    handleSelectionChange(selection) {
      // 初始化过程中不触发事件，避免重复调用接口
      if (this.isInitializing) {
        return;
      }
      let selectedExamIds = selection.map(item => item.examId);
      // 传递选中的考试ID给父组件
      this.$emit('selection-change', selectedExamIds);
    },
    // 历史考试对比弹窗
    showExamCompareDialog() {
      this.showBenchTaskSelect = true;
    },
    // 获取选中的ID
    GetSelectId() {
      // 获取选中的考试ID
      const selectedExamIds = this.$store.state.report.lastExamSelectIds || [];
      // 通过事件将选中的考试ID传递给父组件
      this.$emit('select-exam-ids', selectedExamIds);
      // 关闭弹窗
      this.showBenchTaskSelect = false;
    },
    viewDetails(row) {
      this.paperTitle = `${row.examName}_${this.userInfo.userName}`
      this.paperInfo = { examId: this.reportParam.examId, subjectCode: this.reportParam.subjectCode }
      this.showStudentPaperDialog = true
      // 实际项目中可以跳转到详情页面或展开详情
    },
    // 处理分页变化
    handleCurrentChange(val) {
      this.currentPage = val;
      // 触发父组件的分页事件，以便重新获取数据
      this.$emit('page-change', { currentPage: val, pageSize: this.pageSize });
    },
  }
}
</script>

<style scoped lang="scss">
.myGradeHistory {
  background-color: #ffffff;
  border-radius: 10px;
  padding: 20px;
  box-sizing: border-box;

  .chart_title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    height: 36px;
    .title {
      font-size: 16px;
      font-weight: 600;
      color: #333333;

    }

    // 历史考试对比
    .compare_btn {
      font-size: 14px;
      padding: 8px 10px;
      background: #FFFFFF;
      border-radius: 4px;
      border: 1px solid #DCDFE6;
      color: #333333;
      display: flex;
      align-items: center;
      justify-content: center;

      .btn_icon {
        width: 16px;
        height: 16px;
        margin-right: 4px;
        vertical-align: middle;
      }

      span {
        vertical-align: middle;
      }
    }

    // 导出精准提升试题
    .export_btn {
      display: flex;
      align-items: center;
      gap: 5px;
      width: 152px;
      height: 36px;
      line-height: 36px;
      background: #2E64FA;
      color: white;
      border: none;
      border-radius: 4px;
      font-size: 14px;
      cursor: pointer;
      padding: 0;
      transition: all 0.3s ease;

      &:hover {
        background: #5883fb;
      }

      &:active {
        background: #2E64FA;
      }

      .iconfont {
        width: 14px;
        margin-left: 10px;
      }
    }
  }


  /* 表格区域 */
  .content {

    /* 调整表格斑马条纹颜色 */
    :deep(.el-table--striped .el-table__body tr.el-table__row--striped) {
      background-color: #FAFAFA !important;
    }

    /* 确保表头行高 */
    :deep(.el-table__header tr) {
      height: 50px !important;
    }

    /* 确保表格内容行高 */
    :deep(.el-table__body tr) {
      height: 50px !important;
    }

    /* 移除表头单元格内外边距 */
    :deep(.el-table__header th.el-table__cell) {
      padding: 0 !important;
      margin: 0 !important;
      height: 50px !important;
      line-height: 50px !important;
    }

    /* 移除表格内容单元格内外边距 */
    :deep(.el-table__body td.el-table__cell) {
      padding: 0 !important;
      margin: 0 !important;
      height: 50px !important;
      line-height: 50px !important;
    }

    /* 表格圆角样式 */
    :deep(.el-table) {
      border-radius: 6px !important;
      overflow: hidden;
    }

    /* 表头圆角 */
    :deep(.el-table__header-wrapper) {
      border-radius: 6px 6px 0 0;
      overflow: hidden;
    }

    /* 表尾圆角 */
    :deep(.el-table__body-wrapper) {
      border-radius: 0 0 6px 6px;
      overflow: hidden;
    }

    /* 表头首列圆角 */
    :deep(.el-table__header th.el-table__cell:first-child) {
      border-radius: 6px 0 0 0 !important;
    }

    /* 表头末列圆角 */
    :deep(.el-table__header th.el-table__cell:last-child) {
      border-radius: 0 6px 0 0 !important;
    }

    /* 表尾首列圆角 */
    :deep(.el-table__body tr:last-child td.el-table__cell:first-child) {
      border-radius: 0 0 0 6px !important;
    }

    /* 表尾末列圆角 */
    :deep(.el-table__body tr:last-child td.el-table__cell:last-child) {
      border-radius: 0 0 6px 0 !important;
    }

    .pagination {
      margin-top: 16px;
      display: flex;
      justify-content: flex-end;
      align-items: center;

      /* 分页器样式 */
      :deep(.el-pagination) {

        /* 分页按钮通用样式 */
        .el-pager li {
          height: 32px;
          line-height: 32px;
          border-radius: 4px;
          margin: 0 5px;

          /* 未选中状态 */
          background-color: #f3f3f3;
          color: #606266;

          /* 选中状态 */
          &.active {
            background-color: #2e64fa;
            color: #ffffff;
          }
        }

        /* 上一页/下一页按钮 */
        .btn-prev,
        .btn-next {
          height: 32px;
          line-height: 32px;
          border-radius: 4px;
          background-color: #f3f3f3;
          color: #606266;

          &:hover {
            background-color: #e6e8eb;
          }
        }
      }
    }
  }

  // 暂无数据样式
  .noData {
    position: relative;
    height: 220px;

    /* 暂无数据样式 */
    .no_data {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 14px;
      color: #909399;
      text-align: center;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 8px;

      span {
        margin-top: 11%;
      }
    }
  }
}
</style>