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

export interface ParentBindChildInfo {
    account?: string;
    avatar?: string;
    id?: number;
    name?: string;
    nickname?: string;
    phone?: string;
    [key: string]: any;
}

export interface ParentBindChildStudent {
    account?: string;
    avatar?: string;
    gradeId?: number;
    gradeName?: string;
    id?: number;
    name?: string;
    nickname?: string;
    [key: string]: any;
}

export interface ParentBindChildItem {
    id?: number;
    adminFlag?: number;
    leadFlag?: number;
    bindFlag?: number;
    bindTime?: string;
    identityType?: number;
    child?: ParentBindChildStudent;
    parent?: ParentBindChildInfo;
    [key: string]: any;
}

export interface PageResult<T> {
    current?: number;
    rows?: T[];
    size?: number;
    totalPage?: number;
    totalRows?: number;
    [key: string]: any;
}

/** 家长绑定孩子列表（当前家长已绑定） */
export const getParentBindChildList = (params: {
    parentId: string | number;
    current?: number;
    size?: number;
}) =>
    request<PageResult<ParentBindChildItem>>({
        url: '/parentBindChild/list',
        method: 'GET',
        params: {
            parentId: params.parentId,
            current: params.current ?? 1,
            size: params.size ?? 100,
            bindFlag: 1,
        },
    });

/** 按孩子 ID 查询绑定家长（扫码绑定前校验） */
export const getBindParentsByChildId = (childId: string | number) =>
    request<PageResult<ParentBindChildItem>>({
        url: '/parentBindChild/list',
        method: 'GET',
        params: {
            childId,
            size: -1,
        },
    });

/** 按设备序列号查询绑定家长 */
export const getBindParentsByDevice = (simSerialNumber: string) =>
    request<PageResult<any>>({
        url: '/parentBindDevice/list',
        method: 'GET',
        params: {
            simSerialNumber,
            size: -1,
        },
    });

/** 手动输入孩子账号绑定 */
export const manualBindChild = (childAcc: string) =>
    request<number>({
        url: '/parentBind/familyTeacherBindAcc',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        data: `childAcc=${encodeURIComponent(childAcc.trim())}`,
    });

/** 解绑家长与孩子 */
export const unbindParentChild = (data: { parentId: string | number; childId: string | number }) =>
    request({
        url: '/parentBindChild/unBound',
        method: 'POST',
        data,
    });

export interface WrongKpointRatioItem {
    errorCount?: number;
    kpointId?: number;
    kpointName?: string;
    ratio?: number;
    ratioPercent?: number;
}

export interface WrongKpointRatioResult {
    items?: WrongKpointRatioItem[];
    subjectId?: number;
    subjectName?: string;
    totalErrorCount?: number;
}

export interface KpointScoreItem {
    kpointId?: number;
    kpointName?: string;
    actualScore?: number;
    fullScore?: number;
    scoreRate?: number;
    scoreRatePercent?: number;
    levelCode?: number;
    levelName?: string;
}

export interface KpointScoreLevel {
    levelCode?: number;
    levelName?: string;
    items?: KpointScoreItem[];
}

export interface KpointScoreResult {
    subjectId?: number;
    subjectName?: string;
    levels?: KpointScoreLevel[];
}

export interface ScoreAbilityPoint {
    hasData?: boolean;
    scoreAbility?: number;
    scoreRate?: number;
    statDate?: string;
}

export interface ScoreAbilityResult {
    assessmentCode?: number;
    assessmentName?: string;
    endDate?: string;
    overallScoreAbility?: number;
    points?: ScoreAbilityPoint[];
    stabilityCode?: number;
    stabilityName?: string;
    startDate?: string;
    subjectId?: number;
    subjectName?: string;
}

export interface WrongQuestionSubjectSummary {
    subjectId?: number;
    subjectName?: string;
    totalCount?: number;
    masteredCount?: number;
    reviewCount?: number;
    newCount?: number;
}

export interface WrongQuestionSummaryResult {
    thisWeekStart?: string;
    thisWeekEnd?: string;
    subjects?: WrongQuestionSubjectSummary[];
}

export type WeeklySubjectTrendCode = 'PROGRESS' | 'REGRESSION' | 'STABLE' | 'NO_COMPARE';

export interface WeeklySubjectItem {
    subjectId?: number;
    subjectName?: string;
    levelCode?: number;
    levelName?: string;
    thisWeekRecordCount?: number;
    thisWeekScoreRate?: number;
    lastWeekRecordCount?: number;
    lastWeekScoreRate?: number | null;
    delta?: number | null;
    trendCode?: WeeklySubjectTrendCode | string;
    trendName?: string;
}

export interface WeeklySubjectLevel {
    levelCode?: number;
    levelName?: string;
    subjects?: WeeklySubjectItem[];
}

export interface WeeklySubjectResult {
    lastWeekEnd?: string;
    lastWeekStart?: string;
    thisWeekEnd?: string;
    thisWeekStart?: string;
    levels?: WeeklySubjectLevel[];
    subjects?: WeeklySubjectItem[];
}

