<template>
  <!-- 成绩查询 成绩单 -->
  <ReportModule
    ref="reportModuleRef"
    :titleList="['错题分析表']"
    :showDescribe="false"
    tableOrChart="table"
    :showTablePage="false"
    @ExportExcel="ExportExcel"
    @PrintPdf="PrintPdf"
  >
    <template #module_table_chart>
      <el-table
        :data="state.tableData"
        border
        stripe
        row-key="questionId"
        max-height="700"
        :span-method="SpanMethod"
        :row-class-name="ErrorTableRowClassName"
        :cell-class-name="ErrorTableCellClassName"
        v-loading="state.tableLoading"
        :element-loading-text="state.loadingText"
        :element-loading-spinner="loadingSvgIcon"
        element-loading-background="#ffffff"
      >
        <el-table-column
          prop="questionName"
          label="小题名称"
          width="80"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="questionType"
          label="题型"
          width="80"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="questionScore"
          label="满分"
          width="70"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="difficulty"
          label="难度"
          width="70"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="discrimination"
          label="区分度"
          width="80"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="averageScore"
          label="平均分"
          width="70"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="scoreRate"
          label="得分率"
          width="80"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="studentCount"
          label="答题人数"
          width="80"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="errorCount"
          label="错题人数"
          width="80"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          prop="answerValue"
          label="正确答案"
          width="80"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.answerValue ?? "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="errorDetail" label="错题详情" align="center">
          <el-table-column
            :align="key == 'registrationCodeList' ? 'left' : 'center'"
            v-for="(key, index) in [
              'name',
              'rate',
              'studentNum',
              'registrationCodeList',
            ]"
            :key="key"
            label=""
            :prop="key"
            :min-width="[60, 70, 60, 384][index]"
            :show-overflow-tooltip="
              key == 'registrationCodeList' ? false : true
            "
          >
            <template #default="{ row: org }">
              <span v-if="key == 'registrationCodeList'">{{ org[key] }}</span>
              <span v-else-if="key == 'rate'">{{
                org[key] == "-" ? "-" : `${org[key]}%`
              }}</span>
              <span v-else>{{ org[key] }}</span>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </template>
  </ReportModule>
  <ErrorsPdf
    ref="errPdfReport"
    :tableData="state.tableData"
    :className="analysisStore.filterObject.classGroupName"
    :subjectName="analysisStore.filterObject.subjectName || ''"
    :examName="getExamName"
    @PdfLoadEnd="PdfLoadEnd"
  />
</template>
<script lang="ts" setup>
import ReportModule from "@/components/ReportModule.vue";
import { useAnalysisStore } from "@/store/analysis";
import ErrorsPdf from "@/components/ErrorsPdf.vue";
import { onMounted, reactive, computed, ref, watch } from "vue";
import { errorQuestionAnalysis, exportErrorQuestion } from "@/api/analysis";
import { loadingSvgIcon } from "@/utils/common";
import {
  downloadExcel,
  GetExcelFileName,
  errorQuestionDataStaticHeaderData,
  errorQuestionDataChildHeaderData,
} from "@/utils/exportExcel";

// 定义表格行数据类型
interface TableDataItem {
  questionId: string | number;
  questionName?: string;
  questionType?: string;
  questionScore?: number | string;
  difficulty?: number | string;
  discrimination?: number | string;
  averageScore?: number | string;
  scoreRate?: number | string;
  studentCount?: number;
  errorCount?: number;
  answerValue?: string;
  answerList?: any[];
  questionStatsList?: any[];
  rowspan?: number;
  colspan?: number;
  rowKey?: number;
  rowspanIndex?: number;
  [key: string]: any;
}

const state = reactive<{
  tableData: TableDataItem[];
  tableLoading: boolean;
  loadingText: string;
}>({
  tableData: [],
  tableLoading: true,
  loadingText: "加载中,请稍后...",
});

const analysisStore = useAnalysisStore();
const reportModuleRef = ref<any>(null);
const errPdfReport = ref<any>(null);

const getExamName = computed(() => {
  return analysisStore.analysisExamInfo.examName || "";
});

// 错题分析
const GetErrorQuestionAnalysis = async () => {
  state.tableLoading = true;
  const res: any = await errorQuestionAnalysis({
    ...(analysisStore.filterObject as any),
  });

  if (res.code === 200) {
    const allTableData = res.data || [];
    state.tableData = [];
    const tableData = allTableData.filter((item: any) => {
      if (analysisStore.filterObject.classLevel == 0) {
        return item.classIdCode.indexOf("school") > -1;
      } else {
        return item.className == analysisStore.filterObject.classGroupName;
      }
    });

    if (tableData?.length) {
      tableData[0].questionStatsList.forEach((item: any, key: number) => {
        const answerListLen = item?.answerList?.length || 0;
        if (answerListLen == 0) {
          item.answerList = [
            {
              name: "-",
              rate: "-",
              registrationCodeList: "-",
              score: "-",
              studentNum: "-",
            },
          ];
        }
        const rowspan = item.answerList.length;
        item.answerList.forEach((answer: any, index: number) => {
          if (index == 0) {
            state.tableData.push({
              ...item,
              scoreRate: `${item.scoreRate}%`,
              ...answer,
              rowspan: rowspan, // 合并行
              colspan: 1,
              rowKey: index, // 行索引
              rowspanIndex: key, // 合并行之后的索引
            });
          } else {
            state.tableData.push({
              ...item,
              questionId: `${item.questionId}_${index}`,
              scoreRate: `${item.scoreRate}%`,
              ...answer,
              rowKey: index, // 行索引
              rowspanIndex: key, // 合并行之后的索引
            });
          }
        });
      });
    }
  } else {
    state.tableData = [];
  }
  state.tableLoading = false;
};

