requirements-confirm-card.ts 80 KB

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