/** 家长端首页 - 本周学科分层与趋势 */
export const getWeeklySubject = (params: { userId: string | number }) =>
    request<WeeklySubjectResult>({
        url: '/school/parent/weeklySubject',
        method: 'GET',
        params,
    });

/** 家长端 - 错题汇总（按学科） */
export const getWrongQuestionSummary = (params: { userId: string | number }) =>
    request<WrongQuestionSummaryResult>({
        url: '/school/parent/wrongQuestionSummary',
        method: 'GET',
        params,
    });

export interface QuestionTitle {
    actualScore?: number;
    aiAnalyze?: string;
    aiAnswer?: string;
    answer?: string;
    answerHtml?: string;
    answerSqs?: string;
    correctResult?: number;
    courseId?: number;
    difficulty?: number;
    difficultyCode?: number;
    difficultyLevel?: string;
    explanation?: string;
    id?: string;
    itemId?: number;
    optionHtml?: string;
    optionSqs?: string;
    score?: number;
    stem?: string;
    stemHtml?: string;
    submitAnswer?: string;
    submitAnswerPic?: string;
    typeId?: string;
    typeName?: string;
    [key: string]: any;
}

export interface WrongQuestionItem {
    id: number;
    questionId: string;
    userId?: number;
    subjectId?: number;
    textbookId?: number;
    chapterId?: number;
    courseId?: number;
    errorCount: number;
    errorType?: number;
    masteryLevel?: number;
    status?: number;
    firstErrorTime: string;
    lastErrorTime: string;
    lastCorrectTime?: string;
    questionTitle?: QuestionTitle;
    [key: string]: any;
}

export interface WrongQuestionFilterPageParams {
    userId?: string | number;
    subjectId?: string | number;
    current?: number;
    size?: number;
    startTime?: string;
    endTime?: string;
}

export interface FilterSubject {
    id: number;
    name: string;
}

/** 学科网 - 错题筛选分页列表 */
export const getWrongQuestionFilterPage = (params: WrongQuestionFilterPageParams) => {
    const query: Record<string, string | number> = {
        current: params.current ?? 1,
        size: params.size ?? 10,
    };
    if (params.userId) query.userId = params.userId;
    if (params.subjectId) query.subjectId = Number(params.subjectId);
    if (params.startTime) query.startTime = params.startTime;
    if (params.endTime) query.endTime = params.endTime;
    return request<PageResult<WrongQuestionItem>>({
        url: '/xkw/wrong/question/filter/page',
        method: 'GET',
        params: query,
    });
};

/** 学科网 - 错题筛选学科列表 */
export const getWrongQuestionFilterSubjects = (params?: { userId?: string | number }) =>
    request<FilterSubject[]>({
        url: '/xkw/wrong/question/filter/subjects',
        method: 'GET',
        params: params?.userId ? { userId: params.userId } : undefined,
    });

/** 家长端 - 错题知识点占比 */
export const getWrongKpointRatio = (params: { subjectId: string | number; userId: string | number }) =>
    request<WrongKpointRatioResult>({
        url: '/school/parent/wrongKpointRatio',
        method: 'GET',
        params,
    });

/** 家长端 - 知识点得分（按等级分组） */
export const getKpointScore = (params: { subjectId: string | number; userId: string | number }) =>
    request<KpointScoreResult>({
        url: '/school/parent/kpointScore',
        method: 'GET',
        params,
    });

/** 家长端 - 得分能力趋势 */
export const getScoreAbility = (params: { subjectId: string | number; userId: string | number }) =>
    request<ScoreAbilityResult>({
        url: '/school/parent/scoreAbility',
        method: 'GET',
        params,
    });

/** 扫码后申请绑定孩子/设备 */
export const parentBindApply = (params: {
    childId?: string | number;
    simSerialNumber?: string;
    identityType: number;
}) => {
    const childDto = params.childId
        ? { childId: params.childId, identityType: params.identityType }
        : undefined;
    const deviceDto = params.simSerialNumber
        ? { simSerialNumber: params.simSerialNumber, identityType: params.identityType }
        : undefined;
    return request({
        url: '/parentBind/apply',
        method: 'POST',
        data: { childDto, deviceDto },
    });
};

export interface ParentBindApplyItem {
    id?: string | number;
    createTime?: string;
    initiatingUserPhone?: string;
    initiatingUserAvatar?: string;
    childUserName?: string;
    childUserAvatar?: string;
    simSerialNumber?: string;
    identityType?: number;
    [key: string]: any;
}

/** 当前家长待处理绑定申请 */
export const getParentBindApplies = () =>
    request<ParentBindApplyItem[]>({
        url: '/parentBind/applyInfoList',
        method: 'GET',
    });

/** 管理员审批绑定申请 */
export const approveParentBindApply = (data: {
    id: string | number;
    approvalFlag: boolean;
    leadFlag?: number;
}) =>
    request({
        url: '/parentBind/admin/approval',
        method: 'POST',
        data,
    });