// 错题分析  合并单元格
const SpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  const props = [
    "errorDetail",
    "name",
    "rate",
    "studentNum",
    "registrationCodeList",
  ];
  if (props.indexOf(column.property) == -1) {
    if (row.rowspan) {
      return {
        rowspan: row.rowspan,
        colspan: row.colspan,
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0,
      };
    }
  }
};

// 定义行样式
const ErrorTableRowClassName = ({ row, rowIndex }: any) => {
  if (row.rowspanIndex % 2 === 0) {
    return "row_color_FFFFFF";
  } else {
    return "row_color_FAFAFA";
  }
};

// 设置单元格样式
const ErrorTableCellClassName = ({
  row,
  column,
  rowIndex,
  columnIndex,
}: any) => {
  if (column.property == "registrationCodeList") {
    return "white_space_normal";
  } else {
    return "";
  }
};

// 导出Excel
const ExportExcel = () => {
  // 1. 设置加载状态
  reportModuleRef.value?.SetExportLoading?.(true);

  // 2. 参数
  const examName = getExamName.value;
  let params: any = {
    fileName: `${GetExcelFileName(examName, analysisStore.filterObject as any, "错题分析表")}`,
    examName: examName, // 考试名称
    sheetName: "错题分析表", // sheet页名称
  };

  const staticHeader: any[] = errorQuestionDataStaticHeaderData();
  const childHeader = ["name", "rate", "studentNum", "registrationCodeList"];
  const childHeaderData: any[] = errorQuestionDataChildHeaderData(childHeader);
  const staticHeaderData = [...staticHeader, ...childHeaderData];

  params.staticHeaderData = staticHeaderData;
  params.childHeaderData = [];
  params.dynamicsHeaderData = [];

  let dataList: any[] = [];
  state.tableData.forEach((item) => {
    const rowData: any[] = [];
    staticHeaderData.forEach((header: any) => {
      if (header.prop == "rate") {
        const rate = `${item[header.prop]}${item[header.prop] == "-" ? "" : "%"}`;
        rowData.push(rate);
      } else {
        rowData.push(item?.[header.prop] ?? "-");
      }
    });
    dataList.push(rowData);
  });

  params.dataList = dataList;
  params.mergeColumn = staticHeader.length - 1; // 合并的列

  // 3. 调用通用下载方法，并在完成后重置加载状态
  downloadExcel(exportErrorQuestion, params).finally(() => {
    reportModuleRef.value?.SetExportLoading?.(false);
  });
};

// 导出PDF
const PrintPdf = () => {
  reportModuleRef.value?.SetPrintLoading?.(true);
  errPdfReport.value?.DownloadPdf?.();
};

// 导出PDF  加载完成
const PdfLoadEnd = () => {
  reportModuleRef.value?.SetPrintLoading?.(false);
};

// 初始化
const pageInit = () => {
  GetErrorQuestionAnalysis();
};

// 监听筛选条件
watch(
  () => analysisStore.filterObject,
  async () => {
    pageInit();
  },
  { deep: true },
);

onMounted(() => {
  pageInit();
});
</script>

<style lang="scss" scoped>
:deep(.el-table) {
  .el-table__header-wrapper {
    .el-table__header {
      .is-group {
        tr {
          &:nth-child(2) {
            display: none;
          }
        }
      }
    }
  }

  .el-table__cell {
    &.white_space_normal {
      .cell {
        white-space: normal;
        padding: 10px 0 10px 10px !important;
      }
    }
  }

  &.el-table--striped {
    .el-table__body {
      tr {
        &.el-table__row--striped {
          &.row_color_FFFFFF {
            td.el-table__cell {
              background: #ffffff;
            }
          }
        }
      }
    }
  }

  &.el-table--striped
    .el-table__body
    tr.el-table__row.row_color_FAFAFA
    td.el-table__cell {
    background: #fafafa;
  }

  &.el-table--striped
    .el-table__body
    tr.el-table__row--striped.row_color_FAFAFA
    td.el-table__cell {
    background: #fafafa;
  }

  &.el-table--enable-row-hover .el-table__body tr.row_color_FFFFFF > td {
    background-color: transparent !important;
  }
}
</style>
