/** * API 客户端模块 * 提供统一的 HTTP 请求封装和认证管理 */ (function() { 'use strict'; /** * API 客户端类 */ class APIClient { constructor() { this.baseURL = window.API_CONFIG?.baseURL || ''; this.version = window.API_CONFIG?.version || '/api'; this.timeout = window.API_CONFIG?.timeout || 30000; } /** * 获取完整 URL */ getUrl(endpoint) { return `${this.baseURL}${this.version}${endpoint}`; } /** * 获取认证 Token */ getToken() { return localStorage.getItem('smart_center_token'); } /** * 检查是否已登录 */ isAuthenticated() { const token = this.getToken(); return !!token; } /** * 发送 HTTP 请求 */ async request(endpoint, options = {}) { const url = this.getUrl(endpoint); const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', ...options.headers }; // 添加认证 Token const token = this.getToken(); if (token) { headers['Authorization'] = `Bearer ${token}`; } try { const response = await fetch(url, { ...options, headers, signal: AbortSignal.timeout(this.timeout) }); const data = await response.json(); if (!response.ok) { throw new Error(data.message || `HTTP ${response.status}`); } return data; } catch (error) { console.error(`API 请求失败 [${endpoint}]:`, error); throw error; } } /** * GET 请求 */ async get(endpoint, params = {}) { const queryString = new URLSearchParams(params).toString(); const url = queryString ? `${endpoint}?${queryString}` : endpoint; return this.request(url, { method: 'GET' }); } /** * POST 请求 */ async post(endpoint, data = {}) { return this.request(endpoint, { method: 'POST', body: JSON.stringify(data) }); } /** * PUT 请求 */ async put(endpoint, data = {}) { return this.request(endpoint, { method: 'PUT', body: JSON.stringify(data) }); } /** * DELETE 请求 */ async delete(endpoint) { return this.request(endpoint, { method: 'DELETE' }); } /** * 上传文件 */ async upload(endpoint, formData) { const url = this.getUrl(endpoint); const headers = {}; const token = this.getToken(); if (token) { headers['Authorization'] = `Bearer ${token}`; } try { const response = await fetch(url, { method: 'POST', headers, body: formData, signal: AbortSignal.timeout(this.timeout) }); const data = await response.json(); if (!response.ok) { throw new Error(data.message || `HTTP ${response.status}`); } return data; } catch (error) { console.error(`文件上传失败 [${endpoint}]:`, error); throw error; } } /** * 登录 */ async login(username, password) { const data = await this.post('/auth/login', { username, password }); if (data.token) { localStorage.setItem('smart_center_token', data.token); } return data; } /** * 注册 */ async register(userData) { return this.post('/auth/register', userData); } /** * 登出 */ async logout() { try { await this.post('/auth/logout'); } finally { localStorage.removeItem('smart_center_token'); } } /** * 获取用户信息 */ async getUserInfo() { return this.get('/user/info'); } /** * 发送聊天消息 */ async sendMessage(message, attachments = []) { if (attachments.length > 0) { // 多模态消息 const formData = new FormData(); formData.append('message', message); for (const file of attachments) { formData.append('files', file); } return this.upload('/chat/multimodal', formData); } else { // 纯文本消息 return this.post('/chat/send', { message }); } } /** * 获取模块列表 */ async getModuleList() { return this.get('/modules/list'); } /** * 获取模块详情 */ async getModuleDetail(moduleName) { return this.get(`/modules/detail/${moduleName}`); } } // 创建全局实例 window.APIClient = APIClient; window.apiClient = new APIClient(); console.log('✅ APIClient 已加载'); })();