<template>
  <!-- 成绩查询 首页 -->
  <div class="page_report_main" ref="mainContent">
    <div class="page_filter">
      <FiltersItem :data="filtersData" @select="handleSelectChange" />
    </div>
    <div class="report_content" ref="reportContentRef">
      <router-view />
      <div
        class="report_bottom"
        v-if="route.name != 'score' && route.name != 'optionDetail'"
      >
        <div class="bottom_no_more">
          没有更多了，<span @click="goToPageTop">回到顶部</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import FiltersItem from "@/components/FiltersItem.vue";
// 重命名导入的 API 函数以避免冲突
import {
  findCommonSelectList,
  getAnalysisExamInfo,
  getIdByAiExamId,
} from "@/api/analysis";
import { onMounted, ref, computed } from "vue";
import { useRoute } from "vue-router";
import { useAnalysisStore } from "@/store/analysis";
import { useExamStore } from "@/store/exam";
import { ElMessage } from 'element-plus'

const examStore = useExamStore();
const analysisStore = useAnalysisStore();
const route = useRoute();
const reportContentRef = ref<HTMLElement | null>(null);

// 考试科目 code
const subjectCode = computed(() => {
  return examStore.currentExam?.examSubjectCode;
});
const aiExamId = computed(() => {
  return examStore.currentExam?.id || "";
});

// --- 类型定义 ---
interface FilterOption {
  label: string;
  value: string;
  [key: string]: any; // 保留用于动态属性，如 selectSchoolVoList 等
}

interface FilterItem {
  label: string;
  type:
    | "subjectName"
    | "schoolName"
    | "registrationType"
    | "scoreType"
    | "classType"
    | "className";
  list: FilterOption[];
  value: string;
}

// 简化接口定义，利用 TS 推断或保持必要结构
interface SubjectItem {
  subjectName: string;
  subjectCode: string;
  subjectId: string;
  isTotal: number | string;
  subjectGroupType: number;
  selectSchoolVoList: SchoolItem[];
  subjectGroupCodes: string;
}

interface SchoolItem {
  schoolId: string;
  schoolName: string;
  schoolLevel: string | number; // 兼容可能的数字类型
  schoolGroupId: string;
  selectStatusVoList: StatusItem[];
  schoolGroupNames: string;
}

interface StatusItem {
  statusName: string;
  statusGroupType: string;
  statusGroupId: string;
  examCommonSelectScoreList: ScoreTypeItem[];
  statusGroupNames: string;
}

interface ScoreTypeItem {
  scoreType: string;
  typeName: string;
  selectClassVoList: ClassTypeItem[];
}

interface ClassTypeItem {
  typeName: string;
  classType: string;
  selectInfoVoList: ClassItem[];
}

interface ClassItem {
  className: string;
  classLevel: string | number;
  classGroupId: string;
  classIdCode: string;
  classCode: string;
  classGroupNames: string;
}

interface FilterParams {
  examId: string;
  examLevel: number; // 修正为 number
  subjectCode: string;
  subjectName: string;
  subjectId: string;
  subjectGroupType: number;
  isTotal: number | string;
  subjectGroupCodes: string;
  schoolId: string;
  schoolLevel: number;
  schoolGroupId: string;
  schoolGroupName: string | null | undefined;
  schoolName: string | null;
  schoolGroupNames: string;
  registrationType: string;
  registrationName: string | null;
  registrationGroupId: string;
  statusGroupNames: string;
  scoreType: string;
  classType: string;
  classIdCode: string;
  classLevel: string | number;
  classGroupId: string;
  classGroupName: string;
  classGroupNames: string[];
}

// --- 状态数据 ---
const filtersData = ref<FilterItem[]>([
  { label: "科目名称", type: "subjectName", list: [], value: "" },
  { label: "学校名称", type: "schoolName", list: [], value: "" },
  { label: "学生类型", type: "registrationType", list: [], value: "" },
  { label: "分数类型", type: "scoreType", list: [], value: "" },
  { label: "班级类型", type: "classType", list: [], value: "" },
  { label: "班级名称", type: "className", list: [], value: "" },
]);
const examId = ref("");//2036963589738971137
// --- 工具函数 ---
const updateBySchool = (school: FilterOption) => {
  if (!school || !school.selectStatusVoList) return;

  const registrationTypeList: FilterOption[] = school.selectStatusVoList.map(
    (item: StatusItem) => ({
      label: item.statusName,
      value: `${item.statusGroupType || ""}${item.statusGroupId || ""}${item.statusName || ""}`,
      statusGroupType: item.statusGroupType,
      statusName: item.statusName,
      statusGroupId: item.statusGroupId,
      examCommonSelectScoreList: item.examCommonSelectScoreList,
      statusGroupNames: item.statusGroupNames,
    }),
  );

  filtersData.value[2].list = registrationTypeList;
  filtersData.value[2].value = registrationTypeList[0]?.value || "";
  updateByStatus(registrationTypeList[0]);
};

