project-detail.ts 179 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262
  1. import { Component, OnInit, OnDestroy, ChangeDetectorRef } from '@angular/core';
  2. import { CommonModule } from '@angular/common';
  3. import { ActivatedRoute, Router } from '@angular/router';
  4. import { FormsModule, ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms';
  5. import { ProjectService } from '../../../services/project.service';
  6. import { PaymentVoucherRecognitionService } from '../../../services/payment-voucher-recognition.service';
  7. import { ProjectReviewService, ReviewReportExportRequest, ReviewReportShareRequest } from '../../../services/project-review.service';
  8. import {
  9. Project,
  10. RenderProgress,
  11. CustomerFeedback,
  12. DesignerChange,
  13. Settlement,
  14. ProjectStage,
  15. PanoramicSynthesis,
  16. ModelCheckItem
  17. } from '../../../models/project.model';
  18. import { RequirementsConfirmCardComponent } from '../../../shared/components/requirements-confirm-card/requirements-confirm-card';
  19. import { SettlementCardComponent } from '../../../shared/components/settlement-card/settlement-card';
  20. import { CustomerReviewCardComponent, DetailedCustomerReview } from '../../../shared/components/customer-review-card/customer-review-card';
  21. import { CustomerReviewFormComponent } from '../../../shared/components/customer-review-form/customer-review-form';
  22. import { ComplaintCardComponent } from '../../../shared/components/complaint-card/complaint-card';
  23. import { PanoramicSynthesisCardComponent } from '../../../shared/components/panoramic-synthesis-card/panoramic-synthesis-card';
  24. import { QuotationDetailsComponent, QuotationData } from './components/quotation-details/quotation-details.component';
  25. import { DesignerAssignmentComponent, DesignerAssignmentData, Designer as AssignmentDesigner } from './components/designer-assignment/designer-assignment.component';
  26. // 引入客户服务模块的设计师日历组件
  27. import { DesignerCalendarComponent, Designer as CalendarDesigner, ProjectGroup as CalendarProjectGroup } from '../../customer-service/consultation-order/components/designer-calendar/designer-calendar.component';
  28. // 引入参考图管理组件
  29. import { ReferenceImageManagerComponent } from './components/reference-image-manager/reference-image-manager.component';
  30. import { ColorAnalysisResult } from '../../../shared/services/color-analysis.service';
  31. interface ExceptionHistory {
  32. id: string;
  33. type: 'failed' | 'stuck' | 'quality' | 'other';
  34. description: string;
  35. submitTime: Date;
  36. status: '待处理' | '处理中' | '已解决';
  37. response?: string;
  38. }
  39. interface ProjectMember {
  40. id: string;
  41. name: string;
  42. role: string;
  43. avatar: string;
  44. skillMatch: number;
  45. progress: number;
  46. contribution: number;
  47. }
  48. interface ProjectFile {
  49. id: string;
  50. name: string;
  51. type: string;
  52. size: string;
  53. date: string;
  54. url: string;
  55. }
  56. interface TimelineEvent {
  57. id: string;
  58. time: string;
  59. title: string;
  60. action: string;
  61. description: string;
  62. }
  63. // 新增:四大板块键类型(顶层声明,供组件与模板共同使用)
  64. type SectionKey = 'order' | 'requirements' | 'delivery' | 'aftercare';
  65. // 素材解析后的方案数据结构
  66. interface MaterialAnalysis {
  67. category: string;
  68. specifications: {
  69. type: string;
  70. grade: string;
  71. thickness?: string;
  72. finish?: string;
  73. durability: string;
  74. };
  75. usage: {
  76. area: string;
  77. percentage: number;
  78. priority: 'primary' | 'secondary' | 'accent';
  79. };
  80. properties: {
  81. texture: string;
  82. color: string;
  83. maintenance: string;
  84. };
  85. }
  86. interface DesignStyleAnalysis {
  87. primaryStyle: string;
  88. styleElements: {
  89. element: string;
  90. description: string;
  91. influence: number; // 影响程度 0-100
  92. }[];
  93. characteristics: {
  94. feature: string;
  95. value: string;
  96. importance: 'high' | 'medium' | 'low';
  97. }[];
  98. compatibility: {
  99. withMaterials: string[];
  100. withColors: string[];
  101. score: number; // 兼容性评分 0-100
  102. };
  103. }
  104. interface ColorSchemeAnalysis {
  105. palette: {
  106. color: string;
  107. hex: string;
  108. rgb: string;
  109. percentage: number;
  110. role: 'dominant' | 'secondary' | 'accent' | 'neutral';
  111. }[];
  112. harmony: {
  113. type: string; // 如:互补色、类似色、三角色等
  114. temperature: 'warm' | 'cool' | 'neutral';
  115. contrast: number; // 对比度 0-100
  116. };
  117. psychology: {
  118. mood: string;
  119. atmosphere: string;
  120. suitability: string[];
  121. };
  122. }
  123. interface SpaceAnalysis {
  124. dimensions: {
  125. length: number;
  126. width: number;
  127. height: number;
  128. area: number;
  129. volume: number;
  130. };
  131. functionalZones: {
  132. zone: string;
  133. area: number;
  134. percentage: number;
  135. requirements: string[];
  136. furniture: string[];
  137. }[];
  138. circulation: {
  139. mainPaths: string[];
  140. pathWidth: number;
  141. efficiency: number; // 动线效率 0-100
  142. };
  143. lighting: {
  144. natural: {
  145. direction: string[];
  146. intensity: string;
  147. duration: string;
  148. };
  149. artificial: {
  150. zones: string[];
  151. requirements: string[];
  152. };
  153. };
  154. }
  155. // 新增:项目复盘数据结构
  156. interface ProjectReview {
  157. id: string;
  158. projectId: string;
  159. generatedAt: Date;
  160. overallScore: number; // 项目总评分 0-100
  161. sopAnalysis: {
  162. stageName: string;
  163. plannedDuration: number; // 计划天数
  164. actualDuration: number; // 实际天数
  165. score: number; // 阶段评分 0-100
  166. executionStatus: 'excellent' | 'good' | 'average' | 'poor';
  167. issues?: string[]; // 问题列表
  168. }[];
  169. keyHighlights: string[]; // 项目亮点
  170. improvementSuggestions: string[]; // 改进建议
  171. customerSatisfaction: {
  172. overallRating: number; // 1-5星
  173. feedback?: string; // 客户反馈
  174. responseTime: number; // 响应时间(小时)
  175. completionTime: number; // 完成时间(天)
  176. };
  177. teamPerformance: {
  178. designerScore: number;
  179. communicationScore: number;
  180. timelinessScore: number;
  181. qualityScore: number;
  182. };
  183. budgetAnalysis: {
  184. plannedBudget: number;
  185. actualBudget: number;
  186. variance: number; // 预算偏差百分比
  187. costBreakdown: {
  188. category: string;
  189. planned: number;
  190. actual: number;
  191. }[];
  192. };
  193. lessonsLearned: string[]; // 经验教训
  194. recommendations: string[]; // 后续项目建议
  195. }
  196. interface ProposalAnalysis {
  197. id: string;
  198. name: string;
  199. version: string;
  200. createdAt: Date;
  201. status: 'analyzing' | 'completed' | 'approved' | 'rejected';
  202. materials: MaterialAnalysis[];
  203. designStyle: DesignStyleAnalysis;
  204. colorScheme: ColorSchemeAnalysis;
  205. spaceLayout: SpaceAnalysis;
  206. budget: {
  207. total: number;
  208. breakdown: {
  209. category: string;
  210. amount: number;
  211. percentage: number;
  212. }[];
  213. };
  214. timeline: {
  215. phase: string;
  216. duration: number;
  217. dependencies: string[];
  218. }[];
  219. feasibility: {
  220. technical: number; // 技术可行性 0-100
  221. budget: number; // 预算可行性 0-100
  222. timeline: number; // 时间可行性 0-100
  223. overall: number; // 综合可行性 0-100
  224. };
  225. }
  226. // 交付执行板块数据结构
  227. interface DeliverySpace {
  228. id: string;
  229. name: string; // 空间名称:卧室、餐厅、厨房等
  230. isExpanded: boolean; // 是否展开
  231. order: number; // 排序
  232. }
  233. interface DeliveryProcess {
  234. id: string;
  235. name: string; // 流程名称:建模、软装、渲染、后期
  236. type: 'modeling' | 'softDecor' | 'rendering' | 'postProcess';
  237. spaces: DeliverySpace[]; // 该流程下的空间列表
  238. isExpanded: boolean; // 是否展开
  239. content: {
  240. [spaceId: string]: {
  241. // 每个空间的具体内容
  242. images: Array<{ id: string; name: string; url: string; size?: string; reviewStatus?: 'pending' | 'approved' | 'rejected' }>;
  243. progress: number; // 进度百分比
  244. status: 'pending' | 'in_progress' | 'completed' | 'approved';
  245. notes: string; // 备注
  246. lastUpdated: Date;
  247. };
  248. };
  249. }
  250. @Component({
  251. selector: 'app-project-detail',
  252. standalone: true,
  253. imports: [CommonModule, FormsModule, ReactiveFormsModule, RequirementsConfirmCardComponent, SettlementCardComponent, CustomerReviewCardComponent, CustomerReviewFormComponent, ComplaintCardComponent, PanoramicSynthesisCardComponent, QuotationDetailsComponent, DesignerAssignmentComponent, DesignerCalendarComponent, ReferenceImageManagerComponent],
  254. templateUrl: './project-detail.html',
  255. styleUrls: ['./project-detail.scss', './debug-styles.scss', './horizontal-panel.scss']
  256. })
  257. export class ProjectDetail implements OnInit, OnDestroy {
  258. // 项目基本数据
  259. projectId: string = '';
  260. project: Project | undefined;
  261. renderProgress: RenderProgress | undefined;
  262. feedbacks: CustomerFeedback[] = [];
  263. detailedReviews: DetailedCustomerReview[] = [];
  264. designerChanges: DesignerChange[] = [];
  265. settlements: Settlement[] = [];
  266. requirementChecklist: string[] = [];
  267. reminderMessage: string = '';
  268. isLoadingRenderProgress: boolean = false;
  269. errorLoadingRenderProgress: boolean = false;
  270. feedbackTimeoutCountdown: number = 0;
  271. private countdownInterval: any;
  272. projects: {id: string, name: string, status: string}[] = [];
  273. showDropdown: boolean = false;
  274. currentStage: string = '';
  275. // 新增:只读复盘模式(从财务工作台跳转)
  276. isReviewOnlyMode: boolean = false;
  277. // 新增:尾款结算完成状态
  278. isSettlementCompleted: boolean = false;
  279. isConfirmingSettlement: boolean = false;
  280. isSettlementInitiated: boolean = false;
  281. // 新增:自动化功能状态跟踪
  282. miniprogramPaymentStatus: 'active' | 'inactive' = 'inactive';
  283. voucherRecognitionCount: number = 0;
  284. notificationsSent: number = 0;
  285. isAutoSettling: boolean = false;
  286. isPaymentVerified: boolean = false;
  287. // 客户信息卡片展开/收起状态
  288. isCustomerInfoExpanded: boolean = false;
  289. // 新增:订单创建表单相关
  290. orderCreationForm!: FormGroup;
  291. optionalForm!: FormGroup;
  292. isOptionalFormExpanded: boolean = false;
  293. orderCreationData: any = null;
  294. // 新增:方案分析相关数据
  295. proposalAnalysis: ProposalAnalysis | null = null;
  296. isAnalyzing: boolean = false;
  297. analysisProgress: number = 0;
  298. // 新增:右侧色彩分析结果展示
  299. colorAnalysisResult: ColorAnalysisResult | null = null;
  300. dominantColorHex: string | null = null;
  301. // 新增:区分展示的参考图片与CAD文件(来源于需求确认子组件)
  302. referenceImages: any[] = [];
  303. cadFiles: any[] = [];
  304. // 新增:详细分析数据属性
  305. enhancedColorAnalysis: any = null;
  306. formAnalysis: any = null;
  307. textureAnalysis: any = null;
  308. patternAnalysis: any = null;
  309. lightingAnalysis: any = null;
  310. materialAnalysisData: any[] = [];
  311. // 新增:9阶段顺序(串式流程)- 包含后期阶段
  312. stageOrder: ProjectStage[] = ['订单创建', '需求沟通', '方案确认', '建模', '软装', '渲染', '后期', '尾款结算', '客户评价', '投诉处理'];
  313. // 新增:阶段展开状态(默认全部收起,当前阶段在数据加载后自动展开)
  314. expandedStages: Partial<Record<ProjectStage, boolean>> = {
  315. '订单创建': false,
  316. '需求沟通': false,
  317. '方案确认': false,
  318. '建模': false,
  319. '软装': false,
  320. '渲染': false,
  321. '后期': false,
  322. '尾款结算': false,
  323. '客户评价': false,
  324. '投诉处理': false,
  325. };
  326. // 新增:四大板块定义与展开状态 - 交付执行板块调整为三个阶段
  327. sections: Array<{ key: SectionKey; label: string; stages: ProjectStage[] }> = [
  328. { key: 'order', label: '订单创建', stages: ['订单创建'] },
  329. { key: 'requirements', label: '确认需求', stages: ['需求沟通', '方案确认'] },
  330. { key: 'delivery', label: '交付执行', stages: ['建模', '软装', '渲染', '后期'] },
  331. { key: 'aftercare', label: '售后', stages: [] }
  332. ];
  333. expandedSection: SectionKey | null = null;
  334. // 渲染异常反馈相关属性
  335. exceptionType: 'failed' | 'stuck' | 'quality' | 'other' = 'failed';
  336. exceptionDescription: string = '';
  337. exceptionScreenshotUrl: string | null = null;
  338. exceptionHistories: ExceptionHistory[] = [];
  339. isSubmittingFeedback: boolean = false;
  340. selectedScreenshot: File | null = null;
  341. screenshotPreview: string | null = null;
  342. showExceptionForm: boolean = false;
  343. // 标签页相关
  344. activeTab: 'progress' | 'members' | 'files' | 'reference' = 'progress';
  345. tabs: Array<{ id: 'progress' | 'members' | 'files' | 'reference'; name: string }> = [
  346. { id: 'progress', name: '项目进度' },
  347. { id: 'members', name: '项目成员' },
  348. { id: 'files', name: '项目文件' },
  349. { id: 'reference', name: '参考图管理' }
  350. ];
  351. // 标准化阶段(视图层映射)
  352. standardPhases: Array<'待分配' | '需求方案' | '项目执行' | '收尾验收' | '归档'> = ['待分配', '需求方案', '项目执行', '收尾验收', '归档'];
  353. // 文件上传(通用)
  354. acceptedFileTypes: string = '.doc,.docx,.pdf,.jpg,.jpeg,.png,.zip,.rar,.max,.obj';
  355. isUploadingFile: boolean = false;
  356. projectMembers: ProjectMember[] = [];
  357. // 项目文件数据
  358. projectFiles: ProjectFile[] = [];
  359. // 团队协作时间轴
  360. timelineEvents: TimelineEvent[] = [];
  361. // 团队分配弹窗相关
  362. selectedDesigner: any = null;
  363. projectData: any = null;
  364. // ============ 阶段图片上传状态(新增) ============
  365. allowedImageTypes: string = '.jpg,.jpeg,.png';
  366. // 增加审核状态reviewStatus与是否已同步synced标记(仅由组长操作)
  367. whiteModelImages: Array<{ id: string; name: string; url: string; size?: string; reviewStatus?: 'pending' | 'approved' | 'rejected'; synced?: boolean }> = [];
  368. softDecorImages: Array<{ id: string; name: string; url: string; size?: string; reviewStatus?: 'pending' | 'approved' | 'rejected'; synced?: boolean }> = [];
  369. renderLargeImages: Array<{ id: string; name: string; url: string; size?: string; locked?: boolean; reviewStatus?: 'pending' | 'approved' | 'rejected'; synced?: boolean }> = [];
  370. postProcessImages: Array<{ id: string; name: string; url: string; size?: string; reviewStatus?: 'pending' | 'approved' | 'rejected'; synced?: boolean }> = [];
  371. showRenderUploadModal: boolean = false;
  372. pendingRenderLargeItems: Array<{ id: string; name: string; url: string; file: File }> = [];
  373. // 视图上下文:根据路由前缀识别角色视角(客服/设计师/组长)
  374. roleContext: 'customer-service' | 'designer' | 'team-leader' | 'technical' = 'designer';
  375. // ============ 模型检查项数据 ============
  376. modelCheckItems: ModelCheckItem[] = [
  377. { id: 'check-1', name: '户型匹配度检查', isPassed: false, notes: '' },
  378. { id: 'check-2', name: '尺寸精度验证', isPassed: false, notes: '' },
  379. { id: 'check-3', name: '材质贴图检查', isPassed: false, notes: '' },
  380. { id: 'check-4', name: '光影效果验证', isPassed: false, notes: '' },
  381. { id: 'check-5', name: '细节完整性检查', isPassed: false, notes: '' }
  382. ];
  383. // ============ 交付执行板块数据 ============
  384. deliveryProcesses: DeliveryProcess[] = [
  385. {
  386. id: 'modeling',
  387. name: '建模',
  388. type: 'modeling',
  389. isExpanded: true, // 默认展开第一个
  390. spaces: [
  391. { id: 'bedroom', name: '卧室', isExpanded: false, order: 1 },
  392. { id: 'living', name: '客厅', isExpanded: false, order: 2 },
  393. { id: 'kitchen', name: '厨房', isExpanded: false, order: 3 }
  394. ],
  395. content: {
  396. 'bedroom': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() },
  397. 'living': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() },
  398. 'kitchen': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() }
  399. }
  400. },
  401. {
  402. id: 'softDecor',
  403. name: '软装',
  404. type: 'softDecor',
  405. isExpanded: false,
  406. spaces: [
  407. { id: 'bedroom', name: '卧室', isExpanded: false, order: 1 },
  408. { id: 'living', name: '客厅', isExpanded: false, order: 2 },
  409. { id: 'kitchen', name: '厨房', isExpanded: false, order: 3 }
  410. ],
  411. content: {
  412. 'bedroom': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() },
  413. 'living': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() },
  414. 'kitchen': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() }
  415. }
  416. },
  417. {
  418. id: 'rendering',
  419. name: '渲染',
  420. type: 'rendering',
  421. isExpanded: false,
  422. spaces: [
  423. { id: 'bedroom', name: '卧室', isExpanded: false, order: 1 },
  424. { id: 'living', name: '客厅', isExpanded: false, order: 2 },
  425. { id: 'kitchen', name: '厨房', isExpanded: false, order: 3 }
  426. ],
  427. content: {
  428. 'bedroom': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() },
  429. 'living': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() },
  430. 'kitchen': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() }
  431. }
  432. },
  433. {
  434. id: 'postProcess',
  435. name: '后期',
  436. type: 'postProcess',
  437. isExpanded: false,
  438. spaces: [
  439. { id: 'bedroom', name: '卧室', isExpanded: false, order: 1 },
  440. { id: 'living', name: '客厅', isExpanded: false, order: 2 },
  441. { id: 'kitchen', name: '厨房', isExpanded: false, order: 3 }
  442. ],
  443. content: {
  444. 'bedroom': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() },
  445. 'living': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() },
  446. 'kitchen': { images: [], progress: 0, status: 'pending', notes: '', lastUpdated: new Date() }
  447. }
  448. }
  449. ];
  450. // 新增空间输入框状态
  451. newSpaceName: { [processId: string]: string } = {};
  452. showAddSpaceInput: { [processId: string]: boolean } = {};
  453. constructor(
  454. private route: ActivatedRoute,
  455. private projectService: ProjectService,
  456. private router: Router,
  457. private fb: FormBuilder,
  458. private cdr: ChangeDetectorRef,
  459. private paymentVoucherService: PaymentVoucherRecognitionService,
  460. private projectReviewService: ProjectReviewService
  461. ) {}
  462. // 切换标签页
  463. switchTab(tabId: 'progress' | 'members' | 'files' | 'reference') {
  464. this.activeTab = tabId;
  465. }
  466. // 类型安全的标签页检查方法
  467. isActiveTab(tabId: 'progress' | 'members' | 'files' | 'reference'): boolean {
  468. return this.activeTab === tabId;
  469. }
  470. // 根据事件类型获取作者名称
  471. getEventAuthor(action: string): string {
  472. // 根据不同的action类型返回对应的作者名称
  473. switch(action) {
  474. case '完成':
  475. case '更新':
  476. case '优化':
  477. return '李设计师';
  478. case '收到':
  479. return '李客服';
  480. case '提交':
  481. return '赵建模师';
  482. default:
  483. return '王组长';
  484. }
  485. }
  486. // 切换项目
  487. switchProject(projectId: string): void {
  488. this.projectId = projectId;
  489. this.loadProjectData();
  490. this.loadProjectMembers();
  491. this.loadProjectFiles();
  492. this.loadTimelineEvents();
  493. // 更新URL但不触发组件重载
  494. this.router.navigate([], { relativeTo: this.route, queryParamsHandling: 'merge', queryParams: { id: projectId } });
  495. }
  496. // 检查是否处于订单创建阶段,用于红色高亮显示
  497. isCurrentOrderCreation(): boolean {
  498. // 只有当订单创建阶段是当前活跃阶段时才标红显示
  499. // 修复逻辑:完成前序环节后才标红当前阶段
  500. const currentStage = this.project?.currentStage;
  501. if (!currentStage) return false;
  502. // 如果当前阶段就是订单创建阶段,说明需要标红显示
  503. if (currentStage === '订单创建') return true;
  504. // 如果当前阶段在订单创建之后,说明订单创建已完成,不应标红
  505. const stageOrder = [
  506. '订单创建', '需求沟通', '方案确认', '建模', '软装',
  507. '渲染', '尾款结算', '客户评价', '投诉处理'
  508. ];
  509. const currentIndex = stageOrder.indexOf(currentStage);
  510. const orderCreationIndex = stageOrder.indexOf('订单创建');
  511. // 如果当前阶段在订单创建之后,说明订单创建已完成
  512. return currentIndex <= orderCreationIndex;
  513. }
  514. // 返回工作台
  515. backToWorkbench(): void {
  516. this.router.navigate(['/designer/dashboard']);
  517. }
  518. // 检查阶段是否已完成
  519. isStageCompleted(stage: ProjectStage): boolean {
  520. if (!this.project) return false;
  521. // 定义阶段顺序
  522. const stageOrder = [
  523. '订单创建', '需求沟通', '方案确认', '建模', '软装',
  524. '渲染', '尾款结算', '客户评价', '投诉处理'
  525. ];
  526. // 获取当前阶段和检查阶段的索引
  527. const currentStageIndex = stageOrder.indexOf(this.project.currentStage);
  528. const checkStageIndex = stageOrder.indexOf(stage);
  529. // 如果检查阶段在当前阶段之前,则已完成
  530. return checkStageIndex < currentStageIndex;
  531. }
  532. // 获取阶段状态:completed/active/pending
  533. getStageStatus(stage: ProjectStage): 'completed' | 'active' | 'pending' {
  534. const order = this.stageOrder;
  535. // 优先使用 currentStage 属性,如果没有则使用 project.currentStage
  536. const current = (this.currentStage as ProjectStage) || (this.project?.currentStage as ProjectStage | undefined);
  537. const currentIdx = current ? order.indexOf(current) : -1;
  538. const idx = order.indexOf(stage);
  539. if (idx === -1) return 'pending';
  540. if (currentIdx === -1) return 'pending';
  541. if (idx < currentIdx) return 'completed';
  542. if (idx === currentIdx) return 'active';
  543. return 'pending';
  544. }
  545. // 切换阶段展开/收起,并保持单展开
  546. toggleStage(stage: ProjectStage): void {
  547. // 已移除所有展开按钮,本方法保留以兼容模板其它引用,如无需可进一步删除调用点和方法
  548. const exclusivelyOpen = true;
  549. if (exclusivelyOpen) {
  550. Object.keys(this.expandedStages).forEach((key) => (this.expandedStages[key as ProjectStage] = false));
  551. this.expandedStages[stage] = true;
  552. } else {
  553. this.expandedStages[stage] = !this.expandedStages[stage];
  554. }
  555. }
  556. // 查看阶段详情(已不再通过按钮触发,保留以兼容日志或未来调用)
  557. viewStageDetails(stage: ProjectStage): void {
  558. // 以往这里有 alert/导航行为,现清空用户交互,避免误触
  559. return;
  560. }
  561. ngOnInit(): void {
  562. // 检查是否为只读复盘模式(从财务工作台跳转)
  563. this.route.queryParams.subscribe(params => {
  564. if (params['view'] === 'review-only') {
  565. this.isReviewOnlyMode = true;
  566. }
  567. // 检查是否需要直接定位到售后板块
  568. if (params['section'] === 'aftercare' || params['view'] === 'review-only') {
  569. // 自动切换到售后板块
  570. this.expandedSection = 'aftercare';
  571. // 滚动到项目复盘区域
  572. setTimeout(() => {
  573. const reviewSection = document.querySelector('.project-review-section');
  574. if (reviewSection) {
  575. reviewSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
  576. }
  577. }, 500);
  578. }
  579. });
  580. // 初始化表单
  581. this.initializeForms();
  582. // 初始化需求关键信息数据
  583. this.ensureRequirementData();
  584. // 重置方案分析状态,确保需求信息展示区域能够显示
  585. this.resetProposalAnalysis();
  586. // 初始化售后模块示例数据
  587. this.initializeAftercareData();
  588. this.route.paramMap.subscribe(params => {
  589. this.projectId = params.get('id') || '';
  590. // 根据当前URL检测视图上下文
  591. this.roleContext = this.detectRoleContextFromUrl();
  592. this.loadProjectData();
  593. this.loadExceptionHistories();
  594. this.loadProjectMembers();
  595. this.loadProjectFiles();
  596. this.loadTimelineEvents();
  597. // 启动客户信息自动同步
  598. this.startAutoSync();
  599. });
  600. // 新增:监听查询参数,支持通过 activeTab 设置初始标签页和 currentStage 设置当前阶段
  601. this.route.queryParamMap.subscribe(qp => {
  602. const raw = qp.get('activeTab');
  603. const alias: Record<string, 'progress' | 'members' | 'files' | 'reference'> = {
  604. requirements: 'progress',
  605. overview: 'progress'
  606. };
  607. const tab = raw && (raw in alias ? alias[raw] : raw);
  608. if (tab === 'progress' || tab === 'members' || tab === 'files' || tab === 'reference') {
  609. this.activeTab = tab;
  610. }
  611. // 处理 currentStage 查询参数
  612. const currentStageParam = qp.get('currentStage');
  613. if (currentStageParam) {
  614. this.currentStage = currentStageParam;
  615. // 根据当前阶段设置项目状态和展开相应区域
  616. this.initializeStageFromRoute(currentStageParam as ProjectStage);
  617. // 根据当前阶段自动展开对应的区域
  618. const sectionKey = this.getSectionKeyForStage(currentStageParam as ProjectStage);
  619. if (sectionKey) {
  620. this.expandedSection = sectionKey;
  621. }
  622. // 延迟滚动到对应阶段
  623. setTimeout(() => {
  624. this.scrollToStage(currentStageParam as ProjectStage);
  625. }, 500);
  626. }
  627. // 处理从客服项目列表传递的同步数据
  628. const syncDataParam = qp.get('syncData');
  629. if (syncDataParam) {
  630. try {
  631. const syncData = JSON.parse(syncDataParam);
  632. console.log('接收到客服同步数据:', syncData);
  633. // 设置同步状态
  634. this.isSyncingCustomerInfo = true;
  635. // 存储订单创建数据用于显示
  636. this.orderCreationData = syncData;
  637. // 更新projectData以传递给子组件
  638. this.projectData = {
  639. customerInfo: syncData.customerInfo,
  640. requirementInfo: syncData.requirementInfo,
  641. preferenceTags: syncData.preferenceTags
  642. };
  643. // 同步客户信息到表单
  644. if (syncData.customerInfo) {
  645. this.customerForm.patchValue({
  646. name: syncData.customerInfo.name || '',
  647. phone: syncData.customerInfo.phone || '',
  648. wechat: syncData.customerInfo.wechat || '',
  649. customerType: syncData.customerInfo.customerType || '新客户',
  650. source: syncData.customerInfo.source || '小程序',
  651. remark: syncData.customerInfo.remark || '',
  652. demandType: syncData.customerInfo.demandType || '',
  653. followUpStatus: syncData.customerInfo.followUpStatus || '待分配'
  654. });
  655. // 设置选中的客户
  656. this.selectedOrderCustomer = {
  657. id: syncData.customerInfo.id || 'temp-' + Date.now(),
  658. name: syncData.customerInfo.name,
  659. phone: syncData.customerInfo.phone,
  660. wechat: syncData.customerInfo.wechat,
  661. customerType: syncData.customerInfo.customerType,
  662. source: syncData.customerInfo.source,
  663. remark: syncData.customerInfo.remark
  664. };
  665. }
  666. // 同步需求信息
  667. if (syncData.requirementInfo) {
  668. this.syncRequirementKeyInfo(syncData.requirementInfo);
  669. }
  670. // 同步偏好标签到项目数据
  671. if (syncData.preferenceTags && this.project) {
  672. this.project.customerTags = syncData.preferenceTags.map((tag: string) => ({
  673. source: '客服填写',
  674. needType: tag,
  675. preference: tag,
  676. colorAtmosphere: tag
  677. }));
  678. }
  679. // 模拟同步完成
  680. setTimeout(() => {
  681. this.isSyncingCustomerInfo = false;
  682. this.lastSyncTime = new Date();
  683. this.cdr.detectChanges();
  684. console.log('客户信息同步完成');
  685. }, 1500);
  686. // 触发界面更新
  687. this.cdr.detectChanges();
  688. console.log('客服数据同步完成,orderCreationData:', this.orderCreationData);
  689. } catch (error) {
  690. console.error('解析同步数据失败:', error);
  691. this.isSyncingCustomerInfo = false;
  692. }
  693. }
  694. });
  695. // 添加点击事件监听器,当点击页面其他位置时关闭下拉菜单
  696. document.addEventListener('click', this.closeDropdownOnClickOutside);
  697. // 初始化客户表单(与客服端保持一致)
  698. this.customerForm = this.fb.group({
  699. name: ['', Validators.required],
  700. phone: ['', [Validators.required, Validators.pattern(/^1[3-9]\d{9}$/)]],
  701. wechat: [''],
  702. customerType: ['新客户'],
  703. source: [''],
  704. remark: [''],
  705. demandType: [''],
  706. followUpStatus: ['']
  707. });
  708. // 自动生成下单时间
  709. this.orderTime = new Date().toLocaleString('zh-CN', {
  710. year: 'numeric', month: '2-digit', day: '2-digit',
  711. hour: '2-digit', minute: '2-digit', second: '2-digit'
  712. });
  713. }
  714. // 新增:根据路由参数初始化阶段状态
  715. private initializeStageFromRoute(targetStage: ProjectStage): void {
  716. // 设置当前阶段
  717. this.currentStage = targetStage;
  718. // 根据目标阶段设置之前的阶段为已完成
  719. const targetIndex = this.stageOrder.indexOf(targetStage);
  720. if (targetIndex > 0) {
  721. // 将目标阶段之前的所有阶段设置为已完成
  722. for (let i = 0; i < targetIndex; i++) {
  723. const stage = this.stageOrder[i];
  724. this.expandedStages[stage] = false; // 已完成的阶段收起
  725. }
  726. }
  727. // 展开当前阶段
  728. this.expandedStages[targetStage] = true;
  729. // 如果项目对象存在,更新项目的当前阶段
  730. if (this.project) {
  731. this.project.currentStage = targetStage;
  732. }
  733. // 触发变更检测以更新UI
  734. this.cdr.detectChanges();
  735. }
  736. ngOnDestroy(): void {
  737. if (this.countdownInterval) {
  738. clearInterval(this.countdownInterval);
  739. }
  740. // 停止自动同步
  741. this.stopAutoSync();
  742. document.removeEventListener('click', this.closeDropdownOnClickOutside);
  743. // 释放所有 blob 预览 URL
  744. const revokeList: string[] = [];
  745. this.whiteModelImages.forEach(i => { if (i.url.startsWith('blob:')) revokeList.push(i.url); });
  746. this.softDecorImages.forEach(i => { if (i.url.startsWith('blob:')) revokeList.push(i.url); });
  747. this.renderLargeImages.forEach(i => { if (i.url.startsWith('blob:')) revokeList.push(i.url); });
  748. this.pendingRenderLargeItems.forEach(i => { if (i.url.startsWith('blob:')) revokeList.push(i.url); });
  749. revokeList.forEach(u => URL.revokeObjectURL(u));
  750. }
  751. // ============ 角色视图与只读控制(新增) ============
  752. private detectRoleContextFromUrl(): 'customer-service' | 'designer' | 'team-leader' | 'technical' {
  753. const url = this.router.url || '';
  754. // 首先检查查询参数中的role
  755. const queryParams = this.route.snapshot.queryParamMap;
  756. const roleParam = queryParams.get('role');
  757. if (roleParam === 'customer-service') {
  758. return 'customer-service';
  759. }
  760. if (roleParam === 'technical') {
  761. return 'technical';
  762. }
  763. // 如果没有role查询参数,则根据URL路径判断
  764. if (url.includes('/customer-service/')) return 'customer-service';
  765. if (url.includes('/team-leader/')) return 'team-leader';
  766. if (url.includes('/technical/')) return 'technical';
  767. return 'designer';
  768. }
  769. isDesignerView(): boolean { return this.roleContext === 'designer'; }
  770. isTeamLeaderView(): boolean { return this.roleContext === 'team-leader'; }
  771. isCustomerServiceView(): boolean { return this.roleContext === 'customer-service'; }
  772. isTechnicalView(): boolean { return this.roleContext === 'technical'; }
  773. // 只读规则:客服视角为只读
  774. isReadOnly(): boolean { return this.isCustomerServiceView(); }
  775. // 权限控制:客服只能编辑订单创建、确认需求、售后板块
  776. canEditSection(sectionKey: SectionKey): boolean {
  777. if (this.isCustomerServiceView()) {
  778. return sectionKey === 'order' || sectionKey === 'requirements' || sectionKey === 'aftercare';
  779. }
  780. return true; // 设计师和组长可以编辑所有板块
  781. }
  782. // 权限控制:客服只能编辑特定阶段
  783. canEditStage(stage: ProjectStage): boolean {
  784. if (this.isCustomerServiceView()) {
  785. const editableStages: ProjectStage[] = [
  786. '订单创建', '需求沟通', '方案确认', // 订单创建和确认需求板块
  787. '尾款结算', '客户评价', '投诉处理' // 售后板块
  788. ];
  789. return editableStages.includes(stage);
  790. }
  791. return true; // 设计师和组长可以编辑所有阶段
  792. }
  793. // 计算当前激活板块:优先用户点击的 expandedSection;否则取当前阶段所属板块;再否则回退首个板块
  794. private getActiveSectionKey(): SectionKey {
  795. if (this.expandedSection) return this.expandedSection;
  796. const current = this.project?.currentStage as ProjectStage | undefined;
  797. return current ? this.getSectionKeyForStage(current) : this.sections[0].key;
  798. }
  799. // 返回当前板块的全部阶段(所有角色一致):
  800. // 设计师也可查看 订单创建/确认需求/售后 板块内容
  801. getVisibleStages(): ProjectStage[] {
  802. const activeKey = this.getActiveSectionKey();
  803. const sec = this.sections.find(s => s.key === activeKey);
  804. return sec ? sec.stages : [];
  805. }
  806. // ============ 组长:同步上传与审核(新增,模拟实现) ============
  807. syncUploadedImages(phase: 'white' | 'soft' | 'render' | 'postProcess'): void {
  808. if (!this.isTeamLeaderView()) return;
  809. const markSynced = (arr: Array<{ reviewStatus?: 'pending'|'approved'|'rejected'; synced?: boolean }>) => {
  810. arr.forEach(img => {
  811. if (!img.synced) img.synced = true;
  812. if (!img.reviewStatus) img.reviewStatus = 'pending';
  813. });
  814. };
  815. if (phase === 'white') markSynced(this.whiteModelImages);
  816. if (phase === 'soft') markSynced(this.softDecorImages);
  817. if (phase === 'render') markSynced(this.renderLargeImages);
  818. if (phase === 'postProcess') markSynced(this.postProcessImages);
  819. alert('已同步该阶段的图片信息(模拟)');
  820. }
  821. reviewImage(imageId: string, phase: 'white' | 'soft' | 'render' | 'postProcess', status: 'approved' | 'rejected'): void {
  822. if (!this.isTeamLeaderView()) return;
  823. const setStatus = (arr: Array<{ id: string; reviewStatus?: 'pending'|'approved'|'rejected'; synced?: boolean }>) => {
  824. const target = arr.find(i => i.id === imageId);
  825. if (target) {
  826. target.reviewStatus = status;
  827. if (!target.synced) target.synced = true; // 审核时自动视为已同步
  828. }
  829. };
  830. if (phase === 'white') setStatus(this.whiteModelImages);
  831. if (phase === 'soft') setStatus(this.softDecorImages);
  832. if (phase === 'render') setStatus(this.renderLargeImages);
  833. if (phase === 'postProcess') setStatus(this.postProcessImages);
  834. }
  835. getImageReviewStatusText(img: { reviewStatus?: 'pending'|'approved'|'rejected'; synced?: boolean }): string {
  836. const synced = img.synced ? '已同步' : '未同步';
  837. const map: Record<string, string> = {
  838. 'pending': '待审',
  839. 'approved': '已通过',
  840. 'rejected': '已驳回'
  841. };
  842. const st = img.reviewStatus ? map[img.reviewStatus] : '未标记';
  843. return `${st} · ${synced}`;
  844. }
  845. // 点击页面其他位置时关闭下拉菜单
  846. private closeDropdownOnClickOutside = (event: MouseEvent): void => {
  847. const targetElement = event.target as HTMLElement;
  848. const projectSwitcher = targetElement.closest('.project-switcher');
  849. if (!projectSwitcher && this.showDropdown) {
  850. this.showDropdown = false;
  851. }
  852. };
  853. loadProjectData(): void {
  854. if (this.projectId) {
  855. this.loadProjectDetails();
  856. this.loadRenderProgress();
  857. this.loadCustomerFeedbacks();
  858. this.loadDesignerChanges();
  859. this.loadSettlements();
  860. this.loadRequirementChecklist();
  861. }
  862. // 初始化项目列表数据(模拟)
  863. this.projects = [
  864. { id: '1', name: '现代风格客厅设计', status: '进行中' },
  865. { id: '2', name: '北欧风卧室装修', status: '已完成' },
  866. { id: '3', name: '新中式书房改造', status: '进行中' },
  867. { id: '4', name: '工业风餐厅设计', status: '待处理' }
  868. ];
  869. }
  870. // 加载项目成员数据
  871. loadProjectMembers(): void {
  872. // 模拟API请求获取项目成员数据
  873. setTimeout(() => {
  874. this.projectMembers = [
  875. {
  876. id: '1',
  877. name: '李设计师',
  878. role: '主设计师',
  879. avatar: '李',
  880. skillMatch: 95,
  881. progress: 65,
  882. contribution: 75
  883. },
  884. {
  885. id: '2',
  886. name: '陈设计师',
  887. role: '助理设计师',
  888. avatar: '陈',
  889. skillMatch: 88,
  890. progress: 80,
  891. contribution: 60
  892. },
  893. {
  894. id: '3',
  895. name: '王组长',
  896. role: '项目组长',
  897. avatar: '王',
  898. skillMatch: 92,
  899. progress: 70,
  900. contribution: 70
  901. },
  902. {
  903. id: '4',
  904. name: '赵建模师',
  905. role: '3D建模师',
  906. avatar: '赵',
  907. skillMatch: 90,
  908. progress: 90,
  909. contribution: 85
  910. }
  911. ];
  912. }, 600);
  913. }
  914. // 加载项目文件数据
  915. loadProjectFiles(): void {
  916. // 模拟API请求获取项目文件数据
  917. setTimeout(() => {
  918. this.projectFiles = [
  919. {
  920. id: '1',
  921. name: '客厅设计方案V2.0.pdf',
  922. type: 'pdf',
  923. size: '2.5MB',
  924. date: '2024-02-10',
  925. url: '#'
  926. },
  927. {
  928. id: '2',
  929. name: '材质库集合.rar',
  930. type: 'rar',
  931. size: '45.8MB',
  932. date: '2024-02-08',
  933. url: '#'
  934. },
  935. {
  936. id: '3',
  937. name: '客厅渲染预览1.jpg',
  938. type: 'jpg',
  939. size: '3.2MB',
  940. date: '2024-02-14',
  941. url: '#'
  942. },
  943. {
  944. id: '4',
  945. name: '3D模型文件.max',
  946. type: 'max',
  947. size: '87.5MB',
  948. date: '2024-02-12',
  949. url: '#'
  950. },
  951. {
  952. id: '5',
  953. name: '客户需求文档.docx',
  954. type: 'docx',
  955. size: '1.2MB',
  956. date: '2024-01-15',
  957. url: '#'
  958. },
  959. {
  960. id: '6',
  961. name: '客厅渲染预览2.jpg',
  962. type: 'jpg',
  963. size: '3.8MB',
  964. date: '2024-02-15',
  965. url: '#'
  966. }
  967. ];
  968. }, 700);
  969. }
  970. // 加载团队协作时间轴数据
  971. loadTimelineEvents(): void {
  972. // 模拟API请求获取时间轴数据
  973. setTimeout(() => {
  974. this.timelineEvents = [
  975. {
  976. id: '1',
  977. time: '2024-02-15 14:30',
  978. title: '渲染完成',
  979. action: '完成',
  980. description: '客厅主视角渲染已完成,等待客户确认'
  981. },
  982. {
  983. id: '2',
  984. time: '2024-02-14 10:15',
  985. title: '材质调整',
  986. action: '更新',
  987. description: '根据客户反馈调整了沙发和窗帘材质'
  988. },
  989. {
  990. id: '3',
  991. time: '2024-02-12 16:45',
  992. title: '模型优化',
  993. action: '优化',
  994. description: '优化了模型面数,提高渲染效率'
  995. },
  996. {
  997. id: '4',
  998. time: '2024-02-10 09:30',
  999. title: '客户反馈',
  1000. action: '收到',
  1001. description: '收到客户关于颜色和储物空间的反馈意见'
  1002. },
  1003. {
  1004. id: '5',
  1005. time: '2024-02-08 15:20',
  1006. title: '模型提交',
  1007. action: '提交',
  1008. description: '完成3D模型搭建并提交审核'
  1009. }
  1010. ];
  1011. }, 800);
  1012. }
  1013. // 加载历史反馈记录
  1014. loadExceptionHistories(): void {
  1015. this.projectService.getExceptionHistories(this.projectId).subscribe(histories => {
  1016. this.exceptionHistories = histories;
  1017. });
  1018. }
  1019. loadProjectDetails(): void {
  1020. console.log('=== loadProjectDetails 开始加载项目数据 ===');
  1021. console.log('当前项目ID:', this.projectId);
  1022. this.projectService.getProjectById(this.projectId).subscribe(project => {
  1023. console.log('获取到的项目数据:', project);
  1024. if (!project) {
  1025. console.error('未找到项目数据,项目ID:', this.projectId);
  1026. // 如果找不到项目,尝试使用默认项目ID
  1027. console.log('尝试使用默认项目ID: proj-001');
  1028. this.projectService.getProjectById('proj-001').subscribe(defaultProject => {
  1029. console.log('默认项目数据:', defaultProject);
  1030. if (defaultProject) {
  1031. this.project = defaultProject;
  1032. this.currentStage = defaultProject.currentStage || '';
  1033. console.log('使用默认项目,设置当前阶段:', this.currentStage);
  1034. this.setupStageExpansion(defaultProject);
  1035. }
  1036. });
  1037. return;
  1038. }
  1039. this.project = project;
  1040. // 设置当前阶段
  1041. if (project) {
  1042. this.currentStage = project.currentStage || '';
  1043. console.log('设置当前阶段:', this.currentStage);
  1044. this.setupStageExpansion(project);
  1045. }
  1046. // 检查技能匹配度 - 已注释掉以取消弹窗警告
  1047. // this.checkSkillMismatch();
  1048. });
  1049. }
  1050. private setupStageExpansion(project: any): void {
  1051. // 重置展开状态并默认展开当前阶段
  1052. this.stageOrder.forEach(s => this.expandedStages[s] = false);
  1053. const currentStage = project.currentStage as ProjectStage;
  1054. if (this.stageOrder.includes(currentStage)) {
  1055. this.expandedStages[currentStage] = true;
  1056. console.log('展开当前阶段:', currentStage);
  1057. }
  1058. // 新增:根据当前阶段默认展开所属板块
  1059. const currentSec = this.getSectionKeyForStage(currentStage);
  1060. this.expandedSection = currentSec;
  1061. console.log('展开板块:', currentSec);
  1062. // 新增:如果当前阶段是建模、软装或渲染,自动展开对应的折叠面板
  1063. if (currentStage === '建模' || currentStage === '软装' || currentStage === '渲染') {
  1064. const processTypeMap = {
  1065. '建模': 'modeling',
  1066. '软装': 'softDecor',
  1067. '渲染': 'rendering'
  1068. };
  1069. const processType = processTypeMap[currentStage] as 'modeling' | 'softDecor' | 'rendering';
  1070. const targetProcess = this.deliveryProcesses.find(p => p.type === processType);
  1071. if (targetProcess) {
  1072. // 展开对应的流程面板
  1073. targetProcess.isExpanded = true;
  1074. // 展开第一个空间以便用户操作
  1075. if (targetProcess.spaces.length > 0) {
  1076. targetProcess.spaces[0].isExpanded = true;
  1077. // 关闭其他空间
  1078. targetProcess.spaces.slice(1).forEach(space => space.isExpanded = false);
  1079. }
  1080. console.log('自动展开折叠面板:', currentStage, processType);
  1081. }
  1082. }
  1083. }
  1084. // 整理项目详情
  1085. organizeProject(): void {
  1086. // 模拟整理项目逻辑
  1087. alert('项目详情已整理');
  1088. }
  1089. // 检查当前阶段是否显示特定卡片
  1090. shouldShowCard(cardType: string): boolean {
  1091. // 改为始终显示:各阶段详情在看板下方就地展示,不再受当前阶段限制
  1092. return true;
  1093. }
  1094. loadRenderProgress(): void {
  1095. this.isLoadingRenderProgress = true;
  1096. this.errorLoadingRenderProgress = false;
  1097. // 模拟API加载过程
  1098. setTimeout(() => {
  1099. this.projectService.getRenderProgress(this.projectId).subscribe(progress => {
  1100. this.renderProgress = progress;
  1101. this.isLoadingRenderProgress = false;
  1102. // 模拟API加载失败的情况
  1103. if (!progress) {
  1104. this.errorLoadingRenderProgress = true;
  1105. // 通知技术组长
  1106. this.notifyTeamLeader('render-failed');
  1107. } else {
  1108. // 检查是否需要显示超时预警
  1109. this.checkRenderTimeout();
  1110. }
  1111. });
  1112. }, 1000);
  1113. }
  1114. loadCustomerFeedbacks(): void {
  1115. this.projectService.getCustomerFeedbacks().subscribe(feedbacks => {
  1116. this.feedbacks = feedbacks.filter(f => f.projectId === this.projectId);
  1117. // 为反馈添加分类标签
  1118. this.tagCustomerFeedbacks();
  1119. // 检查是否有需要处理的反馈并启动倒计时
  1120. this.checkFeedbackTimeout();
  1121. });
  1122. }
  1123. loadDesignerChanges(): void {
  1124. // 在实际应用中,这里应该从服务中获取设计师变更记录
  1125. // 这里使用模拟数据
  1126. this.designerChanges = [
  1127. {
  1128. id: 'dc1',
  1129. projectId: this.projectId,
  1130. oldDesignerId: 'designer2',
  1131. oldDesignerName: '设计师B',
  1132. newDesignerId: 'designer1',
  1133. newDesignerName: '设计师A',
  1134. changeTime: new Date('2025-09-05'),
  1135. acceptanceTime: new Date('2025-09-05'),
  1136. historicalAchievements: ['完成初步建模', '确定色彩方案'],
  1137. completedWorkload: 30
  1138. }
  1139. ];
  1140. }
  1141. loadSettlements(): void {
  1142. this.projectService.getSettlements().subscribe(settlements => {
  1143. this.settlements = settlements.filter(s => s.projectId === this.projectId);
  1144. });
  1145. }
  1146. loadRequirementChecklist(): void {
  1147. this.projectService.generateRequirementChecklist(this.projectId).subscribe(checklist => {
  1148. this.requirementChecklist = checklist;
  1149. });
  1150. }
  1151. updateFeedbackStatus(feedbackId: string, status: '处理中' | '已解决'): void {
  1152. this.projectService.updateFeedbackStatus(feedbackId, status).subscribe(() => {
  1153. this.loadCustomerFeedbacks(); // 重新加载反馈
  1154. // 清除倒计时
  1155. if (this.countdownInterval) {
  1156. clearInterval(this.countdownInterval);
  1157. this.feedbackTimeoutCountdown = 0;
  1158. }
  1159. });
  1160. }
  1161. updateProjectStage(stage: ProjectStage): void {
  1162. if (this.project) {
  1163. this.projectService.updateProjectStage(this.projectId, stage).subscribe(() => {
  1164. this.currentStage = stage; // 同步更新本地状态
  1165. this.project!.currentStage = stage; // 同步更新project对象的currentStage
  1166. this.loadProjectDetails(); // 重新加载项目详情
  1167. this.cdr.detectChanges(); // 触发变更检测以更新导航栏颜色
  1168. });
  1169. }
  1170. }
  1171. // 新增:根据给定阶段跳转到下一阶段
  1172. advanceToNextStage(afterStage: ProjectStage): void {
  1173. const idx = this.stageOrder.indexOf(afterStage);
  1174. if (idx >= 0 && idx < this.stageOrder.length - 1) {
  1175. const next = this.stageOrder[idx + 1];
  1176. this.updateProjectStage(next);
  1177. // 更新展开状态,折叠当前、展开下一阶段,提升体验
  1178. if (this.expandedStages[afterStage] !== undefined) this.expandedStages[afterStage] = false as any;
  1179. if (this.expandedStages[next] !== undefined) this.expandedStages[next] = true as any;
  1180. // 更新板块展开状态
  1181. const nextSection = this.getSectionKeyForStage(next);
  1182. this.expandedSection = nextSection;
  1183. // 新增:自动展开对应阶段的折叠面板
  1184. if (next === '软装' || next === '渲染') {
  1185. const processType = next === '软装' ? 'softDecor' : 'rendering';
  1186. const targetProcess = this.deliveryProcesses.find(p => p.type === processType);
  1187. if (targetProcess) {
  1188. // 展开对应的流程面板
  1189. targetProcess.isExpanded = true;
  1190. // 展开第一个空间以便用户操作
  1191. if (targetProcess.spaces.length > 0) {
  1192. targetProcess.spaces[0].isExpanded = true;
  1193. // 关闭其他空间
  1194. targetProcess.spaces.slice(1).forEach(space => space.isExpanded = false);
  1195. }
  1196. }
  1197. }
  1198. // 触发变更检测以更新导航栏颜色
  1199. this.cdr.detectChanges();
  1200. }
  1201. }
  1202. generateReminderMessage(): void {
  1203. this.projectService.generateReminderMessage('stagnation').subscribe(message => {
  1204. this.reminderMessage = message;
  1205. // 3秒后自动清除提醒
  1206. setTimeout(() => {
  1207. this.reminderMessage = '';
  1208. }, 3000);
  1209. });
  1210. }
  1211. // ============ 新增:标准化阶段映射与紧急程度 ============
  1212. // 计算距离截止日期的天数(向下取整)
  1213. getDaysToDeadline(): number | null {
  1214. if (!this.project?.deadline) return null;
  1215. const now = new Date();
  1216. const deadline = new Date(this.project.deadline);
  1217. const diffMs = deadline.getTime() - now.getTime();
  1218. return Math.floor(diffMs / (1000 * 60 * 60 * 24));
  1219. }
  1220. // 是否延期/临期/提示
  1221. getUrgencyBadge(): 'overdue' | 'due_3' | 'due_7' | null {
  1222. const d = this.getDaysToDeadline();
  1223. if (d === null) return null;
  1224. if (d < 0) return 'overdue';
  1225. if (d <= 3) return 'due_3';
  1226. if (d <= 7) return 'due_7';
  1227. return null;
  1228. }
  1229. // 是否存在不满意或待处理投诉/反馈
  1230. hasPendingComplaint(): boolean {
  1231. return this.feedbacks.some(f => !f.isSatisfied || f.status === '待处理');
  1232. }
  1233. // 将现有细分阶段映射为标准化阶段
  1234. mapToStandardPhase(stage: ProjectStage): '待分配' | '需求方案' | '项目执行' | '收尾验收' | '归档' {
  1235. const mapping: Record<ProjectStage, '待分配' | '需求方案' | '项目执行' | '收尾验收' | '归档'> = {
  1236. '订单创建': '待分配',
  1237. '需求沟通': '需求方案',
  1238. '方案确认': '需求方案',
  1239. '建模': '项目执行',
  1240. '软装': '项目执行',
  1241. '渲染': '项目执行',
  1242. '后期': '项目执行',
  1243. '尾款结算': '收尾验收',
  1244. '客户评价': '收尾验收',
  1245. '投诉处理': '收尾验收'
  1246. };
  1247. return mapping[stage] ?? '待分配';
  1248. }
  1249. getStandardPhaseIndex(): number {
  1250. if (!this.project?.currentStage) return 0;
  1251. const phase = this.mapToStandardPhase(this.project.currentStage);
  1252. return this.standardPhases.indexOf(phase);
  1253. }
  1254. isStandardPhaseCompleted(phase: '待分配' | '需求方案' | '项目执行' | '收尾验收' | '归档'): boolean {
  1255. return this.standardPhases.indexOf(phase) < this.getStandardPhaseIndex();
  1256. }
  1257. isStandardPhaseCurrent(phase: '待分配' | '需求方案' | '项目执行' | '收尾验收' | '归档'): boolean {
  1258. return this.standardPhases.indexOf(phase) === this.getStandardPhaseIndex();
  1259. }
  1260. // ============ 新增:项目报告导出 ============
  1261. exportProjectReport(): void {
  1262. if (!this.project) return;
  1263. const lines: string[] = [];
  1264. const d = this.getDaysToDeadline();
  1265. lines.push(`项目名称: ${this.project.name}`);
  1266. lines.push(`当前阶段(细分): ${this.project.currentStage}`);
  1267. lines.push(`当前阶段(标准化): ${this.mapToStandardPhase(this.project.currentStage)}`);
  1268. if (this.project.deadline) {
  1269. lines.push(`截止日期: ${this.formatDate(this.project.deadline)}`);
  1270. lines.push(`剩余天数: ${d !== null ? d : '-'}天`);
  1271. }
  1272. lines.push(`技能需求: ${(this.project.skillsRequired || []).join('、')}`);
  1273. lines.push('—— 渲染进度 ——');
  1274. lines.push(this.renderProgress ? `状态: ${this.renderProgress.status}, 完成度: ${this.renderProgress.completionRate}%` : '无渲染进度数据');
  1275. lines.push('—— 客户反馈 ——');
  1276. lines.push(this.feedbacks.length ? `${this.feedbacks.length} 条` : '暂无');
  1277. lines.push('—— 设计师变更 ——');
  1278. lines.push(this.designerChanges.length ? `${this.designerChanges.length} 条` : '暂无');
  1279. lines.push('—— 交付文件 ——');
  1280. lines.push(this.projectFiles.length ? this.projectFiles.map(f => `• ${f.name} (${f.type}, ${f.size})`).join('\n') : '暂无');
  1281. const content = lines.join('\n');
  1282. const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
  1283. const url = URL.createObjectURL(blob);
  1284. const a = document.createElement('a');
  1285. a.href = url;
  1286. a.download = `${this.project.name || '项目'}-阶段报告.txt`;
  1287. a.click();
  1288. URL.revokeObjectURL(url);
  1289. }
  1290. // ============ 新增:通用文件上传(含4K图片校验) ============
  1291. async onGeneralFilesSelected(event: Event): Promise<void> {
  1292. const input = event.target as HTMLInputElement;
  1293. if (!input.files || input.files.length === 0) return;
  1294. const files = Array.from(input.files);
  1295. this.isUploadingFile = true;
  1296. for (const file of files) {
  1297. // 对图片进行4K校验(最大边 >= 4000px)
  1298. if (/\.(jpg|jpeg|png)$/i.test(file.name)) {
  1299. const ok = await this.validateImage4K(file).catch(() => false);
  1300. if (!ok) {
  1301. alert(`图片不符合4K标准(最大边需≥4000像素):${file.name}`);
  1302. continue;
  1303. }
  1304. }
  1305. // 简化:直接追加到本地列表(实际应上传到服务器)
  1306. const fakeType = (file.name.split('.').pop() || '').toLowerCase();
  1307. const sizeMB = (file.size / (1024 * 1024)).toFixed(1) + 'MB';
  1308. const nowStr = this.formatDate(new Date());
  1309. this.projectFiles.unshift({
  1310. id: `file-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
  1311. name: file.name,
  1312. type: fakeType,
  1313. size: sizeMB,
  1314. date: nowStr,
  1315. url: '#'
  1316. });
  1317. }
  1318. this.isUploadingFile = false;
  1319. // 清空选择
  1320. input.value = '';
  1321. }
  1322. validateImage4K(file: File): Promise<boolean> {
  1323. return new Promise((resolve, reject) => {
  1324. const reader = new FileReader();
  1325. reader.onload = () => {
  1326. const img = new Image();
  1327. img.onload = () => {
  1328. const maxSide = Math.max(img.width, img.height);
  1329. resolve(maxSide >= 4000);
  1330. };
  1331. img.onerror = () => reject('image load error');
  1332. img.src = reader.result as string;
  1333. };
  1334. reader.onerror = () => reject('read error');
  1335. reader.readAsDataURL(file);
  1336. });
  1337. }
  1338. // 可选:列表 trackBy,优化渲染
  1339. trackById(_: number, item: { id: string }): string { return item.id; }
  1340. retryLoadRenderProgress(): void {
  1341. this.loadRenderProgress();
  1342. }
  1343. // 检查是否所有模型检查项都已通过
  1344. // 获取技能匹配度警告
  1345. getSkillMismatchWarning(): string | null {
  1346. if (!this.project) return null;
  1347. // 模拟技能匹配度检查
  1348. const designerSkills = ['现代风格', '硬装'];
  1349. const requiredSkills = this.project.skillsRequired;
  1350. const mismatchedSkills = requiredSkills.filter(skill => !designerSkills.includes(skill));
  1351. if (mismatchedSkills.length > 0) {
  1352. return `警告:您不擅长${mismatchedSkills.join('、')},建议联系组长协调`;
  1353. }
  1354. return null;
  1355. }
  1356. // 检查渲染是否超时
  1357. checkRenderTimeout(): void {
  1358. if (!this.renderProgress || !this.project) return;
  1359. // 模拟交付前3小时预警
  1360. const deliveryTime = new Date(this.project.deadline);
  1361. const currentTime = new Date();
  1362. const timeDifference = deliveryTime.getTime() - currentTime.getTime();
  1363. const hoursRemaining = Math.floor(timeDifference / (1000 * 60 * 60));
  1364. if (hoursRemaining <= 3 && hoursRemaining > 0) {
  1365. // 弹窗预警
  1366. alert('渲染进度预警:交付前3小时,请关注渲染进度');
  1367. }
  1368. if (hoursRemaining <= 1 && hoursRemaining > 0) {
  1369. // 更严重的预警
  1370. alert('渲染进度严重预警:交付前1小时,渲染可能无法按时完成!');
  1371. }
  1372. }
  1373. // 为客户反馈添加分类标签
  1374. tagCustomerFeedbacks(): void {
  1375. this.feedbacks.forEach(feedback => {
  1376. // 添加分类标签
  1377. if (feedback.content.includes('色彩') || feedback.problemLocation?.includes('色彩')) {
  1378. (feedback as any).tag = '色彩问题';
  1379. } else if (feedback.content.includes('家具') || feedback.problemLocation?.includes('家具')) {
  1380. (feedback as any).tag = '家具款式问题';
  1381. } else if (feedback.content.includes('光线') || feedback.content.includes('照明')) {
  1382. (feedback as any).tag = '光线问题';
  1383. } else {
  1384. (feedback as any).tag = '其他问题';
  1385. }
  1386. });
  1387. }
  1388. // 获取反馈标签的辅助方法
  1389. getFeedbackTag(feedback: CustomerFeedback): string {
  1390. return (feedback as any).tag || '';
  1391. }
  1392. // 检查反馈超时
  1393. checkFeedbackTimeout(): void {
  1394. const pendingFeedbacks = this.feedbacks.filter(f => f.status === '待处理');
  1395. if (pendingFeedbacks.length > 0) {
  1396. // 启动1小时倒计时
  1397. this.feedbackTimeoutCountdown = 3600; // 3600秒 = 1小时
  1398. this.startCountdown();
  1399. }
  1400. }
  1401. // 启动倒计时
  1402. startCountdown(): void {
  1403. this.countdownInterval = setInterval(() => {
  1404. if (this.feedbackTimeoutCountdown > 0) {
  1405. this.feedbackTimeoutCountdown--;
  1406. } else {
  1407. clearInterval(this.countdownInterval);
  1408. // 超时提醒
  1409. alert('客户反馈已超过1小时未响应,请立即处理!');
  1410. this.notifyTeamLeader('feedback-overdue');
  1411. }
  1412. }, 1000);
  1413. }
  1414. // 通知技术组长
  1415. notifyTeamLeader(type: 'render-failed' | 'feedback-overdue' | 'skill-mismatch'): void {
  1416. // 实际应用中应调用消息服务通知组长
  1417. console.log(`通知技术组长:${type} - 项目ID: ${this.projectId}`);
  1418. }
  1419. // 检查技能匹配度并提示
  1420. checkSkillMismatch(): void {
  1421. const warning = this.getSkillMismatchWarning();
  1422. if (warning) {
  1423. // 显示技能不匹配警告
  1424. if (confirm(`${warning}\n是否联系技术组长协调支持?`)) {
  1425. this.notifyTeamLeader('skill-mismatch');
  1426. }
  1427. }
  1428. }
  1429. // 发起设计师变更
  1430. initiateDesignerChange(reason: string): void {
  1431. // 实际应用中应调用API发起变更
  1432. console.log(`发起设计师变更,原因:${reason}`);
  1433. alert('已发起设计师变更申请,请等待新设计师承接');
  1434. }
  1435. // 确认承接变更项目
  1436. acceptDesignerChange(changeId: string): void {
  1437. // 实际应用中应调用API确认承接
  1438. console.log(`确认承接设计师变更:${changeId}`);
  1439. alert('已确认承接项目,系统已记录时间戳和责任人');
  1440. }
  1441. // 格式化倒计时显示
  1442. formatCountdown(seconds: number): string {
  1443. const hours = Math.floor(seconds / 3600);
  1444. const minutes = Math.floor((seconds % 3600) / 60);
  1445. const remainingSeconds = seconds % 60;
  1446. return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
  1447. }
  1448. // 提交异常反馈
  1449. submitExceptionFeedback(): void {
  1450. if (!this.exceptionDescription.trim() || this.isSubmittingFeedback) {
  1451. alert('请填写异常类型和描述');
  1452. return;
  1453. }
  1454. this.isSubmittingFeedback = true;
  1455. // 模拟提交反馈到服务器
  1456. setTimeout(() => {
  1457. const newException: ExceptionHistory = {
  1458. id: `exception-${Date.now()}`,
  1459. type: this.exceptionType,
  1460. description: this.exceptionDescription,
  1461. submitTime: new Date(),
  1462. status: '待处理'
  1463. };
  1464. // 添加到历史记录中
  1465. this.exceptionHistories.unshift(newException);
  1466. // 通知客服和技术支持
  1467. this.notifyTechnicalSupport(newException);
  1468. // 清空表单
  1469. this.exceptionDescription = '';
  1470. this.clearExceptionScreenshot();
  1471. this.showExceptionForm = false;
  1472. // 显示成功消息
  1473. alert('异常反馈已提交,技术支持将尽快处理');
  1474. this.isSubmittingFeedback = false;
  1475. }, 1000);
  1476. }
  1477. // 上传异常截图
  1478. uploadExceptionScreenshot(event: Event): void {
  1479. const input = event.target as HTMLInputElement;
  1480. if (input.files && input.files[0]) {
  1481. const file = input.files[0];
  1482. // 在实际应用中,这里应该上传文件到服务器
  1483. // 这里我们使用FileReader来生成一个预览URL
  1484. const reader = new FileReader();
  1485. reader.onload = (e) => {
  1486. this.exceptionScreenshotUrl = e.target?.result as string;
  1487. };
  1488. reader.readAsDataURL(file);
  1489. }
  1490. }
  1491. // 清除异常截图
  1492. clearExceptionScreenshot(): void {
  1493. this.exceptionScreenshotUrl = null;
  1494. const input = document.getElementById('screenshot-upload') as HTMLInputElement;
  1495. if (input) {
  1496. input.value = '';
  1497. }
  1498. }
  1499. // 联系组长
  1500. contactTeamLeader() {
  1501. alert(`已联系${this.project?.assigneeName || '项目组长'}`);
  1502. }
  1503. // 处理渲染超时预警
  1504. handleRenderTimeout() {
  1505. alert('已发送渲染超时预警通知');
  1506. }
  1507. // 通知技术支持
  1508. notifyTechnicalSupport(exception: ExceptionHistory): void {
  1509. // 实际应用中应调用消息服务通知技术支持和客服
  1510. console.log(`通知技术支持和客服:渲染异常 - 项目ID: ${this.projectId}`);
  1511. console.log(`异常类型: ${this.getExceptionTypeText(exception.type)}, 描述: ${exception.description}`);
  1512. }
  1513. // 获取异常类型文本
  1514. getExceptionTypeText(type: string): string {
  1515. const typeMap: Record<string, string> = {
  1516. 'failed': '渲染失败',
  1517. 'stuck': '渲染卡顿',
  1518. 'quality': '渲染质量问题',
  1519. 'other': '其他问题'
  1520. };
  1521. return typeMap[type] || type;
  1522. }
  1523. // 格式化日期
  1524. formatDate(date: Date | string): string {
  1525. const d = typeof date === 'string' ? new Date(date) : date;
  1526. const year = d.getFullYear();
  1527. const month = String(d.getMonth() + 1).padStart(2, '0');
  1528. const day = String(d.getDate()).padStart(2, '0');
  1529. const hours = String(d.getHours()).padStart(2, '0');
  1530. const minutes = String(d.getMinutes()).padStart(2, '0');
  1531. return `${year}-${month}-${day} ${hours}:${minutes}`;
  1532. }
  1533. // 将字节格式化为易读尺寸
  1534. private formatFileSize(bytes: number): string {
  1535. if (bytes < 1024) return `${bytes}B`;
  1536. const kb = bytes / 1024;
  1537. if (kb < 1024) return `${kb.toFixed(1)}KB`;
  1538. const mb = kb / 1024;
  1539. if (mb < 1024) return `${mb.toFixed(1)}MB`;
  1540. const gb = mb / 1024;
  1541. return `${gb.toFixed(2)}GB`;
  1542. }
  1543. // 生成缩略图条目(并创建本地预览URL)
  1544. private makeImageItem(file: File): { id: string; name: string; url: string; size: string } {
  1545. const id = `img-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
  1546. const url = URL.createObjectURL(file);
  1547. return { id, name: file.name, url, size: this.formatFileSize(file.size) };
  1548. }
  1549. // 释放对象URL
  1550. private revokeUrl(url: string): void {
  1551. try { if (url && url.startsWith('blob:')) URL.revokeObjectURL(url); } catch {}
  1552. }
  1553. // =========== 建模阶段:白模上传 ===========
  1554. onWhiteModelSelected(event: Event): void {
  1555. const input = event.target as HTMLInputElement;
  1556. if (!input.files || input.files.length === 0) return;
  1557. const files = Array.from(input.files).filter(f => /\.(jpg|jpeg|png)$/i.test(f.name));
  1558. const items = files.map(f => this.makeImageItem(f));
  1559. this.whiteModelImages.unshift(...items);
  1560. input.value = '';
  1561. }
  1562. removeWhiteModelImage(id: string): void {
  1563. const target = this.whiteModelImages.find(i => i.id === id);
  1564. if (target) this.revokeUrl(target.url);
  1565. this.whiteModelImages = this.whiteModelImages.filter(i => i.id !== id);
  1566. }
  1567. // 新增:建模阶段 确认上传并自动进入下一阶段(软装)
  1568. confirmWhiteModelUpload(): void {
  1569. // 检查建模阶段的图片数据
  1570. const modelingProcess = this.deliveryProcesses.find(p => p.id === 'modeling');
  1571. if (!modelingProcess) return;
  1572. // 检查是否有任何空间上传了图片
  1573. const hasImages = modelingProcess.spaces.some(space => {
  1574. const content = modelingProcess.content[space.id];
  1575. return content && content.images && content.images.length > 0;
  1576. });
  1577. if (!hasImages) return;
  1578. this.advanceToNextStage('建模');
  1579. }
  1580. // =========== 软装阶段:小图上传(建议≤1MB,不强制) ===========
  1581. onSoftDecorSmallPicsSelected(event: Event): void {
  1582. const input = event.target as HTMLInputElement;
  1583. if (!input.files || input.files.length === 0) return;
  1584. const files = Array.from(input.files).filter(f => /\.(jpg|jpeg|png)$/i.test(f.name));
  1585. const warnOversize = files.filter(f => f.size > 1024 * 1024);
  1586. if (warnOversize.length > 0) {
  1587. // 仅提示,不阻断
  1588. console.warn('软装小图建议≤1MB,以下文件较大:', warnOversize.map(f => f.name));
  1589. }
  1590. const items = files.map(f => this.makeImageItem(f));
  1591. this.softDecorImages.unshift(...items);
  1592. input.value = '';
  1593. }
  1594. // 拖拽上传相关属性
  1595. isDragOver: boolean = false;
  1596. // 图片预览相关属性
  1597. showImagePreview: boolean = false;
  1598. previewImageData: any = null;
  1599. // 图片预览方法(含渲染大图加锁校验)
  1600. previewImage(img: any): void {
  1601. const isRenderLarge = !!this.renderLargeImages.find(i => i.id === img?.id);
  1602. if (isRenderLarge && img?.locked) {
  1603. alert('该渲染大图已加锁,需完成尾款结算并上传/识别支付凭证后方可预览。');
  1604. return;
  1605. }
  1606. this.previewImageData = img;
  1607. this.showImagePreview = true;
  1608. }
  1609. closeImagePreview(): void {
  1610. this.showImagePreview = false;
  1611. this.previewImageData = null;
  1612. }
  1613. downloadImage(img: any): void {
  1614. const isRenderLarge = !!this.renderLargeImages.find(i => i.id === img?.id);
  1615. if (isRenderLarge && img?.locked) {
  1616. alert('该渲染大图已加锁,需完成尾款结算并上传/识别支付凭证后方可下载。');
  1617. return;
  1618. }
  1619. if (img) {
  1620. const link = document.createElement('a');
  1621. link.href = img.url;
  1622. link.download = img.name;
  1623. link.click();
  1624. }
  1625. }
  1626. removeImageFromPreview(): void {
  1627. if (this.previewImageData) {
  1628. // 首先检查新的 deliveryProcesses 结构
  1629. let imageFound = false;
  1630. for (const process of this.deliveryProcesses) {
  1631. for (const space of process.spaces) {
  1632. if (process.content[space.id]?.images) {
  1633. const imageIndex = process.content[space.id].images.findIndex(img => img.id === this.previewImageData.id);
  1634. if (imageIndex > -1) {
  1635. this.removeSpaceImage(process.id, space.id, this.previewImageData.id);
  1636. imageFound = true;
  1637. break;
  1638. }
  1639. }
  1640. }
  1641. if (imageFound) break;
  1642. }
  1643. // 如果在新结构中没找到,检查旧的图片数组
  1644. if (!imageFound) {
  1645. if (this.whiteModelImages.find(i => i.id === this.previewImageData.id)) {
  1646. this.removeWhiteModelImage(this.previewImageData.id);
  1647. } else if (this.softDecorImages.find(i => i.id === this.previewImageData.id)) {
  1648. this.removeSoftDecorImage(this.previewImageData.id);
  1649. } else if (this.renderLargeImages.find(i => i.id === this.previewImageData.id)) {
  1650. this.removeRenderLargeImage(this.previewImageData.id);
  1651. } else if (this.postProcessImages.find(i => i.id === this.previewImageData.id)) {
  1652. this.removePostProcessImage(this.previewImageData.id);
  1653. }
  1654. }
  1655. this.closeImagePreview();
  1656. }
  1657. }
  1658. // 拖拽事件处理
  1659. onDragOver(event: DragEvent): void {
  1660. event.preventDefault();
  1661. event.stopPropagation();
  1662. this.isDragOver = true;
  1663. }
  1664. onDragLeave(event: DragEvent): void {
  1665. event.preventDefault();
  1666. event.stopPropagation();
  1667. this.isDragOver = false;
  1668. }
  1669. onFileDrop(event: DragEvent, type: 'whiteModel' | 'softDecor' | 'render' | 'postProcess'): void {
  1670. event.preventDefault();
  1671. event.stopPropagation();
  1672. this.isDragOver = false;
  1673. const files = event.dataTransfer?.files;
  1674. if (!files || files.length === 0) return;
  1675. // 创建模拟的input事件
  1676. const mockEvent = {
  1677. target: {
  1678. files: files
  1679. }
  1680. } as any;
  1681. // 根据类型调用相应的处理方法
  1682. switch (type) {
  1683. case 'whiteModel':
  1684. this.onWhiteModelSelected(mockEvent);
  1685. break;
  1686. case 'softDecor':
  1687. this.onSoftDecorSmallPicsSelected(mockEvent);
  1688. break;
  1689. case 'render':
  1690. this.onRenderLargePicsSelected(mockEvent);
  1691. break;
  1692. case 'postProcess':
  1693. this.onPostProcessPicsSelected(mockEvent);
  1694. break;
  1695. }
  1696. }
  1697. // 触发文件输入框
  1698. triggerFileInput(type: 'whiteModel' | 'softDecor' | 'render' | 'postProcess'): void {
  1699. let inputId: string;
  1700. switch (type) {
  1701. case 'whiteModel':
  1702. inputId = 'whiteModelFileInput';
  1703. break;
  1704. case 'softDecor':
  1705. inputId = 'softDecorFileInput';
  1706. break;
  1707. case 'render':
  1708. inputId = 'renderFileInput';
  1709. break;
  1710. case 'postProcess':
  1711. inputId = 'postProcessFileInput';
  1712. break;
  1713. }
  1714. const input = document.querySelector(`#${inputId}`) as HTMLInputElement;
  1715. if (input) {
  1716. input.click();
  1717. }
  1718. }
  1719. removeSoftDecorImage(id: string): void {
  1720. const target = this.softDecorImages.find(i => i.id === id);
  1721. if (target) this.revokeUrl(target.url);
  1722. this.softDecorImages = this.softDecorImages.filter(i => i.id !== id);
  1723. }
  1724. // 新增:后期阶段图片上传处理
  1725. async onPostProcessPicsSelected(event: Event): Promise<void> {
  1726. const input = event.target as HTMLInputElement;
  1727. if (!input.files || input.files.length === 0) return;
  1728. const files = Array.from(input.files).filter(f => /\.(jpg|jpeg|png)$/i.test(f.name));
  1729. for (const f of files) {
  1730. const item = this.makeImageItem(f);
  1731. this.postProcessImages.unshift({
  1732. id: item.id,
  1733. name: item.name,
  1734. url: item.url,
  1735. size: this.formatFileSize(f.size)
  1736. });
  1737. }
  1738. input.value = '';
  1739. }
  1740. removePostProcessImage(id: string): void {
  1741. const target = this.postProcessImages.find(i => i.id === id);
  1742. if (target) this.revokeUrl(target.url);
  1743. this.postProcessImages = this.postProcessImages.filter(i => i.id !== id);
  1744. }
  1745. // 新增:后期阶段 确认上传并自动进入下一阶段(尾款结算)
  1746. confirmPostProcessUpload(): void {
  1747. // 检查后期阶段的图片数据
  1748. const postProcessProcess = this.deliveryProcesses.find(p => p.id === 'post-processing');
  1749. if (!postProcessProcess) return;
  1750. // 检查是否有任何空间上传了图片
  1751. const hasImages = postProcessProcess.spaces.some(space => {
  1752. const content = postProcessProcess.content[space.id];
  1753. return content && content.images && content.images.length > 0;
  1754. });
  1755. if (!hasImages) return;
  1756. this.advanceToNextStage('后期');
  1757. }
  1758. // 新增:尾款结算阶段确认并自动进入下一阶段(客户评价)
  1759. confirmSettlement(): void {
  1760. if (this.isConfirmingSettlement) return;
  1761. this.isConfirmingSettlement = true;
  1762. // 模拟API调用延迟
  1763. setTimeout(() => {
  1764. this.isSettlementCompleted = true;
  1765. this.isConfirmingSettlement = false;
  1766. // 显示成功提示
  1767. alert('尾款结算已确认完成!');
  1768. // 进入下一阶段
  1769. this.advanceToNextStage('尾款结算');
  1770. }, 1500);
  1771. }
  1772. // 新增:投诉处理阶段确认并完成项目(基础版本,详细版本在售后模块中)
  1773. confirmComplaintBasic(): void {
  1774. console.log('确认投诉处理完成');
  1775. // 可以在这里添加更多逻辑,比如标记项目完成等
  1776. // 调用服务更新后端数据
  1777. // this.projectService.confirmComplaintResolution(this.projectId);
  1778. this.advanceToNextStage('投诉处理');
  1779. }
  1780. // 新增:软装阶段 确认上传并自动进入下一阶段(渲染)
  1781. confirmSoftDecorUpload(): void {
  1782. // 检查软装阶段的图片数据
  1783. const softDecorProcess = this.deliveryProcesses.find(p => p.id === 'soft-decoration');
  1784. if (!softDecorProcess) return;
  1785. // 检查是否有任何空间上传了图片
  1786. const hasImages = softDecorProcess.spaces.some(space => {
  1787. const content = softDecorProcess.content[space.id];
  1788. return content && content.images && content.images.length > 0;
  1789. });
  1790. if (!hasImages) return;
  1791. this.advanceToNextStage('软装');
  1792. }
  1793. // 新增:渲染阶段 确认上传并自动进入下一阶段(后期)
  1794. confirmRenderUpload(): void {
  1795. // 检查渲染阶段的图片数据
  1796. const renderProcess = this.deliveryProcesses.find(p => p.id === 'rendering');
  1797. if (!renderProcess) return;
  1798. // 检查是否有任何空间上传了图片
  1799. const hasImages = renderProcess.spaces.some(space => {
  1800. const content = renderProcess.content[space.id];
  1801. return content && content.images && content.images.length > 0;
  1802. });
  1803. if (!hasImages) return;
  1804. this.advanceToNextStage('渲染');
  1805. }
  1806. // =========== 渲染阶段:大图上传(弹窗 + 4K校验) ===========
  1807. openRenderUploadModal(): void {
  1808. this.showRenderUploadModal = true;
  1809. this.pendingRenderLargeItems = [];
  1810. }
  1811. closeRenderUploadModal(): void {
  1812. // 关闭时释放临时预览URL
  1813. this.pendingRenderLargeItems.forEach(i => this.revokeUrl(i.url));
  1814. this.pendingRenderLargeItems = [];
  1815. this.showRenderUploadModal = false;
  1816. }
  1817. async onRenderLargePicsSelected(event: Event): Promise<void> {
  1818. const input = event.target as HTMLInputElement;
  1819. if (!input.files || input.files.length === 0) return;
  1820. const files = Array.from(input.files).filter(f => /\.(jpg|jpeg|png)$/i.test(f.name));
  1821. for (const f of files) {
  1822. const ok = await this.validateImage4K(f).catch(() => false);
  1823. if (!ok) {
  1824. alert(`图片不符合4K标准(最大边需≥4000像素):${f.name}`);
  1825. continue;
  1826. }
  1827. const item = this.makeImageItem(f);
  1828. // 直接添加到正式列表,不再使用待确认列表
  1829. this.renderLargeImages.unshift({
  1830. id: item.id,
  1831. name: item.name,
  1832. url: item.url,
  1833. size: this.formatFileSize(f.size),
  1834. locked: true
  1835. });
  1836. }
  1837. input.value = '';
  1838. }
  1839. removeRenderLargeImage(id: string): void {
  1840. const target = this.renderLargeImages.find(i => i.id === id);
  1841. if (target) this.revokeUrl(target.url);
  1842. this.renderLargeImages = this.renderLargeImages.filter(i => i.id !== id);
  1843. }
  1844. // 根据阶段映射所属板块
  1845. getSectionKeyForStage(stage: ProjectStage): SectionKey {
  1846. switch (stage) {
  1847. case '订单创建':
  1848. return 'order';
  1849. case '需求沟通':
  1850. case '方案确认':
  1851. return 'requirements';
  1852. case '建模':
  1853. case '软装':
  1854. case '渲染':
  1855. case '后期':
  1856. return 'delivery';
  1857. case '尾款结算':
  1858. case '客户评价':
  1859. case '投诉处理':
  1860. return 'aftercare';
  1861. default:
  1862. return 'order';
  1863. }
  1864. }
  1865. // 获取板块状态:completed | 'active' | 'pending'
  1866. getSectionStatus(key: SectionKey): 'completed' | 'active' | 'pending' {
  1867. // 优先使用本地的currentStage,如果没有则使用project.currentStage
  1868. const current = (this.currentStage || this.project?.currentStage) as ProjectStage | undefined;
  1869. // 如果没有当前阶段(新创建的项目),默认订单创建板块为active(红色)
  1870. if (!current || current === '订单创建') {
  1871. return key === 'order' ? 'active' : 'pending';
  1872. }
  1873. // 获取当前阶段所属的板块
  1874. const currentSection = this.getSectionKeyForStage(current);
  1875. const sectionOrder = this.sections.map(s => s.key);
  1876. const currentIdx = sectionOrder.indexOf(currentSection);
  1877. const idx = sectionOrder.indexOf(key);
  1878. if (idx === -1 || currentIdx === -1) return 'pending';
  1879. // 已完成的板块:当前阶段所在板块之前的所有板块
  1880. if (idx < currentIdx) return 'completed';
  1881. // 当前进行中的板块:当前阶段所在的板块
  1882. if (idx === currentIdx) return 'active';
  1883. // 未开始的板块:当前阶段所在板块之后的所有板块
  1884. return 'pending';
  1885. }
  1886. // 切换四大板块(单展开)
  1887. toggleSection(key: SectionKey): void {
  1888. this.expandedSection = key;
  1889. // 点击板块按钮时,滚动到该板块的第一个可见阶段卡片
  1890. const sec = this.sections.find(s => s.key === key);
  1891. if (sec) {
  1892. // 设计师仅滚动到可见的三大执行阶段,否则取该板块第一个阶段
  1893. const candidate = this.isDesignerView()
  1894. ? sec.stages.find(st => ['建模', '软装', '渲染'].includes(st)) || sec.stages[0]
  1895. : sec.stages[0];
  1896. this.scrollToStage(candidate);
  1897. }
  1898. }
  1899. // 阶段到锚点的映射
  1900. stageToAnchor(stage: ProjectStage): string {
  1901. const map: Record<ProjectStage, string> = {
  1902. '订单创建': 'order',
  1903. '需求沟通': 'requirements-talk',
  1904. '方案确认': 'proposal-confirm',
  1905. '建模': 'modeling',
  1906. '软装': 'softdecor',
  1907. '渲染': 'render',
  1908. '后期': 'postprocess',
  1909. '尾款结算': 'settlement',
  1910. '客户评价': 'customer-review',
  1911. '投诉处理': 'complaint'
  1912. };
  1913. return `stage-${map[stage] || 'unknown'}`;
  1914. }
  1915. // 平滑滚动到指定阶段卡片
  1916. scrollToStage(stage: ProjectStage): void {
  1917. const anchor = this.stageToAnchor(stage);
  1918. const el = document.getElementById(anchor);
  1919. if (el) {
  1920. el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  1921. }
  1922. }
  1923. // 订单创建阶段:客户信息(迁移自客服端"客户信息"卡片)
  1924. orderCreationMethod: 'miniprogram' | 'manual' = 'miniprogram';
  1925. isSyncing: boolean = false;
  1926. orderTime: string = '';
  1927. // 客户信息实时同步相关变量
  1928. isSyncingCustomerInfo: boolean = false;
  1929. lastSyncTime: Date | null = null;
  1930. syncInterval: any = null;
  1931. customerForm!: FormGroup;
  1932. customerSearchKeyword: string = '';
  1933. customerSearchResults: Array<{ id: string; name: string; phone: string; wechat?: string; avatar?: string; customerType?: string; source?: string; remark?: string }> = [];
  1934. selectedOrderCustomer: { id: string; name: string; phone: string; wechat?: string; avatar?: string; customerType?: string; source?: string; remark?: string } | null = null;
  1935. demandTypes = [
  1936. { value: 'price', label: '价格敏感' },
  1937. { value: 'quality', label: '质量敏感' },
  1938. { value: 'comprehensive', label: '综合要求' }
  1939. ];
  1940. followUpStatus = [
  1941. { value: 'quotation', label: '待报价' },
  1942. { value: 'confirm', label: '待确认需求' },
  1943. { value: 'lost', label: '已失联' }
  1944. ];
  1945. // 需求关键信息同步数据
  1946. requirementKeyInfo = {
  1947. colorAtmosphere: {
  1948. description: '',
  1949. mainColor: '',
  1950. colorTemp: '',
  1951. materials: [] as string[]
  1952. },
  1953. spaceStructure: {
  1954. lineRatio: 0,
  1955. blankRatio: 0,
  1956. flowWidth: 0,
  1957. aspectRatio: 0,
  1958. ceilingHeight: 0
  1959. },
  1960. materialWeights: {
  1961. fabricRatio: 0,
  1962. woodRatio: 0,
  1963. metalRatio: 0,
  1964. smoothness: 0,
  1965. glossiness: 0
  1966. },
  1967. presetAtmosphere: {
  1968. name: '',
  1969. rgb: '',
  1970. colorTemp: '',
  1971. materials: [] as string[]
  1972. }
  1973. };
  1974. // 客户信息:搜索/选择/清空/同步/快速填写 逻辑
  1975. searchCustomer(): void {
  1976. if (this.customerSearchKeyword.trim().length >= 2) {
  1977. this.customerSearchResults = [
  1978. { id: '1', name: '张先生', phone: '138****5678', customerType: '老客户', source: '官网咨询', avatar: "data:image/svg+xml,%3Csvg width='64' height='40' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='100%25' height='100%25' fill='%23E6E6E6'/%3E%3Ctext x='50%25' y='50%25' font-family='Arial' font-size='13.333333333333334' font-weight='bold' text-anchor='middle' fill='%23555555' dy='0.3em'%3EIMG%3C/text%3E%3C/svg%3E" },
  1979. { id: '2', name: '李女士', phone: '139****1234', customerType: 'VIP客户', source: '推荐介绍', avatar: "data:image/svg+xml,%3Csvg width='65' height='40' xmlns='http://www.w3.org/2000/svg'%3E%3Crect width='100%25' height='100%25' fill='%23DCDCDC'/%3E%3Ctext x='50%25' y='50%25' font-family='Arial' font-size='13.333333333333334' font-weight='bold' text-anchor='middle' fill='%23555555' dy='0.3em'%3EIMG%3C/text%3E%3C/svg%3E" }
  1980. ];
  1981. } else {
  1982. this.customerSearchResults = [];
  1983. }
  1984. }
  1985. selectCustomer(customer: { id: string; name: string; phone: string; wechat?: string; avatar?: string; customerType?: string; source?: string; remark?: string }): void {
  1986. this.selectedOrderCustomer = customer;
  1987. this.customerForm.patchValue({
  1988. name: customer.name,
  1989. phone: customer.phone,
  1990. wechat: customer.wechat || '',
  1991. customerType: customer.customerType || '新客户',
  1992. source: customer.source || '',
  1993. remark: customer.remark || ''
  1994. });
  1995. this.customerSearchResults = [];
  1996. this.customerSearchKeyword = '';
  1997. }
  1998. clearSelectedCustomer(): void {
  1999. this.selectedOrderCustomer = null;
  2000. this.customerForm.reset({ customerType: '新客户' });
  2001. }
  2002. quickFillCustomerInfo(keyword: string): void {
  2003. const k = (keyword || '').trim();
  2004. if (!k) return;
  2005. // 模拟:若有搜索结果,选择第一条
  2006. if (this.customerSearchResults.length === 0) this.searchCustomer();
  2007. if (this.customerSearchResults.length > 0) {
  2008. this.selectCustomer(this.customerSearchResults[0]);
  2009. }
  2010. }
  2011. syncMiniprogramCustomerInfo(): void {
  2012. if (this.isSyncing) return;
  2013. this.isSyncing = true;
  2014. setTimeout(() => {
  2015. // 模拟从小程序同步到客户表单
  2016. this.customerForm.patchValue({
  2017. name: '小程序用户',
  2018. phone: '13800001234',
  2019. wechat: 'wx_user_001',
  2020. customerType: '新客户',
  2021. source: '小程序下单'
  2022. });
  2023. this.isSyncing = false;
  2024. // 触发客户信息同步显示
  2025. this.syncCustomerInfoDisplay();
  2026. }, 1000);
  2027. }
  2028. // 同步客户信息显示
  2029. syncCustomerInfoDisplay(): void {
  2030. this.isSyncingCustomerInfo = true;
  2031. // 模拟同步过程
  2032. setTimeout(() => {
  2033. this.lastSyncTime = new Date();
  2034. this.isSyncingCustomerInfo = false;
  2035. // 触发界面更新
  2036. this.cdr.detectChanges();
  2037. console.log('客户信息显示已同步:', this.lastSyncTime);
  2038. }, 800);
  2039. }
  2040. // 启动自动同步
  2041. startAutoSync(): void {
  2042. if (this.syncInterval) {
  2043. clearInterval(this.syncInterval);
  2044. }
  2045. // 每30秒自动同步一次
  2046. this.syncInterval = setInterval(() => {
  2047. this.syncCustomerInfoDisplay();
  2048. }, 30000);
  2049. }
  2050. // 停止自动同步
  2051. stopAutoSync(): void {
  2052. if (this.syncInterval) {
  2053. clearInterval(this.syncInterval);
  2054. this.syncInterval = null;
  2055. }
  2056. }
  2057. // 格式化时间显示
  2058. formatTime(date: Date): string {
  2059. const now = new Date();
  2060. const diff = now.getTime() - date.getTime();
  2061. const minutes = Math.floor(diff / 60000);
  2062. if (minutes < 1) {
  2063. return '刚刚';
  2064. } else if (minutes < 60) {
  2065. return `${minutes}分钟前`;
  2066. } else {
  2067. const hours = Math.floor(minutes / 60);
  2068. return `${hours}小时前`;
  2069. }
  2070. }
  2071. downloadFile(file: ProjectFile): void {
  2072. // 实现文件下载逻辑
  2073. const link = document.createElement('a');
  2074. link.href = file.url;
  2075. link.download = file.name;
  2076. link.click();
  2077. }
  2078. previewFile(file: ProjectFile): void {
  2079. // 预览文件逻辑
  2080. console.log('预览文件:', file.name);
  2081. }
  2082. // 处理参考图更新事件
  2083. onReferenceImagesUpdated(images: any[]): void {
  2084. console.log('参考图已更新:', images);
  2085. // 这里可以实现保存到后端的逻辑
  2086. // 也可以触发项目状态的更新
  2087. }
  2088. // 同步需求关键信息到客户信息卡片
  2089. syncRequirementKeyInfo(requirementData: any): void {
  2090. if (requirementData) {
  2091. // 同步色彩氛围信息
  2092. if (requirementData.colorIndicators) {
  2093. this.requirementKeyInfo.colorAtmosphere = {
  2094. description: requirementData.colorIndicators.colorRange || '',
  2095. mainColor: `rgb(${requirementData.colorIndicators.mainColor?.r || 0}, ${requirementData.colorIndicators.mainColor?.g || 0}, ${requirementData.colorIndicators.mainColor?.b || 0})`,
  2096. colorTemp: `${requirementData.colorIndicators.colorTemperature || 0}K`,
  2097. materials: []
  2098. };
  2099. }
  2100. // 同步空间结构信息
  2101. if (requirementData.spaceIndicators) {
  2102. this.requirementKeyInfo.spaceStructure = {
  2103. lineRatio: requirementData.spaceIndicators.lineRatio || 0,
  2104. blankRatio: requirementData.spaceIndicators.blankRatio || 0,
  2105. flowWidth: requirementData.spaceIndicators.flowWidth || 0,
  2106. aspectRatio: requirementData.spaceIndicators.aspectRatio || 0,
  2107. ceilingHeight: requirementData.spaceIndicators.ceilingHeight || 0
  2108. };
  2109. }
  2110. // 同步材质权重信息
  2111. if (requirementData.materialIndicators) {
  2112. this.requirementKeyInfo.materialWeights = {
  2113. fabricRatio: requirementData.materialIndicators.fabricRatio || 0,
  2114. woodRatio: requirementData.materialIndicators.woodRatio || 0,
  2115. metalRatio: requirementData.materialIndicators.metalRatio || 0,
  2116. smoothness: requirementData.materialIndicators.smoothness || 0,
  2117. glossiness: requirementData.materialIndicators.glossiness || 0
  2118. };
  2119. }
  2120. // 同步预设氛围信息
  2121. if (requirementData.selectedPresetAtmosphere) {
  2122. this.requirementKeyInfo.presetAtmosphere = {
  2123. name: requirementData.selectedPresetAtmosphere.name || '',
  2124. rgb: requirementData.selectedPresetAtmosphere.rgb || '',
  2125. colorTemp: requirementData.selectedPresetAtmosphere.colorTemp || '',
  2126. materials: requirementData.selectedPresetAtmosphere.materials || []
  2127. };
  2128. }
  2129. // 新增:实时更新左侧客户信息显示
  2130. if (this.project) {
  2131. // 更新项目的客户信息
  2132. if (requirementData.colorIndicators && requirementData.colorIndicators.length > 0) {
  2133. this.project.customerInfo = {
  2134. ...this.project.customerInfo,
  2135. colorPreference: requirementData.colorIndicators.map((indicator: any) => indicator.name).join(', ')
  2136. };
  2137. }
  2138. // 更新空间结构信息
  2139. if (requirementData.spaceIndicators && requirementData.spaceIndicators.length > 0) {
  2140. this.project.customerInfo = {
  2141. ...this.project.customerInfo,
  2142. spaceRequirements: requirementData.spaceIndicators.map((indicator: any) => `${indicator.name}: ${indicator.value}`).join(', ')
  2143. };
  2144. }
  2145. // 更新材质偏好
  2146. if (requirementData.materialIndicators && requirementData.materialIndicators.length > 0) {
  2147. this.project.customerInfo = {
  2148. ...this.project.customerInfo,
  2149. materialPreference: requirementData.materialIndicators.map((indicator: any) => `${indicator.name}: ${indicator.value}%`).join(', ')
  2150. };
  2151. }
  2152. // 触发变更检测以更新UI
  2153. this.cdr.detectChanges();
  2154. }
  2155. console.log('需求关键信息已同步:', this.requirementKeyInfo);
  2156. } else {
  2157. // 模拟数据用于演示
  2158. this.requirementKeyInfo = {
  2159. colorAtmosphere: {
  2160. description: '温馨暖调',
  2161. mainColor: 'rgb(255, 230, 180)',
  2162. colorTemp: '2700K',
  2163. materials: ['木质', '布艺']
  2164. },
  2165. spaceStructure: {
  2166. lineRatio: 60,
  2167. blankRatio: 30,
  2168. flowWidth: 0.9,
  2169. aspectRatio: 1.6,
  2170. ceilingHeight: 2.8
  2171. },
  2172. materialWeights: {
  2173. fabricRatio: 50,
  2174. woodRatio: 30,
  2175. metalRatio: 20,
  2176. smoothness: 7,
  2177. glossiness: 4
  2178. },
  2179. presetAtmosphere: {
  2180. name: '现代简约',
  2181. rgb: '200,220,240',
  2182. colorTemp: '5000K',
  2183. materials: ['金属', '玻璃']
  2184. }
  2185. };
  2186. }
  2187. }
  2188. // 新增:处理需求阶段完成事件
  2189. onRequirementsStageCompleted(event: { stage: string; allStagesCompleted: boolean }): void {
  2190. console.log('需求阶段完成事件:', event);
  2191. if (event.allStagesCompleted && event.stage === 'requirements-communication') {
  2192. // 自动推进到方案确认阶段
  2193. this.currentStage = '方案确认';
  2194. this.expandedStages['方案确认'] = true;
  2195. this.expandedStages['需求沟通'] = false;
  2196. // 更新项目状态
  2197. this.updateProjectStage('方案确认');
  2198. console.log('自动推进到方案确认阶段');
  2199. }
  2200. }
  2201. // 新增:确认方案方法
  2202. confirmProposal(): void {
  2203. console.log('确认方案按钮被点击');
  2204. // 使用统一的阶段推进方法
  2205. this.advanceToNextStage('方案确认');
  2206. console.log('已跳转到建模阶段');
  2207. }
  2208. // 获取同步的关键信息摘要
  2209. getRequirementSummary(): string[] {
  2210. const summary: string[] = [];
  2211. if (this.requirementKeyInfo.colorAtmosphere.description) {
  2212. summary.push(`色彩氛围: ${this.requirementKeyInfo.colorAtmosphere.description}`);
  2213. }
  2214. if (this.requirementKeyInfo.spaceStructure.aspectRatio > 0) {
  2215. summary.push(`空间比例: ${this.requirementKeyInfo.spaceStructure.aspectRatio.toFixed(1)}`);
  2216. }
  2217. if (this.requirementKeyInfo.materialWeights.woodRatio > 0) {
  2218. summary.push(`木质占比: ${this.requirementKeyInfo.materialWeights.woodRatio}%`);
  2219. }
  2220. if (this.requirementKeyInfo.presetAtmosphere.name) {
  2221. summary.push(`预设氛围: ${this.requirementKeyInfo.presetAtmosphere.name}`);
  2222. }
  2223. return summary;
  2224. }
  2225. // 检查必需阶段是否全部完成(流程进度 > 确认需求 > 需求沟通四个流程)
  2226. areRequiredStagesCompleted(): boolean {
  2227. // 检查项目是否已经进入方案确认阶段或更后的阶段
  2228. if (!this.project) {
  2229. return false;
  2230. }
  2231. const stageOrder = [
  2232. '订单创建', '需求沟通', '方案确认', '建模', '软装',
  2233. '渲染', '尾款结算', '客户评价', '投诉处理'
  2234. ];
  2235. const currentStageIndex = stageOrder.indexOf(this.project.currentStage);
  2236. const proposalStageIndex = stageOrder.indexOf('方案确认');
  2237. const requirementStageIndex = stageOrder.indexOf('需求沟通');
  2238. // 如果当前阶段是方案确认或之后的阶段,则认为需求阶段已完成
  2239. if (currentStageIndex >= proposalStageIndex) {
  2240. // 确保有基本的需求信息数据,如果没有则初始化模拟数据
  2241. this.ensureRequirementData();
  2242. return true;
  2243. }
  2244. // 如果当前阶段是需求沟通,检查需求沟通是否已完成
  2245. if (currentStageIndex === requirementStageIndex) {
  2246. // 检查需求关键信息是否有数据,或者检查需求沟通组件的完成状态
  2247. const hasRequirementData = this.getRequirementSummary().length > 0 &&
  2248. (!!this.requirementKeyInfo.colorAtmosphere.description ||
  2249. this.requirementKeyInfo.spaceStructure.aspectRatio > 0 ||
  2250. this.requirementKeyInfo.materialWeights.woodRatio > 0 ||
  2251. !!this.requirementKeyInfo.presetAtmosphere.name);
  2252. // 只有在真正有需求数据时才返回true,不再自动初始化模拟数据
  2253. if (hasRequirementData) {
  2254. return true;
  2255. }
  2256. // 如果没有需求数据,返回false,不允许进入下一阶段
  2257. return false;
  2258. }
  2259. // 其他情况返回false
  2260. return false;
  2261. }
  2262. // 确保有需求数据用于方案确认显示
  2263. private ensureRequirementData(): void {
  2264. // console.log('=== ensureRequirementData 开始确保需求数据 ===');
  2265. // console.log('当前requirementKeyInfo:', this.requirementKeyInfo);
  2266. // 修复条件判断:检查是否需要初始化数据
  2267. const needsInitialization =
  2268. !this.requirementKeyInfo.colorAtmosphere.description ||
  2269. this.requirementKeyInfo.spaceStructure.aspectRatio === 0 ||
  2270. this.requirementKeyInfo.materialWeights.woodRatio === 0 ||
  2271. !this.requirementKeyInfo.presetAtmosphere.name;
  2272. console.log('是否需要初始化数据:', needsInitialization);
  2273. if (needsInitialization) {
  2274. console.log('需求关键信息为空,初始化默认数据');
  2275. // 初始化模拟的需求数据
  2276. this.requirementKeyInfo = {
  2277. colorAtmosphere: {
  2278. description: '现代简约风格,以白色和灰色为主调',
  2279. mainColor: '#F5F5F5',
  2280. colorTemp: '冷色调',
  2281. materials: ['木质', '金属', '玻璃']
  2282. },
  2283. spaceStructure: {
  2284. lineRatio: 0.6,
  2285. blankRatio: 0.4,
  2286. flowWidth: 1.2,
  2287. aspectRatio: 1.8,
  2288. ceilingHeight: 2.8
  2289. },
  2290. materialWeights: {
  2291. fabricRatio: 20,
  2292. woodRatio: 45,
  2293. metalRatio: 25,
  2294. smoothness: 0.7,
  2295. glossiness: 0.3
  2296. },
  2297. presetAtmosphere: {
  2298. name: '现代简约',
  2299. rgb: '#F5F5F5',
  2300. colorTemp: '5000K',
  2301. materials: ['木质', '金属']
  2302. }
  2303. };
  2304. // console.log('初始化后的requirementKeyInfo:', this.requirementKeyInfo);
  2305. } else {
  2306. // console.log('需求关键信息已存在,无需初始化');
  2307. }
  2308. }
  2309. // 获取项目状态文本
  2310. getProjectStatusText(): string {
  2311. const current = (this.currentStage || this.project?.currentStage) as ProjectStage | undefined;
  2312. if (!current || current === '订单创建') {
  2313. return '待开始';
  2314. }
  2315. // 检查是否已完成所有阶段
  2316. const allStages: ProjectStage[] = ['订单创建', '需求沟通', '方案确认', '建模', '软装', '渲染', '尾款结算', '客户评价', '投诉处理'];
  2317. const currentIndex = allStages.indexOf(current);
  2318. if (currentIndex === allStages.length - 1) {
  2319. return '已完成';
  2320. }
  2321. return '进行中';
  2322. }
  2323. // 获取当前阶段文本
  2324. getCurrentStageText(): string {
  2325. const current = (this.currentStage || this.project?.currentStage) as ProjectStage | undefined;
  2326. if (!current || current === '订单创建') {
  2327. return '订单创建阶段';
  2328. }
  2329. return `${current}阶段`;
  2330. }
  2331. // 获取整体进度百分比
  2332. getOverallProgress(): number {
  2333. const current = (this.currentStage || this.project?.currentStage) as ProjectStage | undefined;
  2334. if (!current) {
  2335. return 0;
  2336. }
  2337. // 定义所有阶段及其权重
  2338. const stageWeights: Record<ProjectStage, number> = {
  2339. '订单创建': 5,
  2340. '需求沟通': 15,
  2341. '方案确认': 25,
  2342. '建模': 40,
  2343. '软装': 55,
  2344. '渲染': 70,
  2345. '后期': 80,
  2346. '尾款结算': 90,
  2347. '客户评价': 95,
  2348. '投诉处理': 100
  2349. };
  2350. return stageWeights[current] || 0;
  2351. }
  2352. // 获取必需阶段的完成进度百分比
  2353. getRequiredStagesProgress(): number {
  2354. let completedCount = 0;
  2355. const totalCount = 4; // 四个必需流程
  2356. // 检查各个关键信息是否已确认
  2357. if (this.requirementKeyInfo.colorAtmosphere.description) completedCount++;
  2358. if (this.requirementKeyInfo.spaceStructure.aspectRatio > 0) completedCount++;
  2359. if (this.requirementKeyInfo.materialWeights.woodRatio > 0 ||
  2360. this.requirementKeyInfo.materialWeights.fabricRatio > 0 ||
  2361. this.requirementKeyInfo.materialWeights.metalRatio > 0) completedCount++;
  2362. if (this.requirementKeyInfo.presetAtmosphere.name) completedCount++;
  2363. return Math.round((completedCount / totalCount) * 100);
  2364. }
  2365. // 订单金额
  2366. orderAmount: number = 0;
  2367. // 报价明细
  2368. quotationDetails: Array<{
  2369. id: string;
  2370. room: string;
  2371. amount: number;
  2372. description?: string;
  2373. }> = [];
  2374. // AI生成报价明细
  2375. generateQuotationDetails(): void {
  2376. // 基于项目信息生成报价明细
  2377. const rooms = ['客餐厅', '主卧', '次卧', '厨房', '卫生间'];
  2378. this.quotationDetails = rooms.map((room, index) => ({
  2379. id: `quote_${index + 1}`,
  2380. room: room,
  2381. amount: Math.floor(Math.random() * 1000) + 300, // 示例金额
  2382. description: `${room}装修设计费用`
  2383. }));
  2384. // 更新总订单金额
  2385. this.orderAmount = this.quotationDetails.reduce((total, item) => total + item.amount, 0);
  2386. }
  2387. // 添加报价明细项
  2388. addQuotationItem(): void {
  2389. this.quotationDetails.push({
  2390. id: `quote_${Date.now()}`,
  2391. room: '',
  2392. amount: 0,
  2393. description: ''
  2394. });
  2395. }
  2396. // 删除报价明细项
  2397. removeQuotationItem(id: string): void {
  2398. this.quotationDetails = this.quotationDetails.filter(item => item.id !== id);
  2399. this.updateOrderAmount();
  2400. }
  2401. // 更新订单总金额
  2402. updateOrderAmount(): void {
  2403. this.orderAmount = this.quotationDetails.reduce((total, item) => total + item.amount, 0);
  2404. }
  2405. // 报价组件数据
  2406. quotationData: QuotationData = {
  2407. items: [],
  2408. totalAmount: 0,
  2409. materialCost: 0,
  2410. laborCost: 0,
  2411. designFee: 0,
  2412. managementFee: 0
  2413. };
  2414. // 设计师指派数据
  2415. designerAssignmentData?: DesignerAssignmentData;
  2416. // 设计师日历弹窗状态与数据
  2417. showDesignerCalendar: boolean = false;
  2418. selectedCalendarDate: Date = new Date();
  2419. calendarDesigners: CalendarDesigner[] = [];
  2420. calendarGroups: CalendarProjectGroup[] = [];
  2421. onQuotationDataChange(data: QuotationData): void {
  2422. this.quotationData = { ...data };
  2423. this.orderAmount = data.totalAmount || 0;
  2424. }
  2425. onDesignerAssignmentChange(data: DesignerAssignmentData): void {
  2426. this.designerAssignmentData = { ...data };
  2427. }
  2428. onDesignerClick(designer: AssignmentDesigner): void {
  2429. const mapped = this.mapAssignmentDesignerToCalendar(designer);
  2430. this.calendarDesigners = [mapped];
  2431. this.calendarGroups = [{ id: designer.teamId, name: designer.teamName, leaderId: designer.id, memberIds: [designer.id] }];
  2432. this.selectedCalendarDate = new Date();
  2433. this.showDesignerCalendar = true;
  2434. }
  2435. closeDesignerCalendar(): void {
  2436. this.showDesignerCalendar = false;
  2437. }
  2438. onCalendarDesignerSelected(designer: CalendarDesigner): void {
  2439. this.selectedDesigner = designer;
  2440. this.closeDesignerCalendar();
  2441. }
  2442. onCalendarAssignmentRequested(designer: CalendarDesigner): void {
  2443. this.selectedDesigner = designer;
  2444. this.closeDesignerCalendar();
  2445. }
  2446. private mapAssignmentDesignerToCalendar(d: AssignmentDesigner): CalendarDesigner {
  2447. return {
  2448. id: d.id,
  2449. name: d.name,
  2450. avatar: d.avatar,
  2451. groupId: d.teamId,
  2452. groupName: d.teamName,
  2453. isLeader: !!d.isTeamLeader,
  2454. status: d.status === 'idle' ? 'available' : 'busy',
  2455. currentProjects: Math.max(0, d.recentOrders || 0),
  2456. lastOrderDate: d.lastOrderDate,
  2457. idleDays: Math.max(0, d.idleDays || 0),
  2458. completedThisMonth: Math.max(0, d.recentOrders || 0),
  2459. averageCycle: 15,
  2460. upcomingEvents: (d.reviewDates || []).map((dateStr, idx) => ({
  2461. id: `${d.id}-review-${idx}`,
  2462. date: new Date(dateStr),
  2463. title: '对图评审',
  2464. type: 'review',
  2465. projectId: undefined,
  2466. duration: 2
  2467. })),
  2468. workload: Math.max(0, d.workload || 0),
  2469. nextAvailableDate: new Date()
  2470. };
  2471. }
  2472. // 处理咨询订单表单提交
  2473. // 存储订单创建时的客户信息和需求信息
  2474. onConsultationOrderSubmit(formData: any): void {
  2475. console.log('咨询订单表单提交:', formData);
  2476. // 保存订单创建数据
  2477. this.orderCreationData = formData;
  2478. // 更新projectData以便传递给子组件(集成报价与指派信息)
  2479. this.projectData = {
  2480. customerInfo: formData.customerInfo,
  2481. requirementInfo: formData.requirementInfo,
  2482. preferenceTags: formData.preferenceTags,
  2483. quotation: this.quotationData ? { ...this.quotationData } : undefined,
  2484. assignment: this.designerAssignmentData ? { ...this.designerAssignmentData } : undefined,
  2485. orderAmount: this.quotationData?.totalAmount ?? this.orderAmount ?? 0
  2486. };
  2487. // 实时更新左侧客户信息显示
  2488. this.updateCustomerInfoDisplay(formData);
  2489. // 根据角色上下文处理数据同步
  2490. if (formData.roleContext === 'customer-service') {
  2491. // 客服端创建的订单需要同步到设计师端
  2492. this.syncOrderToDesignerView(formData);
  2493. }
  2494. // 根据报价数据更新订单金额
  2495. this.orderAmount = this.quotationData?.totalAmount ?? this.orderAmount ?? 0;
  2496. this.updateOrderAmount();
  2497. // 触发变更检测以更新UI
  2498. this.cdr.detectChanges();
  2499. }
  2500. // 新增:更新客户信息显示 - 优化后只更新实际存在的字段
  2501. private updateCustomerInfoDisplay(formData: any): void {
  2502. if (formData.customerInfo) {
  2503. // 更新项目对象中的客户信息 - 只更新实际存在的字段
  2504. if (this.project) {
  2505. // 由于已移除客户姓名和手机号字段,只更新微信和客户类型
  2506. if (formData.customerInfo.wechat) {
  2507. this.project.customerWechat = formData.customerInfo.wechat;
  2508. }
  2509. if (formData.customerInfo.customerType) {
  2510. this.project.customerType = formData.customerInfo.customerType;
  2511. }
  2512. if (formData.customerInfo.source) {
  2513. this.project.customerSource = formData.customerInfo.source;
  2514. }
  2515. if (formData.customerInfo.remark) {
  2516. this.project.customerRemark = formData.customerInfo.remark;
  2517. }
  2518. }
  2519. // 更新客户标签
  2520. if (formData.preferenceTags) {
  2521. this.project = {
  2522. ...this.project,
  2523. customerTags: formData.preferenceTags
  2524. } as any;
  2525. }
  2526. // 更新需求信息 - 只更新实际存在的字段
  2527. if (formData.requirementInfo) {
  2528. this.project = {
  2529. ...this.project,
  2530. // 移除已删除的字段:decorationType, firstDraftDate, style, budget, area, houseType
  2531. downPayment: formData.requirementInfo.downPayment,
  2532. smallImageTime: formData.requirementInfo.smallImageTime,
  2533. spaceRequirements: formData.requirementInfo.spaceRequirements,
  2534. designAngles: formData.requirementInfo.designAngles,
  2535. specialAreaHandling: formData.requirementInfo.specialAreaHandling,
  2536. materialRequirements: formData.requirementInfo.materialRequirements,
  2537. lightingRequirements: formData.requirementInfo.lightingRequirements
  2538. } as any;
  2539. }
  2540. console.log('客户信息已实时更新:', this.project);
  2541. }
  2542. }
  2543. // 新增:同步订单数据到设计师视图
  2544. private syncOrderToDesignerView(formData: any): void {
  2545. // 创建项目数据
  2546. const projectData = {
  2547. customerId: formData.customerInfo.id || 'customer-' + Date.now(),
  2548. customerName: formData.customerInfo.name,
  2549. requirement: formData.requirementInfo,
  2550. referenceCases: [],
  2551. tags: {
  2552. demandType: formData.customerInfo.demandType,
  2553. preferenceTags: formData.preferenceTags,
  2554. followUpStatus: formData.customerInfo.followUpStatus
  2555. },
  2556. // 新增:报价与指派信息(可选)
  2557. quotation: this.quotationData ? { ...this.quotationData } : undefined,
  2558. assignment: this.designerAssignmentData ? { ...this.designerAssignmentData } : undefined,
  2559. orderAmount: this.quotationData?.totalAmount ?? this.orderAmount ?? 0
  2560. };
  2561. // 调用项目服务创建项目
  2562. this.projectService.createProject(projectData).subscribe(
  2563. result => {
  2564. if (result.success) {
  2565. console.log('订单数据已同步到设计师端,项目ID:', result.projectId);
  2566. // 可以在这里添加成功提示或其他处理逻辑
  2567. }
  2568. },
  2569. error => {
  2570. console.error('同步订单数据到设计师端失败:', error);
  2571. }
  2572. );
  2573. }
  2574. // 确认团队分配
  2575. confirmTeamAssignment(designer: any): void {
  2576. if (designer) {
  2577. this.selectedDesigner = designer;
  2578. console.log('团队分配确认:', designer);
  2579. // 这里可以添加实际的团队分配逻辑
  2580. // 例如调用服务来分配设计师到项目
  2581. // 进入下一个阶段:需求沟通
  2582. this.updateProjectStage('需求沟通');
  2583. this.expandedStages['需求沟通'] = true;
  2584. this.expandedStages['订单创建'] = false;
  2585. // 显示成功消息
  2586. alert('团队分配成功!已进入需求沟通阶段');
  2587. console.log('团队分配完成,已跳转到需求沟通阶段');
  2588. }
  2589. }
  2590. // 项目创建完成事件处理
  2591. onProjectCreated(projectData: any): void {
  2592. console.log('项目创建完成:', projectData);
  2593. this.projectData = projectData;
  2594. // 团队分配已在子组件中完成并触发该事件:推进到需求沟通阶段
  2595. this.updateProjectStage('需求沟通');
  2596. // 更新项目对象的当前阶段,确保四大板块状态正确显示
  2597. if (this.project) {
  2598. this.project.currentStage = '需求沟通';
  2599. }
  2600. // 展开需求沟通阶段,收起订单创建阶段
  2601. this.expandedStages['需求沟通'] = true;
  2602. this.expandedStages['订单创建'] = false;
  2603. // 自动展开确认需求板块
  2604. this.expandedSection = 'requirements';
  2605. // 强制触发变更检测,确保UI更新
  2606. this.cdr.detectChanges();
  2607. // 延迟滚动到需求沟通阶段,确保DOM更新完成
  2608. setTimeout(() => {
  2609. this.scrollToStage('需求沟通');
  2610. // 再次触发变更检测,确保所有状态都已正确更新
  2611. this.cdr.detectChanges();
  2612. }, 100);
  2613. console.log('项目创建成功,已推进到需求沟通阶段,四大板块状态已更新');
  2614. }
  2615. // 新增:处理实时需求数据更新
  2616. onRequirementDataUpdated(data: any): void {
  2617. console.log('收到需求数据更新:', data);
  2618. // 同步关键信息
  2619. this.syncRequirementKeyInfo(data);
  2620. // 更新客户信息显示
  2621. if (data && this.project) {
  2622. // 更新项目的客户信息
  2623. if (data.colorIndicators && data.colorIndicators.length > 0) {
  2624. this.project.customerInfo = {
  2625. ...this.project.customerInfo,
  2626. colorPreference: data.colorIndicators.map((indicator: any) => indicator.name).join(', ')
  2627. };
  2628. }
  2629. // 更新空间结构信息
  2630. if (data.spaceIndicators && data.spaceIndicators.length > 0) {
  2631. this.project.customerInfo = {
  2632. ...this.project.customerInfo,
  2633. spaceRequirements: data.spaceIndicators.map((indicator: any) => `${indicator.name}: ${indicator.value}`).join(', ')
  2634. };
  2635. }
  2636. // 更新材质偏好
  2637. if (data.materialIndicators && data.materialIndicators.length > 0) {
  2638. this.project.customerInfo = {
  2639. ...this.project.customerInfo,
  2640. materialPreference: data.materialIndicators.map((indicator: any) => `${indicator.name}: ${indicator.value}%`).join(', ')
  2641. };
  2642. }
  2643. // 更新需求项目
  2644. if (data.requirementItems && data.requirementItems.length > 0) {
  2645. this.project.requirements = data.requirementItems.map((item: any) => ({
  2646. id: item.id,
  2647. description: item.description,
  2648. status: item.status,
  2649. priority: item.priority || 'medium'
  2650. }));
  2651. }
  2652. // 接收色彩分析结果并存储用于右侧展示
  2653. if (data.colorAnalysisResult) {
  2654. console.log('接收到色彩分析结果:', data.colorAnalysisResult);
  2655. this.colorAnalysisResult = data.colorAnalysisResult as ColorAnalysisResult;
  2656. console.log('设置colorAnalysisResult后:', this.colorAnalysisResult);
  2657. // 计算主色:按占比最高的颜色
  2658. const colors = this.colorAnalysisResult?.colors || [];
  2659. if (colors.length > 0) {
  2660. const dominant = colors.reduce((max, cur) => cur.percentage > max.percentage ? cur : max, colors[0]);
  2661. this.dominantColorHex = dominant.hex;
  2662. console.log('计算出的主色:', this.dominantColorHex);
  2663. } else {
  2664. this.dominantColorHex = null;
  2665. console.log('没有颜色数据,主色设为null');
  2666. }
  2667. } else {
  2668. console.log('没有接收到色彩分析结果');
  2669. }
  2670. // 新增:处理详细的分析数据
  2671. if (data.detailedAnalysis) {
  2672. console.log('接收到详细分析数据:', data.detailedAnalysis);
  2673. // 存储各类分析结果
  2674. this.enhancedColorAnalysis = data.detailedAnalysis.enhancedColorAnalysis;
  2675. this.formAnalysis = data.detailedAnalysis.formAnalysis;
  2676. this.textureAnalysis = data.detailedAnalysis.textureAnalysis;
  2677. this.patternAnalysis = data.detailedAnalysis.patternAnalysis;
  2678. this.lightingAnalysis = data.detailedAnalysis.lightingAnalysis;
  2679. console.log('详细分析数据已存储:', {
  2680. enhancedColorAnalysis: this.enhancedColorAnalysis,
  2681. formAnalysis: this.formAnalysis,
  2682. textureAnalysis: this.textureAnalysis,
  2683. patternAnalysis: this.patternAnalysis,
  2684. lightingAnalysis: this.lightingAnalysis
  2685. });
  2686. }
  2687. // 新增:处理材料分析数据
  2688. if (data.materialAnalysisData && data.materialAnalysisData.length > 0) {
  2689. console.log('接收到材料分析数据:', data.materialAnalysisData);
  2690. this.materialAnalysisData = data.materialAnalysisData;
  2691. }
  2692. // 新增:根据上传来源拆分材料文件用于左右区展示
  2693. const materials = Array.isArray(data?.materials) ? data.materials : [];
  2694. this.referenceImages = materials.filter((m: any) => m?.type === 'image');
  2695. this.cadFiles = materials.filter((m: any) => m?.type === 'cad');
  2696. // 触发变更检测以更新UI
  2697. this.cdr.detectChanges();
  2698. console.log('客户信息已实时更新,当前colorAnalysisResult状态:', !!this.colorAnalysisResult);
  2699. }
  2700. }
  2701. // 预览右侧色彩分析参考图
  2702. previewColorRefImage(): void {
  2703. const url = this.colorAnalysisResult?.originalImage;
  2704. if (url) {
  2705. window.open(url, '_blank');
  2706. }
  2707. }
  2708. // 新增:点击预览参考图片与CAD文件
  2709. previewImageFile(url?: string): void {
  2710. if (!url) return;
  2711. window.open(url, '_blank');
  2712. }
  2713. previewCadFile(url?: string): void {
  2714. if (!url) return;
  2715. window.open(url, '_blank');
  2716. }
  2717. // 切换客户信息卡片展开状态
  2718. toggleCustomerInfo(): void {
  2719. this.isCustomerInfoExpanded = !this.isCustomerInfoExpanded;
  2720. }
  2721. // 新增:重置方案分析状态的方法
  2722. resetProposalAnalysis(): void {
  2723. this.proposalAnalysis = null;
  2724. this.isAnalyzing = false;
  2725. this.analysisProgress = 0;
  2726. console.log('方案分析状态已重置');
  2727. }
  2728. // 新增:模拟素材解析方法
  2729. startMaterialAnalysis(): void {
  2730. this.isAnalyzing = true;
  2731. this.analysisProgress = 0;
  2732. const progressInterval = setInterval(() => {
  2733. this.analysisProgress += Math.random() * 15;
  2734. if (this.analysisProgress >= 100) {
  2735. this.analysisProgress = 100;
  2736. clearInterval(progressInterval);
  2737. this.completeMaterialAnalysis();
  2738. }
  2739. }, 500);
  2740. }
  2741. // 完成素材解析,生成方案数据
  2742. private completeMaterialAnalysis(): void {
  2743. this.isAnalyzing = false;
  2744. // 生成模拟的方案分析数据
  2745. this.proposalAnalysis = {
  2746. id: 'proposal-' + Date.now(),
  2747. name: '现代简约风格方案',
  2748. version: 'v1.0',
  2749. createdAt: new Date(),
  2750. status: 'completed',
  2751. materials: [
  2752. {
  2753. category: '地面材料',
  2754. specifications: {
  2755. type: '复合木地板',
  2756. grade: 'E0级',
  2757. thickness: '12mm',
  2758. finish: '哑光面',
  2759. durability: '家用33级'
  2760. },
  2761. usage: {
  2762. area: '客厅、卧室',
  2763. percentage: 65,
  2764. priority: 'primary'
  2765. },
  2766. properties: {
  2767. texture: '木纹理',
  2768. color: '浅橡木色',
  2769. maintenance: '日常清洁'
  2770. }
  2771. },
  2772. {
  2773. category: '墙面材料',
  2774. specifications: {
  2775. type: '乳胶漆',
  2776. grade: '净味抗甲醛',
  2777. finish: '丝光面',
  2778. durability: '15年'
  2779. },
  2780. usage: {
  2781. area: '全屋墙面',
  2782. percentage: 80,
  2783. priority: 'primary'
  2784. },
  2785. properties: {
  2786. texture: '平滑',
  2787. color: '暖白色',
  2788. maintenance: '可擦洗'
  2789. }
  2790. },
  2791. {
  2792. category: '软装面料',
  2793. specifications: {
  2794. type: '亚麻混纺',
  2795. grade: 'A级',
  2796. finish: '防污处理',
  2797. durability: '5-8年'
  2798. },
  2799. usage: {
  2800. area: '沙发、窗帘',
  2801. percentage: 25,
  2802. priority: 'secondary'
  2803. },
  2804. properties: {
  2805. texture: '自然纹理',
  2806. color: '米灰色系',
  2807. maintenance: '干洗'
  2808. }
  2809. }
  2810. ],
  2811. designStyle: {
  2812. primaryStyle: '现代简约',
  2813. styleElements: [
  2814. {
  2815. element: '线条设计',
  2816. description: '简洁流畅的直线条,避免繁复装饰',
  2817. influence: 85
  2818. },
  2819. {
  2820. element: '色彩搭配',
  2821. description: '以中性色为主,局部点缀暖色',
  2822. influence: 75
  2823. },
  2824. {
  2825. element: '材质选择',
  2826. description: '天然材质与现代工艺结合',
  2827. influence: 70
  2828. }
  2829. ],
  2830. characteristics: [
  2831. {
  2832. feature: '空间感',
  2833. value: '开放通透',
  2834. importance: 'high'
  2835. },
  2836. {
  2837. feature: '功能性',
  2838. value: '实用至上',
  2839. importance: 'high'
  2840. },
  2841. {
  2842. feature: '装饰性',
  2843. value: '简约精致',
  2844. importance: 'medium'
  2845. }
  2846. ],
  2847. compatibility: {
  2848. withMaterials: ['木材', '金属', '玻璃', '石材'],
  2849. withColors: ['白色', '灰色', '米色', '原木色'],
  2850. score: 92
  2851. }
  2852. },
  2853. colorScheme: {
  2854. palette: [
  2855. {
  2856. color: '暖白色',
  2857. hex: '#F8F6F0',
  2858. rgb: '248, 246, 240',
  2859. percentage: 45,
  2860. role: 'dominant'
  2861. },
  2862. {
  2863. color: '浅灰色',
  2864. hex: '#E5E5E5',
  2865. rgb: '229, 229, 229',
  2866. percentage: 30,
  2867. role: 'secondary'
  2868. },
  2869. {
  2870. color: '原木色',
  2871. hex: '#D4A574',
  2872. rgb: '212, 165, 116',
  2873. percentage: 20,
  2874. role: 'accent'
  2875. },
  2876. {
  2877. color: '深灰色',
  2878. hex: '#4A4A4A',
  2879. rgb: '74, 74, 74',
  2880. percentage: 5,
  2881. role: 'neutral'
  2882. }
  2883. ],
  2884. harmony: {
  2885. type: '类似色调和',
  2886. temperature: 'warm',
  2887. contrast: 65
  2888. },
  2889. psychology: {
  2890. mood: '宁静舒适',
  2891. atmosphere: '温馨自然',
  2892. suitability: ['居住', '办公', '休闲']
  2893. }
  2894. },
  2895. spaceLayout: {
  2896. dimensions: {
  2897. length: 12.5,
  2898. width: 8.2,
  2899. height: 2.8,
  2900. area: 102.5,
  2901. volume: 287
  2902. },
  2903. functionalZones: [
  2904. {
  2905. zone: '客厅区域',
  2906. area: 35.2,
  2907. percentage: 34.3,
  2908. requirements: ['会客', '娱乐', '休息'],
  2909. furniture: ['沙发', '茶几', '电视柜', '边几']
  2910. },
  2911. {
  2912. zone: '餐厅区域',
  2913. area: 18.5,
  2914. percentage: 18.0,
  2915. requirements: ['用餐', '储物'],
  2916. furniture: ['餐桌', '餐椅', '餐边柜']
  2917. },
  2918. {
  2919. zone: '厨房区域',
  2920. area: 12.8,
  2921. percentage: 12.5,
  2922. requirements: ['烹饪', '储存', '清洁'],
  2923. furniture: ['橱柜', '岛台', '吧台椅']
  2924. },
  2925. {
  2926. zone: '主卧区域',
  2927. area: 25.6,
  2928. percentage: 25.0,
  2929. requirements: ['睡眠', '储衣', '梳妆'],
  2930. furniture: ['床', '衣柜', '梳妆台', '床头柜']
  2931. },
  2932. {
  2933. zone: '次卧区域',
  2934. area: 10.4,
  2935. percentage: 10.2,
  2936. requirements: ['睡眠', '学习'],
  2937. furniture: ['床', '书桌', '衣柜']
  2938. }
  2939. ],
  2940. circulation: {
  2941. mainPaths: ['入户-客厅', '客厅-餐厅', '餐厅-厨房', '客厅-卧室'],
  2942. pathWidth: 1.2,
  2943. efficiency: 88
  2944. },
  2945. lighting: {
  2946. natural: {
  2947. direction: ['南向', '东向'],
  2948. intensity: '充足',
  2949. duration: '8-10小时'
  2950. },
  2951. artificial: {
  2952. zones: ['主照明', '局部照明', '装饰照明'],
  2953. requirements: ['无主灯设计', '分层控制', '调光调色']
  2954. }
  2955. }
  2956. },
  2957. budget: {
  2958. total: 285000,
  2959. breakdown: [
  2960. {
  2961. category: '基础装修',
  2962. amount: 142500,
  2963. percentage: 50
  2964. },
  2965. {
  2966. category: '主材采购',
  2967. amount: 85500,
  2968. percentage: 30
  2969. },
  2970. {
  2971. category: '软装配饰',
  2972. amount: 42750,
  2973. percentage: 15
  2974. },
  2975. {
  2976. category: '设计费用',
  2977. amount: 14250,
  2978. percentage: 5
  2979. }
  2980. ]
  2981. },
  2982. timeline: [
  2983. {
  2984. phase: '设计深化',
  2985. duration: 7,
  2986. dependencies: ['需求确认']
  2987. },
  2988. {
  2989. phase: '材料采购',
  2990. duration: 5,
  2991. dependencies: ['设计深化']
  2992. },
  2993. {
  2994. phase: '基础施工',
  2995. duration: 30,
  2996. dependencies: ['材料采购']
  2997. },
  2998. {
  2999. phase: '软装进场',
  3000. duration: 7,
  3001. dependencies: ['基础施工']
  3002. },
  3003. {
  3004. phase: '验收交付',
  3005. duration: 3,
  3006. dependencies: ['软装进场']
  3007. }
  3008. ],
  3009. feasibility: {
  3010. technical: 95,
  3011. budget: 88,
  3012. timeline: 92,
  3013. overall: 92
  3014. }
  3015. };
  3016. }
  3017. // 获取材质分类统计
  3018. getMaterialCategories(): { category: string; count: number; percentage: number }[] {
  3019. if (!this.proposalAnalysis) return [];
  3020. const categories = this.proposalAnalysis.materials.reduce((acc, material) => {
  3021. acc[material.category] = (acc[material.category] || 0) + 1;
  3022. return acc;
  3023. }, {} as Record<string, number>);
  3024. const total = Object.values(categories).reduce((sum, count) => sum + count, 0);
  3025. return Object.entries(categories).map(([category, count]) => ({
  3026. category,
  3027. count,
  3028. percentage: Math.round((count / total) * 100)
  3029. }));
  3030. }
  3031. // 获取设计风格特征摘要
  3032. getStyleSummary(): string {
  3033. if (!this.proposalAnalysis) return '';
  3034. const style = this.proposalAnalysis.designStyle;
  3035. const topElements = style.styleElements
  3036. .sort((a, b) => b.influence - a.influence)
  3037. .slice(0, 2)
  3038. .map(el => el.element)
  3039. .join('、');
  3040. return `${style.primaryStyle}风格,主要体现在${topElements}等方面`;
  3041. }
  3042. // 获取色彩方案摘要
  3043. getColorSummary(): string {
  3044. if (!this.proposalAnalysis) return '';
  3045. const scheme = this.proposalAnalysis.colorScheme;
  3046. const dominantColor = scheme.palette.find(p => p.role === 'dominant')?.color || '';
  3047. const accentColor = scheme.palette.find(p => p.role === 'accent')?.color || '';
  3048. return `以${dominantColor}为主调,${accentColor}作点缀,营造${scheme.psychology.mood}的氛围`;
  3049. }
  3050. // 获取空间效率评分
  3051. getSpaceEfficiency(): number {
  3052. if (!this.proposalAnalysis) return 0;
  3053. return this.proposalAnalysis.spaceLayout.circulation.efficiency;
  3054. }
  3055. private handlePaymentProofUpload(file: File): void {
  3056. // 显示上传进度
  3057. const uploadingMessage = `正在上传支付凭证:${file.name}...`;
  3058. console.log(uploadingMessage);
  3059. // 使用支付凭证识别服务处理上传
  3060. const settlementId = this.project?.id || 'default_settlement';
  3061. this.paymentVoucherService.processPaymentVoucherUpload(file, settlementId).subscribe({
  3062. next: (result) => {
  3063. if (result.success && result.recognitionResult) {
  3064. const recognition = result.recognitionResult;
  3065. // 更新识别计数
  3066. this.voucherRecognitionCount++;
  3067. // 显示识别结果
  3068. const successMessage = `
  3069. 支付凭证识别成功!
  3070. 支付方式:${recognition.paymentMethod}
  3071. 支付金额:¥${recognition.amount}
  3072. 交易号:${recognition.transactionNumber}
  3073. 置信度:${(recognition.confidence * 100).toFixed(1)}%
  3074. `;
  3075. alert(successMessage);
  3076. console.log('支付凭证识别完成', recognition);
  3077. // 自动标记验证通过并解锁渲染大图
  3078. this.isPaymentVerified = true;
  3079. this.renderLargeImages = this.renderLargeImages.map(img => ({ ...img, locked: false }));
  3080. // 触发自动通知流程
  3081. this.triggerPaymentCompletedNotification(recognition);
  3082. } else {
  3083. const errorMessage = `支付凭证识别失败:${result.error || '未知错误'}`;
  3084. alert(errorMessage);
  3085. console.error('支付凭证识别失败', result.error);
  3086. }
  3087. },
  3088. error: (error) => {
  3089. const errorMessage = `支付凭证处理出错:${error.message || '网络错误'}`;
  3090. alert(errorMessage);
  3091. console.error('支付凭证处理出错', error);
  3092. }
  3093. });
  3094. }
  3095. /**
  3096. * 触发支付完成通知流程
  3097. */
  3098. private triggerPaymentCompletedNotification(recognition: any): void {
  3099. console.log('触发支付完成自动通知流程...');
  3100. // 模拟调用通知服务发送多渠道通知
  3101. this.sendMultiChannelNotifications(recognition);
  3102. // 模拟发送通知
  3103. setTimeout(() => {
  3104. const notificationMessage = `
  3105. 🎉 尾款已到账,大图已解锁!
  3106. 支付信息:
  3107. • 支付方式:${recognition.paymentMethod}
  3108. • 支付金额:¥${recognition.amount}
  3109. • 处理时间:${new Date().toLocaleString()}
  3110. 📱 系统已自动发送通知至:
  3111. • 短信通知:138****8888
  3112. • 微信通知:已推送至微信
  3113. • 邮件通知:customer@example.com
  3114. 🖼️ 高清渲染图下载链接已发送
  3115. 您现在可以下载4K高清渲染图了!
  3116. `;
  3117. alert(notificationMessage);
  3118. console.log('自动通知发送完成');
  3119. }, 1000);
  3120. }
  3121. /**
  3122. * 发送多渠道通知
  3123. */
  3124. private sendMultiChannelNotifications(recognition: any): void {
  3125. console.log('开始发送多渠道通知...');
  3126. // 更新通知发送计数
  3127. this.notificationsSent++;
  3128. // 模拟发送短信通知
  3129. console.log('📱 发送短信通知: 尾款已到账,大图已解锁');
  3130. // 模拟发送微信通知
  3131. console.log('💬 发送微信通知: 支付成功,高清图片已准备就绪');
  3132. // 模拟发送邮件通知
  3133. console.log('📧 发送邮件通知: 包含下载链接的详细通知');
  3134. // 模拟发送应用内通知
  3135. console.log('🔔 发送应用内通知: 实时推送支付状态更新');
  3136. // 模拟通知发送结果
  3137. setTimeout(() => {
  3138. console.log('✅ 所有渠道通知发送完成');
  3139. console.log(`通知发送统计: 短信✅ 微信✅ 邮件✅ 应用内✅ (总计: ${this.notificationsSent} 次)`);
  3140. }, 500);
  3141. }
  3142. // 获取当前设计师名称
  3143. getCurrentDesignerName(): string {
  3144. // 这里应该从用户服务或认证信息中获取当前用户名称
  3145. // 暂时返回一个默认值
  3146. return '张设计师';
  3147. }
  3148. // ==================== 售后相关变量 ====================
  3149. // 售后标签页控制
  3150. activeAftercareTab: string = 'services'; // 当前激活的售后标签页
  3151. // 售后状态管理
  3152. afterSalesStage: string = '未开始'; // 售后阶段:未开始、进行中、已完成
  3153. afterSalesStatus: 'pending' | 'in_progress' | 'completed' | 'cancelled' = 'pending'; // 售后状态
  3154. afterSalesProgress: number = 0; // 售后进度百分比
  3155. // 售后服务数据
  3156. afterSalesServices: Array<{
  3157. id: string;
  3158. type: string; // 服务类型:维修、保养、咨询、投诉处理
  3159. description: string;
  3160. assignedTo: string; // 指派给的人员
  3161. scheduledDate?: Date; // 计划服务日期
  3162. completedDate?: Date; // 完成日期
  3163. status: 'pending' | 'scheduled' | 'in_progress' | 'completed' | 'cancelled';
  3164. priority: 'low' | 'medium' | 'high';
  3165. }> = [];
  3166. // 售后评价和反馈
  3167. afterSalesRating: number = 0; // 售后评分(0-5)
  3168. afterSalesFeedback: string = ''; // 售后反馈内容
  3169. afterSalesFeedbackDate?: Date; // 反馈日期
  3170. // 售后时间跟踪
  3171. afterSalesResponseTime?: Date; // 首次响应时间
  3172. afterSalesStartTime?: Date; // 售后开始时间
  3173. afterSalesCompletionTime?: Date; // 售后完成时间
  3174. afterSalesTotalDuration: number = 0; // 总耗时(小时)
  3175. // 售后联系人信息
  3176. afterSalesContact: {
  3177. name: string;
  3178. phone: string;
  3179. wechat?: string;
  3180. email?: string;
  3181. } = {
  3182. name: '',
  3183. phone: ''
  3184. };
  3185. // 售后问题记录
  3186. afterSalesIssues: Array<{
  3187. id: string;
  3188. title: string;
  3189. description: string;
  3190. severity: 'low' | 'medium' | 'high' | 'critical';
  3191. reportedDate: Date;
  3192. resolvedDate?: Date;
  3193. status: 'reported' | 'investigating' | 'resolved' | 'closed';
  3194. }> = [];
  3195. // 售后文件记录
  3196. afterSalesDocuments: Array<{
  3197. id: string;
  3198. name: string;
  3199. type: string; // 文件类型:合同、报告、照片、视频
  3200. uploadDate: Date;
  3201. url: string;
  3202. }> = [];
  3203. // 售后费用记录
  3204. afterSalesCosts: Array<{
  3205. id: string;
  3206. description: string;
  3207. amount: number;
  3208. category: 'material' | 'labor' | 'transportation' | 'other';
  3209. date: Date;
  3210. status: 'pending' | 'approved' | 'paid' | 'rejected';
  3211. }> = [];
  3212. // 售后沟通记录
  3213. afterSalesCommunications: Array<{
  3214. id: string;
  3215. type: 'phone' | 'wechat' | 'email' | 'visit';
  3216. date: Date;
  3217. summary: string;
  3218. participants: string[];
  3219. }> = [];
  3220. // 新增:项目复盘相关属性
  3221. projectReview: ProjectReview | null = null;
  3222. isGeneratingReview: boolean = false;
  3223. // 项目复盘 Tab 切换
  3224. activeReviewTab: 'sop' | 'experience' | 'suggestions' = 'sop';
  3225. // SOP执行数据
  3226. sopMetrics: any = {
  3227. communicationCount: 6,
  3228. avgCommunication: 5,
  3229. revisionCount: 3,
  3230. avgRevision: 2,
  3231. deliveryCycle: 18,
  3232. standardCycle: 15,
  3233. customerSatisfaction: 4.5
  3234. };
  3235. sopStagesData: any[] = [
  3236. { name: '订单创建', plannedDuration: 1, actualDuration: 1, score: 95, status: 'completed', statusText: '已完成', isDelayed: false, issues: [] },
  3237. { name: '需求沟通', plannedDuration: 3, actualDuration: 4, score: 75, status: 'completed', statusText: '已完成', isDelayed: true, issues: ['沟通次数超标'] },
  3238. { name: '方案确认', plannedDuration: 2, actualDuration: 2, score: 90, status: 'completed', statusText: '已完成', isDelayed: false, issues: [] },
  3239. { name: '建模', plannedDuration: 4, actualDuration: 5, score: 80, status: 'completed', statusText: '已完成', isDelayed: true, issues: ['细节调整耗时'] },
  3240. { name: '软装', plannedDuration: 2, actualDuration: 2, score: 92, status: 'completed', statusText: '已完成', isDelayed: false, issues: [] },
  3241. { name: '渲染', plannedDuration: 3, actualDuration: 4, score: 85, status: 'ongoing', statusText: '进行中', isDelayed: false, issues: [] }
  3242. ];
  3243. // 经验复盘数据
  3244. experienceData: any = {
  3245. customerNeeds: [
  3246. { text: '希望客厅采用现代简约风格,注重收纳功能', timestamp: '2024-01-15 10:30', source: '初次沟通' },
  3247. { text: '卧室需要温馨氛围,色调以暖色为主', timestamp: '2024-01-16 14:20', source: '需求确认' },
  3248. { text: '厨房要求实用性强,采用白色橱柜', timestamp: '2024-01-17 09:15', source: '细节讨论' }
  3249. ],
  3250. customerConcerns: [
  3251. { text: '担心渲染图与实际效果有差异', timestamp: '2024-01-18 16:40', resolved: true },
  3252. { text: '预算控制在合理范围内', timestamp: '2024-01-19 11:25', resolved: true }
  3253. ],
  3254. complaintPoints: [
  3255. { text: '首版方案色彩搭配不符合预期', timestamp: '2024-01-20 15:10', severity: 'medium', severityText: '中等', resolution: '已调整为客户偏好的配色方案' }
  3256. ],
  3257. projectHighlights: [
  3258. { text: '设计师对空间的功能分区把握精准', category: '设计亮点', praised: true },
  3259. { text: '材质选择符合客户品味且性价比高', category: '材质选择', praised: true },
  3260. { text: '渲染效果图质量优秀,客户非常满意', category: '技术表现', praised: true }
  3261. ],
  3262. communications: [
  3263. { timestamp: '2024-01-15 10:30', participant: '客户', type: 'requirement', typeText: '需求提出', message: '希望整体风格简约现代,注重实用性...', attachments: [] },
  3264. { timestamp: '2024-01-16 09:00', participant: '设计师', type: 'response', typeText: '设计反馈', message: '根据您的需求,我们建议采用...', attachments: ['方案草图.jpg'] },
  3265. { timestamp: '2024-01-20 14:30', participant: '客户', type: 'concern', typeText: '疑虑表达', message: '对配色方案有些疑虑...', attachments: [] }
  3266. ]
  3267. };
  3268. // 优化建议数据
  3269. optimizationSuggestions: any[] = [
  3270. {
  3271. priority: 'high',
  3272. priorityText: '高优先级',
  3273. category: '需求沟通',
  3274. expectedImprovement: '减少30%改图次数',
  3275. problem: '该项目因需求理解不够深入导致改图3次,超出平均水平',
  3276. dataPoints: [
  3277. { label: '实际改图次数', value: '3次', isWarning: true },
  3278. { label: '平均改图次数', value: '2次', isWarning: false },
  3279. { label: '超出比例', value: '+50%', isWarning: true }
  3280. ],
  3281. solution: '建议在需求沟通阶段增加确认环节,通过详细的需求确认清单和参考案例,确保设计师完全理解客户需求',
  3282. actionPlan: [
  3283. '制定标准化的需求确认清单,覆盖风格、色彩、材质、功能等核心要素',
  3284. '在方案设计前与客户进行一次需求复核会议',
  3285. '准备3-5个同类型案例供客户参考,明确设计方向',
  3286. '使用可视化工具(如情绪板)帮助客户表达偏好'
  3287. ],
  3288. references: ['项目A-123', '项目B-456']
  3289. },
  3290. {
  3291. priority: 'medium',
  3292. priorityText: '中优先级',
  3293. category: '时间管理',
  3294. expectedImprovement: '缩短15%交付周期',
  3295. problem: '项目交付周期为18天,超出标准周期15天',
  3296. dataPoints: [
  3297. { label: '实际周期', value: '18天', isWarning: true },
  3298. { label: '标准周期', value: '15天', isWarning: false },
  3299. { label: '延期', value: '+3天', isWarning: true }
  3300. ],
  3301. solution: '优化建模和渲染阶段的时间分配,采用并行工作模式提高效率',
  3302. actionPlan: [
  3303. '建模和软装选择可以部分并行进行',
  3304. '提前准备常用材质库,减少临时查找时间',
  3305. '设置阶段里程碑提醒,避免单一阶段耗时过长'
  3306. ],
  3307. references: ['时间优化案例-001']
  3308. },
  3309. {
  3310. priority: 'low',
  3311. priorityText: '低优先级',
  3312. category: '客户体验',
  3313. expectedImprovement: '提升客户满意度至4.8分',
  3314. problem: '当前客户满意度为4.5分,仍有提升空间',
  3315. dataPoints: [
  3316. { label: '当前满意度', value: '4.5/5', isWarning: false },
  3317. { label: '目标满意度', value: '4.8/5', isWarning: false }
  3318. ],
  3319. solution: '增加交付过程中的沟通频率,及时展示阶段性成果',
  3320. actionPlan: [
  3321. '每个关键节点完成后主动向客户汇报进度',
  3322. '提供阶段性预览图,让客户参与到创作过程中',
  3323. '建立客户反馈快速响应机制'
  3324. ],
  3325. references: []
  3326. }
  3327. ];
  3328. switchAftercareTab(tab: string): void {
  3329. this.activeAftercareTab = tab;
  3330. console.log('切换到售后标签页:', tab);
  3331. }
  3332. // ==================== 自动结算相关 ====================
  3333. // 检查项目是否已完成验收
  3334. isProjectAccepted(): boolean {
  3335. // 检查所有交付阶段是否完成
  3336. const deliveryStages: ProjectStage[] = ['建模', '软装', '渲染', '后期'];
  3337. return deliveryStages.every(stage => this.getStageStatus(stage) === 'completed');
  3338. }
  3339. // 启动自动结算(只有技术人员可触发)
  3340. initiateAutoSettlement(): void {
  3341. if (this.isAutoSettling) return;
  3342. // 权限检查
  3343. if (!this.isTechnicalView()) {
  3344. alert('⚠️ 仅技术人员可以启动自动化结算流程');
  3345. return;
  3346. }
  3347. // 验收状态检查
  3348. if (!this.isProjectAccepted()) {
  3349. const confirmStart = confirm('项目尚未完成全部验收,确定要启动结算流程吗?');
  3350. if (!confirmStart) return;
  3351. }
  3352. this.isAutoSettling = true;
  3353. console.log('启动自动化结算流程...');
  3354. // 模拟启动各个自动化功能
  3355. setTimeout(() => {
  3356. // 1. 启动小程序支付监听
  3357. this.miniprogramPaymentStatus = 'active';
  3358. this.isSettlementInitiated = true;
  3359. console.log('✅ 自动化结算已启动');
  3360. console.log('🟢 小程序支付监听已激活');
  3361. console.log('🔍 支付凭证智能识别已就绪');
  3362. console.log('📱 自动通知系统已就绪');
  3363. // 2. 自动生成尾款结算记录
  3364. this.createFinalPaymentRecord();
  3365. // 3. 通知客服跟进尾款
  3366. this.notifyCustomerServiceForFinalPayment();
  3367. // 4. 设置支付监听和自动化流程
  3368. this.setupPaymentAutomation();
  3369. this.isAutoSettling = false;
  3370. // 显示启动成功消息
  3371. alert(`🚀 自动化结算已成功启动!
  3372. ✅ 已启动功能:
  3373. • 小程序支付自动监听
  3374. • 支付凭证智能识别
  3375. • 多渠道自动通知
  3376. • 大图自动解锁
  3377. • 已通知客服跟进尾款
  3378. 系统将自动处理后续支付流程。`);
  3379. }, 2000);
  3380. }
  3381. // 创建尾款结算记录
  3382. private createFinalPaymentRecord(): void {
  3383. const finalPaymentRecord: Settlement = {
  3384. id: `settlement_${Date.now()}`,
  3385. projectId: this.projectId,
  3386. projectName: this.project?.name || '',
  3387. type: 'final_payment',
  3388. amount: this.project?.finalPaymentAmount || 0,
  3389. percentage: 30,
  3390. status: 'pending',
  3391. createdAt: new Date(),
  3392. initiatedBy: 'technical',
  3393. initiatedAt: new Date(),
  3394. notifiedCustomerService: false,
  3395. paymentReceived: false,
  3396. imagesUnlocked: false
  3397. };
  3398. // 添加到结算列表
  3399. if (!this.settlements.find(s => s.type === 'final_payment')) {
  3400. this.settlements.unshift(finalPaymentRecord);
  3401. }
  3402. console.log('📝 已创建尾款结算记录:', finalPaymentRecord);
  3403. }
  3404. // 通知客服跟进尾款
  3405. private notifyCustomerServiceForFinalPayment(): void {
  3406. const projectInfo = {
  3407. projectId: this.projectId,
  3408. projectName: this.project?.name || '未知项目',
  3409. customerName: this.project?.customerName || '未知客户',
  3410. customerPhone: this.project?.customerPhone || '',
  3411. finalPaymentAmount: this.project?.finalPaymentAmount || 0,
  3412. notificationTime: new Date(),
  3413. status: 'pending_followup',
  3414. priority: 'high',
  3415. autoGenerated: true,
  3416. message: `项目【${this.project?.name}】已完成技术验收,请及时跟进客户尾款支付。`
  3417. };
  3418. // 发送通知到客服系统
  3419. console.log('📢 正在通知客服跟进尾款...', projectInfo);
  3420. // 模拟API调用到客服通知系统
  3421. // this.customerServiceAPI.addPendingTask(projectInfo).subscribe(...)
  3422. setTimeout(() => {
  3423. console.log('✅ 客服通知已发送成功');
  3424. // 更新结算记录状态
  3425. const settlement = this.settlements.find(s => s.type === 'final_payment');
  3426. if (settlement) {
  3427. settlement.notifiedCustomerService = true;
  3428. }
  3429. }, 500);
  3430. }
  3431. // 设置支付自动化流程
  3432. private setupPaymentAutomation(): void {
  3433. console.log('⚙️ 设置支付自动化监听...');
  3434. // 模拟支付监听(实际应使用WebSocket或轮询)
  3435. // 这里仅作演示
  3436. this.monitorPaymentStatus();
  3437. }
  3438. // 监听支付状态
  3439. private monitorPaymentStatus(): void {
  3440. // 实际应该使用WebSocket连接或定时轮询API
  3441. // 这里仅作演示用setTimeout模拟
  3442. console.log('👀 开始监听支付状态...');
  3443. // 当检测到支付完成时,自动触发后续流程
  3444. // this.onPaymentReceived();
  3445. }
  3446. // 支付到账回调
  3447. onPaymentReceived(paymentInfo?: any): void {
  3448. console.log('💰 检测到支付到账:', paymentInfo);
  3449. const settlement = this.settlements.find(s => s.type === 'final_payment');
  3450. if (!settlement) return;
  3451. // 更新结算状态
  3452. settlement.status = '已结算';
  3453. settlement.settledAt = new Date();
  3454. settlement.paymentReceived = true;
  3455. settlement.paymentReceivedAt = new Date();
  3456. // 自动解锁并发送大图
  3457. this.autoUnlockAndSendImages();
  3458. // 通知客户和客服
  3459. this.sendPaymentConfirmationNotifications();
  3460. }
  3461. // 自动解锁并发送大图
  3462. private autoUnlockAndSendImages(): void {
  3463. console.log('🔓 自动解锁大图...');
  3464. // 更新结算记录
  3465. const settlement = this.settlements.find(s => s.type === 'final_payment');
  3466. if (settlement) {
  3467. settlement.imagesUnlocked = true;
  3468. settlement.imagesUnlockedAt = new Date();
  3469. }
  3470. // 自动发送大图给客户(通过客服)
  3471. this.autoSendImagesToCustomer();
  3472. console.log('✅ 大图已解锁并准备发送');
  3473. }
  3474. // 自动发送图片给客户
  3475. private autoSendImagesToCustomer(): void {
  3476. console.log('📤 自动发送大图给客户...');
  3477. // 收集所有渲染大图
  3478. const renderProcess = this.deliveryProcesses.find(p => p.id === 'rendering');
  3479. const images: string[] = [];
  3480. if (renderProcess) {
  3481. Object.keys(renderProcess.content).forEach(spaceId => {
  3482. const content = renderProcess.content[spaceId];
  3483. if (content.images) {
  3484. content.images.forEach(img => {
  3485. images.push(img.url);
  3486. });
  3487. }
  3488. });
  3489. }
  3490. const sendInfo = {
  3491. projectId: this.projectId,
  3492. customerName: this.project?.customerName || '',
  3493. images: images,
  3494. sendMethod: 'wechat',
  3495. autoGenerated: true
  3496. };
  3497. console.log('📨 准备发送的大图信息:', sendInfo);
  3498. // 调用客服系统API一键发图
  3499. // this.customerServiceAPI.sendImagesToCustomer(sendInfo).subscribe(...)
  3500. }
  3501. // 发送支付确认通知
  3502. private sendPaymentConfirmationNotifications(): void {
  3503. console.log('📱 发送支付确认通知...');
  3504. // 通知客户
  3505. const customerMessage = `尊敬的${this.project?.customerName || '客户'},您的尾款支付已确认,大图已自动解锁并发送,请查收。感谢您的信任!`;
  3506. // 通知客服
  3507. const csMessage = `项目【${this.project?.name}】尾款已到账,大图已自动解锁,请一键发送给客户。`;
  3508. console.log('📧 客户通知:', customerMessage);
  3509. console.log('📧 客服通知:', csMessage);
  3510. // 实际发送通知
  3511. // this.notificationService.send({ to: 'customer', message: customerMessage });
  3512. // this.notificationService.send({ to: 'customer_service', message: csMessage });
  3513. }
  3514. // ==================== 全景图合成相关 ====================
  3515. // 全景图合成数据
  3516. panoramicSyntheses: PanoramicSynthesis[] = [];
  3517. isUploadingPanoramicImages: boolean = false;
  3518. panoramicUploadProgress: number = 0;
  3519. // 启动全景图合成流程
  3520. // 上传支付凭证
  3521. uploadPaymentProof(): void {
  3522. console.log('📎 打开支付凭证上传...');
  3523. const fileInput = document.createElement('input');
  3524. fileInput.type = 'file';
  3525. fileInput.accept = 'image/*';
  3526. fileInput.onchange = (event: any) => {
  3527. const file = (event.target as HTMLInputElement).files?.[0];
  3528. if (!file) return;
  3529. console.log('📄 上传的凭证文件:', file.name);
  3530. alert(`📎 支付凭证已上传:${file.name}\n\n系统将自动识别支付金额和支付方式。`);
  3531. // 模拟凭证识别和处理
  3532. setTimeout(() => {
  3533. const mockPaymentInfo = {
  3534. amount: this.project?.finalPaymentAmount || 5000,
  3535. method: '微信支付',
  3536. imageUrl: URL.createObjectURL(file),
  3537. uploadTime: new Date()
  3538. };
  3539. console.log('✅ 支付凭证识别完成:', mockPaymentInfo);
  3540. this.onPaymentReceived(mockPaymentInfo);
  3541. }, 1500);
  3542. };
  3543. fileInput.click();
  3544. }
  3545. startPanoramicSynthesis(): void {
  3546. console.log('🎨 启动全景图合成...');
  3547. // 显示提示信息
  3548. alert('📸 请选择需要合成全景图的图片\n\n提示:\n1. 建议选择同一空间的多个角度照片\n2. 图片文件名可以包含空间名称(如:客厅-角度1.jpg)\n3. 系统会自动识别并分类');
  3549. // 打开文件选择对话框,支持多文件选择
  3550. const fileInput = document.createElement('input');
  3551. fileInput.type = 'file';
  3552. fileInput.accept = 'image/*';
  3553. fileInput.multiple = true;
  3554. fileInput.onchange = (event: any) => {
  3555. const files = Array.from(event.target.files || []) as File[];
  3556. if (files.length === 0) return;
  3557. console.log(`📸 选择了 ${files.length} 张图片进行合成`);
  3558. this.processPanoramicImages(files);
  3559. };
  3560. fileInput.click();
  3561. }
  3562. // 处理全景图片上传和合成
  3563. private processPanoramicImages(files: File[]): void {
  3564. this.isUploadingPanoramicImages = true;
  3565. this.panoramicUploadProgress = 0;
  3566. console.log(`📸 开始处理 ${files.length} 张全景图片...`);
  3567. // 模拟上传进度
  3568. const uploadInterval = setInterval(() => {
  3569. this.panoramicUploadProgress += 10;
  3570. if (this.panoramicUploadProgress >= 100) {
  3571. clearInterval(uploadInterval);
  3572. this.panoramicUploadProgress = 100;
  3573. // 上传完成后开始合成
  3574. this.synthesizePanoramicView(files);
  3575. }
  3576. }, 300);
  3577. }
  3578. // 合成全景漫游
  3579. private synthesizePanoramicView(files: File[]): void {
  3580. console.log('🔄 开始合成全景漫游...');
  3581. // 创建合成记录
  3582. const synthesis: PanoramicSynthesis = {
  3583. id: 'panoramic-' + Date.now(),
  3584. projectId: this.projectId,
  3585. projectName: this.project?.name || '未知项目',
  3586. spaces: [],
  3587. status: 'processing',
  3588. quality: 'high',
  3589. createdAt: new Date(),
  3590. updatedAt: new Date(),
  3591. progress: 0
  3592. };
  3593. // 根据上传的文件创建空间列表
  3594. files.forEach((file, index) => {
  3595. // 从文件名提取空间名称(如"客厅-角度1.jpg")
  3596. const fileName = file.name.replace(/\.(jpg|jpeg|png|gif)$/i, '');
  3597. const match = fileName.match(/^(.+?)-/);
  3598. const spaceName = match ? match[1] : `空间${index + 1}`;
  3599. // 根据空间名称推断类型
  3600. let spaceType: 'living_room' | 'bedroom' | 'kitchen' | 'bathroom' | 'dining_room' | 'study' | 'balcony' = 'living_room';
  3601. if (spaceName.includes('客厅')) spaceType = 'living_room';
  3602. else if (spaceName.includes('卧室')) spaceType = 'bedroom';
  3603. else if (spaceName.includes('厨房')) spaceType = 'kitchen';
  3604. else if (spaceName.includes('卫生间') || spaceName.includes('浴室')) spaceType = 'bathroom';
  3605. else if (spaceName.includes('餐厅')) spaceType = 'dining_room';
  3606. else if (spaceName.includes('书房')) spaceType = 'study';
  3607. else if (spaceName.includes('阳台')) spaceType = 'balcony';
  3608. synthesis.spaces.push({
  3609. id: `space_${Date.now()}_${index}`,
  3610. name: spaceName,
  3611. type: spaceType,
  3612. imageCount: 1,
  3613. viewAngle: fileName
  3614. });
  3615. });
  3616. this.panoramicSyntheses.unshift(synthesis);
  3617. // 模拟KR Panel合成进度
  3618. let progress = 0;
  3619. const synthesisInterval = setInterval(() => {
  3620. progress += 15;
  3621. synthesis.progress = Math.min(progress, 100);
  3622. synthesis.updatedAt = new Date();
  3623. if (progress >= 100) {
  3624. clearInterval(synthesisInterval);
  3625. // 合成完成
  3626. synthesis.status = 'completed';
  3627. synthesis.completedAt = new Date();
  3628. synthesis.previewUrl = this.generateMockPanoramicUrl(synthesis.id);
  3629. synthesis.downloadUrl = this.generateMockDownloadUrl(synthesis.id);
  3630. synthesis.renderTime = 120 + Math.floor(Math.random() * 60);
  3631. synthesis.fileSize = files.reduce((sum, f) => sum + f.size, 0);
  3632. this.isUploadingPanoramicImages = false;
  3633. console.log('✅ 全景图合成完成:', synthesis);
  3634. // 自动生成分享链接
  3635. this.generatePanoramicShareLink(synthesis);
  3636. }
  3637. }, 500);
  3638. }
  3639. // 生成全景图分享链接
  3640. private generatePanoramicShareLink(synthesis: PanoramicSynthesis): void {
  3641. const shareLink = `https://panoramic.example.com/view/${synthesis.id}`;
  3642. synthesis.shareLink = shareLink;
  3643. console.log('🔗 全景图分享链接:', shareLink);
  3644. // 自动通知客服发送给客户
  3645. this.notifyCustomerServiceForPanoramicLink(synthesis);
  3646. }
  3647. // 通知客服发送全景图链接
  3648. private notifyCustomerServiceForPanoramicLink(synthesis: PanoramicSynthesis): void {
  3649. const notification = {
  3650. type: 'panoramic_ready',
  3651. projectId: this.projectId,
  3652. projectName: synthesis.projectName,
  3653. shareLink: synthesis.shareLink,
  3654. message: `项目【${synthesis.projectName}】的全景漫游已生成完成,请发送给客户查看。`,
  3655. timestamp: new Date()
  3656. };
  3657. console.log('📢 通知客服发送全景图链接:', notification);
  3658. // 调用客服通知API
  3659. // this.customerServiceAPI.notifyPanoramicReady(notification).subscribe(...)
  3660. }
  3661. // 生成模拟全景图URL
  3662. private generateMockPanoramicUrl(id: string): string {
  3663. return `https://panoramic.example.com/preview/${id}`;
  3664. }
  3665. // 生成模拟下载URL
  3666. private generateMockDownloadUrl(id: string): string {
  3667. return `https://panoramic.example.com/download/${id}`;
  3668. }
  3669. // 查看全景图画廊
  3670. viewPanoramicGallery(): void {
  3671. console.log('📁 打开全景图画廊');
  3672. if (this.panoramicSyntheses.length === 0) {
  3673. alert('📁 全景图画廊\n\n暂无全景图记录,请先进行全景图合成。');
  3674. return;
  3675. }
  3676. // 显示全景图列表提示
  3677. const galleryInfo = this.panoramicSyntheses.map((item, index) =>
  3678. `${index + 1}. ${item.projectName} - ${item.status === 'completed' ? '✅ 已完成' : '⏳ 处理中'} (${item.spaces?.length || 0}个空间)`
  3679. ).join('\n');
  3680. alert(`📁 全景图画廊(共${this.panoramicSyntheses.length}个)\n\n${galleryInfo}\n\n提示:点击列表中的全景图可查看详情或下载`);
  3681. }
  3682. // 复制全景图链接
  3683. copyPanoramicLink(synthesis: PanoramicSynthesis): void {
  3684. if (!synthesis.shareLink) {
  3685. alert('全景图链接尚未生成');
  3686. return;
  3687. }
  3688. navigator.clipboard.writeText(synthesis.shareLink).then(() => {
  3689. alert(`✅ 全景图链接已复制!\n\n${synthesis.shareLink}`);
  3690. }).catch(() => {
  3691. alert(`全景图链接:\n${synthesis.shareLink}`);
  3692. });
  3693. }
  3694. // ==================== 评价统计相关 ====================
  3695. // 评价统计数据
  3696. reviewStats: {
  3697. overallScore: number;
  3698. timelinessScore: number;
  3699. qualityScore: number;
  3700. communicationScore: number;
  3701. } = {
  3702. overallScore: 4.8,
  3703. timelinessScore: 4.7,
  3704. qualityScore: 4.9,
  3705. communicationScore: 4.6
  3706. };
  3707. // ==================== 客户评价相关 ====================
  3708. // 生成评价链接
  3709. generateReviewLink(): void {
  3710. console.log('📋 生成客户评价链接...');
  3711. // 生成唯一的评价令牌
  3712. const reviewToken = this.generateReviewToken();
  3713. const reviewLink = `https://review.yss.com/project/${this.projectId}?token=${reviewToken}`;
  3714. // 保存评价链接记录
  3715. const reviewRecord = {
  3716. projectId: this.projectId,
  3717. projectName: this.project?.name || '',
  3718. customerName: this.project?.customerName || '',
  3719. reviewLink: reviewLink,
  3720. token: reviewToken,
  3721. createdAt: new Date(),
  3722. expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30天有效期
  3723. status: 'active',
  3724. accessed: false
  3725. };
  3726. console.log('✅ 评价链接已生成:', reviewRecord);
  3727. // 复制到剪贴板
  3728. navigator.clipboard.writeText(reviewLink).then(() => {
  3729. alert(`✅ 评价链接已复制到剪贴板!\n\n链接:${reviewLink}\n\n有效期:30天\n\n请通过企业微信发送给客户`);
  3730. }).catch(() => {
  3731. alert(`评价链接:\n\n${reviewLink}\n\n有效期:30天\n\n请通过企业微信发送给客户`);
  3732. });
  3733. // 通知客服发送评价链接
  3734. this.notifyCustomerServiceForReviewLink(reviewRecord);
  3735. }
  3736. // 生成评价令牌
  3737. private generateReviewToken(): string {
  3738. return `review_${this.projectId}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  3739. }
  3740. // 通知客服发送评价链接
  3741. private notifyCustomerServiceForReviewLink(reviewRecord: any): void {
  3742. const notification = {
  3743. type: 'review_link_ready',
  3744. projectId: this.projectId,
  3745. projectName: reviewRecord.projectName,
  3746. customerName: reviewRecord.customerName,
  3747. reviewLink: reviewRecord.reviewLink,
  3748. message: `项目【${reviewRecord.projectName}】的客户评价链接已生成,请发送给客户。`,
  3749. timestamp: new Date()
  3750. };
  3751. console.log('📢 通知客服发送评价链接:', notification);
  3752. // 调用客服通知API
  3753. // this.customerServiceAPI.notifyReviewLinkReady(notification).subscribe(...)
  3754. }
  3755. // 确认客户评价完成
  3756. confirmCustomerReview(): void {
  3757. console.log('✅ 确认客户评价完成');
  3758. // 更新项目状态
  3759. if (this.project) {
  3760. this.project.customerReviewCompleted = true;
  3761. this.project.customerReviewCompletedAt = new Date();
  3762. }
  3763. alert('✅ 客户评价已确认完成!');
  3764. // 可选:自动进入下一阶段
  3765. // this.advanceToNextStage('客户评价');
  3766. }
  3767. // ==================== 投诉管理相关 ====================
  3768. // 关键词监控配置
  3769. complaintKeywords: string[] = ['不满意', '投诉', '退款', '差评', '质量问题', '延期', '态度差'];
  3770. isKeywordMonitoringActive: boolean = false;
  3771. // 手动创建投诉
  3772. createComplaintManually(): void {
  3773. console.log('📝 手动创建投诉');
  3774. // 显示创建投诉表单提示
  3775. alert('📝 创建投诉记录\n\n即将打开投诉创建表单,请填写以下信息:\n• 投诉环节\n• 核心问题\n• 客户反馈\n• 严重程度');
  3776. // 弹出创建投诉表单
  3777. const complaintReason = prompt('请输入投诉原因:');
  3778. if (!complaintReason || complaintReason.trim() === '') return;
  3779. const complaintStage = prompt('请输入投诉环节(如:需求沟通、建模、渲染等):') || '未指定';
  3780. // 创建投诉记录
  3781. const complaint: any = {
  3782. id: `complaint_${Date.now()}`,
  3783. projectId: this.projectId,
  3784. projectName: this.project?.name || '',
  3785. customerName: this.project?.customerName || '',
  3786. type: '人工创建',
  3787. stage: complaintStage,
  3788. reason: complaintReason,
  3789. severity: 'medium',
  3790. status: 'pending',
  3791. createdBy: 'manual',
  3792. createdAt: new Date(),
  3793. handler: '',
  3794. resolution: '',
  3795. resolvedAt: null
  3796. };
  3797. // 智能标注核心问题
  3798. complaint.tags = this.analyzeComplaintTags(complaintReason);
  3799. // 添加到投诉列表
  3800. this.exceptionHistories.unshift(complaint);
  3801. console.log('✅ 投诉记录已创建:', complaint);
  3802. alert(`✅ 投诉记录已创建!\n\n投诉环节:${complaintStage}\n核心问题:${complaint.tags.join('、')}\n\n系统将自动跟踪处理进度。`);
  3803. // 通知相关人员
  3804. this.notifyComplaintHandlers(complaint);
  3805. }
  3806. // 分析投诉标签
  3807. private analyzeComplaintTags(reason: string): string[] {
  3808. const tags: string[] = [];
  3809. const tagPatterns = {
  3810. '需求理解': ['需求', '理解', '沟通', '误解'],
  3811. '设计质量': ['质量', '效果', '不好', '不满意'],
  3812. '交付延期': ['延期', '超时', '慢', '着急'],
  3813. '服务态度': ['态度', '不礼貌', '敷衍', '回复慢'],
  3814. '价格问题': ['价格', '费用', '贵', '退款']
  3815. };
  3816. Object.entries(tagPatterns).forEach(([tag, keywords]) => {
  3817. if (keywords.some(keyword => reason.includes(keyword))) {
  3818. tags.push(tag);
  3819. }
  3820. });
  3821. return tags.length > 0 ? tags : ['其他'];
  3822. }
  3823. // 通知投诉处理人员
  3824. private notifyComplaintHandlers(complaint: any): void {
  3825. const notification = {
  3826. type: 'new_complaint',
  3827. projectId: this.projectId,
  3828. complaintId: complaint.id,
  3829. projectName: complaint.projectName,
  3830. customerName: complaint.customerName,
  3831. severity: complaint.severity,
  3832. tags: complaint.tags,
  3833. message: `项目【${complaint.projectName}】收到新投诉,请及时处理。`,
  3834. timestamp: new Date()
  3835. };
  3836. console.log('📢 通知投诉处理人员:', notification);
  3837. // 调用通知API
  3838. // this.complaintService.notifyHandlers(notification).subscribe(...)
  3839. }
  3840. // 设置关键词监控
  3841. setupKeywordMonitoring(): void {
  3842. console.log('⚙️ 设置关键词监控');
  3843. if (this.isKeywordMonitoringActive) {
  3844. const confirmStop = confirm('⚙️ 关键词监控管理\n\n状态:✅ 已激活\n监控关键词:' + this.complaintKeywords.join('、') + '\n\n是否停止监控?');
  3845. if (confirmStop) {
  3846. this.isKeywordMonitoringActive = false;
  3847. alert('⏸️ 关键词监控已停止\n\n系统将不再自动抓取企业微信群中的投诉关键词');
  3848. }
  3849. return;
  3850. }
  3851. // 显示设置说明和当前关键词
  3852. alert('⚙️ 关键词监控功能\n\n功能说明:\n• 自动监测企业微信群消息\n• 识别投诉相关关键词\n• 自动创建投诉记录并标注\n• 实时通知相关处理人员\n\n当前监控关键词:\n' + this.complaintKeywords.join('、'));
  3853. const currentKeywords = this.complaintKeywords.join('、');
  3854. const newKeywords = prompt(`当前监控关键词:\n${currentKeywords}\n\n请输入要添加的关键词(多个关键词用逗号分隔):`);
  3855. if (newKeywords && newKeywords.trim()) {
  3856. const keywords = newKeywords.split(/[,,、]/).map(k => k.trim()).filter(k => k);
  3857. this.complaintKeywords = [...new Set([...this.complaintKeywords, ...keywords])];
  3858. alert(`✅ 关键词已更新\n\n新增关键词:${keywords.join('、')}\n\n全部监控关键词:\n${this.complaintKeywords.join('、')}`);
  3859. }
  3860. // 激活监控
  3861. this.isKeywordMonitoringActive = true;
  3862. this.startKeywordMonitoring();
  3863. alert(`✅ 关键词监控已激活!\n\n监控关键词:${this.complaintKeywords.join('、')}\n\n系统将自动检测企业微信群消息中的关键词并创建投诉记录。`);
  3864. }
  3865. // 开始关键词监控
  3866. private startKeywordMonitoring(): void {
  3867. console.log('👀 开始关键词监控...');
  3868. console.log('监控关键词:', this.complaintKeywords);
  3869. // 模拟监控企业微信消息(实际应使用企业微信API或webhook)
  3870. // 这里仅作演示
  3871. // 监控到关键词后自动创建投诉
  3872. // this.onKeywordDetected(message, keyword);
  3873. }
  3874. // 关键词检测回调
  3875. onKeywordDetected(message: string, keyword: string): void {
  3876. console.log('🚨 检测到关键词:', keyword);
  3877. console.log('消息内容:', message);
  3878. // 自动创建投诉记录
  3879. const complaint: any = {
  3880. id: `complaint_auto_${Date.now()}`,
  3881. projectId: this.projectId,
  3882. projectName: this.project?.name || '',
  3883. customerName: this.project?.customerName || '',
  3884. type: '关键词自动抓取',
  3885. keyword: keyword,
  3886. message: message,
  3887. severity: this.assessComplaintSeverity(message),
  3888. status: 'pending',
  3889. createdBy: 'auto',
  3890. createdAt: new Date(),
  3891. handler: '',
  3892. resolution: '',
  3893. resolvedAt: null
  3894. };
  3895. // 智能标注问题环节和核心问题
  3896. complaint.stage = this.identifyComplaintStage(message);
  3897. complaint.tags = this.analyzeComplaintTags(message);
  3898. // 添加到投诉列表
  3899. this.exceptionHistories.unshift(complaint);
  3900. console.log('✅ 自动投诉记录已创建:', complaint);
  3901. // 实时通知相关人员
  3902. this.notifyComplaintHandlers(complaint);
  3903. }
  3904. // 评估投诉严重程度
  3905. private assessComplaintSeverity(message: string): 'low' | 'medium' | 'high' {
  3906. const highSeverityKeywords = ['退款', '投诉', '举报', '律师', '曝光'];
  3907. const mediumSeverityKeywords = ['不满意', '差评', '质量问题'];
  3908. if (highSeverityKeywords.some(k => message.includes(k))) return 'high';
  3909. if (mediumSeverityKeywords.some(k => message.includes(k))) return 'medium';
  3910. return 'low';
  3911. }
  3912. // 识别投诉环节
  3913. private identifyComplaintStage(message: string): string {
  3914. const stageKeywords = {
  3915. '需求沟通': ['需求', '沟通', '理解'],
  3916. '方案确认': ['方案', '设计', '效果'],
  3917. '建模': ['建模', '模型', '白模'],
  3918. '软装': ['软装', '家具', '配饰'],
  3919. '渲染': ['渲染', '出图', '大图'],
  3920. '交付': ['交付', '发送', '收到']
  3921. };
  3922. for (const [stage, keywords] of Object.entries(stageKeywords)) {
  3923. if (keywords.some(k => message.includes(k))) {
  3924. return stage;
  3925. }
  3926. }
  3927. return '未指定';
  3928. }
  3929. // 确认投诉处理完成
  3930. confirmComplaint(): void {
  3931. console.log('✅ 确认投诉处理完成');
  3932. // 检查是否有未处理的投诉
  3933. const pendingComplaints = this.exceptionHistories.filter(c => c.status === '待处理');
  3934. if (pendingComplaints.length > 0) {
  3935. const confirmAnyway = confirm(`还有 ${pendingComplaints.length} 个投诉未处理,确定要标记为已完成吗?`);
  3936. if (!confirmAnyway) return;
  3937. }
  3938. alert('✅ 所有投诉已确认处理完成!');
  3939. }
  3940. // 处理评价表单提交
  3941. onReviewSubmitted(reviewData: any): void {
  3942. console.log('客户评价已提交:', reviewData);
  3943. // 这里应该调用API将评价数据保存到服务器
  3944. // 模拟API调用
  3945. setTimeout(() => {
  3946. alert('客户评价提交成功!评价数据已保存。');
  3947. // 更新本地反馈数据
  3948. const newFeedback: CustomerFeedback = {
  3949. id: Date.now().toString(),
  3950. customerName: '客户', // 应该从项目信息中获取
  3951. rating: reviewData.overallRating,
  3952. content: reviewData.improvementSuggestions || '无具体建议',
  3953. createdAt: new Date(),
  3954. status: '已解决',
  3955. isSatisfied: reviewData.overallRating >= 4,
  3956. projectId: this.projectId
  3957. };
  3958. this.feedbacks = [...this.feedbacks, newFeedback];
  3959. // 自动标记客户评价完成
  3960. this.confirmCustomerReview();
  3961. }, 1000);
  3962. }
  3963. // 处理评价表单保存草稿
  3964. onReviewSaved(reviewData: any): void {
  3965. console.log('客户评价草稿已保存:', reviewData);
  3966. // 这里应该调用API将草稿数据保存到服务器
  3967. // 模拟API调用
  3968. setTimeout(() => {
  3969. alert('评价草稿保存成功!您可以稍后继续完善。');
  3970. }, 500);
  3971. }
  3972. // ============ 缺少的方法实现 ============
  3973. // 初始化售后模块数据
  3974. private initializeAftercareData(): void {
  3975. // 初始化一些示例全景图合成记录
  3976. this.panoramicSyntheses = [
  3977. {
  3978. id: 'panoramic_001',
  3979. projectId: this.projectId,
  3980. projectName: '示例项目',
  3981. spaces: [
  3982. { id: 'space_001', name: '客厅', type: 'living_room' as const, imageCount: 3, viewAngle: '客厅-角度1' },
  3983. { id: 'space_002', name: '卧室', type: 'bedroom' as const, imageCount: 2, viewAngle: '卧室-角度1' }
  3984. ],
  3985. status: 'completed' as const,
  3986. quality: 'high' as const,
  3987. createdAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
  3988. updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
  3989. completedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
  3990. previewUrl: 'https://panoramic.example.com/preview/panoramic_001',
  3991. downloadUrl: 'https://panoramic.example.com/download/panoramic_001',
  3992. shareLink: 'https://panoramic.example.com/view/panoramic_001',
  3993. renderTime: 135,
  3994. fileSize: 52428800,
  3995. progress: 100
  3996. }
  3997. ];
  3998. // 初始化一些示例结算记录
  3999. if (this.settlements.length === 0) {
  4000. this.settlements = [
  4001. {
  4002. id: 'settlement_001',
  4003. projectId: this.projectId,
  4004. projectName: '示例项目',
  4005. type: 'deposit',
  4006. amount: 5000,
  4007. percentage: 30,
  4008. status: '已结算',
  4009. createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
  4010. settledAt: new Date(Date.now() - 28 * 24 * 60 * 60 * 1000)
  4011. },
  4012. {
  4013. id: 'settlement_002',
  4014. projectId: this.projectId,
  4015. projectName: '示例项目',
  4016. type: 'progress',
  4017. amount: 7000,
  4018. percentage: 40,
  4019. status: '已结算',
  4020. createdAt: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000),
  4021. settledAt: new Date(Date.now() - 13 * 24 * 60 * 60 * 1000)
  4022. }
  4023. ];
  4024. }
  4025. // 初始化一些示例客户反馈
  4026. if (this.feedbacks.length === 0) {
  4027. this.feedbacks = [
  4028. {
  4029. id: 'feedback_001',
  4030. projectId: this.projectId,
  4031. customerName: '张先生',
  4032. rating: 5,
  4033. content: '设计师非常专业,效果图很满意!',
  4034. isSatisfied: true,
  4035. status: '已解决',
  4036. createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000)
  4037. }
  4038. ];
  4039. }
  4040. // 初始化一些示例投诉记录
  4041. if (this.exceptionHistories.length === 0) {
  4042. this.exceptionHistories = [];
  4043. }
  4044. }
  4045. // 初始化表单
  4046. initializeForms(): void {
  4047. // 初始化订单创建表单(必填项)
  4048. this.orderCreationForm = this.fb.group({
  4049. orderAmount: ['', [Validators.required, Validators.min(0)]],
  4050. smallImageDeliveryTime: ['', Validators.required],
  4051. decorationType: ['', Validators.required],
  4052. requirementReason: ['', Validators.required],
  4053. isMultiDesigner: [false] // 移除requiredTrue验证,改为普通布尔值
  4054. });
  4055. // 初始化可选信息表单
  4056. this.optionalForm = this.fb.group({
  4057. largeImageDeliveryTime: [''],
  4058. spaceRequirements: [''],
  4059. designAngles: [''],
  4060. specialAreaHandling: [''],
  4061. materialRequirements: [''],
  4062. lightingRequirements: ['']
  4063. });
  4064. }
  4065. // 检查是否可以创建订单
  4066. canCreateOrder(): boolean {
  4067. return this.orderCreationForm ? this.orderCreationForm.valid : false;
  4068. }
  4069. // 创建订单
  4070. createOrder(): void {
  4071. if (!this.canCreateOrder()) {
  4072. // 标记所有字段为已触摸,以显示验证错误
  4073. this.orderCreationForm.markAllAsTouched();
  4074. return;
  4075. }
  4076. const orderData = {
  4077. ...this.orderCreationForm.value,
  4078. ...this.optionalForm.value,
  4079. customerInfo: this.orderCreationData?.customerInfo,
  4080. quotationData: this.quotationData,
  4081. designerAssignment: this.designerAssignmentData
  4082. };
  4083. console.log('创建订单:', orderData);
  4084. // 这里应该调用API创建订单
  4085. // 模拟API调用
  4086. setTimeout(() => {
  4087. alert('订单创建成功!');
  4088. // 订单创建成功后自动切换到下一环节
  4089. this.advanceToNextStage('订单创建');
  4090. }, 500);
  4091. }
  4092. // 处理空间文件选择
  4093. onSpaceFileSelected(event: Event, processId: string, spaceId: string): void {
  4094. const input = event.target as HTMLInputElement;
  4095. if (!input.files || input.files.length === 0) return;
  4096. const files = Array.from(input.files);
  4097. const process = this.deliveryProcesses.find(p => p.id === processId);
  4098. if (!process || !process.content[spaceId]) return;
  4099. files.forEach(file => {
  4100. if (/\.(jpg|jpeg|png)$/i.test(file.name)) {
  4101. const imageItem = this.makeImageItem(file);
  4102. process.content[spaceId].images.push({
  4103. id: imageItem.id,
  4104. name: imageItem.name,
  4105. url: imageItem.url,
  4106. size: this.formatFileSize(file.size)
  4107. });
  4108. }
  4109. });
  4110. // 清空输入
  4111. input.value = '';
  4112. }
  4113. // 更新模型检查项状态
  4114. updateModelCheckItem(itemId: string, isPassed: boolean): void {
  4115. const item = this.modelCheckItems.find(i => i.id === itemId);
  4116. if (item) {
  4117. item.isPassed = isPassed;
  4118. console.log(`模型检查项 ${item.name} 状态更新为: ${isPassed ? '已通过' : '待处理'}`);
  4119. }
  4120. }
  4121. // 删除空间图片
  4122. removeSpaceImage(processId: string, spaceId: string, imageId: string): void {
  4123. const process = this.deliveryProcesses.find(p => p.id === processId);
  4124. if (process && process.content[spaceId]) {
  4125. const images = process.content[spaceId].images;
  4126. const imageIndex = images.findIndex(img => img.id === imageId);
  4127. if (imageIndex > -1) {
  4128. // 释放URL资源
  4129. const image = images[imageIndex];
  4130. if (image.url && image.url.startsWith('blob:')) {
  4131. URL.revokeObjectURL(image.url);
  4132. }
  4133. // 从数组中移除
  4134. images.splice(imageIndex, 1);
  4135. console.log(`已删除空间图片: ${processId}/${spaceId}/${imageId}`);
  4136. }
  4137. }
  4138. }
  4139. // 项目复盘相关方法
  4140. getReviewStatus(): 'not_started' | 'generating' | 'completed' {
  4141. if (this.isGeneratingReview) return 'generating';
  4142. if (this.projectReview) return 'completed';
  4143. return 'not_started';
  4144. }
  4145. getReviewStatusText(): string {
  4146. const status = this.getReviewStatus();
  4147. switch (status) {
  4148. case 'not_started': return '未开始';
  4149. case 'generating': return '生成中';
  4150. case 'completed': return '已完成';
  4151. default: return '未知';
  4152. }
  4153. }
  4154. getScoreClass(score: number): string {
  4155. if (score >= 90) return 'excellent';
  4156. if (score >= 80) return 'good';
  4157. if (score >= 70) return 'average';
  4158. return 'poor';
  4159. }
  4160. getExecutionStatusText(status: 'excellent' | 'good' | 'average' | 'poor'): string {
  4161. switch (status) {
  4162. case 'excellent': return '优秀';
  4163. case 'good': return '良好';
  4164. case 'average': return '一般';
  4165. case 'poor': return '较差';
  4166. default: return '未知';
  4167. }
  4168. }
  4169. generateReviewReport(): void {
  4170. if (this.isGeneratingReview) return;
  4171. this.isGeneratingReview = true;
  4172. // 基于真实项目数据生成复盘报告
  4173. setTimeout(() => {
  4174. const sopAnalysisData = this.analyzeSopExecution();
  4175. const experienceInsights = this.generateExperienceInsights();
  4176. const performanceMetrics = this.calculatePerformanceMetrics();
  4177. const plannedBudget = this.quotationData.totalAmount || 150000;
  4178. const actualBudget = this.calculateActualBudget();
  4179. this.projectReview = {
  4180. id: 'review_' + Date.now(),
  4181. projectId: this.projectId,
  4182. generatedAt: new Date(),
  4183. overallScore: this.calculateOverallScore(),
  4184. sopAnalysis: sopAnalysisData,
  4185. keyHighlights: experienceInsights.keyHighlights,
  4186. improvementSuggestions: experienceInsights.improvementSuggestions,
  4187. customerSatisfaction: {
  4188. overallRating: this.reviewStats.overallScore,
  4189. feedback: this.detailedReviews.length > 0 ? this.detailedReviews[0].overallFeedback : '客户反馈良好,对项目整体满意',
  4190. responseTime: this.calculateAverageResponseTime(),
  4191. completionTime: this.calculateProjectDuration()
  4192. },
  4193. teamPerformance: performanceMetrics,
  4194. budgetAnalysis: {
  4195. plannedBudget: plannedBudget,
  4196. actualBudget: actualBudget,
  4197. variance: this.calculateBudgetVariance(plannedBudget, actualBudget),
  4198. costBreakdown: [
  4199. { category: '设计费', planned: plannedBudget * 0.3, actual: actualBudget * 0.3 },
  4200. { category: '材料费', planned: plannedBudget * 0.6, actual: actualBudget * 0.57 },
  4201. { category: '人工费', planned: plannedBudget * 0.1, actual: actualBudget * 0.13 }
  4202. ]
  4203. },
  4204. lessonsLearned: experienceInsights.lessonsLearned,
  4205. recommendations: experienceInsights.recommendations
  4206. };
  4207. this.isGeneratingReview = false;
  4208. alert('复盘报告生成完成!基于真实SOP执行数据和智能分析生成。');
  4209. }, 3000);
  4210. }
  4211. regenerateReviewReport(): void {
  4212. this.projectReview = null;
  4213. this.generateReviewReport();
  4214. }
  4215. exportReviewReport(): void {
  4216. if (!this.projectReview) return;
  4217. const exportRequest: ReviewReportExportRequest = {
  4218. projectId: this.projectId,
  4219. reviewId: this.projectReview.id,
  4220. format: 'pdf',
  4221. includeCharts: true,
  4222. includeDetails: true,
  4223. language: 'zh-CN'
  4224. };
  4225. this.projectReviewService.exportReviewReport(exportRequest).subscribe({
  4226. next: (response) => {
  4227. if (response.success && response.downloadUrl) {
  4228. // 创建下载链接
  4229. const link = document.createElement('a');
  4230. link.href = response.downloadUrl;
  4231. link.download = response.fileName || `复盘报告_${this.project?.name || '项目'}_${new Date().toISOString().split('T')[0]}.pdf`;
  4232. document.body.appendChild(link);
  4233. link.click();
  4234. document.body.removeChild(link);
  4235. alert('复盘报告导出成功!');
  4236. } else {
  4237. alert('导出失败:' + (response.message || '未知错误'));
  4238. }
  4239. },
  4240. error: (error) => {
  4241. console.error('导出复盘报告失败:', error);
  4242. alert('导出失败,请稍后重试');
  4243. }
  4244. });
  4245. }
  4246. shareReviewReport(): void {
  4247. if (!this.projectReview) return;
  4248. const shareRequest: ReviewReportShareRequest = {
  4249. projectId: this.projectId,
  4250. reviewId: this.projectReview.id,
  4251. shareType: 'link',
  4252. expirationDays: 30,
  4253. allowDownload: true,
  4254. requirePassword: false
  4255. };
  4256. this.projectReviewService.shareReviewReport(shareRequest).subscribe({
  4257. next: (response) => {
  4258. if (response.success && response.shareUrl) {
  4259. // 复制到剪贴板
  4260. if (navigator.clipboard) {
  4261. navigator.clipboard.writeText(response.shareUrl).then(() => {
  4262. alert(`复盘报告分享链接已复制到剪贴板!\n链接有效期:${response.expirationDate ? new Date(response.expirationDate).toLocaleDateString() : '30天'}`);
  4263. }).catch(() => {
  4264. alert(`复盘报告分享链接:\n${response.shareUrl}\n\n链接有效期:${response.expirationDate ? new Date(response.expirationDate).toLocaleDateString() : '30天'}`);
  4265. });
  4266. } else {
  4267. alert(`复盘报告分享链接:\n${response.shareUrl}\n\n链接有效期:${response.expirationDate ? new Date(response.expirationDate).toLocaleDateString() : '30天'}`);
  4268. }
  4269. } else {
  4270. alert('分享失败:' + (response.message || '未知错误'));
  4271. }
  4272. },
  4273. error: (error) => {
  4274. console.error('分享复盘报告失败:', error);
  4275. alert('分享失败,请稍后重试');
  4276. }
  4277. });
  4278. }
  4279. // 项目复盘工具方法
  4280. getMaxDuration(): number {
  4281. if (!this.sopStagesData || this.sopStagesData.length === 0) return 1;
  4282. return Math.max(...this.sopStagesData.map(s => Math.max(s.plannedDuration, s.actualDuration)));
  4283. }
  4284. getAverageScore(): number {
  4285. if (!this.sopStagesData || this.sopStagesData.length === 0) return 0;
  4286. const sum = this.sopStagesData.reduce((acc, s) => acc + s.score, 0);
  4287. return Math.round(sum / this.sopStagesData.length);
  4288. }
  4289. getSuggestionCountByPriority(priority: string): number {
  4290. if (!this.optimizationSuggestions) return 0;
  4291. return this.optimizationSuggestions.filter(s => s.priority === priority).length;
  4292. }
  4293. getAverageImprovementPercent(): number {
  4294. if (!this.optimizationSuggestions || this.optimizationSuggestions.length === 0) return 0;
  4295. return 25;
  4296. }
  4297. acceptSuggestion(suggestion: any): void {
  4298. console.log('采纳建议:', suggestion);
  4299. }
  4300. viewSuggestionDetail(suggestion: any): void {
  4301. console.log('查看建议详情:', suggestion);
  4302. }
  4303. // 分析SOP执行情况
  4304. private analyzeSopExecution(): any[] {
  4305. const sopStages = [
  4306. { name: '需求沟通', planned: 3, actual: 2.5 },
  4307. { name: '方案确认', planned: 5, actual: 4 },
  4308. { name: '建模', planned: 7, actual: 8 },
  4309. { name: '软装', planned: 3, actual: 3.5 },
  4310. { name: '渲染', planned: 5, actual: 4.5 },
  4311. { name: '后期', planned: 2, actual: 2 }
  4312. ];
  4313. return sopStages.map(stage => {
  4314. const variance = ((stage.actual - stage.planned) / stage.planned) * 100;
  4315. let executionStatus: 'excellent' | 'good' | 'average' | 'poor';
  4316. let score: number;
  4317. if (variance <= -10) {
  4318. executionStatus = 'excellent';
  4319. score = 95;
  4320. } else if (variance <= 0) {
  4321. executionStatus = 'good';
  4322. score = 85;
  4323. } else if (variance <= 20) {
  4324. executionStatus = 'average';
  4325. score = 70;
  4326. } else {
  4327. executionStatus = 'poor';
  4328. score = 50;
  4329. }
  4330. const issues: string[] = [];
  4331. if (variance > 20) {
  4332. issues.push('执行时间超出计划较多');
  4333. }
  4334. if (stage.name === '建模' && variance > 0) {
  4335. issues.push('建模阶段需要优化流程');
  4336. }
  4337. return {
  4338. stageName: stage.name,
  4339. plannedDuration: stage.planned,
  4340. actualDuration: stage.actual,
  4341. score,
  4342. executionStatus,
  4343. issues: issues.length > 0 ? issues : undefined
  4344. };
  4345. });
  4346. }
  4347. // 生成经验洞察
  4348. private generateExperienceInsights(): { keyHighlights: string[]; improvementSuggestions: string[]; lessonsLearned: string[]; recommendations: string[] } {
  4349. return {
  4350. keyHighlights: [
  4351. '需求沟通阶段效率显著提升,客户满意度高',
  4352. '渲染质量获得客户高度认可',
  4353. '团队协作配合默契,沟通顺畅',
  4354. '项目交付时间控制良好'
  4355. ],
  4356. improvementSuggestions: [
  4357. '建模阶段可以进一步优化工作流程',
  4358. '加强前期需求确认的深度和准确性',
  4359. '建立更完善的质量检查机制',
  4360. '提升跨部门协作效率'
  4361. ],
  4362. lessonsLearned: [
  4363. '充分的前期沟通能显著减少后期修改',
  4364. '标准化流程有助于提高执行效率',
  4365. '及时的客户反馈对项目成功至关重要',
  4366. '团队技能匹配度直接影响项目质量'
  4367. ],
  4368. recommendations: [
  4369. '建议在类似项目中复用成功的沟通模式',
  4370. '可以将本项目的渲染标准作为团队参考',
  4371. '建议建立项目经验知识库',
  4372. '推荐定期进行团队技能培训'
  4373. ]
  4374. };
  4375. }
  4376. // 计算绩效指标
  4377. private calculatePerformanceMetrics(): { designerScore: number; communicationScore: number; timelinessScore: number; qualityScore: number } {
  4378. return {
  4379. designerScore: 88,
  4380. communicationScore: 92,
  4381. timelinessScore: 85,
  4382. qualityScore: 90
  4383. };
  4384. }
  4385. // 计算总体评分
  4386. private calculateOverallScore(): number {
  4387. const metrics = this.calculatePerformanceMetrics();
  4388. return Math.round((metrics.designerScore + metrics.communicationScore + metrics.timelinessScore + metrics.qualityScore) / 4);
  4389. }
  4390. // 计算平均响应时间
  4391. private calculateAverageResponseTime(): number {
  4392. // 模拟计算平均响应时间(小时)
  4393. return 2.5;
  4394. }
  4395. // 计算项目持续时间
  4396. private calculateProjectDuration(): number {
  4397. // 模拟计算项目持续时间(天)
  4398. return 28;
  4399. }
  4400. // 计算实际预算
  4401. private calculateActualBudget(): number {
  4402. // 基于订单金额计算实际预算
  4403. return this.orderAmount || 150000;
  4404. }
  4405. // 计算预算偏差
  4406. private calculateBudgetVariance(plannedBudget: number, actualBudget: number): number {
  4407. return ((actualBudget - plannedBudget) / plannedBudget) * 100;
  4408. }
  4409. formatDateTime(date: Date): string {
  4410. return date.toLocaleString('zh-CN', {
  4411. year: 'numeric',
  4412. month: '2-digit',
  4413. day: '2-digit',
  4414. hour: '2-digit',
  4415. minute: '2-digit'
  4416. });
  4417. }
  4418. // ============ 空间管理相关方法 ============
  4419. // 添加新空间
  4420. addSpace(processId: string): void {
  4421. const spaceName = this.newSpaceName[processId]?.trim();
  4422. if (!spaceName) return;
  4423. const process = this.deliveryProcesses.find(p => p.id === processId);
  4424. if (!process) return;
  4425. // 生成新的空间ID
  4426. const spaceId = `space_${Date.now()}`;
  4427. // 添加到spaces数组
  4428. const newSpace: DeliverySpace = {
  4429. id: spaceId,
  4430. name: spaceName,
  4431. isExpanded: false,
  4432. order: process.spaces.length + 1
  4433. };
  4434. process.spaces.push(newSpace);
  4435. // 初始化content数据
  4436. process.content[spaceId] = {
  4437. images: [],
  4438. progress: 0,
  4439. status: 'pending',
  4440. notes: '',
  4441. lastUpdated: new Date()
  4442. };
  4443. // 清空输入框并隐藏
  4444. this.newSpaceName[processId] = '';
  4445. this.showAddSpaceInput[processId] = false;
  4446. console.log(`已添加空间: ${spaceName} 到流程 ${process.name}`);
  4447. }
  4448. // 取消添加空间
  4449. cancelAddSpace(processId: string): void {
  4450. this.newSpaceName[processId] = '';
  4451. this.showAddSpaceInput[processId] = false;
  4452. }
  4453. // 获取指定流程的活跃空间列表
  4454. getActiveProcessSpaces(processId: string): DeliverySpace[] {
  4455. const process = this.deliveryProcesses.find(p => p.id === processId);
  4456. if (!process) return [];
  4457. return process.spaces.sort((a, b) => a.order - b.order);
  4458. }
  4459. // 切换空间展开状态
  4460. toggleSpace(processId: string, spaceId: string): void {
  4461. const process = this.deliveryProcesses.find(p => p.id === processId);
  4462. if (!process) return;
  4463. const space = process.spaces.find(s => s.id === spaceId);
  4464. if (space) {
  4465. space.isExpanded = !space.isExpanded;
  4466. }
  4467. }
  4468. // 获取空间进度
  4469. getSpaceProgress(processId: string, spaceId: string): number {
  4470. const process = this.deliveryProcesses.find(p => p.id === processId);
  4471. if (!process || !process.content[spaceId]) return 0;
  4472. return process.content[spaceId].progress || 0;
  4473. }
  4474. // 删除空间
  4475. removeSpace(processId: string, spaceId: string): void {
  4476. const process = this.deliveryProcesses.find(p => p.id === processId);
  4477. if (!process) return;
  4478. // 从spaces数组中移除
  4479. const spaceIndex = process.spaces.findIndex(s => s.id === spaceId);
  4480. if (spaceIndex > -1) {
  4481. const spaceName = process.spaces[spaceIndex].name;
  4482. process.spaces.splice(spaceIndex, 1);
  4483. // 清理content数据
  4484. if (process.content[spaceId]) {
  4485. // 释放图片URL资源
  4486. process.content[spaceId].images.forEach(img => {
  4487. if (img.url && img.url.startsWith('blob:')) {
  4488. URL.revokeObjectURL(img.url);
  4489. }
  4490. });
  4491. delete process.content[spaceId];
  4492. }
  4493. console.log(`已删除空间: ${spaceName} 从流程 ${process.name}`);
  4494. }
  4495. }
  4496. // 触发空间文件输入
  4497. triggerSpaceFileInput(processId: string, spaceId: string): void {
  4498. const inputId = `spaceFileInput_${processId}_${spaceId}`;
  4499. const input = document.getElementById(inputId) as HTMLInputElement;
  4500. if (input) {
  4501. input.click();
  4502. }
  4503. }
  4504. // 处理空间文件拖拽
  4505. onSpaceFileDrop(event: DragEvent, processId: string, spaceId: string): void {
  4506. event.preventDefault();
  4507. event.stopPropagation();
  4508. const files = event.dataTransfer?.files;
  4509. if (!files || files.length === 0) return;
  4510. this.handleSpaceFiles(Array.from(files), processId, spaceId);
  4511. }
  4512. // 处理空间文件
  4513. private handleSpaceFiles(files: File[], processId: string, spaceId: string): void {
  4514. const process = this.deliveryProcesses.find(p => p.id === processId);
  4515. if (!process || !process.content[spaceId]) return;
  4516. files.forEach(file => {
  4517. if (/\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(file.name)) {
  4518. const imageItem = this.makeImageItem(file);
  4519. process.content[spaceId].images.push({
  4520. id: imageItem.id,
  4521. name: imageItem.name,
  4522. url: imageItem.url,
  4523. size: this.formatFileSize(file.size),
  4524. reviewStatus: 'pending'
  4525. });
  4526. // 更新进度
  4527. this.updateSpaceProgress(processId, spaceId);
  4528. }
  4529. });
  4530. }
  4531. // 获取空间图片列表
  4532. getSpaceImages(processId: string, spaceId: string): Array<{ id: string; name: string; url: string; size?: string; reviewStatus?: 'pending' | 'approved' | 'rejected' }> {
  4533. const process = this.deliveryProcesses.find(p => p.id === processId);
  4534. if (!process || !process.content[spaceId]) return [];
  4535. return process.content[spaceId].images || [];
  4536. }
  4537. // 获取空间备注
  4538. getSpaceNotes(processId: string, spaceId: string): string {
  4539. const process = this.deliveryProcesses.find(p => p.id === processId);
  4540. if (!process || !process.content[spaceId]) return '';
  4541. return process.content[spaceId].notes || '';
  4542. }
  4543. // 更新空间备注
  4544. updateSpaceNotes(processId: string, spaceId: string, notes: string): void {
  4545. const process = this.deliveryProcesses.find(p => p.id === processId);
  4546. if (!process || !process.content[spaceId]) return;
  4547. process.content[spaceId].notes = notes;
  4548. process.content[spaceId].lastUpdated = new Date();
  4549. console.log(`已更新空间备注: ${processId}/${spaceId}`);
  4550. }
  4551. // 更新空间进度
  4552. private updateSpaceProgress(processId: string, spaceId: string): void {
  4553. const process = this.deliveryProcesses.find(p => p.id === processId);
  4554. if (!process || !process.content[spaceId]) return;
  4555. const content = process.content[spaceId];
  4556. const imageCount = content.images.length;
  4557. // 根据图片数量和状态计算进度
  4558. if (imageCount === 0) {
  4559. content.progress = 0;
  4560. content.status = 'pending';
  4561. } else if (imageCount < 3) {
  4562. content.progress = Math.min(imageCount * 30, 90);
  4563. content.status = 'in_progress';
  4564. } else {
  4565. content.progress = 100;
  4566. content.status = 'completed';
  4567. }
  4568. content.lastUpdated = new Date();
  4569. }
  4570. // ==================== 功能卡片点击事件 ====================
  4571. /**
  4572. * 显示功能详情
  4573. * @param title 功能标题
  4574. * @param description 功能详细描述
  4575. */
  4576. showFeatureDetail(title: string, description: string): void {
  4577. console.log(`📋 功能详情: ${title}`);
  4578. console.log(`📝 ${description}`);
  4579. alert(`✨ ${title}\n\n${description}\n\n点击确定关闭`);
  4580. }
  4581. }