import { ElMessage } from "element-plus";
import dayjs from "dayjs";
/**
 * 通用 Excel 下载方法
 * @param apiFunc API 请求函数
 * @param params 请求参数
 */
export const downloadExcel = async (
  apiFunc: (params: any) => Promise<any>,
  params: any,
) => {
  try {
    const res = await apiFunc(params);

    // 检查响应状态
    if (res.status === 200) {
      // 创建 Blob
      const blob = new Blob([res.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      // 解析文件名，默认为 "导出文件.xlsx"
      let fileName = "导出文件.xlsx";
      const contentDisposition = res.headers?.["content-disposition"];
      if (contentDisposition) {
        const match = contentDisposition.match(/filename="?([^"]+)"?/);
        if (match && match[1]) {
          try {
            fileName = decodeURIComponent(match[1]);
          } catch (e) {
            console.warn("文件名解码失败", e);
          }
        }
      }

      // 触发下载
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();

      // 清理
      setTimeout(() => {
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
      }, 100);
    } else {
      ElMessage.error("导出失败！");
    }
  } catch (error) {
    console.error("导出异常:", error);
    ElMessage.error("导出异常！");
  }
};
// 定义报告参数的类型接口
interface ReportParam {
  schoolLevel?: number | string;
  schoolGroupName?: string;
  schoolName?: string;
  subjectName?: string;
  classGroupName?: string;
}
/**
 * 导出文件名称生成
 * @param examName 考试名称
 * @param reportParam 报告参数对象
 */
export const GetExcelFileName = (
  examName: string,
  reportParam: ReportParam,
  title?: string,
) => {
  // 防御性检查：如果 reportParam 为空，返回默认名称
  if (!reportParam) {
    return `${examName || "考试"}_导出文件`;
  }

  //0-联考 1-学校分组 2-具体学校
  let schoolName = "";
  // 统一转换为数字进行比较，防止类型不一致导致判断失效
  const level = Number(reportParam.schoolLevel);

  if (level === 0) {
    schoolName = "联校";
  } else if (level === 1) {
    schoolName = reportParam.schoolGroupName || "";
  } else {
    // 默认为具体学校 (level 2 或其他情况)
    schoolName = reportParam.schoolName || "";
  }

  // 获取科目名称，防止 undefined
  const subjectName = reportParam.subjectName || "";

  // 构建学校部分后缀
  const schoolSuffix = schoolName ? `_${schoolName}` : "";

  // 构建班级部分后缀：仅当 level 为 2 且存在 classGroupName 时添加
  const classSuffix =
    level === 2 && reportParam.classGroupName
      ? `_${reportParam.classGroupName}`
      : "";

  // 组合最终文件名
  return `${examName}_${subjectName}${schoolSuffix}${classSuffix}_${title}_${GetExportDate()}`;
};
//导出时间
export const GetExportDate = () => {
  return dayjs().format("MM-DD");
};
//命题分析表头
export const propositionAnalysisStaticHeaderData = () => {
  return [
    { display: true, label: "题号", prop: "questionCode" },
    { display: true, label: "题型", prop: "questionTypeName" },
    { display: true, label: "实考人数", prop: "studentCount" },
    { display: true, label: "满分", prop: "fullMark" },
    { display: true, label: "难度", prop: "difficulty" },
    { display: true, label: "区分度", prop: "discrimination" },
    { display: true, label: "平均分", prop: "averageScore" },
    { display: true, label: "最高分", prop: "maxScore" },
    { display: true, label: "最低分", prop: "minScore" },
    { display: true, label: "得分率", prop: "scoreRate" },
    { display: true, label: "标准差", prop: "standardDeviation" },
  ];
};
//客观题分析表
export const selectQuestionAnalysisStaticHeaderData = () => {
  return [
    { display: true, label: "题号", prop: "questionName" },
    { display: true, label: "题型", prop: "questionType" },
    { display: true, label: "分数", prop: "answerScore" },
    { display: true, label: "平均分", prop: "averageScore" },
    { display: true, label: "得分率", prop: "scoreRate" },
    { display: true, label: "答案", prop: "answerValue" },
  ];
};
export const selectQuestionAnalysisDynamicsHeaderData = () => {
  return [
    { display: true, label: "各选项选择人数", prop: "" },
    { display: true, label: "各选项选择人数占比", prop: "" },
  ];
};
//错题分析表
export const errorQuestionDataStaticHeaderData = () => {
  return [
    { display: true, label: "小题名称", prop: "questionName" },
    { display: true, label: "题型", prop: "questionType" },
    { display: true, label: "满分", prop: "questionScore" },
    { display: true, label: "难度", prop: "difficulty" },
    { display: true, label: "区分度", prop: "discrimination" },
    { display: true, label: "平均分", prop: "averageScore" },
    { display: true, label: "得分率", prop: "scoreRate" },
    { display: true, label: "答题人数", prop: "studentCount" },
    { display: true, label: "错题人数", prop: "errorCount" },
    { display: true, label: "正确答案", prop: "answerValue" },
  ];
};
// 错题分析表头
export const errorQuestionDataChildHeaderData = (headerData: any[]) => {
  return headerData.map((item) => ({
    display: true,
    label: "错题详情",
    prop: item,
  }));
};
//人数弹框
export const studentListStaticHeaderData = (
  examLevel: number,
  isAssign: number,
  isSubjectGroup: boolean,
) => {
  if (isAssign == 0) {
    if (isSubjectGroup) {
      //单科
      if (examLevel == 1) {
        //联校
        return [
          { display: true, label: "序号", prop: "index" },
          { display: true, label: "学校", prop: "schoolName" },
          { display: true, label: "学号", prop: "studentUserCode" },
          { display: true, label: "姓名", prop: "studentUserName" },
          { display: true, label: "行政班", prop: "className" },
          { display: true, label: "教学班", prop: "teachClassName" },
          { display: true, label: "得分", prop: "score" },
        ];
      } else {
        return [
          { display: true, label: "序号", prop: "index" },
          { display: true, label: "学号", prop: "studentUserCode" },
          { display: true, label: "姓名", prop: "studentUserName" },
          { display: true, label: "行政班", prop: "className" },
          { display: true, label: "教学班", prop: "teachClassName" },
          { display: true, label: "得分", prop: "score" },
        ];
      }
    } else {
      if (examLevel == 1) {
        //联校
        return [
          { display: true, label: "序号", prop: "index" },
          { display: true, label: "学校", prop: "schoolName" },
          { display: true, label: "学号", prop: "studentUserCode" },
          { display: true, label: "姓名", prop: "studentUserName" },
          { display: true, label: "行政班", prop: "className" },
          { display: true, label: "得分", prop: "score" },
        ];
      } else {
        return [
          { display: true, label: "序号", prop: "index" },
          { display: true, label: "学号", prop: "studentUserCode" },
          { display: true, label: "姓名", prop: "studentUserName" },
          { display: true, label: "行政班", prop: "className" },
          { display: true, label: "得分", prop: "score" },
        ];
      }
    }
  } else {
    if (isSubjectGroup) {
      if (examLevel == 1) {
        //联校
        return [
          { display: true, label: "序号", prop: "index" },
          { display: true, label: "学校", prop: "schoolName" },
          { display: true, label: "学号", prop: "studentUserCode" },
          { display: true, label: "姓名", prop: "studentUserName" },
          { display: true, label: "行政班", prop: "className" },
          { display: true, label: "教学班", prop: "teachClassName" },
          { display: true, label: "原始分", prop: "score" },
          { display: true, label: "赋分", prop: "rateScore" },
        ];
      } else {
        return [
          { display: true, label: "序号", prop: "index" },
          { display: true, label: "学号", prop: "studentUserCode" },
          { display: true, label: "姓名", prop: "studentUserName" },
          { display: true, label: "行政班", prop: "className" },
          { display: true, label: "教学班", prop: "teachClassName" },
          { display: true, label: "原始分", prop: "score" },
          { display: true, label: "赋分", prop: "rateScore" },
        ];
      }
    } else {
      if (examLevel == 1) {
        //联校
        return [
          { display: true, label: "序号", prop: "index" },
          { display: true, label: "学校", prop: "schoolName" },
          { display: true, label: "学号", prop: "studentUserCode" },
          { display: true, label: "姓名", prop: "studentUserName" },
          { display: true, label: "行政班", prop: "className" },
          { display: true, label: "原始分", prop: "score" },
          { display: true, label: "赋分", prop: "rateScore" },
        ];
      } else {
        return [
          { display: true, label: "序号", prop: "index" },
          { display: true, label: "学号", prop: "studentUserCode" },
          { display: true, label: "姓名", prop: "studentUserName" },
          { display: true, label: "行政班", prop: "className" },
          { display: true, label: "原始分", prop: "score" },
          { display: true, label: "赋分", prop: "rateScore" },
        ];
      }
    }
  }
};
