import type { AiExecutionRequest } from '@classhelper/shared'; import axios, { type AxiosError, type AxiosRequestConfig } from 'axios'; import { ElMessage } from 'element-plus'; import { STORAGE_KEYS, type ApiErrorResponse, type ApiResponse } from '@classhelper/shared'; import { API_BASE_URL } from '@/config'; import { clearCalendarCache } from '@/composables/calendarCache'; import { allowsAiExecution } from '@/composables/assistantRequests'; /** * Axios 封装: * 1) 自动携带 JWT * 2) 统一拆包(响应拦截器直接把 data 返回给调用方) * 3) 统一错误提示;401 自动清理会话并回到登录页 */ const instance = axios.create({ baseURL: API_BASE_URL, timeout: 20000, }); instance.interceptors.request.use((config) => { const token = localStorage.getItem(STORAGE_KEYS.token); if (token) config.headers.Authorization = `Bearer ${token}`; return config; }); instance.interceptors.response.use( (response) => { const body = response.data as ApiResponse | undefined; if (body && typeof body === 'object' && 'success' in body) { if (!body.success) { ElMessage.error(body.message || '请求失败'); return Promise.reject(new Error(body.message || '请求失败')); } return body.data as never; } return response.data as never; }, (error: AxiosError) => { const status = error.response?.status; const message = error.response?.data?.message ?? error.message ?? '网络请求失败'; if (status === 401) { clearCalendarCache(); localStorage.removeItem(STORAGE_KEYS.token); localStorage.removeItem(STORAGE_KEYS.user); ElMessage.warning('登录状态已失效,请重新登录'); if (!window.location.pathname.endsWith('/login')) { window.location.assign('/login'); } } else { ElMessage.error(message); } return Promise.reject(error); }, ); /** 统一请求入口:返回值已经是响应体里的 data */ async function request(config: AxiosRequestConfig): Promise { return (await instance.request(config)) as unknown as T; } export const api = { stageAiAttachment: ( taskId: string, attachmentId: string, file: File, signal?: AbortSignal, ): Promise => request({ method: 'PUT', url: `/ai/tasks/${encodeURIComponent(taskId)}/files/${encodeURIComponent(attachmentId)}`, data: file, headers: { 'content-type': 'application/octet-stream' }, signal, timeout: 600000, }), executeAi: ( stepId: string, action: AiExecutionRequest, file?: File, signal?: AbortSignal, progress?: (percent: number) => void, ): Promise => { if (!allowsAiExecution(action)) throw new Error('助手不允许执行此请求'); return request({ method: action.method, url: action.path, params: action.query, data: file ?? action.body, signal, timeout: file || action.path === '/update/client/fetch' ? 600000 : 120000, headers: { 'x-classhelper-ai-step': stepId, ...(file ? { 'content-type': 'application/octet-stream', 'x-classhelper-ai-sha256': action.sha256 } : {}), }, onUploadProgress: (event) => progress?.(Math.min(100, Math.round(100 * (event.loaded / (event.total || file?.size || 1))))), }); }, get: (url: string, params?: Record): Promise => request({ method: 'GET', url, params }), post: (url: string, data?: unknown, config?: AxiosRequestConfig): Promise => request({ method: 'POST', url, data, ...config }), patch: (url: string, data?: unknown): Promise => request({ method: 'PATCH', url, data }), put: (url: string, data?: unknown): Promise => request({ method: 'PUT', url, data }), delete: (url: string): Promise => request({ method: 'DELETE', url }), /** * 下载二进制(返回 Blob,调用方负责触发浏览器保存)。 * 请求拦截器照常带 token;响应是 Blob 时拦截器原样放行(不含 success 字段)。 */ download: (url: string): Promise => request({ method: 'GET', url, responseType: 'blob' }), };