Brak opisu
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

project-tab.component.ts 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import { Component, OnInit, OnDestroy, HostListener, Input, OnChanges, SimpleChanges } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { ActivatedRoute } from '@angular/router';
  4. import { MatIcon } from '@angular/material/icon';
  5. import { MatButtonModule } from '@angular/material/button';
  6. import { MatCardModule } from '@angular/material/card';
  7. import { MatListModule } from '@angular/material/list';
  8. import { MatExpansionModule } from '@angular/material/expansion';
  9. import { MatChipsModule } from '@angular/material/chips';
  10. import { MatProgressBarModule } from '@angular/material/progress-bar';
  11. import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
  12. import { MatTooltipModule } from '@angular/material/tooltip';
  13. import { Subscription } from 'rxjs';
  14. import { ConversationComponent } from './conversation.component';
  15. import { DocumentListComponent } from './document-list.component';
  16. import { AIResponseComponent } from './ai-response.component';
  17. import { SessionService } from '../services/session.service';
  18. import { AgentService } from '../services/agent.service';
  19. import { MockDataService } from '../services/mock-data.service';
  20. import { EventService } from '../services/event.service';
  21. import { IndependentEventService } from '../services/independent-event.service';
  22. import { Session, SessionStatus } from '../models/session.model';
  23. import { DocumentType, DocumentSession } from '../models/document.model';
  24. @Component({
  25. selector: 'app-project-tab',
  26. standalone: true,
  27. imports: [
  28. CommonModule,
  29. MatIcon,
  30. MatButtonModule,
  31. MatCardModule,
  32. MatListModule,
  33. MatExpansionModule,
  34. MatChipsModule,
  35. MatProgressBarModule,
  36. MatProgressSpinnerModule,
  37. MatTooltipModule,
  38. ConversationComponent,
  39. DocumentListComponent,
  40. AIResponseComponent
  41. ],
  42. templateUrl: './project-tab.component.html',
  43. styleUrl: './project-tab.component.scss',
  44. })
  45. export class ProjectTabComponent implements OnInit, OnDestroy, OnChanges {
  46. @Input() tabId?: string;
  47. @Input() standalone = false;
  48. @Input() instanceId?: string;
  49. @Input() projectId?: string;
  50. @Input() independentEventService?: IndependentEventService;
  51. project: Session | null = null;
  52. effectiveInstanceId: string = '';
  53. // 文档数据
  54. documentSessions: DocumentSession[] = [];
  55. leftWidth = 320;
  56. middleWidth = 500;
  57. isDragging = false;
  58. isDraggingMiddle = false;
  59. minLeftWidth = 280;
  60. maxLeftWidth = 500;
  61. minMiddleWidth = 400;
  62. maxMiddleWidth = 800;
  63. private subscriptions: Subscription = new Subscription();
  64. private eventSubscription?: Subscription;
  65. constructor(
  66. private sessionService: SessionService,
  67. private agentService: AgentService,
  68. private mockDataService: MockDataService,
  69. private eventService: EventService,
  70. private route: ActivatedRoute
  71. ) {}
  72. ngOnInit() {
  73. // 生成或使用传入的实例ID
  74. this.updateEffectiveInstanceId();
  75. // 从本地存储恢复宽度
  76. const savedLeftWidth = localStorage.getItem('project_tab_leftWidth');
  77. if (savedLeftWidth) {
  78. this.leftWidth = parseInt(savedLeftWidth, 10);
  79. }
  80. const savedMiddleWidth = localStorage.getItem('project_tab_middleWidth');
  81. if (savedMiddleWidth) {
  82. this.middleWidth = parseInt(savedMiddleWidth, 10);
  83. }
  84. // 监听路由参数变化或使用输入参数
  85. if (this.projectId) {
  86. // 使用输入的项目ID
  87. this.loadProjectDirectly(this.projectId);
  88. } else {
  89. // 监听路由参数
  90. this.subscriptions.add(
  91. this.route.paramMap.subscribe(params => {
  92. const projectId = params.get('projectId');
  93. if (projectId) {
  94. this.loadProjectDirectly(projectId);
  95. }
  96. })
  97. );
  98. }
  99. }
  100. ngOnChanges(changes: SimpleChanges) {
  101. console.log('🔍 [ProjectTabComponent] 输入属性变化:', changes);
  102. // 处理instanceId变化
  103. if (changes['instanceId']) {
  104. console.log('🔍 [ProjectTabComponent] instanceId变化,更新有效实例ID');
  105. this.updateEffectiveInstanceId();
  106. }
  107. if (changes['projectId'] && !changes['projectId'].firstChange) {
  108. console.log('🔍 [ProjectTabComponent] 项目ID变化,重新加载项目:', this.projectId);
  109. // 清理旧的订阅
  110. this.subscriptions.unsubscribe();
  111. this.subscriptions = new Subscription();
  112. // 取消文档事件订阅
  113. if (this.eventSubscription) {
  114. this.eventSubscription.unsubscribe();
  115. this.eventSubscription = undefined;
  116. }
  117. // 重置项目数据
  118. this.project = null;
  119. this.documentSessions = [];
  120. // 项目变化时更新实例ID,确保SSE事件路由正确
  121. this.updateEffectiveInstanceId();
  122. // 重新加载项目
  123. if (this.projectId) {
  124. this.loadProjectDirectly(this.projectId);
  125. }
  126. }
  127. }
  128. private loadProjectDirectly(projectId: string) {
  129. console.log('🔍 [ProjectTabComponent] 独立模式加载项目:', projectId);
  130. // 直接从会话服务加载项目,不依赖标签页
  131. this.subscriptions.add(
  132. this.sessionService.sessions$.subscribe(sessions => {
  133. console.log('🔍 [ProjectTabComponent] 收到会话列表,数量:', sessions.length, '查找项目ID:', projectId);
  134. // 首先尝试用project_id匹配(项目ID)
  135. let session = sessions.find(s => s.project_id === projectId);
  136. if (session) {
  137. console.log('🔍 [ProjectTabComponent] 通过project_id找到会话:', session.id, '标题:', session.title);
  138. } else {
  139. // 如果没找到,尝试用id匹配(可能是会话ID)
  140. session = sessions.find(s => s.id === projectId);
  141. if (session) {
  142. console.log('🔍 [ProjectTabComponent] 通过id找到会话:', session.id, '标题:', session.title, 'project_id:', session.project_id);
  143. }
  144. }
  145. if (session && session !== this.project) {
  146. console.log('🔍 [ProjectTabComponent] 设置项目会话:', session.id);
  147. this.project = session;
  148. this.updateEffectiveInstanceId();
  149. // 独立模式下不设置全局活动会话,避免状态污染
  150. // this.sessionService.setActiveSession(session);
  151. this.loadDocumentSessions();
  152. } else if (!session) {
  153. console.log('🔍 [ProjectTabComponent] 未找到对应会话,等待会话加载');
  154. }
  155. })
  156. );
  157. // 初始加载会话列表
  158. this.sessionService.loadSessions();
  159. }
  160. getAgentDisplayName(agentId: string): string {
  161. return this.agentService.getAgentDisplayName(agentId);
  162. }
  163. getStatusDisplayName(status: string): string {
  164. const statusMap: Record<string, string> = {
  165. 'requirement_document': '需求文档',
  166. 'technical_document': '技术文档',
  167. 'code': '代码开发',
  168. 'test': '测试',
  169. 'release': '发布'
  170. };
  171. return statusMap[status] || status;
  172. }
  173. getStatusClass(status: string): string {
  174. return `status-${status}`;
  175. }
  176. formatDate(dateString?: string): string {
  177. if (!dateString) return '未知';
  178. const date = new Date(dateString);
  179. return date.toLocaleDateString('zh-CN');
  180. }
  181. getProgressValue(status: string): number {
  182. const progressMap: Record<string, number> = {
  183. 'requirement_document': 20,
  184. 'technical_document': 40,
  185. 'code': 60,
  186. 'test': 80,
  187. 'release': 100
  188. };
  189. return progressMap[status] || 0;
  190. }
  191. getProgressText(status: string): string {
  192. const progressMap: Record<string, string> = {
  193. 'requirement_document': '20% - 需求分析',
  194. 'technical_document': '40% - 技术设计',
  195. 'code': '60% - 代码开发',
  196. 'test': '80% - 测试验证',
  197. 'release': '100% - 发布完成'
  198. };
  199. return progressMap[status] || '0% - 未开始';
  200. }
  201. focusRequirementInput() {
  202. // TODO: 聚焦到对话输入框,并提示输入需求
  203. console.log('聚焦需求输入');
  204. // 可以通过服务或事件通知ConversationComponent
  205. }
  206. startDrag(event: MouseEvent) {
  207. event.preventDefault();
  208. this.isDragging = true;
  209. document.body.style.cursor = 'col-resize';
  210. document.body.style.userSelect = 'none';
  211. }
  212. startMiddleDrag(event: MouseEvent) {
  213. event.preventDefault();
  214. this.isDraggingMiddle = true;
  215. document.body.style.cursor = 'col-resize';
  216. document.body.style.userSelect = 'none';
  217. }
  218. @HostListener('document:mousemove', ['$event'])
  219. onDrag(event: MouseEvent) {
  220. if (this.isDragging) {
  221. const newWidth = event.clientX;
  222. if (newWidth >= this.minLeftWidth && newWidth <= this.maxLeftWidth) {
  223. this.leftWidth = newWidth;
  224. }
  225. }
  226. if (this.isDraggingMiddle) {
  227. const newWidth = event.clientX - this.leftWidth - 8;
  228. if (newWidth >= this.minMiddleWidth && newWidth <= this.maxMiddleWidth) {
  229. this.middleWidth = newWidth;
  230. }
  231. }
  232. }
  233. @HostListener('document:mouseup')
  234. stopDrag() {
  235. if (this.isDragging) {
  236. this.isDragging = false;
  237. localStorage.setItem('project_tab_leftWidth', this.leftWidth.toString());
  238. }
  239. if (this.isDraggingMiddle) {
  240. this.isDraggingMiddle = false;
  241. localStorage.setItem('project_tab_middleWidth', this.middleWidth.toString());
  242. }
  243. document.body.style.cursor = '';
  244. document.body.style.userSelect = '';
  245. }
  246. /**
  247. * 加载文档会话数据
  248. */
  249. private loadDocumentSessions() {
  250. if (!this.project) return;
  251. const projectId = this.project.project_id || this.project.id;
  252. this.mockDataService.getProjectDocuments(projectId).subscribe({
  253. next: (documents) => {
  254. this.documentSessions = documents;
  255. // 设置文档会话的事件订阅
  256. this.setupDocumentEventSubscriptions();
  257. },
  258. error: (error) => {
  259. console.error('加载文档数据失败:', error);
  260. // 使用空文档作为回退
  261. import('../models/document.model').then(module => {
  262. this.documentSessions = module.createEmptyDocumentSessions(projectId);
  263. // 即使使用空文档,也尝试设置事件订阅
  264. this.setupDocumentEventSubscriptions();
  265. });
  266. }
  267. });
  268. }
  269. /**
  270. * 设置文档会话的事件订阅
  271. */
  272. private setupDocumentEventSubscriptions() {
  273. // 取消现有的事件订阅
  274. if (this.eventSubscription) {
  275. this.eventSubscription.unsubscribe();
  276. this.eventSubscription = undefined;
  277. }
  278. // 获取有效的文档会话ID
  279. const sessionIds = this.getDocumentSessionIds();
  280. if (sessionIds.length === 0) {
  281. console.log('没有有效的文档会话ID可订阅');
  282. return;
  283. }
  284. console.log(`设置文档事件订阅,会话ID:`, sessionIds);
  285. // 连接到多会话事件流
  286. this.eventService.connectToMultipleSessions(sessionIds);
  287. // 订阅多会话事件
  288. this.eventSubscription = this.eventService.multiSessionEvents$.subscribe({
  289. next: ({ sessionId, event }) => {
  290. this.handleDocumentEvent(sessionId, event);
  291. },
  292. error: (error) => {
  293. console.error('文档事件订阅错误:', error);
  294. }
  295. });
  296. }
  297. /**
  298. * 处理文档事件,更新文档内容
  299. */
  300. private handleDocumentEvent(sessionId: string, event: any) {
  301. // 找到对应的文档
  302. const docIndex = this.documentSessions.findIndex(doc => doc.sessionId === sessionId);
  303. if (docIndex === -1) {
  304. // 未找到对应文档,可能是其他事件
  305. return;
  306. }
  307. const payload = event.payload;
  308. console.log(`处理文档事件,会话ID: ${sessionId}, 类型: ${payload.type}`);
  309. // 提取内容
  310. let content = '';
  311. const properties = payload.properties || {};
  312. if (payload.type === 'message.updated') {
  313. // 处理消息更新事件
  314. const messageInfo = properties.info || {};
  315. if (messageInfo.content) {
  316. content = messageInfo.content;
  317. }
  318. } else if (properties.content) {
  319. content = properties.content;
  320. } else if (properties.message) {
  321. content = properties.message;
  322. } else if (properties.info && properties.info.content) {
  323. content = properties.info.content;
  324. }
  325. if (content) {
  326. // 更新文档内容
  327. this.documentSessions[docIndex] = {
  328. ...this.documentSessions[docIndex],
  329. content: content,
  330. lastUpdated: new Date(),
  331. hasContent: true,
  332. isLoading: false
  333. };
  334. // 触发变更检测(使用展开操作符创建新数组)
  335. this.documentSessions = [...this.documentSessions];
  336. console.log(`文档 ${this.documentSessions[docIndex].title} 内容已更新,长度: ${content.length} 字符`);
  337. }
  338. }
  339. /**
  340. * 获取所有文档会话ID(过滤空值)
  341. */
  342. getDocumentSessionIds(): string[] {
  343. return this.documentSessions
  344. .map(doc => doc.sessionId)
  345. .filter(sessionId => sessionId && sessionId.trim() !== '');
  346. }
  347. /**
  348. * 更新有效的实例ID
  349. * 优先使用传入的instanceId,其次使用项目会话ID,最后生成一个唯一ID
  350. */
  351. private updateEffectiveInstanceId(): void {
  352. if (this.instanceId && this.instanceId.trim() !== '') {
  353. // 使用传入的instanceId
  354. this.effectiveInstanceId = this.instanceId;
  355. console.log('🔍 [ProjectTabComponent] 使用传入的instanceId:', this.effectiveInstanceId);
  356. } else {
  357. // 生成唯一的实例ID作为回退,确保每个标签页有唯一ID
  358. this.effectiveInstanceId = `tab-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  359. console.log('🔍 [ProjectTabComponent] 生成唯一instanceId:', this.effectiveInstanceId);
  360. }
  361. }
  362. ngOnDestroy() {
  363. this.subscriptions.unsubscribe();
  364. // 取消文档事件订阅
  365. if (this.eventSubscription) {
  366. this.eventSubscription.unsubscribe();
  367. this.eventSubscription = undefined;
  368. }
  369. }
  370. }