requirements-confirm-card.ts 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017
  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. import { ColorWheelVisualizerComponent } from '../color-wheel-visualizer/color-wheel-visualizer';
  13. import { FurnitureFormSelectorComponent } from '../furniture-form-selector/furniture-form-selector';
  14. import { TextureComparisonVisualizerComponent } from '../texture-comparison-visualizer/texture-comparison-visualizer';
  15. import { PatternVisualizerComponent } from '../pattern-visualizer/pattern-visualizer';
  16. // 素材文件接口
  17. interface MaterialFile {
  18. id: string;
  19. name: string;
  20. type: 'text' | 'image' | 'cad';
  21. url?: string;
  22. content?: string;
  23. size?: string;
  24. uploadTime: Date;
  25. analysis?: MaterialAnalysis;
  26. }
  27. // 素材解析结果接口
  28. interface MaterialAnalysis {
  29. // 文本类解析
  30. atmosphere?: { description: string; rgb?: string; colorTemp?: string };
  31. residents?: { type: string; details: string };
  32. scenes?: { preference: string; requirements: string };
  33. keywords?: { positive: string[]; negative: string[] };
  34. // 图片类解析
  35. mainColors?: { hex: string; rgb: { r: number; g: number; b: number }; percentage: number; name?: string }[];
  36. colorTemperature?: string;
  37. materialRatio?: { material: string; percentage: number }[];
  38. spaceRatio?: number;
  39. // CAD类解析
  40. structuralElements?: { type: string; position: string; changeable: boolean }[];
  41. spaceMetrics?: { room: string; ratio: string; width: string }[];
  42. flowMetrics?: { area: string; width: string; compliance: boolean }[];
  43. // 增强色彩分析
  44. enhancedColorAnalysis?: {
  45. colorWheel?: {
  46. primaryHue: number;
  47. saturation: number;
  48. brightness: number;
  49. dominantColors: Array<{ hue: number; saturation: number; brightness: number; percentage: number }>;
  50. colorDistribution: string;
  51. };
  52. colorHarmony?: {
  53. harmonyType: string;
  54. harmonyScore: number;
  55. complementaryColors: string[];
  56. suggestions: string[];
  57. };
  58. colorTemperatureAnalysis?: {
  59. kelvin: number;
  60. warmCoolBalance: number;
  61. description: string;
  62. lightingRecommendations: string[];
  63. };
  64. colorPsychology?: {
  65. primaryMood: string;
  66. atmosphere: string;
  67. psychologicalEffects: string[];
  68. suitableSpaces: string[];
  69. };
  70. };
  71. // 形体分析
  72. formAnalysis?: {
  73. lineAnalysis?: {
  74. dominantLines: Array<{ type: string; percentage: number; characteristics: string[] }>;
  75. lineQuality: { smoothness: number; precision: number; expressiveness: number };
  76. visualFlow: { direction: string; rhythm: string; continuity: number };
  77. };
  78. geometryAnalysis?: {
  79. primaryShapes: Array<{ shape: string; percentage: number; characteristics: string[] }>;
  80. complexity: string;
  81. symmetry: { type: string; score: number };
  82. balance: { visual: number; compositional: number };
  83. };
  84. proportionAnalysis?: {
  85. aspectRatio: number;
  86. goldenRatio: number;
  87. proportionHarmony: number;
  88. scaleRelationships: Array<{ element: string; scale: string; relationship: string }>;
  89. };
  90. overallAssessment?: {
  91. formComplexity: number;
  92. visualImpact: number;
  93. functionalSuitability: number;
  94. aestheticAppeal: number;
  95. };
  96. };
  97. // 质感分析
  98. textureAnalysis?: {
  99. surfaceProperties?: {
  100. roughness: { level: string; value: number; description: string };
  101. glossiness: { level: string; value: number; reflectivity: number };
  102. transparency: { level: string; value: number };
  103. porosity: { level: string; value: number };
  104. };
  105. tactilePredict?: {
  106. temperature: { perceived: string; thermalConductivity: number };
  107. hardness: { level: string; value: number };
  108. flexibility: { level: string; value: number };
  109. weight: { perceived: string; density: number };
  110. comfort: { tactileComfort: number; ergonomicSuitability: number };
  111. };
  112. materialClassification?: {
  113. primaryMaterial: { category: string; confidence: number; subcategory?: string };
  114. secondaryMaterials: Array<{ category: string; percentage: number; confidence: number }>;
  115. materialProperties: { durability: number; maintenance: string; sustainability: number; costLevel: string };
  116. };
  117. textureQuality?: {
  118. overallQuality: number;
  119. consistency: number;
  120. authenticity: number;
  121. visualAppeal: number;
  122. functionalSuitability: number;
  123. ageingCharacteristics: { wearResistance: number; patinaPotential: number; maintenanceNeeds: string[] };
  124. };
  125. };
  126. // 纹理图案分析
  127. patternAnalysis?: {
  128. patternRecognition?: {
  129. primaryPatterns: Array<{ type: string; confidence: number; coverage: number; characteristics: string[] }>;
  130. patternComplexity: { level: string; score: number; elements: number };
  131. patternScale: { size: string; uniformity: number; variation: number };
  132. };
  133. repetitionAnalysis?: {
  134. repetitionType: { primary: string; pattern: string; consistency: number };
  135. spacing: { horizontal: number; vertical: number; uniformity: number; rhythm: string };
  136. symmetry: { type: string; strength: number; axes: number };
  137. tiling: { seamless: boolean; quality: number; edgeHandling: string };
  138. };
  139. textureClassification?: {
  140. textureFamily: { primary: string; subcategory: string; confidence: number };
  141. surfaceCharacter: { tactileQuality: string; visualDepth: number; dimensionality: string };
  142. materialSuggestion: { likelyMaterials: string[]; fabricationMethod: string[]; applicationSuitability: string[] };
  143. };
  144. visualRhythm?: {
  145. rhythmType: { primary: string; intensity: number; tempo: string };
  146. movement: { direction: string; flow: number; energy: number };
  147. emphasis: { focalPoints: number; contrast: number; hierarchy: number };
  148. harmony: { overall: number; balance: number; unity: number };
  149. };
  150. };
  151. // 灯光分析
  152. lightingAnalysis?: {
  153. lightSourceIdentification?: {
  154. primarySources: Array<{
  155. type: string;
  156. subtype: string;
  157. position: { direction: string; angle: number; distance: string };
  158. intensity: number;
  159. confidence: number;
  160. }>;
  161. lightingSetup: { complexity: string; sourceCount: number; dominantSource: string; lightingStyle: string };
  162. };
  163. illuminationAnalysis?: {
  164. brightness: { overall: number; distribution: string; dynamicRange: number; exposure: string };
  165. contrast: { level: number; type: string; areas: { highlights: number; midtones: number; shadows: number } };
  166. colorTemperature: { kelvin: number; warmth: string; consistency: number; mixedLighting: boolean };
  167. lightQuality: { softness: number; diffusion: number; directionality: number; evenness: number };
  168. };
  169. shadowAnalysis?: {
  170. shadowPresence: { coverage: number; intensity: number; sharpness: string; definition: number };
  171. shadowCharacteristics: { direction: string; length: string; density: number; falloff: string };
  172. shadowTypes: Array<{ type: 'cast' | 'form' | 'occlusion' | 'contact'; prominence: number; contribution: string }>;
  173. dimensionalEffect: { depth: number; volume: number; threedimensionality: number };
  174. };
  175. ambientAnalysis?: {
  176. ambientLevel: { strength: number; uniformity: number; contribution: number };
  177. lightingMood: { primary: string; intensity: number; emotional_impact: string[] };
  178. atmosphericEffects: { haze: number; glare: number; reflections: number; transparency: number };
  179. spatialPerception: { depth_enhancement: number; space_definition: number; focal_guidance: number };
  180. };
  181. // 新增:光比分析
  182. lightingRatio?: {
  183. keyToFill: number;
  184. contrast: number;
  185. description: 'low-contrast' | 'medium-contrast' | 'high-contrast' | 'dramatic';
  186. keyLightIntensity: number;
  187. fillLightIntensity: number;
  188. ratioQuality: 'flat' | 'balanced' | 'dramatic' | 'extreme';
  189. };
  190. // 新增:光占比分析
  191. lightDistribution?: {
  192. natural: number;
  193. artificial: number;
  194. ambient: number;
  195. direct: number;
  196. indirect: number;
  197. dominantType: 'natural' | 'artificial' | 'mixed';
  198. lightingBalance: 'natural-dominant' | 'artificial-dominant' | 'balanced';
  199. };
  200. };
  201. }
  202. // 需求指标接口
  203. interface RequirementMetric {
  204. id: string;
  205. category: 'color' | 'space' | 'material';
  206. name: string;
  207. value: any;
  208. unit?: string;
  209. range?: { min: number; max: number };
  210. description?: string;
  211. }
  212. // 协作评论接口
  213. interface CollaborationComment {
  214. id: string;
  215. author: string;
  216. role: 'customer-service' | 'designer' | 'client';
  217. content: string;
  218. timestamp: Date;
  219. requirementId?: string;
  220. status: 'pending' | 'resolved';
  221. }
  222. // 需求项接口
  223. interface RequirementItem {
  224. id: string;
  225. title: string;
  226. description: string;
  227. priority: 'high' | 'medium' | 'low';
  228. status: 'pending' | 'confirmed' | 'rejected';
  229. tags?: string[];
  230. metrics?: RequirementMetric[];
  231. comments?: CollaborationComment[];
  232. lastUpdated: Date;
  233. showComments?: boolean;
  234. }
  235. // 上传文件接口
  236. interface UploadedFile {
  237. id: string;
  238. name: string;
  239. url: string;
  240. size?: number;
  241. type: 'image' | 'cad' | 'text';
  242. preview?: string;
  243. }
  244. @Component({
  245. selector: 'app-requirements-confirm-card',
  246. standalone: true,
  247. imports: [
  248. CommonModule,
  249. FormsModule,
  250. ReactiveFormsModule,
  251. UploadSuccessModalComponent,
  252. GlobalPromptComponent,
  253. FullReportOverlayComponent,
  254. ColorWheelVisualizerComponent,
  255. FurnitureFormSelectorComponent,
  256. TextureComparisonVisualizerComponent,
  257. PatternVisualizerComponent
  258. ],
  259. providers: [CadAnalysisService],
  260. templateUrl: './requirements-confirm-card.html',
  261. styleUrls: ['./requirements-confirm-card.scss'],
  262. changeDetection: ChangeDetectionStrategy.Default // 确保使用默认变更检测策略
  263. })
  264. export class RequirementsConfirmCardComponent implements OnInit, OnDestroy {
  265. @Input() projectId?: string;
  266. @Output() requirementConfirmed = new EventEmitter<RequirementItem>();
  267. @Output() progressUpdated = new EventEmitter<number>();
  268. @Output() stageCompleted = new EventEmitter<{ stage: string; allStagesCompleted: boolean }>();
  269. @Output() dataUpdated = new EventEmitter<any>(); // 新增:实时数据更新事件
  270. @Output() mappingDataUpdated = new EventEmitter<{
  271. uploadedFiles: any[];
  272. analysisResult: any;
  273. requirementMapping: any;
  274. testSteps: any[];
  275. isAnalyzing: boolean;
  276. isGeneratingMapping: boolean;
  277. }>();
  278. @Output() uploadModalRequested = new EventEmitter<{
  279. show: boolean;
  280. uploadedFiles: any[];
  281. uploadType: string;
  282. colorAnalysisResult?: any;
  283. isAnalyzing: boolean;
  284. }>(); // 新增:需求映射数据更新事件
  285. // 表单
  286. materialForm!: FormGroup;
  287. commentForm!: FormGroup;
  288. materialUploadForm!: FormGroup;
  289. // 数据
  290. materialFiles: MaterialFile[] = [];
  291. materials: MaterialFile[] = [];
  292. requirementMetrics: RequirementMetric[] = [];
  293. collaborationComments: CollaborationComment[] = [];
  294. requirementItems: RequirementItem[] = [];
  295. // 状态
  296. activeTab: 'materials' | 'mapping' | 'collaboration' | 'progress' | 'analysis-summary' = 'materials';
  297. isUploading = false;
  298. isAnalyzing = false;
  299. // 新增:全展示模式
  300. isFullDisplayMode = false;
  301. expandedMaterials: Set<string> = new Set(); // 展开的素材ID集合
  302. dragOver = false;
  303. showConsistencyWarning = false;
  304. warningMessage = '';
  305. // 自动保存相关状态
  306. autoSaveEnabled = true;
  307. lastSaveTime?: Date;
  308. hasUnsavedChanges = false;
  309. isSaving = false;
  310. saveStatus: 'saved' | 'saving' | 'error' | 'unsaved' = 'saved';
  311. // 流程状态
  312. stageCompletionStatus = {
  313. materialAnalysis: false,
  314. collaboration: false,
  315. progressReview: false
  316. };
  317. // 自动保存定时器
  318. private autoSaveTimer?: any;
  319. // 需求指标
  320. colorIndicators = {
  321. mainColor: { r: 255, g: 230, b: 180 },
  322. colorTemperature: 2700,
  323. colorRange: '暖色调',
  324. saturation: 70,
  325. brightness: 80,
  326. contrast: 60
  327. };
  328. spaceIndicators = {
  329. lineRatio: 60,
  330. blankRatio: 30,
  331. flowWidth: 0.9,
  332. aspectRatio: 1.6,
  333. ceilingHeight: 2.8,
  334. lightingLevel: 300
  335. };
  336. materialIndicators = {
  337. fabricRatio: 50,
  338. woodRatio: 30,
  339. metalRatio: 20,
  340. smoothness: 7,
  341. glossiness: 4,
  342. texture: 6
  343. };
  344. // 指标范围配置
  345. indicatorRanges = {
  346. color: {
  347. r: { min: 0, max: 255 },
  348. g: { min: 0, max: 255 },
  349. b: { min: 0, max: 255 },
  350. temperature: { min: 2000, max: 6500 },
  351. saturation: { min: 0, max: 100 },
  352. brightness: { min: 0, max: 100 },
  353. contrast: { min: 0, max: 100 }
  354. },
  355. space: {
  356. lineRatio: { min: 0, max: 100 },
  357. blankRatio: { min: 10, max: 80 },
  358. flowWidth: { min: 0.6, max: 1.5 },
  359. aspectRatio: { min: 1.0, max: 3.0 },
  360. ceilingHeight: { min: 2.4, max: 4.0 },
  361. lightingLevel: { min: 100, max: 800 }
  362. },
  363. material: {
  364. fabricRatio: { min: 0, max: 100 },
  365. woodRatio: { min: 0, max: 100 },
  366. metalRatio: { min: 0, max: 100 },
  367. smoothness: { min: 1, max: 10 },
  368. glossiness: { min: 1, max: 10 },
  369. texture: { min: 1, max: 10 }
  370. }
  371. };
  372. // 预设数据
  373. presetAtmospheres = [
  374. { name: '温馨暖调', rgb: '255,230,180', colorTemp: '2700-3000K', materials: ['木质', '布艺'] },
  375. { name: '现代冷调', rgb: '200,220,240', colorTemp: '5000-6000K', materials: ['金属', '玻璃'] },
  376. { name: '自然清新', rgb: '220,240,220', colorTemp: '4000-4500K', materials: ['竹木', '石材'] }
  377. ];
  378. // 一致性检查
  379. consistencyWarnings: string[] = [];
  380. historyStates: any[] = [];
  381. // 上传成功弹窗相关
  382. showUploadSuccessModal = false;
  383. uploadedFiles: { id: string; name: string; url: string; size?: number; type?: 'image' | 'cad' | 'text'; preview?: string }[] = [];
  384. uploadType: 'image' | 'document' | 'mixed' = 'image';
  385. colorAnalysisResult?: ColorAnalysisResult;
  386. cadAnalysisResult?: CadAnalysisResult;
  387. isAnalyzingColors = false; // 新增:色彩分析状态
  388. // 全局提示组件状态
  389. showGlobalPrompt = false;
  390. promptMode: 'fullscreen' | 'corner' = 'corner';
  391. promptPosition: 'top-right' | 'bottom-right' = 'bottom-right';
  392. promptTitle = '上传成功!';
  393. promptMessage = '';
  394. // 全屏报告覆盖层
  395. showFullReportOverlay = false;
  396. // 需求映射测试相关属性
  397. testSteps = [
  398. { id: 'upload', name: '图片上传', status: 'pending' as 'pending' | 'in-progress' | 'completed' | 'error' },
  399. { id: 'analysis', name: '图片分析', status: 'pending' as 'pending' | 'in-progress' | 'completed' | 'error' },
  400. { id: 'mapping', name: '需求映射', status: 'pending' as 'pending' | 'in-progress' | 'completed' | 'error' },
  401. { id: 'preview', name: '氛围预览', status: 'pending' as 'pending' | 'in-progress' | 'completed' | 'error' }
  402. ];
  403. // 需求映射相关状态
  404. isGeneratingMapping = false;
  405. requirementMapping: RequirementMapping | null = null;
  406. mappingError: string | null = null;
  407. analysisError: string | null = null;
  408. analysisResult: ColorAnalysisResult | undefined = undefined;
  409. // 上传模态框状态
  410. showUploadModal = false;
  411. // 订阅管理
  412. private subscriptions: Subscription[] = [];
  413. constructor(
  414. private fb: FormBuilder,
  415. private cdr: ChangeDetectorRef,
  416. private colorAnalysisService: ColorAnalysisService,
  417. private cadAnalysisService: CadAnalysisService,
  418. private requirementMappingService: RequirementMappingService
  419. ) {}
  420. ngOnInit() {
  421. this.initializeForms();
  422. this.initializeRequirements();
  423. this.loadPresetMetrics();
  424. // 启用自动保存
  425. this.autoSaveEnabled = true;
  426. // 定期检查阶段完成状态
  427. setInterval(() => {
  428. this.checkStageCompletion();
  429. }, 5000);
  430. }
  431. ngOnDestroy(): void {
  432. // 清理自动保存定时器
  433. if (this.autoSaveTimer) {
  434. clearTimeout(this.autoSaveTimer);
  435. }
  436. // 清理订阅
  437. this.subscriptions.forEach(sub => sub.unsubscribe());
  438. // 清理对象URL
  439. this.uploadedFiles.forEach(file => {
  440. if (file.url.startsWith('blob:')) {
  441. URL.revokeObjectURL(file.url);
  442. }
  443. });
  444. }
  445. private initializeForms() {
  446. this.materialForm = this.fb.group({
  447. textContent: ['', Validators.required],
  448. atmosphereDescription: [''],
  449. residentInfo: [''],
  450. scenePreferences: [''],
  451. title: [''],
  452. content: ['']
  453. });
  454. this.commentForm = this.fb.group({
  455. content: ['', Validators.required],
  456. requirementId: ['']
  457. });
  458. this.materialUploadForm = this.fb.group({
  459. file: [''],
  460. textContent: ['', Validators.required]
  461. });
  462. }
  463. private initializeRequirements() {
  464. this.requirementItems = [
  465. {
  466. id: 'color-atmosphere',
  467. title: '色彩氛围',
  468. description: '整体色调和氛围营造',
  469. priority: 'high',
  470. status: 'pending',
  471. lastUpdated: new Date()
  472. },
  473. {
  474. id: 'space-layout',
  475. title: '空间布局',
  476. description: '功能分区和动线设计',
  477. priority: 'high',
  478. status: 'pending',
  479. lastUpdated: new Date()
  480. },
  481. {
  482. id: 'material-selection',
  483. title: '材质选择',
  484. description: '主要材质和质感要求',
  485. priority: 'medium',
  486. status: 'pending',
  487. lastUpdated: new Date()
  488. }
  489. ];
  490. }
  491. private loadPresetMetrics() {
  492. this.requirementMetrics = [
  493. {
  494. id: 'main-color',
  495. category: 'color',
  496. name: '主色调',
  497. value: { r: 255, g: 230, b: 180 },
  498. description: '空间主要色彩'
  499. },
  500. {
  501. id: 'color-temp',
  502. category: 'color',
  503. name: '色温',
  504. value: 3000,
  505. unit: 'K',
  506. range: { min: 2700, max: 6500 },
  507. description: '照明色温范围'
  508. },
  509. {
  510. id: 'wood-ratio',
  511. category: 'material',
  512. name: '木质占比',
  513. value: 60,
  514. unit: '%',
  515. range: { min: 0, max: 100 },
  516. description: '木质材料使用比例'
  517. }
  518. ];
  519. }
  520. // 素材上传功能
  521. onFileSelected(event: Event, type: 'text' | 'image' | 'cad') {
  522. const input = event.target as HTMLInputElement;
  523. if (input.files) {
  524. Array.from(input.files).forEach(file => {
  525. this.uploadFile(file, type);
  526. });
  527. }
  528. }
  529. onFileDrop(event: DragEvent, type: 'text' | 'image' | 'cad') {
  530. event.preventDefault();
  531. this.dragOver = false;
  532. if (event.dataTransfer?.files) {
  533. Array.from(event.dataTransfer.files).forEach(file => {
  534. this.uploadFile(file, type);
  535. });
  536. }
  537. }
  538. onDragOver(event: DragEvent) {
  539. event.preventDefault();
  540. this.dragOver = true;
  541. }
  542. onDragLeave(event: DragEvent) {
  543. event.preventDefault();
  544. this.dragOver = false;
  545. }
  546. private uploadFile(file: File, type: 'text' | 'image' | 'cad') {
  547. this.isUploading = true;
  548. // 模拟文件上传
  549. setTimeout(() => {
  550. const materialFile: MaterialFile = {
  551. id: this.generateId(),
  552. name: file.name,
  553. type: type,
  554. url: URL.createObjectURL(file),
  555. size: this.formatFileSize(file.size),
  556. uploadTime: new Date()
  557. };
  558. this.materialFiles.push(materialFile);
  559. this.materials.push(materialFile);
  560. this.isUploading = false;
  561. // 如果是图片类型,添加到需求映射界面的uploadedFiles数组(支持多图片)
  562. if (type === 'image') {
  563. // 检查是否已存在
  564. const existingIndex = this.uploadedFiles.findIndex(f => f.id === materialFile.id);
  565. if (existingIndex === -1) {
  566. const uploadedFile = {
  567. id: materialFile.id,
  568. name: file.name,
  569. url: materialFile.url || '',
  570. size: file.size,
  571. type: 'image' as const,
  572. preview: materialFile.url || ''
  573. };
  574. this.uploadedFiles.push(uploadedFile);
  575. console.log('✅ 图片已同步到需求映射,当前共', this.uploadedFiles.length, '张');
  576. // 🔥 显示上传成功弹窗并开始色彩分析
  577. this.showUploadSuccessModalAndAnalyze(uploadedFile);
  578. }
  579. } else {
  580. // 非图片类型,保持原有逻辑
  581. this.uploadedFiles = [{
  582. id: materialFile.id,
  583. name: file.name,
  584. url: materialFile.url || '',
  585. size: file.size,
  586. type: type === 'text' ? 'text' : type === 'cad' ? 'cad' : 'image'
  587. }];
  588. }
  589. // 通知父组件显示上传成功弹窗
  590. this.uploadModalRequested.emit({
  591. show: true,
  592. uploadedFiles: this.uploadedFiles,
  593. uploadType: this.uploadType,
  594. colorAnalysisResult: this.colorAnalysisResult,
  595. isAnalyzing: this.isAnalyzingColors
  596. });
  597. this.uploadType = type === 'text' ? 'document' : type === 'image' ? 'image' : 'mixed';
  598. // 自动解析(素材分析用)
  599. this.analyzeMaterial(materialFile);
  600. }, 1000);
  601. }
  602. // 文本提交
  603. onTextSubmit(): void {
  604. if (this.materialUploadForm.valid) {
  605. const formValue = this.materialUploadForm.value;
  606. const textMaterial: MaterialFile = {
  607. id: this.generateId(),
  608. name: '文本需求',
  609. type: 'text',
  610. content: formValue.textContent,
  611. uploadTime: new Date(),
  612. size: this.formatFileSize(formValue.textContent?.length || 0)
  613. };
  614. this.materialFiles.push(textMaterial);
  615. this.materials.push(textMaterial);
  616. this.analyzeMaterial(textMaterial);
  617. this.materialUploadForm.reset();
  618. }
  619. }
  620. // 素材解析功能
  621. private analyzeMaterial(material: MaterialFile): void {
  622. this.isAnalyzing = true;
  623. // CAD采用服务分析,其它类型保持模拟
  624. if (material.type === 'cad') {
  625. const fileUrl = material.url || '';
  626. this.cadAnalysisService.analyzeByUrl(fileUrl, material.name).subscribe({
  627. next: (result) => {
  628. this.cadAnalysisResult = result;
  629. const analysis: MaterialAnalysis = {
  630. structuralElements: result.structuralElements,
  631. spaceMetrics: result.spaceMetrics,
  632. flowMetrics: result.flowMetrics
  633. };
  634. material.analysis = analysis;
  635. this.isAnalyzing = false;
  636. this.updateRequirementsFromAnalysis(analysis);
  637. },
  638. error: () => {
  639. this.cadAnalysisService.simulateCadAnalysis(material.name).subscribe({
  640. next: (mock) => {
  641. this.cadAnalysisResult = mock;
  642. const analysis: MaterialAnalysis = {
  643. structuralElements: mock.structuralElements,
  644. spaceMetrics: mock.spaceMetrics,
  645. flowMetrics: mock.flowMetrics
  646. };
  647. material.analysis = analysis;
  648. this.isAnalyzing = false;
  649. this.updateRequirementsFromAnalysis(analysis);
  650. },
  651. error: () => {
  652. this.isAnalyzing = false;
  653. console.error('CAD分析失败');
  654. }
  655. });
  656. }
  657. });
  658. return;
  659. }
  660. // 非CAD类型模拟
  661. setTimeout(() => {
  662. let analysis: MaterialAnalysis = {};
  663. switch (material.type) {
  664. case 'text':
  665. analysis = this.analyzeTextMaterial(material);
  666. break;
  667. case 'image':
  668. analysis = this.analyzeImageMaterial(material);
  669. break;
  670. }
  671. material.analysis = analysis;
  672. this.isAnalyzing = false;
  673. this.updateRequirementsFromAnalysis(analysis);
  674. }, 1200);
  675. }
  676. private analyzeTextMaterial(material: MaterialFile): MaterialAnalysis {
  677. return {
  678. atmosphere: {
  679. description: '温馨暖调',
  680. rgb: '255,230,180',
  681. colorTemp: '2700-3000K'
  682. },
  683. residents: {
  684. type: '亲子家庭',
  685. details: '孩子年龄3-6岁'
  686. },
  687. scenes: {
  688. preference: '瑜伽爱好者',
  689. requirements: '需要瑜伽区收纳'
  690. },
  691. keywords: {
  692. positive: ['科技感', '温馨', '实用'],
  693. negative: ['复杂线条', '冷色调']
  694. }
  695. };
  696. }
  697. private analyzeImageMaterial(material: MaterialFile): MaterialAnalysis {
  698. return {
  699. // 基础色彩数据
  700. mainColors: [
  701. { hex: '#FFE6B4', rgb: { r: 255, g: 230, b: 180 }, percentage: 45, name: '暖木色' },
  702. { hex: '#C8B4A0', rgb: { r: 200, g: 180, b: 160 }, percentage: 30, name: '米色' },
  703. { hex: '#B4A08C', rgb: { r: 180, g: 160, b: 140 }, percentage: 25, name: '浅棕' }
  704. ],
  705. colorTemperature: '3000K',
  706. materialRatio: [
  707. { material: '木质', percentage: 60 },
  708. { material: '布艺', percentage: 25 },
  709. { material: '金属', percentage: 15 }
  710. ],
  711. spaceRatio: 35,
  712. // 增强色彩分析
  713. enhancedColorAnalysis: {
  714. colorWheel: {
  715. primaryHue: 35,
  716. saturation: 65,
  717. brightness: 85,
  718. dominantColors: [
  719. { hue: 35, saturation: 65, brightness: 85, percentage: 45 },
  720. { hue: 30, saturation: 50, brightness: 75, percentage: 30 },
  721. { hue: 25, saturation: 55, brightness: 70, percentage: 25 }
  722. ],
  723. colorDistribution: '暖色调为主,分布均衡'
  724. },
  725. colorHarmony: {
  726. harmonyType: '类比色',
  727. harmonyScore: 85,
  728. complementaryColors: ['#4A90E2', '#5FA3E8'],
  729. suggestions: ['可添加蓝色系装饰增强对比', '保持暖色调主导']
  730. },
  731. colorTemperatureAnalysis: {
  732. kelvin: 3000,
  733. warmCoolBalance: 75,
  734. description: '温暖舒适',
  735. lightingRecommendations: ['建议使用暖白光源', '可配合自然光']
  736. },
  737. colorPsychology: {
  738. primaryMood: '温馨放松',
  739. atmosphere: '家庭温暖',
  740. psychologicalEffects: ['促进放松', '增强归属感', '营造安全感'],
  741. suitableSpaces: ['客厅', '卧室', '休闲区']
  742. }
  743. },
  744. // 形体分析
  745. formAnalysis: {
  746. lineAnalysis: {
  747. dominantLines: [
  748. { type: '直线', percentage: 60, characteristics: ['简洁', '现代'] },
  749. { type: '曲线', percentage: 30, characteristics: ['柔和', '优雅'] },
  750. { type: '斜线', percentage: 10, characteristics: ['动感'] }
  751. ],
  752. lineQuality: { smoothness: 85, precision: 90, expressiveness: 75 },
  753. visualFlow: { direction: '水平为主', rhythm: '平稳', continuity: 80 }
  754. },
  755. geometryAnalysis: {
  756. primaryShapes: [
  757. { shape: '矩形', percentage: 55, characteristics: ['稳定', '规整'] },
  758. { shape: '圆形', percentage: 30, characteristics: ['柔和', '完整'] },
  759. { shape: '不规则', percentage: 15, characteristics: ['自然'] }
  760. ],
  761. complexity: '中等',
  762. symmetry: { type: '对称', score: 75 },
  763. balance: { visual: 80, compositional: 85 }
  764. },
  765. proportionAnalysis: {
  766. aspectRatio: 1.618,
  767. goldenRatio: 0.85,
  768. proportionHarmony: 80,
  769. scaleRelationships: [
  770. { element: '家具', scale: '1:1.5', relationship: '协调' },
  771. { element: '装饰', scale: '1:3', relationship: '点缀' }
  772. ]
  773. },
  774. overallAssessment: {
  775. formComplexity: 65,
  776. visualImpact: 75,
  777. functionalSuitability: 85,
  778. aestheticAppeal: 80
  779. }
  780. },
  781. // 质感分析
  782. textureAnalysis: {
  783. surfaceProperties: {
  784. roughness: { value: 45, level: '中等粗糙', description: '自然木纹质感' },
  785. glossiness: { value: 35, level: '哑光', reflectivity: 25 },
  786. transparency: { value: 10, level: '不透明' },
  787. porosity: { value: 30, level: '中等' }
  788. },
  789. tactilePredict: {
  790. temperature: { perceived: '温暖', thermalConductivity: 0.15 },
  791. hardness: { level: '中硬', value: 60 },
  792. flexibility: { level: '刚性', value: 20 },
  793. weight: { perceived: '中等', density: 0.6 },
  794. comfort: { tactileComfort: 75, ergonomicSuitability: 80 }
  795. },
  796. materialClassification: {
  797. primaryMaterial: { category: '木材', subcategory: '实木', confidence: 85 },
  798. secondaryMaterials: [
  799. { category: '布艺', percentage: 25, confidence: 70 },
  800. { category: '金属', percentage: 15, confidence: 60 }
  801. ],
  802. materialProperties: { durability: 80, maintenance: '中等', sustainability: 75, costLevel: '中高' }
  803. },
  804. textureQuality: {
  805. overallQuality: 85,
  806. consistency: 80,
  807. authenticity: 90,
  808. visualAppeal: 85,
  809. functionalSuitability: 80,
  810. ageingCharacteristics: { wearResistance: 75, patinaPotential: 60, maintenanceNeeds: ['定期清洁', '防潮处理'] }
  811. }
  812. },
  813. // 纹理分析
  814. patternAnalysis: {
  815. patternRecognition: {
  816. primaryPatterns: [
  817. { type: '木纹', confidence: 90, coverage: 60, characteristics: ['自然', '有机'] },
  818. { type: '编织', confidence: 75, coverage: 25, characteristics: ['规律', '几何'] },
  819. { type: '金属拉丝', confidence: 70, coverage: 15, characteristics: ['线性', '现代'] }
  820. ],
  821. patternComplexity: { level: '中等', score: 65, elements: 3 },
  822. patternScale: { size: '中等', uniformity: 70, variation: 30 }
  823. },
  824. repetitionAnalysis: {
  825. repetitionType: { primary: '有机重复', pattern: '自然纹理', consistency: 60 },
  826. spacing: { horizontal: 50, vertical: 50, uniformity: 70, rhythm: '平稳' },
  827. symmetry: { type: '近似对称', strength: 60, axes: 1 },
  828. tiling: { seamless: false, quality: 75, edgeHandling: '自然过渡' }
  829. },
  830. textureClassification: {
  831. textureFamily: { primary: '木质纹理', subcategory: '硬木', confidence: 85 },
  832. surfaceCharacter: { tactileQuality: '细腻', visualDepth: 70, dimensionality: '中等立体' },
  833. materialSuggestion: { likelyMaterials: ['橡木', '胡桃木'], fabricationMethod: ['实木加工', '贴面'], applicationSuitability: ['家具', '地板', '墙面'] }
  834. },
  835. visualRhythm: {
  836. rhythmType: { primary: '有机节奏', intensity: 65, tempo: '平稳' },
  837. movement: { direction: '纵向', flow: 70, energy: 55 },
  838. emphasis: { focalPoints: 2, contrast: 60, hierarchy: 65 },
  839. harmony: { overall: 80, balance: 75, unity: 85 }
  840. }
  841. },
  842. // 灯光分析
  843. lightingAnalysis: {
  844. lightSourceIdentification: {
  845. primarySources: [
  846. { type: '自然光', subtype: '侧窗光', position: { direction: '左侧', angle: 45, distance: '2-3m' }, intensity: 70, confidence: 85 },
  847. { type: '人工光', subtype: '顶灯', position: { direction: '正上方', angle: 90, distance: '2.5m' }, intensity: 50, confidence: 75 }
  848. ],
  849. lightingSetup: { complexity: '简单', sourceCount: 2, dominantSource: '自然光', lightingStyle: '自然柔和' }
  850. },
  851. illuminationAnalysis: {
  852. brightness: { overall: 65, distribution: '均匀', dynamicRange: 60, exposure: '适中' },
  853. contrast: { level: 60, type: '中等对比', areas: { highlights: 80, midtones: 65, shadows: 40 } },
  854. colorTemperature: { kelvin: 3000, warmth: '温暖', consistency: 75, mixedLighting: true },
  855. lightQuality: { softness: 75, diffusion: 80, directionality: 55, evenness: 70 }
  856. },
  857. shadowAnalysis: {
  858. shadowPresence: { coverage: 35, intensity: 50, sharpness: '柔和', definition: 60 },
  859. shadowCharacteristics: { direction: '右下', length: '中等', density: 50, falloff: '渐变' },
  860. shadowTypes: [
  861. { type: 'cast', prominence: 60, contribution: '主要阴影' },
  862. { type: 'form', prominence: 40, contribution: '体积感' }
  863. ],
  864. dimensionalEffect: { depth: 70, volume: 65, threedimensionality: 70 }
  865. },
  866. ambientAnalysis: {
  867. ambientLevel: { strength: 60, uniformity: 75, contribution: 50 },
  868. lightingMood: { primary: '温馨舒适', intensity: 70, emotional_impact: ['放松', '温暖', '自然'] },
  869. atmosphericEffects: { haze: 10, glare: 15, reflections: 40, transparency: 90 },
  870. spatialPerception: { depth_enhancement: 65, space_definition: 70, focal_guidance: 60 }
  871. },
  872. lightingRatio: {
  873. keyToFill: 3,
  874. contrast: 60,
  875. description: 'medium-contrast',
  876. keyLightIntensity: 75,
  877. fillLightIntensity: 25,
  878. ratioQuality: 'balanced'
  879. },
  880. lightDistribution: {
  881. natural: 60,
  882. artificial: 40,
  883. ambient: 50,
  884. direct: 30,
  885. indirect: 70,
  886. dominantType: 'natural',
  887. lightingBalance: 'natural-dominant'
  888. }
  889. }
  890. };
  891. }
  892. private analyzeCADMaterial(material: MaterialFile): MaterialAnalysis {
  893. return {
  894. structuralElements: [
  895. { type: '承重柱', position: '客厅中央', changeable: false },
  896. { type: '门窗', position: '南墙', changeable: false }
  897. ],
  898. spaceMetrics: [
  899. { room: '客厅', ratio: '16:9', width: '4.2m' },
  900. { room: '卧室', ratio: '4:3', width: '3.6m' }
  901. ],
  902. flowMetrics: [
  903. { area: '主通道', width: '1.2m', compliance: true },
  904. { area: '次通道', width: '0.8m', compliance: false }
  905. ]
  906. };
  907. }
  908. private updateRequirementsFromAnalysis(analysis: MaterialAnalysis) {
  909. if (analysis.atmosphere?.rgb) {
  910. const colorMetric = this.requirementMetrics.find(m => m.id === 'main-color');
  911. if (colorMetric) {
  912. const [r, g, b] = analysis.atmosphere.rgb.split(',').map(Number);
  913. colorMetric.value = { r, g, b };
  914. }
  915. }
  916. if (analysis.materialRatio) {
  917. const woodRatio = analysis.materialRatio.find(m => m.material === '木质');
  918. if (woodRatio) {
  919. const woodMetric = this.requirementMetrics.find(m => m.id === 'wood-ratio');
  920. if (woodMetric) {
  921. woodMetric.value = woodRatio.percentage;
  922. }
  923. }
  924. }
  925. }
  926. // 需求确认功能
  927. confirmRequirement(requirementId: string) {
  928. // 检查是否可以进行需求确认操作
  929. if (!this.canProceedToNextStage('materialAnalysis')) {
  930. window?.fmode?.alert('请先完成素材分析阶段的所有必要操作');
  931. return;
  932. }
  933. const requirement = this.requirementItems.find(r => r.id === requirementId);
  934. if (requirement) {
  935. requirement.status = 'confirmed';
  936. requirement.lastUpdated = new Date();
  937. this.requirementConfirmed.emit(requirement);
  938. this.updateProgress();
  939. this.triggerAutoSave();
  940. // 检查阶段完成状态
  941. this.checkStageCompletion();
  942. }
  943. }
  944. rejectRequirement(requirementId: string, reason?: string) {
  945. // 检查是否可以进行需求拒绝操作
  946. if (!this.canProceedToNextStage('materialAnalysis')) {
  947. window?.fmode?.alert('请先完成素材分析阶段的所有必要操作');
  948. return;
  949. }
  950. const requirement = this.requirementItems.find(r => r.id === requirementId);
  951. if (requirement) {
  952. requirement.status = 'rejected';
  953. requirement.lastUpdated = new Date();
  954. if (reason) {
  955. this.addCommentToRequirement(requirementId, reason, 'system');
  956. }
  957. this.updateProgress();
  958. this.triggerAutoSave();
  959. // 检查阶段完成状态
  960. this.checkStageCompletion();
  961. }
  962. }
  963. // 协作功能
  964. addComment() {
  965. if (this.commentForm.valid) {
  966. const comment: CollaborationComment = {
  967. id: this.generateId(),
  968. author: '当前用户',
  969. role: 'designer',
  970. content: this.commentForm.value.content,
  971. timestamp: new Date(),
  972. requirementId: this.commentForm.value.requirementId,
  973. status: 'pending'
  974. };
  975. this.collaborationComments.push(comment);
  976. this.commentForm.reset();
  977. this.triggerAutoSave();
  978. // 检查阶段完成状态
  979. this.checkStageCompletion();
  980. }
  981. }
  982. resolveComment(commentId: string) {
  983. const comment = this.collaborationComments.find(c => c.id === commentId);
  984. if (comment) {
  985. comment.status = 'resolved';
  986. this.triggerAutoSave();
  987. // 检查阶段完成状态
  988. this.checkStageCompletion();
  989. }
  990. }
  991. // 进度管理
  992. private updateProgress() {
  993. const totalRequirements = this.requirementItems.length;
  994. const confirmedRequirements = this.requirementItems.filter(r => r.status === 'confirmed').length;
  995. const progress = totalRequirements > 0 ? (confirmedRequirements / totalRequirements) * 100 : 0;
  996. // 实时更新进度条
  997. this.updateProgressBar(progress);
  998. this.progressUpdated.emit(progress);
  999. // 检查是否完成所有需求
  1000. if (progress === 100) {
  1001. this.onRequirementCommunicationComplete();
  1002. }
  1003. }
  1004. private updateProgressBar(progress: number): void {
  1005. // 更新进度条显示
  1006. const progressBar = document.querySelector('.progress-bar-fill') as HTMLElement;
  1007. if (progressBar) {
  1008. progressBar.style.width = `${progress}%`;
  1009. }
  1010. // 更新进度文本
  1011. const progressText = document.querySelector('.progress-text') as HTMLElement;
  1012. if (progressText) {
  1013. progressText.textContent = `${Math.round(progress)}%`;
  1014. }
  1015. // 添加进度动画效果
  1016. this.animateProgressUpdate(progress);
  1017. }
  1018. private animateProgressUpdate(progress: number): void {
  1019. // 添加进度更新的视觉反馈
  1020. const progressContainer = document.querySelector('.progress-container') as HTMLElement;
  1021. if (progressContainer) {
  1022. progressContainer.classList.add('progress-updated');
  1023. setTimeout(() => {
  1024. progressContainer.classList.remove('progress-updated');
  1025. }, 500);
  1026. }
  1027. }
  1028. // 需求沟通阶段完成处理
  1029. private onRequirementCommunicationComplete(): void {
  1030. console.log('需求沟通阶段完成,开始同步关键信息');
  1031. this.syncKeyInfoToSolutionConfirmation();
  1032. }
  1033. // 同步关键信息到方案确认阶段
  1034. private syncKeyInfoToSolutionConfirmation(): void {
  1035. const keyInfo = {
  1036. colorAtmosphere: {
  1037. mainColor: this.colorIndicators.mainColor,
  1038. colorTemperature: this.colorIndicators.colorTemperature,
  1039. saturation: this.colorIndicators.saturation,
  1040. brightness: this.colorIndicators.brightness
  1041. },
  1042. spaceStructure: {
  1043. lineRatio: this.spaceIndicators.lineRatio,
  1044. blankRatio: this.spaceIndicators.blankRatio,
  1045. flowWidth: this.spaceIndicators.flowWidth
  1046. },
  1047. materialWeights: {
  1048. fabricRatio: this.materialIndicators.fabricRatio,
  1049. woodRatio: this.materialIndicators.woodRatio,
  1050. metalRatio: this.materialIndicators.metalRatio,
  1051. smoothness: this.materialIndicators.smoothness
  1052. },
  1053. presetAtmosphere: this.getSelectedPresetAtmosphere()
  1054. };
  1055. // 触发同步事件
  1056. this.requirementConfirmed.emit({
  1057. id: 'requirement-sync',
  1058. title: '需求沟通完成',
  1059. description: '关键信息已同步至方案确认阶段',
  1060. priority: 'high',
  1061. status: 'confirmed',
  1062. lastUpdated: new Date(),
  1063. metrics: this.convertToMetrics(keyInfo)
  1064. });
  1065. // 启动交付执行流程
  1066. setTimeout(() => {
  1067. this.startDeliveryExecution();
  1068. }, 1000);
  1069. }
  1070. private getSelectedPresetAtmosphere(): any {
  1071. // 根据当前颜色指标找到最匹配的预设氛围
  1072. const currentRgb = `${this.colorIndicators.mainColor.r},${this.colorIndicators.mainColor.g},${this.colorIndicators.mainColor.b}`;
  1073. return this.presetAtmospheres.find(preset => preset.rgb === currentRgb) || this.presetAtmospheres[0];
  1074. }
  1075. private convertToMetrics(keyInfo: any): RequirementMetric[] {
  1076. return [
  1077. {
  1078. id: 'color-sync',
  1079. category: 'color',
  1080. name: '色彩氛围',
  1081. value: keyInfo.colorAtmosphere
  1082. },
  1083. {
  1084. id: 'space-sync',
  1085. category: 'space',
  1086. name: '空间结构',
  1087. value: keyInfo.spaceStructure
  1088. },
  1089. {
  1090. id: 'material-sync',
  1091. category: 'material',
  1092. name: '材质权重',
  1093. value: keyInfo.materialWeights
  1094. }
  1095. ];
  1096. }
  1097. // 启动交付执行流程
  1098. private startDeliveryExecution(): void {
  1099. console.log('启动交付执行流程');
  1100. // 显示执行启动提示
  1101. this.showExecutionStartNotification();
  1102. // 这里可以触发路由跳转或其他业务逻辑
  1103. // 例如:this.router.navigate(['/project', this.projectId, 'execution']);
  1104. }
  1105. private showExecutionStartNotification(): void {
  1106. // 显示执行流程启动的通知
  1107. const notification = document.createElement('div');
  1108. notification.className = 'execution-notification';
  1109. notification.innerHTML = `
  1110. <div class="notification-content">
  1111. <svg viewBox="0 0 24 24" fill="currentColor">
  1112. <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
  1113. </svg>
  1114. <span>交付执行流程已启动</span>
  1115. </div>
  1116. `;
  1117. document.body.appendChild(notification);
  1118. setTimeout(() => {
  1119. notification.remove();
  1120. }, 3000);
  1121. }
  1122. getProgressPercentage(): number {
  1123. if (this.requirementItems.length === 0) return 0;
  1124. const confirmedCount = this.requirementItems.filter(r => r.status === 'confirmed').length;
  1125. return Math.round((confirmedCount / this.requirementItems.length) * 100);
  1126. }
  1127. // 处理优先级更新
  1128. onPriorityChange(requirementId: string, event: Event): void {
  1129. const target = event.target as HTMLSelectElement;
  1130. this.updateRequirementPriority(requirementId, target.value as 'high' | 'medium' | 'low');
  1131. }
  1132. // 检查需求是否有待处理评论
  1133. hasUnreadComments(requirementId: string): boolean {
  1134. return this.getCommentsForRequirement(requirementId).some(c => c.status === 'pending');
  1135. }
  1136. // 处理历史状态选择
  1137. onHistoryStateChange(event: Event): void {
  1138. const target = event.target as HTMLSelectElement;
  1139. const index = +target.value;
  1140. if (index >= 0) {
  1141. this.restoreHistoryState(index);
  1142. }
  1143. }
  1144. // 获取指定状态的需求数量
  1145. getRequirementCountByStatus(status: 'confirmed' | 'pending' | 'rejected'): number {
  1146. return (this.requirementItems || []).filter(r => r.status === status).length;
  1147. }
  1148. // 获取状态百分比
  1149. getStatusPercentage(status: 'confirmed' | 'pending' | 'rejected'): number {
  1150. const total = this.requirementItems.length;
  1151. if (total === 0) return 0;
  1152. const statusCount = this.getRequirementCountByStatus(status);
  1153. return Math.round((statusCount / total) * 100);
  1154. }
  1155. // 指标映射功能
  1156. updateMetricValue(metricId: string, value: any) {
  1157. const metric = this.requirementMetrics.find(m => m.id === metricId);
  1158. if (metric) {
  1159. metric.value = value;
  1160. this.checkConsistency();
  1161. }
  1162. }
  1163. // 滑动条数值同步方法
  1164. onSliderChange(key: string, value: number): void {
  1165. console.log(`滑动条变化: ${key} = ${value}`);
  1166. console.log('变化前的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  1167. // 直接更新数据,不需要额外的updateIndicatorValue调用
  1168. // 因为使用了双向绑定,数据已经自动更新
  1169. if (key === 'r' || key === 'g' || key === 'b') {
  1170. // 确保RGB值在有效范围内
  1171. const range = this.getIndicatorRange(key);
  1172. if (range) {
  1173. const clampedValue = Math.max(range.min, Math.min(range.max, value));
  1174. this.colorIndicators.mainColor[key as keyof typeof this.colorIndicators.mainColor] = clampedValue;
  1175. console.log(`RGB值已更新: ${key} = ${clampedValue}`);
  1176. console.log('变化后的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  1177. }
  1178. // 触发颜色指标更新
  1179. this.updateColorIndicator('mainColor', this.colorIndicators.mainColor);
  1180. } else {
  1181. // 处理其他颜色指标
  1182. this.updateIndicatorValue(key, value);
  1183. }
  1184. this.triggerAutoSave(); // 触发自动保存
  1185. this.checkStageCompletion(); // 检查阶段完成状态
  1186. // 发射实时数据更新事件
  1187. this.emitDataUpdate();
  1188. // 强制触发变更检测
  1189. this.cdr.detectChanges();
  1190. console.log('滑动条变更检测已触发');
  1191. }
  1192. onInputChange(key: string, value: number): void {
  1193. console.log(`输入框变化: ${key} = ${value}`);
  1194. console.log('变化前的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  1195. // 直接更新数据,不需要额外的updateIndicatorValue调用
  1196. // 因为使用了双向绑定,数据已经自动更新
  1197. if (key === 'r' || key === 'g' || key === 'b') {
  1198. // 确保RGB值在有效范围内
  1199. const range = this.getIndicatorRange(key);
  1200. if (range) {
  1201. const clampedValue = Math.max(range.min, Math.min(range.max, value));
  1202. this.colorIndicators.mainColor[key as keyof typeof this.colorIndicators.mainColor] = clampedValue;
  1203. console.log(`RGB值已更新: ${key} = ${clampedValue}`);
  1204. console.log('变化后的mainColor:', JSON.stringify(this.colorIndicators.mainColor));
  1205. }
  1206. // 触发颜色指标更新
  1207. this.updateColorIndicator('mainColor', this.colorIndicators.mainColor);
  1208. } else {
  1209. // 处理其他颜色指标
  1210. this.updateIndicatorValue(key, value);
  1211. }
  1212. this.triggerAutoSave();
  1213. // 发射实时数据更新事件
  1214. this.emitDataUpdate();
  1215. // 强制触发变更检测
  1216. this.cdr.detectChanges();
  1217. console.log('输入框变更检测已触发');
  1218. }
  1219. validateInput(key: string, value: string): void {
  1220. const numValue = parseFloat(value);
  1221. if (isNaN(numValue)) {
  1222. // 如果输入无效,恢复原值
  1223. this.restoreIndicatorValue(key);
  1224. return;
  1225. }
  1226. const range = this.getIndicatorRange(key);
  1227. if (range) {
  1228. const clampedValue = Math.max(range.min, Math.min(range.max, numValue));
  1229. this.updateIndicatorValue(key, clampedValue);
  1230. }
  1231. }
  1232. private updateIndicatorValue(key: string, value: number): void {
  1233. console.log(`updateIndicatorValue调用: ${key} = ${value}`);
  1234. // 更新颜色指标
  1235. if (key in this.colorIndicators) {
  1236. if (key === 'r' || key === 'g' || key === 'b') {
  1237. // 创建新的mainColor对象以确保变更检测
  1238. const oldColor = { ...this.colorIndicators.mainColor };
  1239. this.colorIndicators.mainColor = {
  1240. ...this.colorIndicators.mainColor,
  1241. [key]: value
  1242. };
  1243. console.log(`RGB更新: ${key}从${oldColor[key as keyof typeof oldColor]}变为${value}`,
  1244. '新mainColor:', this.colorIndicators.mainColor);
  1245. this.updateColorIndicator('mainColor', this.colorIndicators.mainColor);
  1246. } else {
  1247. (this.colorIndicators as any)[key] = value;
  1248. this.updateColorIndicator(key, value);
  1249. }
  1250. return;
  1251. }
  1252. // 更新空间指标
  1253. if (key in this.spaceIndicators) {
  1254. (this.spaceIndicators as any)[key] = value;
  1255. this.updateSpaceIndicator(key, value);
  1256. return;
  1257. }
  1258. // 更新材质指标
  1259. if (key in this.materialIndicators) {
  1260. (this.materialIndicators as any)[key] = value;
  1261. this.updateMaterialIndicator(key, value);
  1262. return;
  1263. }
  1264. }
  1265. private restoreIndicatorValue(key: string): void {
  1266. // 这里可以从历史状态或默认值恢复
  1267. console.log(`恢复指标值: ${key}`);
  1268. }
  1269. private getIndicatorRange(key: string): { min: number; max: number } | null {
  1270. // 检查颜色范围
  1271. if (key === 'r' || key === 'g' || key === 'b') {
  1272. return this.indicatorRanges.color[key as keyof typeof this.indicatorRanges.color];
  1273. }
  1274. if (key in this.indicatorRanges.color) {
  1275. return (this.indicatorRanges.color as any)[key];
  1276. }
  1277. // 检查空间范围
  1278. if (key in this.indicatorRanges.space) {
  1279. return (this.indicatorRanges.space as any)[key];
  1280. }
  1281. // 检查材质范围
  1282. if (key in this.indicatorRanges.material) {
  1283. return (this.indicatorRanges.material as any)[key];
  1284. }
  1285. return null;
  1286. }
  1287. // 指标更新方法
  1288. updateColorIndicator(type: string, value?: any): void {
  1289. switch (type) {
  1290. case 'mainColor':
  1291. if (value && typeof value === 'object' && 'r' in value) {
  1292. this.colorIndicators.mainColor = { ...value }; // 创建新对象以触发变更检测
  1293. console.log('mainColor更新后:', this.colorIndicators.mainColor);
  1294. }
  1295. break;
  1296. case 'colorTemperature':
  1297. // 色温更新时不需要改变颜色值,只是触发一致性检查
  1298. break;
  1299. case 'saturation':
  1300. // 饱和度更新时不需要改变颜色值,只是触发一致性检查
  1301. break;
  1302. }
  1303. console.log(`更新颜色指示器 ${type}:`, value, '当前RGB:', this.getRgbString());
  1304. this.checkConsistency();
  1305. this.updatePreview();
  1306. // 强制触发变更检测
  1307. this.cdr.detectChanges();
  1308. console.log('变更检测已触发');
  1309. }
  1310. updateSpaceIndicator(key: string, value: number) {
  1311. if (key in this.spaceIndicators) {
  1312. (this.spaceIndicators as any)[key] = value;
  1313. this.checkConsistency();
  1314. }
  1315. }
  1316. updateMaterialIndicator(key: string, value: number) {
  1317. if (key in this.materialIndicators) {
  1318. (this.materialIndicators as any)[key] = value;
  1319. this.checkConsistency();
  1320. this.normalizeMaterialRatios();
  1321. }
  1322. }
  1323. // 材质比例归一化
  1324. private normalizeMaterialRatios() {
  1325. const total = this.materialIndicators.fabricRatio +
  1326. this.materialIndicators.woodRatio +
  1327. this.materialIndicators.metalRatio;
  1328. if (total > 100) {
  1329. const scale = 100 / total;
  1330. this.materialIndicators.fabricRatio = Math.round(this.materialIndicators.fabricRatio * scale);
  1331. this.materialIndicators.woodRatio = Math.round(this.materialIndicators.woodRatio * scale);
  1332. this.materialIndicators.metalRatio = 100 - this.materialIndicators.fabricRatio - this.materialIndicators.woodRatio;
  1333. }
  1334. }
  1335. // 预览更新
  1336. private updatePreview() {
  1337. // 移除直接DOM操作,依赖Angular的属性绑定
  1338. console.log('updatePreview调用,当前RGB:', this.getRgbString());
  1339. // 不再直接操作DOM,让Angular的变更检测处理
  1340. }
  1341. // 获取RGB字符串
  1342. getRgbString(): string {
  1343. const { r, g, b } = this.colorIndicators.mainColor;
  1344. const rgbString = `rgb(${r}, ${g}, ${b})`;
  1345. console.log('getRgbString调用:', rgbString, '完整mainColor对象:', this.colorIndicators.mainColor);
  1346. return rgbString;
  1347. }
  1348. // 获取色温描述
  1349. getColorTemperatureDescription(): string {
  1350. const temp = this.colorIndicators.colorTemperature;
  1351. if (temp < 3000) return '暖色调';
  1352. if (temp < 4000) return '中性色调';
  1353. if (temp < 5000) return '自然色调';
  1354. return '冷色调';
  1355. }
  1356. applyPresetAtmosphere(preset: any) {
  1357. const rgbMatch = preset.rgb.match(/(\d+),(\d+),(\d+)/);
  1358. if (rgbMatch) {
  1359. this.colorIndicators.mainColor = {
  1360. r: parseInt(rgbMatch[1]),
  1361. g: parseInt(rgbMatch[2]),
  1362. b: parseInt(rgbMatch[3])
  1363. };
  1364. }
  1365. const tempMatch = preset.colorTemp.match(/(\d+)/);
  1366. if (tempMatch) {
  1367. this.colorIndicators.colorTemperature = parseInt(tempMatch[1]);
  1368. }
  1369. if (preset.materials.includes('木质')) {
  1370. this.materialIndicators.woodRatio = 60;
  1371. this.materialIndicators.fabricRatio = 30;
  1372. this.materialIndicators.metalRatio = 10;
  1373. } else if (preset.materials.includes('金属')) {
  1374. this.materialIndicators.metalRatio = 50;
  1375. this.materialIndicators.woodRatio = 20;
  1376. this.materialIndicators.fabricRatio = 30;
  1377. }
  1378. this.updatePreview();
  1379. this.checkConsistency();
  1380. }
  1381. // 一致性检查
  1382. private checkConsistency() {
  1383. this.consistencyWarnings = [];
  1384. if (this.colorIndicators.colorTemperature < 3000 &&
  1385. this.colorIndicators.mainColor.r > 200 &&
  1386. this.colorIndicators.mainColor.g < 150) {
  1387. this.consistencyWarnings.push('暖调氛围与冷色调RGB值存在矛盾');
  1388. }
  1389. if (this.materialIndicators.fabricRatio > 70 && this.colorIndicators.colorTemperature > 5000) {
  1390. this.consistencyWarnings.push('高布艺占比与冷色调可能不协调');
  1391. }
  1392. if (this.spaceIndicators.lineRatio > 80 && this.materialIndicators.woodRatio > 60) {
  1393. this.consistencyWarnings.push('高直线条占比与高木质占比可能过于刚硬');
  1394. }
  1395. }
  1396. // 协作批注功能
  1397. addCommentToRequirement(requirementId: string, content: string, author: string = '当前用户'): void {
  1398. const comment: CollaborationComment = {
  1399. id: this.generateId(),
  1400. author,
  1401. role: 'designer',
  1402. content,
  1403. timestamp: new Date(),
  1404. requirementId,
  1405. status: 'pending'
  1406. };
  1407. this.collaborationComments.push(comment);
  1408. this.updateProgress();
  1409. }
  1410. // 优先级排序功能
  1411. updateRequirementPriority(requirementId: string, priority: 'high' | 'medium' | 'low'): void {
  1412. const requirement = this.requirementItems.find(r => r.id === requirementId);
  1413. if (requirement) {
  1414. requirement.priority = priority;
  1415. requirement.lastUpdated = new Date();
  1416. this.sortRequirementsByPriority();
  1417. }
  1418. }
  1419. sortRequirementsByPriority(): void {
  1420. const priorityOrder = { 'high': 3, 'medium': 2, 'low': 1 };
  1421. this.requirementItems.sort((a, b) => {
  1422. return priorityOrder[b.priority] - priorityOrder[a.priority];
  1423. });
  1424. }
  1425. // 历史记录功能
  1426. saveCurrentState(): void {
  1427. const currentState = {
  1428. timestamp: new Date(),
  1429. colorIndicators: { ...this.colorIndicators },
  1430. spaceIndicators: { ...this.spaceIndicators },
  1431. materialIndicators: { ...this.materialIndicators },
  1432. requirementItems: this.requirementItems.map((r: RequirementItem) => ({ ...r })),
  1433. author: '当前用户'
  1434. };
  1435. this.historyStates.push(currentState);
  1436. if (this.historyStates.length > 10) {
  1437. this.historyStates.shift();
  1438. }
  1439. }
  1440. restoreHistoryState(index: number): void {
  1441. if (index >= 0 && index < this.historyStates.length) {
  1442. const state = this.historyStates[index];
  1443. this.colorIndicators = { ...state.colorIndicators };
  1444. this.spaceIndicators = { ...state.spaceIndicators };
  1445. this.materialIndicators = { ...state.materialIndicators };
  1446. this.requirementItems = state.requirementItems.map((r: RequirementItem) => ({ ...r }));
  1447. this.updatePreview();
  1448. this.checkConsistency();
  1449. }
  1450. }
  1451. // 获取未解决的评论数量
  1452. getUnresolvedCommentsCount(): number {
  1453. return this.collaborationComments.filter(c => c.status === 'pending').length;
  1454. }
  1455. // 获取需求的评论
  1456. getCommentsForRequirement(requirementId: string): CollaborationComment[] {
  1457. return this.collaborationComments.filter(comment => comment.requirementId === requirementId) || [];
  1458. }
  1459. // 获取状态样式类
  1460. getStatusClass(status: string): string {
  1461. return status;
  1462. }
  1463. // 工具方法
  1464. private generateId(): string {
  1465. return Math.random().toString(36).substr(2, 9);
  1466. }
  1467. private formatFileSize(bytes: number): string {
  1468. if (bytes === 0) return '0 Bytes';
  1469. const k = 1024;
  1470. const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  1471. const i = Math.floor(Math.log(bytes) / Math.log(k));
  1472. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  1473. }
  1474. // 删除素材
  1475. removeMaterial(materialId: string) {
  1476. const index = this.materialFiles.findIndex(m => m.id === materialId);
  1477. if (index > -1) {
  1478. const material = this.materialFiles[index];
  1479. if (material.url) {
  1480. URL.revokeObjectURL(material.url);
  1481. }
  1482. this.materialFiles.splice(index, 1);
  1483. }
  1484. const materialsIndex = this.materials.findIndex(m => m.id === materialId);
  1485. if (materialsIndex > -1) {
  1486. this.materials.splice(materialsIndex, 1);
  1487. }
  1488. }
  1489. // 切换标签页
  1490. switchTab(tab: 'materials' | 'mapping' | 'collaboration' | 'progress' | 'analysis-summary') {
  1491. this.activeTab = tab;
  1492. }
  1493. /**
  1494. * 切换全展示模式
  1495. */
  1496. toggleFullDisplayMode(): void {
  1497. this.isFullDisplayMode = !this.isFullDisplayMode;
  1498. if (this.isFullDisplayMode) {
  1499. // 展开所有素材
  1500. this.materials.forEach(material => {
  1501. this.expandedMaterials.add(material.id);
  1502. });
  1503. } else {
  1504. // 折叠所有素材
  1505. this.expandedMaterials.clear();
  1506. }
  1507. }
  1508. /**
  1509. * 切换单个素材的展开状态
  1510. */
  1511. toggleMaterialExpansion(materialId: string): void {
  1512. if (this.expandedMaterials.has(materialId)) {
  1513. this.expandedMaterials.delete(materialId);
  1514. } else {
  1515. this.expandedMaterials.add(materialId);
  1516. }
  1517. }
  1518. /**
  1519. * 检查素材是否已展开
  1520. */
  1521. isMaterialExpanded(materialId: string): boolean {
  1522. return this.expandedMaterials.has(materialId);
  1523. }
  1524. /**
  1525. * 🔥 自动生成需求映射(后台触发,无UI交互)
  1526. */
  1527. private autoGenerateRequirementMapping(analysisResult: ColorAnalysisResult): void {
  1528. console.log('🎯 开始后台生成需求映射...');
  1529. this.isGeneratingMapping = true;
  1530. this.mappingError = null;
  1531. // 更新测试步骤
  1532. const mappingStep = this.testSteps.find(s => s.id === 'mapping');
  1533. if (mappingStep) {
  1534. mappingStep.status = 'in-progress';
  1535. }
  1536. // 使用需求映射服务生成映射
  1537. this.requirementMappingService.generateRequirementMapping(analysisResult).subscribe({
  1538. next: (mapping: RequirementMapping) => {
  1539. this.requirementMapping = mapping;
  1540. this.isGeneratingMapping = false;
  1541. // 更新步骤状态
  1542. if (mappingStep) {
  1543. mappingStep.status = 'completed';
  1544. }
  1545. console.log('✅ 需求映射生成完成(后台)');
  1546. // 发射数据更新事件
  1547. this.emitMappingDataUpdate();
  1548. // 显示成功提示
  1549. this.promptTitle = '需求映射完成';
  1550. this.promptMessage = '系统已自动生成场景参数和氛围预览';
  1551. this.promptMode = 'corner';
  1552. this.promptPosition = 'bottom-right';
  1553. this.showGlobalPrompt = true;
  1554. },
  1555. error: (error: any) => {
  1556. this.mappingError = '映射生成失败';
  1557. this.isGeneratingMapping = false;
  1558. if (mappingStep) {
  1559. mappingStep.status = 'error';
  1560. }
  1561. console.error('❌ 需求映射生成失败:', error);
  1562. }
  1563. });
  1564. }
  1565. /**
  1566. * 导出分析报告(JSON格式)
  1567. */
  1568. exportAnalysisReportJSON(): void {
  1569. const reportData = this.generateReportData();
  1570. const blob = new Blob([JSON.stringify(reportData, null, 2)], { type: 'application/json' });
  1571. const url = window.URL.createObjectURL(blob);
  1572. const link = document.createElement('a');
  1573. link.href = url;
  1574. link.download = `素材分析报告_${new Date().toISOString().split('T')[0]}.json`;
  1575. link.click();
  1576. window.URL.revokeObjectURL(url);
  1577. }
  1578. /**
  1579. * 导出分析报告(HTML格式)
  1580. */
  1581. exportAnalysisReportHTML(): void {
  1582. const reportData = this.generateReportData();
  1583. const htmlContent = this.generateHTMLReport(reportData);
  1584. const blob = new Blob([htmlContent], { type: 'text/html' });
  1585. const url = window.URL.createObjectURL(blob);
  1586. const link = document.createElement('a');
  1587. link.href = url;
  1588. link.download = `素材分析报告_${new Date().toISOString().split('T')[0]}.html`;
  1589. link.click();
  1590. window.URL.revokeObjectURL(url);
  1591. }
  1592. /**
  1593. * 生成报告数据
  1594. */
  1595. private generateReportData(): any {
  1596. return {
  1597. projectId: this.projectId,
  1598. reportDate: new Date().toISOString(),
  1599. materials: this.materials.map(material => ({
  1600. id: material.id,
  1601. name: material.name,
  1602. type: material.type,
  1603. uploadTime: material.uploadTime,
  1604. analysis: material.analysis
  1605. })),
  1606. summary: {
  1607. totalMaterials: this.materials.length,
  1608. textCount: this.materials.filter(m => m.type === 'text').length,
  1609. imageCount: this.materials.filter(m => m.type === 'image').length,
  1610. cadCount: this.materials.filter(m => m.type === 'cad').length
  1611. }
  1612. };
  1613. }
  1614. /**
  1615. * 生成HTML报告
  1616. */
  1617. private generateHTMLReport(data: any): string {
  1618. return `
  1619. <!DOCTYPE html>
  1620. <html lang="zh-CN">
  1621. <head>
  1622. <meta charset="UTF-8">
  1623. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1624. <title>素材分析报告</title>
  1625. <style>
  1626. body {
  1627. font-family: 'Microsoft YaHei', Arial, sans-serif;
  1628. line-height: 1.6;
  1629. color: #333;
  1630. max-width: 1200px;
  1631. margin: 0 auto;
  1632. padding: 20px;
  1633. background: #f5f5f5;
  1634. }
  1635. .header {
  1636. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  1637. color: white;
  1638. padding: 30px;
  1639. border-radius: 8px;
  1640. margin-bottom: 30px;
  1641. }
  1642. .header h1 {
  1643. margin: 0 0 10px 0;
  1644. }
  1645. .summary {
  1646. background: white;
  1647. padding: 20px;
  1648. border-radius: 8px;
  1649. margin-bottom: 20px;
  1650. box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  1651. }
  1652. .material-item {
  1653. background: white;
  1654. padding: 20px;
  1655. border-radius: 8px;
  1656. margin-bottom: 20px;
  1657. box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  1658. }
  1659. .material-header {
  1660. display: flex;
  1661. justify-content: space-between;
  1662. align-items: center;
  1663. margin-bottom: 15px;
  1664. padding-bottom: 15px;
  1665. border-bottom: 2px solid #f0f0f0;
  1666. }
  1667. .analysis-section {
  1668. margin-top: 15px;
  1669. }
  1670. .analysis-section h4 {
  1671. color: #667eea;
  1672. margin: 10px 0;
  1673. }
  1674. </style>
  1675. </head>
  1676. <body>
  1677. <div class="header">
  1678. <h1>素材分析报告</h1>
  1679. <p>生成时间: ${new Date(data.reportDate).toLocaleString('zh-CN')}</p>
  1680. ${data.projectId ? `<p>项目ID: ${data.projectId}</p>` : ''}
  1681. </div>
  1682. <div class="summary">
  1683. <h2>汇总信息</h2>
  1684. <p>总素材数: ${data.summary.totalMaterials}</p>
  1685. <p>文本: ${data.summary.textCount} | 图片: ${data.summary.imageCount} | CAD: ${data.summary.cadCount}</p>
  1686. </div>
  1687. ${data.materials.map((material: any, index: number) => `
  1688. <div class="material-item">
  1689. <div class="material-header">
  1690. <h3>${index + 1}. ${material.name}</h3>
  1691. <span class="badge">${material.type === 'text' ? '文本' : material.type === 'image' ? '图片' : 'CAD'}</span>
  1692. </div>
  1693. ${material.analysis ? `
  1694. <div class="analysis-section">
  1695. <h4>分析结果</h4>
  1696. <pre>${JSON.stringify(material.analysis, null, 2)}</pre>
  1697. </div>
  1698. ` : '<p>暂无分析数据</p>'}
  1699. </div>
  1700. `).join('')}
  1701. <div class="footer" style="text-align: center; margin-top: 40px; color: #999;">
  1702. <p>报告生成于 ${new Date().toLocaleString('zh-CN')}</p>
  1703. </div>
  1704. </body>
  1705. </html>
  1706. `.trim();
  1707. }
  1708. // 获取需求状态文本
  1709. getRequirementStatusText(status: string): string {
  1710. const statusMap: { [key: string]: string } = {
  1711. 'pending': '待确认',
  1712. 'confirmed': '已确认',
  1713. 'rejected': '已拒绝'
  1714. };
  1715. return statusMap[status] || status;
  1716. }
  1717. // 获取优先级文本
  1718. getPriorityText(priority: string): string {
  1719. const priorityMap: { [key: string]: string } = {
  1720. 'high': '高',
  1721. 'medium': '中',
  1722. 'low': '低'
  1723. };
  1724. return priorityMap[priority] || priority;
  1725. }
  1726. // 刷新进度(保留用于手动刷新,但不再强制要求)
  1727. refreshProgress(): void {
  1728. // 重新计算进度
  1729. this.updateProgress();
  1730. // 更新进度条显示
  1731. const progress = this.getProgressPercentage();
  1732. this.updateProgressBar(progress);
  1733. // 检查阶段完成状态
  1734. this.checkStageCompletion();
  1735. // 触发进度更新事件
  1736. this.progressUpdated.emit(progress);
  1737. console.log('进度已手动刷新:', progress + '%');
  1738. }
  1739. // 自动保存功能
  1740. private triggerAutoSave(): void {
  1741. if (!this.autoSaveEnabled) return;
  1742. this.hasUnsavedChanges = true;
  1743. this.saveStatus = 'unsaved';
  1744. // 清除之前的定时器
  1745. if (this.autoSaveTimer) {
  1746. clearTimeout(this.autoSaveTimer);
  1747. }
  1748. // 设置新的自动保存定时器(延迟1秒)
  1749. this.autoSaveTimer = setTimeout(() => {
  1750. this.performAutoSave();
  1751. }, 1000);
  1752. }
  1753. private async performAutoSave(): Promise<void> {
  1754. if (this.isSaving) return;
  1755. this.isSaving = true;
  1756. this.saveStatus = 'saving';
  1757. try {
  1758. // 收集所有需要保存的数据
  1759. const saveData = this.collectSaveData();
  1760. // 模拟保存操作(实际项目中这里会调用API)
  1761. await this.saveToServer(saveData);
  1762. this.hasUnsavedChanges = false;
  1763. this.saveStatus = 'saved';
  1764. this.lastSaveTime = new Date();
  1765. console.log('自动保存成功:', new Date().toLocaleTimeString());
  1766. } catch (error) {
  1767. this.saveStatus = 'error';
  1768. console.error('自动保存失败:', error);
  1769. } finally {
  1770. this.isSaving = false;
  1771. }
  1772. }
  1773. // 手动保存
  1774. async manualSave(): Promise<void> {
  1775. if (this.isSaving) return;
  1776. // 清除自动保存定时器
  1777. if (this.autoSaveTimer) {
  1778. clearTimeout(this.autoSaveTimer);
  1779. }
  1780. await this.performAutoSave();
  1781. }
  1782. private collectSaveData(): any {
  1783. return {
  1784. projectId: this.projectId,
  1785. colorIndicators: this.colorIndicators,
  1786. spaceIndicators: this.spaceIndicators,
  1787. materialIndicators: this.materialIndicators,
  1788. requirementItems: this.requirementItems,
  1789. requirementMetrics: this.requirementMetrics,
  1790. materialFiles: this.materialFiles,
  1791. collaborationComments: this.collaborationComments,
  1792. stageCompletionStatus: this.stageCompletionStatus,
  1793. lastUpdated: new Date()
  1794. };
  1795. }
  1796. private async saveToServer(data: any): Promise<void> {
  1797. // 模拟API调用延迟
  1798. return new Promise((resolve, reject) => {
  1799. setTimeout(() => {
  1800. // 模拟90%成功率
  1801. if (Math.random() > 0.1) {
  1802. resolve();
  1803. } else {
  1804. reject(new Error('网络错误'));
  1805. }
  1806. }, 500);
  1807. });
  1808. }
  1809. // 检查阶段完成状态
  1810. private checkStageCompletion(): void {
  1811. // 检查素材解析阶段 - 需要有素材文件且都已分析
  1812. this.stageCompletionStatus.materialAnalysis = this.materialFiles.length > 0 &&
  1813. this.materialFiles.every(m => m.analysis);
  1814. // 检查协作验证阶段 - 需要有协作评论或需求评论
  1815. this.stageCompletionStatus.collaboration = this.collaborationComments.length > 0 ||
  1816. this.requirementItems.some(r => r.comments && r.comments.length > 0);
  1817. // 检查进度管理阶段 - 需要进度达到80%以上
  1818. this.stageCompletionStatus.progressReview = this.getProgressPercentage() >= 80;
  1819. console.log('阶段完成状态更新:', this.stageCompletionStatus);
  1820. // 检查是否所有阶段都已完成
  1821. const allStagesCompleted = Object.values(this.stageCompletionStatus).every(status => status);
  1822. // 发射阶段完成事件
  1823. if (allStagesCompleted) {
  1824. this.stageCompleted.emit({ stage: 'requirements-communication', allStagesCompleted: true });
  1825. }
  1826. }
  1827. // 检查指示器是否有变化
  1828. private hasIndicatorChanges(): boolean {
  1829. // 检查颜色指示器是否有变化(与默认值比较)
  1830. const defaultColorIndicators = {
  1831. mainColor: { r: 255, g: 230, b: 180 },
  1832. colorTemperature: 2700,
  1833. colorRange: '暖色调',
  1834. saturation: 70,
  1835. brightness: 80,
  1836. contrast: 60
  1837. };
  1838. const defaultSpaceIndicators = {
  1839. lineRatio: 60,
  1840. blankRatio: 30,
  1841. flowWidth: 0.9,
  1842. aspectRatio: 1.6,
  1843. ceilingHeight: 2.8,
  1844. lightingLevel: 300
  1845. };
  1846. const defaultMaterialIndicators = {
  1847. fabricRatio: 50,
  1848. woodRatio: 30,
  1849. metalRatio: 20,
  1850. smoothness: 7,
  1851. glossiness: 4,
  1852. texture: 6
  1853. };
  1854. // 检查颜色指示器变化
  1855. const colorChanged = JSON.stringify(this.colorIndicators) !== JSON.stringify(defaultColorIndicators);
  1856. // 检查空间指示器变化
  1857. const spaceChanged = JSON.stringify(this.spaceIndicators) !== JSON.stringify(defaultSpaceIndicators);
  1858. // 检查材质指示器变化
  1859. const materialChanged = JSON.stringify(this.materialIndicators) !== JSON.stringify(defaultMaterialIndicators);
  1860. return colorChanged || spaceChanged || materialChanged;
  1861. }
  1862. // 获取阶段状态文本
  1863. getStageStatusText(stage: keyof typeof this.stageCompletionStatus): string {
  1864. if (this.stageCompletionStatus[stage]) {
  1865. return '已完成';
  1866. } else {
  1867. // 检查是否为未开始状态
  1868. const stages = ['materialAnalysis', 'collaboration', 'progressReview'];
  1869. const currentIndex = stages.indexOf(stage);
  1870. // 检查前面的阶段是否都已完成
  1871. let allPreviousCompleted = true;
  1872. for (let i = 0; i < currentIndex; i++) {
  1873. if (!this.stageCompletionStatus[stages[i] as keyof typeof this.stageCompletionStatus]) {
  1874. allPreviousCompleted = false;
  1875. break;
  1876. }
  1877. }
  1878. return allPreviousCompleted ? '进行中' : '未进行';
  1879. }
  1880. }
  1881. // 获取阶段状态类名
  1882. getStageStatusClass(stage: keyof typeof this.stageCompletionStatus): string {
  1883. if (this.stageCompletionStatus[stage]) {
  1884. return 'stage-completed';
  1885. } else {
  1886. // 检查是否为未开始状态
  1887. const stages = ['materialAnalysis', 'collaboration', 'progressReview'];
  1888. const currentIndex = stages.indexOf(stage);
  1889. // 检查前面的阶段是否都已完成
  1890. let allPreviousCompleted = true;
  1891. for (let i = 0; i < currentIndex; i++) {
  1892. if (!this.stageCompletionStatus[stages[i] as keyof typeof this.stageCompletionStatus]) {
  1893. allPreviousCompleted = false;
  1894. break;
  1895. }
  1896. }
  1897. return allPreviousCompleted ? 'stage-in-progress' : 'stage-pending';
  1898. }
  1899. }
  1900. // 检查是否可以进入下一阶段
  1901. canProceedToNextStage(currentStage: keyof typeof this.stageCompletionStatus): boolean {
  1902. const stages = Object.keys(this.stageCompletionStatus) as (keyof typeof this.stageCompletionStatus)[];
  1903. const currentIndex = stages.indexOf(currentStage);
  1904. // 检查当前阶段之前的所有阶段是否都已完成
  1905. for (let i = 0; i <= currentIndex; i++) {
  1906. if (!this.stageCompletionStatus[stages[i]]) {
  1907. return false;
  1908. }
  1909. }
  1910. return true;
  1911. }
  1912. // 获取保存状态文本
  1913. getSaveStatusText(): string {
  1914. switch (this.saveStatus) {
  1915. case 'saved': return this.lastSaveTime ? `已保存 ${this.lastSaveTime.toLocaleTimeString()}` : '已保存';
  1916. case 'saving': return '保存中...';
  1917. case 'error': return '保存失败';
  1918. case 'unsaved': return '有未保存的更改';
  1919. default: return '';
  1920. }
  1921. }
  1922. // 获取保存状态图标
  1923. getSaveStatusIcon(): string {
  1924. switch (this.saveStatus) {
  1925. case 'saved': return '✓';
  1926. case 'saving': return '⏳';
  1927. case 'error': return '⚠';
  1928. case 'unsaved': return '●';
  1929. default: return '';
  1930. }
  1931. }
  1932. // 上传成功弹窗相关方法
  1933. onModalClose(): void {
  1934. this.showUploadSuccessModal = false;
  1935. this.uploadedFiles = [];
  1936. this.colorAnalysisResult = undefined;
  1937. }
  1938. // 全局提示关闭
  1939. onPromptClose(): void {
  1940. this.showGlobalPrompt = false;
  1941. }
  1942. onAnalyzeColors(): void {
  1943. if (this.uploadedFiles.length > 0 && this.uploadType === 'image') {
  1944. const imageFile = this.uploadedFiles[0];
  1945. // 设置分析状态为true
  1946. this.isAnalyzingColors = true;
  1947. // 从URL获取文件数据并创建File对象
  1948. fetch(imageFile.url)
  1949. .then(response => {
  1950. if (!response.ok) {
  1951. throw new Error(`HTTP error! status: ${response.status}`);
  1952. }
  1953. return response.blob();
  1954. })
  1955. .then(blob => {
  1956. // 创建包含实际文件数据的File对象
  1957. const file = new File([blob], imageFile.name, { type: imageFile.type || 'image/jpeg' });
  1958. // 使用模拟分析(在实际应用中应该调用真实的API)
  1959. this.colorAnalysisService.simulateAnalysis(file).subscribe({
  1960. next: (result) => {
  1961. this.colorAnalysisResult = result;
  1962. this.isAnalyzingColors = false; // 分析完成,设置状态为false
  1963. // 可以在这里更新颜色指标
  1964. if (result.colors.length > 0) {
  1965. const mainColor = result.colors[0];
  1966. this.updateColorIndicator('mainColor', mainColor.rgb);
  1967. }
  1968. // 新增:分析完成后向父级发射数据更新,包含色彩分析结果
  1969. this.emitDataUpdate();
  1970. },
  1971. error: (error) => {
  1972. console.error('颜色分析失败:', error);
  1973. this.isAnalyzingColors = false; // 分析失败,也要重置状态
  1974. }
  1975. });
  1976. })
  1977. .catch(error => {
  1978. console.error('获取文件数据失败:', error);
  1979. this.isAnalyzingColors = false; // 获取文件失败,重置状态
  1980. });
  1981. }
  1982. }
  1983. onViewReport(): void {
  1984. console.log('onViewReport被调用,当前colorAnalysisResult:', this.colorAnalysisResult);
  1985. // 打开全屏报告覆盖层
  1986. this.showFullReportOverlay = true;
  1987. // 确保色彩分析结果传递给父组件用于右侧展示
  1988. if (this.colorAnalysisResult) {
  1989. console.log('调用emitDataUpdate传递色彩分析结果');
  1990. this.emitDataUpdate();
  1991. } else {
  1992. console.log('没有色彩分析结果可传递');
  1993. }
  1994. }
  1995. onCloseFullReport(): void {
  1996. this.showFullReportOverlay = false;
  1997. }
  1998. // 新增:发射实时数据更新事件的方法
  1999. private emitDataUpdate(): void {
  2000. // 收集所有材料的详细分析数据
  2001. const materialAnalysisData = this.materials.map(material => ({
  2002. id: material.id,
  2003. name: material.name,
  2004. type: material.type,
  2005. analysis: material.analysis || {}
  2006. }));
  2007. const currentData = {
  2008. colorIndicators: this.colorIndicators || [],
  2009. spaceIndicators: this.spaceIndicators || [],
  2010. materialIndicators: this.materialIndicators || [],
  2011. requirementItems: this.requirementItems || [],
  2012. materials: this.materials || [],
  2013. collaborationComments: this.collaborationComments || '',
  2014. stageCompletionStatus: this.stageCompletionStatus || {},
  2015. // 传递色彩分析结果到父级用于右侧展示
  2016. colorAnalysisResult: this.colorAnalysisResult,
  2017. // 新增:传递完整的材料分析数据,包含色彩、形体、质感、纹理、灯光分析
  2018. materialAnalysisData: materialAnalysisData,
  2019. // 新增:传递详细的分析结果
  2020. detailedAnalysis: {
  2021. enhancedColorAnalysis: this.extractEnhancedColorAnalysis(),
  2022. formAnalysis: this.extractFormAnalysis(),
  2023. textureAnalysis: this.extractTextureAnalysis(),
  2024. patternAnalysis: this.extractPatternAnalysis(),
  2025. lightingAnalysis: this.extractLightingAnalysis()
  2026. }
  2027. };
  2028. console.log('emitDataUpdate被调用,准备发射数据:', {
  2029. colorAnalysisResult: this.colorAnalysisResult,
  2030. materials: this.materials,
  2031. requirementItems: this.requirementItems,
  2032. materialAnalysisData: materialAnalysisData,
  2033. detailedAnalysis: currentData.detailedAnalysis
  2034. });
  2035. this.dataUpdated.emit(currentData);
  2036. console.log('实时数据更新事件已发射:', currentData);
  2037. }
  2038. // 提取增强色彩分析数据
  2039. private extractEnhancedColorAnalysis(): any {
  2040. const colorAnalyses = this.materials
  2041. .filter(m => m.analysis?.enhancedColorAnalysis)
  2042. .map(m => m.analysis!.enhancedColorAnalysis);
  2043. if (colorAnalyses.length === 0) return null;
  2044. // 合并所有色彩分析数据
  2045. return colorAnalyses.reduce((merged, current) => ({
  2046. ...merged,
  2047. ...current
  2048. }), {});
  2049. }
  2050. // 提取形体分析数据
  2051. private extractFormAnalysis(): any {
  2052. const formAnalyses = this.materials
  2053. .filter(m => m.analysis?.formAnalysis)
  2054. .map(m => m.analysis!.formAnalysis);
  2055. if (formAnalyses.length === 0) return null;
  2056. return formAnalyses.reduce((merged, current) => ({
  2057. ...merged,
  2058. ...current
  2059. }), {});
  2060. }
  2061. // 提取质感分析数据
  2062. private extractTextureAnalysis(): any {
  2063. const textureAnalyses = this.materials
  2064. .filter(m => m.analysis?.textureAnalysis)
  2065. .map(m => m.analysis!.textureAnalysis);
  2066. if (textureAnalyses.length === 0) return null;
  2067. return textureAnalyses.reduce((merged, current) => ({
  2068. ...merged,
  2069. ...current
  2070. }), {});
  2071. }
  2072. // 提取纹理分析数据
  2073. private extractPatternAnalysis(): any {
  2074. const patternAnalyses = this.materials
  2075. .filter(m => m.analysis?.patternAnalysis)
  2076. .map(m => m.analysis!.patternAnalysis);
  2077. if (patternAnalyses.length === 0) return null;
  2078. return patternAnalyses.reduce((merged, current) => ({
  2079. ...merged,
  2080. ...current
  2081. }), {});
  2082. }
  2083. // 提取灯光分析数据
  2084. private extractLightingAnalysis(): any {
  2085. const lightingAnalyses = this.materials
  2086. .filter(m => m.analysis?.lightingAnalysis)
  2087. .map(m => m.analysis!.lightingAnalysis);
  2088. if (lightingAnalyses.length === 0) return null;
  2089. return lightingAnalyses.reduce((merged, current) => ({
  2090. ...merged,
  2091. ...current
  2092. }), {});
  2093. }
  2094. // 新增:图片与CAD文件预览方法
  2095. previewImage(url?: string): void {
  2096. if (!url) { return; }
  2097. try {
  2098. window.open(url, '_blank');
  2099. } catch (e) {
  2100. console.error('预览图片失败:', e);
  2101. }
  2102. }
  2103. previewCad(url?: string): void {
  2104. if (!url) { return; }
  2105. try {
  2106. window.open(url, '_blank');
  2107. } catch (e) {
  2108. console.error('预览CAD失败:', e);
  2109. }
  2110. }
  2111. // 需求映射测试相关方法
  2112. onFileSelectedForMapping(event: Event): void {
  2113. const input = event.target as HTMLInputElement;
  2114. if (!input.files || input.files.length === 0) return;
  2115. this.updateStepStatus('upload', 'in-progress');
  2116. this.isUploading = true;
  2117. try {
  2118. const files = Array.from(input.files);
  2119. this.uploadedFiles = files.map(file => ({
  2120. id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
  2121. name: file.name,
  2122. url: URL.createObjectURL(file),
  2123. size: file.size,
  2124. type: 'image' as const,
  2125. preview: URL.createObjectURL(file)
  2126. }));
  2127. // 模拟上传延迟
  2128. setTimeout(() => {
  2129. this.isUploading = false;
  2130. this.updateStepStatus('upload', 'completed');
  2131. this.showUploadModal = true;
  2132. // 自动开始分析
  2133. this.startAnalysis();
  2134. }, 1000);
  2135. } catch (error) {
  2136. console.error('文件上传失败:', error);
  2137. this.isUploading = false;
  2138. this.updateStepStatus('upload', 'error');
  2139. }
  2140. }
  2141. // 开始分析 - 支持多图片分析
  2142. startAnalysis(): void {
  2143. if (this.uploadedFiles.length === 0) return;
  2144. this.updateStepStatus('analysis', 'in-progress');
  2145. this.isAnalyzing = true;
  2146. this.analysisError = null;
  2147. // 过滤出所有图片文件
  2148. const imageFiles = this.uploadedFiles.filter(f => f.type === 'image');
  2149. if (imageFiles.length === 0) {
  2150. this.analysisError = '未找到有效的图片文件';
  2151. this.isAnalyzing = false;
  2152. this.updateStepStatus('analysis', 'error');
  2153. return;
  2154. }
  2155. try {
  2156. // 如果只有一张图片,使用单图分析
  2157. if (imageFiles.length === 1) {
  2158. const analysisSubscription = this.colorAnalysisService.analyzeImage(imageFiles[0]).subscribe({
  2159. next: (result: ColorAnalysisResult) => {
  2160. if (result) {
  2161. this.analysisResult = result;
  2162. this.isAnalyzing = false;
  2163. this.updateStepStatus('analysis', 'completed');
  2164. // 自动开始需求映射
  2165. this.startRequirementMapping();
  2166. } else {
  2167. this.analysisError = '分析结果为空';
  2168. this.isAnalyzing = false;
  2169. this.updateStepStatus('analysis', 'error');
  2170. }
  2171. },
  2172. error: (error: any) => {
  2173. console.error('分析失败:', error);
  2174. this.analysisError = '图片分析失败,请重试';
  2175. this.isAnalyzing = false;
  2176. this.updateStepStatus('analysis', 'error');
  2177. }
  2178. });
  2179. this.subscriptions.push(analysisSubscription);
  2180. } else {
  2181. // 多图片分析:分析所有图片并合并结果
  2182. this.analyzeBatchImages(imageFiles);
  2183. }
  2184. } catch (error) {
  2185. console.error('启动分析失败:', error);
  2186. this.analysisError = '启动分析失败,请重试';
  2187. this.isAnalyzing = false;
  2188. this.updateStepStatus('analysis', 'error');
  2189. }
  2190. }
  2191. // 批量图片分析
  2192. private analyzeBatchImages(imageFiles: any[]): void {
  2193. console.log(`开始批量分析 ${imageFiles.length} 张图片...`);
  2194. let completedCount = 0;
  2195. const allResults: ColorAnalysisResult[] = [];
  2196. imageFiles.forEach((file, index) => {
  2197. const analysisSubscription = this.colorAnalysisService.analyzeImage(file).subscribe({
  2198. next: (result: ColorAnalysisResult) => {
  2199. allResults.push(result);
  2200. completedCount++;
  2201. console.log(`图片 ${index + 1}/${imageFiles.length} 分析完成`);
  2202. // 所有图片分析完成后,合并结果
  2203. if (completedCount === imageFiles.length) {
  2204. this.analysisResult = this.mergeAnalysisResults(allResults);
  2205. this.isAnalyzing = false;
  2206. this.updateStepStatus('analysis', 'completed');
  2207. console.log('批量分析完成,合并结果:', this.analysisResult);
  2208. // 自动开始需求映射
  2209. this.startRequirementMapping();
  2210. }
  2211. },
  2212. error: (error: any) => {
  2213. console.error(`图片 ${index + 1} 分析失败:`, error);
  2214. completedCount++;
  2215. // 即使部分失败,也尝试合并已成功的结果
  2216. if (completedCount === imageFiles.length) {
  2217. if (allResults.length > 0) {
  2218. this.analysisResult = this.mergeAnalysisResults(allResults);
  2219. this.isAnalyzing = false;
  2220. this.updateStepStatus('analysis', 'completed');
  2221. this.startRequirementMapping();
  2222. } else {
  2223. this.analysisError = '所有图片分析失败,请重试';
  2224. this.isAnalyzing = false;
  2225. this.updateStepStatus('analysis', 'error');
  2226. }
  2227. }
  2228. }
  2229. });
  2230. this.subscriptions.push(analysisSubscription);
  2231. });
  2232. }
  2233. // 合并多个分析结果
  2234. private mergeAnalysisResults(results: ColorAnalysisResult[]): ColorAnalysisResult {
  2235. if (results.length === 0) {
  2236. throw new Error('没有有效的分析结果');
  2237. }
  2238. if (results.length === 1) {
  2239. return results[0];
  2240. }
  2241. console.log('合并多个分析结果:', results.length);
  2242. // 合并颜色信息
  2243. const allColors: any[] = [];
  2244. results.forEach(result => {
  2245. result.colors.forEach(color => {
  2246. const existing = allColors.find(c => c.hex === color.hex);
  2247. if (existing) {
  2248. existing.percentage += color.percentage / results.length;
  2249. } else {
  2250. allColors.push({
  2251. ...color,
  2252. percentage: color.percentage / results.length
  2253. });
  2254. }
  2255. });
  2256. });
  2257. // 按百分比排序并取前7种颜色
  2258. allColors.sort((a, b) => b.percentage - a.percentage);
  2259. const mergedColors = allColors.slice(0, 7);
  2260. // 重新计算百分比使总和为100%
  2261. const totalPercentage = mergedColors.reduce((sum, c) => sum + c.percentage, 0);
  2262. mergedColors.forEach(c => {
  2263. c.percentage = (c.percentage / totalPercentage) * 100;
  2264. });
  2265. // 合并增强分析数据(取平均值或第一个)
  2266. const baseResult = results[0];
  2267. return {
  2268. colors: mergedColors,
  2269. originalImage: results[0].originalImage,
  2270. mosaicImage: results[0].mosaicImage,
  2271. reportPath: results[0].reportPath,
  2272. enhancedAnalysis: baseResult.enhancedAnalysis,
  2273. formAnalysis: baseResult.formAnalysis,
  2274. textureAnalysis: baseResult.textureAnalysis,
  2275. patternAnalysis: baseResult.patternAnalysis,
  2276. lightingAnalysis: baseResult.lightingAnalysis
  2277. };
  2278. }
  2279. // 开始需求映射
  2280. startRequirementMapping(): void {
  2281. if (!this.analysisResult) {
  2282. console.warn('分析结果为空,无法开始需求映射');
  2283. return;
  2284. }
  2285. this.updateStepStatus('mapping', 'in-progress');
  2286. this.isGeneratingMapping = true;
  2287. this.mappingError = null;
  2288. try {
  2289. const mappingSubscription = this.requirementMappingService.generateRequirementMapping(
  2290. this.analysisResult,
  2291. SceneTemplate.LIVING_ROOM_MODERN
  2292. ).subscribe({
  2293. next: (mapping) => {
  2294. if (mapping) {
  2295. this.requirementMapping = mapping;
  2296. this.isGeneratingMapping = false;
  2297. this.updateStepStatus('mapping', 'completed');
  2298. this.updateStepStatus('preview', 'completed');
  2299. console.log('=== 需求映射测试完成 ===');
  2300. console.log('映射结果:', this.requirementMapping);
  2301. // 发送映射数据更新到父组件
  2302. this.emitMappingDataUpdate();
  2303. } else {
  2304. this.mappingError = '需求映射结果为空';
  2305. this.isGeneratingMapping = false;
  2306. this.updateStepStatus('mapping', 'error');
  2307. }
  2308. },
  2309. error: (error) => {
  2310. console.error('需求映射生成失败:', error);
  2311. this.mappingError = '需求映射生成失败,请重试';
  2312. this.isGeneratingMapping = false;
  2313. this.updateStepStatus('mapping', 'error');
  2314. }
  2315. });
  2316. this.subscriptions.push(mappingSubscription);
  2317. } catch (error) {
  2318. console.error('启动需求映射失败:', error);
  2319. this.mappingError = '启动需求映射失败,请重试';
  2320. this.isGeneratingMapping = false;
  2321. this.updateStepStatus('mapping', 'error');
  2322. }
  2323. }
  2324. // 更新步骤状态
  2325. private updateStepStatus(stepId: string, status: 'pending' | 'in-progress' | 'completed' | 'error'): void {
  2326. const step = this.testSteps.find(s => s.id === stepId);
  2327. if (step) {
  2328. step.status = status;
  2329. } else {
  2330. console.warn(`未找到步骤: ${stepId}`);
  2331. }
  2332. }
  2333. // 辅助方法:获取步骤图标
  2334. getStepIcon(status: string): string {
  2335. switch (status) {
  2336. case 'completed': return '✅';
  2337. case 'in-progress': return '⏳';
  2338. case 'error': return '❌';
  2339. default: return '⭕';
  2340. }
  2341. }
  2342. // 获取步骤状态类名
  2343. getStepClass(status: string): string {
  2344. return `step-${status}`;
  2345. }
  2346. // 手动重试分析
  2347. retryAnalysis(): void {
  2348. this.analysisError = null;
  2349. this.startAnalysis();
  2350. }
  2351. // 手动重试映射
  2352. retryMapping(): void {
  2353. this.mappingError = null;
  2354. this.startRequirementMapping();
  2355. }
  2356. // 下载测试结果
  2357. downloadTestResult(): void {
  2358. if (!this.requirementMapping) return;
  2359. const testResult = {
  2360. timestamp: new Date().toISOString(),
  2361. uploadedFiles: this.uploadedFiles.map(f => ({
  2362. name: f.name,
  2363. size: f.size,
  2364. type: f.type
  2365. })),
  2366. analysisResult: this.analysisResult,
  2367. requirementMapping: this.requirementMapping,
  2368. testSteps: this.testSteps
  2369. };
  2370. const blob = new Blob([JSON.stringify(testResult, null, 2)], { type: 'application/json' });
  2371. const url = URL.createObjectURL(blob);
  2372. const link = document.createElement('a');
  2373. link.href = url;
  2374. link.download = `requirement-mapping-test-${Date.now()}.json`;
  2375. link.click();
  2376. URL.revokeObjectURL(url);
  2377. }
  2378. // 辅助方法:获取材质名称的中文翻译
  2379. getMaterialName(category: string | undefined): string {
  2380. if (!category) return '未识别';
  2381. const nameMap: { [key: string]: string } = {
  2382. 'wood': '木材',
  2383. 'metal': '金属',
  2384. 'fabric': '织物',
  2385. 'leather': '皮革',
  2386. 'plastic': '塑料',
  2387. 'glass': '玻璃',
  2388. 'ceramic': '陶瓷',
  2389. 'stone': '石材',
  2390. 'composite': '复合材料'
  2391. };
  2392. return nameMap[category] || category;
  2393. }
  2394. // 获取灯光情绪名称的中文翻译
  2395. getLightingMoodName(mood: string | undefined): string {
  2396. if (!mood) return '未识别';
  2397. const nameMap: { [key: string]: string } = {
  2398. 'dramatic': '戏剧性',
  2399. 'romantic': '浪漫',
  2400. 'energetic': '活力',
  2401. 'calm': '平静',
  2402. 'mysterious': '神秘',
  2403. 'cheerful': '愉悦',
  2404. 'professional': '专业'
  2405. };
  2406. return nameMap[mood] || mood;
  2407. }
  2408. // 获取复杂度名称的中文翻译
  2409. getComplexityName(level: string): string {
  2410. const nameMap: { [key: string]: string } = {
  2411. 'simple': '简单',
  2412. 'moderate': '中等',
  2413. 'complex': '复杂',
  2414. 'very-complex': '非常复杂'
  2415. };
  2416. return nameMap[level] || level;
  2417. }
  2418. // 获取色彩和谐类型的中文翻译
  2419. getColorHarmonyName(harmony: string): string {
  2420. const nameMap: { [key: string]: string } = {
  2421. 'monochromatic': '单色调和',
  2422. 'analogous': '类似色调和',
  2423. 'complementary': '互补色调和',
  2424. 'triadic': '三角色调和',
  2425. 'tetradic': '四角色调和',
  2426. 'split-complementary': '分裂互补色调和'
  2427. };
  2428. return nameMap[harmony] || harmony;
  2429. }
  2430. // 获取空间布局类型的中文翻译
  2431. getLayoutTypeName(type: string): string {
  2432. const nameMap: { [key: string]: string } = {
  2433. 'open': '开放式',
  2434. 'enclosed': '封闭式',
  2435. 'semi-open': '半开放式',
  2436. 'multi-level': '多层次'
  2437. };
  2438. return nameMap[type] || type;
  2439. }
  2440. // 获取空间流线类型的中文翻译
  2441. getFlowTypeName(flow: string): string {
  2442. const nameMap: { [key: string]: string } = {
  2443. 'linear': '线性流线',
  2444. 'circular': '环形流线',
  2445. 'grid': '网格流线',
  2446. 'organic': '有机流线'
  2447. };
  2448. return nameMap[flow] || flow;
  2449. }
  2450. // 新增:获取光比描述的中文翻译
  2451. getRatioDescription(description: string): string {
  2452. const nameMap: { [key: string]: string } = {
  2453. 'low-contrast': '低反差',
  2454. 'medium-contrast': '中等反差',
  2455. 'high-contrast': '高反差',
  2456. 'dramatic': '戏剧化'
  2457. };
  2458. return nameMap[description] || description;
  2459. }
  2460. // 新增:获取光平衡描述的中文翻译
  2461. getBalanceDescription(balance: string): string {
  2462. const nameMap: { [key: string]: string } = {
  2463. 'natural-dominant': '自然光主导',
  2464. 'artificial-dominant': '人工光主导',
  2465. 'balanced': '光源平衡'
  2466. };
  2467. return nameMap[balance] || balance;
  2468. }
  2469. // 形体选择事件处理
  2470. onFormSelected(form: any): void {
  2471. console.log('✅ 选择形体:', form);
  2472. // 可以在这里保存选择的形体数据到材料分析中
  2473. }
  2474. onFormDeselected(form: any): void {
  2475. console.log('❌ 取消选择形体:', form);
  2476. // 可以在这里移除取消选择的形体数据
  2477. }
  2478. // 移除需求映射界面中已上传的文件
  2479. removeUploadedFile(fileId: string): void {
  2480. const index = this.uploadedFiles.findIndex(f => f.id === fileId);
  2481. if (index !== -1) {
  2482. const file = this.uploadedFiles[index];
  2483. // 清理对象URL
  2484. if (file.url && file.url.startsWith('blob:')) {
  2485. URL.revokeObjectURL(file.url);
  2486. }
  2487. if (file.preview && file.preview.startsWith('blob:')) {
  2488. URL.revokeObjectURL(file.preview);
  2489. }
  2490. this.uploadedFiles.splice(index, 1);
  2491. // 如果没有文件了,重置分析状态
  2492. if (this.uploadedFiles.length === 0) {
  2493. this.analysisResult = undefined;
  2494. this.requirementMapping = null;
  2495. this.updateStepStatus('upload', 'pending');
  2496. this.updateStepStatus('analysis', 'pending');
  2497. this.updateStepStatus('mapping', 'pending');
  2498. this.updateStepStatus('preview', 'pending');
  2499. } else {
  2500. // 还有其他图片,重新分析剩余图片
  2501. this.restartAnalysisWithRemainingImages();
  2502. }
  2503. }
  2504. }
  2505. /**
  2506. * 🔥 显示上传成功弹窗并开始色彩分析
  2507. */
  2508. private showUploadSuccessModalAndAnalyze(uploadedFile: any): void {
  2509. console.log('🎨 显示上传成功弹窗并开始色彩分析:', uploadedFile.name);
  2510. // 1. 显示弹窗(不显示全局提示,避免干扰)
  2511. this.showUploadSuccessModal = true;
  2512. this.showGlobalPrompt = false; // 关闭全局提示
  2513. this.uploadType = 'image';
  2514. this.isAnalyzingColors = true;
  2515. // 2. 开始色彩分析(用于弹窗显示)
  2516. this.colorAnalysisService.analyzeImage(uploadedFile).subscribe({
  2517. next: (result) => {
  2518. this.colorAnalysisResult = result;
  2519. this.isAnalyzingColors = false;
  2520. console.log('✅ 色彩分析完成(弹窗):', result);
  2521. // 3. 色彩分析完成后,触发后台需求映射生成
  2522. setTimeout(() => {
  2523. this.triggerRealtimeAnalysis(uploadedFile);
  2524. }, 500);
  2525. },
  2526. error: (error) => {
  2527. this.isAnalyzingColors = false;
  2528. console.error('❌ 色彩分析失败:', error);
  2529. }
  2530. });
  2531. }
  2532. // 实时触发分析(每上传一张图片就分析一张)
  2533. private triggerRealtimeAnalysis(newFile: any): void {
  2534. console.log('🚀 触发实时分析:', newFile.name);
  2535. // 自动开始分析
  2536. setTimeout(() => {
  2537. this.performAutoAnalysis(newFile);
  2538. }, 500);
  2539. }
  2540. /**
  2541. * 执行自动分析和映射生成
  2542. */
  2543. private performAutoAnalysis(file: any): void {
  2544. this.isAnalyzing = true;
  2545. this.analysisError = null;
  2546. // 更新测试步骤
  2547. const analysisStep = this.testSteps.find(s => s.id === 'analysis');
  2548. if (analysisStep) {
  2549. analysisStep.status = 'in-progress';
  2550. }
  2551. // 使用色彩分析服务
  2552. this.colorAnalysisService.analyzeImage(file).subscribe({
  2553. next: (result: ColorAnalysisResult) => {
  2554. this.analysisResult = result;
  2555. this.isAnalyzing = false;
  2556. // 更新步骤状态
  2557. if (analysisStep) {
  2558. analysisStep.status = 'completed';
  2559. }
  2560. console.log('✅ 分析完成,自动触发需求映射生成');
  2561. // 🔥 关键:分析完成后自动触发需求映射
  2562. this.autoGenerateRequirementMapping(result);
  2563. // 发射数据更新事件
  2564. this.emitMappingDataUpdate();
  2565. },
  2566. error: (error: any) => {
  2567. this.analysisError = '分析失败,请重试';
  2568. this.isAnalyzing = false;
  2569. if (analysisStep) {
  2570. analysisStep.status = 'error';
  2571. }
  2572. console.error('❌ 分析失败:', error);
  2573. }
  2574. });
  2575. }
  2576. // 重新分析剩余图片
  2577. private restartAnalysisWithRemainingImages(): void {
  2578. console.log('🔄 重新分析剩余图片,共', this.uploadedFiles.length, '张');
  2579. this.updateStepStatus('analysis', 'in-progress');
  2580. this.isAnalyzing = true;
  2581. this.analysisResult = undefined;
  2582. // 重新分析所有剩余图片
  2583. const imageFiles = this.uploadedFiles.filter(f => f.type === 'image');
  2584. if (imageFiles.length === 0) {
  2585. this.isAnalyzing = false;
  2586. this.updateStepStatus('analysis', 'pending');
  2587. return;
  2588. }
  2589. // 使用批量分析
  2590. this.analyzeBatchImages(imageFiles);
  2591. }
  2592. // 发送映射数据更新到父组件
  2593. private emitMappingDataUpdate(): void {
  2594. // 将ColorAnalysisResult转换为父组件期望的扁平化格式
  2595. const transformedAnalysisResult = this.analysisResult ? {
  2596. primaryColor: this.analysisResult.colors?.[0] || null,
  2597. materialType: this.analysisResult.textureAnalysis?.materialClassification?.primaryMaterial?.category || '未知',
  2598. lightingMood: this.analysisResult.lightingAnalysis?.ambientAnalysis?.lightingMood?.primary || '未知',
  2599. contrast: this.analysisResult.lightingAnalysis?.illuminationAnalysis?.contrast?.level
  2600. ? `${this.analysisResult.lightingAnalysis.illuminationAnalysis.contrast.level}`
  2601. : '未知',
  2602. // 保留原始完整数据以备使用
  2603. fullAnalysis: this.analysisResult
  2604. } : null;
  2605. // 将RequirementMapping转换为父组件期望的格式
  2606. const transformedMapping = this.requirementMapping ? {
  2607. color: {
  2608. harmony: this.requirementMapping.parameterMapping?.colorParams?.colorHarmony || '未知',
  2609. temperature: this.requirementMapping.parameterMapping?.colorParams?.temperature || '未知'
  2610. },
  2611. space: {
  2612. layout: this.requirementMapping.parameterMapping?.spaceParams?.layout?.type || '未知',
  2613. flow: this.requirementMapping.parameterMapping?.spaceParams?.layout?.flow || '未知'
  2614. },
  2615. material: {
  2616. textureScale: this.requirementMapping.parameterMapping?.materialParams?.textureScale || 0,
  2617. reflectivity: this.requirementMapping.parameterMapping?.materialParams?.reflectivity || 0
  2618. },
  2619. // 保留原始完整数据
  2620. fullMapping: this.requirementMapping
  2621. } : null;
  2622. this.mappingDataUpdated.emit({
  2623. uploadedFiles: this.uploadedFiles,
  2624. analysisResult: transformedAnalysisResult,
  2625. requirementMapping: transformedMapping,
  2626. testSteps: this.testSteps,
  2627. isAnalyzing: this.isAnalyzing,
  2628. isGeneratingMapping: this.isGeneratingMapping
  2629. });
  2630. console.log('✅ 发射需求映射数据更新:', {
  2631. uploadedFiles: this.uploadedFiles.length,
  2632. analysisResult: transformedAnalysisResult,
  2633. requirementMapping: transformedMapping
  2634. });
  2635. }
  2636. // 生成质感对比数据
  2637. getTextureDataForMaterial(material: MaterialFile): any[] {
  2638. if (!material.analysis?.textureAnalysis?.surfaceProperties ||
  2639. !material.analysis?.textureAnalysis?.materialClassification?.primaryMaterial) {
  2640. return [];
  2641. }
  2642. const textureAnalysis = material.analysis.textureAnalysis;
  2643. const materialClassification = textureAnalysis.materialClassification;
  2644. const primaryMaterial = materialClassification?.primaryMaterial;
  2645. const surfaceProps = textureAnalysis.surfaceProperties;
  2646. if (!primaryMaterial || !surfaceProps) {
  2647. return [];
  2648. }
  2649. return [{
  2650. materialName: primaryMaterial.category || '未知材质',
  2651. materialType: primaryMaterial.category || '未知类型',
  2652. properties: [
  2653. { name: '粗糙度', value: surfaceProps.roughness?.value || 50, category: 'tactile' as const },
  2654. { name: '光泽度', value: surfaceProps.glossiness?.value || 40, category: 'visual' as const },
  2655. { name: '反射率', value: surfaceProps.glossiness?.reflectivity || 30, category: 'reflective' as const },
  2656. { name: '触感柔软度', value: 60, category: 'tactile' as const },
  2657. { name: '纹理密度', value: 50, category: 'visual' as const },
  2658. { name: '视觉温暖度', value: 55, category: 'visual' as const }
  2659. ],
  2660. dominantCharacteristic: 'mixed' as const
  2661. }];
  2662. }
  2663. }