requirements-confirm-card.ts 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575
  1. import { Component, Input, Output, EventEmitter, OnInit, OnDestroy, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { FormsModule, ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
  4. import { UploadSuccessModalComponent } from '../upload-success-modal/upload-success-modal.component';
  5. import { GlobalPromptComponent } from '../global-prompt/global-prompt.component';
  6. import { ColorAnalysisService, ColorAnalysisResult } from '../../services/color-analysis.service';
  7. import { FullReportOverlayComponent } from '../full-report-overlay/full-report-overlay.component';
  8. import { CadAnalysisService, CadAnalysisResult } from '../../services/cad-analysis.service';
  9. // 素材文件接口
  10. interface MaterialFile {
  11. id: string;
  12. name: string;
  13. type: 'text' | 'image' | 'cad';
  14. url?: string;
  15. content?: string;
  16. size?: string;
  17. uploadTime: Date;
  18. analysis?: MaterialAnalysis;
  19. }
  20. // 素材解析结果接口
  21. interface MaterialAnalysis {
  22. // 文本类解析
  23. atmosphere?: { description: string; rgb?: string; colorTemp?: string };
  24. residents?: { type: string; details: string };
  25. scenes?: { preference: string; requirements: string };
  26. keywords?: { positive: string[]; negative: string[] };
  27. // 图片类解析
  28. mainColors?: { rgb: string; percentage: number }[];
  29. colorTemperature?: string;
  30. materialRatio?: { material: string; percentage: number }[];
  31. spaceRatio?: number;
  32. // CAD类解析
  33. structuralElements?: { type: string; position: string; changeable: boolean }[];
  34. spaceMetrics?: { room: string; ratio: string; width: string }[];
  35. flowMetrics?: { area: string; width: string; compliance: boolean }[];
  36. }
  37. // 需求指标接口
  38. interface RequirementMetric {
  39. id: string;
  40. category: 'color' | 'space' | 'material';
  41. name: string;
  42. value: any;
  43. unit?: string;
  44. range?: { min: number; max: number };
  45. description?: string;
  46. }
  47. // 协作评论接口
  48. interface CollaborationComment {
  49. id: string;
  50. author: string;
  51. role: 'customer-service' | 'designer' | 'client';
  52. content: string;
  53. timestamp: Date;
  54. requirementId?: string;
  55. status: 'pending' | 'resolved';
  56. }
  57. // 需求项接口
  58. interface RequirementItem {
  59. id: string;
  60. title: string;
  61. description: string;
  62. priority: 'high' | 'medium' | 'low';
  63. status: 'pending' | 'confirmed' | 'rejected';
  64. tags?: string[];
  65. metrics?: RequirementMetric[];
  66. comments?: CollaborationComment[];
  67. lastUpdated: Date;
  68. showComments?: boolean;
  69. }
  70. @Component({
  71. selector: 'app-requirements-confirm-card',
  72. standalone: true,
  73. imports: [CommonModule, FormsModule, ReactiveFormsModule, UploadSuccessModalComponent, GlobalPromptComponent, FullReportOverlayComponent],
  74. providers: [CadAnalysisService],
  75. templateUrl: './requirements-confirm-card.html',
  76. styleUrls: ['./requirements-confirm-card.scss'],
  77. changeDetection: ChangeDetectionStrategy.Default // 确保使用默认变更检测策略
  78. })
  79. export class RequirementsConfirmCardComponent implements OnInit, OnDestroy {
  80. @Input() projectId?: string;
  81. @Output() requirementConfirmed = new EventEmitter<RequirementItem>();
  82. @Output() progressUpdated = new EventEmitter<number>();
  83. @Output() stageCompleted = new EventEmitter<{ stage: string; allStagesCompleted: boolean }>();
  84. @Output() dataUpdated = new EventEmitter<any>(); // 新增:实时数据更新事件
  85. // 表单
  86. materialForm!: FormGroup;
  87. commentForm!: FormGroup;
  88. materialUploadForm!: FormGroup;
  89. // 数据
  90. materialFiles: MaterialFile[] = [];
  91. materials: MaterialFile[] = [];
  92. requirementMetrics: RequirementMetric[] = [];
  93. collaborationComments: CollaborationComment[] = [];
  94. requirementItems: RequirementItem[] = [];
  95. // 状态
  96. activeTab: 'materials' | 'mapping' | 'collaboration' | 'progress' = 'materials';
  97. isUploading = false;
  98. isAnalyzing = false;
  99. dragOver = false;
  100. showConsistencyWarning = false;
  101. warningMessage = '';
  102. // 自动保存相关状态
  103. autoSaveEnabled = true;
  104. lastSaveTime?: Date;
  105. hasUnsavedChanges = false;
  106. isSaving = false;
  107. saveStatus: 'saved' | 'saving' | 'error' | 'unsaved' = 'saved';
  108. // 流程状态
  109. stageCompletionStatus = {
  110. materialAnalysis: false,
  111. requirementMapping: false,
  112. collaboration: false,
  113. progressReview: false
  114. };
  115. // 自动保存定时器
  116. private autoSaveTimer?: any;
  117. // 需求指标
  118. colorIndicators = {
  119. mainColor: { r: 255, g: 230, b: 180 },
  120. colorTemperature: 2700,
  121. colorRange: '暖色调',
  122. saturation: 70,
  123. brightness: 80,
  124. contrast: 60
  125. };
  126. spaceIndicators = {
  127. lineRatio: 60,
  128. blankRatio: 30,
  129. flowWidth: 0.9,
  130. aspectRatio: 1.6,
  131. ceilingHeight: 2.8,
  132. lightingLevel: 300
  133. };
  134. materialIndicators = {
  135. fabricRatio: 50,
  136. woodRatio: 30,
  137. metalRatio: 20,
  138. smoothness: 7,
  139. glossiness: 4,
  140. texture: 6
  141. };
  142. // 指标范围配置
  143. indicatorRanges = {
  144. color: {
  145. r: { min: 0, max: 255 },
  146. g: { min: 0, max: 255 },
  147. b: { min: 0, max: 255 },
  148. temperature: { min: 2000, max: 6500 },
  149. saturation: { min: 0, max: 100 },
  150. brightness: { min: 0, max: 100 },
  151. contrast: { min: 0, max: 100 }
  152. },
  153. space: {
  154. lineRatio: { min: 0, max: 100 },
  155. blankRatio: { min: 10, max: 80 },
  156. flowWidth: { min: 0.6, max: 1.5 },
  157. aspectRatio: { min: 1.0, max: 3.0 },
  158. ceilingHeight: { min: 2.4, max: 4.0 },
  159. lightingLevel: { min: 100, max: 800 }
  160. },
  161. material: {
  162. fabricRatio: { min: 0, max: 100 },
  163. woodRatio: { min: 0, max: 100 },
  164. metalRatio: { min: 0, max: 100 },
  165. smoothness: { min: 1, max: 10 },
  166. glossiness: { min: 1, max: 10 },
  167. texture: { min: 1, max: 10 }
  168. }
  169. };
  170. // 预设数据
  171. presetAtmospheres = [
  172. { name: '温馨暖调', rgb: '255,230,180', colorTemp: '2700-3000K', materials: ['木质', '布艺'] },
  173. { name: '现代冷调', rgb: '200,220,240', colorTemp: '5000-6000K', materials: ['金属', '玻璃'] },
  174. { name: '自然清新', rgb: '220,240,220', colorTemp: '4000-4500K', materials: ['竹木', '石材'] }
  175. ];
  176. // 一致性检查
  177. consistencyWarnings: string[] = [];
  178. historyStates: any[] = [];
  179. // 上传成功弹窗相关
  180. showUploadSuccessModal = false;
  181. uploadedFiles: { id: string; name: string; url: string; size?: number; type?: 'image' | 'cad' | 'text'; preview?: string }[] = [];
  182. uploadType: 'image' | 'document' | 'mixed' = 'image';
  183. colorAnalysisResult?: ColorAnalysisResult;
  184. cadAnalysisResult?: CadAnalysisResult;
  185. // 全局提示组件状态
  186. showGlobalPrompt = false;
  187. promptMode: 'fullscreen' | 'corner' = 'corner';
  188. promptPosition: 'top-right' | 'bottom-right' = 'bottom-right';
  189. promptTitle = '上传成功!';
  190. promptMessage = '';
  191. // 全屏报告覆盖层
  192. showFullReportOverlay = false;
  193. constructor(
  194. private fb: FormBuilder,
  195. private cdr: ChangeDetectorRef,
  196. private colorAnalysisService: ColorAnalysisService,
  197. private cadAnalysisService: CadAnalysisService
  198. ) {}
  199. ngOnInit() {
  200. this.initializeForms();
  201. this.initializeRequirements();
  202. this.loadPresetMetrics();
  203. // 启用自动保存
  204. this.autoSaveEnabled = true;
  205. // 定期检查阶段完成状态
  206. setInterval(() => {
  207. this.checkStageCompletion();
  208. }, 5000);
  209. }
  210. ngOnDestroy(): void {
  211. // 清理自动保存定时器
  212. if (this.autoSaveTimer) {
  213. clearTimeout(this.autoSaveTimer);
  214. }
  215. }
  216. private initializeForms() {
  217. this.materialForm = this.fb.group({
  218. textContent: ['', Validators.required],
  219. atmosphereDescription: [''],
  220. residentInfo: [''],
  221. scenePreferences: [''],
  222. title: [''],
  223. content: ['']
  224. });
  225. this.commentForm = this.fb.group({
  226. content: ['', Validators.required],
  227. requirementId: ['']
  228. });
  229. this.materialUploadForm = this.fb.group({
  230. file: [''],
  231. textContent: ['', Validators.required]
  232. });
  233. }
  234. private initializeRequirements() {
  235. this.requirementItems = [
  236. {
  237. id: 'color-atmosphere',
  238. title: '色彩氛围',
  239. description: '整体色调和氛围营造',
  240. priority: 'high',
  241. status: 'pending',
  242. lastUpdated: new Date()
  243. },
  244. {
  245. id: 'space-layout',
  246. title: '空间布局',
  247. description: '功能分区和动线设计',
  248. priority: 'high',
  249. status: 'pending',
  250. lastUpdated: new Date()
  251. },
  252. {
  253. id: 'material-selection',
  254. title: '材质选择',
  255. description: '主要材质和质感要求',
  256. priority: 'medium',
  257. status: 'pending',
  258. lastUpdated: new Date()
  259. }
  260. ];
  261. }
  262. private loadPresetMetrics() {
  263. this.requirementMetrics = [
  264. {
  265. id: 'main-color',
  266. category: 'color',
  267. name: '主色调',
  268. value: { r: 255, g: 230, b: 180 },
  269. description: '空间主要色彩'
  270. },
  271. {
  272. id: 'color-temp',
  273. category: 'color',
  274. name: '色温',
  275. value: 3000,
  276. unit: 'K',
  277. range: { min: 2700, max: 6500 },
  278. description: '照明色温范围'
  279. },
  280. {
  281. id: 'wood-ratio',
  282. category: 'material',
  283. name: '木质占比',
  284. value: 60,
  285. unit: '%',
  286. range: { min: 0, max: 100 },
  287. description: '木质材料使用比例'
  288. }
  289. ];
  290. }
  291. // 素材上传功能
  292. onFileSelected(event: Event, type: 'text' | 'image' | 'cad') {
  293. const input = event.target as HTMLInputElement;
  294. if (input.files) {
  295. Array.from(input.files).forEach(file => {
  296. this.uploadFile(file, type);
  297. });
  298. }
  299. }
  300. onFileDrop(event: DragEvent, type: 'text' | 'image' | 'cad') {
  301. event.preventDefault();
  302. this.dragOver = false;
  303. if (event.dataTransfer?.files) {
  304. Array.from(event.dataTransfer.files).forEach(file => {
  305. this.uploadFile(file, type);
  306. });
  307. }
  308. }
  309. onDragOver(event: DragEvent) {
  310. event.preventDefault();
  311. this.dragOver = true;
  312. }
  313. onDragLeave(event: DragEvent) {
  314. event.preventDefault();
  315. this.dragOver = false;
  316. }
  317. private uploadFile(file: File, type: 'text' | 'image' | 'cad') {
  318. this.isUploading = true;
  319. // 模拟文件上传
  320. setTimeout(() => {
  321. const materialFile: MaterialFile = {
  322. id: this.generateId(),
  323. name: file.name,
  324. type: type,
  325. url: URL.createObjectURL(file),
  326. size: this.formatFileSize(file.size),
  327. uploadTime: new Date()
  328. };
  329. this.materialFiles.push(materialFile);
  330. this.materials.push(materialFile);
  331. this.isUploading = false;
  332. // 显示全局提示(角落模式,无遮罩,不遮挡操作)
  333. this.promptTitle = '上传成功!';
  334. this.promptMessage = `已上传文件:${file.name}`;
  335. this.promptMode = 'corner';
  336. this.promptPosition = 'bottom-right';
  337. this.showGlobalPrompt = true;
  338. // 显示上传成功弹窗
  339. this.showUploadSuccessModal = true;
  340. this.uploadedFiles = [{
  341. id: materialFile.id,
  342. name: file.name,
  343. url: materialFile.url || '',
  344. size: file.size,
  345. type: type === 'text' ? 'text' : type === 'image' ? 'image' : 'cad'
  346. }];
  347. this.uploadType = type === 'text' ? 'document' : type === 'image' ? 'image' : 'mixed';
  348. // 自动解析
  349. this.analyzeMaterial(materialFile);
  350. }, 1000);
  351. }
  352. // 文本提交
  353. onTextSubmit(): void {
  354. if (this.materialUploadForm.valid) {
  355. const formValue = this.materialUploadForm.value;
  356. const textMaterial: MaterialFile = {
  357. id: this.generateId(),
  358. name: '文本需求',
  359. type: 'text',
  360. content: formValue.textContent,
  361. uploadTime: new Date(),
  362. size: this.formatFileSize(formValue.textContent?.length || 0)
  363. };
  364. this.materialFiles.push(textMaterial);
  365. this.materials.push(textMaterial);
  366. this.analyzeMaterial(textMaterial);
  367. this.materialUploadForm.reset();
  368. }
  369. }
  370. // 素材解析功能
  371. private analyzeMaterial(material: MaterialFile) {
  372. this.isAnalyzing = true;
  373. // CAD采用服务分析,其它类型保持模拟
  374. if (material.type === 'cad') {
  375. const fileUrl = material.url || '';
  376. this.cadAnalysisService.analyzeByUrl(fileUrl, material.name).subscribe({
  377. next: (result) => {
  378. this.cadAnalysisResult = result;
  379. const analysis: MaterialAnalysis = {
  380. structuralElements: result.structuralElements,
  381. spaceMetrics: result.spaceMetrics,
  382. flowMetrics: result.flowMetrics
  383. };
  384. material.analysis = analysis;
  385. this.isAnalyzing = false;
  386. this.updateRequirementsFromAnalysis(analysis);
  387. },
  388. error: () => {
  389. this.cadAnalysisService.simulateCadAnalysis(material.name).subscribe({
  390. next: (mock) => {
  391. this.cadAnalysisResult = mock;
  392. const analysis: MaterialAnalysis = {
  393. structuralElements: mock.structuralElements,
  394. spaceMetrics: mock.spaceMetrics,
  395. flowMetrics: mock.flowMetrics
  396. };
  397. material.analysis = analysis;
  398. this.isAnalyzing = false;
  399. this.updateRequirementsFromAnalysis(analysis);
  400. },
  401. error: () => {
  402. this.isAnalyzing = false;
  403. console.error('CAD分析失败');
  404. }
  405. });
  406. }
  407. });
  408. return;
  409. }
  410. // 非CAD类型模拟
  411. setTimeout(() => {
  412. let analysis: MaterialAnalysis = {};
  413. switch (material.type) {
  414. case 'text':
  415. analysis = this.analyzeTextMaterial(material);
  416. break;
  417. case 'image':
  418. analysis = this.analyzeImageMaterial(material);
  419. break;
  420. }
  421. material.analysis = analysis;
  422. this.isAnalyzing = false;
  423. this.updateRequirementsFromAnalysis(analysis);
  424. }, 1200);
  425. }
  426. private analyzeTextMaterial(material: MaterialFile): MaterialAnalysis {
  427. return {
  428. atmosphere: {
  429. description: '温馨暖调',
  430. rgb: '255,230,180',
  431. colorTemp: '2700-3000K'
  432. },
  433. residents: {
  434. type: '亲子家庭',
  435. details: '孩子年龄3-6岁'
  436. },
  437. scenes: {
  438. preference: '瑜伽爱好者',
  439. requirements: '需要瑜伽区收纳'
  440. },
  441. keywords: {
  442. positive: ['科技感', '温馨', '实用'],
  443. negative: ['复杂线条', '冷色调']
  444. }
  445. };
  446. }
  447. private analyzeImageMaterial(material: MaterialFile): MaterialAnalysis {
  448. return {
  449. mainColors: [
  450. { rgb: '255,230,180', percentage: 45 },
  451. { rgb: '200,180,160', percentage: 30 },
  452. { rgb: '180,160,140', percentage: 25 }
  453. ],
  454. colorTemperature: '3000K',
  455. materialRatio: [
  456. { material: '木质', percentage: 60 },
  457. { material: '布艺', percentage: 25 },
  458. { material: '金属', percentage: 15 }
  459. ],
  460. spaceRatio: 35
  461. };
  462. }
  463. private analyzeCADMaterial(material: MaterialFile): MaterialAnalysis {
  464. return {
  465. structuralElements: [
  466. { type: '承重柱', position: '客厅中央', changeable: false },
  467. { type: '门窗', position: '南墙', changeable: false }
  468. ],
  469. spaceMetrics: [
  470. { room: '客厅', ratio: '16:9', width: '4.2m' },
  471. { room: '卧室', ratio: '4:3', width: '3.6m' }
  472. ],
  473. flowMetrics: [
  474. { area: '主通道', width: '1.2m', compliance: true },
  475. { area: '次通道', width: '0.8m', compliance: false }
  476. ]
  477. };
  478. }
  479. private updateRequirementsFromAnalysis(analysis: MaterialAnalysis) {
  480. if (analysis.atmosphere?.rgb) {
  481. const colorMetric = this.requirementMetrics.find(m => m.id === 'main-color');
  482. if (colorMetric) {
  483. const [r, g, b] = analysis.atmosphere.rgb.split(',').map(Number);
  484. colorMetric.value = { r, g, b };
  485. }
  486. }
  487. if (analysis.materialRatio) {
  488. const woodRatio = analysis.materialRatio.find(m => m.material === '木质');
  489. if (woodRatio) {
  490. const woodMetric = this.requirementMetrics.find(m => m.id === 'wood-ratio');
  491. if (woodMetric) {
  492. woodMetric.value = woodRatio.percentage;
  493. }
  494. }
  495. }
  496. }
  497. // 需求确认功能
  498. confirmRequirement(requirementId: string) {
  499. // 检查是否可以进行需求确认操作
  500. if (!this.canProceedToNextStage('materialAnalysis')) {
  501. alert('请先完成素材分析阶段的所有必要操作');
  502. return;
  503. }
  504. const requirement = this.requirementItems.find(r => r.id === requirementId);
  505. if (requirement) {
  506. requirement.status = 'confirmed';
  507. requirement.lastUpdated = new Date();
  508. this.requirementConfirmed.emit(requirement);
  509. this.updateProgress();
  510. this.triggerAutoSave();
  511. // 检查阶段完成状态
  512. this.checkStageCompletion();
  513. }
  514. }
  515. rejectRequirement(requirementId: string, reason?: string) {
  516. // 检查是否可以进行需求拒绝操作
  517. if (!this.canProceedToNextStage('materialAnalysis')) {
  518. alert('请先完成素材分析阶段的所有必要操作');
  519. return;
  520. }
  521. const requirement = this.requirementItems.find(r => r.id === requirementId);
  522. if (requirement) {
  523. requirement.status = 'rejected';
  524. requirement.lastUpdated = new Date();
  525. if (reason) {
  526. this.addCommentToRequirement(requirementId, reason, 'system');
  527. }
  528. this.updateProgress();
  529. this.triggerAutoSave();
  530. // 检查阶段完成状态
  531. this.checkStageCompletion();
  532. }
  533. }
  534. // 协作功能
  535. addComment() {
  536. if (this.commentForm.valid) {
  537. const comment: CollaborationComment = {
  538. id: this.generateId(),
  539. author: '当前用户',
  540. role: 'designer',
  541. content: this.commentForm.value.content,
  542. timestamp: new Date(),
  543. requirementId: this.commentForm.value.requirementId,
  544. status: 'pending'
  545. };
  546. this.collaborationComments.push(comment);
  547. this.commentForm.reset();
  548. this.triggerAutoSave();
  549. // 检查阶段完成状态
  550. this.checkStageCompletion();
  551. }
  552. }
  553. resolveComment(commentId: string) {
  554. const comment = this.collaborationComments.find(c => c.id === commentId);
  555. if (comment) {
  556. comment.status = 'resolved';
  557. this.triggerAutoSave();
  558. // 检查阶段完成状态
  559. this.checkStageCompletion();
  560. }
  561. }
  562. // 进度管理
  563. private updateProgress() {
  564. const totalRequirements = this.requirementItems.length;
  565. const confirmedRequirements = this.requirementItems.filter(r => r.status === 'confirmed').length;
  566. const progress = totalRequirements > 0 ? (confirmedRequirements / totalRequirements) * 100 : 0;
  567. // 实时更新进度条
  568. this.updateProgressBar(progress);
  569. this.progressUpdated.emit(progress);
  570. // 检查是否完成所有需求
  571. if (progress === 100) {
  572. this.onRequirementCommunicationComplete();
  573. }
  574. }
  575. private updateProgressBar(progress: number): void {
  576. // 更新进度条显示
  577. const progressBar = document.querySelector('.progress-bar-fill') as HTMLElement;
  578. if (progressBar) {
  579. progressBar.style.width = `${progress}%`;
  580. }
  581. // 更新进度文本
  582. const progressText = document.querySelector('.progress-text') as HTMLElement;
  583. if (progressText) {
  584. progressText.textContent = `${Math.round(progress)}%`;
  585. }
  586. // 添加进度动画效果
  587. this.animateProgressUpdate(progress);
  588. }
  589. private animateProgressUpdate(progress: number): void {
  590. // 添加进度更新的视觉反馈
  591. const progressContainer = document.querySelector('.progress-container') as HTMLElement;
  592. if (progressContainer) {
  593. progressContainer.classList.add('progress-updated');
  594. setTimeout(() => {
  595. progressContainer.classList.remove('progress-updated');
  596. }, 500);
  597. }
  598. }
  599. // 需求沟通阶段完成处理
  600. private onRequirementCommunicationComplete(): void {
  601. console.log('需求沟通阶段完成,开始同步关键信息');
  602. this.syncKeyInfoToSolutionConfirmation();
  603. }
  604. // 同步关键信息到方案确认阶段
  605. private syncKeyInfoToSolutionConfirmation(): void {
  606. const keyInfo = {
  607. colorAtmosphere: {
  608. mainColor: this.colorIndicators.mainColor,
  609. colorTemperature: this.colorIndicators.colorTemperature,
  610. saturation: this.colorIndicators.saturation,
  611. brightness: this.colorIndicators.brightness
  612. },
  613. spaceStructure: {
  614. lineRatio: this.spaceIndicators.lineRatio,
  615. blankRatio: this.spaceIndicators.blankRatio,
  616. flowWidth: this.spaceIndicators.flowWidth
  617. },
  618. materialWeights: {
  619. fabricRatio: this.materialIndicators.fabricRatio,
  620. woodRatio: this.materialIndicators.woodRatio,
  621. metalRatio: this.materialIndicators.metalRatio,
  622. smoothness: this.materialIndicators.smoothness
  623. },
  624. presetAtmosphere: this.getSelectedPresetAtmosphere()
  625. };
  626. // 触发同步事件
  627. this.requirementConfirmed.emit({
  628. id: 'requirement-sync',
  629. title: '需求沟通完成',
  630. description: '关键信息已同步至方案确认阶段',
  631. priority: 'high',
  632. status: 'confirmed',
  633. lastUpdated: new Date(),
  634. metrics: this.convertToMetrics(keyInfo)
  635. });
  636. // 启动交付执行流程
  637. setTimeout(() => {
  638. this.startDeliveryExecution();
  639. }, 1000);
  640. }
  641. private getSelectedPresetAtmosphere(): any {
  642. // 根据当前颜色指标找到最匹配的预设氛围
  643. const currentRgb = `${this.colorIndicators.mainColor.r},${this.colorIndicators.mainColor.g},${this.colorIndicators.mainColor.b}`;
  644. return this.presetAtmospheres.find(preset => preset.rgb === currentRgb) || this.presetAtmospheres[0];
  645. }
  646. private convertToMetrics(keyInfo: any): RequirementMetric[] {
  647. return [
  648. {
  649. id: 'color-sync',
  650. category: 'color',
  651. name: '色彩氛围',
  652. value: keyInfo.colorAtmosphere
  653. },
  654. {
  655. id: 'space-sync',
  656. category: 'space',
  657. name: '空间结构',
  658. value: keyInfo.spaceStructure
  659. },
  660. {
  661. id: 'material-sync',
  662. category: 'material',
  663. name: '材质权重',
  664. value: keyInfo.materialWeights
  665. }
  666. ];
  667. }
  668. // 启动交付执行流程
  669. private startDeliveryExecution(): void {
  670. console.log('启动交付执行流程');
  671. // 显示执行启动提示
  672. this.showExecutionStartNotification();
  673. // 这里可以触发路由跳转或其他业务逻辑
  674. // 例如:this.router.navigate(['/project', this.projectId, 'execution']);
  675. }
  676. private showExecutionStartNotification(): void {
  677. // 显示执行流程启动的通知
  678. const notification = document.createElement('div');
  679. notification.className = 'execution-notification';
  680. notification.innerHTML = `
  681. <div class="notification-content">
  682. <svg viewBox="0 0 24 24" fill="currentColor">
  683. <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
  684. </svg>
  685. <span>交付执行流程已启动</span>
  686. </div>
  687. `;
  688. document.body.appendChild(notification);
  689. setTimeout(() => {
  690. notification.remove();
  691. }, 3000);
  692. }
  693. getProgressPercentage(): number {
  694. if (this.requirementItems.length === 0) return 0;
  695. const confirmedCount = this.requirementItems.filter(r => r.status === 'confirmed').length;
  696. return Math.round((confirmedCount / this.requirementItems.length) * 100);
  697. }
  698. // 处理优先级更新
  699. onPriorityChange(requirementId: string, event: Event): void {
  700. const target = event.target as HTMLSelectElement;
  701. this.updateRequirementPriority(requirementId, target.value as 'high' | 'medium' | 'low');
  702. }
  703. // 检查需求是否有待处理评论
  704. hasUnreadComments(requirementId: string): boolean {
  705. return this.getCommentsForRequirement(requirementId).some(c => c.status === 'pending');
  706. }
  707. // 处理历史状态选择
  708. onHistoryStateChange(event: Event): void {
  709. const target = event.target as HTMLSelectElement;
  710. const index = +target.value;
  711. if (index >= 0) {
  712. this.restoreHistoryState(index);
  713. }
  714. }
  715. // 获取指定状态的需求数量
  716. getRequirementCountByStatus(status: 'confirmed' | 'pending' | 'rejected'): number {
  717. return (this.requirementItems || []).filter(r => r.status === status).length;
  718. }
  719. // 获取状态百分比
  720. getStatusPercentage(status: 'confirmed' | 'pending' | 'rejected'): number {
  721. const total = this.requirementItems.length;
  722. if (total === 0) return 0;
  723. const statusCount = this.getRequirementCountByStatus(status);
  724. return Math.round((statusCount / total) * 100);
  725. }
  726. // 指标映射功能
  727. updateMetricValue(metricId: string, value: any) {
  728. const metric = this.requirementMetrics.find(m => m.id === metricId);
  729. if (metric) {
  730. metric.value = value;
  731. this.checkConsistency();
  732. }
  733. }
  734. // 滑动条数值同步方法
  735. onSliderChange(key: string, value: number): void {
  736. console.log(`滑动条变化: ${key} = ${value}`);
  737. console.log('变化前的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  738. // 直接更新数据,不需要额外的updateIndicatorValue调用
  739. // 因为使用了双向绑定,数据已经自动更新
  740. if (key === 'r' || key === 'g' || key === 'b') {
  741. // 确保RGB值在有效范围内
  742. const range = this.getIndicatorRange(key);
  743. if (range) {
  744. const clampedValue = Math.max(range.min, Math.min(range.max, value));
  745. this.colorIndicators.mainColor[key as keyof typeof this.colorIndicators.mainColor] = clampedValue;
  746. console.log(`RGB值已更新: ${key} = ${clampedValue}`);
  747. console.log('变化后的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  748. }
  749. // 触发颜色指标更新
  750. this.updateColorIndicator('mainColor', this.colorIndicators.mainColor);
  751. } else {
  752. // 处理其他颜色指标
  753. this.updateIndicatorValue(key, value);
  754. }
  755. this.triggerAutoSave(); // 触发自动保存
  756. this.checkStageCompletion(); // 检查阶段完成状态
  757. // 发射实时数据更新事件
  758. this.emitDataUpdate();
  759. // 强制触发变更检测
  760. this.cdr.detectChanges();
  761. console.log('滑动条变更检测已触发');
  762. }
  763. onInputChange(key: string, value: number): void {
  764. console.log(`输入框变化: ${key} = ${value}`);
  765. console.log('变化前的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  766. // 直接更新数据,不需要额外的updateIndicatorValue调用
  767. // 因为使用了双向绑定,数据已经自动更新
  768. if (key === 'r' || key === 'g' || key === 'b') {
  769. // 确保RGB值在有效范围内
  770. const range = this.getIndicatorRange(key);
  771. if (range) {
  772. const clampedValue = Math.max(range.min, Math.min(range.max, value));
  773. this.colorIndicators.mainColor[key as keyof typeof this.colorIndicators.mainColor] = clampedValue;
  774. console.log(`RGB值已更新: ${key} = ${clampedValue}`);
  775. console.log('变化后的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  776. }
  777. // 触发颜色指标更新
  778. this.updateColorIndicator('mainColor', this.colorIndicators.mainColor);
  779. } else {
  780. // 处理其他颜色指标
  781. this.updateIndicatorValue(key, value);
  782. }
  783. this.triggerAutoSave();
  784. // 发射实时数据更新事件
  785. this.emitDataUpdate();
  786. // 强制触发变更检测
  787. this.cdr.detectChanges();
  788. console.log('输入框变更检测已触发');
  789. }
  790. validateInput(key: string, value: string): void {
  791. const numValue = parseFloat(value);
  792. if (isNaN(numValue)) {
  793. // 如果输入无效,恢复原值
  794. this.restoreIndicatorValue(key);
  795. return;
  796. }
  797. const range = this.getIndicatorRange(key);
  798. if (range) {
  799. const clampedValue = Math.max(range.min, Math.min(range.max, numValue));
  800. this.updateIndicatorValue(key, clampedValue);
  801. }
  802. }
  803. private updateIndicatorValue(key: string, value: number): void {
  804. console.log(`updateIndicatorValue调用: ${key} = ${value}`);
  805. // 更新颜色指标
  806. if (key in this.colorIndicators) {
  807. if (key === 'r' || key === 'g' || key === 'b') {
  808. // 创建新的mainColor对象以确保变更检测
  809. const oldColor = { ...this.colorIndicators.mainColor };
  810. this.colorIndicators.mainColor = {
  811. ...this.colorIndicators.mainColor,
  812. [key]: value
  813. };
  814. console.log(`RGB更新: ${key}从${oldColor[key as keyof typeof oldColor]}变为${value}`,
  815. '新mainColor:', this.colorIndicators.mainColor);
  816. this.updateColorIndicator('mainColor', this.colorIndicators.mainColor);
  817. } else {
  818. (this.colorIndicators as any)[key] = value;
  819. this.updateColorIndicator(key, value);
  820. }
  821. return;
  822. }
  823. // 更新空间指标
  824. if (key in this.spaceIndicators) {
  825. (this.spaceIndicators as any)[key] = value;
  826. this.updateSpaceIndicator(key, value);
  827. return;
  828. }
  829. // 更新材质指标
  830. if (key in this.materialIndicators) {
  831. (this.materialIndicators as any)[key] = value;
  832. this.updateMaterialIndicator(key, value);
  833. return;
  834. }
  835. }
  836. private restoreIndicatorValue(key: string): void {
  837. // 这里可以从历史状态或默认值恢复
  838. console.log(`恢复指标值: ${key}`);
  839. }
  840. private getIndicatorRange(key: string): { min: number; max: number } | null {
  841. // 检查颜色范围
  842. if (key === 'r' || key === 'g' || key === 'b') {
  843. return this.indicatorRanges.color[key as keyof typeof this.indicatorRanges.color];
  844. }
  845. if (key in this.indicatorRanges.color) {
  846. return (this.indicatorRanges.color as any)[key];
  847. }
  848. // 检查空间范围
  849. if (key in this.indicatorRanges.space) {
  850. return (this.indicatorRanges.space as any)[key];
  851. }
  852. // 检查材质范围
  853. if (key in this.indicatorRanges.material) {
  854. return (this.indicatorRanges.material as any)[key];
  855. }
  856. return null;
  857. }
  858. // 指标更新方法
  859. updateColorIndicator(type: string, value?: any): void {
  860. switch (type) {
  861. case 'mainColor':
  862. if (value && typeof value === 'object' && 'r' in value) {
  863. this.colorIndicators.mainColor = { ...value }; // 创建新对象以触发变更检测
  864. console.log('mainColor更新后:', this.colorIndicators.mainColor);
  865. }
  866. break;
  867. case 'colorTemperature':
  868. // 色温更新时不需要改变颜色值,只是触发一致性检查
  869. break;
  870. case 'saturation':
  871. // 饱和度更新时不需要改变颜色值,只是触发一致性检查
  872. break;
  873. }
  874. console.log(`更新颜色指示器 ${type}:`, value, '当前RGB:', this.getRgbString());
  875. this.checkConsistency();
  876. this.updatePreview();
  877. // 强制触发变更检测
  878. this.cdr.detectChanges();
  879. console.log('变更检测已触发');
  880. }
  881. updateSpaceIndicator(key: string, value: number) {
  882. if (key in this.spaceIndicators) {
  883. (this.spaceIndicators as any)[key] = value;
  884. this.checkConsistency();
  885. }
  886. }
  887. updateMaterialIndicator(key: string, value: number) {
  888. if (key in this.materialIndicators) {
  889. (this.materialIndicators as any)[key] = value;
  890. this.checkConsistency();
  891. this.normalizeMaterialRatios();
  892. }
  893. }
  894. // 材质比例归一化
  895. private normalizeMaterialRatios() {
  896. const total = this.materialIndicators.fabricRatio +
  897. this.materialIndicators.woodRatio +
  898. this.materialIndicators.metalRatio;
  899. if (total > 100) {
  900. const scale = 100 / total;
  901. this.materialIndicators.fabricRatio = Math.round(this.materialIndicators.fabricRatio * scale);
  902. this.materialIndicators.woodRatio = Math.round(this.materialIndicators.woodRatio * scale);
  903. this.materialIndicators.metalRatio = 100 - this.materialIndicators.fabricRatio - this.materialIndicators.woodRatio;
  904. }
  905. }
  906. // 预览更新
  907. private updatePreview() {
  908. // 移除直接DOM操作,依赖Angular的属性绑定
  909. console.log('updatePreview调用,当前RGB:', this.getRgbString());
  910. // 不再直接操作DOM,让Angular的变更检测处理
  911. }
  912. // 获取RGB字符串
  913. getRgbString(): string {
  914. const { r, g, b } = this.colorIndicators.mainColor;
  915. const rgbString = `rgb(${r}, ${g}, ${b})`;
  916. console.log('getRgbString调用:', rgbString, '完整mainColor对象:', this.colorIndicators.mainColor);
  917. return rgbString;
  918. }
  919. // 获取色温描述
  920. getColorTemperatureDescription(): string {
  921. const temp = this.colorIndicators.colorTemperature;
  922. if (temp < 3000) return '暖色调';
  923. if (temp < 4000) return '中性色调';
  924. if (temp < 5000) return '自然色调';
  925. return '冷色调';
  926. }
  927. applyPresetAtmosphere(preset: any) {
  928. const rgbMatch = preset.rgb.match(/(\d+),(\d+),(\d+)/);
  929. if (rgbMatch) {
  930. this.colorIndicators.mainColor = {
  931. r: parseInt(rgbMatch[1]),
  932. g: parseInt(rgbMatch[2]),
  933. b: parseInt(rgbMatch[3])
  934. };
  935. }
  936. const tempMatch = preset.colorTemp.match(/(\d+)/);
  937. if (tempMatch) {
  938. this.colorIndicators.colorTemperature = parseInt(tempMatch[1]);
  939. }
  940. if (preset.materials.includes('木质')) {
  941. this.materialIndicators.woodRatio = 60;
  942. this.materialIndicators.fabricRatio = 30;
  943. this.materialIndicators.metalRatio = 10;
  944. } else if (preset.materials.includes('金属')) {
  945. this.materialIndicators.metalRatio = 50;
  946. this.materialIndicators.woodRatio = 20;
  947. this.materialIndicators.fabricRatio = 30;
  948. }
  949. this.updatePreview();
  950. this.checkConsistency();
  951. }
  952. // 一致性检查
  953. private checkConsistency() {
  954. this.consistencyWarnings = [];
  955. if (this.colorIndicators.colorTemperature < 3000 &&
  956. this.colorIndicators.mainColor.r > 200 &&
  957. this.colorIndicators.mainColor.g < 150) {
  958. this.consistencyWarnings.push('暖调氛围与冷色调RGB值存在矛盾');
  959. }
  960. if (this.materialIndicators.fabricRatio > 70 && this.colorIndicators.colorTemperature > 5000) {
  961. this.consistencyWarnings.push('高布艺占比与冷色调可能不协调');
  962. }
  963. if (this.spaceIndicators.lineRatio > 80 && this.materialIndicators.woodRatio > 60) {
  964. this.consistencyWarnings.push('高直线条占比与高木质占比可能过于刚硬');
  965. }
  966. }
  967. // 协作批注功能
  968. addCommentToRequirement(requirementId: string, content: string, author: string = '当前用户'): void {
  969. const comment: CollaborationComment = {
  970. id: this.generateId(),
  971. author,
  972. role: 'designer',
  973. content,
  974. timestamp: new Date(),
  975. requirementId,
  976. status: 'pending'
  977. };
  978. this.collaborationComments.push(comment);
  979. this.updateProgress();
  980. }
  981. // 优先级排序功能
  982. updateRequirementPriority(requirementId: string, priority: 'high' | 'medium' | 'low'): void {
  983. const requirement = this.requirementItems.find(r => r.id === requirementId);
  984. if (requirement) {
  985. requirement.priority = priority;
  986. requirement.lastUpdated = new Date();
  987. this.sortRequirementsByPriority();
  988. }
  989. }
  990. sortRequirementsByPriority(): void {
  991. const priorityOrder = { 'high': 3, 'medium': 2, 'low': 1 };
  992. this.requirementItems.sort((a, b) => {
  993. return priorityOrder[b.priority] - priorityOrder[a.priority];
  994. });
  995. }
  996. // 历史记录功能
  997. saveCurrentState(): void {
  998. const currentState = {
  999. timestamp: new Date(),
  1000. colorIndicators: { ...this.colorIndicators },
  1001. spaceIndicators: { ...this.spaceIndicators },
  1002. materialIndicators: { ...this.materialIndicators },
  1003. requirementItems: this.requirementItems.map((r: RequirementItem) => ({ ...r })),
  1004. author: '当前用户'
  1005. };
  1006. this.historyStates.push(currentState);
  1007. if (this.historyStates.length > 10) {
  1008. this.historyStates.shift();
  1009. }
  1010. }
  1011. restoreHistoryState(index: number): void {
  1012. if (index >= 0 && index < this.historyStates.length) {
  1013. const state = this.historyStates[index];
  1014. this.colorIndicators = { ...state.colorIndicators };
  1015. this.spaceIndicators = { ...state.spaceIndicators };
  1016. this.materialIndicators = { ...state.materialIndicators };
  1017. this.requirementItems = state.requirementItems.map((r: RequirementItem) => ({ ...r }));
  1018. this.updatePreview();
  1019. this.checkConsistency();
  1020. }
  1021. }
  1022. // 获取未解决的评论数量
  1023. getUnresolvedCommentsCount(): number {
  1024. return this.collaborationComments.filter(c => c.status === 'pending').length;
  1025. }
  1026. // 获取需求的评论
  1027. getCommentsForRequirement(requirementId: string): CollaborationComment[] {
  1028. return this.collaborationComments.filter(comment => comment.requirementId === requirementId) || [];
  1029. }
  1030. // 获取状态样式类
  1031. getStatusClass(status: string): string {
  1032. return status;
  1033. }
  1034. // 工具方法
  1035. private generateId(): string {
  1036. return Math.random().toString(36).substr(2, 9);
  1037. }
  1038. private formatFileSize(bytes: number): string {
  1039. if (bytes === 0) return '0 Bytes';
  1040. const k = 1024;
  1041. const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  1042. const i = Math.floor(Math.log(bytes) / Math.log(k));
  1043. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  1044. }
  1045. // 删除素材
  1046. removeMaterial(materialId: string) {
  1047. const index = this.materialFiles.findIndex(m => m.id === materialId);
  1048. if (index > -1) {
  1049. const material = this.materialFiles[index];
  1050. if (material.url) {
  1051. URL.revokeObjectURL(material.url);
  1052. }
  1053. this.materialFiles.splice(index, 1);
  1054. }
  1055. const materialsIndex = this.materials.findIndex(m => m.id === materialId);
  1056. if (materialsIndex > -1) {
  1057. this.materials.splice(materialsIndex, 1);
  1058. }
  1059. }
  1060. // 切换标签页
  1061. switchTab(tab: 'materials' | 'mapping' | 'collaboration' | 'progress') {
  1062. this.activeTab = tab;
  1063. }
  1064. // 获取需求状态文本
  1065. getRequirementStatusText(status: string): string {
  1066. const statusMap: { [key: string]: string } = {
  1067. 'pending': '待确认',
  1068. 'confirmed': '已确认',
  1069. 'rejected': '已拒绝'
  1070. };
  1071. return statusMap[status] || status;
  1072. }
  1073. // 获取优先级文本
  1074. getPriorityText(priority: string): string {
  1075. const priorityMap: { [key: string]: string } = {
  1076. 'high': '高',
  1077. 'medium': '中',
  1078. 'low': '低'
  1079. };
  1080. return priorityMap[priority] || priority;
  1081. }
  1082. // 刷新进度(保留用于手动刷新,但不再强制要求)
  1083. refreshProgress(): void {
  1084. // 重新计算进度
  1085. this.updateProgress();
  1086. // 更新进度条显示
  1087. const progress = this.getProgressPercentage();
  1088. this.updateProgressBar(progress);
  1089. // 检查阶段完成状态
  1090. this.checkStageCompletion();
  1091. // 触发进度更新事件
  1092. this.progressUpdated.emit(progress);
  1093. console.log('进度已手动刷新:', progress + '%');
  1094. }
  1095. // 自动保存功能
  1096. private triggerAutoSave(): void {
  1097. if (!this.autoSaveEnabled) return;
  1098. this.hasUnsavedChanges = true;
  1099. this.saveStatus = 'unsaved';
  1100. // 清除之前的定时器
  1101. if (this.autoSaveTimer) {
  1102. clearTimeout(this.autoSaveTimer);
  1103. }
  1104. // 设置新的自动保存定时器(延迟1秒)
  1105. this.autoSaveTimer = setTimeout(() => {
  1106. this.performAutoSave();
  1107. }, 1000);
  1108. }
  1109. private async performAutoSave(): Promise<void> {
  1110. if (this.isSaving) return;
  1111. this.isSaving = true;
  1112. this.saveStatus = 'saving';
  1113. try {
  1114. // 收集所有需要保存的数据
  1115. const saveData = this.collectSaveData();
  1116. // 模拟保存操作(实际项目中这里会调用API)
  1117. await this.saveToServer(saveData);
  1118. this.hasUnsavedChanges = false;
  1119. this.saveStatus = 'saved';
  1120. this.lastSaveTime = new Date();
  1121. console.log('自动保存成功:', new Date().toLocaleTimeString());
  1122. } catch (error) {
  1123. this.saveStatus = 'error';
  1124. console.error('自动保存失败:', error);
  1125. } finally {
  1126. this.isSaving = false;
  1127. }
  1128. }
  1129. // 手动保存
  1130. async manualSave(): Promise<void> {
  1131. if (this.isSaving) return;
  1132. // 清除自动保存定时器
  1133. if (this.autoSaveTimer) {
  1134. clearTimeout(this.autoSaveTimer);
  1135. }
  1136. await this.performAutoSave();
  1137. }
  1138. private collectSaveData(): any {
  1139. return {
  1140. projectId: this.projectId,
  1141. colorIndicators: this.colorIndicators,
  1142. spaceIndicators: this.spaceIndicators,
  1143. materialIndicators: this.materialIndicators,
  1144. requirementItems: this.requirementItems,
  1145. requirementMetrics: this.requirementMetrics,
  1146. materialFiles: this.materialFiles,
  1147. collaborationComments: this.collaborationComments,
  1148. stageCompletionStatus: this.stageCompletionStatus,
  1149. lastUpdated: new Date()
  1150. };
  1151. }
  1152. private async saveToServer(data: any): Promise<void> {
  1153. // 模拟API调用延迟
  1154. return new Promise((resolve, reject) => {
  1155. setTimeout(() => {
  1156. // 模拟90%成功率
  1157. if (Math.random() > 0.1) {
  1158. resolve();
  1159. } else {
  1160. reject(new Error('网络错误'));
  1161. }
  1162. }, 500);
  1163. });
  1164. }
  1165. // 检查阶段完成状态
  1166. private checkStageCompletion(): void {
  1167. // 检查素材分析阶段 - 需要有素材文件且都已分析
  1168. this.stageCompletionStatus.materialAnalysis = this.materialFiles.length > 0 &&
  1169. this.materialFiles.every(m => m.analysis);
  1170. // 检查需求映射阶段 - 需要有确认的需求项,或者滑动条数据已调整且保存
  1171. const hasConfirmedRequirements = this.requirementItems.length > 0 &&
  1172. this.requirementItems.some(r => r.status === 'confirmed');
  1173. const hasAdjustedIndicators = this.hasIndicatorChanges();
  1174. this.stageCompletionStatus.requirementMapping = hasConfirmedRequirements ||
  1175. (hasAdjustedIndicators && this.saveStatus === 'saved');
  1176. // 检查协作验证阶段 - 需要有协作评论或需求评论
  1177. this.stageCompletionStatus.collaboration = this.collaborationComments.length > 0 ||
  1178. this.requirementItems.some(r => r.comments && r.comments.length > 0);
  1179. // 检查进度审查阶段 - 需要进度达到80%以上
  1180. this.stageCompletionStatus.progressReview = this.getProgressPercentage() >= 80;
  1181. console.log('阶段完成状态更新:', this.stageCompletionStatus);
  1182. // 检查是否所有阶段都已完成
  1183. const allStagesCompleted = Object.values(this.stageCompletionStatus).every(status => status);
  1184. // 发射阶段完成事件
  1185. if (allStagesCompleted) {
  1186. this.stageCompleted.emit({ stage: 'requirements-communication', allStagesCompleted: true });
  1187. }
  1188. }
  1189. // 检查指示器是否有变化
  1190. private hasIndicatorChanges(): boolean {
  1191. // 检查颜色指示器是否有变化(与默认值比较)
  1192. const defaultColorIndicators = {
  1193. mainColor: { r: 255, g: 230, b: 180 },
  1194. colorTemperature: 2700,
  1195. colorRange: '暖色调',
  1196. saturation: 70,
  1197. brightness: 80,
  1198. contrast: 60
  1199. };
  1200. const defaultSpaceIndicators = {
  1201. lineRatio: 60,
  1202. blankRatio: 30,
  1203. flowWidth: 0.9,
  1204. aspectRatio: 1.6,
  1205. ceilingHeight: 2.8,
  1206. lightingLevel: 300
  1207. };
  1208. const defaultMaterialIndicators = {
  1209. fabricRatio: 50,
  1210. woodRatio: 30,
  1211. metalRatio: 20,
  1212. smoothness: 7,
  1213. glossiness: 4,
  1214. texture: 6
  1215. };
  1216. // 检查颜色指示器变化
  1217. const colorChanged = JSON.stringify(this.colorIndicators) !== JSON.stringify(defaultColorIndicators);
  1218. // 检查空间指示器变化
  1219. const spaceChanged = JSON.stringify(this.spaceIndicators) !== JSON.stringify(defaultSpaceIndicators);
  1220. // 检查材质指示器变化
  1221. const materialChanged = JSON.stringify(this.materialIndicators) !== JSON.stringify(defaultMaterialIndicators);
  1222. return colorChanged || spaceChanged || materialChanged;
  1223. }
  1224. // 获取阶段状态文本
  1225. getStageStatusText(stage: keyof typeof this.stageCompletionStatus): string {
  1226. if (this.stageCompletionStatus[stage]) {
  1227. return '已完成';
  1228. } else {
  1229. // 检查是否为未开始状态
  1230. const stages = ['materialAnalysis', 'requirementMapping', 'collaboration', 'progressReview'];
  1231. const currentIndex = stages.indexOf(stage);
  1232. // 检查前面的阶段是否都已完成
  1233. let allPreviousCompleted = true;
  1234. for (let i = 0; i < currentIndex; i++) {
  1235. if (!this.stageCompletionStatus[stages[i] as keyof typeof this.stageCompletionStatus]) {
  1236. allPreviousCompleted = false;
  1237. break;
  1238. }
  1239. }
  1240. return allPreviousCompleted ? '进行中' : '未进行';
  1241. }
  1242. }
  1243. // 获取阶段状态类名
  1244. getStageStatusClass(stage: keyof typeof this.stageCompletionStatus): string {
  1245. if (this.stageCompletionStatus[stage]) {
  1246. return 'stage-completed';
  1247. } else {
  1248. // 检查是否为未开始状态
  1249. const stages = ['materialAnalysis', 'requirementMapping', 'collaboration', 'progressReview'];
  1250. const currentIndex = stages.indexOf(stage);
  1251. // 检查前面的阶段是否都已完成
  1252. let allPreviousCompleted = true;
  1253. for (let i = 0; i < currentIndex; i++) {
  1254. if (!this.stageCompletionStatus[stages[i] as keyof typeof this.stageCompletionStatus]) {
  1255. allPreviousCompleted = false;
  1256. break;
  1257. }
  1258. }
  1259. return allPreviousCompleted ? 'stage-in-progress' : 'stage-pending';
  1260. }
  1261. }
  1262. // 检查是否可以进入下一阶段
  1263. canProceedToNextStage(currentStage: keyof typeof this.stageCompletionStatus): boolean {
  1264. const stages = Object.keys(this.stageCompletionStatus) as (keyof typeof this.stageCompletionStatus)[];
  1265. const currentIndex = stages.indexOf(currentStage);
  1266. // 检查当前阶段之前的所有阶段是否都已完成
  1267. for (let i = 0; i <= currentIndex; i++) {
  1268. if (!this.stageCompletionStatus[stages[i]]) {
  1269. return false;
  1270. }
  1271. }
  1272. return true;
  1273. }
  1274. // 获取保存状态文本
  1275. getSaveStatusText(): string {
  1276. switch (this.saveStatus) {
  1277. case 'saved': return this.lastSaveTime ? `已保存 ${this.lastSaveTime.toLocaleTimeString()}` : '已保存';
  1278. case 'saving': return '保存中...';
  1279. case 'error': return '保存失败';
  1280. case 'unsaved': return '有未保存的更改';
  1281. default: return '';
  1282. }
  1283. }
  1284. // 获取保存状态图标
  1285. getSaveStatusIcon(): string {
  1286. switch (this.saveStatus) {
  1287. case 'saved': return '✓';
  1288. case 'saving': return '⏳';
  1289. case 'error': return '⚠';
  1290. case 'unsaved': return '●';
  1291. default: return '';
  1292. }
  1293. }
  1294. // 上传成功弹窗相关方法
  1295. onModalClose(): void {
  1296. this.showUploadSuccessModal = false;
  1297. this.uploadedFiles = [];
  1298. this.colorAnalysisResult = undefined;
  1299. }
  1300. // 全局提示关闭
  1301. onPromptClose(): void {
  1302. this.showGlobalPrompt = false;
  1303. }
  1304. onAnalyzeColors(): void {
  1305. if (this.uploadedFiles.length > 0 && this.uploadType === 'image') {
  1306. const imageFile = this.uploadedFiles[0];
  1307. // 创建一个File对象用于分析
  1308. const file = new File([], imageFile.name, { type: imageFile.type || 'image/jpeg' });
  1309. // 使用模拟分析(在实际应用中应该调用真实的API)
  1310. this.colorAnalysisService.simulateAnalysis(file).subscribe({
  1311. next: (result) => {
  1312. this.colorAnalysisResult = result;
  1313. // 可以在这里更新颜色指标
  1314. if (result.colors.length > 0) {
  1315. const mainColor = result.colors[0];
  1316. this.updateColorIndicator('mainColor', mainColor.rgb);
  1317. }
  1318. // 新增:分析完成后向父级发射数据更新,包含色彩分析结果
  1319. this.emitDataUpdate();
  1320. },
  1321. error: (error) => {
  1322. console.error('颜色分析失败:', error);
  1323. }
  1324. });
  1325. }
  1326. }
  1327. onViewReport(): void {
  1328. // 打开全屏报告覆盖层
  1329. this.showFullReportOverlay = true;
  1330. }
  1331. onCloseFullReport(): void {
  1332. this.showFullReportOverlay = false;
  1333. }
  1334. // 新增:发射实时数据更新事件的方法
  1335. private emitDataUpdate(): void {
  1336. const currentData = {
  1337. colorIndicators: this.colorIndicators || [],
  1338. spaceIndicators: this.spaceIndicators || [],
  1339. materialIndicators: this.materialIndicators || [],
  1340. requirementItems: this.requirementItems || [],
  1341. materials: this.materials || [],
  1342. collaborationComments: this.collaborationComments || '',
  1343. stageCompletionStatus: this.stageCompletionStatus || {},
  1344. // 新增:传递色彩分析结果到父级用于右侧展示
  1345. colorAnalysisResult: this.colorAnalysisResult
  1346. };
  1347. this.dataUpdated.emit(currentData);
  1348. console.log('实时数据更新事件已发射:', currentData);
  1349. }
  1350. // 新增:图片与CAD文件预览方法
  1351. previewImage(url?: string): void {
  1352. if (!url) { return; }
  1353. try {
  1354. window.open(url, '_blank');
  1355. } catch (e) {
  1356. console.error('预览图片失败:', e);
  1357. }
  1358. }
  1359. previewCad(url?: string): void {
  1360. if (!url) { return; }
  1361. try {
  1362. window.open(url, '_blank');
  1363. } catch (e) {
  1364. console.error('预览CAD失败:', e);
  1365. }
  1366. }
  1367. }