project-detail.ts 208 KB

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