requirements-confirm-card.ts 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086
  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 { Subscription } from 'rxjs';
  5. import { UploadSuccessModalComponent } from '../upload-success-modal/upload-success-modal.component';
  6. import { GlobalPromptComponent } from '../global-prompt/global-prompt.component';
  7. import { ColorAnalysisService, ColorAnalysisResult } from '../../services/color-analysis.service';
  8. import { FullReportOverlayComponent } from '../full-report-overlay/full-report-overlay.component';
  9. import { CadAnalysisService, CadAnalysisResult } from '../../services/cad-analysis.service';
  10. import { RequirementMappingService } from '../../../services/requirement-mapping.service';
  11. import { RequirementMapping, SceneTemplate } from '../../../models/requirement-mapping.interface';
  12. // 素材文件接口
  13. interface MaterialFile {
  14. id: string;
  15. name: string;
  16. type: 'text' | 'image' | 'cad';
  17. url?: string;
  18. content?: string;
  19. size?: string;
  20. uploadTime: Date;
  21. analysis?: MaterialAnalysis;
  22. }
  23. // 素材解析结果接口
  24. interface MaterialAnalysis {
  25. // 文本类解析
  26. atmosphere?: { description: string; rgb?: string; colorTemp?: string };
  27. residents?: { type: string; details: string };
  28. scenes?: { preference: string; requirements: string };
  29. keywords?: { positive: string[]; negative: string[] };
  30. // 图片类解析
  31. mainColors?: { rgb: string; percentage: number }[];
  32. colorTemperature?: string;
  33. materialRatio?: { material: string; percentage: number }[];
  34. spaceRatio?: number;
  35. // CAD类解析
  36. structuralElements?: { type: string; position: string; changeable: boolean }[];
  37. spaceMetrics?: { room: string; ratio: string; width: string }[];
  38. flowMetrics?: { area: string; width: string; compliance: boolean }[];
  39. // 增强色彩分析
  40. enhancedColorAnalysis?: {
  41. colorWheel?: {
  42. primaryHue: number;
  43. saturation: number;
  44. brightness: number;
  45. dominantColors: Array<{ hue: number; saturation: number; brightness: number; percentage: number }>;
  46. colorDistribution: string;
  47. };
  48. colorHarmony?: {
  49. harmonyType: string;
  50. harmonyScore: number;
  51. complementaryColors: string[];
  52. suggestions: string[];
  53. };
  54. colorTemperatureAnalysis?: {
  55. kelvin: number;
  56. warmCoolBalance: number;
  57. description: string;
  58. lightingRecommendations: string[];
  59. };
  60. colorPsychology?: {
  61. primaryMood: string;
  62. atmosphere: string;
  63. psychologicalEffects: string[];
  64. suitableSpaces: string[];
  65. };
  66. };
  67. // 形体分析
  68. formAnalysis?: {
  69. lineAnalysis?: {
  70. dominantLines: Array<{ type: string; percentage: number; characteristics: string[] }>;
  71. lineQuality: { smoothness: number; precision: number; expressiveness: number };
  72. visualFlow: { direction: string; rhythm: string; continuity: number };
  73. };
  74. geometryAnalysis?: {
  75. primaryShapes: Array<{ shape: string; percentage: number; characteristics: string[] }>;
  76. complexity: string;
  77. symmetry: { type: string; score: number };
  78. balance: { visual: number; compositional: number };
  79. };
  80. proportionAnalysis?: {
  81. aspectRatio: number;
  82. goldenRatio: number;
  83. proportionHarmony: number;
  84. scaleRelationships: Array<{ element: string; scale: string; relationship: string }>;
  85. };
  86. overallAssessment?: {
  87. formComplexity: number;
  88. visualImpact: number;
  89. functionalSuitability: number;
  90. aestheticAppeal: number;
  91. };
  92. };
  93. // 质感分析
  94. textureAnalysis?: {
  95. surfaceProperties?: {
  96. roughness: { level: string; value: number; description: string };
  97. glossiness: { level: string; value: number; reflectivity: number };
  98. transparency: { level: string; value: number };
  99. porosity: { level: string; value: number };
  100. };
  101. tactilePredict?: {
  102. temperature: { perceived: string; thermalConductivity: number };
  103. hardness: { level: string; value: number };
  104. flexibility: { level: string; value: number };
  105. weight: { perceived: string; density: number };
  106. comfort: { tactileComfort: number; ergonomicSuitability: number };
  107. };
  108. materialClassification?: {
  109. primaryMaterial: { category: string; confidence: number; subcategory?: string };
  110. secondaryMaterials: Array<{ category: string; percentage: number; confidence: number }>;
  111. materialProperties: { durability: number; maintenance: string; sustainability: number; costLevel: string };
  112. };
  113. textureQuality?: {
  114. overallQuality: number;
  115. consistency: number;
  116. authenticity: number;
  117. visualAppeal: number;
  118. functionalSuitability: number;
  119. ageingCharacteristics: { wearResistance: number; patinaPotential: number; maintenanceNeeds: string[] };
  120. };
  121. };
  122. // 纹理图案分析
  123. patternAnalysis?: {
  124. patternRecognition?: {
  125. primaryPatterns: Array<{ type: string; confidence: number; coverage: number; characteristics: string[] }>;
  126. patternComplexity: { level: string; score: number; elements: number };
  127. patternScale: { size: string; uniformity: number; variation: number };
  128. };
  129. repetitionAnalysis?: {
  130. repetitionType: { primary: string; pattern: string; consistency: number };
  131. spacing: { horizontal: number; vertical: number; uniformity: number; rhythm: string };
  132. symmetry: { type: string; strength: number; axes: number };
  133. tiling: { seamless: boolean; quality: number; edgeHandling: string };
  134. };
  135. textureClassification?: {
  136. textureFamily: { primary: string; subcategory: string; confidence: number };
  137. surfaceCharacter: { tactileQuality: string; visualDepth: number; dimensionality: string };
  138. materialSuggestion: { likelyMaterials: string[]; fabricationMethod: string[]; applicationSuitability: string[] };
  139. };
  140. visualRhythm?: {
  141. rhythmType: { primary: string; intensity: number; tempo: string };
  142. movement: { direction: string; flow: number; energy: number };
  143. emphasis: { focalPoints: number; contrast: number; hierarchy: number };
  144. harmony: { overall: number; balance: number; unity: number };
  145. };
  146. };
  147. // 灯光分析
  148. lightingAnalysis?: {
  149. lightSourceIdentification?: {
  150. primarySources: Array<{
  151. type: string;
  152. subtype: string;
  153. position: { direction: string; angle: number; distance: string };
  154. intensity: number;
  155. confidence: number;
  156. }>;
  157. lightingSetup: { complexity: string; sourceCount: number; dominantSource: string; lightingStyle: string };
  158. };
  159. illuminationAnalysis?: {
  160. brightness: { overall: number; distribution: string; dynamicRange: number; exposure: string };
  161. contrast: { level: number; type: string; areas: { highlights: number; midtones: number; shadows: number } };
  162. colorTemperature: { kelvin: number; warmth: string; consistency: number; mixedLighting: boolean };
  163. lightQuality: { softness: number; diffusion: number; directionality: number; evenness: number };
  164. };
  165. shadowAnalysis?: {
  166. shadowPresence: { coverage: number; intensity: number; sharpness: string; definition: number };
  167. shadowCharacteristics: { direction: string; length: string; density: number; falloff: string };
  168. shadowTypes: Array<{ type: 'cast' | 'form' | 'occlusion' | 'contact'; prominence: number; contribution: string }>;
  169. dimensionalEffect: { depth: number; volume: number; threedimensionality: number };
  170. };
  171. ambientAnalysis?: {
  172. ambientLevel: { strength: number; uniformity: number; contribution: number };
  173. lightingMood: { primary: string; intensity: number; emotional_impact: string[] };
  174. atmosphericEffects: { haze: number; glare: number; reflections: number; transparency: number };
  175. spatialPerception: { depth_enhancement: number; space_definition: number; focal_guidance: number };
  176. };
  177. };
  178. }
  179. // 需求指标接口
  180. interface RequirementMetric {
  181. id: string;
  182. category: 'color' | 'space' | 'material';
  183. name: string;
  184. value: any;
  185. unit?: string;
  186. range?: { min: number; max: number };
  187. description?: string;
  188. }
  189. // 协作评论接口
  190. interface CollaborationComment {
  191. id: string;
  192. author: string;
  193. role: 'customer-service' | 'designer' | 'client';
  194. content: string;
  195. timestamp: Date;
  196. requirementId?: string;
  197. status: 'pending' | 'resolved';
  198. }
  199. // 需求项接口
  200. interface RequirementItem {
  201. id: string;
  202. title: string;
  203. description: string;
  204. priority: 'high' | 'medium' | 'low';
  205. status: 'pending' | 'confirmed' | 'rejected';
  206. tags?: string[];
  207. metrics?: RequirementMetric[];
  208. comments?: CollaborationComment[];
  209. lastUpdated: Date;
  210. showComments?: boolean;
  211. }
  212. // 上传文件接口
  213. interface UploadedFile {
  214. id: string;
  215. name: string;
  216. url: string;
  217. size?: number;
  218. type: 'image' | 'cad' | 'text';
  219. preview?: string;
  220. }
  221. @Component({
  222. selector: 'app-requirements-confirm-card',
  223. standalone: true,
  224. imports: [CommonModule, FormsModule, ReactiveFormsModule, UploadSuccessModalComponent, GlobalPromptComponent, FullReportOverlayComponent],
  225. providers: [CadAnalysisService],
  226. templateUrl: './requirements-confirm-card.html',
  227. styleUrls: ['./requirements-confirm-card.scss'],
  228. changeDetection: ChangeDetectionStrategy.Default // 确保使用默认变更检测策略
  229. })
  230. export class RequirementsConfirmCardComponent implements OnInit, OnDestroy {
  231. @Input() projectId?: string;
  232. @Output() requirementConfirmed = new EventEmitter<RequirementItem>();
  233. @Output() progressUpdated = new EventEmitter<number>();
  234. @Output() stageCompleted = new EventEmitter<{ stage: string; allStagesCompleted: boolean }>();
  235. @Output() dataUpdated = new EventEmitter<any>(); // 新增:实时数据更新事件
  236. // 表单
  237. materialForm!: FormGroup;
  238. commentForm!: FormGroup;
  239. materialUploadForm!: FormGroup;
  240. // 数据
  241. materialFiles: MaterialFile[] = [];
  242. materials: MaterialFile[] = [];
  243. requirementMetrics: RequirementMetric[] = [];
  244. collaborationComments: CollaborationComment[] = [];
  245. requirementItems: RequirementItem[] = [];
  246. // 状态
  247. activeTab: 'materials' | 'mapping' | 'collaboration' | 'progress' = 'materials';
  248. isUploading = false;
  249. isAnalyzing = false;
  250. dragOver = false;
  251. showConsistencyWarning = false;
  252. warningMessage = '';
  253. // 自动保存相关状态
  254. autoSaveEnabled = true;
  255. lastSaveTime?: Date;
  256. hasUnsavedChanges = false;
  257. isSaving = false;
  258. saveStatus: 'saved' | 'saving' | 'error' | 'unsaved' = 'saved';
  259. // 流程状态
  260. stageCompletionStatus = {
  261. materialAnalysis: false,
  262. requirementMapping: false,
  263. collaboration: false,
  264. progressReview: false
  265. };
  266. // 自动保存定时器
  267. private autoSaveTimer?: any;
  268. // 需求指标
  269. colorIndicators = {
  270. mainColor: { r: 255, g: 230, b: 180 },
  271. colorTemperature: 2700,
  272. colorRange: '暖色调',
  273. saturation: 70,
  274. brightness: 80,
  275. contrast: 60
  276. };
  277. spaceIndicators = {
  278. lineRatio: 60,
  279. blankRatio: 30,
  280. flowWidth: 0.9,
  281. aspectRatio: 1.6,
  282. ceilingHeight: 2.8,
  283. lightingLevel: 300
  284. };
  285. materialIndicators = {
  286. fabricRatio: 50,
  287. woodRatio: 30,
  288. metalRatio: 20,
  289. smoothness: 7,
  290. glossiness: 4,
  291. texture: 6
  292. };
  293. // 指标范围配置
  294. indicatorRanges = {
  295. color: {
  296. r: { min: 0, max: 255 },
  297. g: { min: 0, max: 255 },
  298. b: { min: 0, max: 255 },
  299. temperature: { min: 2000, max: 6500 },
  300. saturation: { min: 0, max: 100 },
  301. brightness: { min: 0, max: 100 },
  302. contrast: { min: 0, max: 100 }
  303. },
  304. space: {
  305. lineRatio: { min: 0, max: 100 },
  306. blankRatio: { min: 10, max: 80 },
  307. flowWidth: { min: 0.6, max: 1.5 },
  308. aspectRatio: { min: 1.0, max: 3.0 },
  309. ceilingHeight: { min: 2.4, max: 4.0 },
  310. lightingLevel: { min: 100, max: 800 }
  311. },
  312. material: {
  313. fabricRatio: { min: 0, max: 100 },
  314. woodRatio: { min: 0, max: 100 },
  315. metalRatio: { min: 0, max: 100 },
  316. smoothness: { min: 1, max: 10 },
  317. glossiness: { min: 1, max: 10 },
  318. texture: { min: 1, max: 10 }
  319. }
  320. };
  321. // 预设数据
  322. presetAtmospheres = [
  323. { name: '温馨暖调', rgb: '255,230,180', colorTemp: '2700-3000K', materials: ['木质', '布艺'] },
  324. { name: '现代冷调', rgb: '200,220,240', colorTemp: '5000-6000K', materials: ['金属', '玻璃'] },
  325. { name: '自然清新', rgb: '220,240,220', colorTemp: '4000-4500K', materials: ['竹木', '石材'] }
  326. ];
  327. // 一致性检查
  328. consistencyWarnings: string[] = [];
  329. historyStates: any[] = [];
  330. // 上传成功弹窗相关
  331. showUploadSuccessModal = false;
  332. uploadedFiles: { id: string; name: string; url: string; size?: number; type?: 'image' | 'cad' | 'text'; preview?: string }[] = [];
  333. uploadType: 'image' | 'document' | 'mixed' = 'image';
  334. colorAnalysisResult?: ColorAnalysisResult;
  335. cadAnalysisResult?: CadAnalysisResult;
  336. isAnalyzingColors = false; // 新增:色彩分析状态
  337. // 全局提示组件状态
  338. showGlobalPrompt = false;
  339. promptMode: 'fullscreen' | 'corner' = 'corner';
  340. promptPosition: 'top-right' | 'bottom-right' = 'bottom-right';
  341. promptTitle = '上传成功!';
  342. promptMessage = '';
  343. // 全屏报告覆盖层
  344. showFullReportOverlay = false;
  345. // 需求映射测试相关属性
  346. testSteps = [
  347. { id: 'upload', name: '图片上传', status: 'pending' as 'pending' | 'in-progress' | 'completed' | 'error' },
  348. { id: 'analysis', name: '图片分析', status: 'pending' as 'pending' | 'in-progress' | 'completed' | 'error' },
  349. { id: 'mapping', name: '需求映射', status: 'pending' as 'pending' | 'in-progress' | 'completed' | 'error' },
  350. { id: 'preview', name: '氛围预览', status: 'pending' as 'pending' | 'in-progress' | 'completed' | 'error' }
  351. ];
  352. // 需求映射相关状态
  353. isGeneratingMapping = false;
  354. requirementMapping: RequirementMapping | null = null;
  355. mappingError: string | null = null;
  356. analysisError: string | null = null;
  357. analysisResult: ColorAnalysisResult | undefined = undefined;
  358. // 订阅管理
  359. private subscriptions: Subscription[] = [];
  360. constructor(
  361. private fb: FormBuilder,
  362. private cdr: ChangeDetectorRef,
  363. private colorAnalysisService: ColorAnalysisService,
  364. private cadAnalysisService: CadAnalysisService,
  365. private requirementMappingService: RequirementMappingService
  366. ) {}
  367. ngOnInit() {
  368. this.initializeForms();
  369. this.initializeRequirements();
  370. this.loadPresetMetrics();
  371. // 启用自动保存
  372. this.autoSaveEnabled = true;
  373. // 定期检查阶段完成状态
  374. setInterval(() => {
  375. this.checkStageCompletion();
  376. }, 5000);
  377. }
  378. ngOnDestroy(): void {
  379. // 清理自动保存定时器
  380. if (this.autoSaveTimer) {
  381. clearTimeout(this.autoSaveTimer);
  382. }
  383. // 清理订阅
  384. this.subscriptions.forEach(sub => sub.unsubscribe());
  385. // 清理对象URL
  386. this.uploadedFiles.forEach(file => {
  387. if (file.url.startsWith('blob:')) {
  388. URL.revokeObjectURL(file.url);
  389. }
  390. });
  391. }
  392. private initializeForms() {
  393. this.materialForm = this.fb.group({
  394. textContent: ['', Validators.required],
  395. atmosphereDescription: [''],
  396. residentInfo: [''],
  397. scenePreferences: [''],
  398. title: [''],
  399. content: ['']
  400. });
  401. this.commentForm = this.fb.group({
  402. content: ['', Validators.required],
  403. requirementId: ['']
  404. });
  405. this.materialUploadForm = this.fb.group({
  406. file: [''],
  407. textContent: ['', Validators.required]
  408. });
  409. }
  410. private initializeRequirements() {
  411. this.requirementItems = [
  412. {
  413. id: 'color-atmosphere',
  414. title: '色彩氛围',
  415. description: '整体色调和氛围营造',
  416. priority: 'high',
  417. status: 'pending',
  418. lastUpdated: new Date()
  419. },
  420. {
  421. id: 'space-layout',
  422. title: '空间布局',
  423. description: '功能分区和动线设计',
  424. priority: 'high',
  425. status: 'pending',
  426. lastUpdated: new Date()
  427. },
  428. {
  429. id: 'material-selection',
  430. title: '材质选择',
  431. description: '主要材质和质感要求',
  432. priority: 'medium',
  433. status: 'pending',
  434. lastUpdated: new Date()
  435. }
  436. ];
  437. }
  438. private loadPresetMetrics() {
  439. this.requirementMetrics = [
  440. {
  441. id: 'main-color',
  442. category: 'color',
  443. name: '主色调',
  444. value: { r: 255, g: 230, b: 180 },
  445. description: '空间主要色彩'
  446. },
  447. {
  448. id: 'color-temp',
  449. category: 'color',
  450. name: '色温',
  451. value: 3000,
  452. unit: 'K',
  453. range: { min: 2700, max: 6500 },
  454. description: '照明色温范围'
  455. },
  456. {
  457. id: 'wood-ratio',
  458. category: 'material',
  459. name: '木质占比',
  460. value: 60,
  461. unit: '%',
  462. range: { min: 0, max: 100 },
  463. description: '木质材料使用比例'
  464. }
  465. ];
  466. }
  467. // 素材上传功能
  468. onFileSelected(event: Event, type: 'text' | 'image' | 'cad') {
  469. const input = event.target as HTMLInputElement;
  470. if (input.files) {
  471. Array.from(input.files).forEach(file => {
  472. this.uploadFile(file, type);
  473. });
  474. }
  475. }
  476. onFileDrop(event: DragEvent, type: 'text' | 'image' | 'cad') {
  477. event.preventDefault();
  478. this.dragOver = false;
  479. if (event.dataTransfer?.files) {
  480. Array.from(event.dataTransfer.files).forEach(file => {
  481. this.uploadFile(file, type);
  482. });
  483. }
  484. }
  485. onDragOver(event: DragEvent) {
  486. event.preventDefault();
  487. this.dragOver = true;
  488. }
  489. onDragLeave(event: DragEvent) {
  490. event.preventDefault();
  491. this.dragOver = false;
  492. }
  493. private uploadFile(file: File, type: 'text' | 'image' | 'cad') {
  494. this.isUploading = true;
  495. // 模拟文件上传
  496. setTimeout(() => {
  497. const materialFile: MaterialFile = {
  498. id: this.generateId(),
  499. name: file.name,
  500. type: type,
  501. url: URL.createObjectURL(file),
  502. size: this.formatFileSize(file.size),
  503. uploadTime: new Date()
  504. };
  505. this.materialFiles.push(materialFile);
  506. this.materials.push(materialFile);
  507. this.isUploading = false;
  508. // 显示全局提示(角落模式,无遮罩,不遮挡操作)
  509. this.promptTitle = '上传成功!';
  510. this.promptMessage = `已上传文件:${file.name}`;
  511. this.promptMode = 'corner';
  512. this.promptPosition = 'bottom-right';
  513. this.showGlobalPrompt = true;
  514. // 显示上传成功弹窗
  515. this.showUploadSuccessModal = true;
  516. this.uploadedFiles = [{
  517. id: materialFile.id,
  518. name: file.name,
  519. url: materialFile.url || '',
  520. size: file.size,
  521. type: type === 'text' ? 'text' : type === 'image' ? 'image' : 'cad'
  522. }];
  523. this.uploadType = type === 'text' ? 'document' : type === 'image' ? 'image' : 'mixed';
  524. // 自动解析
  525. this.analyzeMaterial(materialFile);
  526. }, 1000);
  527. }
  528. // 文本提交
  529. onTextSubmit(): void {
  530. if (this.materialUploadForm.valid) {
  531. const formValue = this.materialUploadForm.value;
  532. const textMaterial: MaterialFile = {
  533. id: this.generateId(),
  534. name: '文本需求',
  535. type: 'text',
  536. content: formValue.textContent,
  537. uploadTime: new Date(),
  538. size: this.formatFileSize(formValue.textContent?.length || 0)
  539. };
  540. this.materialFiles.push(textMaterial);
  541. this.materials.push(textMaterial);
  542. this.analyzeMaterial(textMaterial);
  543. this.materialUploadForm.reset();
  544. }
  545. }
  546. // 素材解析功能
  547. private analyzeMaterial(material: MaterialFile): void {
  548. this.isAnalyzing = true;
  549. // CAD采用服务分析,其它类型保持模拟
  550. if (material.type === 'cad') {
  551. const fileUrl = material.url || '';
  552. this.cadAnalysisService.analyzeByUrl(fileUrl, material.name).subscribe({
  553. next: (result) => {
  554. this.cadAnalysisResult = result;
  555. const analysis: MaterialAnalysis = {
  556. structuralElements: result.structuralElements,
  557. spaceMetrics: result.spaceMetrics,
  558. flowMetrics: result.flowMetrics
  559. };
  560. material.analysis = analysis;
  561. this.isAnalyzing = false;
  562. this.updateRequirementsFromAnalysis(analysis);
  563. },
  564. error: () => {
  565. this.cadAnalysisService.simulateCadAnalysis(material.name).subscribe({
  566. next: (mock) => {
  567. this.cadAnalysisResult = mock;
  568. const analysis: MaterialAnalysis = {
  569. structuralElements: mock.structuralElements,
  570. spaceMetrics: mock.spaceMetrics,
  571. flowMetrics: mock.flowMetrics
  572. };
  573. material.analysis = analysis;
  574. this.isAnalyzing = false;
  575. this.updateRequirementsFromAnalysis(analysis);
  576. },
  577. error: () => {
  578. this.isAnalyzing = false;
  579. console.error('CAD分析失败');
  580. }
  581. });
  582. }
  583. });
  584. return;
  585. }
  586. // 非CAD类型模拟
  587. setTimeout(() => {
  588. let analysis: MaterialAnalysis = {};
  589. switch (material.type) {
  590. case 'text':
  591. analysis = this.analyzeTextMaterial(material);
  592. break;
  593. case 'image':
  594. analysis = this.analyzeImageMaterial(material);
  595. break;
  596. }
  597. material.analysis = analysis;
  598. this.isAnalyzing = false;
  599. this.updateRequirementsFromAnalysis(analysis);
  600. }, 1200);
  601. }
  602. private analyzeTextMaterial(material: MaterialFile): MaterialAnalysis {
  603. return {
  604. atmosphere: {
  605. description: '温馨暖调',
  606. rgb: '255,230,180',
  607. colorTemp: '2700-3000K'
  608. },
  609. residents: {
  610. type: '亲子家庭',
  611. details: '孩子年龄3-6岁'
  612. },
  613. scenes: {
  614. preference: '瑜伽爱好者',
  615. requirements: '需要瑜伽区收纳'
  616. },
  617. keywords: {
  618. positive: ['科技感', '温馨', '实用'],
  619. negative: ['复杂线条', '冷色调']
  620. }
  621. };
  622. }
  623. private analyzeImageMaterial(material: MaterialFile): MaterialAnalysis {
  624. return {
  625. mainColors: [
  626. { rgb: '255,230,180', percentage: 45 },
  627. { rgb: '200,180,160', percentage: 30 },
  628. { rgb: '180,160,140', percentage: 25 }
  629. ],
  630. colorTemperature: '3000K',
  631. materialRatio: [
  632. { material: '木质', percentage: 60 },
  633. { material: '布艺', percentage: 25 },
  634. { material: '金属', percentage: 15 }
  635. ],
  636. spaceRatio: 35
  637. };
  638. }
  639. private analyzeCADMaterial(material: MaterialFile): MaterialAnalysis {
  640. return {
  641. structuralElements: [
  642. { type: '承重柱', position: '客厅中央', changeable: false },
  643. { type: '门窗', position: '南墙', changeable: false }
  644. ],
  645. spaceMetrics: [
  646. { room: '客厅', ratio: '16:9', width: '4.2m' },
  647. { room: '卧室', ratio: '4:3', width: '3.6m' }
  648. ],
  649. flowMetrics: [
  650. { area: '主通道', width: '1.2m', compliance: true },
  651. { area: '次通道', width: '0.8m', compliance: false }
  652. ]
  653. };
  654. }
  655. private updateRequirementsFromAnalysis(analysis: MaterialAnalysis) {
  656. if (analysis.atmosphere?.rgb) {
  657. const colorMetric = this.requirementMetrics.find(m => m.id === 'main-color');
  658. if (colorMetric) {
  659. const [r, g, b] = analysis.atmosphere.rgb.split(',').map(Number);
  660. colorMetric.value = { r, g, b };
  661. }
  662. }
  663. if (analysis.materialRatio) {
  664. const woodRatio = analysis.materialRatio.find(m => m.material === '木质');
  665. if (woodRatio) {
  666. const woodMetric = this.requirementMetrics.find(m => m.id === 'wood-ratio');
  667. if (woodMetric) {
  668. woodMetric.value = woodRatio.percentage;
  669. }
  670. }
  671. }
  672. }
  673. // 需求确认功能
  674. confirmRequirement(requirementId: string) {
  675. // 检查是否可以进行需求确认操作
  676. if (!this.canProceedToNextStage('materialAnalysis')) {
  677. alert('请先完成素材分析阶段的所有必要操作');
  678. return;
  679. }
  680. const requirement = this.requirementItems.find(r => r.id === requirementId);
  681. if (requirement) {
  682. requirement.status = 'confirmed';
  683. requirement.lastUpdated = new Date();
  684. this.requirementConfirmed.emit(requirement);
  685. this.updateProgress();
  686. this.triggerAutoSave();
  687. // 检查阶段完成状态
  688. this.checkStageCompletion();
  689. }
  690. }
  691. rejectRequirement(requirementId: string, reason?: string) {
  692. // 检查是否可以进行需求拒绝操作
  693. if (!this.canProceedToNextStage('materialAnalysis')) {
  694. alert('请先完成素材分析阶段的所有必要操作');
  695. return;
  696. }
  697. const requirement = this.requirementItems.find(r => r.id === requirementId);
  698. if (requirement) {
  699. requirement.status = 'rejected';
  700. requirement.lastUpdated = new Date();
  701. if (reason) {
  702. this.addCommentToRequirement(requirementId, reason, 'system');
  703. }
  704. this.updateProgress();
  705. this.triggerAutoSave();
  706. // 检查阶段完成状态
  707. this.checkStageCompletion();
  708. }
  709. }
  710. // 协作功能
  711. addComment() {
  712. if (this.commentForm.valid) {
  713. const comment: CollaborationComment = {
  714. id: this.generateId(),
  715. author: '当前用户',
  716. role: 'designer',
  717. content: this.commentForm.value.content,
  718. timestamp: new Date(),
  719. requirementId: this.commentForm.value.requirementId,
  720. status: 'pending'
  721. };
  722. this.collaborationComments.push(comment);
  723. this.commentForm.reset();
  724. this.triggerAutoSave();
  725. // 检查阶段完成状态
  726. this.checkStageCompletion();
  727. }
  728. }
  729. resolveComment(commentId: string) {
  730. const comment = this.collaborationComments.find(c => c.id === commentId);
  731. if (comment) {
  732. comment.status = 'resolved';
  733. this.triggerAutoSave();
  734. // 检查阶段完成状态
  735. this.checkStageCompletion();
  736. }
  737. }
  738. // 进度管理
  739. private updateProgress() {
  740. const totalRequirements = this.requirementItems.length;
  741. const confirmedRequirements = this.requirementItems.filter(r => r.status === 'confirmed').length;
  742. const progress = totalRequirements > 0 ? (confirmedRequirements / totalRequirements) * 100 : 0;
  743. // 实时更新进度条
  744. this.updateProgressBar(progress);
  745. this.progressUpdated.emit(progress);
  746. // 检查是否完成所有需求
  747. if (progress === 100) {
  748. this.onRequirementCommunicationComplete();
  749. }
  750. }
  751. private updateProgressBar(progress: number): void {
  752. // 更新进度条显示
  753. const progressBar = document.querySelector('.progress-bar-fill') as HTMLElement;
  754. if (progressBar) {
  755. progressBar.style.width = `${progress}%`;
  756. }
  757. // 更新进度文本
  758. const progressText = document.querySelector('.progress-text') as HTMLElement;
  759. if (progressText) {
  760. progressText.textContent = `${Math.round(progress)}%`;
  761. }
  762. // 添加进度动画效果
  763. this.animateProgressUpdate(progress);
  764. }
  765. private animateProgressUpdate(progress: number): void {
  766. // 添加进度更新的视觉反馈
  767. const progressContainer = document.querySelector('.progress-container') as HTMLElement;
  768. if (progressContainer) {
  769. progressContainer.classList.add('progress-updated');
  770. setTimeout(() => {
  771. progressContainer.classList.remove('progress-updated');
  772. }, 500);
  773. }
  774. }
  775. // 需求沟通阶段完成处理
  776. private onRequirementCommunicationComplete(): void {
  777. console.log('需求沟通阶段完成,开始同步关键信息');
  778. this.syncKeyInfoToSolutionConfirmation();
  779. }
  780. // 同步关键信息到方案确认阶段
  781. private syncKeyInfoToSolutionConfirmation(): void {
  782. const keyInfo = {
  783. colorAtmosphere: {
  784. mainColor: this.colorIndicators.mainColor,
  785. colorTemperature: this.colorIndicators.colorTemperature,
  786. saturation: this.colorIndicators.saturation,
  787. brightness: this.colorIndicators.brightness
  788. },
  789. spaceStructure: {
  790. lineRatio: this.spaceIndicators.lineRatio,
  791. blankRatio: this.spaceIndicators.blankRatio,
  792. flowWidth: this.spaceIndicators.flowWidth
  793. },
  794. materialWeights: {
  795. fabricRatio: this.materialIndicators.fabricRatio,
  796. woodRatio: this.materialIndicators.woodRatio,
  797. metalRatio: this.materialIndicators.metalRatio,
  798. smoothness: this.materialIndicators.smoothness
  799. },
  800. presetAtmosphere: this.getSelectedPresetAtmosphere()
  801. };
  802. // 触发同步事件
  803. this.requirementConfirmed.emit({
  804. id: 'requirement-sync',
  805. title: '需求沟通完成',
  806. description: '关键信息已同步至方案确认阶段',
  807. priority: 'high',
  808. status: 'confirmed',
  809. lastUpdated: new Date(),
  810. metrics: this.convertToMetrics(keyInfo)
  811. });
  812. // 启动交付执行流程
  813. setTimeout(() => {
  814. this.startDeliveryExecution();
  815. }, 1000);
  816. }
  817. private getSelectedPresetAtmosphere(): any {
  818. // 根据当前颜色指标找到最匹配的预设氛围
  819. const currentRgb = `${this.colorIndicators.mainColor.r},${this.colorIndicators.mainColor.g},${this.colorIndicators.mainColor.b}`;
  820. return this.presetAtmospheres.find(preset => preset.rgb === currentRgb) || this.presetAtmospheres[0];
  821. }
  822. private convertToMetrics(keyInfo: any): RequirementMetric[] {
  823. return [
  824. {
  825. id: 'color-sync',
  826. category: 'color',
  827. name: '色彩氛围',
  828. value: keyInfo.colorAtmosphere
  829. },
  830. {
  831. id: 'space-sync',
  832. category: 'space',
  833. name: '空间结构',
  834. value: keyInfo.spaceStructure
  835. },
  836. {
  837. id: 'material-sync',
  838. category: 'material',
  839. name: '材质权重',
  840. value: keyInfo.materialWeights
  841. }
  842. ];
  843. }
  844. // 启动交付执行流程
  845. private startDeliveryExecution(): void {
  846. console.log('启动交付执行流程');
  847. // 显示执行启动提示
  848. this.showExecutionStartNotification();
  849. // 这里可以触发路由跳转或其他业务逻辑
  850. // 例如:this.router.navigate(['/project', this.projectId, 'execution']);
  851. }
  852. private showExecutionStartNotification(): void {
  853. // 显示执行流程启动的通知
  854. const notification = document.createElement('div');
  855. notification.className = 'execution-notification';
  856. notification.innerHTML = `
  857. <div class="notification-content">
  858. <svg viewBox="0 0 24 24" fill="currentColor">
  859. <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
  860. </svg>
  861. <span>交付执行流程已启动</span>
  862. </div>
  863. `;
  864. document.body.appendChild(notification);
  865. setTimeout(() => {
  866. notification.remove();
  867. }, 3000);
  868. }
  869. getProgressPercentage(): number {
  870. if (this.requirementItems.length === 0) return 0;
  871. const confirmedCount = this.requirementItems.filter(r => r.status === 'confirmed').length;
  872. return Math.round((confirmedCount / this.requirementItems.length) * 100);
  873. }
  874. // 处理优先级更新
  875. onPriorityChange(requirementId: string, event: Event): void {
  876. const target = event.target as HTMLSelectElement;
  877. this.updateRequirementPriority(requirementId, target.value as 'high' | 'medium' | 'low');
  878. }
  879. // 检查需求是否有待处理评论
  880. hasUnreadComments(requirementId: string): boolean {
  881. return this.getCommentsForRequirement(requirementId).some(c => c.status === 'pending');
  882. }
  883. // 处理历史状态选择
  884. onHistoryStateChange(event: Event): void {
  885. const target = event.target as HTMLSelectElement;
  886. const index = +target.value;
  887. if (index >= 0) {
  888. this.restoreHistoryState(index);
  889. }
  890. }
  891. // 获取指定状态的需求数量
  892. getRequirementCountByStatus(status: 'confirmed' | 'pending' | 'rejected'): number {
  893. return (this.requirementItems || []).filter(r => r.status === status).length;
  894. }
  895. // 获取状态百分比
  896. getStatusPercentage(status: 'confirmed' | 'pending' | 'rejected'): number {
  897. const total = this.requirementItems.length;
  898. if (total === 0) return 0;
  899. const statusCount = this.getRequirementCountByStatus(status);
  900. return Math.round((statusCount / total) * 100);
  901. }
  902. // 指标映射功能
  903. updateMetricValue(metricId: string, value: any) {
  904. const metric = this.requirementMetrics.find(m => m.id === metricId);
  905. if (metric) {
  906. metric.value = value;
  907. this.checkConsistency();
  908. }
  909. }
  910. // 滑动条数值同步方法
  911. onSliderChange(key: string, value: number): void {
  912. console.log(`滑动条变化: ${key} = ${value}`);
  913. console.log('变化前的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  914. // 直接更新数据,不需要额外的updateIndicatorValue调用
  915. // 因为使用了双向绑定,数据已经自动更新
  916. if (key === 'r' || key === 'g' || key === 'b') {
  917. // 确保RGB值在有效范围内
  918. const range = this.getIndicatorRange(key);
  919. if (range) {
  920. const clampedValue = Math.max(range.min, Math.min(range.max, value));
  921. this.colorIndicators.mainColor[key as keyof typeof this.colorIndicators.mainColor] = clampedValue;
  922. console.log(`RGB值已更新: ${key} = ${clampedValue}`);
  923. console.log('变化后的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  924. }
  925. // 触发颜色指标更新
  926. this.updateColorIndicator('mainColor', this.colorIndicators.mainColor);
  927. } else {
  928. // 处理其他颜色指标
  929. this.updateIndicatorValue(key, value);
  930. }
  931. this.triggerAutoSave(); // 触发自动保存
  932. this.checkStageCompletion(); // 检查阶段完成状态
  933. // 发射实时数据更新事件
  934. this.emitDataUpdate();
  935. // 强制触发变更检测
  936. this.cdr.detectChanges();
  937. console.log('滑动条变更检测已触发');
  938. }
  939. onInputChange(key: string, value: number): void {
  940. console.log(`输入框变化: ${key} = ${value}`);
  941. console.log('变化前的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  942. // 直接更新数据,不需要额外的updateIndicatorValue调用
  943. // 因为使用了双向绑定,数据已经自动更新
  944. if (key === 'r' || key === 'g' || key === 'b') {
  945. // 确保RGB值在有效范围内
  946. const range = this.getIndicatorRange(key);
  947. if (range) {
  948. const clampedValue = Math.max(range.min, Math.min(range.max, value));
  949. this.colorIndicators.mainColor[key as keyof typeof this.colorIndicators.mainColor] = clampedValue;
  950. console.log(`RGB值已更新: ${key} = ${clampedValue}`);
  951. console.log('变化后的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  952. }
  953. // 触发颜色指标更新
  954. this.updateColorIndicator('mainColor', this.colorIndicators.mainColor);
  955. } else {
  956. // 处理其他颜色指标
  957. this.updateIndicatorValue(key, value);
  958. }
  959. this.triggerAutoSave();
  960. // 发射实时数据更新事件
  961. this.emitDataUpdate();
  962. // 强制触发变更检测
  963. this.cdr.detectChanges();
  964. console.log('输入框变更检测已触发');
  965. }
  966. validateInput(key: string, value: string): void {
  967. const numValue = parseFloat(value);
  968. if (isNaN(numValue)) {
  969. // 如果输入无效,恢复原值
  970. this.restoreIndicatorValue(key);
  971. return;
  972. }
  973. const range = this.getIndicatorRange(key);
  974. if (range) {
  975. const clampedValue = Math.max(range.min, Math.min(range.max, numValue));
  976. this.updateIndicatorValue(key, clampedValue);
  977. }
  978. }
  979. private updateIndicatorValue(key: string, value: number): void {
  980. console.log(`updateIndicatorValue调用: ${key} = ${value}`);
  981. // 更新颜色指标
  982. if (key in this.colorIndicators) {
  983. if (key === 'r' || key === 'g' || key === 'b') {
  984. // 创建新的mainColor对象以确保变更检测
  985. const oldColor = { ...this.colorIndicators.mainColor };
  986. this.colorIndicators.mainColor = {
  987. ...this.colorIndicators.mainColor,
  988. [key]: value
  989. };
  990. console.log(`RGB更新: ${key}从${oldColor[key as keyof typeof oldColor]}变为${value}`,
  991. '新mainColor:', this.colorIndicators.mainColor);
  992. this.updateColorIndicator('mainColor', this.colorIndicators.mainColor);
  993. } else {
  994. (this.colorIndicators as any)[key] = value;
  995. this.updateColorIndicator(key, value);
  996. }
  997. return;
  998. }
  999. // 更新空间指标
  1000. if (key in this.spaceIndicators) {
  1001. (this.spaceIndicators as any)[key] = value;
  1002. this.updateSpaceIndicator(key, value);
  1003. return;
  1004. }
  1005. // 更新材质指标
  1006. if (key in this.materialIndicators) {
  1007. (this.materialIndicators as any)[key] = value;
  1008. this.updateMaterialIndicator(key, value);
  1009. return;
  1010. }
  1011. }
  1012. private restoreIndicatorValue(key: string): void {
  1013. // 这里可以从历史状态或默认值恢复
  1014. console.log(`恢复指标值: ${key}`);
  1015. }
  1016. private getIndicatorRange(key: string): { min: number; max: number } | null {
  1017. // 检查颜色范围
  1018. if (key === 'r' || key === 'g' || key === 'b') {
  1019. return this.indicatorRanges.color[key as keyof typeof this.indicatorRanges.color];
  1020. }
  1021. if (key in this.indicatorRanges.color) {
  1022. return (this.indicatorRanges.color as any)[key];
  1023. }
  1024. // 检查空间范围
  1025. if (key in this.indicatorRanges.space) {
  1026. return (this.indicatorRanges.space as any)[key];
  1027. }
  1028. // 检查材质范围
  1029. if (key in this.indicatorRanges.material) {
  1030. return (this.indicatorRanges.material as any)[key];
  1031. }
  1032. return null;
  1033. }
  1034. // 指标更新方法
  1035. updateColorIndicator(type: string, value?: any): void {
  1036. switch (type) {
  1037. case 'mainColor':
  1038. if (value && typeof value === 'object' && 'r' in value) {
  1039. this.colorIndicators.mainColor = { ...value }; // 创建新对象以触发变更检测
  1040. console.log('mainColor更新后:', this.colorIndicators.mainColor);
  1041. }
  1042. break;
  1043. case 'colorTemperature':
  1044. // 色温更新时不需要改变颜色值,只是触发一致性检查
  1045. break;
  1046. case 'saturation':
  1047. // 饱和度更新时不需要改变颜色值,只是触发一致性检查
  1048. break;
  1049. }
  1050. console.log(`更新颜色指示器 ${type}:`, value, '当前RGB:', this.getRgbString());
  1051. this.checkConsistency();
  1052. this.updatePreview();
  1053. // 强制触发变更检测
  1054. this.cdr.detectChanges();
  1055. console.log('变更检测已触发');
  1056. }
  1057. updateSpaceIndicator(key: string, value: number) {
  1058. if (key in this.spaceIndicators) {
  1059. (this.spaceIndicators as any)[key] = value;
  1060. this.checkConsistency();
  1061. }
  1062. }
  1063. updateMaterialIndicator(key: string, value: number) {
  1064. if (key in this.materialIndicators) {
  1065. (this.materialIndicators as any)[key] = value;
  1066. this.checkConsistency();
  1067. this.normalizeMaterialRatios();
  1068. }
  1069. }
  1070. // 材质比例归一化
  1071. private normalizeMaterialRatios() {
  1072. const total = this.materialIndicators.fabricRatio +
  1073. this.materialIndicators.woodRatio +
  1074. this.materialIndicators.metalRatio;
  1075. if (total > 100) {
  1076. const scale = 100 / total;
  1077. this.materialIndicators.fabricRatio = Math.round(this.materialIndicators.fabricRatio * scale);
  1078. this.materialIndicators.woodRatio = Math.round(this.materialIndicators.woodRatio * scale);
  1079. this.materialIndicators.metalRatio = 100 - this.materialIndicators.fabricRatio - this.materialIndicators.woodRatio;
  1080. }
  1081. }
  1082. // 预览更新
  1083. private updatePreview() {
  1084. // 移除直接DOM操作,依赖Angular的属性绑定
  1085. console.log('updatePreview调用,当前RGB:', this.getRgbString());
  1086. // 不再直接操作DOM,让Angular的变更检测处理
  1087. }
  1088. // 获取RGB字符串
  1089. getRgbString(): string {
  1090. const { r, g, b } = this.colorIndicators.mainColor;
  1091. const rgbString = `rgb(${r}, ${g}, ${b})`;
  1092. console.log('getRgbString调用:', rgbString, '完整mainColor对象:', this.colorIndicators.mainColor);
  1093. return rgbString;
  1094. }
  1095. // 获取色温描述
  1096. getColorTemperatureDescription(): string {
  1097. const temp = this.colorIndicators.colorTemperature;
  1098. if (temp < 3000) return '暖色调';
  1099. if (temp < 4000) return '中性色调';
  1100. if (temp < 5000) return '自然色调';
  1101. return '冷色调';
  1102. }
  1103. applyPresetAtmosphere(preset: any) {
  1104. const rgbMatch = preset.rgb.match(/(\d+),(\d+),(\d+)/);
  1105. if (rgbMatch) {
  1106. this.colorIndicators.mainColor = {
  1107. r: parseInt(rgbMatch[1]),
  1108. g: parseInt(rgbMatch[2]),
  1109. b: parseInt(rgbMatch[3])
  1110. };
  1111. }
  1112. const tempMatch = preset.colorTemp.match(/(\d+)/);
  1113. if (tempMatch) {
  1114. this.colorIndicators.colorTemperature = parseInt(tempMatch[1]);
  1115. }
  1116. if (preset.materials.includes('木质')) {
  1117. this.materialIndicators.woodRatio = 60;
  1118. this.materialIndicators.fabricRatio = 30;
  1119. this.materialIndicators.metalRatio = 10;
  1120. } else if (preset.materials.includes('金属')) {
  1121. this.materialIndicators.metalRatio = 50;
  1122. this.materialIndicators.woodRatio = 20;
  1123. this.materialIndicators.fabricRatio = 30;
  1124. }
  1125. this.updatePreview();
  1126. this.checkConsistency();
  1127. }
  1128. // 一致性检查
  1129. private checkConsistency() {
  1130. this.consistencyWarnings = [];
  1131. if (this.colorIndicators.colorTemperature < 3000 &&
  1132. this.colorIndicators.mainColor.r > 200 &&
  1133. this.colorIndicators.mainColor.g < 150) {
  1134. this.consistencyWarnings.push('暖调氛围与冷色调RGB值存在矛盾');
  1135. }
  1136. if (this.materialIndicators.fabricRatio > 70 && this.colorIndicators.colorTemperature > 5000) {
  1137. this.consistencyWarnings.push('高布艺占比与冷色调可能不协调');
  1138. }
  1139. if (this.spaceIndicators.lineRatio > 80 && this.materialIndicators.woodRatio > 60) {
  1140. this.consistencyWarnings.push('高直线条占比与高木质占比可能过于刚硬');
  1141. }
  1142. }
  1143. // 协作批注功能
  1144. addCommentToRequirement(requirementId: string, content: string, author: string = '当前用户'): void {
  1145. const comment: CollaborationComment = {
  1146. id: this.generateId(),
  1147. author,
  1148. role: 'designer',
  1149. content,
  1150. timestamp: new Date(),
  1151. requirementId,
  1152. status: 'pending'
  1153. };
  1154. this.collaborationComments.push(comment);
  1155. this.updateProgress();
  1156. }
  1157. // 优先级排序功能
  1158. updateRequirementPriority(requirementId: string, priority: 'high' | 'medium' | 'low'): void {
  1159. const requirement = this.requirementItems.find(r => r.id === requirementId);
  1160. if (requirement) {
  1161. requirement.priority = priority;
  1162. requirement.lastUpdated = new Date();
  1163. this.sortRequirementsByPriority();
  1164. }
  1165. }
  1166. sortRequirementsByPriority(): void {
  1167. const priorityOrder = { 'high': 3, 'medium': 2, 'low': 1 };
  1168. this.requirementItems.sort((a, b) => {
  1169. return priorityOrder[b.priority] - priorityOrder[a.priority];
  1170. });
  1171. }
  1172. // 历史记录功能
  1173. saveCurrentState(): void {
  1174. const currentState = {
  1175. timestamp: new Date(),
  1176. colorIndicators: { ...this.colorIndicators },
  1177. spaceIndicators: { ...this.spaceIndicators },
  1178. materialIndicators: { ...this.materialIndicators },
  1179. requirementItems: this.requirementItems.map((r: RequirementItem) => ({ ...r })),
  1180. author: '当前用户'
  1181. };
  1182. this.historyStates.push(currentState);
  1183. if (this.historyStates.length > 10) {
  1184. this.historyStates.shift();
  1185. }
  1186. }
  1187. restoreHistoryState(index: number): void {
  1188. if (index >= 0 && index < this.historyStates.length) {
  1189. const state = this.historyStates[index];
  1190. this.colorIndicators = { ...state.colorIndicators };
  1191. this.spaceIndicators = { ...state.spaceIndicators };
  1192. this.materialIndicators = { ...state.materialIndicators };
  1193. this.requirementItems = state.requirementItems.map((r: RequirementItem) => ({ ...r }));
  1194. this.updatePreview();
  1195. this.checkConsistency();
  1196. }
  1197. }
  1198. // 获取未解决的评论数量
  1199. getUnresolvedCommentsCount(): number {
  1200. return this.collaborationComments.filter(c => c.status === 'pending').length;
  1201. }
  1202. // 获取需求的评论
  1203. getCommentsForRequirement(requirementId: string): CollaborationComment[] {
  1204. return this.collaborationComments.filter(comment => comment.requirementId === requirementId) || [];
  1205. }
  1206. // 获取状态样式类
  1207. getStatusClass(status: string): string {
  1208. return status;
  1209. }
  1210. // 工具方法
  1211. private generateId(): string {
  1212. return Math.random().toString(36).substr(2, 9);
  1213. }
  1214. private formatFileSize(bytes: number): string {
  1215. if (bytes === 0) return '0 Bytes';
  1216. const k = 1024;
  1217. const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  1218. const i = Math.floor(Math.log(bytes) / Math.log(k));
  1219. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  1220. }
  1221. // 删除素材
  1222. removeMaterial(materialId: string) {
  1223. const index = this.materialFiles.findIndex(m => m.id === materialId);
  1224. if (index > -1) {
  1225. const material = this.materialFiles[index];
  1226. if (material.url) {
  1227. URL.revokeObjectURL(material.url);
  1228. }
  1229. this.materialFiles.splice(index, 1);
  1230. }
  1231. const materialsIndex = this.materials.findIndex(m => m.id === materialId);
  1232. if (materialsIndex > -1) {
  1233. this.materials.splice(materialsIndex, 1);
  1234. }
  1235. }
  1236. // 切换标签页
  1237. switchTab(tab: 'materials' | 'mapping' | 'collaboration' | 'progress') {
  1238. this.activeTab = tab;
  1239. }
  1240. // 获取需求状态文本
  1241. getRequirementStatusText(status: string): string {
  1242. const statusMap: { [key: string]: string } = {
  1243. 'pending': '待确认',
  1244. 'confirmed': '已确认',
  1245. 'rejected': '已拒绝'
  1246. };
  1247. return statusMap[status] || status;
  1248. }
  1249. // 获取优先级文本
  1250. getPriorityText(priority: string): string {
  1251. const priorityMap: { [key: string]: string } = {
  1252. 'high': '高',
  1253. 'medium': '中',
  1254. 'low': '低'
  1255. };
  1256. return priorityMap[priority] || priority;
  1257. }
  1258. // 刷新进度(保留用于手动刷新,但不再强制要求)
  1259. refreshProgress(): void {
  1260. // 重新计算进度
  1261. this.updateProgress();
  1262. // 更新进度条显示
  1263. const progress = this.getProgressPercentage();
  1264. this.updateProgressBar(progress);
  1265. // 检查阶段完成状态
  1266. this.checkStageCompletion();
  1267. // 触发进度更新事件
  1268. this.progressUpdated.emit(progress);
  1269. console.log('进度已手动刷新:', progress + '%');
  1270. }
  1271. // 自动保存功能
  1272. private triggerAutoSave(): void {
  1273. if (!this.autoSaveEnabled) return;
  1274. this.hasUnsavedChanges = true;
  1275. this.saveStatus = 'unsaved';
  1276. // 清除之前的定时器
  1277. if (this.autoSaveTimer) {
  1278. clearTimeout(this.autoSaveTimer);
  1279. }
  1280. // 设置新的自动保存定时器(延迟1秒)
  1281. this.autoSaveTimer = setTimeout(() => {
  1282. this.performAutoSave();
  1283. }, 1000);
  1284. }
  1285. private async performAutoSave(): Promise<void> {
  1286. if (this.isSaving) return;
  1287. this.isSaving = true;
  1288. this.saveStatus = 'saving';
  1289. try {
  1290. // 收集所有需要保存的数据
  1291. const saveData = this.collectSaveData();
  1292. // 模拟保存操作(实际项目中这里会调用API)
  1293. await this.saveToServer(saveData);
  1294. this.hasUnsavedChanges = false;
  1295. this.saveStatus = 'saved';
  1296. this.lastSaveTime = new Date();
  1297. console.log('自动保存成功:', new Date().toLocaleTimeString());
  1298. } catch (error) {
  1299. this.saveStatus = 'error';
  1300. console.error('自动保存失败:', error);
  1301. } finally {
  1302. this.isSaving = false;
  1303. }
  1304. }
  1305. // 手动保存
  1306. async manualSave(): Promise<void> {
  1307. if (this.isSaving) return;
  1308. // 清除自动保存定时器
  1309. if (this.autoSaveTimer) {
  1310. clearTimeout(this.autoSaveTimer);
  1311. }
  1312. await this.performAutoSave();
  1313. }
  1314. private collectSaveData(): any {
  1315. return {
  1316. projectId: this.projectId,
  1317. colorIndicators: this.colorIndicators,
  1318. spaceIndicators: this.spaceIndicators,
  1319. materialIndicators: this.materialIndicators,
  1320. requirementItems: this.requirementItems,
  1321. requirementMetrics: this.requirementMetrics,
  1322. materialFiles: this.materialFiles,
  1323. collaborationComments: this.collaborationComments,
  1324. stageCompletionStatus: this.stageCompletionStatus,
  1325. lastUpdated: new Date()
  1326. };
  1327. }
  1328. private async saveToServer(data: any): Promise<void> {
  1329. // 模拟API调用延迟
  1330. return new Promise((resolve, reject) => {
  1331. setTimeout(() => {
  1332. // 模拟90%成功率
  1333. if (Math.random() > 0.1) {
  1334. resolve();
  1335. } else {
  1336. reject(new Error('网络错误'));
  1337. }
  1338. }, 500);
  1339. });
  1340. }
  1341. // 检查阶段完成状态
  1342. private checkStageCompletion(): void {
  1343. // 检查素材分析阶段 - 需要有素材文件且都已分析
  1344. this.stageCompletionStatus.materialAnalysis = this.materialFiles.length > 0 &&
  1345. this.materialFiles.every(m => m.analysis);
  1346. // 检查需求映射阶段 - 需要有确认的需求项,或者滑动条数据已调整且保存
  1347. const hasConfirmedRequirements = this.requirementItems.length > 0 &&
  1348. this.requirementItems.some(r => r.status === 'confirmed');
  1349. const hasAdjustedIndicators = this.hasIndicatorChanges();
  1350. this.stageCompletionStatus.requirementMapping = hasConfirmedRequirements ||
  1351. (hasAdjustedIndicators && this.saveStatus === 'saved');
  1352. // 检查协作验证阶段 - 需要有协作评论或需求评论
  1353. this.stageCompletionStatus.collaboration = this.collaborationComments.length > 0 ||
  1354. this.requirementItems.some(r => r.comments && r.comments.length > 0);
  1355. // 检查进度审查阶段 - 需要进度达到80%以上
  1356. this.stageCompletionStatus.progressReview = this.getProgressPercentage() >= 80;
  1357. console.log('阶段完成状态更新:', this.stageCompletionStatus);
  1358. // 检查是否所有阶段都已完成
  1359. const allStagesCompleted = Object.values(this.stageCompletionStatus).every(status => status);
  1360. // 发射阶段完成事件
  1361. if (allStagesCompleted) {
  1362. this.stageCompleted.emit({ stage: 'requirements-communication', allStagesCompleted: true });
  1363. }
  1364. }
  1365. // 检查指示器是否有变化
  1366. private hasIndicatorChanges(): boolean {
  1367. // 检查颜色指示器是否有变化(与默认值比较)
  1368. const defaultColorIndicators = {
  1369. mainColor: { r: 255, g: 230, b: 180 },
  1370. colorTemperature: 2700,
  1371. colorRange: '暖色调',
  1372. saturation: 70,
  1373. brightness: 80,
  1374. contrast: 60
  1375. };
  1376. const defaultSpaceIndicators = {
  1377. lineRatio: 60,
  1378. blankRatio: 30,
  1379. flowWidth: 0.9,
  1380. aspectRatio: 1.6,
  1381. ceilingHeight: 2.8,
  1382. lightingLevel: 300
  1383. };
  1384. const defaultMaterialIndicators = {
  1385. fabricRatio: 50,
  1386. woodRatio: 30,
  1387. metalRatio: 20,
  1388. smoothness: 7,
  1389. glossiness: 4,
  1390. texture: 6
  1391. };
  1392. // 检查颜色指示器变化
  1393. const colorChanged = JSON.stringify(this.colorIndicators) !== JSON.stringify(defaultColorIndicators);
  1394. // 检查空间指示器变化
  1395. const spaceChanged = JSON.stringify(this.spaceIndicators) !== JSON.stringify(defaultSpaceIndicators);
  1396. // 检查材质指示器变化
  1397. const materialChanged = JSON.stringify(this.materialIndicators) !== JSON.stringify(defaultMaterialIndicators);
  1398. return colorChanged || spaceChanged || materialChanged;
  1399. }
  1400. // 获取阶段状态文本
  1401. getStageStatusText(stage: keyof typeof this.stageCompletionStatus): string {
  1402. if (this.stageCompletionStatus[stage]) {
  1403. return '已完成';
  1404. } else {
  1405. // 检查是否为未开始状态
  1406. const stages = ['materialAnalysis', 'requirementMapping', 'collaboration', 'progressReview'];
  1407. const currentIndex = stages.indexOf(stage);
  1408. // 检查前面的阶段是否都已完成
  1409. let allPreviousCompleted = true;
  1410. for (let i = 0; i < currentIndex; i++) {
  1411. if (!this.stageCompletionStatus[stages[i] as keyof typeof this.stageCompletionStatus]) {
  1412. allPreviousCompleted = false;
  1413. break;
  1414. }
  1415. }
  1416. return allPreviousCompleted ? '进行中' : '未进行';
  1417. }
  1418. }
  1419. // 获取阶段状态类名
  1420. getStageStatusClass(stage: keyof typeof this.stageCompletionStatus): string {
  1421. if (this.stageCompletionStatus[stage]) {
  1422. return 'stage-completed';
  1423. } else {
  1424. // 检查是否为未开始状态
  1425. const stages = ['materialAnalysis', 'requirementMapping', 'collaboration', 'progressReview'];
  1426. const currentIndex = stages.indexOf(stage);
  1427. // 检查前面的阶段是否都已完成
  1428. let allPreviousCompleted = true;
  1429. for (let i = 0; i < currentIndex; i++) {
  1430. if (!this.stageCompletionStatus[stages[i] as keyof typeof this.stageCompletionStatus]) {
  1431. allPreviousCompleted = false;
  1432. break;
  1433. }
  1434. }
  1435. return allPreviousCompleted ? 'stage-in-progress' : 'stage-pending';
  1436. }
  1437. }
  1438. // 检查是否可以进入下一阶段
  1439. canProceedToNextStage(currentStage: keyof typeof this.stageCompletionStatus): boolean {
  1440. const stages = Object.keys(this.stageCompletionStatus) as (keyof typeof this.stageCompletionStatus)[];
  1441. const currentIndex = stages.indexOf(currentStage);
  1442. // 检查当前阶段之前的所有阶段是否都已完成
  1443. for (let i = 0; i <= currentIndex; i++) {
  1444. if (!this.stageCompletionStatus[stages[i]]) {
  1445. return false;
  1446. }
  1447. }
  1448. return true;
  1449. }
  1450. // 获取保存状态文本
  1451. getSaveStatusText(): string {
  1452. switch (this.saveStatus) {
  1453. case 'saved': return this.lastSaveTime ? `已保存 ${this.lastSaveTime.toLocaleTimeString()}` : '已保存';
  1454. case 'saving': return '保存中...';
  1455. case 'error': return '保存失败';
  1456. case 'unsaved': return '有未保存的更改';
  1457. default: return '';
  1458. }
  1459. }
  1460. // 获取保存状态图标
  1461. getSaveStatusIcon(): string {
  1462. switch (this.saveStatus) {
  1463. case 'saved': return '✓';
  1464. case 'saving': return '⏳';
  1465. case 'error': return '⚠';
  1466. case 'unsaved': return '●';
  1467. default: return '';
  1468. }
  1469. }
  1470. // 上传成功弹窗相关方法
  1471. onModalClose(): void {
  1472. this.showUploadSuccessModal = false;
  1473. this.uploadedFiles = [];
  1474. this.colorAnalysisResult = undefined;
  1475. }
  1476. // 全局提示关闭
  1477. onPromptClose(): void {
  1478. this.showGlobalPrompt = false;
  1479. }
  1480. onAnalyzeColors(): void {
  1481. if (this.uploadedFiles.length > 0 && this.uploadType === 'image') {
  1482. const imageFile = this.uploadedFiles[0];
  1483. // 设置分析状态为true
  1484. this.isAnalyzingColors = true;
  1485. // 从URL获取文件数据并创建File对象
  1486. fetch(imageFile.url)
  1487. .then(response => {
  1488. if (!response.ok) {
  1489. throw new Error(`HTTP error! status: ${response.status}`);
  1490. }
  1491. return response.blob();
  1492. })
  1493. .then(blob => {
  1494. // 创建包含实际文件数据的File对象
  1495. const file = new File([blob], imageFile.name, { type: imageFile.type || 'image/jpeg' });
  1496. // 使用模拟分析(在实际应用中应该调用真实的API)
  1497. this.colorAnalysisService.simulateAnalysis(file).subscribe({
  1498. next: (result) => {
  1499. this.colorAnalysisResult = result;
  1500. this.isAnalyzingColors = false; // 分析完成,设置状态为false
  1501. // 可以在这里更新颜色指标
  1502. if (result.colors.length > 0) {
  1503. const mainColor = result.colors[0];
  1504. this.updateColorIndicator('mainColor', mainColor.rgb);
  1505. }
  1506. // 新增:分析完成后向父级发射数据更新,包含色彩分析结果
  1507. this.emitDataUpdate();
  1508. },
  1509. error: (error) => {
  1510. console.error('颜色分析失败:', error);
  1511. this.isAnalyzingColors = false; // 分析失败,也要重置状态
  1512. }
  1513. });
  1514. })
  1515. .catch(error => {
  1516. console.error('获取文件数据失败:', error);
  1517. this.isAnalyzingColors = false; // 获取文件失败,重置状态
  1518. });
  1519. }
  1520. }
  1521. onViewReport(): void {
  1522. console.log('onViewReport被调用,当前colorAnalysisResult:', this.colorAnalysisResult);
  1523. // 打开全屏报告覆盖层
  1524. this.showFullReportOverlay = true;
  1525. // 确保色彩分析结果传递给父组件用于右侧展示
  1526. if (this.colorAnalysisResult) {
  1527. console.log('调用emitDataUpdate传递色彩分析结果');
  1528. this.emitDataUpdate();
  1529. } else {
  1530. console.log('没有色彩分析结果可传递');
  1531. }
  1532. }
  1533. onCloseFullReport(): void {
  1534. this.showFullReportOverlay = false;
  1535. }
  1536. // 新增:发射实时数据更新事件的方法
  1537. private emitDataUpdate(): void {
  1538. // 收集所有材料的详细分析数据
  1539. const materialAnalysisData = this.materials.map(material => ({
  1540. id: material.id,
  1541. name: material.name,
  1542. type: material.type,
  1543. analysis: material.analysis || {}
  1544. }));
  1545. const currentData = {
  1546. colorIndicators: this.colorIndicators || [],
  1547. spaceIndicators: this.spaceIndicators || [],
  1548. materialIndicators: this.materialIndicators || [],
  1549. requirementItems: this.requirementItems || [],
  1550. materials: this.materials || [],
  1551. collaborationComments: this.collaborationComments || '',
  1552. stageCompletionStatus: this.stageCompletionStatus || {},
  1553. // 传递色彩分析结果到父级用于右侧展示
  1554. colorAnalysisResult: this.colorAnalysisResult,
  1555. // 新增:传递完整的材料分析数据,包含色彩、形体、质感、纹理、灯光分析
  1556. materialAnalysisData: materialAnalysisData,
  1557. // 新增:传递详细的分析结果
  1558. detailedAnalysis: {
  1559. enhancedColorAnalysis: this.extractEnhancedColorAnalysis(),
  1560. formAnalysis: this.extractFormAnalysis(),
  1561. textureAnalysis: this.extractTextureAnalysis(),
  1562. patternAnalysis: this.extractPatternAnalysis(),
  1563. lightingAnalysis: this.extractLightingAnalysis()
  1564. }
  1565. };
  1566. console.log('emitDataUpdate被调用,准备发射数据:', {
  1567. colorAnalysisResult: this.colorAnalysisResult,
  1568. materials: this.materials,
  1569. requirementItems: this.requirementItems,
  1570. materialAnalysisData: materialAnalysisData,
  1571. detailedAnalysis: currentData.detailedAnalysis
  1572. });
  1573. this.dataUpdated.emit(currentData);
  1574. console.log('实时数据更新事件已发射:', currentData);
  1575. }
  1576. // 提取增强色彩分析数据
  1577. private extractEnhancedColorAnalysis(): any {
  1578. const colorAnalyses = this.materials
  1579. .filter(m => m.analysis?.enhancedColorAnalysis)
  1580. .map(m => m.analysis!.enhancedColorAnalysis);
  1581. if (colorAnalyses.length === 0) return null;
  1582. // 合并所有色彩分析数据
  1583. return colorAnalyses.reduce((merged, current) => ({
  1584. ...merged,
  1585. ...current
  1586. }), {});
  1587. }
  1588. // 提取形体分析数据
  1589. private extractFormAnalysis(): any {
  1590. const formAnalyses = this.materials
  1591. .filter(m => m.analysis?.formAnalysis)
  1592. .map(m => m.analysis!.formAnalysis);
  1593. if (formAnalyses.length === 0) return null;
  1594. return formAnalyses.reduce((merged, current) => ({
  1595. ...merged,
  1596. ...current
  1597. }), {});
  1598. }
  1599. // 提取质感分析数据
  1600. private extractTextureAnalysis(): any {
  1601. const textureAnalyses = this.materials
  1602. .filter(m => m.analysis?.textureAnalysis)
  1603. .map(m => m.analysis!.textureAnalysis);
  1604. if (textureAnalyses.length === 0) return null;
  1605. return textureAnalyses.reduce((merged, current) => ({
  1606. ...merged,
  1607. ...current
  1608. }), {});
  1609. }
  1610. // 提取纹理分析数据
  1611. private extractPatternAnalysis(): any {
  1612. const patternAnalyses = this.materials
  1613. .filter(m => m.analysis?.patternAnalysis)
  1614. .map(m => m.analysis!.patternAnalysis);
  1615. if (patternAnalyses.length === 0) return null;
  1616. return patternAnalyses.reduce((merged, current) => ({
  1617. ...merged,
  1618. ...current
  1619. }), {});
  1620. }
  1621. // 提取灯光分析数据
  1622. private extractLightingAnalysis(): any {
  1623. const lightingAnalyses = this.materials
  1624. .filter(m => m.analysis?.lightingAnalysis)
  1625. .map(m => m.analysis!.lightingAnalysis);
  1626. if (lightingAnalyses.length === 0) return null;
  1627. return lightingAnalyses.reduce((merged, current) => ({
  1628. ...merged,
  1629. ...current
  1630. }), {});
  1631. }
  1632. // 新增:图片与CAD文件预览方法
  1633. previewImage(url?: string): void {
  1634. if (!url) { return; }
  1635. try {
  1636. window.open(url, '_blank');
  1637. } catch (e) {
  1638. console.error('预览图片失败:', e);
  1639. }
  1640. }
  1641. previewCad(url?: string): void {
  1642. if (!url) { return; }
  1643. try {
  1644. window.open(url, '_blank');
  1645. } catch (e) {
  1646. console.error('预览CAD失败:', e);
  1647. }
  1648. }
  1649. // 需求映射测试相关方法
  1650. onFileSelected(event: Event): void {
  1651. const input = event.target as HTMLInputElement;
  1652. if (!input.files || input.files.length === 0) return;
  1653. this.updateStepStatus('upload', 'in-progress');
  1654. this.isUploading = true;
  1655. try {
  1656. const files = Array.from(input.files);
  1657. this.uploadedFiles = files.map(file => ({
  1658. id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
  1659. name: file.name,
  1660. url: URL.createObjectURL(file),
  1661. size: file.size,
  1662. type: 'image' as const,
  1663. preview: URL.createObjectURL(file)
  1664. }));
  1665. // 模拟上传延迟
  1666. setTimeout(() => {
  1667. this.isUploading = false;
  1668. this.updateStepStatus('upload', 'completed');
  1669. this.showUploadModal = true;
  1670. // 自动开始分析
  1671. this.startAnalysis();
  1672. }, 1000);
  1673. } catch (error) {
  1674. console.error('文件上传失败:', error);
  1675. this.isUploading = false;
  1676. this.updateStepStatus('upload', 'error');
  1677. }
  1678. }
  1679. // 开始分析
  1680. startAnalysis(): void {
  1681. if (this.uploadedFiles.length === 0) return;
  1682. this.updateStepStatus('analysis', 'in-progress');
  1683. this.isAnalyzing = true;
  1684. this.analysisError = null;
  1685. // 使用第一个文件进行分析
  1686. const firstFile = this.uploadedFiles[0];
  1687. // 添加null检查和错误处理
  1688. if (!firstFile) {
  1689. this.analysisError = '未找到有效的文件';
  1690. this.isAnalyzing = false;
  1691. this.updateStepStatus('analysis', 'error');
  1692. return;
  1693. }
  1694. try {
  1695. const analysisSubscription = this.colorAnalysisService.analyzeImage(firstFile).subscribe({
  1696. next: (result: ColorAnalysisResult) => {
  1697. if (result) {
  1698. this.analysisResult = result;
  1699. this.isAnalyzing = false;
  1700. this.updateStepStatus('analysis', 'completed');
  1701. // 自动开始需求映射
  1702. this.startRequirementMapping();
  1703. } else {
  1704. this.analysisError = '分析结果为空';
  1705. this.isAnalyzing = false;
  1706. this.updateStepStatus('analysis', 'error');
  1707. }
  1708. },
  1709. error: (error: any) => {
  1710. console.error('分析失败:', error);
  1711. this.analysisError = '图片分析失败,请重试';
  1712. this.isAnalyzing = false;
  1713. this.updateStepStatus('analysis', 'error');
  1714. }
  1715. });
  1716. this.subscriptions.push(analysisSubscription);
  1717. } catch (error) {
  1718. console.error('启动分析失败:', error);
  1719. this.analysisError = '启动分析失败,请重试';
  1720. this.isAnalyzing = false;
  1721. this.updateStepStatus('analysis', 'error');
  1722. }
  1723. }
  1724. // 开始需求映射
  1725. startRequirementMapping(): void {
  1726. if (!this.analysisResult) {
  1727. console.warn('分析结果为空,无法开始需求映射');
  1728. return;
  1729. }
  1730. this.updateStepStatus('mapping', 'in-progress');
  1731. this.isGeneratingMapping = true;
  1732. this.mappingError = null;
  1733. try {
  1734. const mappingSubscription = this.requirementMappingService.generateRequirementMapping(
  1735. this.analysisResult,
  1736. SceneTemplate.LIVING_ROOM_MODERN
  1737. ).subscribe({
  1738. next: (mapping) => {
  1739. if (mapping) {
  1740. this.requirementMapping = mapping;
  1741. this.isGeneratingMapping = false;
  1742. this.updateStepStatus('mapping', 'completed');
  1743. this.updateStepStatus('preview', 'completed');
  1744. console.log('=== 需求映射测试完成 ===');
  1745. console.log('映射结果:', this.requirementMapping);
  1746. } else {
  1747. this.mappingError = '需求映射结果为空';
  1748. this.isGeneratingMapping = false;
  1749. this.updateStepStatus('mapping', 'error');
  1750. }
  1751. },
  1752. error: (error) => {
  1753. console.error('需求映射生成失败:', error);
  1754. this.mappingError = '需求映射生成失败,请重试';
  1755. this.isGeneratingMapping = false;
  1756. this.updateStepStatus('mapping', 'error');
  1757. }
  1758. });
  1759. this.subscriptions.push(mappingSubscription);
  1760. } catch (error) {
  1761. console.error('启动需求映射失败:', error);
  1762. this.mappingError = '启动需求映射失败,请重试';
  1763. this.isGeneratingMapping = false;
  1764. this.updateStepStatus('mapping', 'error');
  1765. }
  1766. }
  1767. // 更新步骤状态
  1768. private updateStepStatus(stepId: string, status: 'pending' | 'in-progress' | 'completed' | 'error'): void {
  1769. const step = this.testSteps.find(s => s.id === stepId);
  1770. if (step) {
  1771. step.status = status;
  1772. } else {
  1773. console.warn(`未找到步骤: ${stepId}`);
  1774. }
  1775. }
  1776. // 辅助方法:获取步骤图标
  1777. getStepIcon(status: string): string {
  1778. switch (status) {
  1779. case 'completed': return '✅';
  1780. case 'in-progress': return '⏳';
  1781. case 'error': return '❌';
  1782. default: return '⭕';
  1783. }
  1784. }
  1785. // 获取步骤状态类名
  1786. getStepClass(status: string): string {
  1787. return `step-${status}`;
  1788. }
  1789. // 手动重试分析
  1790. retryAnalysis(): void {
  1791. this.analysisError = null;
  1792. this.startAnalysis();
  1793. }
  1794. // 手动重试映射
  1795. retryMapping(): void {
  1796. this.mappingError = null;
  1797. this.startRequirementMapping();
  1798. }
  1799. // 下载测试结果
  1800. downloadTestResult(): void {
  1801. if (!this.requirementMapping) return;
  1802. const testResult = {
  1803. timestamp: new Date().toISOString(),
  1804. uploadedFiles: this.uploadedFiles.map(f => ({
  1805. name: f.name,
  1806. size: f.size,
  1807. type: f.type
  1808. })),
  1809. analysisResult: this.analysisResult,
  1810. requirementMapping: this.requirementMapping,
  1811. testSteps: this.testSteps
  1812. };
  1813. const blob = new Blob([JSON.stringify(testResult, null, 2)], { type: 'application/json' });
  1814. const url = URL.createObjectURL(blob);
  1815. const link = document.createElement('a');
  1816. link.href = url;
  1817. link.download = `requirement-mapping-test-${Date.now()}.json`;
  1818. link.click();
  1819. URL.revokeObjectURL(url);
  1820. }
  1821. }