import { getCache } from '@/utils/cache';
import { request, HOST, TENANT_ID, handleUnauthorized, HttpError } from '@/utils/request';

/**
 * 上传图片到后端，返回 { url, ... }
 */
export const uploadFile = (filePath: string): Promise<{ url: string; [key: string]: any }> => {
    const token = getCache('token');

    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: `${HOST}/api/main/sysFileInfo/tenUploadAll`,
            filePath,
            name: 'file',
            header: {
                Authorization: token ? `Bearer ${token}` : '',
                'x-tenant-id': TENANT_ID,
            },
            success: (res) => {
                try {
                    const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
                    if (data.code === 200 || data.code === 0) {
                        resolve(data.data);
                    } else if (Number(data.code) === 401) {
                        const msg401 = data.message || data.msg || '登录已失效，请重新登录';
                        handleUnauthorized(msg401);
                        reject(new HttpError(msg401, 401, data));
                    } else {
                        reject(new Error(data.message || data.msg || '上传失败'));
                    }
                } catch (e) {
                    reject(new Error('上传返回格式异常'));
                }
            },
            fail: (err) => reject(err),
        });
    });
};

export interface MediaAuditRecord {
    id?: string;
    recordId?: string;
    titleId?: string;
    bizId?: string;
    imageUrl?: string;
    mediaUrl?: string;
    url?: string;
    /** pass | review | risky */
    suggest?: string;
    /** 100 正常；20001 时政；20002 色情；20006 违法犯罪；21000 其他 */
    label?: number;
    status?: number | string;
    auditStatus?: number | string;
    checkStatus?: number | string;
    pass?: boolean;
    auditPass?: boolean;
    auditResult?: string;
    resultMsg?: string;
    message?: string;
    [key: string]: any;
}

/**
 * 提交图片内容安全检测（异步，结果需通过查询接口获取）
 */
export const checkImage = (data: {
    openid: string;
    recordId: string;
    titleId: string;
    imageUrl: string;
}) =>
    request({
        url: '/applet/media/checkImage',
        method: 'POST',
        data,
        silent: true,
    });

/**
 * 按试卷记录查询全部图片审核结果
 */
export const listMediaByRecordId = (recordId: string) =>
    request<MediaAuditRecord[]>({
        url: '/applet/media/listByRecordId',
        method: 'GET',
        params: { recordId },
        silent: true,
    });

/**
 * 按试卷记录 + 题目查询图片审核结果
 */
export const getMediaByRecordAndTitle = (recordId: string, titleId: string) =>
    request<MediaAuditRecord | MediaAuditRecord[]>({
        url: '/applet/media/getByRecordAndTitle',
        method: 'GET',
        params: { recordId, titleId },
        silent: true,
    });
