project-detail.ts 192 KB

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