const updateByStatus = (status: FilterOption) => {
  if (!status || !status.examCommonSelectScoreList) return;

  const scoreTypeList: FilterOption[] = status.examCommonSelectScoreList.map(
    (item: ScoreTypeItem) => ({
      label: item.typeName,
      value: item.scoreType,
      selectClassVoList: item.selectClassVoList,
    }),
  );

  filtersData.value[3].list = scoreTypeList;
  filtersData.value[3].value = scoreTypeList[0]?.value || "";
  updateByScoreType(scoreTypeList[0]);
};

const updateByScoreType = (type: FilterOption) => {
  if (!type || !type.selectClassVoList) return;

  const classTypeList: FilterOption[] = type.selectClassVoList.map(
    (item: ClassTypeItem) => ({
      label: item.typeName,
      value: item.classType,
      selectInfoVoList: item.selectInfoVoList,
    }),
  );

  filtersData.value[4].list = classTypeList;
  filtersData.value[4].value = classTypeList[0]?.value || "";
  updateByClassType(classTypeList[0]);
};

const updateByClassType = (classType: FilterOption) => {
  if (!classType || !classType.selectInfoVoList) return;

  const classList: FilterOption[] = (classType.selectInfoVoList || []).map(
    (item: ClassItem) => ({
      label: item.className,
      value: `${item.classLevel || ""}${item.classGroupId || ""}${item.classIdCode || ""}`,
      classLevel: item.classLevel,
      className: item.className,
      classCode: item.classCode,
      classIdCode: item.classIdCode,
      classGroupId: item.classGroupId,
      classGroupNames: item.classGroupNames,
    }),
  );

  filtersData.value[5].list = classList;
  filtersData.value[5].value = classList[0]?.value || "";
};

// 构建筛选参数并保存
const buildAndSaveFilterParams = () => {
  const courseObj = filtersData.value[0].list.find(
    (item) => item.value === filtersData.value[0].value,
  );
  const schoolObj = filtersData.value[1].list.find(
    (item) => item.value === filtersData.value[1].value,
  );
  const statusObj = filtersData.value[2].list.find(
    (item) => item.value === filtersData.value[2].value,
  );
  const classObj = filtersData.value[5].list.find(
    (item) => item.value === filtersData.value[5].value,
  );

  if (!courseObj || !schoolObj || !statusObj) return;

  const filterObject: FilterParams = {
    examId: examId.value,
    examLevel: 2, // 单校
    subjectCode: courseObj.subjectCode,
    subjectName: courseObj.subjectName,
    subjectId: courseObj.subjectId,
    subjectGroupType: courseObj.subjectGroupType,
    isTotal: courseObj.isTotal,
    subjectGroupCodes: courseObj.subjectGroupCodes,

    schoolId: schoolObj.schoolId,
    schoolLevel: schoolObj.schoolLevel,
    schoolGroupId: schoolObj.schoolGroupId,
    schoolGroupName:
      schoolObj.schoolLevel === 0 || schoolObj.schoolLevel === 2
        ? null
        : schoolObj.schoolName,
    schoolName: schoolObj.schoolLevel === 2 ? schoolObj.schoolName : null,
    schoolGroupNames: schoolObj.schoolGroupNames,

    registrationType: statusObj.statusGroupType,
    registrationName:
      statusObj.statusName === "全部" ? null : statusObj.statusName,
    registrationGroupId: statusObj.statusGroupId,
    statusGroupNames: statusObj.statusGroupNames,

    scoreType: filtersData.value[3].value,
    classType: filtersData.value[4].value,

    classIdCode: classObj?.classIdCode || "",
    classLevel: classObj?.classLevel || 0,
    classGroupId: classObj?.classGroupId || "",
    classGroupName: classObj?.className || "",
    classGroupNames: classObj?.classGroupNames || [],
  };

  analysisStore.setFilterObject(filterObject);
};

// --- 业务逻辑 ---

