import { request } from '@/utils/request';

/** 试卷测试类型：1 单元测试 2 周测 3 月测 4 随堂练习 5 课前预习 */
export type PaperTestType = 1 | 2 | 3 | 4 | 5;

export const PAPER_TEST_TYPE_MAP: Record<PaperTestType, string> = {
    1: '单元测试',
    2: '周测',
    3: '月测',
    4: '随堂练习',
    5: '课前预习',
};

export const PAPER_TEST_TYPE_OPTIONS: Array<{ label: string; value?: PaperTestType }> = [
    { label: '全部类型' },
    { label: '单元测试', value: 1 },
    { label: '周测', value: 2 },
    { label: '月测', value: 3 },
    { label: '随堂练习', value: 4 },
    { label: '课前预习', value: 5 },
];

export const getPaperTestTypeLabel = (type?: number | null) => {
    if (!type) return '';
    return PAPER_TEST_TYPE_MAP[type as PaperTestType] || '';
};

export interface PaperRecord {
    id: string;
    paperId: string;
    paperName: string;
    subjectId: string;
    subjectName: string;
    publisherName: string;
    createTime: string;
    endTime: string;
    remark: string;
    costTime: number;
    totalScore?: number;
    score?: number;
    type?: PaperTestType;
    gradeName?: string;
    markTime?: string;
    submitTime?: string;
}

export interface ListCompleteRecordParams {
    current?: number;
    resourceType?: number;
    userId?: string | number;
    subjectId?: string;
    type?: PaperTestType;
    gradingStatus?: string;
}

export interface ListCompleteRecordPage {
    rows: PaperRecord[];
    current?: number;
    totalRows?: number;
}

/** 获取未完成作业列表 */
export const getUnfinishedHomework = () =>
    request<PaperRecord[]>({
        url: '/school/paper/userRecord/listExamRecord',
        method: 'GET',
    });

/** 开始答题 */
export const startExam = (recordId: string) =>
    request<any>({
        url: '/school/paper/exam',
        method: 'POST',
        data: { recordId },
    });

/** 保存单道题目答案 */
export const saveRecordAnswer = (data: {
    answer: string;
    answerPic: string;
    costTime: number;
    itemId: string;
    recordId: string;
}) =>
    request({
        url: '/school/paper/saveRecordAnswer',
        method: 'POST',
        data,
        silent: true,
    });

/** 提交作业 */
export const submitExam = (data: {
    answerDtoList: Array<{ itemId: string; answer: string; answerPic: string }>;
    costTime: number;
    recordId: string;
}) =>
    request({
        url: '/school/paper/submit',
        method: 'POST',
        data,
    });

/** 已完成作业/考试记录列表 */
export const getListCompleteRecord = (params?: ListCompleteRecordParams) =>
    request<PaperRecord[] | ListCompleteRecordPage>({
        url: '/school/paper/userRecord/listCompleteRecord',
        method: 'GET',
        params: {
            resourceType: 0,
            ...params,
        },
    });

/** 解析分页或数组两种返回结构 */
export const normalizeListCompleteRecord = (
    data: PaperRecord[] | ListCompleteRecordPage | null | undefined,
) => {
    if (!data) {
        return { rows: [] as PaperRecord[], totalRows: 0, current: 1 };
    }
    if (Array.isArray(data)) {
        return { rows: data, totalRows: data.length, current: 1 };
    }
    const rows = data.rows || [];
    return {
        rows,
        totalRows: data.totalRows ?? rows.length,
        current: data.current ?? 1,
    };
};

/** 作业详情（含题目） */
export const getPaperRecordDetail = (data: { recordId: string; reportFlag: number }) =>
    request<any>({
        url: '/school/paper/getPaperRecordDetail',
        method: 'POST',
        data,
    });

export interface JobReportVo {
    actualScore?: number;
    markScore?: number;
    beginTime?: string;
    costTime?: number;
    jobId?: number;
    jobName?: string;
    submitEndTime?: string;
    totalScore?: number;
    userId?: number;
}

export interface PaperChanelAnalyzeItem {
    chanelTypeName?: string;
    titleCount?: number;
}

export interface PaperDifficultyAnalyzeItem {
    actualScore?: number;
    difficultyName?: string;
    /** 百分比比例，乘以 10000，如 9850 表示 98.5% */
    proportion?: number;
    score?: number;
    titleCount?: number;
}

export interface StuRankVoItem {
    markScore?: number;
    paperScore?: number;
    rankNum?: number;
    scoreRate?: number;
    selfFlag?: number;
    stuName?: string;
}

export interface JobAnalyseVo {
    jobReportVo?: JobReportVo;
    paperChanelAnalyzeList?: PaperChanelAnalyzeItem[];
    paperDifficultyAnalyzeList?: PaperDifficultyAnalyzeItem[];
    stuRankVoList?: StuRankVoItem[];
}

/** 作业整体分析（家长端查看孩子报告时需传 userId） */
export const getJobAnalyse = (params: { recordId: string; userId?: string }) =>
    request<JobAnalyseVo>({
        url: '/sc/job/getJobAnalyse',
        method: 'GET',
        params,
    });

export interface KnowledgeAnalyzeItem {
    knowledgeId?: string;
    knowledgeName?: string;
    answerScore?: number;
    titleScore?: number;
}

/** 知识点分析（家长端查看孩子报告时需传 userId） */
export const getKnowledgeAnalyse = (params: { recordId: string; userId?: string }) =>
    request<KnowledgeAnalyzeItem[]>({
        url: '/sc/job/statisticalKnowledge',
        method: 'GET',
        params,
    });
