import type { MediaAuditRecord } from '@/api/upload';

export type MediaAuditStatus = 'pass' | 'fail' | 'pending' | 'unknown';

/** 微信内容安全 label 枚举 */
export const MEDIA_AUDIT_LABEL_TEXT: Record<number, string> = {
    100: '正常',
    20001: '时政',
    20002: '色情',
    20006: '违法犯罪',
    21000: '其他',
};

export interface MediaAuditDisplayInfo {
    status: MediaAuditStatus;
    label: number;
    labelText: string;
    statusText: string;
}

export const getMediaAuditLabelText = (label?: number | string | null) => {
    const num = Number(label);
    if (!Number.isFinite(num) || num === 100) return '';
    return MEDIA_AUDIT_LABEL_TEXT[num] || '';
};

export const getMediaAuditStatusText = (
    status: MediaAuditStatus,
    label?: number | string | null,
) => {
    const labelText = getMediaAuditLabelText(label);
    if (status === 'pass' || status === 'unknown') return '';

    if (status === 'pending') {
        return labelText ? `${labelText}·待复核` : '待复核';
    }

    if (status === 'fail') {
        return labelText ? `涉${labelText}内容` : '未通过审核';
    }

    return '';
};

const normalizeImageUrl = (url?: string) =>
    String(url || '')
        .replace(/[`]/g, '')
        .replace(/http:\/\//gi, 'https://')
        .trim();

/** 取 URL 文件名作为弱匹配键，避免域名或协议差异导致匹配失败 */
const getImageUrlFileKey = (url?: string) => {
    const normalized = normalizeImageUrl(url);
    if (!normalized) return '';
    const withoutQuery = normalized.split('?')[0].split('#')[0];
    const segments = withoutQuery.split('/').filter(Boolean);
    return segments[segments.length - 1] || withoutQuery;
};

export const getMediaAuditImageUrl = (item: MediaAuditRecord) =>
    normalizeImageUrl(item.imageUrl || item.mediaUrl || item.url);

/** 题目侧可用于与审核记录 titleId / bizId 对齐的 ID */
export const getQuestionMatchKeys = (item: any) =>
    [
        item?.jobStuTittleId,
        item?.id,
        item?.titleId,
        item?.questionId,
        item?.titleInfoId,
        item?.itemId,
    ]
        .filter(Boolean)
        .map(String);

/** 提交图片审核时使用的题目 ID，优先与接口 titleId 字段一致 */
export const getQuestionTitleId = (item: any) => {
    const keys = getQuestionMatchKeys(item);
    return keys[0] || keys[1] || '';
};

/** 审核记录侧可用于分组的 ID */
export const getAuditRecordMatchKeys = (item: MediaAuditRecord) =>
    [item.titleId, item.bizId].filter(Boolean).map(String);

export const normalizeMediaAuditStatus = (item: MediaAuditRecord): MediaAuditStatus => {
    const suggest = String(item.suggest || '').toLowerCase();
    if (suggest === 'pass') return 'pass';
    if (suggest === 'risky') return 'fail';
    if (suggest === 'review') return 'pending';

    if (item.pass === true || item.auditPass === true) return 'pass';
    if (item.pass === false || item.auditPass === false) return 'fail';

    const rawStatus = item.status ?? item.auditStatus ?? item.checkStatus ?? item.result;
    const statusText = String(rawStatus ?? '').toLowerCase();

    if (rawStatus === true || statusText === '1' || statusText === 'pass') return 'pass';
    if (rawStatus === false || statusText === '2' || statusText === 'fail' || statusText === 'risky') {
        return 'fail';
    }
    if (
        rawStatus === 0
        || statusText === '0'
        || statusText === 'pending'
        || statusText === 'review'
    ) {
        return 'pending';
    }

    if (item.label != null && item.label !== 100) {
        if (suggest === 'pass') return 'pass';
        if (suggest === 'review') return 'pending';
        if (suggest === 'risky') return 'fail';
    }

    const text = String(item.auditResult || item.resultMsg || item.message || '').toLowerCase();
    if (/pass|success|合规|通过/.test(text)) return 'pass';
    if (/fail|reject|risky|违规|不合规|不通过/.test(text)) return 'fail';
    if (/pending|review|审核中|复核|处理中/.test(text)) return 'pending';

    return 'unknown';
};

const dedupeAuditRecords = (records: MediaAuditRecord[]) => {
    const seen = new Set<string>();
    return records.filter((item) => {
        const key = [
            String(item.id || ''),
            String(item.titleId || item.bizId || ''),
            getMediaAuditImageUrl(item),
            String(item.status ?? item.auditStatus ?? item.suggest ?? ''),
        ].join('|');
        if (seen.has(key)) return false;
        seen.add(key);
        return Boolean(getMediaAuditImageUrl(item) || item.titleId || item.bizId);
    });
};

export const groupMediaAuditByTitleId = (records: MediaAuditRecord[]) => {
    const grouped = new Map<string, MediaAuditRecord[]>();
    records.forEach((item) => {
        getAuditRecordMatchKeys(item).forEach((key) => {
            const list = grouped.get(key) || [];
            list.push(item);
            grouped.set(key, list);
        });
    });
    return grouped;
};

const groupMediaAuditByImageFile = (records: MediaAuditRecord[]) => {
    const grouped = new Map<string, MediaAuditRecord[]>();
    records.forEach((item) => {
        const fileKey = getImageUrlFileKey(getMediaAuditImageUrl(item));
        if (!fileKey) return;
        const list = grouped.get(fileKey) || [];
        list.push(item);
        grouped.set(fileKey, list);
    });
    return grouped;
};

const getQuestionImageUrls = (item: any) =>
    String(item?.submitAnswerPic || '')
        .split(',')
        .map((url) => normalizeImageUrl(url))
        .filter(Boolean);

/**
 * 将 recordId 下全部审核记录，按题目 ID 与图片 URL 分发到各题
 */
export const attachMediaAuditToPaperList = (
    paperList: any[],
    auditRecords: MediaAuditRecord[] | null | undefined,
) => {
    if (!Array.isArray(paperList) || !Array.isArray(auditRecords)) return;

    const groupedByTitle = groupMediaAuditByTitleId(auditRecords);
    const groupedByFile = groupMediaAuditByImageFile(auditRecords);

    paperList.forEach((item) => {
        const matched: MediaAuditRecord[] = [];

        getQuestionMatchKeys(item).forEach((key) => {
            matched.push(...(groupedByTitle.get(key) || []));
        });

        getQuestionImageUrls(item).forEach((url) => {
            const fileKey = getImageUrlFileKey(url);
            if (fileKey) {
                matched.push(...(groupedByFile.get(fileKey) || []));
            }
        });

        item.mediaAuditList = dedupeAuditRecords(matched);
    });
};

export const findMediaAuditForImage = (
    imageUrl: string,
    auditList: MediaAuditRecord[] | undefined,
) => {
    if (!auditList?.length) return undefined;

    const target = normalizeImageUrl(imageUrl);
    const exact = auditList.find((item) => getMediaAuditImageUrl(item) === target);
    if (exact) return exact;

    const fileKey = getImageUrlFileKey(target);
    if (!fileKey) return undefined;

    return auditList.find((item) => getImageUrlFileKey(getMediaAuditImageUrl(item)) === fileKey);
};

export const getMediaAuditStatusForImage = (
    imageUrl: string,
    auditList: MediaAuditRecord[] | undefined,
): MediaAuditStatus => {
    const matched = findMediaAuditForImage(imageUrl, auditList);
    return matched ? normalizeMediaAuditStatus(matched) : 'unknown';
};

export const getMediaAuditInfoForImage = (
    imageUrl: string,
    auditList: MediaAuditRecord[] | undefined,
): MediaAuditDisplayInfo => {
    const matched = findMediaAuditForImage(imageUrl, auditList);
    const status = matched ? normalizeMediaAuditStatus(matched) : 'unknown';
    const label = Number(matched?.label ?? 100);
    const labelText = getMediaAuditLabelText(label);

    return {
        status,
        label,
        labelText,
        statusText: getMediaAuditStatusText(status, label),
    };
};
