import { Injectable, OnDestroy } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { BehaviorSubject, Observable, of, Subscription } from 'rxjs'; import { map, tap } from 'rxjs/operators'; import { Session, SessionCreateRequest, SessionCreateApiResponse, SessionListResponse } from '../models/session.model'; import { AuthService } from './auth.service'; import { EventService } from './event.service'; import { SessionUpdatedEvent } from '../models/event.model'; @Injectable({ providedIn: 'root' }) export class SessionService implements OnDestroy { private activeSession = new BehaviorSubject(null); activeSession$ = this.activeSession.asObservable(); private sessions: Session[] = []; private sessionsSubject = new BehaviorSubject([]); sessions$ = this.sessionsSubject.asObservable(); private eventSubscription: Subscription = new Subscription(); constructor( private http: HttpClient, private authService: AuthService, private eventService: EventService ) { this.setupEventSubscriptions(); } // 获取会话列表(需要认证) getSessions(): Observable { // 检查用户是否已认证 if (!this.authService.isAuthenticated()) { console.warn('用户未认证,无法获取会话列表,返回空数组'); return of([]); } return this.http.get('/api/session/list').pipe( map(response => { if (response.success && response.data) { this.sessions = response.data; this.sessionsSubject.next(this.sessions); return response.data; } else { throw new Error(response.message || '获取会话列表失败'); } }), tap(sessions => { // 如果没有活动会话,设置第一个为活动会话 if (sessions.length > 0 && !this.activeSession.value) { this.setActiveSession(sessions[0]); } }) ); } // 创建新会话 createSession(title: string): Observable { // 检查用户是否已认证 if (!this.authService.isAuthenticated()) { console.error('用户未认证,无法创建会话'); throw new Error('用户未认证,请先登录'); } const request: SessionCreateRequest = { title }; return this.http.post('/api/session/create', request).pipe( map(response => { console.log('🔍 [SessionService] 创建会话响应:', response); if (response.success && response.data) { const sessionData = response.data; const newSession: Session = { id: sessionData.id, title: sessionData.title, port: sessionData.port, baseURL: sessionData.baseURL }; this.sessions.unshift(newSession); this.sessionsSubject.next([...this.sessions]); this.setActiveSession(newSession); return newSession; } else { throw new Error(response.message || '创建会话失败'); } }) ); } // 设置活动会话 setActiveSession(session: Session | null) { this.activeSession.next(session); } // 获取当前活动会话 getActiveSession(): Session | null { return this.activeSession.value; } // 根据ID获取会话 getSessionById(id: string): Session | undefined { return this.sessions.find(session => session.id === id); } // 加载会话列表(公共方法,供组件调用) loadSessions(): void { if (!this.authService.isAuthenticated()) { console.warn('用户未认证,跳过会话列表加载'); this.sessionsSubject.next([]); return; } this.getSessions().subscribe({ error: (error) => { console.error('加载会话列表失败:', error); // 如果API不可用,使用空列表 this.sessionsSubject.next([]); } }); } // 删除会话(如果后端支持) deleteSession(sessionId: string): Observable { // 注意:后端可能没有删除API,这里只是示例 return of(true).pipe( tap(() => { this.sessions = this.sessions.filter(s => s.id !== sessionId); this.sessionsSubject.next([...this.sessions]); // 如果删除的是活动会话,清空活动会话 if (this.activeSession.value?.id === sessionId) { this.setActiveSession(null); } }) ); } // 设置事件订阅 private setupEventSubscriptions() { // 订阅会话更新事件 this.eventSubscription.add( this.eventService.sessionUpdated$.subscribe(event => { this.handleSessionUpdated(event); }) ); } // 处理会话更新事件 private handleSessionUpdated(event: SessionUpdatedEvent) { const sessionInfo = event.properties.info; console.log('SessionService: 处理会话更新事件', sessionInfo.id, sessionInfo.title); // 查找现有会话 const existingSessionIndex = this.sessions.findIndex(s => s.id === sessionInfo.id); if (existingSessionIndex !== -1) { // 更新现有会话 const updatedSession: Session = { ...this.sessions[existingSessionIndex], title: sessionInfo.title, // 保留其他字段如port、baseURL等 }; this.sessions[existingSessionIndex] = updatedSession; console.log('SessionService: 更新现有会话', updatedSession.title); } else { // 添加新会话到列表开头 const newSession: Session = { id: sessionInfo.id, title: sessionInfo.title, // port和baseURL可能在后端创建会话时提供,这里使用默认值 // 实际使用中,可以从事件或后续API调用中获取 port: 8020, // 默认端口,可根据需要调整 baseURL: `http://localhost:8020`, // 默认baseURL }; this.sessions.unshift(newSession); console.log('SessionService: 添加新会话', newSession.title); } // 通知订阅者 this.sessionsSubject.next([...this.sessions]); } ngOnDestroy() { this.eventSubscription.unsubscribe(); } }