// 初始化加载公共筛选列表
const getCommonSelectList = async () => {
  try {
    const res = await findCommonSelectList({ aiExamId: examId.value });
    if (res.code !== 200 || !res.data?.length) return;

    const subjectList: FilterOption[] = (res.data as SubjectItem[])
      .filter((item) => item.isTotal === 0)
      .map((item) => ({
        label: item.subjectName,
        value: item.subjectCode,
        subjectName: item.subjectName,
        subjectId: item.subjectId,
        subjectCode: item.subjectCode,
        isTotal: item.isTotal,
        subjectGroupType: item.subjectGroupType,
        isTotalScore: item.subjectGroupType === 1,
        isMulCourse: item.subjectGroupType === 1,
        selectSchoolVoList: item.selectSchoolVoList,
        subjectGroupCodes: item.subjectGroupCodes,
      }));

    if (!subjectList.length) return;

    filtersData.value[0].list = subjectList;
    filtersData.value[0].value = subjectList[0].value;

    const firstSubject = subjectList[0];
    if (!firstSubject.selectSchoolVoList) return;

    const schoolList: FilterOption[] = firstSubject.selectSchoolVoList.map(
      (item: SchoolItem) => ({
        label: item.schoolName,
        value: `${item.schoolLevel || ""}${item.schoolGroupId || ""}${item.schoolId || ""}`,
        schoolId: item.schoolId,
        schoolName: item.schoolName,
        schoolLevel: item.schoolLevel,
        schoolGroupId: item.schoolGroupId,
        selectStatusVoList: item.selectStatusVoList,
        schoolGroupNames: item.schoolGroupNames,
      }),
    );

    filtersData.value[1].list = schoolList;
    filtersData.value[1].value = schoolList[0]?.value || "";

    if (schoolList[0]) {
      updateBySchool(schoolList[0]);
    }
    analysisStore.setFiltersData(filtersData.value);
    buildAndSaveFilterParams();
  } catch (err) {
    console.error("获取筛选数据失败：", err);
  }
};

// 获取任务的相关配置和信息
const loadAnalysisExamInfo = async () => {
  try {
    // 如果 subjectCode 可能为空，可能需要处理
    const currentSubjectCode = subjectCode.value;
    if (!currentSubjectCode) {
      console.warn("Subject code is not available");
      return;
    }

    const res = await getAnalysisExamInfo({
      examId: examId.value,
      subjectCode: currentSubjectCode,
    });

    if (res.code === 200 && res.data) {
      const resData = res.data;
      const fiveRate = {
        3: "三率",
        4: "四率",
        5: "五率",
      };
      resData.fiveRateName = fiveRate[resData.fiveRateType];
      analysisStore.setAnalysisExamInfo(resData);
    }
  } catch (error) {
    console.error("获取分析考试信息失败:", error);
  }
};

// 筛选切换处理
const handleSelectChange = (index: number, value: string) => {
  filtersData.value[index].value = value;
  const selectedItem = filtersData.value[index].list.find(
    (item) => item.value === value,
  );
  if (!selectedItem) return;

  const { type } = filtersData.value[index];

  if (type === "subjectName") {
    if (!selectedItem.selectSchoolVoList) return;
    const schoolList: FilterOption[] = selectedItem.selectSchoolVoList.map(
      (item: SchoolItem) => ({
        label: item.schoolName,
        value: `${item.schoolLevel || ""}${item.schoolGroupId || ""}${item.schoolId || ""}`,
        schoolId: item.schoolId,
        schoolName: item.schoolName,
        schoolLevel: item.schoolLevel,
        schoolGroupId: item.schoolGroupId,
        selectStatusVoList: item.selectStatusVoList,
        schoolGroupNames: item.schoolGroupNames,
      }),
    );
    filtersData.value[1].list = schoolList;
    filtersData.value[1].value = schoolList[0]?.value || "";
    if (schoolList[0]) {
      updateBySchool(schoolList[0]);
    }
  } else if (type === "schoolName") {
    updateBySchool(selectedItem);
  } else if (type === "registrationType") {
    updateByStatus(selectedItem);
  } else if (type === "scoreType") {
    updateByScoreType(selectedItem);
  } else if (type === "classType") {
    updateByClassType(selectedItem);
  }
  analysisStore.setFiltersData(filtersData.value);
  buildAndSaveFilterParams();
};
// 回到顶部
const goToPageTop = () => {
  reportContentRef.value?.scrollTo({ top: 0, behavior: "smooth" });
};

onMounted(async () => {
  // 根据选择题判分系统ID获取考试的examId
  const res = await getIdByAiExamId({
    aiExamId: aiExamId.value,
  });
  if (res.code === 200 && res.data) {
    examId.value = res.data;
  }else{
    ElMessage.error("获取考试信息失败");
    // return;
  }
  if (analysisStore?.filtersData?.length) {
    filtersData.value = analysisStore.filtersData;
  } else {
    getCommonSelectList();
  }
  loadAnalysisExamInfo();
});
</script>

<style lang="scss" scoped>
.report_bottom {
  width: 100%;
  padding: 20px 0;
  text-align: center;
}

.bottom_no_more {
  font-size: 14px;
  color: #666;

  span {
    color: #2e64fa;
    font-weight: 500;
    cursor: pointer;
  }
}
</style>
