<template>
  <ReportModule
    tableOrChart="qita"
    :showHeader="false"
    :showTitle="false"
    :showPrintBtn="false"
    :showExportBtn="false"
    :showDescribe="false"
  >
    <template #module_qita>
      <ModuleTab :tabList="state.tabList" @TabChange="TabChange"></ModuleTab>
    </template>
  </ReportModule>
  <ReportModule
    :titleList="[`1、${state.groupTitle}分析图`]"
    tableOrChart="chart"
    :showPrintBtn="false"
    :showExportBtn="false"
  >
    <template #title_right>
      <!-- 五率综合分析图类型切换 -->
      <EchartType
        v-if="state.tabActive == 'rateAll'"
        :chartTypeList="state.fiveRateData.chartTypeList"
        :current="state.fiveRateData.chartType"
        @ChangeEchartType="(val) => ChangeEchartType(val, 'fiveRateData')"
      />
      <!-- 得分率/五率分析图类型切换 -->
      <EchartType
        v-if="
          state.tabActive == '2' ||
          state.tabActive == 'high' ||
          state.tabActive == 'good' ||
          state.tabActive == 'fine' ||
          state.tabActive == 'pass' ||
          state.tabActive == 'low'
        "
        :chartTypeList="state.analysisData.chartTypeList"
        :current="state.analysisData.chartType"
        @ChangeEchartType="(val) => ChangeEchartType(val, 'analysisData')"
      />
      <!-- 平均分排序选项 -->
      <div
        class="right_item no_border"
        v-if="state.tabActive == '0'"
        v-for="item in state.sortOption"
        :key="item.value"
        :class="state.sortValue == item.value ? 'item_active' : ''"
        @click="ChangeChartOrder(item.value)"
      >
        {{ item.label }}
      </div>
    </template>
    <template #module_table_chart>
      <template v-if="state.analysisData.tableData.length > 0">
        <!-- 五率综合分析图 -->
        <template v-if="state.tabActive == 'rateAll'">
          <template v-if="state.fiveRateData.chartType == 'stacked_chart'">
            <BarStackChartVertical
              :data="state.fiveRateData.data"
              :tooltipData="state.fiveRateData.tooltipData"
              :color="state.fiveRateData.color"
            >
            </BarStackChartVertical>
          </template>
          <template v-if="state.fiveRateData.chartType == 'vertical_bar'">
            <BarsCharts
              :data="state.fiveRateData.data"
              :fiveTooltipData="state.fiveRateData.tooltipData"
              :color="state.fiveRateData.color"
              unit="%"
            ></BarsCharts>
          </template>
          <template v-if="state.fiveRateData.chartType == 'horizontal_bar'">
            <BarStackChartHorizontal
              :data="state.fiveRateData.data"
              :tooltipData="state.fiveRateData.tooltipData"
              :color="state.fiveRateData.color"
            >
            </BarStackChartHorizontal>
          </template>
        </template>
        <!-- 其他分析图 -->
        <template v-else>
          <!-- 平均分 -->
          <template v-if="state.tabActive == '0'">
            <BarChart
              :datax="state.analysisData.datax"
              :tooltipData="state.analysisData.tooltipData"
              :typeName="state.groupTitle"
              :datay="state.analysisData.datay"
              :unit="state.analysisData.unit"
              :color="state.analysisData.color"
              :markLineData="state.analysisData.markLineData"
            ></BarChart>
          </template>
          <!-- 标准分/超均分/超均率 -->
          <template
            v-else-if="
              state.tabActive == '1' ||
              state.tabActive == '3' ||
              state.tabActive == '4'
            "
          >
            <DifferenceChart
              :datax="state.analysisData.datax"
              :tooltipData="state.analysisData.tooltipData"
              :unit="state.tabActive == '4' ? '%' : ''"
              :datay="state.analysisData.datay"
              :rate="0"
            ></DifferenceChart>
          </template>
          <!-- 得分率 -->
          <template v-else-if="state.tabActive == '2'">
            <template v-if="state.analysisData.chartType == 'vertical_bar'">
              <BarScoringRateVertical
                v-if="state.analysisData.datax.length > 0"
                :datax="state.analysisData.datax"
                :tooltipData="state.analysisData.tooltipData"
                :typeName="state.groupTitle"
                :datay="state.analysisData.dataStackY"
                unit="%"
                :color="['#3BA272', '#EE6666']"
                :average="state.analysisData.average"
                :markLineData="state.analysisData.markLineData"
              >
              </BarScoringRateVertical>
            </template>
            <template v-if="state.analysisData.chartType == 'horizontal_bar'">
              <BarScoringRateHorzontal
                v-if="state.analysisData.datax.length > 0"
                :datax="state.analysisData.datax"
                :datay="state.analysisData.dataStackY"
                :tooltipData="state.analysisData.tooltipData"
                :typeName="state.groupTitle"
                :color="['#3BA272', '#EE6666']"
                :average="state.analysisData.average"
                :markLineData="state.analysisData.markLineData"
              ></BarScoringRateHorzontal>
            </template>
          </template>
          <!-- 五率（优秀率/良好率/及格率/低分率等） -->
          <template v-else>
            <template v-if="state.analysisData.chartType == 'vertical_bar'">
              <BarChart
                :datax="state.analysisData.datax"
                :tooltipData="state.analysisData.tooltipData"
                :typeName="state.groupTitle"
                :datay="state.analysisData.datay"
                unit="%"
                :color="state.analysisData.color"
                :markLineData="state.analysisData.markLineData"
              ></BarChart>
            </template>
            <template v-if="state.analysisData.chartType == 'horizontal_bar'">
              <BarChartHorizontal
                :datax="state.analysisData.datax"
                :datay="state.analysisData.datay"
                :tooltipData="state.analysisData.tooltipData"
                :typeName="state.groupTitle"
                :color="state.analysisData.color"
                :markLineData="state.analysisData.markLineData"
              ></BarChartHorizontal>
            </template>
          </template>
        </template>
      </template>
      <!-- 无数据占位 -->
      <div
        v-else
        class="no_content_data"
        v-loading="state.analysisLoading"
        :element-loading-text="state.loadingText"
        :element-loading-spinner="loadingSvgIcon"
        element-loading-background="#ffffff"
      >
        <span>暂无数据</span>
      </div>
    </template>
    <template #module_describe>
      <div v-html="state.analysisData.expandableText"></div>
    </template>
  </ReportModule>
  <!-- 分析表 -->
  <ReportModule
    ref="reportModuleRef"
    :titleList="[`2、${state.groupTitle}分析表`]"
    tableOrChart="table"
    :showPrintBtn="false"
    :showDescribe="false"
    :currentPage="state.analysisData.pageNum"
    :pageSize="state.analysisData.pageSize"
    :total="state.analysisData.total"
    @ChangePageSize="ChangePageSize"
    @ChangeCurrentPage="ChangeCurrentPage"
    @ExportExcel="ExportExcel"
  >
    <template #title_right>
      <SetTableHeader
        :data="{
          static: state.analysisData.headerData.static,
          dynamisc: [],
          child: state.analysisData.headerData.child,
        }"
        :notEditable="['序号', '班级']"
        @SetEnterHeaderData="SetEnterHeaderData"
      ></SetTableHeader>
    </template>
    <template #module_table_chart>
      <el-table :data="analysisTableData" border stripe align="left">
        <!-- 静态表头列 -->
        <template
          v-for="(header, headerIndex) in state.analysisData.staticHeader"
        >
          <el-table-column
            align="center"
            :prop="header.prop"
            :label="header.label"
            show-overflow-tooltip
            v-if="header.label == '班级'"
            width="150"
            fixed="left"
            :key="`${header.prop}_${headerIndex}`"
          >
            <template #default="scope">
              {{ scope.row[header.prop] || scope.row.keyName }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :prop="header.prop"
            :label="header.label"
            show-overflow-tooltip
            v-else-if="header.label == '教师'"
            fixed="left"
            :key="`techer_${header.prop}_${headerIndex}`"
          >
            <template #default="scope">
              {{ scope.row[header.prop] || "-" }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :prop="header.prop"
            :label="header.label"
            show-overflow-tooltip
            v-else-if="header.label == '科目' || header.label == '序号'"
            fixed="left"
            :key="`subject_${header.prop}_${headerIndex}`"
          >
          </el-table-column>
          <el-table-column
            align="center"
            :prop="header.prop"
            :label="header.label"
            show-overflow-tooltip
            v-else-if="header.label == '平均分'"
            :key="`average_${header.prop}_${headerIndex}`"
          >
            <template #default="scope">
              {{ scope.row.fiveRateResultVo?.[header.prop] || "-" }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :prop="header.prop"
            :label="header.label"
            v-else
            :key="`qita_${header.prop}_${headerIndex}`"
          >
            <template #default="scope">
              {{ scope.row.fiveRateResultVo?.[header.prop] || "-"
              }}<span
                v-if="
                  header.label.includes('率') &&
                  scope.row.fiveRateResultVo?.[header.prop] &&
                  scope.row.fiveRateResultVo?.[header.prop] != '-'
                "
                >%</span
              >
            </template>
          </el-table-column>
        </template>
        <!-- 动态表头列（五率详情） -->
        <el-table-column
          align="center"
          :label="`${header.name}`"
          v-for="(header, headerIndex) in state.analysisData.dynamicsHeader"
          :key="`${header.prop}_${headerIndex}`"
        >
          <el-table-column
            align="center"
            :label="child.label"
            v-for="(child, childIndex) in header.headerList"
            width="120"
            :key="childIndex"
          >
            <template #default="scope">
              <template v-if="child.prop.includes('Num')">
                <span
                  class="table_row_blue"
                  @click="OpenStudentDialog(scope.row, header, child)"
                  v-if="scope.row.fiveRateResultVo?.[child.prop] > 0"
                >
                  {{ scope.row.fiveRateResultVo?.[child.prop] }}
                </span>
                <span v-else>{{
                  scope.row?.fiveRateResultVo?.[child.prop] ?? 0
                }}</span>
              </template>
              <template v-else>
                {{ scope.row.fiveRateResultVo?.[child.prop] || "-"
                }}<span
                  v-if="
                    child.prop.includes('Rate') && !child.prop.includes('Rank')
                  "
                  >%</span
                >
              </template>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </template>
  </ReportModule>
  <StudentList
    :showDialog.sync="state.dialogData.showDialog"
    :title="state.dialogData.title"
    :tableTitle="state.dialogData.tableTitle"
    apiName="contrastStudentInfo"
    :studentParam="{
      fiveRateName: state.dialogData.fiveRateName, //当前选择的五率的名称
      selectSubjectName: state.dialogData.selectSubjectName, //当前选择的科目名称
      selectSchoolLevel: state.dialogData.selectSchoolLevel, //当前选择的学校级别：0-联考 1-学校分组 2-具体学校
      selectSchoolName: state.dialogData.selectSchoolName, //当前选择的学校名称：联校 组合学校 单校名称
      selectClassLevel: state.dialogData.selectClassLevel, //当前选择的班级级别：0-年级 1-组合班级 2-具体班级
      selectClassName: state.dialogData.selectClassName, //当前选择的班级名称：年级 组合班级 单班
      titleType: 0,
      paperTypeName: '',
    }"
    @CloseDialog="CloseDialog"
  >
  </StudentList>
</template>

<script lang="ts" setup>
import ReportModule from "@/components/ReportModule.vue";
import ModuleTab from "@/components/ModuleTab.vue";
import EchartType from "@/components/EchartType.vue";
import BarChart from "@/components/echarts/barChart.vue"; //单柱状图组件
import BarsCharts from "@/components/echarts/barsCharts.vue"; //多柱状图组件
import BarChartHorizontal from "@/components/echarts/barHorizontal.vue"; //横向柱状图
import BarScoringRateVertical from "@/components/echarts/barScoringRate_vertical.vue"; //得分率 纵向柱状图
import BarScoringRateHorzontal from "@/components/echarts/barScoringRate_horzontal.vue"; //得分率 横向柱状图
import BarStackChartVertical from "@/components/echarts/barStackChart_vertical.vue"; //竖向堆叠条形图
import BarStackChartHorizontal from "@/components/echarts/barStackChart_horzontal.vue"; //横向堆叠条形图
import DifferenceChart from "@/components/echarts/differenceChart.vue"; //率差图
import StudentList from "@/components/studentList.vue"; //学生列表弹窗组件
import SetTableHeader from "@/components/SetTableHeader.vue";
import { onMounted, reactive, computed, watch, ref } from "vue";
import { useAnalysisStore } from "@/store/analysis";
import { classContrastSubjectTable, publicExportFive } from "@/api/analysis";
import { getSchoolFiveRateColor, loadingSvgIcon } from "@/utils/common";
import { downloadExcel, GetExcelFileName } from "@/utils/exportExcel";
import { cloneDeep } from "lodash-es";

// ================= 类型定义 =================

/** Tab 选项类型 */
interface TabItem {
  title: string;
  value: string;
}

/** 图表类型选项 */
interface ChartTypeOption {
  label: string;
  value: string;
}

/** 排序选项 */
interface SortOption {
  value: string;
  label: string;
}

/** 五率数据项 */
interface FiveRateItem {
  title: string;
  value: string;
}

/** 图表数据项（包含五率结果） */
interface ChartDataItem {
  keyName: string;
  isLine?: boolean;
  isShow?: boolean;
  showCharts?: boolean;
  classLevel?: number;
  schoolLevel?: number;
  teacherName?: string;
  fiveRateResultVo?: Record<string, any>;
  totalSubject?: ChartDataItem;
  mergeSubjects?: ChartDataItem[];
  subjectList?: ChartDataItem[];
  [key: string]: any;
}

/** 表头项 */
interface HeaderItem {
  prop: string;
  label: string;
  display?: boolean;
  name?: string;
  value?: string;
  headerList?: HeaderItem[];
}

/** 悬浮提示数据项 */
interface TooltipItem {
  list: Array<{ name: string; value: any }>;
  name: string;
}

/** 五率综合分析数据 */
interface FiveRateData {
  tooltipData: any[];
  chartData: ChartDataItem[];
  chartTypeList: ChartTypeOption[];
  chartType: string;
  data: (string | number)[][];
  color: string[];
}

/** 班级分析数据 */
interface AnalysisData {
  chartTypeList: ChartTypeOption[];
  chartType: string;
  datax: string[];
  datay: (string | number)[];
  dataStackY: (string | number)[][];
  color: string | string[];
  unit: string;
  tooltipData: TooltipItem[];
  chartData: ChartDataItem[];
  chartDatas: ChartDataItem[];
  avgScoreChartData: Array<{ x: string; y: number; tip: TooltipItem }>;
  tableData: any[];
  tableDatas: any[];
  headerData: {
    static: HeaderItem[];
    dynamisc: HeaderItem[];
    child: HeaderItem[];
  };
  staticHeader: HeaderItem[];
  dynamicsHeader: HeaderItem[];
  childHeader: HeaderItem[];
  pageSize: number;
  total: number;
  pageNum: number;
  expandableText: string;
  average?: number;
  markLineData?: Array<{ legendName: string; value: number; isShow?: boolean }>;
}
/** 弹窗数据类型 */
interface DialogData {
  showDialog: boolean;
  studentRegistrationCode: any[];
  title: string;
  tableTitle: string;
  fiveRateName: string;
  selectSubjectName: string;
  selectSchoolLevel: string | number;
  selectSchoolName: string;
  selectClassLevel: string | number;
  selectClassName: string;
}
/** 页面状态类型 */
interface PageState {
  fiveRateList: FiveRateItem[];
  rateName: string;
  tabList: TabItem[];
  tabActive: string;
  fiveRateData: FiveRateData;
  analysisData: AnalysisData;
  analysisLoading: boolean;
  loadingText: string;
  rankType: number;
  groupTitle: string;
  sortValue: string;
  sortOption: SortOption[];
  dialogData: DialogData;
}

// ================= 组件引用 & Store =================

const reportModuleRef = ref<InstanceType<typeof ReportModule> | null>(null);
const analysisStore = useAnalysisStore();
const filterObject = computed(() => analysisStore.filterObject || {});
const schoolLevel = computed(() => analysisStore.filterObject.schoolLevel);

/** 考试名称计算属性 */
const getExamName = computed(() => {
  return analysisStore.analysisExamInfo.examName || "";
});

// ================= 响应式状态 =================

const state = reactive<PageState>({
  fiveRateList: [] as FiveRateItem[], // 五率列表
  rateName: "", // 五率名称
  tabList: [
    { title: "平均分", value: "0" },
    { title: "标准分", value: "1" },
    { title: "得分率", value: "2" },
    { title: "超均分", value: "3" },
    { title: "超均率", value: "4" },
  ] as TabItem[], // 固定的 0平均分 1标准分 2得分率 3超均分 4超均率
  tabActive: "0", // 当前选择的tab
  fiveRateData: {
    tooltipData: [],
    chartData: [],
    chartTypeList: [
      { label: "堆积图", value: "stacked_chart" },
      { label: "柱状图", value: "vertical_bar" },
      { label: "条形图", value: "horizontal_bar" },
    ],
    chartType: "stacked_chart", // 图类型 默认堆积图
    data: [], // 数据集
    color: ["#5470C6", "#3BA272", "#FAC858", "#995FB3", "#EE6666"], // 对应颜色值
  },
  analysisData: {
    chartTypeList: [
      { label: "柱状图", value: "vertical_bar" },
      { label: "条形图", value: "horizontal_bar" },
    ],
    chartType: "vertical_bar", // 图表类型 默认柱状图
    datax: [], // x轴数据
    datay: [], // y轴数据
    dataStackY: [], // 得分率y轴数据
    color: "#5470C6", // 柱状图颜色
    unit: "", // 单位
    tooltipData: [],
    chartData: [], // 图表原始数据（年级在前）
    chartDatas: [],
    avgScoreChartData: [],
    tableData: [], // 班级分析表原始数据（年级在后）
    tableDatas: [], // 班级分析表展示数据
    headerData: {
      static: [],
      dynamisc: [],
      child: [],
    },
    staticHeader: [],
    dynamicsHeader: [],
    childHeader: [],
    pageSize: 10,
    total: 0,
    pageNum: 1,
    expandableText: "",
    average: 0,
    markLineData: [],
  },
  analysisLoading: false, // 班级分析表加载中
  loadingText: "加载中,请稍后...",
  rankType: 2, // 超均分/超均率 联1 校2切换
  groupTitle: "平均分", // 默认平均分
  sortValue: "1",
  sortOption: [
    { value: "1", label: "默认" },
    { value: "2", label: "升序" },
    { value: "3", label: "降序" },
  ],
  dialogData: {
    showDialog: false,
    studentRegistrationCode: [],
    title: "",
    tableTitle: "",
    fiveRateName: "", //当前选择的五率的名称
    selectSubjectName: "", //当前选择的科目名称
    selectSchoolLevel: "", //当前选择的学校级别：0-联考 1-学校分组 2-具体学校
    selectSchoolName: "", //当前选择的学校名称：联校 组合学校 单校名称
    selectClassLevel: "", //当前选择的班级级别：0-年级 1-组合班级 2-具体班级
    selectClassName: "", //当前选择的班级名称：年级 组合班级 单班
  }, // 弹框的数据
});

// ================= 计算属性 =================

/** 班级分析表表格数据（分页后） */
const analysisTableData = computed(() => {
  const { tableDatas, pageSize, pageNum } = state.analysisData;
  const start = (pageNum - 1) * pageSize;
  const end = start + pageSize;
  return tableDatas.slice(start, end);
});

// ================= 事件处理函数 =================

/** 切换 Tab */
const TabChange = (item: TabItem) => {
  state.tabActive = item.value;
  state.groupTitle = item.title;
  state.sortValue = "1";
  state.analysisData.pageNum = 1;
  state.rankType = 1;
  if (state.tabActive == "rateAll") {
    GetAnalysisFiveRateData(); // 设置分析五率数据
  } else {
    ChangeChartBarData(); // 切换分析图数据
  }
};

/** 切换图表类型 */
const ChangeEchartType = (
  val: string | number,
  prop: "fiveRateData" | "analysisData",
) => {
  state[prop].chartType = String(val);
};

// ================= 数据获取与处理 =================

/** 获取班级分析数据 */
const GetSingleClassAnalysisData = () => {
  const params = {
    ...filterObject.value,
    titleType: 0,
  };
  state.analysisLoading = true;
  classContrastSubjectTable(params).then((res: any) => {
    if (res.code == 200) {
      let chartData: ChartDataItem[] = []; // 图表原始数据（年级在最前）
      let tableData: any[] = []; // 表格原始数据（年级在最后）
      let tableDatas: any[] = []; // 显示各班的表格数据

      if (res.data.classDataList && res.data.classDataList.length > 0) {
        // 根据学校层级处理图表数据
        if (schoolLevel.value == 0) {
          res.data.examDataList?.forEach((item: ChartDataItem) => {
            chartData.push({ ...item, isLine: true, isShow: true });
          });
        }
        if (schoolLevel.value == 1) {
          res.data.examDataList?.forEach((item: ChartDataItem) => {
            chartData.push({ ...item, isLine: true });
          });
          res.data.schoolGroupDataList?.forEach((item: ChartDataItem) => {
            chartData.push({ ...item, isLine: true, isShow: true });
          });
        }
        if (schoolLevel.value == 2) {
          res.data.examDataList?.forEach((item: ChartDataItem) => {
            chartData.push({ ...item, isLine: true });
          });
          res.data.schoolGroupDataList?.forEach((item: ChartDataItem) => {
            chartData.push({ ...item, isLine: true });
          });
          res.data.schoolDataList?.forEach((item: ChartDataItem) => {
            chartData.push({
              ...item,
              isLine: true,
              isShow: filterObject.value.classLevel != 1,
            });
          });
        }
        // 组合班级
        res.data.classGroupDataList?.forEach((item: ChartDataItem) => {
          chartData.push({
            ...item,
            isLine: filterObject.value.classLevel == 1,
            isShow: filterObject.value.classLevel == 1,
          });
        });
        // 单班
        res.data.classDataList?.forEach(
          (item: ChartDataItem, index: number) => {
            chartData.push(item);
            item.subjectList?.forEach((i: any, key: number) => {
              if (key == 0) i.index = index + 1;
              tableData.push(i);
              tableDatas.push(i);
            });
          },
        );
        // 组合班级
        res.data.classGroupDataList?.forEach((item: ChartDataItem) => {
          item.subjectList?.forEach((i: any, key: number) => {
            if (key == 0) i.index = "-";
            tableDatas.push(i);
            tableData.push(i);
          });
        });
        // 单校
        res.data.schoolDataList?.forEach((item: ChartDataItem) => {
          item.subjectList?.forEach((i: any, key: number) => {
            if (key == 0) i.index = "-";
            tableDatas.push(i);
            tableData.push(i);
          });
        });
        // 组合学校
        res.data.schoolGroupDataList?.forEach((item: ChartDataItem) => {
          item.subjectList?.forEach((i: any, key: number) => {
            if (key == 0) i.index = "-";
            tableDatas.push(i);
            tableData.push(i);
          });
        });
        // 联校
        res.data.examDataList?.forEach((item: ChartDataItem) => {
          item.subjectList?.forEach((i: any, key: number) => {
            if (key == 0) i.index = "-";
            tableDatas.push(i);
            tableData.push(i);
          });
        });
      }

      // 过滤并重新编号
      let list = [...tableDatas];
      tableDatas = list
        .filter((item) => item.showCharts)
        .map((item, index) => {
          if (item.schoolLevel == 2 && item.classLevel == 2) {
            item.index = index + 1;
          } else {
            item.index = "-";
          }
          return item;
        });

      // 处理表头
      let childHeaderList: HeaderItem[] = [];
      let dynamicsHeader: HeaderItem[] = [];
      res.data.fiveRateHeaderList?.forEach((item: HeaderItem) => {
        let child: HeaderItem[] = [];
        item.headerList?.forEach((childItem: HeaderItem) => {
          if (childItem.display) child.push(childItem);
          childHeaderList.push(childItem);
        });
        dynamicsHeader.push({
          name: item.name || "",
          value: item.value || "",
          prop: item.prop || "",
          headerList: child,
        });
      });

      // 更新分析数据状态
      state.analysisData = {
        chartTypeList: [
          { label: "柱状图", value: "vertical_bar" },
          { label: "条形图", value: "horizontal_bar" },
        ],
        chartType: "vertical_bar",
        datax: [],
        datay: [],
        dataStackY: [],
        color: "#5470C6",
        unit: "",
        tooltipData: [],
        chartData: chartData,
        chartDatas: [],
        avgScoreChartData: [],
        tableData: tableData,
        tableDatas: tableDatas,
        headerData: {
          static: res.data.headerList || [],
          dynamisc: res.data.fiveRateHeaderList || [],
          child: childHeaderList,
        },
        staticHeader: (res.data.headerList || []).filter(
          (header: HeaderItem) => header.display === true,
        ),
        dynamicsHeader: dynamicsHeader,
        childHeader: (res.data.childHeaderList || []).filter(
          (child: HeaderItem) => child.display === true,
        ),
        pageSize: 10,
        total: tableDatas.length,
        pageNum: 1,
        expandableText: "",
        average: 0,
        markLineData: [],
      };
      state.analysisLoading = false;
      ChangeChartBarData(); // 设置班级分析图数据
    }
  });
};

/** 切换分析图数据 */
const ChangeChartBarData = () => {
  let datax: string[] = [];
  let datay: (string | number)[] = [];
  let dataLoseRate: (string | number)[] = [];
  let average: number | string = 0;
  let markLineData: Array<{
    legendName: string;
    value: any;
    isShow?: boolean;
  }> = [];
  let color = "#5470C6";
  let maxClassName = "";
  let minClassName = "";
  let maxScore = 0;
  let minScore = 750;
  let expandableText = "";
  let tooltipData: TooltipItem[] = [];
  let unit = "";

  // 展平图表数据
  let chartData: ChartDataItem[] = [];
  state.analysisData.chartData.forEach((item) => {
    if (item.totalSubject) {
      chartData.push({
        ...item.totalSubject,
        isLine: item.isLine,
        isShow: item.isShow ? true : false,
      });
    }
    item.mergeSubjects?.forEach((i) => {
      chartData.push({
        ...i,
        isLine: item.isLine,
        isShow: item.isShow ? true : false,
      });
    });
    item.subjectList?.forEach((i) => {
      chartData.push({
        ...i,
        isLine: item.isLine,
        isShow: item.isShow ? true : false,
      });
    });
  });
  chartData = chartData.filter((item) => item.showCharts);

  // 构建 chartDatas 和 chartDatasList
  let chartDatas: ChartDataItem[] = [...chartData];
  const chartDatasList: ChartDataItem[] = [];
  state.analysisData.chartData.forEach((item) => {
    chartDatas.forEach((i) => {
      if (item.keyName == i.keyName && !item.isLine) {
        chartDatasList.push(item);
      }
    });
  });

  // 遍历数据，根据 tabActive 处理不同指标
  chartDatas.forEach((item) => {
    if (item.isLine) {
      // 辅助线数据（年级/联校等）
      switch (state.tabActive) {
        case "0":
          average = item.fiveRateResultVo?.avgScore ?? 0;
          markLineData.push({
            legendName: item.keyName,
            value: average,
            isShow: item.isShow,
          });
          break;
        case "1":
          average = 0;
          break;
        case "2":
          average = item.fiveRateResultVo?.rateScore ?? 0;
          markLineData.push({
            legendName: item.keyName,
            value: average,
            isShow: item.isShow,
          });
          break;
        case "3":
        case "4":
          average = 0;
          break;
        default:
          average = item.fiveRateResultVo?.[`${state.tabActive}Rate`] ?? 0;
          markLineData.push({
            legendName: item.keyName,
            value: average,
            isShow: item.isShow,
          });
          break;
      }
    } else {
      datax.push(item.keyName);
      let list: Array<{ name: string; value: any }> = [];

      switch (state.tabActive) {
        case "0": // 平均分
          datay.push(item.fiveRateResultVo?.avgScore ?? 0);
          if (item.classLevel == 2) {
            const score = parseFloat(item.fiveRateResultVo?.avgScore) || 0;
            if (!maxClassName && !minClassName) {
              maxScore = score;
              minScore = score;
              maxClassName = item.keyName;
              minClassName = item.keyName;
            } else {
              if (score > maxScore) {
                maxScore = score;
                maxClassName = item.keyName;
              } else if (score < minScore) {
                minScore = score;
                minClassName = item.keyName;
              }
            }
          }
          if (filterObject.value.examLevel == 1) {
            list.push({
              name: "均分联排",
              value: item.fiveRateResultVo?.avgExamRank || "-",
            });
          }
          list.push(
            { name: "均分校排", value: item.fiveRateResultVo?.avgRank || "-" },
            { name: "最高分", value: item.fiveRateResultVo?.maxScore },
            { name: "最低分", value: item.fiveRateResultVo?.minScore },
            { name: "标准差", value: item.fiveRateResultVo?.stdScore },
            { name: "实考人数", value: item.fiveRateResultVo?.effectiveNum },
            { name: "教师", value: item.teacherName || "-" },
          );
          tooltipData.push({ list, name: item.keyName });
          break;

        case "1": // 标准分
          if (item.classLevel == 2) {
            const score =
              parseFloat(item.fiveRateResultVo?.standardAvgScore) || 0;
            if (!maxClassName && !minClassName) {
              maxScore = score;
              minScore = score;
              maxClassName = item.keyName;
              minClassName = item.keyName;
            } else {
              if (score > maxScore) {
                maxScore = score;
                maxClassName = item.keyName;
              } else if (score < minScore) {
                minScore = score;
                minClassName = item.keyName;
              }
            }
          }
          const zscore = parseFloat(
            item.fiveRateResultVo?.standardAvgScore,
          ).toFixed(2);
          datay.push(isNaN(Number(zscore)) ? 0 : zscore);
          list.push(
            { name: "标准分", value: item.fiveRateResultVo?.standardAvgScore },
            { name: "平均分", value: item.fiveRateResultVo?.avgScore },
            { name: "实考人数", value: item.fiveRateResultVo?.effectiveNum },
            { name: "教师", value: item.teacherName || "-" },
          );
          tooltipData.push({ list, name: item.keyName });
          break;

        case "2": // 得分率
          if (item.classLevel == 2) {
            const score = parseFloat(item.fiveRateResultVo?.rateScore) || 0;
            if (!maxClassName && !minClassName) {
              maxScore = score;
              minScore = score;
              maxClassName = item.keyName;
              minClassName = item.keyName;
            } else {
              if (score > maxScore) {
                maxScore = score;
                maxClassName = item.keyName;
              } else if (score < minScore) {
                minScore = score;
                minClassName = item.keyName;
              }
            }
          }
          datay.push(item.fiveRateResultVo?.rateScore ?? 0);
          dataLoseRate.push(item.fiveRateResultVo?.lostRate ?? 0);
          list.push(
            {
              name: "失分率",
              value: (item.fiveRateResultVo?.lostRate ?? 0) + "%",
            },
            { name: "实考人数", value: item.fiveRateResultVo?.effectiveNum },
            { name: "教师", value: item.teacherName || "-" },
          );
          tooltipData.push({ list, name: item.keyName });
          break;

        case "3": // 超均分
        case "4": // 超均率
          {
            const exceedAvgScore =
              state.rankType == 2
                ? item.fiveRateResultVo?.exceedAvgScore
                : item.fiveRateResultVo?.examExceedAvgScore;
            const exceedAvgScoreRate =
              state.rankType == 2
                ? item.fiveRateResultVo?.exceedAvgScoreRate
                : item.fiveRateResultVo?.examExceedAvgScoreRate;

            const shouldProcess =
              schoolLevel.value == 2 || item.keyName != "年级";
            if (shouldProcess) {
              const targetValue =
                state.tabActive == "3" ? exceedAvgScore : exceedAvgScoreRate;
              const score = parseFloat(targetValue) || 0;
              if (item.classLevel == 2 || schoolLevel.value == 2) {
                if (!maxClassName && !minClassName) {
                  maxScore = score;
                  minScore = score;
                  maxClassName = item.keyName;
                  minClassName = item.keyName;
                } else {
                  if (score > maxScore) {
                    maxScore = score;
                    maxClassName = item.keyName;
                  } else if (score < minScore) {
                    minScore = score;
                    minClassName = item.keyName;
                  }
                }
              }
              const formatted = parseFloat(targetValue).toFixed(2);
              datay.push(isNaN(Number(formatted)) ? 0 : formatted);
              list.push(
                { name: "超均分", value: exceedAvgScore },
                { name: "超均率", value: (exceedAvgScoreRate ?? 0) + "%" },
                { name: "平均分", value: item.fiveRateResultVo?.avgScore },
                {
                  name: "实考人数",
                  value: item.fiveRateResultVo?.effectiveNum,
                },
                { name: "教师", value: item.teacherName || "-" },
              );
              tooltipData.push({ list, name: item.keyName });
            }
          }
          break;

        default:
          {
            // 五率（优秀率/良好率/及格率/低分率等）
            const rate = item.fiveRateResultVo?.[`${state.tabActive}Rate`];
            datay.push(rate ?? 0);
            list.push({
              name: state.groupTitle + "人数",
              value: item.fiveRateResultVo?.[`${state.tabActive}RateNum`],
            });
            if (item.classLevel == 2) {
              const score = parseFloat(rate) || 0;
              if (!maxClassName && !minClassName) {
                maxScore = score;
                minScore = score;
                maxClassName = item.keyName;
                minClassName = item.keyName;
              } else {
                if (score > maxScore) {
                  maxScore = score;
                  maxClassName = item.keyName;
                } else if (score < minScore) {
                  minScore = score;
                  minClassName = item.keyName;
                }
              }
            }
            list.push(
              { name: "实考人数", value: item.fiveRateResultVo?.effectiveNum },
              { name: "教师", value: item.teacherName || "-" },
            );
            tooltipData.push({ list, name: item.keyName });
          }
          break;
      }
    }
  });

  // 颜色设置
  const colorMap: Record<string, string> = {
    high: "#5470C6",
    good: "#3BA272",
    fine: "#FAC858",
    pass: "#995FB3",
    low: "#EE6666",
  };
  color = colorMap[state.tabActive] || "#5470C6";

  // 说明文案设置
  switch (state.tabActive) {
    case "0":
      unit = "";
      expandableText = `说明：平均分指一次考试中一组数据的平均成绩。计算方式为所有人员成绩总和/人员总数。通过平均分可直接体现本次考试各个班级的成绩水平。由图中可以看出，平均分最高的班级为<span class="max_color">${maxClassName}</span>，最低的班级为<span class="min_color">${minClassName}</span>。`;
      break;
    case "1":
      unit = "";
      expandableText =
        "说明：标准分，也称为标准分数或Z分数，是一种由原始分数推导出来的相对地位量数，用于说明原始分数在所属分数群体中的相对位置。其计算公式为：Z = (x - μ)/σ（Z是标准分，X是原始数据的值，μ是该组数据的平均数，σ是该组数据的标准差）。标准分的分数区间通常在-3到+3之间，标准分大于0，表示成绩在平均数之上；标准分数小于0，表示成绩在平均分数之下。与原始分相比，标准分最直接的意义是它给出离平均数的距离。柱图的颜色可直接区分出各班级标准分的差异，标准分越高说明该班的表现越优异。";
      break;
    case "2":
      unit = "%";
      expandableText =
        "说明：得分率是指实际得分除以考核分的比值,换算成的百分数。公式：得分率=得分/满分*100%。得分率是评估考试表现的重要指标。较高的得分率通常代表更好的完成度或掌握程度，而较低的得分率则可能提示需要改进或加强。红色柱代表班级得分率低于年级得分率，反之，绿色柱代表班级得分率高于年级得分率。";
      break;
    case "3":
      unit = "";
      expandableText = `说明：班级超均分指在本次考试中，班级平均分超出年级平均分的分值，正值代表超过了年级均分，负值为低于年级均分，柱图的颜色可直接区分出超过或者低于年级均分的班级。该数据反映了一个班级的均分与年级整体水平之间的差异，超均分越高说明该班的表现越优异。由图中可以看出，超均分最高的班级为<span class="max_color">${maxClassName}</span>，最低的班级为<span class="min_color">${minClassName}</span>。`;
      break;
    case "4":
      unit = "%";
      expandableText = `说明：班级超均率表示班级超过或低于年级平均水平的程度。超均率为正，说明班级水平高于年级平均水平；超均率为负，说明班级水平低于年级平均水平，柱图的颜色可直接区分出超过或者低于年级均分的班级。计算方式为（班级平均分-年级平均分）/年级的平均分*100%。该数据反映了一个班级的均分与年级整体水平之间的差异，超均率越高说明该班的表现越优异。由图中可以看出，超均率最高的班级为<span class="max_color">${maxClassName}</span>，最低的班级为<span class="min_color">${minClassName}</span>。`;
      break;
    default:
      unit = "%";
      const percent: Record<string, string> = {
        high: "",
        good: "",
        fine: "",
        pass: "",
        low: "",
      };
      state.analysisData.dynamicsHeader.forEach((item) => {
        percent[item.prop] = `${item.value}%`;
      });
      expandableText = `说明：班级${state.groupTitle}指班级${state.tabActive == "top" ? "在考试中取得高分" : state.tabActive == "low" ? "成绩低于某个特定" : "在考试中达到" + state.groupTitle.replace("率", "")}标准（通常为科目满分的${percent[state.tabActive]}分数${state.tabActive == "low" ? "以下" : "以上"}）人数占比。计算方式为${state.groupTitle.replace("率", "")}人数/总人数*100%。通过分析${state.groupTitle}，可以了解班级${state.tabActive == "top" ? "高分" : state.groupTitle.replace("率", "")}人数分布情况。由图中可以看出，${state.groupTitle}最高的班级为${state.tabActive == "low" ? `<span class="min_color">` : `<span class="max_color">`}${maxClassName}</span>，最低的班级为${state.tabActive == "low" ? `<span class="max_color">` : `<span class="min_color">`}${minClassName}</span>。`;
      break;
  }

  // 更新状态
  state.analysisData.chartType = "vertical_bar";
  state.analysisData.color = color;
  state.analysisData.average = parseFloat(String(average)) || 0;
  state.analysisData.markLineData = markLineData;
  state.analysisData.datax = datax;
  state.analysisData.datay = datay;
  state.analysisData.dataStackY = [datay, dataLoseRate];
  state.analysisData.tooltipData = tooltipData;
  state.analysisData.avgScoreChartData = datax.map((item, index) => ({
    x: item,
    y: parseFloat(String(datay[index])) || 0,
    tip: tooltipData[index],
  }));
  state.analysisData.unit = unit;
  state.analysisData.expandableText = expandableText;
  state.analysisData.chartDatas = chartDatasList;
};

/** 排序（默认/升序/降序） */
const ChangeChartOrder = (val: string) => {
  state.sortValue = val;
  const cloneChartData = cloneDeep(state.analysisData.avgScoreChartData);
  if (state.sortValue == "2") {
    cloneChartData.sort((a, b) => a.y - b.y); // 升序
  } else if (state.sortValue == "3") {
    cloneChartData.sort((a, b) => b.y - a.y); // 降序
  }
  state.analysisData.datax = cloneChartData.map((item) => item.x);
  state.analysisData.datay = cloneChartData.map((item) => String(item.y));
  state.analysisData.tooltipData = cloneChartData.map((item) => item.tip);
};

/** 获取分析图五率数据 */
const GetAnalysisFiveRateData = () => {
  let data: (string | number)[][] = [];
  let tooltipData: any[] = [];
  let colorList: string[] = [];
  let oneRowData: (string | number)[] = ["group"];

  state.fiveRateList.forEach((item) => {
    oneRowData.push(item.title);
    colorList.push(getSchoolFiveRateColor(item.value));
  });
  data.push(oneRowData);

  // 展平图表数据
  let chartData: ChartDataItem[] = [];
  state.analysisData.chartData.forEach((item) => {
    if (item.totalSubject) chartData.push(item.totalSubject);
    item.mergeSubjects?.forEach((i) => chartData.push(i));
    item.subjectList?.forEach((i) => chartData.push(i));
  });
  const chartDatas = chartData.filter((item) => item.showCharts);

  // 构建五率数据
  chartDatas.forEach((item) => {
    let rowData: (string | number)[] = [];
    let rowTooltip: any[] = [];
    rowData.push(item.keyName);

    state.fiveRateList.forEach((rateItem) => {
      rowData.push(item.fiveRateResultVo?.[`${rateItem.value}Rate`] ?? 0);
      rowTooltip.push({
        list: [
          {
            label: "实考人数",
            value: item?.fiveRateResultVo?.effectiveNum ?? "-",
          },
          { label: "教师", value: item?.teacherName ?? "-" },
        ],
        rateNum: item?.fiveRateResultVo?.[`${rateItem.value}RateNum`] ?? "-",
      });
    });

    // 年级数据插入到第二位
    if (item.schoolLevel == 0) {
      data.splice(1, 0, rowData);
      tooltipData.splice(1, 0, rowTooltip);
    } else {
      data.push(rowData);
      tooltipData.push(rowTooltip);
    }
  });

  state.fiveRateData.tooltipData = tooltipData;
  state.fiveRateData.chartData = chartDatas;
  state.fiveRateData.chartType = "stacked_chart";
  state.fiveRateData.data = data;
  state.fiveRateData.color = colorList;

  const fiveRateNames = state.fiveRateList.map((item) => item.title).join("、");
  state.analysisData.expandableText = `说明：班级<span class="normal_color">${state.rateName}</span>指班级的<span class="normal_color">${fiveRateNames}。${state.rateName}</span>综合展示，可以全面了解班级的成绩水平情况。点击班级的柱可在下方查看该班除总分外其他科目的<span class="normal_color">${state.rateName}</span>占比情况。`;
};
//展开学生弹窗
const OpenStudentDialog = (row: any, header: HeaderItem, child: HeaderItem) => {
  state.dialogData.title = `${header.name}`;
  state.dialogData.tableTitle = row.keyName;
  state.dialogData.fiveRateName = (child.label || "").replace(/人数/g, ""); //当前选择的五率的名称
  state.dialogData.selectSubjectName = row.subjectName; //当前选择的科目名称
  state.dialogData.selectSchoolLevel = row.schoolLevel; //当前选择的学校级别：0-联考 1-学校分组 2-具体学校

  state.dialogData.selectClassLevel = row.classLevel; //当前选择的班级级别：0-年级 1-组合班级 2-具体班级
  if (row.schoolLevel == 2) {
    //单校 班级
    const keyName = row.keyName ?? "";
    if (filterObject.value.schoolLevel == 2) {
      state.dialogData.selectClassName = keyName;
    } else {
      state.dialogData.selectClassName = keyName.split("-")?.[1] ?? ""; //当前选择的班级名称：年级 组合班级 单班
    }
    state.dialogData.selectSchoolName = row?.schoolName ?? "";
  } else if (row.schoolLevel == 1) {
    //组合学校
    state.dialogData.selectClassName = "";
    state.dialogData.selectSchoolName = row.keyName; //当前选择的学校名称：联校 组合学校 单校名称
  } else {
    state.dialogData.selectClassName = "";
    state.dialogData.selectSchoolName = "";
  }
  state.dialogData.showDialog = true;
};

// 关闭学生列表弹窗
const CloseDialog = (val: boolean) => {
  state.dialogData.showDialog = val;
};
//确定显示的表头数据
const SetEnterHeaderData = (data: any) => {
  const staticProps = data.static.filter((item) => item.display).map((item) => item.prop);
  const childProps = data.child.filter((item) => item.display).map((item) => item.prop);
  state.analysisData.staticHeader = state.analysisData.headerData.static.filter(
    (header) => staticProps.includes(header.prop),
  );
  state.analysisData.dynamicsHeader = [];
  state.analysisData.headerData.dynamisc.forEach((item) => {
    let child = [];

    item.headerList.forEach((childItem) => {
      if (childProps.includes(childItem.prop)) {
        child.push(childItem);
      }
    });
    let dynamicsItem = {
      name: item.name,
      value: item.value,
      prop: item.prop || "",
      headerList: child,
    };

    state.analysisData.dynamicsHeader.push(dynamicsItem);
  });
  console.log(data.static,3333)
  // 将 checkData.static 转换为对象映射
  const checkDataStaticMap = {}; //静态对象映射
  const checkDataChildMap = {}; //子表头对象映射
  data.static.forEach((item) => {
    checkDataStaticMap[item.prop] = true;
  });
  data.child.forEach((item: string) => {
    checkDataChildMap[item.prop] = true;
  });
  // 遍历 state.checkData.static 并设置 display 属性
  state.analysisData.headerData.static.forEach((item) => {
    item.display = checkDataStaticMap[item.prop] || false;
  }); //静态
  state.analysisData.headerData.child.forEach((item) => {
    item.display = checkDataChildMap[item.prop] || false;
  }); //子表头
};
/** 导出 Excel */
const ExportExcel = () => {
  reportModuleRef.value?.SetExportLoading?.(true);
  const examName = getExamName.value;
  let params: Record<string, any> = {
    fileName: GetExcelFileName(
      examName,
      filterObject.value,
      `${state.groupTitle}分析表`,
    ),
    examName: examName,
    sheetName: `${state.groupTitle}分析表`,
    chooseType: 1,
    lastExamName: "",
  };

  const staticHeaderData = state.analysisData.headerData.static.filter(
    (item) => item.display,
  );
  params.staticHeaderData = staticHeaderData;

  const childHeaderData = state.analysisData.headerData.child.filter(
    (item) => item.display,
  );
  params.fiveRateHeaderList = state.analysisData.dynamicsHeader;

  let dataList: string[][] = [];
  state.analysisData.tableDatas.forEach((item: any) => {
    const rowData: string[] = [];
    staticHeaderData.forEach((header) => {
      let propVal = "";
      const isRate = header.label.includes("率");
      if (item.hasOwnProperty(header.prop)) {
        const value =
          header.prop == "index" ? item[header.prop] : item[header.prop] || "-";
        propVal = `${value}${isRate && value != "-" ? "%" : ""}`;
      } else if (
        item.fiveRateResultVo &&
        item.fiveRateResultVo.hasOwnProperty(header.prop)
      ) {
        const value = item.fiveRateResultVo[header.prop] || "-";
        propVal = `${value}${isRate && value != "-" ? "%" : ""}`;
      }
      rowData.push(propVal);
    });
    childHeaderData.forEach((child) => {
      let propVal = "-";
      if (
        item.fiveRateResultVo &&
        item.fiveRateResultVo.hasOwnProperty(child.prop)
      ) {
        const reg = /Rate$/;
        const isRate = reg.test(child.prop);
        const value = item.fiveRateResultVo[child.prop] ?? "-";
        propVal = `${value}${isRate && value != "-" ? "%" : ""}`;
      }
      rowData.push(propVal);
    });
    dataList.push(rowData);
  });
  params.dataList = dataList;

  downloadExcel(publicExportFive, params).finally(() => {
    reportModuleRef.value?.SetExportLoading?.(false);
  });
};

// ================= 分页 =================

const ChangeCurrentPage = (val: number) => {
  state.analysisData.pageNum = val;
};

const ChangePageSize = (val: number) => {
  state.analysisData.pageSize = val;
  state.analysisData.pageNum = 1;
};

// ================= 初始化 =================

const pageInit = () => {
  GetSingleClassAnalysisData();
};

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

onMounted(() => {
  const fiveRateList = analysisStore?.analysisExamInfo?.fiveRateList || [];
  state.rateName = analysisStore?.analysisExamInfo?.fiveRateName || "";
  fiveRateList.forEach((item: any) => {
    const obj: FiveRateItem = { title: item.name, value: item.code };
    state.fiveRateList.push(obj);
    state.tabList.push(obj);
  });
  if (fiveRateList.length > 0 && state.rateName !== "") {
    state.tabList.push({ title: `${state.rateName}综合`, value: "rateAll" });
  }
  pageInit();
});
</script>

<style lang="scss" scoped></style>
