| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773 |
- <template>
- <div class="chat-container" @click="handleContainerClick">
- <!-- 最左侧边栏 -->
- <Sidebar />
- <!-- 中间历史记录区域 -->
- <div class="history-sidebar">
- <div class="new-chat-container">
- <button class="new-chat-btn-full" @click="createNewChat" :disabled="isSending || hasTypingMessage">
- <span class="plus-icon">+</span>
- 新建任务
- </button>
- </div>
- <div class="history-header">
- <span class="section-title">历史记录</span>
- </div>
-
- <div class="history-list">
- <!-- 历史记录加载状态 -->
- <div v-if="isLoadingHistory" class="history-loading">
- <div class="loading-spinner"></div>
- <div class="loading-text">正在加载历史记录...</div>
- </div>
-
- <!-- 有历史记录时显示 -->
- <div
- v-else-if="historyTotal > 0"
- v-for="(item, index) in historyData"
- :key="index"
- :class="['history-item', { active: item.isActive }]"
- @click="item.isActive ? null : ((isSending || hasTypingMessage) ? null : handleHistoryItem(item))"
- :style="{
- cursor: item.isActive ? 'default' : ((isSending || hasTypingMessage) ? 'not-allowed' : 'pointer')
- }"
- >
- <div class="history-content">
- <div class="history-title">{{ item.title }}</div>
- <div class="history-time">{{ item.time }}</div>
- </div>
- <div
- class="delete-btn"
- @click.stop="deleteHistoryItem(item, index)"
- :class="{ 'always-visible': item.isActive }"
- >
- <img src="/src/assets/AIWriting/8.png" alt="删除" class="delete-icon" />
- </div>
- </div>
-
- <!-- 无历史记录时显示空状态 -->
- <div v-else class="empty-history">
- <img :src="emptyIcon" alt="暂无数据" class="empty-icon">
- <div class="empty-text">暂无数据</div>
- </div>
- </div>
- </div>
- <div class="chat-main-area">
- <!-- 右侧AI问答区域 -->
- <div class="main-chat" :class="{ 'sidebar-open': webSearchSidebarVisible }">
- <!-- 聊天头部 -->
- <div class="chat-header" v-if="currentMode !== 'exam-workshop' && currentQuestion">
- <div class="question-title-card">
- <h2>{{ currentQuestion }}</h2>
- </div>
- </div>
- <!-- 考试工坊内容区域 -->
- <div v-if="currentMode === 'exam-workshop'" class="exam-workshop-wrapper" style="height: 100%; flex: 1;">
- <ExamWorkshop :hideSidebar="true" @return-to-ai="setMode('ai-qa')" />
- </div>
- <!-- 聊天内容区域 -->
- <div v-else class="chat-content">
- <!-- 初始状态:AI助手介绍和功能卡片 -->
- <div v-if="!showChat" class="initial-content">
- <!-- AI助手介绍 -->
- <div class="ai-intro">
- <div class="ai-avatar">
- <img :src="aiAvatarIcon" alt="AI头像" class="ai-avatar-img">
- </div>
- <div class="ai-greeting">
- <h3>我是蜀道安全管理AI智能助手,您的得力帮手</h3>
- <p>我可以帮您处理这些事情</p>
- </div>
- </div>
- <!-- 功能卡片 -->
- <div class="function-cards">
- <div
- v-for="(card, index) in functionCards"
- :key="card.id || index"
- class="function-card"
- @click="handleFunctionCard(card.function_title)"
- >
- <div class="card-header">
- <div class="card-icon">
- <img :src="getFunctionCardIcon(card.function_title)" :alt="card.function_title" class="card-icon-img">
- </div>
- <h4>{{ card.function_title }}</h4>
- </div>
- <div class="card-description">
- <p>{{ card.function_content }}</p>
- </div>
- </div>
-
- <!-- 如果没有数据,显示默认卡片 -->
- <template v-if="functionCards.length === 0">
- <div
- v-for="(card, index) in defaultFunctionCards"
- :key="`default-card-${index}`"
- class="function-card"
- @click="handleFunctionCard(card.title)"
- >
- <div class="card-header">
- <div class="card-icon">
- <img :src="card.icon" :alt="card.title" class="card-icon-img">
- </div>
- <h4>{{ card.title }}</h4>
- </div>
- <div class="card-description">
- <p>{{ card.description }}</p>
- </div>
- </div>
- </template>
- </div>
- </div>
- <!-- 聊天对话区域 -->
- <div v-else class="chat-messages">
- <div
- v-for="(message, index) in chatMessages"
- :key="index"
- :class="['message-item', message.type]"
- >
- <!-- 用户消息 -->
- <div v-if="message.type === 'user'" class="user-message">
- <div class="message-content">
- <!-- 文件显示 -->
- <div v-if="message.file" class="message-file">
- <div class="file-display">
- <div class="file-icon">
- <img v-if="message.file.icon !== '📎'" :src="message.file.icon" alt="文件图标" class="file-icon-img">
- <span v-else>{{ message.file.icon }}</span>
- </div>
- <div class="file-details">
- <div class="file-name">{{ message.file.name }}</div>
- <div class="file-size">{{ formatFileSize(message.file.size) }}</div>
- </div>
- </div>
- </div>
- <!-- 文本内容 -->
- <div v-if="message.content" class="message-text">{{ message.content }}</div>
- </div>
- <div class="message-actions">
- <button class="action-btn copy-btn" @click="copyUserMessage(message)">
- <img :src="copyIcon" alt="复制" class="action-icon">
- 复制
- </button>
- <button class="action-btn edit-btn" @click="editUserMessage(message)">
- <img :src="editIcon" alt="编辑" class="action-icon">
- 编辑
- </button>
- </div>
- </div>
-
- <!-- AI消息 -->
- <div v-else-if="message.type === 'ai'" class="ai-message">
- <!-- 网络搜索胶囊 - 在输出框上方 -->
- <div v-if="message.webSearchRaw && message.webSearchRaw.total > 0" class="web-search-capsule-outer">
- <WebSearchCapsule
- :total="message.webSearchRaw.total"
- :results="message.webSearchRaw.results"
- :isExpanded="webSearchSidebarVisible"
- @toggle="handleWebSearchToggle(index)"
- />
- </div>
-
- <div class="ai-message-main">
- <div class="ai-avatar-small">
- <img :src="aiAvatarIcon" alt="AI" class="ai-icon">
- </div>
- <div class="message-content" :data-message-index="index" :ref="el => messageContentRefs[index] = el">
- <!-- 完整的AI回复内容 -->
- <div class="ai-response-content">
- <!-- 状态统计卡片 - 优先显示(不等待后端数据) -->
- <div v-if="message.showStats"
- class="files-stats-white"
- :class="{ 'sticky': messageScrollStates[index]?.isSticky && messageScrollStates[index]?.initialized && !messageScrollStates[index]?.isInitializing }"
- :style="(messageScrollStates[index]?.isSticky && messageScrollStates[index]?.initialized && !messageScrollStates[index]?.isInitializing && messageScrollStates[index]?.initialLeft > 0 && messageScrollStates[index]?.initialWidth > 0) ? {
- position: 'fixed',
- top: '56px',
- left: messageScrollStates[index].initialLeft + 'px',
- width: messageScrollStates[index].initialWidth + 'px',
- zIndex: 999
- } : {}"
- :data-message-index="index">
- <div class="stats-left">
- <StatusAvatar
- :status="getAvatarStatus(message.currentStatus, message.progress)"
- :size="36"
- class="stats-avatar"
- />
- <span v-html="message.statusMessage"></span>
- </div>
-
- <!-- 进度条胶囊 - 在白色卡片内 -->
- <div v-if="message.progress < 100" class="progress-capsule-inline">
- <div class="progress-bar-mini">
- <div class="progress-fill" :style="{ width: message.progress + '%' }"></div>
- <div class="progress-dot" :style="{ left: message.progress + '%' }"></div>
- </div>
- <span class="progress-percentage">{{ message.progress }}%</span>
- </div>
-
- <div v-if="message.progress === 100 && message.reports && message.reports.length > 0" class="stats-right">
- <ExportButton
- :reports="message.reports.filter(r => r.status === 'completed' && r.type !== 'category_title')"
- :disabled="false"
- :title="exportTitle"
- />
- </div>
- </div>
-
- <!-- 问题总结 -->
- <div v-if="message.summary" class="question-summary">
- <StreamMarkdown :content="message.summary" :streaming="false" />
- </div>
-
- <!-- 报告生成中的Loading动画 - 当还没有报告时显示 -->
- <div v-if="message.isTyping && (!message.reports || message.reports.length === 0) && message.progress < 100" class="report-loading">
- <span class="loading-text">AI正在思考中...</span>
- <div class="thinking-animation">
- <span class="dot"></span>
- <span class="dot"></span>
- <span class="dot"></span>
- </div>
- </div>
-
- <!-- 报告列表 -->
- <div v-if="message.reports && message.reports.length > 0" class="reports-list">
- <template v-for="(report, rIndex) in message.reports" :key="`${report.source_file}-${report.file_index}-${rIndex}`">
- <!-- 类别标题 -->
- <CategoryTitle
- v-if="report.type === 'category_title'"
- :category="report.category"
- :number="report.number"
- :count="report.count"
- @toggle="(data) => handleCategoryToggle(index, data)"
- />
- <!-- 文件报告 -->
- <FileReportCard
- v-else-if="!report.type || report.type !== 'category_title'"
- v-show="isCategoryExpanded(index, report.metadata?._displayCategory || report.metadata?.primary_category)"
- :report="report"
- @preview-file="handleFilePreview"
- />
- </template>
-
- <!-- 分类下的Loading动画 - 当有分类但还在等待报告时 -->
- <div v-if="message.isTyping && message.progress < 100 && hasOnlyCategoryTitles(message.reports)" class="report-loading">
- <span class="loading-text">AI正在思考中...</span>
- <div class="thinking-animation">
- <span class="dot"></span>
- <span class="dot"></span>
- <span class="dot"></span>
- </div>
- </div>
- </div>
-
- <!-- 网络搜索总结 -->
- <div v-if="message.hasWebSearchResults && message.webSearchSummary">
- <WebSearchSummary :summary="message.webSearchSummary" />
- </div>
-
- <!-- 安全培训文档卡片 -->
- <div v-if="message.isDocument" class="safety-doc-card" @click="handleSafetyDocClick(message)">
- <div class="doc-icon-wrapper">
- <img src="../assets/Chat/26.png" alt="文档" class="doc-icon">
- </div>
- <div class="doc-info">
- <div class="doc-title">{{ currentQuestion || '安全培训文档' }}</div>
- <div class="doc-time">刚刚生成</div>
- </div>
- <div class="doc-action">
- 查看详情 >
- </div>
- </div>
- <!-- AI写作:状态文字 + 文件卡片 -->
- <div v-if="message.isAIWriting" class="ai-writing-block">
- <div class="ai-writing-status-text">
- {{ message.aiWritingStatusText || 'AI智能助手正在为您输出...' }}
- </div>
- <div class="ai-writing-file-card" @click="openAIWritingSidebar(message)">
- <div class="file-card-icon">
- <span class="word-icon">W</span>
- </div>
- <div class="file-card-info">
- <div class="file-card-title">{{ message.aiWritingTitle || currentQuestion || 'AI写作文档' }}</div>
- <div class="file-card-time">创建于 {{ formatTime(message.timestamp) }}</div>
- </div>
- </div>
- </div>
- <!-- 原有的AI文本内容(如果没有报告数据时显示) -->
- <div v-if="!message.reports || message.reports.length === 0" class="ai-text">
- <div v-if="message.displayContent && message.displayContent.length > 0 && !message.isDocument" class="ai-markdown-content">
- <div v-html="message.displayContent"></div>
- </div>
- </div>
- </div>
-
- <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary)" class="divider"></div>
- <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary)" class="message-actions">
- <div class="left-actions">
- <button class="action-btn copy-btn" @click="copyAIMessage(message)">
- <img :src="copyIcon" alt="复制" class="action-icon">
- 复制
- </button>
- <button class="action-btn regenerate-btn" @click="regenerateResponse(index)" :disabled="isSending || hasTypingMessage">
- <img :src="regenerateIcon" alt="重新生成" class="action-icon">
- 重新生成
- </button>
- <!-- 删除按钮 -->
- <button class="action-btn delete-btn" @click="handleDeleteClick(index)">
- <img src="../assets/AIWriting/8.png" alt="删除" class="action-icon">
- 删除
- </button>
- <button class="action-btn voice-btn" @click="handleVoiceRead(message)" :class="{ speaking: isSpeaking(message.id) }">
- <img :src="voiceIcon" alt="语音朗读" class="action-icon">
- {{ isSpeaking(message.id) ? '停止朗读' : '语音朗读' }}
- </button>
- </div>
- <div class="right-actions">
- <button
- class="action-btn thumbs-up-btn"
- :class="{ active: message.userFeedback === 'like' }"
- @click="handleThumbsUp(message)"
- :title="message.userFeedback === 'like' ? '取消点赞' : '点赞'"
- >
- <img :src="likeIcon" alt="点赞" class="action-icon">
- </button>
- <button
- class="action-btn thumbs-down-btn"
- :class="{ active: message.userFeedback === 'dislike' }"
- @click="handleThumbsDown(message)"
- :title="message.userFeedback === 'dislike' ? '取消点踩' : '点踩'"
- >
- <img :src="dislikeIcon" alt="踩" class="action-icon">
- </button>
- </div>
- </div>
- </div>
- </div>
-
- <!-- 搜索来源(仅在没有联网搜索结果时显示) -->
- <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary) && message.searchSources && message.searchSources.length > 0 && !onlineSearchResults[message.id]" class="search-sources">
- <div class="search-sources-header" @click="toggleSearchSources(message.id)">
- <span>基于{{ message.searchSources?.length || 0 }}个搜索来源</span>
- <div class="expand-icon" :class="{ expanded: expandedSearchSources[message.id] }">
- <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
- <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
- </svg>
- </div>
- </div>
- <div v-show="expandedSearchSources[message.id]" class="search-sources-content">
- <div class="sources-section">
- <!-- <div class="section-header">
- <div class="section-icon">🔍</div>
- <span class="section-title">找到{{ message.searchSources?.length || 0 }}个搜索来源</span>
- </div> -->
- <div class="sources-grid">
- <div class="source-card" v-for="(source, index) in (message.searchSources || [])" :key="index" @click="openSearchSource(source.url)">
- <div class="source-title">{{ source.title }}</div>
- <div class="source-description">{{ source.content }}</div>
- <div class="source-badge">{{ index + 1 }}</div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- 推荐问题Loading -->
- <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary) && isGettingRelatedQuestions && (relatedQuestionsMessageId === message.id || relatedQuestionsMessageId === message.ai_message_id) && aiRelatedQuestions.length === 0" class="related-questions-loading">
- <div class="thinking-animation">
- <span class="dot"></span>
- <span class="dot"></span>
- <span class="dot"></span>
- </div>
- </div>
-
- <!-- 提问联想 -->
- <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary) && (relatedQuestionsMessageId === message.id || relatedQuestionsMessageId === message.ai_message_id) && aiRelatedQuestions.length > 0" class="related-questions">
- <div
- v-for="(question, index) in aiRelatedQuestions"
- :key="index"
- class="related-question-item"
- @click="handleRelatedQuestion(question)"
- >
- <span>{{ question }}</span>
- <svg class="arrow-icon" viewBox="0 0 16 16" fill="none">
- <path d="M6 4L10 8L6 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
- </svg>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <!-- 底部输入区域 -->
- <div class="chat-input-section" v-show="currentMode !== 'exam-workshop'">
- <!-- 推荐问题 (移至输入框上方) -->
- <div v-if="!showChat && !selectedFile" class="recommended-questions">
- <div
- v-for="(question, index) in hotQuestions"
- :key="question.id || index"
- class="question-tag"
- @click="handleRecommendedQuestion(question.question)"
- >
- <img :src="getQuestionIcon(question.question)" alt="问题" class="question-icon">
- {{ question.question }}
- </div>
-
- <!-- 如果没有数据,显示默认问题 -->
- <template v-if="hotQuestions.length === 0">
- <div
- v-for="(question, index) in defaultHotQuestions"
- :key="`default-${index}`"
- class="question-tag"
- @click="handleRecommendedQuestion(question)"
- >
- <img :src="getQuestionIcon(question)" alt="问题" class="question-icon">
- {{ question }}
- </div>
- </template>
- </div>
- <!-- 用户推荐问题区域 -->
- <div v-if="userRecommendQuestions.length > 0" class="user-recommend-questions" @click.stop>
- <div class="recommend-list">
- <div
- v-for="(question, index) in userRecommendQuestions"
- :key="index"
- class="recommend-item"
- @click="handleUserRecommendQuestion(question)"
- >
- {{ question }}
- </div>
- </div>
- </div>
- <div class="input-container">
- <!-- 文件预览区域 -->
- <div v-if="selectedFile" class="file-preview-section">
- <div class="file-preview">
- <div class="file-icon">
- <img v-if="selectedFile.icon !== '📎'" :src="selectedFile.icon" alt="文件图标" class="file-icon-img">
- <span v-else>{{ selectedFile.icon }}</span>
- </div>
- <div class="file-info">
- <div class="file-name">{{ selectedFile.name }}</div>
- <div class="file-size">{{ formatFileSize(selectedFile.size) }}</div>
- </div>
- <button class="remove-file-btn" @click="removeSelectedFile">
- <span class="remove-icon">×</span>
- </button>
- </div>
- </div>
-
- <div class="input-box">
- <!-- 上半部分:输入区 -->
- <textarea
- placeholder="给AI智能助手发消息(按Enter进行发送)"
- class="message-input"
- v-model="messageText"
- @keyup.enter.exact="handleSendMessage"
- @input="handleInput"
- :disabled="isSending || hasTypingMessage"
- maxlength="2000"
- rows="3"
- ></textarea>
- <!-- 下半部分:工具栏 -->
- <div class="input-toolbar">
- <div class="toolbar-left">
- <!-- 语音输入 -->
- <button class="voice-btn" @click="handleVoiceClick" :disabled="isSending || hasTypingMessage" :class="{ 'recording': isListening }">
- <div class="icon-container">
- <img :src="voiceInputIcon" alt="语音" class="action-icon">
- <div v-if="isListening" class="recording-indicator"></div>
- </div>
- </button>
- <!-- 模式标签组 -->
- <div class="mode-chips">
- <div
- v-if="currentMode === 'ai-qa' || currentMode === 'ai-writing'"
- class="mode-chip"
- :class="{ active: currentMode === 'ai-writing' }"
- @click="setMode('ai-writing')"
- >
- <img src="../assets/chat/13.png" alt="AI写作" class="chip-icon">
- <span>AI写作</span>
- </div>
-
- <div
- v-if="currentMode === 'ai-qa' || currentMode === 'safety-training'"
- class="mode-chip"
- :class="{ active: currentMode === 'safety-training' }"
- @click="setMode('safety-training')"
- >
- <img src="../assets/chat/14.png" alt="安全培训" class="chip-icon">
- <span>安全培训</span>
- </div>
- <div
- v-if="currentMode === 'ai-qa' || currentMode === 'exam-workshop'"
- class="mode-chip"
- :class="{ active: currentMode === 'exam-workshop' }"
- @click="setMode('exam-workshop')"
- >
- <img src="../assets/chat/19.png" alt="考试工坊" class="chip-icon">
- <span>考试工坊</span>
- </div>
- </div>
- </div>
- <div class="toolbar-right">
- <!-- 在线大模型链接按钮 (左侧) -->
- <button
- class="model-link-btn"
- :class="{ 'active': isOnlineModel }"
- @click="toggleModelType"
- :disabled="isSending || hasTypingMessage"
- :title="isOnlineModel ? '当前:在线大模型 (glm-4-plus)' : '当前:本地模型'"
- >
- <div class="icon-container">
- <img :src="isOnlineModel ? networkSearchIconOn : networkSearchIconOff" alt="在线大模型" class="action-icon network-search-icon" :class="{ 'active-icon': isOnlineModel }">
- </div>
- </button>
- <!-- 附件图标 (右侧) -->
- <button class="attach-btn" @click="triggerFileUpload" :disabled="isSending || hasTypingMessage">
- <div class="icon-container">
- <img :src="attachmentIcon" alt="附件" class="action-icon">
- </div>
- </button>
- <button
- class="send-btn"
- @click="(isSending || hasTypingMessage) ? handleStopGeneration() : handleSendMessage()"
- :disabled="!(isSending || hasTypingMessage) && !messageText.trim()"
- >
- <span v-if="isSending || hasTypingMessage" class="stop-text">停止</span>
- <div v-else class="send-icon-circle" :class="{ 'active': messageText.trim() }">
- <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
- <path d="M12 19V5M12 5L5 12M12 5L19 12" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
- </svg>
- </div>
- </button>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- <!-- AI写作侧边栏 -->
- <transition name="sidebar-slide">
- <div v-if="aiWritingSidebarVisible" class="ai-writing-sidebar">
- <div class="sidebar-header">
- <h3 class="sidebar-title">{{ aiWritingSidebarTitle }}</h3>
- <div class="sidebar-header-actions">
- <button class="sidebar-close-btn" @click="closeAIWritingSidebar">
- <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
- <path d="M12 4L4 12M4 4L12 12" stroke="#909399" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
- </svg>
- </button>
- </div>
- </div>
- <div class="sidebar-toolbar" v-if="!aiWritingIsGenerating">
- <span class="toolbar-label">正文</span>
- <span class="toolbar-font-size">15px</span>
- <div class="toolbar-divider"></div>
- <button class="toolbar-btn"><b>B</b></button>
- <button class="toolbar-btn"><s>S</s></button>
- <button class="toolbar-btn"><u>U</u></button>
- <button class="toolbar-btn"><i>I</i></button>
- </div>
- <div class="sidebar-content">
- <div class="sidebar-doc-content" v-text="aiWritingSidebarContent"></div>
- <div v-if="aiWritingIsGenerating" class="sidebar-generating-hint">
- <span class="generating-text-hint">AI智能助手正在输出</span>
- <span class="generating-dots">
- <span class="dot">.</span>
- <span class="dot">.</span>
- <span class="dot">.</span>
- </span>
- </div>
- </div>
- </div>
- </transition>
- </div>
-
-
-
- <!-- 隐藏的文件输入框 -->
- <input
- ref="fileInput"
- type="file"
- accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,image/*,text/plain"
- style="display: none"
- @change="handleFileSelect"
- />
-
- <!-- Toast提示组件 -->
- <Toast
- ref="toastRef"
- :message="toastMessage"
- :type="toastType"
- :duration="toastDuration"
- />
-
- <!-- 删除确认弹窗 -->
- <DeleteConfirmModal
- :visible="showDeleteModal"
- :title="deleteConfirmTitle"
- :message="deleteConfirmMessage"
- @confirm="confirmDelete"
- @cancel="cancelDelete"
- @close="cancelDelete"
- />
-
- <!-- 文件预览抽屉 -->
- <FilePreviewDrawer
- v-model="showFilePreview"
- :file-path="previewFilePath"
- :file-name="previewFileName"
- />
-
- <!-- 网络搜索侧边栏 -->
- <WebSearchSidebar
- :visible="webSearchSidebarVisible"
- :results="currentWebSearchData.results"
- :keywords="currentWebSearchData.keywords"
- :total="currentWebSearchData.total"
- @update:visible="webSearchSidebarVisible = $event"
- />
-
- </div>
- </template>
- <script setup>
- import { ref, nextTick, reactive, triggerRef, markRaw, onMounted, onBeforeUnmount, computed, watch, onActivated } from 'vue'
- import { useRoute, useRouter } from 'vue-router'
- import Sidebar from '@/components/Sidebar.vue'
- import ExamWorkshop from '@/views/ExamWorkshop.vue'
- import * as mammoth from 'mammoth'
- // 导入Element Plus组件
- import { ElMessage } from 'element-plus'
- import DeleteConfirmModal from '@/components/DeleteConfirmModal.vue'
- import Toast from '@/components/Toast.vue'
- import { useSpeechRecognition } from '@/composables/useSpeechRecognition'
- // ===== 已删除:getUserId - 不再需要,改用token =====
- // import { getUserId } from '@/utils/userManager.js'
- import { stopSSEStream, updateAIMessageContent } from '@/utils/api.js'
- import { getToken, getTokenType } from '@/utils/auth.js'
- import { renderMarkdown } from '@/utils/markdown'
- import 'katex/dist/katex.min.css'
- // 导入ReportGenerator相关组件
- import QuestionInput from '@/components/QuestionInput.vue'
- import CategoryTitle from '@/components/CategoryTitle.vue'
- import FileReportCard from '@/components/FileReportCard.vue'
- import ExportButton from '@/components/ExportButton.vue'
- import StreamMarkdown from '@/components/StreamMarkdown.vue'
- import FilePreviewDrawer from '@/components/FilePreviewDrawer.vue'
- import WebSearchCapsule from '@/components/WebSearchCapsule.vue'
- import WebSearchSidebar from '@/components/WebSearchSidebar.vue'
- import WebSearchSummary from '@/components/WebSearchSummary.vue'
- import StatusAvatar from '@/components/StatusAvatar.vue'
- import { createSSEConnection, closeSSEConnection } from '@/utils/sse'
- import { getApiPrefix } from '@/utils/apiConfig'
- import { Document } from '@element-plus/icons-vue'
- // 导入发送按钮图标
- import sendIconEmpty from '@/assets/chat/15.png'
- import sendIconFilled from '@/assets/chat/16.png'
- // 导入其他图片资源
- import newChatIcon from '@/assets/chat/2.png'
- import emptyIcon from '@/assets/Chat/22.png'
- import aiAvatarIcon from '@/assets/Chat/29.png'
- import bridgeIcon from '@/assets/chat/4.png'
- import constructionIcon from '@/assets/chat/5.png'
- import materialIcon from '@/assets/chat/6.png'
- import standardIcon from '@/assets/chat/7.png'
- import copyIcon from '@/assets/AIWriting/5.png'
- import editIcon from '@/assets/AIWriting/6.png'
- import regenerateIcon from '@/assets/AIWriting/7.png'
- import deleteIcon from '@/assets/AIWriting/8.png'
- import voiceIcon from '@/assets/AIWriting/9.png'
- import likeIcon from '@/assets/AIWriting/10.png'
- import dislikeIcon from '@/assets/AIWriting/11.png'
- import questionIcon1 from '@/assets/chat/12.png'
- import questionIcon2 from '@/assets/chat/10.png'
- import questionIcon3 from '@/assets/chat/11.png'
- import attachmentIcon from '@/assets/chat/9.png'
- import voiceInputIcon from '@/assets/Chat/18.png'
- import networkSearchIconOn from '@/assets/Chat/24.png'
- import networkSearchIconOff from '@/assets/Chat/25.png'
- import wordDocIcon from '@/assets/Chat/26.png'
- import { Link } from '@element-plus/icons-vue'
- import { apis } from '@/request/apis.js'
- // 路由实例
- const route = useRoute()
- const router = useRouter()
- // 响应式数据
- const messageText = ref('')
- const selectedHistoryItem = ref(null) // 选中的历史记录项
- const showChat = ref(false) // 控制是否显示聊天界面
- const isSending = ref(false) // 控制发送状态
- const isOnlineModel = ref(true) // 是否使用在线大模型
- // 切换模型类型
- const toggleModelType = () => {
- isOnlineModel.value = !isOnlineModel.value
- showToast(
- isOnlineModel.value ? '启动在线大模型 (glm-4-plus)' : '已禁用在线大模型'
- )
- }
- const currentMode = ref('ai-qa')
- const hasUserSelectedMode = ref(false)
- const defaultHotQuestionsByMode = {
- 'ai-qa': [
- '施工安全生产责任的规定',
- '工程建设质量的要求',
- '公路桥梁加固设计规范'
- ],
- 'ai-writing': [
- '生成施工安全培训通知',
- '编写安全生产责任制范本',
- '生成隐患排查整改方案'
- ],
- 'safety-training': [
- '新员工安全培训内容有哪些',
- '特种作业人员安全培训要求',
- '安全培训档案应包含哪些内容'
- ],
- 'exam-workshop': [
- '生成安全培训考试题库',
- '安全生产法规知识点整理',
- '常见隐患排查考试题'
- ]
- }
- const defaultHotQuestions = computed(
- () => defaultHotQuestionsByMode[currentMode.value] || defaultHotQuestionsByMode['ai-qa']
- )
- const defaultFunctionCardsByMode = {
- 'ai-qa': [
- {
- title: '桥梁结构设计问题',
- description: '各类桥梁结构设计,计算与分析',
- icon: bridgeIcon
- },
- {
- title: '施工技术咨询',
- description: '桥梁施工方法,工艺与技术要点',
- icon: constructionIcon
- },
- {
- title: '材料与力学问题',
- description: '建筑材料性能与结构力学分析',
- icon: materialIcon
- },
- {
- title: '规范标准查询',
- description: '行业规范,标准解读与应用',
- icon: standardIcon
- }
- ],
- 'ai-writing': [
- {
- title: '安全培训通知',
- description: '生成培训通知、计划与执行安排',
- icon: bridgeIcon
- },
- {
- title: '制度与方案编写',
- description: '生成制度、方案、流程与模板',
- icon: constructionIcon
- },
- {
- title: '隐患整改方案',
- description: '生成整改措施与闭环流程',
- icon: materialIcon
- },
- {
- title: '会议纪要模板',
- description: '生成会议纪要与行动项清单',
- icon: standardIcon
- }
- ],
- 'safety-training': [
- {
- title: '新员工安全培训',
- description: '入职培训要点与必修内容',
- icon: bridgeIcon
- },
- {
- title: '特种作业培训',
- description: '特种作业上岗培训与复训要求',
- icon: constructionIcon
- },
- {
- title: '安全教育制度',
- description: '安全教育制度与实施流程',
- icon: materialIcon
- },
- {
- title: '培训档案管理',
- description: '培训记录与档案规范管理',
- icon: standardIcon
- }
- ],
- 'exam-workshop': [
- {
- title: '考试题库生成',
- description: '按主题生成题库与解析',
- icon: bridgeIcon
- },
- {
- title: '法规知识点',
- description: '法规标准要点梳理与归纳',
- icon: constructionIcon
- },
- {
- title: '隐患排查题',
- description: '隐患识别与处置题型',
- icon: materialIcon
- },
- {
- title: '考试大纲',
- description: '生成考试大纲与评分标准',
- icon: standardIcon
- }
- ]
- }
- const defaultFunctionCards = computed(
- () => defaultFunctionCardsByMode[currentMode.value] || defaultFunctionCardsByMode['ai-qa']
- )
- const setMode = (mode, options = {}) => {
- const { allowToggle = true, source = 'user' } = options
- if (source === 'user') {
- hasUserSelectedMode.value = true
- }
- if (allowToggle && currentMode.value === mode) {
- currentMode.value = 'ai-qa' // 再次点击取消选中,回到默认问答
- } else {
- currentMode.value = mode
- }
-
- // 切换回AI问答时,确保输入框和聊天区域正常显示
- if (currentMode.value === 'ai-qa' && !chatMessages.value.length) {
- showChat.value = false
- } else if (currentMode.value === 'ai-qa' && chatMessages.value.length > 0) {
- showChat.value = true
- }
- }
- // ReportGenerator相关状态
- const categoryExpandStates = ref({})
- const currentQuestion = ref('')
- let sseConnection = null
- const streamingReports = ref(new Map())
- // 删除确认弹窗状态
- const showDeleteModal = ref(false)
- const deleteTargetItem = ref(null) // 要删除的历史记录项
- const deleteType = ref('') // 删除类型:'history' 或 'message'
- // 功能卡片和热点问题数据
- const functionCards = ref([])
- const hotQuestions = ref([])
- // 聊天消息数据
- const chatMessages = ref([])
- const messageContentRefs = ref({})
- const messageScrollStates = ref({})
- // Toast相关
- const toastRef = ref(null)
- const toastMessage = ref('')
- const toastType = ref('success')
- const toastDuration = ref(2000)
- // 显示Toast提示
- const showToast = (message, type = 'success', duration = 2000) => {
- toastMessage.value = message
- toastType.value = type
- toastDuration.value = duration
-
- // 显示Toast
- if (toastRef.value) {
- toastRef.value.show()
- }
- }
- // 语音功能
- const {
- isSupported: speechSupported,
- isListening,
- isSpeaking: speechIsSpeaking,
- transcript,
- error: speechError,
- startListening,
- stopListening,
- speakText,
- stopSpeaking
- } = useSpeechRecognition()
- // 记录正在朗读的消息ID
- const speakingMessageId = ref(null)
- // 页面卸载事件处理函数
- const handlePageUnload = () => {
- if (speakingMessageId.value) {
- stopAllAudio()
- speakingMessageId.value = null
- }
- }
- // 页面可见性变化处理函数
- const handleVisibilityChange = () => {
- if (document.hidden && speakingMessageId.value) {
- stopAllAudio()
- speakingMessageId.value = null
- }
- }
- // 文件上传相关
- const fileInput = ref(null)
- const selectedFile = ref(null)
- const isUploadingFile = ref(false)
- const fileContent = ref('') // 存储文件内容
- // 用户推荐问题相关
- const userRecommendQuestions = ref([]) // 用户输入时获取的推荐问题
- const isGettingRecommendQuestions = ref(false) // 是否正在获取推荐问题
- const recommendQuestionsTimer = ref(null) // 防抖定时器
- // AI回复相关推荐问题
- const aiRelatedQuestions = ref([]) // AI回复后的相关推荐问题
- const isGettingRelatedQuestions = ref(false) // 是否正在获取相关推荐问题
- const relatedQuestionsMessageId = ref(null) // 关联的消息ID
- const isAIReplyProcessComplete = ref(true) // AI回复流程是否完成(包括联网搜索和推荐问题)
- // 联网搜索相关
- const isNetworkSearchEnabled = ref(true) // 联网搜索是否启用,默认为true
- const onlineSearchResults = ref({}) // 存储每个消息的联网搜索结果
- const isGettingOnlineSearch = ref(false) // 是否正在获取联网搜索结果
- const onlineSearchLoadingMessages = ref(new Set()) // 记录正在加载联网搜索的消息ID
- // 搜索来源展开状态
- const expandedSearchSources = ref({}) // 记录每个消息的搜索来源展开状态
- const expandedOnlineSearchResults = ref({}) // 记录每个消息的联网搜索结果展开状态
- // 网络搜索结果数据(新增)
- const webSearchSidebarVisible = ref(false) // 网络搜索侧边栏显示状态
- // AI写作侧边栏状态
- const aiWritingSidebarVisible = ref(false)
- const aiWritingSidebarTitle = ref('')
- const aiWritingSidebarContent = ref('')
- const aiWritingIsGenerating = ref(false)
- const aiWritingFullContent = ref('') // 保存完整内容,用于点击文件卡片时重新打开
- const normalizeAiWritingText = (content) => {
- if (!content) return ''
- return String(content).replace(/\r\n/g, '\n')
- }
- // 关闭AI写作侧边栏
- const closeAIWritingSidebar = () => {
- aiWritingSidebarVisible.value = false
- }
- // 打开AI写作侧边栏(点击文件卡片时)
- const openAIWritingSidebar = (message) => {
- aiWritingSidebarTitle.value = message.aiWritingTitle || currentQuestion.value || 'AI写作文档'
- aiWritingSidebarContent.value = normalizeAiWritingText(message.fullContent || message.content || '')
- aiWritingIsGenerating.value = message.aiWritingStatus === 'generating' || message.isTyping
- aiWritingSidebarVisible.value = true
- }
- const currentWebSearchData = ref({
- results: [],
- keywords: [],
- total: 0
- }) // 当前查看的网络搜索数据
- // 搜索来源数据现在从历史记录中动态获取,不再使用模拟数据
- // 文件处理配置
- const fileConfig = reactive({
- maxSize: 20 * 1024 * 1024, // 20MB
- allowedTypes: ['.docx'] // 只允许.docx格式的Word文档
- })
- // 文件预览相关
- const showFilePreview = ref(false)
- const previewFilePath = ref('')
- const previewFileName = ref('')
- // 计算属性 - 是否有正在打字的AI消息或AI回复流程未完成
- const hasTypingMessage = computed(() => {
- return chatMessages.value.some(message => message.type === 'ai' && message.isTyping) || !isAIReplyProcessComplete.value
- })
- // ReportGenerator相关计算属性
- const exportTitle = computed(() => {
- if (currentQuestion.value) {
- return currentQuestion.value.substring(0, 20) + (currentQuestion.value.length > 20 ? '...' : '')
- }
- return 'AI问题分析报告'
- })
- // 计算属性 - 是否有正在加载的AI消息(内容为空且正在打字)
- const hasLoadingMessage = computed(() => {
- return chatMessages.value.some(message =>
- message.type === 'ai' &&
- message.isTyping &&
- (!message.content || message.content.trim() === '')
- )
- })
- // 计算属性 - 是否有正在打字的AI消息(有内容)
- const hasTypingWithContent = computed(() => {
- return chatMessages.value.some(message =>
- message.type === 'ai' &&
- message.isTyping &&
- message.content &&
- message.content.trim() !== ''
- )
- })
- // 删除确认消息
- const deleteConfirmMessage = computed(() => {
- if (deleteType.value === 'history') {
- const title = deleteTargetItem.value?.item?.title || ''
- return `确定要删除历史记录"${title}"吗?删除后将无法恢复。`
- } else if (deleteType.value === 'message') {
- return '确定要删除这条消息吗?删除后将无法恢复。'
- }
- return '确定要删除吗?删除后将无法恢复。'
- })
- // 删除确认标题
- const deleteConfirmTitle = computed(() => {
- if (deleteType.value === 'history') {
- return '删除历史记录'
- } else if (deleteType.value === 'message') {
- return '删除消息'
- }
- return '删除确认'
- })
- // 处理AI回复中的特殊字符和表情符号
- const processAIResponse = (text) => {
- if (!text) return text
-
- try {
- // URL解码
- if (text.includes('%')) {
- text = decodeURIComponent(text)
- }
-
- // Unicode转义序列
- if (text.includes('\\u')) {
- text = text.replace(/\\u[\dA-F]{4}/gi, (match) => {
- return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16))
- })
- }
-
- // HTML实体解码
- if (text.includes('&')) {
- const textarea = document.createElement('textarea')
- textarea.innerHTML = text
- text = textarea.value
- }
-
- // LaTeX公式转换
- return convertLatexToDisplay(text)
- } catch (error) {
- console.warn('文本处理失败:', error)
- return text
- }
- }
- // 打字机效果函数
- const typewriterIntervals = new Map() // 存储每个消息的打字机定时器
- const reportTypewriters = new Map() // 存储每个报告字段的打字机定时器
- const startTypewriterEffect = (message, fullContent, speed = 30) => {
- return new Promise((resolve) => {
- // 如果已经有打字机在运行,先清除
- if (typewriterIntervals.has(message.id)) {
- clearInterval(typewriterIntervals.get(message.id))
- typewriterIntervals.delete(message.id)
- }
-
- let currentIndex = 0
- message.displayContent = ''
- message.isTyping = true
-
- const interval = setInterval(() => {
- if (currentIndex < fullContent.length) {
- // 每次增加的字符数(速度越快,每次增加越多)
- const charsToAdd = Math.max(1, Math.floor(speed / 10))
- currentIndex = Math.min(currentIndex + charsToAdd, fullContent.length)
-
- // 更新显示内容
- message.displayContent = fullContent.substring(0, currentIndex)
- } else {
- // 打字完成
- clearInterval(interval)
- typewriterIntervals.delete(message.id)
- message.isTyping = false
- message.displayContent = fullContent
-
- // 确保状态更新为完成
- if (message.showStats && message.progress < 100) {
- updateMessageStatus(message, 'completed')
- }
-
- resolve()
- }
- }, 1000 / 60) // 60fps
-
- typewriterIntervals.set(message.id, interval)
- })
- }
- // 为报告字段添加打字机效果
- const startReportFieldTypewriter = (report, field, fullContent, speed = 50) => {
- return new Promise((resolve) => {
- const key = `${report.file_index}_${field}`
-
- // 如果已经有打字机在运行,先清除
- if (reportTypewriters.has(key)) {
- clearInterval(reportTypewriters.get(key))
- reportTypewriters.delete(key)
- }
-
- // 初始化打字机状态
- if (!report._typewriterStates) {
- report._typewriterStates = {}
- }
-
- let currentIndex = 0
- report._typewriterStates[field] = { currentIndex: 0, isTyping: true }
-
- const interval = setInterval(() => {
- if (currentIndex < fullContent.length) {
- const charsToAdd = Math.max(1, Math.floor(speed / 10))
- currentIndex = Math.min(currentIndex + charsToAdd, fullContent.length)
-
- // 更新显示内容
- report.report[field] = fullContent.substring(0, currentIndex)
- report._typewriterStates[field].currentIndex = currentIndex
- } else {
- // 打字完成
- clearInterval(interval)
- reportTypewriters.delete(key)
- report._typewriterStates[field].isTyping = false
- report.report[field] = fullContent
- resolve()
- }
- }, 1000 / 60) // 60fps
-
- reportTypewriters.set(key, interval)
- })
- }
- // 清除所有打字机定时器
- const clearAllTypeIntervals = () => {
- typewriterIntervals.forEach((interval, messageId) => {
- clearInterval(interval)
- })
- typewriterIntervals.clear()
-
- reportTypewriters.forEach((interval, key) => {
- clearInterval(interval)
- })
- reportTypewriters.clear()
- }
- // 处理文件标签格式的回显
- const processFileDisplay = (text, file) => {
- if (!file) {
- // 如果没有文件对象,尝试从文本中提取文件信息
- return processFileDisplayFromText(text)
- }
-
- // 查找文件标签并替换为显示格式
- const fileDisplay = `
- 📄 文件信息:
- 文件名:${file.name}
- 文件大小:${formatFileSize(file.size)}
- 文件类型:${file.type}
- 📝 文件内容:
- ${file.content}
- ---
- `
-
- // 替换文件标签为显示格式
- let processedText = text
- .replace(/<word>.*?<\/word>/gs, fileDisplay)
- .replace(/<filename>.*?<\/filename>/g, '')
- .replace(/<filesize>.*?<\/filesize>/g, '')
-
- return processedText
- }
- // 从文本中提取文件信息并转换为显示格式
- const processFileDisplayFromText = (text) => {
- // 提取文件名
- const filenameMatch = text.match(/<filename>(.*?)<\/filename>/)
- const filename = filenameMatch ? filenameMatch[1] : '未知文件'
-
- // 提取文件大小
- const filesizeMatch = text.match(/<filesize>(.*?)<\/filesize>/)
- const filesize = filesizeMatch ? parseInt(filesizeMatch[1]) : 0
-
- // 提取文件内容
- const wordMatch = text.match(/<word>(.*?)<\/word>/s)
- const fileContent = wordMatch ? wordMatch[1].trim() : '无内容'
-
- // 创建文件显示格式
- const fileDisplay = `
- 📄 文件信息:
- 文件名:${filename}
- 文件大小:${formatFileSize(filesize)}
- 文件类型:${filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '未知'}
- 📝 文件内容:
- ${fileContent}
- ---
- `
-
- // 替换文件标签为显示格式
- let processedText = text
- .replace(/<word>.*?<\/word>/gs, fileDisplay)
- .replace(/<filename>.*?<\/filename>/g, '')
- .replace(/<filesize>.*?<\/filesize>/g, '')
-
- return processedText
- }
- // 使用markdown.js渲染Markdown内容
- const renderMarkdownContent = (content) => {
- try {
- let html = renderMarkdown(content)
- html = processStandardReferences(html)
-
- nextTick(() => {
- bindStandardReferenceEvents()
- })
-
- return html
- } catch (error) {
- console.error('Markdown渲染失败:', error)
- return content.replace(/\n/g, '<br>')
- }
- }
- // LaTeX公式转换函数
- const convertLatexToDisplay = (text) => {
- if (!text) return text
-
- let convertedText = text
-
- // 希腊字母转换
- const greekLetters = {
- '\\alpha': 'α', '\\beta': 'β', '\\gamma': 'γ', '\\delta': 'δ', '\\epsilon': 'ε',
- '\\varepsilon': 'ε', '\\zeta': 'ζ', '\\eta': 'η', '\\theta': 'θ', '\\iota': 'ι',
- '\\kappa': 'κ', '\\lambda': 'λ', '\\mu': 'μ', '\\nu': 'ν', '\\xi': 'ξ',
- '\\pi': 'π', '\\rho': 'ρ', '\\sigma': 'σ', '\\tau': 'τ', '\\upsilon': 'υ',
- '\\phi': 'φ', '\\chi': 'χ', '\\psi': 'ψ', '\\omega': 'ω',
- '\\Gamma': 'Γ', '\\Delta': 'Δ', '\\Theta': 'Θ', '\\Lambda': 'Λ', '\\Xi': 'Ξ',
- '\\Pi': 'Π', '\\Sigma': 'Σ', '\\Upsilon': 'Υ', '\\Phi': 'Φ', '\\Psi': 'Ψ', '\\Omega': 'Ω'
- }
-
- // 转换希腊字母
- for (const [latex, symbol] of Object.entries(greekLetters)) {
- const regex = new RegExp(latex.replace(/\\/g, '\\\\'), 'g')
- convertedText = convertedText.replace(regex, symbol)
- }
-
- // 分数转换 \frac{a}{b} → a/b
- convertedText = convertedText.replace(/\\frac\{([^}]+)\}\{([^}]+)\}/g, '$1/$2')
-
- // 上标转换 a^b → a^b (保持原样,因为前端可以显示)
- // convertedText = convertedText.replace(/\^(\w+)/g, '^$1')
-
- // 下标转换 a_b → a_b (保持原样,因为前端可以显示)
- // convertedText = convertedText.replace(/_(\w+)/g, '_$1')
-
- // 根号转换 \sqrt{a} → √a
- convertedText = convertedText.replace(/\\sqrt\{([^}]+)\}/g, '√$1')
-
- // 积分符号转换
- convertedText = convertedText.replace(/\\int/g, '∫')
- convertedText = convertedText.replace(/\\sum/g, '∑')
- convertedText = convertedText.replace(/\\prod/g, '∏')
- convertedText = convertedText.replace(/\\partial/g, '∂')
- convertedText = convertedText.replace(/\\nabla/g, '∇')
- convertedText = convertedText.replace(/\\infty/g, '∞')
-
- // 其他数学符号
- convertedText = convertedText.replace(/\\pm/g, '±')
- convertedText = convertedText.replace(/\\times/g, '×')
- convertedText = convertedText.replace(/\\div/g, '÷')
- convertedText = convertedText.replace(/\\leq/g, '≤')
- convertedText = convertedText.replace(/\\geq/g, '≥')
- convertedText = convertedText.replace(/\\neq/g, '≠')
- convertedText = convertedText.replace(/\\approx/g, '≈')
- convertedText = convertedText.replace(/\\equiv/g, '≡')
- convertedText = convertedText.replace(/\\propto/g, '∝')
-
- // 集合符号
- convertedText = convertedText.replace(/\\in/g, '∈')
- convertedText = convertedText.replace(/\\notin/g, '∉')
- convertedText = convertedText.replace(/\\subset/g, '⊂')
- convertedText = convertedText.replace(/\\supset/g, '⊃')
- convertedText = convertedText.replace(/\\cup/g, '∪')
- convertedText = convertedText.replace(/\\cap/g, '∩')
- convertedText = convertedText.replace(/\\emptyset/g, '∅')
-
- // 逻辑符号
- convertedText = convertedText.replace(/\\land/g, '∧')
- convertedText = convertedText.replace(/\\lor/g, '∨')
- convertedText = convertedText.replace(/\\neg/g, '¬')
- convertedText = convertedText.replace(/\\rightarrow/g, '→')
- convertedText = convertedText.replace(/\\leftarrow/g, '←')
- convertedText = convertedText.replace(/\\leftrightarrow/g, '↔')
- convertedText = convertedText.replace(/\\forall/g, '∀')
- convertedText = convertedText.replace(/\\exists/g, '∃')
-
- return convertedText
- }
- // 处理规范引用 - 将<file></file>标签内容转换为可点击的规范引用
- const processStandardReferences = (html) => {
- if (!html) return html
-
- const refStyle = 'background-color: #EAEAEE; color: #616161; font-size: 0.75rem; padding: 3px 8px; border-radius: 6px; cursor: pointer; display: inline-block; margin: 4px 2px; border: 1px solid #EAEAEE; font-weight: 500; transition: all 0.2s ease; line-height: 1.4; max-width: 300px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'
-
- return html.replace(/<file>(.*?)<\/file>/g, (match, content) => {
- if (/^<span\s+class="standard-reference"/i.test(content)) {
- return match
- }
-
- const standardMatch = content.match(/^([《「『【]?[\s\S]*?[》」』】]?)[\s]*\(([^)]+)\)$/)
- if (standardMatch) {
- return `<span class="standard-reference" data-standard="${content}" title="点击查看标准详情" style="${refStyle}">${content}</span>`
- }
-
- return `<span class="standard-reference" data-reference="${content}" title="点击查看详情" style="${refStyle}">${content}</span>`
- })
- }
- // 历史记录数据
- const historyData = ref([])
- const historyTotal = ref(0) // 历史记录总数
- const isLoadingHistory = ref(false) // 是否正在加载历史记录
- // 获取历史记录列表 (合并所有模块)
- const getHistoryRecordList = async () => {
- try {
- isLoadingHistory.value = true
-
- const response = await apis.getHistoryRecord({
- ai_conversation_id: 0
- })
- let allRecords = []
- let totalCount = 0
- if (response.statusCode === 200 && response.data) {
- totalCount = response.total || response.data.length || 0
- allRecords = response.data
- }
-
- // 按时间降序排序
- allRecords.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
-
- historyTotal.value = totalCount
- historyData.value = allRecords.map(conversation => ({
- id: conversation.id,
- title: conversation.title || generateConversationTitle(conversation.content),
- time: formatTime(conversation.updated_at),
- businessType: conversation.business_type,
- isActive: false,
- rawData: conversation
- }))
- } catch (error) {
- console.error('获取历史记录失败:', error)
- } finally {
- isLoadingHistory.value = false
- }
- }
- // 获取指定对话的详细消息
- const getConversationMessages = async (conversationId) => {
- try {
- const response = await apis.getHistoryRecord({
- // ===== 已删除:user_id - 后端从token解析 =====
- ai_conversation_id: conversationId,
- business_type: 0
- })
-
- if (response.statusCode === 200) {
- if (!response.data || !Array.isArray(response.data)) {
- console.error('响应数据格式错误')
- return false
- }
-
- const messages = await Promise.all(response.data.map(async (message, index) => {
- const userFeedback = convertUserFeedback(message.user_feedback)
-
- // 如果是用户消息且包含文件标签,提取文件信息
- let file = null
- let userContent = message.content
-
- // 获取前一条用户消息作为AI消息的问题上下文
- let userQuestion = null
- if (message.type === 'ai' && index > 0) {
- const prevMessage = response.data[index - 1]
- if (prevMessage && prevMessage.type === 'user') {
- // 提取用户实际问题(去除文件标签)
- if (prevMessage.content.includes('</filesize>')) {
- const userMessageMatch = prevMessage.content.split('</filesize>')[1]
- userQuestion = userMessageMatch ? userMessageMatch.trim() : prevMessage.content
- } else {
- userQuestion = prevMessage.content
- }
- }
- }
-
- if (message.type === 'user' && message.content.includes('</filesize>')) {
- // 提取文件信息
- const filenameMatch = message.content.match(/<filename>(.*?)<\/filename>/)
- const filesizeMatch = message.content.match(/<filesize>(.*?)<\/filesize>/)
- const wordMatch = message.content.match(/<word>(.*?)<\/word>/s)
-
- if (filenameMatch && filesizeMatch) {
- const filename = filenameMatch[1]
- const filesize = parseInt(filesizeMatch[1])
- const fileContent = wordMatch ? wordMatch[1].trim() : ''
-
- // 创建文件对象
- file = {
- name: filename,
- size: filesize,
- type: filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '.docx',
- icon: getFileIcon(filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '.docx'),
- content: fileContent
- }
-
- // 提取用户实际说的话(</filesize>标签后的内容)
- const userMessageMatch = message.content.split('</filesize>')[1]
- userContent = userMessageMatch ? userMessageMatch.trim() : ''
- }
- }
-
- // 为AI消息准备displayContent
- let displayContent = userContent || ''
- let reports = []
- let summary = message.summary || '' // 从后端恢复summary字段
-
- if (message.type === 'ai') {
- try {
- const contentStr = message.content || ''
-
- // 尝试解析content为JSON
- if (contentStr.trim().startsWith('[') || contentStr.trim().startsWith('{')) {
- try {
- const parsedContent = JSON.parse(contentStr)
-
- // 检查是否是新格式(包含reports和webSearch数据)
- if (parsedContent.reports && Array.isArray(parsedContent.reports)) {
- reports = parsedContent.reports
- // 恢复网络搜索数据
- if (parsedContent.webSearchRaw) {
- message.webSearchRaw = parsedContent.webSearchRaw
- }
- if (parsedContent.webSearchSummary) {
- message.webSearchSummary = parsedContent.webSearchSummary
- message.hasWebSearchResults = parsedContent.hasWebSearchResults || false
- }
- // ===== 🔧 修复:从content JSON中恢复summary =====
- if (parsedContent.summary) {
- summary = parsedContent.summary
- }
- } else if (Array.isArray(parsedContent)) {
- // 旧格式,直接是reports数组
- reports = parsedContent
- } else {
- throw new Error('Not an array or valid format')
- }
- } catch (jsonError) {
- // JSON解析失败,当作普通Markdown文本处理
- let processedContent = contentStr
- .replace(/\\n/g, '\n')
- .replace(/\\t/g, '\t')
- .replace(/\\r/g, '\r')
-
- displayContent = renderMarkdownContent(processedContent)
- }
- } else {
- // 不是JSON格式,直接按Markdown处理
- let processedContent = contentStr
- .replace(/\\n/g, '\n')
- .replace(/\\t/g, '\t')
- .replace(/\\r/g, '\r')
-
- displayContent = renderMarkdownContent(processedContent)
- }
- } catch (error) {
- console.error('历史记录处理失败:', error)
- displayContent = message.content || ''
- }
- }
-
- // 如果有reports,计算相关统计信息
- let totalFiles = 0
- let completedCount = 0
- let progress = 100
-
- if (reports.length > 0) {
- // 过滤掉category_title类型,只统计实际报告
- const actualReports = reports.filter(r => r.type !== 'category_title')
- totalFiles = actualReports.length
- completedCount = actualReports.filter(r => r.status === 'completed').length
- progress = totalFiles > 0 ? Math.round((completedCount / totalFiles) * 100) : 100
- }
-
- return {
- type: message.type, // 'user' 或 'ai'
- content: userContent, // 使用提取的用户消息
- displayContent: displayContent,
- reports: reports, // 添加reports数组
- summary: summary, // 添加summary字段
- totalFiles: totalFiles, // 总文件数
- completedCount: completedCount, // 完成数
- progress: progress, // 进度
- file: file, // 添加文件对象
- isTyping: false,
- id: message.id,
- userFeedback: userFeedback,
- userQuestion: userQuestion, // AI消息对应的用户问题
- searchSources: message.type === 'ai' && message.search_source ? parseSearchSources(message.search_source) : null, // 解析搜索来源
- // 保存原始数据
- rawData: message,
- // 网络搜索数据(如果有)
- webSearchRaw: message.webSearchRaw || null,
- webSearchSummary: message.webSearchSummary || null,
- hasWebSearchResults: message.hasWebSearchResults || false,
- webSearchTotal: message.webSearchRaw?.total || 0,
- // 状态管理(历史记录默认完成状态)
- showStats: totalFiles > 0,
- currentStatus: 'completed',
- statusMessage: totalFiles > 0
- ? (message.webSearchRaw?.total > 0
- ? ` <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析 <span class="file-count">${totalFiles}</span> 个知识库文件,以及 <span class="file-count">${message.webSearchRaw.total}</span> 个相关网络资源`
- : ` <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析 <span class="file-count">${totalFiles}</span> 个知识库文件`)
- : ''
- }
- }))
-
- chatMessages.value = messages
- ai_conversation_id.value = conversationId
-
- const lastAIMessage = messages.filter(msg => msg.type === 'ai').pop()
-
- // 恢复所有AI消息的联网搜索结果、推荐问题和分类展开状态
- messages.forEach((message, index) => {
- if (message.type === 'ai' && message.rawData) {
- // 恢复联网搜索结果
- if (message.rawData.search_source) {
- try {
- const searchResults = JSON.parse(message.rawData.search_source)
- if (Array.isArray(searchResults) && searchResults.length > 0) {
- onlineSearchResults.value[message.id] = searchResults
- }
- } catch (error) {
- console.error('解析搜索结果失败:', error)
- }
- }
-
- // 恢复reports的分类展开状态
- if (message.reports && message.reports.length > 0) {
- if (!categoryExpandStates.value[index]) {
- categoryExpandStates.value[index] = {}
- }
-
- const categories = message.reports
- .filter(r => r.type === 'category_title')
- .map(r => r.category)
-
- categories.forEach(category => {
- categoryExpandStates.value[index][category] = false
- })
- }
-
- // 恢复推荐问题(只处理最后一条AI消息)
- if (message === lastAIMessage && message.rawData.guess_you_want) {
- try {
- const questions = message.rawData.guess_you_want.trim()
- .split('\n')
- .map(q => q.trim())
- .filter(q => q.length > 0)
- .filter((q, index, arr) => arr.indexOf(q) === index)
- .slice(0, 3)
-
- if (questions.length > 0) {
- aiRelatedQuestions.value = questions
- relatedQuestionsMessageId.value = message.id
- }
- } catch (error) {
- console.error('解析推荐问题失败:', error)
- }
- }
- }
- })
-
- // 等待DOM更新后绑定规范引用事件
- await nextTick()
- setTimeout(() => bindStandardReferenceEvents(), 100)
-
- return true
- } else {
- console.error('获取对话消息失败:', response.statusCode)
- return false
- }
- } catch (error) {
- console.error('获取对话消息失败:', error)
- return false
- }
- }
- // 生成对话标题(从内容中提取)
- const generateConversationTitle = (content) => {
- if (!content) return '未知对话'
-
- // 检查是否包含文件标签格式
- if (content.includes('</filesize>')) {
- // 提取</filesize>标签后面的内容
- const userMessage = content.split('</filesize>')[1]
- if (userMessage && userMessage.trim()) {
- // 清理多余的空格和换行
- const cleanMessage = userMessage.replace(/\s+/g, ' ').trim()
-
- // 提取第一句话作为标题,但排除AI回复的开头
- let firstSentence = cleanMessage.split(/[。!?\n]/)[0]
-
- // 如果包含AI回复的开头,只取用户问题部分
- if (firstSentence.includes('基于您好') || firstSentence.includes('蜀道安全管理AI智能助手')) {
- // 提取"问题描述:"后面的内容
- const problemMatch = firstSentence.match(/问题描述[::](.+?)(?=分析结果|$)/)
- if (problemMatch) {
- firstSentence = problemMatch[1].trim()
- } else {
- // 如果没有找到问题描述,取前20个字符
- firstSentence = firstSentence.substring(0, 20)
- }
- }
-
- // 限制标题长度
- if (firstSentence.length > 30) {
- return firstSentence.substring(0, 30) + '...'
- }
-
- return firstSentence || '新对话'
- }
- }
-
- // 如果没有文件标签,使用原来的方法
- let cleanContent = content.replace(/<[^>]*>/g, '')
- cleanContent = cleanContent.replace(/\s+/g, ' ').trim()
-
- // 提取第一句话作为标题,但排除AI回复的开头
- let firstSentence = cleanContent.split(/[。!?\n]/)[0]
-
- // 如果包含AI回复的开头,只取用户问题部分
- if (firstSentence.includes('基于您好') || firstSentence.includes('蜀道安全管理AI智能助手')) {
- // 提取"问题描述:"后面的内容
- const problemMatch = firstSentence.match(/问题描述[::](.+?)(?=查询结果|$)/)
- if (problemMatch) {
- firstSentence = problemMatch[1].trim()
- } else {
- // 如果没有找到问题描述,取前20个字符
- firstSentence = firstSentence.substring(0, 20)
- }
- }
-
- // 限制标题长度
- if (firstSentence.length > 30) {
- return firstSentence.substring(0, 30) + '...'
- }
-
- return firstSentence || '新对话'
- }
- // 格式化时间
- const formatTime = (timestamp) => {
- if (!timestamp) return '未知时间'
-
- let date
- if (typeof timestamp === 'string') {
- date = new Date(timestamp)
- } else {
- let timestampMs = timestamp
- if (timestamp.toString().length === 10 || timestamp.toString().length === 11) {
- timestampMs = timestamp * 1000
- }
- date = new Date(timestampMs)
- }
-
- const now = new Date()
- const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
- const yesterdayStart = new Date(todayStart.getTime() - 24 * 60 * 60 * 1000)
-
- if (date >= todayStart) {
- return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
- }
-
- if (date >= yesterdayStart && date < todayStart) {
- return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
- }
-
- const month = date.getMonth() + 1
- const day = date.getDate()
- const time = date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
- return `${month}月${day}日 ${time}`
- }
- // 转换用户反馈状态
- const convertUserFeedback = (feedback) => {
- switch (parseInt(feedback)) {
- case 2: return 'like'
- case 3: return 'dislike'
- default: return null
- }
- }
- // 转换前端反馈状态为后端格式
- const convertFeedbackToBackend = (feedback) => {
- switch (feedback) {
- case 'like': return 2
- case 'dislike': return 3
- default: return 0
- }
- }
- // 解析搜索来源数据
- const parseSearchSources = (searchSourceStr) => {
- try {
- if (!searchSourceStr || typeof searchSourceStr !== 'string' || !searchSourceStr.trim()) {
- return null
- }
-
- const sources = JSON.parse(searchSourceStr)
-
- if (!Array.isArray(sources)) {
- return null
- }
-
- const validSources = sources.filter(source =>
- source && typeof source === 'object' && source.title && source.content
- )
-
- return validSources.length > 0 ? validSources : null
- } catch (error) {
- console.error('解析搜索来源失败:', error)
- return null
- }
- }
- //对话id
- const ai_conversation_id = ref(0)
- //业务类型
- const business_type = ref(0)
- // 清理新对话状态
- const clearNewConversationState = () => {
- if (chatMessages.value.length === 0) {
- historyData.value.forEach(item => item.isActive = false)
- expandedSearchSources.value = {}
- expandedOnlineSearchResults.value = {}
- onlineSearchResults.value = {}
- }
- }
- // 根据当前模式分发发送请求
- const submitQuestionByCurrentMode = async (question, options = {}) => {
- const { windowSize = 3, nResults = 10 } = options
- const normalizedQuestion = typeof question === 'string' ? question.trim() : ''
- if (!normalizedQuestion) return
- if (currentMode.value === 'ai-writing' || currentMode.value === 'safety-training') {
- await handleNonStreamingSubmit({
- question: normalizedQuestion,
- businessType: currentMode.value === 'ai-writing' ? 2 : 1
- })
- return
- }
- await handleReportGeneratorSubmit({
- question: normalizedQuestion,
- windowSize,
- nResults
- })
- }
- // 发送消息
- const handleSendMessage = async () => {
- if (!messageText.value.trim() || isSending.value) return
-
- clearRecommendQuestions()
- aiRelatedQuestions.value = []
- relatedQuestionsMessageId.value = null
- isSending.value = true
- showChat.value = true
-
- clearNewConversationState()
- await submitQuestionByCurrentMode(messageText.value, {
- windowSize: 3,
- nResults: 10
- })
-
- messageText.value = ''
- clearRecommendQuestions()
-
- if (selectedFile.value) {
- removeSelectedFile()
- }
-
- scrollToBottom()
- }
- // 处理非流式请求 (AI写作 和 安全培训)
- const handleAIWritingStream = async (data) => {
- if (!isSending.value) {
- isSending.value = true
- }
- currentQuestion.value = data.question
- chatMessages.value.push({
- id: Date.now(),
- type: 'user',
- content: data.question,
- timestamp: new Date().toISOString()
- })
- const aiMessageIndex = chatMessages.value.length
- const aiMsgTimestamp = new Date().toISOString()
- chatMessages.value.push({
- id: Date.now() + 1,
- type: 'ai',
- userQuestion: data.question,
- isTyping: true,
- content: '',
- displayContent: '',
- timestamp: aiMsgTimestamp,
- reports: [],
- isAIWriting: true,
- aiWritingTitle: data.question,
- aiWritingStatusText: 'AI智能助手正在为您输出...',
- aiWritingStatus: 'generating',
- ai_message_id: null
- })
- aiWritingSidebarTitle.value = data.question
- aiWritingSidebarContent.value = ''
- aiWritingIsGenerating.value = true
- aiWritingSidebarVisible.value = true
- const aiMessage = chatMessages.value[aiMessageIndex]
- let fullContent = ''
- try {
- const apiPrefix = getApiPrefix()
- const url = `${apiPrefix}/stream/chat-with-db`
- const token = getToken()
- const headers = {
- 'Content-Type': 'application/json'
- }
- if (token) {
- headers['Authorization'] = `Bearer ${token}`
- }
- const response = await fetch(url, {
- method: 'POST',
- headers,
- body: JSON.stringify({
- message: data.question,
- ai_conversation_id: ai_conversation_id.value,
- business_type: data.businessType
- })
- })
- if (!response.ok) {
- throw new Error(`请求失败: ${response.status} ${response.statusText}`)
- }
- const reader = response.body.getReader()
- const decoder = new TextDecoder('utf-8')
- let buffer = ''
- let isDone = false
- while (!isDone) {
- const { done, value } = await reader.read()
- if (done) break
- buffer += decoder.decode(value, { stream: true })
- const lines = buffer.split('\n')
- buffer = lines.pop() || ''
- for (const line of lines) {
- if (!line.startsWith('data:')) continue
- const payload = line.slice(5).trim()
- if (!payload) continue
- if (payload === '[DONE]') {
- isDone = true
- break
- }
- let parsed = null
- if (payload.startsWith('{') && payload.endsWith('}')) {
- try {
- parsed = JSON.parse(payload)
- } catch (e) {
- parsed = null
- }
- }
- const isMeta =
- parsed &&
- (parsed.type ||
- parsed.ai_conversation_id ||
- parsed.ai_message_id ||
- parsed.error)
- if (isMeta) {
- if (parsed.type === 'initial') {
- if (parsed.ai_conversation_id) {
- ai_conversation_id.value = parsed.ai_conversation_id
- }
- if (parsed.ai_message_id) {
- aiMessage.ai_message_id = parsed.ai_message_id
- }
- }
- if (parsed.error) {
- throw new Error(parsed.error)
- }
- continue
- }
- const chunk = parsed && typeof parsed.content === 'string' ? parsed.content : payload
- const normalizedChunk = chunk.replace(/\\n/g, '\n')
- if (normalizedChunk) {
- fullContent += normalizedChunk
- aiMessage.fullContent = fullContent
- aiMessage.content = fullContent
- aiWritingSidebarContent.value = normalizeAiWritingText(fullContent)
- }
- }
- }
- aiMessage.isTyping = false
- aiMessage.aiWritingStatus = 'completed'
- aiMessage.aiWritingStatusText = '已按照要求输出文章,你可以基于当前结果进一步编辑整理~'
- aiWritingIsGenerating.value = false
- aiWritingFullContent.value = fullContent
- aiWritingSidebarVisible.value = false
- getHistoryRecordList()
- } catch (error) {
- console.error('AI写作流式请求失败:', error)
- aiMessage.isTyping = false
- aiMessage.aiWritingStatus = 'error'
- aiMessage.aiWritingStatusText = '生成失败,请重试'
- aiWritingIsGenerating.value = false
- aiWritingSidebarContent.value = normalizeAiWritingText(fullContent || '生成失败,请重试。')
- ElMessage.error(`请求失败: ${error.message}`)
- } finally {
- isSending.value = false
- }
- }
- const handleNonStreamingSubmit = async (data) => {
- if (data.businessType === 2) {
- await handleAIWritingStream(data)
- return
- }
- if (!isSending.value) {
- isSending.value = true
- }
- currentQuestion.value = data.question
-
- // 添加用户消息
- chatMessages.value.push({
- id: Date.now(),
- type: 'user',
- content: data.question,
- timestamp: new Date().toISOString()
- })
-
- // 添加AI消息占位符
- const aiMessageIndex = chatMessages.value.length
- const aiMsgTimestamp = new Date().toISOString()
- chatMessages.value.push({
- id: Date.now() + 1,
- type: 'ai',
- userQuestion: data.question,
- isTyping: true, // 显示 loading 状态
- content: '',
- displayContent: '',
- timestamp: aiMsgTimestamp,
- reports: [],
- // AI写作模式下,立即显示文件卡片和状态文字
- ...(data.businessType === 2 ? {
- isAIWriting: true,
- aiWritingTitle: data.question,
- aiWritingStatusText: 'AI智能助手正在为您输出...',
- aiWritingStatus: 'generating'
- } : {})
- })
-
- // AI写作模式:立即打开侧边栏,显示生成中状态
- if (data.businessType === 2) {
- aiWritingSidebarTitle.value = data.question
- aiWritingSidebarContent.value = ''
- aiWritingIsGenerating.value = true
- aiWritingSidebarVisible.value = true
- }
-
- try {
- const response = await apis.sendDeepseekMessage({
- message: data.question,
- business_type: data.businessType,
- enable_online_model: isOnlineModel.value,
- conversation_id: ai_conversation_id.value
- })
- if (response.statusCode === 200) {
- const aiMessage = chatMessages.value[aiMessageIndex]
- const responseData = response?.data || {}
- const aiReply =
- responseData.reply ||
- responseData.response ||
- responseData.content ||
- response.reply ||
- response.content ||
- ''
- const conversationId =
- responseData.ai_conversation_id ||
- responseData.conversation_id ||
- response.ai_conversation_id ||
- response.conversation_id
-
- // 如果用户已经点击了停止,则不再继续输出
- if (aiMessage._stopped) {
- return
- }
-
- if (!aiReply || typeof aiReply !== 'string') {
- throw new Error('AI返回内容为空')
- }
- aiMessage.isTyping = false
- aiMessage.content = aiReply
-
- // 更新 conversation ID
- if (conversationId) {
- ai_conversation_id.value = conversationId
- }
-
- // 添加打字机效果显示
- if (data.businessType === 1) {
- // 安全培训: 只展示一个输出文档
- aiMessage.isDocument = true
- aiMessage.displayContent = `<div class="safety-training-doc-card">
- <div class="doc-header">
- <span class="doc-icon">📄</span>
- <span class="doc-title">安全培训生成文档</span>
- </div>
- <div class="doc-actions">
- <button class="view-doc-btn">查看详情</button>
- </div>
- </div>`
- // 实际内容保存起来,点击查看详情时可以使用
- aiMessage.fullContent = aiReply
- } else if (data.businessType === 2) {
- // AI写作: 显示文件卡片 + 打开侧边栏输出
- aiMessage.isAIWriting = true
- aiMessage.aiWritingTitle = data.question
- aiMessage.fullContent = aiReply
- aiMessage.aiWritingStatus = 'completed' // 标记为已完成
- aiMessage.aiWritingStatusText = '已按照要求输出文章,你可以基于当前结果进一步编辑整理~'
-
- // 关闭侧边栏(生成完成)
- aiWritingSidebarVisible.value = false
- aiWritingIsGenerating.value = false
- } else {
- // 其他: 正常打字机输出
- startTypewriterEffect(aiMessage, aiReply, 30)
- }
-
- // 刷新历史记录
- getHistoryRecordList()
- } else {
- throw new Error(response.msg || '请求失败')
- }
- } catch (error) {
- console.error('发送请求失败:', error)
- const aiMessage = chatMessages.value[aiMessageIndex]
-
- if (aiMessage._stopped) {
- return
- }
-
- aiMessage.isTyping = false
- aiMessage.displayContent = '抱歉,生成内容时发生错误,请重试。'
- ElMessage.error(`请求失败: ${error.message}`)
- } finally {
- isSending.value = false
- }
- }
- // 功能卡片图标计数器
- let functionCardIconIndex = 0
- // 推荐问题图标计数器
- let questionIconIndex = 0
- // 根据功能卡片标题返回对应的图标
- const getFunctionCardIcon = (title) => {
- // 按顺序循环使用4个图标
- const icons = [bridgeIcon, constructionIcon, materialIcon, standardIcon]
- const icon = icons[functionCardIconIndex % icons.length]
- functionCardIconIndex++
- return icon
- }
- // 根据问题标题返回对应的图标
- const getQuestionIcon = (question) => {
- // 按顺序循环使用3个图标
- const icons = [questionIcon1, questionIcon2, questionIcon3]
- const icon = icons[questionIconIndex % icons.length]
- questionIconIndex++
- return icon
- }
- const getModeRecommendationType = (mode) => {
- if (mode === 'ai-writing') return 2
- if (mode === 'safety-training') return 1
- if (mode === 'exam-workshop') return 3
- return 0
- }
- const pickScopedRecommendationItems = (items, expectedType, typeField) => {
- if (!Array.isArray(items)) return []
- if (expectedType === 0) return items
- const hasTypeField = items.some(
- item => item && Object.prototype.hasOwnProperty.call(item, typeField)
- )
- if (!hasTypeField) {
- return null
- }
- return items.filter(item => Number(item?.[typeField]) === expectedType)
- }
- // 点击功能卡片
- // ReportGenerator相关方法
- const handleCategoryToggle = (messageIndex, data) => {
- if (!categoryExpandStates.value[messageIndex]) {
- categoryExpandStates.value[messageIndex] = {}
- }
- const matchedCategory = findCategoryStateKey(messageIndex, data.category)
- categoryExpandStates.value[messageIndex][matchedCategory || data.category] = data.expanded
- }
- const normalizeCategoryName = (category) => {
- return typeof category === 'string' ? category.trim() : ''
- }
- const findCategoryStateKey = (messageIndex, category) => {
- const stateMap = categoryExpandStates.value[messageIndex]
- if (!stateMap) return ''
- const normalizedCategory = normalizeCategoryName(category)
- if (!normalizedCategory) return ''
- if (Object.prototype.hasOwnProperty.call(stateMap, category)) {
- return category
- }
- const keys = Object.keys(stateMap)
- const exactKey = keys.find(key => normalizeCategoryName(key) === normalizedCategory)
- if (exactKey) return exactKey
- return keys.find(key => {
- const normalizedKey = normalizeCategoryName(key)
- return normalizedKey && (
- normalizedKey.includes(normalizedCategory) ||
- normalizedCategory.includes(normalizedKey)
- )
- }) || ''
- }
- const isCategoryExpanded = (messageIndex, category) => {
- if (!category) return true
- if (!categoryExpandStates.value[messageIndex]) {
- categoryExpandStates.value[messageIndex] = {}
- return false
- }
- const matchedCategory = findCategoryStateKey(messageIndex, category)
- if (!matchedCategory) return false
- return categoryExpandStates.value[messageIndex][matchedCategory] === true
- }
- // 处理安全培训文档点击
- const handleSafetyDocClick = (message) => {
- if (message.rawData && message.rawData.ai_conversation_id) {
- router.push({ path: '/safety-hazard', query: { id: message.rawData.ai_conversation_id } })
- } else if (ai_conversation_id.value) {
- router.push({ path: '/safety-hazard', query: { id: ai_conversation_id.value } })
- }
- }
- // 检查reports数组是否只包含分类标题,没有实际报告
- const hasOnlyCategoryTitles = (reports) => {
- if (!reports || reports.length === 0) return false
- // 检查是否所有报告都是category_title类型
- return reports.every(r => r.type === 'category_title')
- }
- // 将消息状态映射到头像状态
- const getAvatarStatus = (currentStatus, progress) => {
- if (progress === 100) return 'completed'
-
- switch (currentStatus) {
- case 'querying_kb':
- case 'web_searching':
- return 'searching'
- case 'analyzing_files':
- case 'analyzing_web':
- return 'analyzing'
- case 'deep_thinking':
- return 'thinking'
- case 'outputting':
- return 'analyzing'
- case 'completed':
- return 'completed'
- case 'error':
- return 'error'
- default:
- return 'idle'
- }
- }
- // 更新AI消息状态和进度
- const updateMessageStatus = (aiMessage, status, customMessage = null) => {
- const statusConfig = {
- querying_kb: {
- message: '🔍 <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析知识库……',
- progress: 10
- },
- web_searching: {
- message: '🌐 <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您联网分析……',
- progress: 15
- },
- data_retrieved: {
- message: null, // 动态生成
- progress: 30
- },
- analyzing_files: {
- message: '😊 <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析文件内容……',
- progress: 45
- },
- analyzing_web: {
- message: '😉 <span class="ai-name">蜀道安全管理AI智能助手</span>正在分析联网数据……',
- progress: 70
- },
- deep_thinking: {
- message: '🤔 <span class="ai-name">蜀道安全管理AI智能助手</span>正在深度思考中,请您稍等片刻……',
- progress: 75
- },
- outputting: {
- message: '😄 <span class="ai-name">蜀道安全管理AI智能助手</span>正在整理分析中!',
- progress: 90
- },
- completed: {
- message: null, // 动态生成
- progress: 100
- }
- }
-
- const config = statusConfig[status]
- if (config) {
- aiMessage.currentStatus = status
-
- // 对于data_retrieved状态,生成动态消息
- if (status === 'data_retrieved') {
- const kbCount = aiMessage.totalFiles || 0
- const webCount = aiMessage.webSearchTotal || 0
-
- if (webCount > 0) {
- aiMessage.statusMessage = `<span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析 <span class="file-count">${kbCount}</span> 个知识库文件,以及 <span class="file-count">${webCount}</span> 个相关网络资源`
- } else {
- aiMessage.statusMessage = `<span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析 <span class="file-count">${kbCount}</span> 个知识库文件`
- }
- } else if (status === 'completed') {
- // 对于completed状态,生成动态完成消息
- const kbCount = aiMessage.totalFiles || 0
- const webCount = aiMessage.webSearchTotal || 0
-
- if (webCount > 0) {
- aiMessage.statusMessage = `✅ <span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${kbCount}</span> 个知识库文件,以及 <span class="file-count">${webCount}</span> 个相关网络资源`
- } else {
- aiMessage.statusMessage = `✅ <span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${kbCount}</span> 个知识库文件`
- }
- } else {
- aiMessage.statusMessage = customMessage || config.message
- }
-
- aiMessage.progress = config.progress
- }
- }
- const handleSSEMessage = (data, aiMessageIndex) => {
- const aiMessage = chatMessages.value[aiMessageIndex]
- if (!aiMessage) return
-
- // 🔍 调试:打印SSE返回的完整数据对象
- console.log('🔍 SSE事件完整数据:', {
- type: data.type,
- conversation_id: data.conversation_id,
- message_id: data.message_id,
- ai_conversation_id: data.ai_conversation_id,
- ai_message_id: data.ai_message_id,
- allKeys: Object.keys(data)
- })
-
- // 捕获conversation_id(后端返回的字段名,可能是conversation_id或ai_conversation_id)
- const conversationId = data.conversation_id || data.ai_conversation_id
- if (conversationId) {
- if (ai_conversation_id.value === 0) {
- ai_conversation_id.value = conversationId
- console.log('✅ SSE收到conversation_id并赋值:', conversationId)
- }
- }
-
- // 捕获message_id(后端返回的字段名,可能是message_id或ai_message_id)
- const messageId = data.message_id || data.ai_message_id
- if (messageId) {
- if (!aiMessage.ai_message_id) {
- aiMessage.ai_message_id = messageId
- console.log('✅ SSE收到message_id并赋值:', messageId)
- console.log(' - aiMessage.id (前端临时ID):', aiMessage.id)
- console.log(' - aiMessage.ai_message_id (后端ID):', aiMessage.ai_message_id)
-
- // 同时更新rawData对象,确保操作按钮能够使用正确的ID
- if (!aiMessage.rawData) {
- aiMessage.rawData = {}
- }
- aiMessage.rawData.id = messageId
- console.log(' - aiMessage.rawData.id:', aiMessage.rawData.id)
- }
- }
-
- switch (data.type) {
- case 'intent':
- // 检查是否为专业问题
- if (data.is_professional_question === false) {
- // 非专业问题:立即隐藏状态显示组件
- aiMessage.showStats = false
- // 非专业问题,只输出summary字段内容并终止流程
- const summaryContent = data.summary || '抱歉,我暂时无法回答您的问题。'
- // 先缓存summary作为兜底内容,但继续等待online_answer/completed事件
- aiMessage.summary = summaryContent
- aiMessage._fullSummary = summaryContent
- break
- }
- // 专业问题:意图识别完成,更新为查询知识库状态
- updateMessageStatus(aiMessage, 'querying_kb')
- // 如果启用联网搜索,稍后会更新为web_searching状态
- // (当收到web_search_raw事件时)
- // 保存问题总结并使用打字机效果
- if (data.summary) {
- const fullSummary = data.summary
- aiMessage._fullSummary = fullSummary
- aiMessage.summary = ''
- // 使用打字机效果显示问题总结
- startReportFieldTypewriter(
- { file_index: 'summary', report: aiMessage, _typewriterStates: {} },
- 'summary',
- fullSummary,
- 50
- ).catch(err => {
- console.error('问题总结打字机效果失败:', err)
- aiMessage.summary = fullSummary
- })
- }
- break
- case 'online_answer': {
- aiMessage.showStats = false
- aiMessage.summary = ''
- const finalContent = data.content || ''
- aiMessage.content = finalContent
- if (!finalContent.trim()) {
- aiMessage.displayContent = ''
- aiMessage.isTyping = false
- break
- }
- const processedReply = processAIResponse(finalContent)
- const renderedReply = renderMarkdownContent(processedReply)
- startTypewriterEffect(aiMessage, renderedReply, 200)
- .catch(err => {
- console.error('在线回答打字机效果失败:', err)
- aiMessage.displayContent = renderedReply
- aiMessage.isTyping = false
- })
- break
- }
- case 'online_error':
- aiMessage.showStats = false
- aiMessage.content = data.message || '在线模型服务暂不可用'
- aiMessage.displayContent = renderMarkdownContent(processAIResponse(aiMessage.content))
- aiMessage.isTyping = false
- break
-
- case 'documents':
- aiMessage.totalFiles = data.total
- aiMessage.completedCount = 0
-
- // 收到文档数据后的状态处理
- if (isNetworkSearchEnabled.value) {
- // 如果启用了联网搜索,更新状态为联网搜索中
- updateMessageStatus(aiMessage, 'web_searching')
- // 等待web_search_raw事件后再更新为data_retrieved
- } else {
- // 如果没有联网搜索,直接显示检索结果
- updateMessageStatus(aiMessage, 'data_retrieved')
- }
-
- // 文档数量更新后,触发滚动检测以初始化进度卡片
- nextTick(() => {
- handleProgressCardScroll()
- })
- break
-
- case 'category_title':
- // 第一个分类标题时,说明开始分析文件
- if (aiMessage.reports.length === 0) {
- // 只有在当前状态进度 >= data_retrieved的进度时,才更新为analyzing_files
- // 这样确保data_retrieved状态能被看到
- if (aiMessage.progress >= 30) {
- updateMessageStatus(aiMessage, 'analyzing_files')
- }
- }
-
- const categoryTitle = {
- type: 'category_title',
- category: data.category,
- number: data.number,
- count: data.count,
- source_file: `【${data.number}、${data.category}】(共${data.count}个文件)`,
- file_index: -1,
- status: 'category'
- }
- aiMessage.reports.push(categoryTitle)
-
- // 初始化该分类为展开状态
- if (!categoryExpandStates.value[aiMessageIndex]) {
- categoryExpandStates.value[aiMessageIndex] = {}
- }
- categoryExpandStates.value[aiMessageIndex][data.category] = false
-
- // 保存当前分类名称,用于后续报告匹配
- aiMessage.currentCategory = data.category
- break
-
- case 'report_start':
- // 调试日志:查看完整的数据结构
- console.log('🔍 [DEBUG] report_start 数据:', {
- file_index: data.file_index,
- source_file: data.source_file,
- file_path: data.file_path,
- metadata: data.metadata,
- 完整data: data
- })
-
- const placeholderReport = {
- file_index: data.file_index,
- total_files: aiMessage.totalFiles,
- source_file: data.source_file,
- file_path: data.file_path,
- similarity: data.similarity,
- metadata: {
- ...data.metadata,
- _displayCategory: data.metadata?.primary_category || aiMessage.currentCategory // 存储当前显示的分类名
- },
- report: {
- display_name: '',
- summary: '',
- analysis: '',
- clauses: ''
- },
- status: 'streaming'
- }
- aiMessage.reports.push(placeholderReport)
- streamingReports.value.set(data.file_index, aiMessage.reports.length - 1)
- break
-
- case 'report_chunk':
- // 不再处理report_chunk,等待完整的report消息后用打字机效果显示
- // 这样可以避免与打字机效果冲突
- break
-
- case 'report':
- // 第一个报告开始时,更新到深度思考状态
- if (aiMessage.reports.filter(r => r.status === 'completed').length === 0) {
- updateMessageStatus(aiMessage, 'deep_thinking')
- }
-
- const reportData = data.data || data
-
- // 调试日志:查看完整的report数据
- console.log('🔍 [DEBUG] report 数据:', {
- file_index: reportData.file_index,
- source_file: reportData.source_file,
- file_path: reportData.file_path,
- metadata: reportData.metadata,
- 完整reportData: reportData
- })
-
- const idx = streamingReports.value.get(reportData.file_index)
-
- let targetReport
- if (idx !== undefined) {
- const displayCategory = reportData.metadata?.primary_category ||
- aiMessage.reports[idx].metadata?._displayCategory ||
- aiMessage.currentCategory
- const fullSummary = reportData.report?.summary || ''
- const fullAnalysis = reportData.report?.analysis || ''
- const fullClauses = reportData.report?.clauses || ''
- const fullDisplayName = reportData.report?.display_name || ''
-
- // 创建带空内容的报告对象,保留所有原始字段
- aiMessage.reports[idx] = {
- ...reportData, // 保留所有原始字段,包括可能的链接字段
- report: {
- display_name: fullDisplayName, // 直接显示
- summary: '',
- analysis: '',
- clauses: ''
- },
- status: 'completed',
- metadata: {
- ...reportData.metadata, // 保留所有metadata字段
- _displayCategory: displayCategory
- },
- _fullContent: {
- display_name: fullDisplayName,
- summary: fullSummary,
- analysis: fullAnalysis,
- clauses: fullClauses
- }
- }
- targetReport = aiMessage.reports[idx]
- streamingReports.value.delete(reportData.file_index)
- } else {
- const fullSummary = reportData.report?.summary || ''
- const fullAnalysis = reportData.report?.analysis || ''
- const fullClauses = reportData.report?.clauses || ''
- const fullDisplayName = reportData.report?.display_name || ''
-
- const newReport = {
- ...reportData, // 保留所有原始字段,包括可能的链接字段
- report: {
- display_name: fullDisplayName, // 直接显示
- summary: '',
- analysis: '',
- clauses: ''
- },
- status: 'completed',
- metadata: {
- ...reportData.metadata, // 保留所有metadata字段
- _displayCategory: reportData.metadata?.primary_category || aiMessage.currentCategory
- },
- _fullContent: {
- display_name: fullDisplayName,
- summary: fullSummary,
- analysis: fullAnalysis,
- clauses: fullClauses
- }
- }
- aiMessage.reports.push(newReport)
- targetReport = newReport
- }
-
- // 使用顺序打字机效果:概述 -> 解析 -> 相关条款
- if (targetReport._fullContent && !targetReport._typewriterCompleted) {
- // 标记打字机已启动,防止重复触发
- targetReport._typewriterStarted = true
-
- // 先打概述(速度200 = 每次20个字符,极快)
- startReportFieldTypewriter(targetReport, 'summary', targetReport._fullContent.summary || '', 200)
- .then(() => {
- // 概述完成后打解析
- return startReportFieldTypewriter(targetReport, 'analysis', targetReport._fullContent.analysis || '', 200)
- })
- .then(() => {
- // 解析完成后打相关条款
- if (targetReport._fullContent.clauses) {
- return startReportFieldTypewriter(targetReport, 'clauses', targetReport._fullContent.clauses || '', 200)
- }
- })
- .then(() => {
- // 全部完成,标记为已完成
- targetReport._typewriterCompleted = true
- })
- .catch(err => {
- console.error('报告打字机效果失败:', err)
- // 失败时直接显示完整内容
- targetReport.report.summary = targetReport._fullContent.summary || ''
- targetReport.report.analysis = targetReport._fullContent.analysis || ''
- targetReport.report.clauses = targetReport._fullContent.clauses || ''
- targetReport._typewriterCompleted = true
- })
-
- console.log('📝 [DEBUG] 报告打字机已启动:', {
- file_index: targetReport.file_index,
- summary_length: targetReport._fullContent.summary?.length || 0,
- analysis_length: targetReport._fullContent.analysis?.length || 0,
- clauses_length: targetReport._fullContent.clauses?.length || 0
- })
- }
-
- // 更新进度
- aiMessage.completedCount = aiMessage.reports.filter(r => r.status === 'completed' && r.type !== 'category_title').length
- const reportProgress = aiMessage.totalFiles > 0 ? (aiMessage.completedCount / aiMessage.totalFiles) : 0
-
- // 根据报告完成度更新状态
- if (reportProgress >= 1) {
- // 所有报告完成,进入输出阶段
- updateMessageStatus(aiMessage, 'outputting')
- } else if (reportProgress >= 0.5) {
- // 过半,深度思考
- updateMessageStatus(aiMessage, 'deep_thinking')
- } else {
- // 继续分析文件
- const currentProgress = 30 + Math.round(reportProgress * 30) // 30%~60%
- aiMessage.progress = currentProgress
- }
- break
-
- case 'web_search_raw':
- // 处理网络搜索原始数据
- if (data.results && data.results.length > 0) {
- aiMessage.webSearchRaw = {
- results: data.results || [],
- keywords: data.keywords || [],
- total: data.total || 0
- }
- aiMessage.webSearchTotal = data.total || 0
-
- // 更新状态显示:已检索到数据(联网搜索完成)
- const statusMsg = `<span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${aiMessage.totalFiles || 0}</span> 个知识库文件,以及 <span class="file-count">${aiMessage.webSearchTotal}</span> 个相关网络资源`
- updateMessageStatus(aiMessage, 'data_retrieved', statusMsg)
-
- console.log(`[网络搜索] 收到原始数据: ${data.total} 条结果`)
- } else {
- // 如果没有搜索结果,也要更新状态,但只显示知识库文件数
- const statusMsg = `<span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${aiMessage.totalFiles || 0}</span> 个知识库文件`
- updateMessageStatus(aiMessage, 'data_retrieved', statusMsg)
- console.log('[网络搜索] 无搜索结果,仅使用知识库')
- }
- break
-
- case 'web_search_summary':
- // 处理网络搜索AI总结 - 使用更快的打字机效果
- if (data.has_results && data.summary) {
- // 检查是否已经有内容,避免重复触发
- if (aiMessage._webSearchSummaryCompleted) {
- console.log('[网络搜索] 总结已完成,跳过重复打字机')
- break
- }
-
- // 保存完整内容
- aiMessage._fullWebSearchSummary = data.summary
- aiMessage.webSearchSummary = '' // 先置空,通过打字机填充
- aiMessage.hasWebSearchResults = true
-
- // 使用更快的打字机效果(速度200 = 每次20个字符)
- const summaryReport = {
- file_index: 'web_search_summary',
- report: aiMessage,
- _typewriterStates: {}
- }
-
- startReportFieldTypewriter(summaryReport, 'webSearchSummary', data.summary, 200)
- .then(() => {
- // 标记为已完成,防止重复触发
- aiMessage._webSearchSummaryCompleted = true
- })
- .catch(err => {
- console.error('网络搜索总结打字机效果失败:', err)
- aiMessage.webSearchSummary = data.summary
- aiMessage._webSearchSummaryCompleted = true
- })
-
- console.log('[网络搜索] 收到AI总结,长度:', data.summary.length)
-
- // 网络搜索总结已接收,准备保存并更新为完成状态
- updateMessageStatus(aiMessage, 'outputting')
-
- // 保存完整数据到后端 - 使用完整的summary而不是打字机过程中的部分内容
- if (aiMessage.ai_message_id) {
- const contentData = {
- reports: aiMessage.reports || [],
- webSearchRaw: aiMessage.webSearchRaw || null,
- webSearchSummary: aiMessage._fullWebSearchSummary || data.summary, // 使用完整的webSearchSummary
- hasWebSearchResults: true,
- // ===== 🔧 修复:将summary也包含在content JSON中 =====
- summary: aiMessage.summary || aiMessage._fullSummary || ''
- }
-
- const collectedContent = JSON.stringify(contentData)
-
- // 同时保存summary字段(作为单独字段)
- const summaryToSave = aiMessage.summary || aiMessage._fullSummary || ''
-
- updateAIMessageContent(aiMessage.ai_message_id, collectedContent, summaryToSave)
- .then((response) => {
- console.log('[网络搜索] AI消息保存成功,更新为完成状态')
- // 保存成功后,更新状态为completed
- updateMessageStatus(aiMessage, 'completed')
- aiMessage.isTyping = false
- isSending.value = false
- streamingReports.value.clear()
-
- // 重置AI回复流程状态
- isAIReplyProcessComplete.value = true
- })
- .catch(err => {
- console.error('[网络搜索] AI消息保存失败:', err)
- // 即使保存失败,也更新为完成状态
- updateMessageStatus(aiMessage, 'completed')
- aiMessage.isTyping = false
- isSending.value = false
- })
- } else {
- // 没有ai_message_id时,直接更新为完成状态
- updateMessageStatus(aiMessage, 'completed')
- aiMessage.isTyping = false
- isSending.value = false
- }
- }
- break
-
- case 'error':
- ElMessage.error(data.message)
- isSending.value = false
- break
-
- case 'completed':
- console.log('[SSE] 收到completed事件')
- isSending.value = false
- streamingReports.value.clear()
- aiMessage.isTyping = false
-
- // 只有在还未完成时才更新状态
- if (aiMessage.progress < 100) {
- updateMessageStatus(aiMessage, 'completed')
- }
-
- ElMessage.success('报告生成完成')
- break
-
- case 'interrupted':
- isSending.value = false
- streamingReports.value.clear()
- aiMessage.isTyping = false
- ElMessage.warning(data.message || '报告生成已中断')
- break
- }
- }
- const handleSSEError = (error) => {
- console.error('❌ SSE连接异常断开:', error)
-
- // 清理SSE连接
- if (sseConnection) {
- closeSSEConnection(sseConnection)
- sseConnection = null
- }
-
- isSending.value = false
- streamingReports.value.clear()
-
- // 将所有正在打字的AI消息标记为完成
- chatMessages.value.forEach(message => {
- if (message.type === 'ai' && message.isTyping) {
- message.isTyping = false
- }
- })
-
- // 重置AI回复流程状态
- isAIReplyProcessComplete.value = true
-
- // 这是非预期的连接断开(网络错误、后端崩溃等)
- ElMessage.error('连接已断开')
- }
- const handleSSEComplete = () => {
- isSending.value = false
-
- chatMessages.value.forEach(message => {
- if (message.type === 'ai' && message.isTyping) {
- message.isTyping = false
-
- if (message.ai_message_id) {
- // 构建完整的内容数据,包含报告、网络搜索结果和summary
- const contentData = {
- reports: message.reports || [],
- webSearchRaw: message.webSearchRaw || null,
- // 使用完整的webSearchSummary,而不是打字机过程中的部分内容
- webSearchSummary: message._fullWebSearchSummary || message.webSearchSummary || null,
- hasWebSearchResults: message.hasWebSearchResults || false,
- // ===== 🔧 修复:将summary也包含在content JSON中 =====
- summary: message.summary || message._fullSummary || ''
- }
-
- const collectedContent = message.reports && message.reports.length > 0
- ? JSON.stringify(contentData)
- : (message.content || message._fullSummary || message.summary || '')
-
- if (collectedContent) {
- // 同时保存summary字段(作为单独字段)
- const summaryToSave = message.summary || message._fullSummary || ''
-
- updateAIMessageContent(message.ai_message_id, collectedContent, summaryToSave)
- .catch(err => console.error('回写AI消息失败:', err))
- }
- }
- }
- })
-
- isAIReplyProcessComplete.value = true
-
- // ===== 🎯 更新历史记录列表并高亮 =====
- console.log('📝 AI回复完成,准备更新历史记录')
- console.log(' - ai_conversation_id:', ai_conversation_id.value)
-
- if (ai_conversation_id.value && ai_conversation_id.value !== 0) {
- console.log('✅ 开始更新历史记录列表')
-
- // 先清除所有高亮
- historyData.value.forEach((item) => {
- item.isActive = false
- })
-
- // 获取第一条用户消息作为标题
- const firstUserMessage = chatMessages.value.find(msg => msg.type === 'user')
- const title = firstUserMessage ? firstUserMessage.content.substring(0, 20) + '...' : '新对话'
- console.log('📝 生成的标题:', title)
-
- // 检查是否已存在
- const existingIndex = historyData.value.findIndex(item => item.id === ai_conversation_id.value)
- console.log('🔍 检查是否已存在,索引:', existingIndex)
-
- if (existingIndex === -1) {
- // 不存在,在最前面插入新项
- const newItem = {
- id: ai_conversation_id.value,
- title: title,
- time: formatTime(new Date().toISOString()),
- businessType: 0,
- isActive: true,
- rawData: {
- id: ai_conversation_id.value,
- content: firstUserMessage?.content || '',
- updated_at: new Date().toISOString()
- }
- }
- console.log('📦 准备插入的新项:', newItem)
- historyData.value.unshift(newItem)
- console.log('✅ 已在列表最前面插入新历史记录并设为高亮')
- console.log('📊 更新后的历史记录数量:', historyData.value.length)
- } else {
- // 已存在,设为高亮并移到最前面
- console.log('🔄 历史记录已存在,将其移到最前面')
- const existingItem = historyData.value.splice(existingIndex, 1)[0]
- existingItem.isActive = true
- existingItem.time = formatTime(new Date().toISOString())
- historyData.value.unshift(existingItem)
- console.log('✅ 已将现有历史记录移到最前面并设为高亮')
- }
-
- // 更新历史记录总数
- historyTotal.value = historyData.value.length
- console.log('📊 最终历史记录总数:', historyTotal.value)
- } else {
- console.warn('⚠️ ai_conversation_id 为 0 或未设置,跳过历史记录更新')
- }
-
- // ===== 🎯 获取AI相关推荐问题 =====
- console.log('🎯 准备获取AI相关推荐问题')
- // 找到最后一条用户消息和最后一条AI消息
- const lastUserMessage = chatMessages.value.filter(msg => msg.type === 'user').pop()
- const lastAIMessage = chatMessages.value.filter(msg => msg.type === 'ai').pop()
-
- if (lastUserMessage && lastAIMessage && lastAIMessage.ai_message_id) {
- console.log('📝 找到最后一条用户消息和AI消息')
- console.log(' - 用户消息:', lastUserMessage.content)
- console.log(' - AI消息ID:', lastAIMessage.ai_message_id)
-
- // 构建AI回复内容用于生成推荐问题
- let aiReplyContent = ''
-
- // 优先使用summary字段
- if (lastAIMessage.summary) {
- aiReplyContent = lastAIMessage.summary
- }
- // 其次使用content字段
- else if (lastAIMessage.content) {
- aiReplyContent = lastAIMessage.content
- }
- // 如果有reports,使用reports的summary
- else if (lastAIMessage.reports && lastAIMessage.reports.length > 0) {
- const summaries = lastAIMessage.reports
- .filter(r => r.report && r.report.summary)
- .map(r => r.report.summary)
- .slice(0, 3) // 只取前3个
- aiReplyContent = summaries.join('\n\n')
- }
-
- if (aiReplyContent && aiReplyContent.trim()) {
- console.log('📝 AI回复内容长度:', aiReplyContent.length)
- // 获取AI相关推荐问题
- getAIRelatedQuestions(
- lastUserMessage.content,
- aiReplyContent,
- lastAIMessage.ai_message_id
- )
- } else {
- console.warn('⚠️ AI回复内容为空,跳过推荐问题获取')
- }
- } else {
- console.warn('⚠️ 未找到有效的用户消息或AI消息,跳过推荐问题获取')
- }
- }
- const handleSSEInterrupted = (data) => {
- if (sseConnection) {
- closeSSEConnection(sseConnection)
- sseConnection = null
- }
-
- isSending.value = false
- streamingReports.value.clear()
-
- chatMessages.value.forEach(message => {
- if (message.type === 'ai' && message.isTyping) {
- message.isTyping = false
-
- // 中断时设置为完成状态
- updateMessageStatus(message, 'completed')
-
- // 保留已接收的网络搜索数据
- // 即使中断,也要确保已接收的webSearchRaw和webSearchSummary能够显示
- if (message.webSearchRaw || message.webSearchSummary) {
- console.log('✅ 保留已接收的网络搜索数据')
- }
-
- if (message.ai_message_id) {
- // 构建完整的内容数据,包含报告、网络搜索结果和summary
- const contentData = {
- reports: message.reports || [],
- webSearchRaw: message.webSearchRaw || null,
- // 使用完整的webSearchSummary,而不是打字机过程中的部分内容
- webSearchSummary: message._fullWebSearchSummary || message.webSearchSummary || null,
- hasWebSearchResults: message.hasWebSearchResults || false,
- // ===== 🔧 修复:将summary也包含在content JSON中 =====
- summary: message.summary || message._fullSummary || ''
- }
-
- const collectedContent = message.reports && message.reports.length > 0
- ? JSON.stringify(contentData)
- : (message.content || message._fullSummary || message.summary || '')
-
- if (collectedContent) {
- // 同时保存summary字段(作为单独字段)
- const summaryToSave = message.summary || message._fullSummary || ''
-
- updateAIMessageContent(message.ai_message_id, collectedContent, summaryToSave)
- .catch(err => console.error('回写AI消息失败:', err))
- }
- }
- }
- })
-
- isAIReplyProcessComplete.value = true
- ElMessage.warning(data.message || '报告生成已中断')
- }
- const handleCancel = () => {
- if (sseConnection) {
- closeSSEConnection(sseConnection)
- sseConnection = null
- }
- isSending.value = false
- ElMessage.warning('已取消生成')
- }
- // 停止报告生成
- const handleStopGeneration = async () => {
- if (ai_conversation_id.value === undefined || ai_conversation_id.value === null) {
- return
- }
-
- if (sseConnection) {
- closeSSEConnection(sseConnection)
- sseConnection = null
- }
-
- isSending.value = false
- streamingReports.value.clear()
- clearAllTypeIntervals()
-
- chatMessages.value.forEach(message => {
- if (message.type === 'ai' && message.isTyping) {
- message.isTyping = false
- message._stopped = true
-
- // 停止时设置为完成状态
- updateMessageStatus(message, 'completed')
-
- // 保留已接收的网络搜索数据
- // 即使停止,也要确保已接收的webSearchRaw和webSearchSummary能够显示
- if (message.webSearchRaw || message.webSearchSummary) {
- console.log('✅ 停止时保留已接收的网络搜索数据')
- }
-
- // 回写数据到后端,包含网络搜索结果和summary
- if (message.ai_message_id) {
- const contentData = {
- reports: message.reports || [],
- webSearchRaw: message.webSearchRaw || null,
- // 使用完整的webSearchSummary,而不是打字机过程中的部分内容
- webSearchSummary: message._fullWebSearchSummary || message.webSearchSummary || null,
- hasWebSearchResults: message.hasWebSearchResults || false,
- // ===== 🔧 修复:将summary也包含在content JSON中 =====
- summary: message.summary || message._fullSummary || ''
- }
-
- const collectedContent = message.reports && message.reports.length > 0
- ? JSON.stringify(contentData)
- : (message.content || message._fullSummary || message.summary || '')
-
- if (collectedContent) {
- // 同时保存summary字段(作为单独字段)
- const summaryToSave = message.summary || message._fullSummary || ''
-
- updateAIMessageContent(message.ai_message_id, collectedContent, summaryToSave)
- .catch(err => console.error('回写AI消息失败:', err))
- }
- }
- }
- })
-
- isAIReplyProcessComplete.value = true
- ElMessage.success('已停止生成')
-
- // ===== 已删除:getUserId() - stopSSEStream 函数需要更新 =====
- stopSSEStream(null, ai_conversation_id.value)
- .catch(error => console.warn('停止请求失败:', error))
- }
- // ReportGenerator提交处理
- const handleReportGeneratorSubmit = async (data) => {
- isSending.value = true
- currentQuestion.value = data.question
-
- // 添加用户消息
- chatMessages.value.push({
- id: Date.now(),
- type: 'user',
- content: data.question,
- timestamp: new Date().toISOString()
- })
-
- // 添加AI消息占位符
- const aiMessageIndex = chatMessages.value.length
- chatMessages.value.push({
- id: Date.now() + 1,
- type: 'ai',
- userQuestion: data.question, // 用户问题
- summary: '',
- totalFiles: 0,
- webSearchTotal: 0,
- progress: 0,
- completedCount: 0,
- reports: [],
- isTyping: true,
- content: '',
- displayContent: '',
- timestamp: new Date().toISOString(),
- // 新增:状态管理
- currentStatus: 'querying_kb', // 当前状态
- statusMessage: '🔍 <span class="ai-name">蜀道安全管理AI智能助手</span>正在从知识库中学习相关信息……', // 状态消息
- showStats: true, // 是否显示统计卡片
- // 新增:后端消息ID(初始为null,从SSE接收后赋值)
- ai_message_id: null,
- rawData: null,
- userFeedback: null
- })
-
- // 等待DOM更新后触发滚动检测,初始化进度卡片状态
- nextTick(() => {
- setTimeout(() => {
- handleProgressCardScroll()
- }, 100)
- })
-
- try {
- const apiPrefix = getApiPrefix()
- const url = `${apiPrefix}/report/complete-flow`
- // 构建 POST 请求体
- const requestBody = {
- user_question: data.question,
- window_size: data.windowSize,
- n_results: 10,
- ai_conversation_id: ai_conversation_id.value,
- is_network_search_enabled: isNetworkSearchEnabled.value,
- enable_online_model: isOnlineModel.value
- }
- console.log('📤 发起 SSE POST 请求:', {
- url,
- body: requestBody
- })
- sseConnection = createSSEConnection(url, {
- onMessage: (eventData) => handleSSEMessage(eventData, aiMessageIndex),
- onError: handleSSEError,
- onComplete: handleSSEComplete,
- onInterrupted: handleSSEInterrupted
- }, {
- body: requestBody
- })
- } catch (error) {
- console.error('启动失败:', error)
- ElMessage.error(`启动失败: ${error.message}`)
- isSending.value = false
- }
- }
- const handleFunctionCard = async (cardType) => {
- clearAllTypeIntervals()
- chatMessages.value = []
- ai_conversation_id.value = 0
- showChat.value = true
-
- await submitQuestionByCurrentMode(`请详细介绍${cardType}的相关内容`, {
- windowSize: 3,
- nResults: 10
- })
- }
- // 点击推荐问题
- const handleRecommendedQuestion = async (question) => {
- clearAllTypeIntervals()
- chatMessages.value = []
- ai_conversation_id.value = 0
- showChat.value = true
-
- await submitQuestionByCurrentMode(question, {
- windowSize: 3,
- nResults: 10
- })
- }
- // 点击用户推荐问题
- const handleUserRecommendQuestion = async (question) => {
- clearRecommendQuestions()
- showChat.value = true
- if (chatMessages.value.length === 0) {
- clearNewConversationState()
- }
-
- await submitQuestionByCurrentMode(question, {
- windowSize: 3,
- nResults: 10
- })
- }
- // 点击历史记录
- const handleHistoryItem = async (historyItem) => {
- if (isSending.value) return
-
- if (speakingMessageId.value) {
- stopAllAudio()
- speakingMessageId.value = null
- }
-
- clearAllTypeIntervals()
- expandedSearchSources.value = {}
- expandedOnlineSearchResults.value = {}
- onlineSearchResults.value = {}
- isAIReplyProcessComplete.value = true
- selectedHistoryItem.value = historyItem
-
- // 设置当前问题为历史记录的标题
- currentQuestion.value = historyItem.title
-
- historyData.value.forEach(item => {
- item.isActive = item.id === historyItem.id
- })
-
- showChat.value = true
-
- const loadingMessage = {
- type: 'ai',
- content: '正在加载历史对话...',
- displayContent: '正在加载历史对话...',
- isTyping: true,
- id: Date.now() + 1,
- userFeedback: null
- }
- chatMessages.value = [loadingMessage]
-
- try {
- const success = await getConversationMessages(historyItem.id)
-
- if (success) {
- chatMessages.value = chatMessages.value.filter(msg => msg.id !== loadingMessage.id)
-
- // 根据历史记录的业务类型进行跳转或模式切换
- const bType = Number(historyItem.businessType)
- if (bType === 3) {
- router.push({ path: '/exam-workshop', query: { historyId: historyItem.id } })
- return
- } else if (bType === 2) {
- currentMode.value = 'ai-writing'
- } else if (bType === 1) {
- currentMode.value = 'safety-training'
- } else {
- currentMode.value = 'ai-qa'
- }
-
- await nextTick()
- scrollToBottom()
-
- if (aiRelatedQuestions.value.length > 0) {
- setTimeout(() => scrollToBottom(), 200)
- }
- } else {
- chatMessages.value = [{
- type: 'ai',
- content: '抱歉,加载历史对话失败,请稍后重试。',
- displayContent: '抱歉,加载历史对话失败,请稍后重试。',
- isTyping: false,
- id: Date.now() + 1,
- userFeedback: null
- }]
-
- await nextTick()
- scrollToBottom()
- }
- } catch (error) {
- console.error('加载历史对话失败:', error)
- chatMessages.value = [{
- type: 'ai',
- content: '抱歉,加载历史对话时发生错误,请稍后重试。',
- displayContent: '抱歉,加载历史对话时发生错误,请稍后重试。',
- isTyping: false,
- id: Date.now() + 1,
- userFeedback: null
- }]
-
- await nextTick()
- scrollToBottom()
- }
- }
- // 删除历史记录
- const deleteHistoryItem = (historyItem, index) => {
- deleteTargetItem.value = { item: historyItem, index: index }
- deleteType.value = 'history'
- showDeleteModal.value = true
- }
- // 统一的确认删除函数
- const confirmDelete = async () => {
- if (!deleteTargetItem.value) return
-
- if (deleteType.value === 'history') {
- await confirmDeleteHistory()
- } else if (deleteType.value === 'message') {
- await confirmDeleteMessage()
- }
- }
- // 确认删除历史记录
- const confirmDeleteHistory = async () => {
- const { item: historyItem, index } = deleteTargetItem.value
-
- try {
- // 调用删除接口
- const response = await apis.deleteHistoryRecord({
- ai_conversation_id: historyItem.id
- })
-
- if (response.statusCode === 200) {
- historyData.value.splice(index, 1)
-
- // 更新历史记录总数
- historyTotal.value = historyData.value.length
-
- if (historyItem.isActive) {
- await createNewChat()
- }
-
- ElMessage.success('删除成功')
- } else {
- ElMessage.error(response.msg || '删除失败')
- }
- } catch (error) {
- console.error('删除失败:', error)
- ElMessage.error('删除失败,请稍后重试')
- } finally {
- showDeleteModal.value = false
- deleteTargetItem.value = null
- deleteType.value = ''
- }
- }
- // 确认删除消息
- const confirmDeleteMessage = async () => {
- const { messageIndex } = deleteTargetItem.value
-
- try {
- const aiMessage = chatMessages.value[messageIndex]
-
- // 优先使用ai_message_id(后端消息ID),其次使用rawData.id
- const messageId = aiMessage.ai_message_id || (aiMessage.rawData && aiMessage.rawData.id)
-
- if (aiMessage && messageId) {
- const response = await apis.deleteConversation({
- ai_message_id: messageId
- })
-
- if (response.statusCode === 200) {
- chatMessages.value.splice(messageIndex, 1)
- if (messageIndex > 0) {
- chatMessages.value.splice(messageIndex - 1, 1)
- }
- ElMessage.success('删除成功')
- } else {
- ElMessage.error('删除失败,请稍后重试')
- }
- } else {
- chatMessages.value.splice(messageIndex, 1)
- ElMessage.success('删除成功')
- }
- } catch (error) {
- console.error('删除失败:', error)
- ElMessage.error('删除失败,请稍后重试')
- } finally {
- showDeleteModal.value = false
- deleteTargetItem.value = null
- deleteType.value = ''
- }
- }
- // 取消删除
- const cancelDelete = () => {
- showDeleteModal.value = false
- deleteTargetItem.value = null
- deleteType.value = ''
- }
- // 新建聊天
- const createNewChat = async () => {
- if (isSending.value) return
-
- if (speakingMessageId.value) {
- stopAllAudio()
- speakingMessageId.value = null
- }
-
- clearAllTypeIntervals()
-
- ai_conversation_id.value = 0
- chatMessages.value = []
- messageText.value = ''
- currentQuestion.value = '' // 清空当前问题
- selectedFile.value = null
- showChat.value = false
- aiRelatedQuestions.value = []
- relatedQuestionsMessageId.value = null
- onlineSearchResults.value = {}
- expandedOnlineSearchResults.value = {}
- expandedSearchSources.value = {}
-
- historyData.value.forEach(item => item.isActive = false)
-
- await getHistoryRecordList()
- }
- // 语音输入
- const handleVoiceClick = () => {
- isListening.value ? stopVoiceInput() : startVoiceInput()
- }
- const startVoiceInput = () => {
- const success = startListening()
- if (!success) {
- ElMessage.error('语音识别启动失败,请检查麦克风权限')
- }
- }
- const stopVoiceInput = () => {
- stopListening()
- if (transcript.value.trim()) {
- messageText.value = transcript.value
- }
- }
- // 当前播放的音频对象
- const currentAudio = ref(null)
- // 音频队列管理
- const audioQueue = ref([])
- const isPlayingQueue = ref(false)
- // 获取TTS服务地址(自动判断是否使用代理)
- const getTTSUrl = () => {
- // 在开发环境中使用代理,生产环境中使用直接地址
- const isDevelopment = import.meta.env.DEV
- if (isDevelopment) {
- return '/api/tts/voice' // 使用Vite代理
- } else {
- return window.location.origin + '/tts/voice' // 生产环境直接地址
- }
- }
- // 测试TTS服务连接
- const testTTSConnection = async () => {
- const ttsUrl = getTTSUrl()
-
- try {
- const controller = new AbortController()
- const timeoutId = setTimeout(() => controller.abort(), 8000)
-
- // 准备请求头,添加认证 Token
- const headers = { 'Content-Type': 'application/json' }
- const token = getToken()
- const tokenType = getTokenType()
- if (token && tokenType) {
- // 确保 Bearer 首字母大写
- const bearerType = tokenType.charAt(0).toUpperCase() + tokenType.slice(1).toLowerCase()
- headers['Authorization'] = `${bearerType} ${token}`
- }
-
- const response = await fetch(ttsUrl, {
- method: 'POST',
- headers,
- body: JSON.stringify({ text: '测试' }),
- signal: controller.signal
- })
-
- clearTimeout(timeoutId)
-
- if (response.ok) {
- await response.blob()
- return { success: true, message: 'TTS服务连接正常' }
- } else {
- return { success: false, message: `TTS服务响应错误: ${response.status}` }
- }
- } catch (error) {
- let message = 'TTS服务连接失败'
- if (error.name === 'AbortError') {
- message = 'TTS服务连接超时'
- } else if (error.message.includes('Failed to fetch')) {
- message = '无法连接到TTS服务'
- }
- return { success: false, message }
- }
- }
- // 调用TTS接口进行语音合成(带重试机制)
- const callTTSAPI = async (text, retryCount = 0) => {
- const ttsUrl = getTTSUrl()
- const maxRetries = 2
-
- try {
- const controller = new AbortController()
- const timeoutId = setTimeout(() => controller.abort(), 15000)
-
- // 准备请求头,添加认证 Token
- const headers = { 'Content-Type': 'application/json' }
- const token = getToken()
- const tokenType = getTokenType()
- if (token && tokenType) {
- // 确保 Bearer 首字母大写
- const bearerType = tokenType.charAt(0).toUpperCase() + tokenType.slice(1).toLowerCase()
- headers['Authorization'] = `${bearerType} ${token}`
- }
-
- const response = await fetch(ttsUrl, {
- method: 'POST',
- headers,
- body: JSON.stringify({ text }),
- signal: controller.signal
- })
-
- clearTimeout(timeoutId)
-
- if (!response.ok) {
- throw new Error(`TTS接口调用失败: ${response.status}`)
- }
-
- const audioBlob = await response.blob()
- if (audioBlob.size === 0) {
- throw new Error('TTS接口返回的音频数据为空')
- }
-
- return URL.createObjectURL(audioBlob)
- } catch (error) {
- // 重试逻辑
- if (retryCount < maxRetries && (
- error.name === 'AbortError' ||
- error.message.includes('Failed to fetch') ||
- error.message.includes('NetworkError')
- )) {
- await new Promise(resolve => setTimeout(resolve, (retryCount + 1) * 1000))
- return callTTSAPI(text, retryCount + 1)
- }
-
- // 错误信息
- let errorMessage = '语音合成失败'
- if (error.name === 'AbortError') {
- errorMessage = '语音合成请求超时'
- } else if (error.message.includes('Failed to fetch')) {
- errorMessage = '无法连接到语音合成服务'
- } else if (error.message.includes('TTS接口调用失败')) {
- errorMessage = error.message
- }
-
- const detailedError = new Error(errorMessage)
- detailedError.originalError = error
- throw detailedError
- }
- }
- // 清理文本内容,移除HTML标签和非文本字符
- const cleanTextForTTS = (text) => {
- if (!text) return ''
-
- // 移除HTML标签
- let cleanText = text.replace(/<[^>]*>/g, '')
-
- // 移除多余的空白字符
- cleanText = cleanText.replace(/\s+/g, ' ').trim()
-
- // 移除特殊字符,保留中文、英文、数字和基本标点
- cleanText = cleanText.replace(/[^\u4e00-\u9fa5a-zA-Z0-9\s,。!?、;:""''()【】《》]/g, '')
-
- return cleanText
- }
- // 将长文本分块处理(第一块较小,后续块较大)
- const splitTextIntoChunks = (text) => {
- if (text.length <= 60) {
- return [text]
- }
-
- const chunks = []
- let currentChunk = ''
- let isFirstChunk = true
-
- // 按句子分割
- const sentences = text.split(/[。!?]/)
-
- for (const sentence of sentences) {
- if (sentence.trim().length === 0) continue
-
- const sentenceWithPunctuation = sentence + (sentence.match(/[。!?]$/) ? '' : '。')
-
- // 第一块限制为60字,后续块限制为200字
- const maxLength = isFirstChunk ? 60 : 200
-
- if (currentChunk.length + sentenceWithPunctuation.length <= maxLength) {
- currentChunk += sentenceWithPunctuation
- } else {
- if (currentChunk.length > 0) {
- chunks.push(currentChunk.trim())
- currentChunk = sentenceWithPunctuation
- isFirstChunk = false // 第一块已完成
- } else {
- // 如果单个句子就超过最大长度,强制分割
- const maxLen = isFirstChunk ? 60 : 200
- chunks.push(sentenceWithPunctuation.substring(0, maxLen))
- currentChunk = sentenceWithPunctuation.substring(maxLen)
- isFirstChunk = false
- }
- }
- }
-
- if (currentChunk.trim().length > 0) {
- chunks.push(currentChunk.trim())
- }
-
- return chunks
- }
- // 播放音频
- const playAudio = (audioUrl) => {
- return new Promise((resolve, reject) => {
- const audio = new Audio(audioUrl)
- currentAudio.value = audio
-
- audio.onended = () => {
- currentAudio.value = null
- resolve()
- }
-
- audio.onerror = (error) => {
- currentAudio.value = null
- reject(error)
- }
-
- audio.play().catch(error => {
- currentAudio.value = null
- reject(error)
- })
- })
- }
- // 停止所有音频播放
- const stopAllAudio = () => {
- try {
- if (currentAudio.value) {
- currentAudio.value.pause()
- currentAudio.value.currentTime = 0
- currentAudio.value = null
- }
-
- audioQueue.value = []
- isPlayingQueue.value = false
- window.speechSynthesis && window.speechSynthesis.cancel()
- } catch (e) {
- console.warn('停止音频播放失败:', e)
- }
- }
- // 优化后的并行预加载音频并播放队列
- const playAudioQueue = async (chunks, messageId) => {
- if (speakingMessageId.value !== messageId) return
-
- try {
- const firstAudioUrl = await callTTSAPI(chunks[0])
- if (speakingMessageId.value !== messageId) {
- URL.revokeObjectURL(firstAudioUrl)
- return
- }
-
- const remainingChunks = chunks.slice(1)
- const remainingPromises = remainingChunks.map(async (chunk, index) => {
- try {
- const audioUrl = await callTTSAPI(chunk)
- return { index: index + 1, audioUrl }
- } catch (error) {
- return { index: index + 1, audioUrl: null }
- }
- })
-
- await playAudio(firstAudioUrl)
- URL.revokeObjectURL(firstAudioUrl)
-
- if (speakingMessageId.value !== messageId) {
- const remainingResults = await Promise.allSettled(remainingPromises)
- remainingResults.forEach(result => {
- if (result.status === 'fulfilled' && result.value.audioUrl) {
- URL.revokeObjectURL(result.value.audioUrl)
- }
- })
- return
- }
-
- const remainingResults = await Promise.allSettled(remainingPromises)
- if (speakingMessageId.value !== messageId) {
- remainingResults.forEach(result => {
- if (result.status === 'fulfilled' && result.value.audioUrl) {
- URL.revokeObjectURL(result.value.audioUrl)
- }
- })
- return
- }
-
- isPlayingQueue.value = true
- for (const result of remainingResults) {
- if (speakingMessageId.value !== messageId) break
-
- if (result.status === 'fulfilled' && result.value.audioUrl) {
- try {
- await playAudio(result.value.audioUrl)
- URL.revokeObjectURL(result.value.audioUrl)
- } catch (error) {
- console.error('音频播放失败:', error)
- }
- }
- }
-
- isPlayingQueue.value = false
- } catch (error) {
- console.error('音频队列播放失败:', error)
- isPlayingQueue.value = false
- }
- }
- // 语音朗读相关方法
- const handleVoiceRead = async (message) => {
- if (speakingMessageId.value === message.id) {
- // 如果正在朗读这条消息,则停止
- stopAllAudio()
- speakingMessageId.value = null
- } else {
- // 如果朗读其他消息,先停止当前朗读
- if (speakingMessageId.value) {
- stopAllAudio()
- speakingMessageId.value = null
- }
-
- const textToRead = message.displayContent || message.content
- if (textToRead && textToRead.trim()) {
- try {
- const cleanText = cleanTextForTTS(textToRead)
-
- if (cleanText.length === 0) {
- ElMessage.warning('文本内容为空,无法进行语音合成')
- return
- }
-
- speakingMessageId.value = message.id
-
- if (cleanText.length <= 60) {
- const audioUrl = await callTTSAPI(cleanText)
- await playAudio(audioUrl)
- URL.revokeObjectURL(audioUrl)
- } else {
- const chunks = splitTextIntoChunks(cleanText)
- await playAudioQueue(chunks, message.id)
- }
- } catch (error) {
- console.error('语音合成失败:', error)
- ElMessage.error('语音合成失败,请稍后重试')
- } finally {
- speakingMessageId.value = null
- isPlayingQueue.value = false
- }
- }
- }
- }
- // 检查消息是否正在朗读
- const isSpeaking = (messageId) => {
- return speakingMessageId.value === messageId
- }
- // 删除弹窗相关方法
- const handleDeleteClick = (messageIndex) => {
- console.log('点击删除按钮,消息索引:', messageIndex)
-
- // 检查是否只剩一句AI回复和一句用户发言
- if (chatMessages.value.length === 2) {
- ElMessage.warning('第一句话无法删除')
- return
- }
-
- // 设置删除类型和要删除的消息索引
- deleteType.value = 'message'
- deleteTargetItem.value = { messageIndex: messageIndex }
- showDeleteModal.value = true
- }
- // 处理输入框输入,限制2000字
- const handleInput = () => {
- if (messageText.value.length > 2000) {
- messageText.value = messageText.value.substring(0, 2000)
- ElMessage.warning('消息长度不能超过2000字')
- }
-
- // 防抖获取推荐问题
- if (recommendQuestionsTimer.value) {
- clearTimeout(recommendQuestionsTimer.value)
- }
-
- // 如果输入内容为空,清空推荐问题
- if (!messageText.value.trim()) {
- userRecommendQuestions.value = []
- return
- }
-
- // 延迟500ms后获取推荐问题,避免频繁调用
- recommendQuestionsTimer.value = setTimeout(() => {
- getUserRecommendQuestions(messageText.value)
- }, 100)
- }
- // 触发文件上传
- const triggerFileUpload = () => {
- if (selectedFile.value) {
- ElMessage.warning('只能上传一个文件,请先删除当前文件')
- return
- }
- fileInput.value?.click()
- }
- // 读取Word文件内容
- const readWordFile = async (file) => {
- try {
- if (file.size === 0) throw new Error('Word文件为空')
- if (!mammoth) throw new Error('Word文档解析库未正确加载')
-
- const fileExtension = file.name.toLowerCase().split('.').pop()
- const arrayBuffer = await file.arrayBuffer()
-
- // 检查文件格式
- if (fileExtension === 'docx') {
- const uint8Array = new Uint8Array(arrayBuffer.slice(0, 2))
- if (uint8Array[0] !== 0x50 || uint8Array[1] !== 0x4B) {
- throw new Error('文件不是有效的.docx格式,可能已损坏')
- }
- } else if (fileExtension === 'doc') {
- throw new Error('检测到.doc格式文件。请将文件另存为.docx格式后重新上传。')
- }
-
- const result = await mammoth.extractRawText({ arrayBuffer })
- return result.value
- } catch (error) {
- console.error('Word文件读取失败:', error)
-
- if (error.message.includes('Can\'t find end of central directory')) {
- throw new Error('文件格式错误:这不是一个有效的Word文档,或者文件已损坏。')
- } else if (error.message.includes('Invalid file format')) {
- throw new Error('Word文件格式无效或已损坏')
- } else {
- throw error
- }
- }
- }
- // 处理文件选择
- const handleFileSelect = async (event) => {
- const file = event.target.files[0]
- if (!file) return
-
- try {
- const fileExtension = validateFile(file)
- if (!mammoth) {
- throw new Error('Word文档解析库未正确加载,请刷新页面重试')
- }
-
- isUploadingFile.value = true
- const extractedContent = await readWordFile(file)
-
- selectedFile.value = {
- file,
- name: file.name,
- size: file.size,
- type: fileExtension,
- icon: getFileIcon(fileExtension),
- content: extractedContent
- }
-
- ElMessage.success(`文件读取成功,共提取 ${extractedContent.length} 个字符`)
- } catch (error) {
- console.error('文件读取失败:', error)
- ElMessage.error(error.message || '文件读取失败,请重试')
- } finally {
- isUploadingFile.value = false
- event.target.value = ''
- }
- }
- // 删除选中的文件
- const removeSelectedFile = () => {
- if (selectedFile.value) {
- selectedFile.value = null
- }
- }
- // 获取功能卡片数据
- const getFunctionCards = async () => {
- try {
- console.log('开始获取功能卡片...')
- const requestMode = currentMode.value
- const functionType = getModeRecommendationType(requestMode)
- const response = await apis.getFunctionCard({ function_type: functionType })
- console.log('功能卡片响应:', response)
-
- if (response.statusCode === 200) {
- if (currentMode.value !== requestMode) {
- console.log('模式已切换,忽略旧的功能卡片结果:', requestMode, '->', currentMode.value)
- return
- }
- const scopedCards = pickScopedRecommendationItems(
- response.data,
- functionType,
- 'function_type'
- )
- if (scopedCards === null) {
- console.warn('功能卡片接口未返回类型字段,当前模式继续使用默认卡片:', requestMode)
- return
- }
- functionCards.value = scopedCards
- console.log('功能卡片数据已设置:', functionCards.value)
- } else {
- console.error('获取功能卡片失败:', response.statusCode)
- }
- } catch (error) {
- console.error('获取功能卡片失败:', error)
- }
- }
- // 获取热点问题数据
- const getHotQuestions = async () => {
- try {
- console.log('开始获取热点问题...')
- const requestMode = currentMode.value
- const questionType = getModeRecommendationType(requestMode)
- const response = await apis.getHotQuestion({ question_type: questionType })
- console.log('热点问题响应:', response)
-
- if (response.statusCode === 200) {
- if (currentMode.value !== requestMode) {
- console.log('模式已切换,忽略旧的热点问题结果:', requestMode, '->', currentMode.value)
- return
- }
- const scopedQuestions = pickScopedRecommendationItems(
- response.data,
- questionType,
- 'question_type'
- )
- if (scopedQuestions === null) {
- console.warn('热点问题接口未返回类型字段,当前模式继续使用默认问题:', requestMode)
- return
- }
- hotQuestions.value = scopedQuestions
- console.log('热点问题数据已设置:', hotQuestions.value)
- } else {
- console.error('获取热点问题失败:', response.statusCode)
- }
- } catch (error) {
- console.error('获取热点问题失败:', error)
- }
- }
- // 监听模式变化,重新获取卡片和问题
- watch(currentMode, () => {
- functionCards.value = []
- hotQuestions.value = []
- getFunctionCards()
- getHotQuestions()
- })
- // 清除推荐问题
- const clearRecommendQuestions = () => {
- userRecommendQuestions.value = []
- if (recommendQuestionsTimer.value) {
- clearTimeout(recommendQuestionsTimer.value)
- recommendQuestionsTimer.value = null
- }
- }
- // 处理容器点击事件
- const handleContainerClick = (event) => {
- // 如果点击的不是推荐问题区域,则清除推荐问题
- if (!event.target.closest('.user-recommend-questions')) {
- clearRecommendQuestions()
- }
-
- // 如果点击的不是网络搜索胶囊或侧边栏,则关闭侧边栏
- if (webSearchSidebarVisible.value &&
- !event.target.closest('.web-search-capsule-outer') &&
- !event.target.closest('.web-search-sidebar')) {
- webSearchSidebarVisible.value = false
- }
- }
- // 切换联网搜索状态
- const toggleNetworkSearch = () => {
- isNetworkSearchEnabled.value = !isNetworkSearchEnabled.value
- ElMessage[isNetworkSearchEnabled.value ? 'success' : 'info'](
- isNetworkSearchEnabled.value ? '联网搜索已启用' : '联网搜索已关闭'
- )
- }
- // 切换搜索来源展开状态
- const toggleSearchSources = (messageId) => {
- expandedSearchSources.value[messageId] = !expandedSearchSources.value[messageId]
- }
- // 切换联网搜索结果展开状态
- const toggleOnlineSearchResults = (messageId) => {
- expandedOnlineSearchResults.value[messageId] = !expandedOnlineSearchResults.value[messageId]
- }
- // 打开链接
- const openUrl = (url) => {
- if (!url || typeof url !== 'string' || !url.trim()) {
- ElMessage.warning('链接地址无效')
- return
- }
-
- try {
- let targetUrl = url.trim()
- if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
- targetUrl = 'https://' + targetUrl
- }
- window.open(targetUrl, '_blank', 'noopener,noreferrer')
- } catch (error) {
- console.error('打开链接失败:', error)
- ElMessage.error('无法打开链接')
- }
- }
- // 打开搜索来源链接
- const openSearchSource = openUrl
- // 打开联网搜索结果链接
- const openSearchResult = openUrl
- // 处理提问联想点击
- const handleRelatedQuestion = (question) => {
- aiRelatedQuestions.value = []
- relatedQuestionsMessageId.value = null
- messageText.value = question
- handleSendMessage()
- }
- // 获取用户推荐问题
- const getUserRecommendQuestions = async (userMessage) => {
- if (!userMessage || !userMessage.trim() || isSending.value || hasTypingMessage.value) {
- userRecommendQuestions.value = []
- return
- }
-
- try {
- isGettingRecommendQuestions.value = true
-
- const response = await apis.getUserRecommendQuestion({
- user_message: userMessage.trim()
- // ===== 已删除:user_id - 后端从token解析 =====
- })
-
- if (isSending.value || hasTypingMessage.value) {
- userRecommendQuestions.value = []
- return
- }
-
- if (response.statusCode === 200 && response.data && response.data.questions) {
- userRecommendQuestions.value = response.data.questions
- } else {
- userRecommendQuestions.value = []
- }
- } catch (error) {
- console.error('获取推荐问题失败:', error)
- userRecommendQuestions.value = []
- } finally {
- isGettingRecommendQuestions.value = false
- }
- }
- // 联网搜索功能
- const performOnlineSearch = async (userInput, messageId) => {
- if (!userInput || userInput.trim() === '') {
- console.log('用户输入为空,跳过搜索')
- return
- }
-
- if (!messageId) {
- console.error('消息ID为空,无法进行联网搜索')
- return
- }
-
- try {
- console.log('开始联网搜索,用户输入:', userInput, '消息ID:', messageId)
- isGettingOnlineSearch.value = true
- onlineSearchLoadingMessages.value.add(messageId)
-
- const response = await apis.onlineSearch({
- keywords: userInput.trim()
- })
-
- console.log('联网搜索结果:', response)
-
- if (response.statusCode === 200 && response.results) {
- try {
- // 解析搜索结果
- const results = response.results
-
-
- // 处理数据格式,确保有必要的字段
- const processedResults = results.map((result, index) => ({
- title: result.title || `搜索结果 ${index + 1}`,
- content: result.content || '暂无内容',
- url: result.url || null
- }))
-
- // 先保存搜索结果并立即显示
- onlineSearchResults.value[messageId] = processedResults
-
- // 设置联网搜索结果默认收起
- expandedOnlineSearchResults.value[messageId] = false
-
- console.log('联网搜索结果已保存,消息ID:', messageId, '结果数量:', processedResults.length)
- console.log('处理后的搜索结果:', processedResults)
- console.log('联网搜索结果已设置为默认收起')
-
- // 保存联网搜索结果到数据库
- try {
- const saveData = {
- id: messageId,
- ai_conversation_id: ai_conversation_id.value,
- search_source: JSON.stringify(processedResults)
- }
-
- const saveResponse = await apis.saveOnlineSearchResult(saveData)
- console.log('联网搜索结果保存到数据库成功:', saveResponse)
- } catch (saveError) {
- console.error('保存联网搜索结果到数据库失败:', saveError)
- }
-
- // 返回搜索结果,但不立即显示
- return processedResults
- } catch (parseError) {
- console.error('解析联网搜索结果失败:', parseError)
- onlineSearchResults.value[messageId] = []
- }
- } else {
- console.error('联网搜索失败:', response.statusCode)
- onlineSearchResults.value[messageId] = []
- }
- } catch (error) {
- console.error('联网搜索请求失败:', error)
- onlineSearchResults.value[messageId] = []
- } finally {
- isGettingOnlineSearch.value = false
- onlineSearchLoadingMessages.value.delete(messageId)
- }
- }
- // 获取AI回复相关推荐问题
- const getAIRelatedQuestions = async (userMessage, aiReply, messageId) => {
- if (!userMessage || !aiReply || !messageId) {
- console.log('参数不完整,跳过相关推荐问题获取')
- return
- }
-
- try {
- console.log('开始获取AI回复相关推荐问题')
- console.log('用户问题:', userMessage)
- console.log('AI回复:', aiReply.substring(0, 100) + '...')
- console.log('消息ID:', messageId)
-
- isGettingRelatedQuestions.value = true
-
- // 设计提示词让大模型返回3条相关推荐问题
- const prompt = `基于以下对话内容,直接生成3条相关的推荐问题。
- 【对话内容】
- 用户问题:${userMessage}
- AI回复:${aiReply}
- 【生成要求】
- - 直接输出3个问题,每个问题一行
- - 问题要与原问题相关但有所延伸
- - 问题要具体、实用,符合中文表达习惯
- - 不要包含任何编号、标题、说明文字
- - 不要重复上述指令内容`
-
- const response = await apis.guessYouWant({
- message: prompt,
- // ===== 已删除:user_id - 后端从token解析 =====
- ai_message_id: messageId
- })
-
- console.log('AI相关推荐问题响应:', response)
-
- if (response.statusCode === 200 && response.data && response.data.reply) {
- // 解析大模型返回的推荐问题
- const replyText = response.data.reply.trim()
- const questions = replyText.split('\n')
- .map(q => q.trim())
- .filter(q => q.length > 0)
- // 过滤掉包含提示词、标题、说明文字的行
- .filter(q => {
- // 过滤包含特定关键词的行
- const excludeKeywords = ['请生成', '推荐问题', '相关问题', '生成要求', '对话内容', '【', '】', '指令']
- return !excludeKeywords.some(keyword => q.includes(keyword))
- })
- // 过滤掉以"-"或"•"开头的行(通常是说明文字)
- .filter(q => !q.startsWith('-') && !q.startsWith('•') && !q.startsWith('*'))
- // 移除可能的编号前缀(1. 2. 3. 或 1、2、3、)
- .map(q => q.replace(/^[0-9]+[\.\、]\s*/, ''))
- .filter(q => q.length > 0)
- // 过滤掉包含冒号的行(通常是标题)
- .filter(q => !q.includes(':') && !q.includes(':'))
- .filter((q, index, arr) => arr.indexOf(q) === index) // 去重
- .slice(0, 3) // 只取前3个
-
- if (questions.length > 0) {
- aiRelatedQuestions.value = questions
- relatedQuestionsMessageId.value = messageId
- console.log('✅ AI相关推荐问题数据已设置:')
- console.log(' - 推荐问题数量:', questions.length)
- console.log(' - 推荐问题内容:', questions)
- console.log(' - 关联消息ID:', messageId)
-
- // 只需要等待DOM更新即可,不需要滚动到底部
- await nextTick()
- console.log('✅ DOM已更新,推荐问题已显示')
- } else {
- console.log('解析推荐问题失败,使用默认问题')
- aiRelatedQuestions.value = []
- relatedQuestionsMessageId.value = null
- }
- } else {
- console.error('获取AI相关推荐问题失败:', response.statusCode)
- aiRelatedQuestions.value = []
- relatedQuestionsMessageId.value = null
- }
- } catch (error) {
- console.error('获取AI相关推荐问题失败:', error)
- aiRelatedQuestions.value = []
- relatedQuestionsMessageId.value = null
- } finally {
- isGettingRelatedQuestions.value = false
- }
- }
- // 文件处理工具函数
- const validateFile = (file) => {
- // 检查文件大小
- if (file.size > fileConfig.maxSize) {
- throw new Error('文件大小不能超过20MB')
- }
-
- // 检查文件类型
- const fileExtension = '.' + file.name.split('.').pop().toLowerCase()
-
- // 支持的扩展名列表(对应于 input 的 accept 属性)
- const supportedExtensions = ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.txt']
-
- if (!supportedExtensions.includes(fileExtension)) {
- throw new Error(`不支持的文件格式: ${fileExtension}。支持的格式: 图片、文档、表格、PPT、PDF等。`)
- }
-
- return fileExtension
- }
- // 获取文件图标
- const getFileIcon = (fileType) => {
- const type = fileType.toLowerCase()
- if (['.doc', '.docx'].includes(type)) {
- return wordDocIcon
- } else if (['.xls', '.xlsx'].includes(type)) {
- return new URL('../assets/chat/excel.png', import.meta.url).href
- } else if (['.ppt', '.pptx'].includes(type)) {
- return new URL('../assets/chat/ppt.png', import.meta.url).href
- } else if (type === '.pdf') {
- return new URL('../assets/chat/pdf.png', import.meta.url).href
- } else if (['.png', '.jpg', '.jpeg', '.gif'].includes(type)) {
- return new URL('../assets/chat/image.png', import.meta.url).href
- } else if (type === '.txt') {
- return new URL('../assets/chat/txt.png', import.meta.url).href
- }
- return '📎'
- }
- // 滚动到底部
- const scrollToBottom = () => {
- nextTick(() => {
- const chatContent = document.querySelector('.chat-content')
- if (chatContent) {
- chatContent.scrollTop = chatContent.scrollHeight
- }
- })
- }
- // 检查是否在底部
- const isAtBottom = () => {
- const chatContent = document.querySelector('.chat-content')
- if (!chatContent) return true
-
- const threshold = 3.125 // 50px的容差 (50px)
- return chatContent.scrollHeight - chatContent.scrollTop - chatContent.clientHeight < threshold
- }
- // 格式化文件大小
- const formatFileSize = (bytes) => {
- if (bytes === 0) return '0 B'
- const k = 1024
- const sizes = ['B', 'KB', 'MB', 'GB']
- const i = Math.floor(Math.log(bytes) / Math.log(k))
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
- }
- // 编辑用户消息
- const editUserMessage = (message) => {
- console.log('编辑用户消息:', message.content)
- messageText.value = message.content
-
- // 恢复文件信息
- if (message.file) {
- selectedFile.value = message.file
- console.log('恢复文件信息:', message.file.name)
- }
-
- // 聚焦到输入框
- const inputElement = document.querySelector('.message-input')
- if (inputElement) {
- inputElement.focus()
- inputElement.setSelectionRange(inputElement.value.length, inputElement.value.length)
- }
- }
- // 重新生成AI回复
- const regenerateResponse = async (messageIndex) => {
- console.log('重新生成回复,消息索引:', messageIndex)
-
- // 找到对应的用户消息
- if (messageIndex > 0) {
- const userMessage = chatMessages.value[messageIndex - 1]
- if (userMessage && userMessage.type === 'user') {
- console.log('重新发送用户消息:', userMessage.content)
-
- // 恢复消息文本和文件信息
- messageText.value = userMessage.content
-
- // 恢复文件信息
- if (userMessage.file) {
- selectedFile.value = userMessage.file
- }
-
- await handleSendMessage()
- }
- }
- }
- // 复制功能
- const copyToClipboard = async (text) => {
- try {
- await navigator.clipboard.writeText(text)
- ElMessage.success('复制成功')
- } catch (err) {
- // 降级方案:使用传统复制方法
- const textArea = document.createElement('textarea')
- textArea.value = text
- document.body.appendChild(textArea)
- textArea.select()
- document.execCommand('copy')
- document.body.removeChild(textArea)
- ElMessage.success('复制成功')
- }
- }
- // 复制用户消息
- const copyUserMessage = (message) => {
- copyToClipboard(message.content)
- }
- // 复制AI消息
- const copyAIMessage = (message) => {
- // 优先使用summary(非专业问题的回复),然后是displayContent,最后是content
- let textToCopy = message.summary || message.displayContent || message.content
-
- // 如果包含HTML标签,转换为纯文本
- if (textToCopy && textToCopy.includes('<')) {
- // 创建临时DOM元素来提取纯文本
- const tempDiv = document.createElement('div')
- tempDiv.innerHTML = textToCopy
- textToCopy = tempDiv.textContent || tempDiv.innerText || textToCopy
- }
-
- // 如果还是没有内容,尝试从reports中提取
- if (!textToCopy && message.reports && message.reports.length > 0) {
- textToCopy = message.reports
- .filter(r => r.type !== 'category_title')
- .map(r => r.report || '')
- .join('\n\n')
- }
-
- // 如果有网络搜索总结,也添加进去
- if (message.webSearchSummary) {
- textToCopy = textToCopy
- ? `${textToCopy}\n\n【网络搜索总结】\n${message.webSearchSummary}`
- : message.webSearchSummary
- }
-
- if (textToCopy && textToCopy.trim()) {
- copyToClipboard(textToCopy)
- } else {
- ElMessage.warning('暂无可复制的内容')
- }
- }
- // 点赞和点踩功能
- const handleThumbsUp = async (message) => {
- console.log('点赞消息:', message.id)
-
- // 如果已经点赞,则取消点赞
- if (message.userFeedback === 'like') {
- message.userFeedback = null
- } else {
- // 设置点赞,取消点踩
- message.userFeedback = 'like'
- }
-
- // 强制触发Vue响应式更新
- chatMessages.value = [...chatMessages.value]
-
- // 同步反馈到后端
- await syncFeedbackToBackend(message)
- }
- const handleThumbsDown = async (message) => {
- console.log('点踩消息:', message.id)
-
- // 如果已经点踩,则取消点踩
- if (message.userFeedback === 'dislike') {
- message.userFeedback = null
- } else {
- // 设置点踩,取消点赞
- message.userFeedback = 'dislike'
- }
-
- // 强制触发Vue响应式更新
- chatMessages.value = [...chatMessages.value]
-
- // 同步反馈到后端
- await syncFeedbackToBackend(message)
- }
- // 同步用户反馈到后端
- const syncFeedbackToBackend = async (message) => {
- try {
- console.log('🔍 syncFeedbackToBackend 收到的message对象:', {
- id: message.id,
- ai_message_id: message.ai_message_id,
- rawData: message.rawData,
- rawData_id: message.rawData?.id
- })
-
- // 优先使用ai_message_id,其次使用rawData.id
- const messageId = message.ai_message_id || (message.rawData && message.rawData.id)
-
- if (!messageId) {
- console.warn('❌ 消息缺少ID,无法同步反馈')
- console.warn(' - message.ai_message_id:', message.ai_message_id)
- console.warn(' - message.rawData:', message.rawData)
- return
- }
-
- const feedback = convertFeedbackToBackend(message.userFeedback)
- console.log('✅ 同步反馈到后端:', {
- messageId: messageId,
- feedback: feedback
- })
-
- // 调用后端点赞点踩接口
- const response = await apis.likeAndDislike({
- id: messageId,
- user_feedback: feedback
- })
-
- if (response.statusCode === 200) {
- console.log('反馈同步成功')
- // 根据反馈类型显示不同提示
- if (feedback === 2) {
- ElMessage.success('点赞成功')
- } else if (feedback === 3) {
- ElMessage.success('点踩成功')
- } else {
- ElMessage.success('已取消反馈')
- }
- } else {
- console.error('反馈同步失败:', response.msg)
- ElMessage.error('反馈提交失败,请稍后重试')
- }
-
- } catch (error) {
- console.error('同步反馈失败:', error)
- ElMessage.error('反馈同步失败,请稍后重试')
- }
- }
- // 自动发送消息功能
- const autoSendMessage = async (message) => {
- if (!message || !message.trim()) return
-
- console.log('自动发送消息:', message)
-
- // 显示聊天界面
- showChat.value = true
-
- // 如果是新对话,清除所有历史记录的选中状态
- if (chatMessages.value.length === 0) {
- historyData.value.forEach((item) => {
- item.isActive = false
- })
- console.log('自动发送新对话,清除所有历史记录的选中状态')
-
- // 清除所有展开状态
- expandedSearchSources.value = {}
- expandedOnlineSearchResults.value = {}
-
- // 清除之前的联网搜索结果,避免重复显示
- onlineSearchResults.value = {}
- }
-
- // 清除AI相关推荐问题
- aiRelatedQuestions.value = []
- relatedQuestionsMessageId.value = null
-
- // 与直接发送一致:按当前模式分发到对应接口
- await submitQuestionByCurrentMode(message, {
- windowSize: 3,
- nResults: 10
- })
- }
- // 初始化中括号缩放补偿
- const initBracketZoomCompensation = () => {
- try {
- // 检测系统缩放比例
- const devicePixelRatio = window.devicePixelRatio || 1
- // console.log('🔍 检测到系统缩放比例:', devicePixelRatio)
-
- // 设置CSS变量,用于CSS缩放补偿
- document.documentElement.style.setProperty('--system-zoom', devicePixelRatio)
-
- // 如果系统缩放不是100%,应用补偿
- if (devicePixelRatio !== 1) {
- const compensationScale = 1 / devicePixelRatio
- // console.log('📐 应用中括号缩放补偿:', compensationScale)
-
- // 动态更新CSS样式
- const style = document.createElement('style')
- style.id = 'bracket-zoom-compensation'
-
- // 移除旧的样式(如果存在)
- const oldStyle = document.getElementById('bracket-zoom-compensation')
- if (oldStyle) {
- oldStyle.remove()
- }
-
- // 添加新的样式
- document.head.appendChild(style)
-
- // console.log('✅ 中括号缩放补偿已应用')
- } else {
- // console.log('🔄 系统缩放100%,无需补偿')
- }
-
- // 监听窗口大小变化,重新检测缩放
- const handleResize = () => {
- setTimeout(() => {
- initBracketZoomCompensation()
- }, 100)
- }
-
- window.addEventListener('resize', handleResize)
-
- // 返回清理函数
- return () => {
- window.removeEventListener('resize', handleResize)
- const style = document.getElementById('bracket-zoom-compensation')
- if (style) {
- style.remove()
- }
- }
-
- } catch (error) {
- console.error('❌ 中括号缩放补偿初始化失败:', error)
- }
- }
- // 处理文件引用和链接点击
- const handleStandardReferenceClick = async (event) => {
- const target = event.target
-
- // 检查是否是链接胶囊或其子元素
- const linkCapsule = target.closest('.link-capsule')
- if (linkCapsule) {
- event.preventDefault()
- event.stopPropagation()
-
- const href = linkCapsule.getAttribute('data-link') || linkCapsule.getAttribute('href')
- if (href && href !== '#') {
- // 使用iframe打开链接
- showLinkInIframe(href)
- }
- return
- }
-
- // 原有的标准引用处理逻辑
- if (!target.classList.contains('standard-reference')) return
-
- event.preventDefault()
- event.stopPropagation()
-
- const fileName = target.getAttribute('data-standard') || target.getAttribute('data-reference')
-
- if (fileName) {
- try {
- const response = await apis.getFileLink({ fileName })
-
- if (response.statusCode === 200 && response.data) {
- if (response.data) {
- window.open(response.data, '_blank')
- } else {
- ElMessage.warning('暂无文件')
- }
- } else {
- ElMessage.warning('暂无文件')
- }
- } catch (error) {
- console.error('获取文件失败:', error)
- ElMessage.error('获取文件失败,请稍后重试')
- }
- }
- }
- // 在iframe中显示链接
- const showLinkInIframe = (url) => {
- // 检查URL是否有效
- try {
- new URL(url)
- } catch {
- ElMessage.error('无效的链接地址')
- return
- }
-
- // 创建一个模态框显示iframe
- const modal = document.createElement('div')
- modal.style.cssText = `
- position: fixed;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- background: rgba(0, 0, 0, 0.5);
- z-index: 10000;
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 20px;
- `
-
- const container = document.createElement('div')
- container.style.cssText = `
- width: 90%;
- height: 90%;
- background: white;
- border-radius: 12px;
- overflow: hidden;
- display: flex;
- flex-direction: column;
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
- `
-
- const header = document.createElement('div')
- header.style.cssText = `
- padding: 16px 20px;
- background: #f5f5f5;
- border-bottom: 1px solid #e0e0e0;
- display: flex;
- align-items: center;
- justify-content: space-between;
- `
-
- const urlDisplay = document.createElement('div')
- urlDisplay.style.cssText = `
- font-size: 14px;
- color: #666;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- flex: 1;
- margin-right: 16px;
- `
- urlDisplay.textContent = url
-
- const closeBtn = document.createElement('button')
- closeBtn.textContent = '✕'
- closeBtn.style.cssText = `
- background: none;
- border: none;
- font-size: 24px;
- color: #666;
- cursor: pointer;
- padding: 0;
- width: 32px;
- height: 32px;
- display: flex;
- align-items: center;
- justify-content: center;
- border-radius: 4px;
- transition: all 0.2s;
- `
- closeBtn.onmouseover = () => {
- closeBtn.style.background = '#e0e0e0'
- }
- closeBtn.onmouseout = () => {
- closeBtn.style.background = 'none'
- }
- closeBtn.onclick = () => {
- document.body.removeChild(modal)
- }
-
- const iframe = document.createElement('iframe')
- iframe.src = url
- iframe.style.cssText = `
- width: 100%;
- height: 100%;
- border: none;
- `
-
- header.appendChild(urlDisplay)
- header.appendChild(closeBtn)
- container.appendChild(header)
- container.appendChild(iframe)
- modal.appendChild(container)
-
- // 点击背景关闭
- modal.onclick = (e) => {
- if (e.target === modal) {
- document.body.removeChild(modal)
- }
- }
-
- document.body.appendChild(modal)
- }
- // 文件预览处理函数
- const handleFilePreview = (data) => {
- if (typeof data === 'string') {
- previewFilePath.value = data
- previewFileName.value = ''
- } else {
- previewFilePath.value = data.filePath
- previewFileName.value = data.fileName || ''
- }
- showFilePreview.value = true
- }
- // 处理网络搜索胶囊点击
- const handleWebSearchToggle = (messageIndex) => {
- const message = chatMessages.value[messageIndex]
- if (message && message.webSearchRaw) {
- currentWebSearchData.value = message.webSearchRaw
- webSearchSidebarVisible.value = !webSearchSidebarVisible.value
- }
- }
- // 监听语音识别错误
- watch(transcript, (newVal) => {
- if (!newVal || isListening.value) return
- messageText.value = newVal
- })
- watch(speechError, (newVal) => {
- if (newVal) {
- console.error('语音识别错误:', newVal)
- ElMessage.error(newVal)
- }
- })
- // 监听网络搜索侧边栏状态变化,实时更新吸附位置
- watch(webSearchSidebarVisible, (newVal) => {
- console.log('🔍 网络搜索侧边栏状态变化:', newVal)
-
- // 等待下一帧,确保main-chat的class已更新
- requestAnimationFrame(() => {
- // 在transition完成后更新位置
- setTimeout(() => {
- handleBrowserResize()
- }, 350)
- })
- })
- // 绑定规范引用点击事件
- const bindStandardReferenceEvents = () => {
- const references = document.querySelectorAll('.standard-reference')
- references.forEach(ref => {
- ref.removeEventListener('click', handleStandardReferenceClick)
- ref.addEventListener('click', handleStandardReferenceClick)
- })
- }
- // 监听路由变化,自动发送消息
- // 处理浏览器缩放的防抖定时器
- let resizeDebounceTimer = null
- // 上次记录的fontSize,用于检测flexible缩放变化
- let lastFontSize = null
- // 处理文件统计卡片滚动吸附到顶部域
- const handleProgressCardScroll = () => {
- console.log('📜 handleProgressCardScroll 被触发')
- const chatHeader = document.querySelector('.chat-header')
- const headerBottom = chatHeader ? chatHeader.getBoundingClientRect().bottom : 0
- console.log('📐 headerBottom:', headerBottom)
-
- console.log('📊 messageContentRefs 数量:', Object.keys(messageContentRefs.value).length)
-
- Object.keys(messageContentRefs.value).forEach(index => {
- const message = chatMessages.value[index]
- if (!message || message.type !== 'ai' || !message.showStats) {
- console.log(`⏭️ 跳过消息 ${index}:`, {
- exists: !!message,
- type: message?.type,
- showStats: message?.showStats
- })
- return
- }
-
- console.log(`✅ 处理消息 ${index}`)
-
- const contentEl = messageContentRefs.value[index]
- if (!contentEl) {
- console.log(`❌ 消息 ${index} 没有找到 contentEl`)
- return
- }
-
- // 查找文件统计白色卡片
- const statsCard = contentEl.querySelector('.files-stats-white')
- if (!statsCard) {
- console.log(`❌ 消息 ${index} 没有找到 .files-stats-white`)
- return
- }
-
- console.log(`✅ 消息 ${index} 找到进度卡片`)
-
- const cardRect = statsCard.getBoundingClientRect()
- const contentRect = contentEl.getBoundingClientRect()
-
- // 如果还没有保存状态,先初始化
- if (!messageScrollStates.value[index]) {
- // 初始化状态,但默认不吸附
- messageScrollStates.value[index] = {
- initialLeft: cardRect.left, // 立即使用当前位置
- initialWidth: cardRect.width, // 立即使用当前宽度
- isSticky: false,
- // 保存卡片相对于消息内容的初始偏移量
- offsetTop: cardRect.top - contentRect.top,
- // 标记是否已初始化完成(用于延迟判断吸附)
- initialized: false,
- // 标记是否正在初始化
- isInitializing: true,
- // 记录初始化开始时间,用于防止过早吸附
- initStartTime: Date.now()
- }
-
- console.log(`[进度卡片] 开始初始化 - 消息${index}, left=${cardRect.left}, width=${cardRect.width}, offsetTop=${messageScrollStates.value[index].offsetTop}`)
-
- // 使用nextTick确保DOM渲染完成后再标记初始化完成
- nextTick(() => {
- // 再次使用requestAnimationFrame确保布局完成
- requestAnimationFrame(() => {
- if (messageScrollStates.value[index]) {
- // 重新获取元素位置(此时DOM已经稳定)
- const updatedStatsCard = contentEl.querySelector('.files-stats-white')
- if (updatedStatsCard) {
- const updatedCardRect = updatedStatsCard.getBoundingClientRect()
- messageScrollStates.value[index].initialLeft = updatedCardRect.left
- messageScrollStates.value[index].initialWidth = updatedCardRect.width
-
- console.log(`[进度卡片] 位置更新 - 消息${index}, left=${updatedCardRect.left}, width=${updatedCardRect.width}`)
- }
-
- // 设置一个最小初始化时间(100ms),防止过早吸附
- const elapsed = Date.now() - messageScrollStates.value[index].initStartTime
- const remainingTime = Math.max(0, 100 - elapsed)
-
- setTimeout(() => {
- if (messageScrollStates.value[index]) {
- messageScrollStates.value[index].initialized = true
- messageScrollStates.value[index].isInitializing = false
- console.log(`[进度卡片] 初始化完成 - 消息${index}`)
- }
- }, remainingTime)
- }
- })
- })
-
- // 初始化阶段直接返回,不进行吸附判断
- return
- }
-
- // 如果还没初始化完成或正在初始化,跳过吸附判断
- if (!messageScrollStates.value[index].initialized || messageScrollStates.value[index].isInitializing) {
- return
- }
-
- // 额外检查:确保初始化后至少过了100ms才允许吸附(防止初始化期间的意外吸附)
- const timeSinceInit = Date.now() - messageScrollStates.value[index].initStartTime
- if (timeSinceInit < 100) {
- console.log(`⏱️ 消息 ${index} 初始化中,已过${timeSinceInit}ms,跳过吸附判断`)
- return
- }
-
- // 计算卡片的"自然"位置(如果不吸附的话应该在哪里)
- // 自然位置 = 消息内容的顶部 + 卡片的初始偏移量
- const naturalTop = contentRect.top + messageScrollStates.value[index].offsetTop
-
- // 判断是否需要吸附
- // 条件:
- // 1. 卡片的自然位置已经到达或超过顶部域(naturalTop <= headerBottom)
- // 2. 输出框还在可视范围内(contentRect.bottom > headerBottom + 60)
- // 3. 当滚动回到原位置时,自然位置会大于顶部域,此时自动解除吸附
- const shouldStick = naturalTop <= headerBottom && contentRect.bottom > headerBottom + 60
-
- console.log(`📍 消息 ${index} 吸附判断:`, {
- naturalTop,
- headerBottom,
- 'naturalTop <= headerBottom': naturalTop <= headerBottom,
- 'contentRect.bottom': contentRect.bottom,
- 'headerBottom + 60': headerBottom + 60,
- shouldStick,
- currentlySticky: messageScrollStates.value[index].isSticky
- })
-
- // 如果从吸附变为非吸附,或从非吸附变为吸附,更新位置信息
- if (messageScrollStates.value[index].isSticky !== shouldStick) {
- if (!shouldStick) {
- // 解除吸附时,重新计算位置(此时卡片回到正常流,可以获取正确位置)
- messageScrollStates.value[index].initialLeft = cardRect.left
- messageScrollStates.value[index].initialWidth = cardRect.width
- } else {
- // 开始吸附时,使用当前位置(此时还未fixed,位置准确)
- messageScrollStates.value[index].initialLeft = cardRect.left
- messageScrollStates.value[index].initialWidth = cardRect.width
- }
- }
- // 注意:当保持吸附状态时(shouldStick && isSticky都为true),不更新位置
- // 因为此时cardRect.left是fixed后的位置,可能因为缩放等原因不准确
-
- messageScrollStates.value[index].isSticky = shouldStick
- messageScrollStates.value[index].stickyTop = headerBottom
- })
- }
- // 处理浏览器缩放的函数(带防抖)
- const handleBrowserResize = () => {
- // 检测是否是flexible方案导致的fontSize变化
- const currentFontSize = window.getComputedStyle(document.documentElement).fontSize
- const isFontSizeChanged = lastFontSize && currentFontSize !== lastFontSize
-
- if (isFontSizeChanged) {
- console.log('🔍 检测到flexible fontSize变化:', lastFontSize, '->', currentFontSize)
- }
-
- lastFontSize = currentFontSize
-
- // 清除之前的定时器
- if (resizeDebounceTimer) {
- clearTimeout(resizeDebounceTimer)
- }
-
- // 100ms防抖延迟(缩短延迟以更快响应)
- resizeDebounceTimer = setTimeout(() => {
- console.log('🔍 检测到窗口大小变化,重新计算所有吸附卡片位置')
-
- // 强制浏览器完成layout重排
- document.body.offsetHeight
-
- // 临时解除所有吸附状态,以便重新计算正确位置
- const stickyStates = {}
- Object.keys(messageScrollStates.value).forEach(index => {
- const state = messageScrollStates.value[index]
- if (state && state.isSticky) {
- stickyStates[index] = true
- state.isSticky = false
- }
- })
-
- // 使用nextTick确保DOM更新完成
- nextTick(() => {
- // 强制再次重排
- document.body.offsetHeight
-
- // 重新计算所有卡片的位置
- Object.keys(messageScrollStates.value).forEach(index => {
- const state = messageScrollStates.value[index]
- if (!state) return
-
- const contentEl = messageContentRefs.value[index]
- if (!contentEl) return
-
- const statsCard = contentEl.querySelector('.files-stats-white')
- if (!statsCard) return
-
- const cardRect = statsCard.getBoundingClientRect()
- const contentRect = contentEl.getBoundingClientRect()
-
- // 更新位置信息(此时元素已恢复正常流,位置准确)
- state.initialLeft = cardRect.left
- state.initialWidth = cardRect.width
- state.offsetTop = cardRect.top - contentRect.top
-
- console.log(` - 更新消息${index}的位置: left=${cardRect.left}, width=${cardRect.width}`)
- })
-
- // 恢复吸附状态
- Object.keys(stickyStates).forEach(index => {
- if (messageScrollStates.value[index]) {
- messageScrollStates.value[index].isSticky = true
- }
- })
-
- // 再次触发滚动检测,确保吸附状态正确
- nextTick(() => {
- handleProgressCardScroll()
- })
- })
- }, 100)
- }
- onMounted(async () => {
- try {
- console.log('🚀 AI问答页面初始化开始,优先加载历史记录...')
-
- // 设置初始加载状态
- isLoadingHistory.value = true
-
- // 添加全局错误处理
- window.addEventListener('error', (event) => {
- console.error('全局错误:', event.error)
- })
-
- window.addEventListener('unhandledrejection', (event) => {
- console.error('未处理的Promise拒绝:', event.reason)
- })
-
- // 移除可能存在的旧事件监听器,然后添加新的
- document.removeEventListener('click', handleStandardReferenceClick)
- document.addEventListener('click', handleStandardReferenceClick)
-
- // 添加滚动监听用于进度卡片吸顶
- const chatContent = document.querySelector('.chat-content')
- if (chatContent) {
- console.log('✅ 找到 .chat-content 元素,添加滚动监听')
- console.log('📦 .chat-content 样式:', {
- overflow: window.getComputedStyle(chatContent).overflow,
- overflowY: window.getComputedStyle(chatContent).overflowY,
- height: chatContent.offsetHeight,
- scrollHeight: chatContent.scrollHeight
- })
-
- // 添加测试监听器来确认滚动事件能触发
- chatContent.addEventListener('scroll', () => {
- console.log('🔄 滚动事件触发!scrollTop:', chatContent.scrollTop)
- }, { once: true }) // 只触发一次,避免刷屏
-
- chatContent.addEventListener('scroll', handleProgressCardScroll)
- } else {
- console.error('❌ 未找到 .chat-content 元素')
- }
-
- // 初始化fontSize记录,用于检测flexible缩放变化
- lastFontSize = window.getComputedStyle(document.documentElement).fontSize
- console.log('📐 初始fontSize:', lastFontSize)
-
- // 添加浏览器缩放监听器(带防抖)
- window.addEventListener('resize', handleBrowserResize)
-
- // 添加页面卸载事件监听器,在刷新时停止语音朗读
-
- window.addEventListener('beforeunload', handlePageUnload)
- window.addEventListener('unload', handlePageUnload)
- document.addEventListener('visibilitychange', handleVisibilityChange)
-
- // 初始化缩放补偿 - 修复中括号背景色随浏览器缩放变化的问题
- initBracketZoomCompensation()
-
- // 1. 首先获取历史记录列表(最高优先级)
- await getHistoryRecordList()
- console.log('✅ AI问答历史记录加载完成')
-
- // 2. 测试TTS服务连接
- try {
- const ttsTest = await testTTSConnection()
- if (ttsTest.success) {
- console.log('✅ TTS服务连接正常')
- } else {
- console.warn('⚠️ TTS服务连接异常:', ttsTest.message)
- }
- } catch (error) {
- console.warn('⚠️ TTS服务连接测试失败:', error)
- }
-
- // 2. 并行获取其他非关键数据(不阻塞历史记录显示)
- const otherDataPromise = Promise.all([
- getFunctionCards(),
- getHotQuestions()
- ])
-
- // 3. 等待其他数据加载完成(后台进行)
- try {
- await otherDataPromise
- console.log('✅ AI问答其他数据加载完成')
- } catch (error) {
- console.warn('⚠️ AI问答其他数据加载失败,但不影响主要功能:', error)
- }
-
- console.log('🎉 AI问答页面初始化完成')
-
- // 检查是否带有指定的模式
- const targetMode = Array.isArray(route.query.mode) ? route.query.mode[0] : route.query.mode
- if (targetMode && ['ai-qa', 'ai-writing', 'safety-training', 'exam-workshop'].includes(targetMode)) {
- console.log('检测到目标模式:', targetMode)
- if (!hasUserSelectedMode.value && currentMode.value !== targetMode) {
- setMode(targetMode, { allowToggle: false, source: 'system' })
- }
-
- // 立即清除URL中的mode参数,防止刷新时问题
- router.replace({
- path: route.path,
- query: { ...route.query, mode: undefined }
- })
- }
- // 检查是否有自动发送的消息
- const autoMessage = route.query.autoMessage
- if (autoMessage) {
- console.log('检测到自动发送消息:', autoMessage)
-
- // 立即清除URL中的autoMessage参数,防止刷新时重复发送
- router.replace({
- path: route.path,
- query: { ...route.query, autoMessage: undefined }
- })
-
- // 延迟一下,确保组件完全挂载
- // setTimeout(() => {
- // autoSendMessage(autoMessage)
- // }, 100)
- autoSendMessage(autoMessage)
- }
- } catch (error) {
- console.error('组件初始化失败:', error)
- }
- })
- // 组件销毁前,强制停止任何朗读
- onBeforeUnmount(() => {
- if (speakingMessageId.value) {
- stopAllAudio()
- speakingMessageId.value = null
- }
-
- // 清理所有打字机定时器
- clearAllTypeIntervals()
-
- // 清理事件监听器,防止重复绑定
- document.removeEventListener('click', handleStandardReferenceClick)
-
- // 清理进度卡片滚动监听
- const chatContent = document.querySelector('.chat-content')
- if (chatContent) {
- chatContent.removeEventListener('scroll', handleProgressCardScroll)
- }
-
- // 清理浏览器缩放监听器
- window.removeEventListener('resize', handleBrowserResize)
-
- // 清理防抖定时器
- if (resizeDebounceTimer) {
- clearTimeout(resizeDebounceTimer)
- resizeDebounceTimer = null
- }
-
- // 清理页面卸载和可见性变化事件监听器
- window.removeEventListener('beforeunload', handlePageUnload)
- window.removeEventListener('unload', handlePageUnload)
- document.removeEventListener('visibilitychange', handleVisibilityChange)
- })
- // 页面重新激活时,重新渲染所有AI消息的markdown内容
- onActivated(async () => {
- console.log('页面重新激活,检查并重新渲染markdown内容')
-
- // 等待DOM更新
- await nextTick()
-
- // 重新渲染所有AI消息的markdown内容
- for (const message of chatMessages.value) {
- if (message.type === 'ai' && message.content && !message.isTyping) {
- try {
- console.log('重新渲染AI消息markdown:', message.id)
- const processedReply = processAIResponse(message.content)
- const processedReplyWithFileDisplay = processFileDisplay(processedReply, message.file)
- const htmlReply = renderMarkdownContent(processedReplyWithFileDisplay)
- message.displayContent = htmlReply
-
- // 重新绑定规范引用点击事件
- setTimeout(() => {
- bindStandardReferenceEvents()
- }, 100)
- } catch (error) {
- console.error('重新渲染markdown失败:', error)
- // 如果重新渲染失败,保持原有内容
- }
- }
- }
-
- // 强制触发Vue响应式更新
- chatMessages.value = [...chatMessages.value]
-
- console.log('页面重新激活完成,markdown内容已重新渲染')
- })
- </script>
- <style lang="less" scoped>
- // 删除图标样式
- .delete-icon {
- width: 16px;
- height: 16px;
- }
- .chat-container {
- display: flex;
- height: 100vh;
- font-family: 'Alibaba PuHuiTi 3.0', sans-serif;
- }
- .chat-main-area {
- flex: 1;
- display: flex;
- min-width: 0;
- height: 100vh;
- overflow: hidden;
- }
- /* 中间历史记录栏 */
- .history-sidebar {
- width: 280px;
- min-width: 280px;
- flex-shrink: 0;
- background: #E8F0FF;
- display: flex;
- flex-direction: column;
- }
- /* 中间历史记录栏样式 */
- .history-sidebar {
- padding: 24px 16px 0 16px;
- .new-chat-container {
- margin-bottom: 24px;
-
- .new-chat-btn-full {
- width: 100%;
- height: 44px;
- background-color: #3E7BFA;
- color: white;
- border: none;
- border-radius: 8px;
- font-size: 14px;
- font-weight: 500;
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 6px;
- cursor: pointer;
- transition: background-color 0.2s;
-
- .plus-icon {
- font-size: 18px;
- font-weight: 400;
- margin-bottom: 2px;
- }
-
- &:hover:not(:disabled) {
- background-color: #2b65e2;
- }
-
- &:disabled {
- opacity: 0.6;
- cursor: not-allowed;
- }
- }
- }
- .history-header {
- background: transparent;
- margin-bottom: 16px;
-
- .section-title {
- font-size: 16px;
- font-weight: 600;
- color: #2C3E50;
- }
- }
-
- .history-list {
- flex: 1;
- overflow-y: auto;
- width: 248px;
- height: 64px;
-
- /* 隐藏滚动条 */
- &::-webkit-scrollbar {
- display: none;
- }
-
- -ms-overflow-style: none; /* IE and Edge */
- scrollbar-width: none; /* Firefox */
-
- .history-item {
- background: white;
- border-radius: 8px;
- padding: 15px;
- margin-bottom: 8px;
- cursor: pointer;
- transition: all 0.3s ease;
- border-left: 3px solid transparent;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
- display: flex;
- align-items: center;
- justify-content: space-between;
- position: relative;
-
- &:hover {
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
-
- .delete-btn {
- opacity: 1;
- visibility: visible;
- }
- }
-
- &.active {
- border-left-color: #3E7BFA;
- box-shadow: 0 2px 8px rgba(62, 123, 250, 0.2);
- cursor: default;
- opacity: 0.8;
-
- &:hover {
- transform: none;
- box-shadow: 0 2px 8px rgba(62, 123, 250, 0.2);
- }
- }
-
- .history-content {
- flex: 1;
- min-width: 0; // 允许内容收缩
- }
-
- .history-title {
- font-size: 14px;
- line-height: 1.4;
- margin-bottom: 6px;
- color: #2C3E50;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- .history-time {
- font-size: 12px;
- color: #7C8DB5;
- }
-
- .delete-btn {
- opacity: 0;
- visibility: hidden;
- transition: all 0.2s ease;
- cursor: pointer;
- padding: 4px;
- border-radius: 4px;
- color: #7C8DB5;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-left: 8px;
- flex-shrink: 0;
-
- &:hover {
- color: #ff4757;
- background-color: rgba(255, 71, 87, 0.1);
- }
-
- &.always-visible {
- opacity: 1;
- visibility: visible;
- }
- }
- }
-
- .empty-history {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- // height: 200px;
- // padding: 20px;
- margin-top: 236px;
-
- .empty-icon {
- width: 147px;
- height: 148px;
- object-fit: contain;
- margin-bottom: 16px;
- }
-
- .empty-text {
- font-size: 16px;
- color: #9C9FA7;
- text-align: center;
- }
- }
- }
- }
- /* 主聊天区域 */
- .embedded-exam-workshop {
- flex: 1;
- display: flex;
- flex-direction: column;
- overflow: hidden;
- height: 100vh;
- }
- .exam-workshop-wrapper {
- flex: 1;
- overflow-y: hidden;
- position: relative;
- background: #f5f7fb;
- }
- .main-chat {
- flex: 1;
- background: #EBF3FF;
- display: flex;
- flex-direction: column;
- transition: margin-right 0.3s ease;
- min-width: 0;
- height: 100%;
- }
- .main-chat.sidebar-open {
- margin-right: 400px;
- }
- /* 聊天头部 */
- .chat-header {
- background: transparent;
- padding: 20px 0px 0px 18px; /* 从30px改为20px,向上提升10px */
-
- .default-title {
- margin: 0;
- font-size: 20px;
- font-weight: 600;
- color: #2C3E50;
- }
-
- .question-title-card {
- display: inline-flex;
- align-items: center;
- background: rgba(91, 141, 239, 0.08);
- backdrop-filter: blur(10px);
- -webkit-backdrop-filter: blur(10px);
- border: 1px solid rgba(91, 141, 239, 0.2);
- border-radius: 20px;
- padding: 6px 16px;
- box-shadow: 0 2px 8px rgba(91, 141, 239, 0.1);
- transition: all 0.3s ease;
- max-width: 750px;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- h2 {
- margin: 0;
- font-size: 13px;
- font-weight: 600;
- color: #5b8def;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- letter-spacing: 0.3px;
- }
- &:hover {
- background: rgba(91, 141, 239, 0.12);
- border-color: rgba(91, 141, 239, 0.3);
- transform: translateY(-1px);
- box-shadow: 0 4px 12px rgba(91, 141, 239, 0.15);
- }
- }
- }
- /* 聊天内容区域 */
- .chat-content {
- flex: 1;
- // padding: 40px 30px;
- overflow-y: auto;
- display: flex;
- flex-direction: column;
- align-items: center;
- margin-top: 24px;
- }
- /* 初始内容样式 */
- .initial-content {
- width: 100%;
- display: flex;
- flex-direction: column;
- align-items: center;
- }
- /* 聊天消息区域 */
- // .chat-messages {
- // width: 100%;
- // max-width: 900px;
- // padding: 0 30px;
- // display: flex;
- // flex-direction: column;
- // gap: 24px;
- // }
- /* 消息项样式 */
- .message-item {
- display: flex;
- flex-direction: column;
- gap: 12px;
- }
- /* 用户消息样式 */
- .user-message {
- display: flex;
- flex-direction: column;
- align-items: flex-end;
- gap: 8px;
-
- .message-content {
- background: #004BFF20;
- color: #000000;
- padding: 16px 20px;
- border-radius: 18px 0px 18px 18px;
- max-width: 900px;
- word-wrap: break-word;
- line-height: 1.5;
- font-size: 16px;
- overflow: hidden;
- .message-file {
- margin-bottom: 12px;
-
- .file-display {
- display: flex;
- align-items: center;
- background: rgba(255, 255, 255, 0.8);
- border: 1px solid #E5E7EB;
- border-radius: 12px;
- padding: 16px;
- max-width: 400px;
-
- .file-icon {
- font-size: 32px;
- margin-right: 16px;
- width: 48px;
- text-align: center;
-
- .file-icon-img {
- width: 32px;
- height: 32px;
- object-fit: contain;
- }
- }
-
- .file-details {
- flex: 1;
-
- .file-name {
- font-size: 14px;
- font-weight: 500;
- color: #374151;
- margin-bottom: 4px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- max-width: 200px;
- }
-
- .file-size {
- font-size: 12px;
- color: #6B7280;
- }
- }
- }
- }
-
- .message-text {
- margin-top: 0;
- }
- }
-
- .message-actions {
- display: flex;
- // gap: 8px;
-
- .action-btn {
- background: none;
- border: none;
- padding: 6px 4px;
- border-radius: 4px;
- font-size: 12px;
- color: #6b7280;
- cursor: pointer;
- transition: all 0.2s ease;
- display: flex;
- align-items: center;
- gap: 4px;
-
- &:hover {
- color: #374151;
- }
-
- .action-icon {
- width: 16px;
- height: 16px;
- object-fit: contain;
- }
- }
- }
- }
- /* AI消息样式 */
- .ai-message {
- display: flex;
- flex-direction: column;
- gap: 0;
-
- .ai-message-main {
- display: flex;
- gap: 12px;
- }
-
- // ReportGenerator相关样式
- .ai-response-content {
- width: 100%;
- }
-
- .question-summary {
- margin-bottom: 16px;
- font-size: 16px;
- line-height: 1.8;
- color: #606266;
- }
-
- .web-search-capsule-outer {
- margin-bottom: 7px;
- display: flex;
- justify-content: flex-start;
- padding-left: 52px;
- }
-
- .files-stats-white {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 16px;
- padding: 12px 16px;
- background: white;
- border-radius: 8px;
- margin-bottom: 16px;
- border: 1px solid #e8ecf1;
- transition: left 0.3s ease, width 0.3s ease, box-shadow 0.3s ease;
- }
-
- .files-stats-white.sticky {
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
- border-bottom: 2px solid #5b8def;
- }
-
- .stats-left {
- display: flex;
- align-items: center;
- gap: 12px;
- flex-shrink: 0;
- }
-
- .stats-avatar {
- flex-shrink: 0;
- }
-
- .stats-icon {
- font-size: 20px;
- color: #5b8def;
- }
-
- .stats-left span {
- font-size: 14px;
- font-weight: 500;
- color: #2d3748;
- white-space: nowrap;
- }
-
- .stats-left .brand-name {
- color: #5b8def !important;
- font-weight: 600 !important;
- }
-
- .stats-left .file-count {
- color: #5b8def !important;
- font-weight: 600 !important;
- font-size: 15px;
- }
-
- .stats-left .ai-name {
- color: #5b8def !important;
- font-weight: 600 !important;
- }
-
- /* 使用:deep()确保样式穿透到v-html渲染的内容 */
- .stats-left :deep(.ai-name) {
- color: #5b8def !important;
- font-weight: 600 !important;
- }
-
- .stats-left :deep(.file-count) {
- color: #5b8def !important;
- font-weight: 600 !important;
- font-size: 15px !important;
- }
-
- .stats-right {
- flex-shrink: 0;
- }
-
- /* 进度条内联样式 - 在白色卡片内 */
- .progress-capsule-inline {
- display: flex;
- align-items: center;
- gap: 12px;
- background: rgba(91, 141, 239, 0.08);
- border: 1px solid rgba(91, 141, 239, 0.2);
- padding: 8px 16px;
- border-radius: 20px;
- flex-shrink: 0;
- }
-
- .progress-capsule-inline .progress-label {
- white-space: nowrap;
- color: #5b8def;
- font-weight: 600;
- font-size: 13px;
- }
-
- .progress-capsule-inline .progress-bar-mini {
- position: relative;
- width: 100px;
- height: 6px;
- background: rgba(91, 141, 239, 0.15);
- border-radius: 3px;
- overflow: visible;
- }
-
- .progress-capsule-inline .progress-fill {
- height: 100%;
- background: linear-gradient(90deg, #5b8def 0%, #4a7ad8 100%);
- border-radius: 3px;
- transition: width 0.6s ease;
- box-shadow: 0 0 8px rgba(91, 141, 239, 0.3);
- }
-
- .progress-capsule-inline .progress-dot {
- position: absolute;
- top: 50%;
- transform: translate(-50%, -50%);
- width: 12px;
- height: 12px;
- background: white;
- border: 2px solid #5b8def;
- border-radius: 50%;
- box-shadow: 0 2px 6px rgba(91, 141, 239, 0.4);
- transition: left 0.6s ease;
- z-index: 1;
- }
-
- .progress-capsule-inline .progress-percentage {
- font-weight: 600;
- min-width: 40px;
- text-align: right;
- color: #5b8def;
- font-size: 13px;
- }
-
-
- .reports-list {
- margin-top: 8px;
- }
-
- .report-loading {
- display: flex;
- flex-direction: row;
- align-items: center;
- justify-content: flex-start;
- gap: 12px;
- padding: 12px 0;
- margin-top: 12px;
- margin-bottom: 8px;
- }
-
- .report-loading .loading-text {
- color: #6B7280;
- font-size: 14px;
- font-weight: 500;
- }
-
- .online-search-results {
- margin: 8px 0 12px 0;
- margin-top: 10px;
- background: white;
- border-radius: 12px;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
- margin-left: 52px;
- overflow: hidden;
- width: fit-content;
-
- .online-search-header {
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 12px;
- cursor: pointer;
- transition: background-color 0.2s ease;
- font-size: 14px;
- color: #37415180;
-
- &:hover {
- background-color: #f9fafb;
- }
-
- .expand-icon {
- margin-left: 8px;
- transition: transform 0.2s ease;
- color: #6b7280;
-
- &.expanded {
- transform: rotate(180deg);
- }
- }
- }
-
- .online-search-content {
- border-top: 1px solid #f3f4f6;
- padding: 16px;
- width: 735px;
- max-height: 400px;
- overflow-y: auto;
-
- /* 自定义滚动条样式 */
- &::-webkit-scrollbar {
- width: 6px;
- }
-
- &::-webkit-scrollbar-track {
- background: #f1f5f9;
- border-radius: 3px;
- }
-
- &::-webkit-scrollbar-thumb {
- background: #cbd5e1;
- border-radius: 3px;
-
- &:hover {
- background: #94a3b8;
- }
- }
-
- .search-results-section {
- .section-header {
- display: flex;
- align-items: center;
- margin-bottom: 16px;
-
- .section-icon {
- width: 24px;
- height: 24px;
- background: #f3f4f6;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-right: 8px;
- font-size: 12px;
- }
-
- .section-title {
- font-size: 14px;
- color: #374151;
- font-weight: 500;
- }
- }
-
- .search-results-grid {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
- gap: 12px;
-
- .search-result-card {
- background: white;
- border: 1px solid #e5e7eb;
- border-radius: 8px;
- padding: 12px;
- position: relative;
- cursor: pointer;
- transition: all 0.2s ease;
- min-height: 80px;
- height: auto;
-
- &:hover {
- border-color: #3b82f6;
- box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
- }
-
- .result-title {
- font-size: 13px;
- color: #1f2937;
- font-weight: 500;
- line-height: 1.4;
- margin-bottom: 6px;
- display: -webkit-box;
- -webkit-line-clamp: 1;
- line-clamp: 1;
- -webkit-box-orient: vertical;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- padding-right: 30px;
- }
-
- .result-description {
- font-size: 12px;
- color: #6b7280;
- line-height: 1.4;
- display: -webkit-box;
- -webkit-line-clamp: 3;
- line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
- word-break: break-word;
- text-overflow: ellipsis;
- padding-right: 30px;
- }
-
- .result-badge {
- position: absolute;
- top: 8px;
- right: 8px;
- width: 20px;
- height: 20px;
- background: #3b82f6;
- color: white;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 10px;
- font-weight: 600;
- z-index: 1;
- }
- }
- }
- }
- }
- }
- .search-sources {
- margin: 8px 0 12px 0;
- margin-top: 10px;
- background: white;
- border-radius: 12px;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
- margin-left: 52px;
- overflow: hidden;
- width: fit-content;
-
- .search-sources-header {
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 12px;
- cursor: pointer;
- transition: background-color 0.2s ease;
- font-size: 14px;
- color: #37415180;
-
- &:hover {
- background-color: #f9fafb;
- }
-
- .expand-icon {
- margin-left: 8px;
- transition: transform 0.2s ease;
- color: #6b7280;
-
- &.expanded {
- transform: rotate(180deg);
- }
- }
- }
-
- .search-sources-content {
- border-top: 1px solid #f3f4f6;
- padding: 16px;
- width: 735px;
- // max-width: 900px;
- max-height: 400px; /* 改为最大高度,允许动态调整 */
- overflow-y: auto;
-
- /* 自定义滚动条样式 */
- &::-webkit-scrollbar {
- width: 6px;
- }
-
- &::-webkit-scrollbar-track {
- background: #f1f5f9;
- border-radius: 3px;
- }
-
- &::-webkit-scrollbar-thumb {
- background: #cbd5e1;
- border-radius: 3px;
-
- &:hover {
- background: #94a3b8;
- }
- }
-
- .sources-section {
- .section-header {
- display: flex;
- align-items: center;
- margin-bottom: 16px;
-
- .section-icon {
- width: 24px;
- height: 24px;
- background: #f3f4f6;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-right: 8px;
- font-size: 12px;
- }
-
- .section-title {
- font-size: 14px;
- color: #374151;
- font-weight: 500;
- }
- }
-
- .sources-grid {
- display: grid;
- grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
- gap: 12px;
-
- .source-card {
- background: white;
- border: 1px solid #e5e7eb;
- border-radius: 8px;
- padding: 12px;
- position: relative;
- cursor: pointer;
- transition: all 0.2s ease;
- min-height: 80px; /* 设置最小高度 */
- height: auto; /* 允许高度自适应 */
-
- &:hover {
- border-color: #3b82f6;
- box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
- }
-
- .source-title {
- font-size: 13px;
- color: #1f2937;
- font-weight: 500;
- line-height: 1.4;
- margin-bottom: 6px;
- display: -webkit-box;
- -webkit-line-clamp: 1;
- line-clamp: 1;
- -webkit-box-orient: vertical;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- padding-right: 30px; /* 为右侧数字留出空间 */
- }
-
- .source-description {
- font-size: 12px;
- color: #6b7280;
- line-height: 1.4;
- display: -webkit-box;
- -webkit-line-clamp: 3;
- line-clamp: 3;
- -webkit-box-orient: vertical;
- overflow: hidden;
- word-break: break-word;
- text-overflow: ellipsis;
- padding-right: 30px; /* 为右侧数字留出空间 */
- }
-
- .source-badge {
- position: absolute;
- top: 8px;
- right: 8px;
- width: 20px;
- height: 20px;
- background: #3b82f6;
- color: white;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 10px;
- font-weight: 600;
- z-index: 1; /* 确保在文字上方 */
- }
- }
- }
- }
- }
-
- }
-
- .related-questions {
- margin-top: 20px;
- padding: 0;
- margin-left: 52px;
- display: flex;
- flex-direction: column;
- gap: 8px;
-
- .related-question-item {
- display: flex;
- align-items: center;
- padding: 12px 16px;
- background: rgba(0,0,0,.05);
- border: 1px solid #e9ecef;
- border-radius: 12px;
- cursor: pointer;
- transition: all 0.2s ease;
- font-size: 16px;
- color: #212529;
- line-height: 1.4;
- width: fit-content;
-
- &:hover {
- background: #E2EBFE;
- border-color: #dee2e6;
- }
-
- .arrow-icon {
- width: 16px;
- height: 16px;
- color: #6c757d;
- flex-shrink: 0;
- margin-left: 8px;
- }
- }
- }
-
- .ai-avatar-small {
- width: 80px;
- height: 80px;
- animation: avatar-pulse 2s ease-in-out infinite;
- flex-shrink: 0;
- /* 位置调整:向上和向左移动,使输出框与搜索结果胶囊对齐 */
- margin-top: -40px;
- margin-left: -45px;
-
- .ai-icon {
- width: 100%;
- height: 100%;
- object-fit: contain;
- filter: drop-shadow(0 4px 16px rgba(91, 141, 239, 0.15));
- }
- }
-
- @keyframes avatar-pulse {
- 0%, 100% {
- transform: scale(1);
- }
- 50% {
- transform: scale(1.05);
- }
- }
-
- .message-content {
- background: white;
- color: #374151;
- padding: 16px 20px;
- border-radius: 0px 18px 18px 18px;
- max-width: 900px;
- width: 900px;
- word-wrap: break-word;
- line-height: 1.5;
- font-size: 16px;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
- white-space: normal;
- transition: width 0.3s ease;
- overflow: hidden;
-
- .ai-text {
- min-height: 20px;
- line-height: 1.5;
- margin-bottom: 16px;
-
- .typing-indicator {
- color: #9CA3AF;
- font-style: italic;
- font-size: 14px;
- display: flex;
- align-items: center;
- gap: 8px;
- white-space: nowrap;
-
- .thinking-animation {
- display: flex;
- gap: 4px;
-
- .dot {
- width: 6px;
- height: 6px;
- background: #9CA3AF;
- border-radius: 50%;
- animation: thinking 1.4s infinite ease-in-out;
-
- &:nth-child(1) { animation-delay: -0.32s; }
- &:nth-child(2) { animation-delay: -0.16s; }
- &:nth-child(3) { animation-delay: 0s; }
- }
- }
- }
-
- .safety-doc-card {
- display: flex;
- align-items: center;
- background: white;
- border: 1px solid #e2e8f0;
- border-radius: 12px;
- padding: 16px 20px;
- margin-bottom: 16px;
- cursor: pointer;
- transition: all 0.3s ease;
- box-shadow: 0 2px 8px rgba(0,0,0,0.04);
- max-width: 400px;
- &:hover {
- box-shadow: 0 4px 12px rgba(0,0,0,0.08);
- transform: translateY(-2px);
- border-color: #3e7bfa;
- }
- .doc-icon-wrapper {
- width: 48px;
- height: 48px;
- background: #f0f5ff;
- border-radius: 10px;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-right: 16px;
- .doc-icon {
- width: 24px;
- height: 24px;
- object-fit: contain;
- }
- }
- .doc-info {
- flex: 1;
- .doc-title {
- font-size: 16px;
- font-weight: 600;
- color: #1f2937;
- margin-bottom: 4px;
- }
- .doc-time {
- font-size: 12px;
- color: #9ca3af;
- }
- }
- .doc-action {
- font-size: 14px;
- color: #3e7bfa;
- font-weight: 500;
- }
- }
-
- .ai-markdown-content {
- /* Markdown样式 - 与StreamMarkdown保持一致 */
- :deep(h2) {
- font-size: 16px;
- font-weight: 600;
- color: #303133;
- margin: 8px 0 4px 0;
- padding-bottom: 4px;
- border-bottom: 1px solid #dcdfe6;
- }
- :deep(h3) {
- font-size: 15px;
- font-weight: 600;
- color: #606266;
- margin: 8px 0 4px 0;
- }
- :deep(p) {
- margin: 8px 0;
- line-height: 1.8;
- }
- :deep(strong) {
- font-weight: 600;
- color: #303133;
- }
- :deep(ul),
- :deep(ol) {
- margin: 8px 0;
- padding-left: 24px;
- }
- :deep(li) {
- margin: 4px 0;
- }
- :deep(blockquote) {
- margin: 12px 0;
- padding: 8px 16px;
- border-left: 4px solid #5b8def;
- background-color: #f7f9fc;
- color: #606266;
- }
- :deep(code) {
- padding: 2px 6px;
- background-color: #f4f4f5;
- border-radius: 3px;
- font-family: 'Courier New', monospace;
- font-size: 13px;
- }
- :deep(pre) {
- margin: 12px 0;
- padding: 12px;
- background-color: #f4f4f5;
- border-radius: 4px;
- overflow-x: auto;
- }
- :deep(pre code) {
- padding: 0;
- background-color: transparent;
- }
- :deep(a) {
- color: #5b8def;
- text-decoration: none;
- cursor: pointer;
- }
- :deep(a:hover) {
- text-decoration: underline;
- color: #4a7de8;
- }
- :deep(hr) {
- margin: 16px 0;
- border: none;
- border-top: 1px solid #dcdfe6;
- }
- :deep(table) {
- border-collapse: collapse;
- width: 100%;
- margin: 12px 0;
- }
- :deep(th),
- :deep(td) {
- border: 1px solid #dcdfe6;
- padding: 8px 12px;
- text-align: left;
- }
- :deep(th) {
- background-color: #f4f4f5;
- font-weight: 600;
- }
- }
- }
-
- .divider {
- height: 1px;
- background: #e5e7eb;
- margin: 16px 0 8px 0;
- }
-
-
- .message-actions {
- display: flex;
- justify-content: space-between;
- align-items: center;
-
- .left-actions {
- display: flex;
- gap: 8px;
- flex-wrap: wrap;
- }
-
- .right-actions {
- display: flex;
- }
-
- .action-btn {
- background: none;
- border: none;
- padding: 6px 5px;
- border-radius: 4px;
- cursor: pointer;
- transition: all 0.2s ease;
- display: flex;
- align-items: center;
- gap: 4px;
- font-size: 12px;
- color: #6b7280;
-
- &:hover:not(:disabled) {
- color: #374151;
- background: rgba(59, 130, 246, 0.1);
- }
-
- &:disabled {
- cursor: not-allowed;
- }
-
- .action-icon {
- width: 16px;
- height: 16px;
- object-fit: contain;
- }
-
- &.voice-btn.speaking {
- color: #dc2626;
- background: rgba(239, 68, 68, 0.08);
-
- .action-icon {
- filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(0deg) brightness(104%) contrast(97%);
- }
- }
- // 点赞和点踩按钮的特殊样式
- &.thumbs-up-btn {
- transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
-
- &:hover {
- color: #059669;
- transform: scale(1.1);
- }
-
- &.active {
- color: #059669;
- transform: scale(1.2);
-
- .action-icon {
- filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(142deg) brightness(104%) contrast(97%);
- }
- }
-
- &:active {
- transform: scale(0.9);
- transition: all 0.1s ease;
- }
- }
-
- &.thumbs-down-btn {
- transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
-
- &:hover {
- color: #dc2626;
- transform: scale(1.1);
- }
-
- &.active {
- color: #dc2626;
- transform: scale(1.2);
-
- .action-icon {
- filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(0deg) brightness(104%) contrast(97%) !important;
- }
- }
-
- &:active {
- transform: scale(0.9);
- transition: all 0.1s ease;
- }
- }
- }
- }
- }
-
- }
- /* 打字动画 */
- @keyframes thinking {
- 0%, 80%, 100% {
- transform: scale(0.8);
- opacity: 0.5;
- }
- 40% {
- transform: scale(1);
- opacity: 1;
- }
- }
- /* 初始内容样式 */
- .initial-content {
- width: 100%;
- display: flex;
- flex-direction: column;
- align-items: center;
- }
- /* 聊天消息区域 */
- .chat-messages {
- width: 100%;
- max-width: 1060px;
- padding: 0 75px 0 35px;
- display: flex;
- flex-direction: column;
- gap: 24px;
- padding-bottom: 40px; /* 添加底部间距 */
- }
- /* 消息项样式 */
- // .message-item {
- // display: flex;
- // flex-direction: column;
- // gap: 12px;
- // }
-
- /* 打字动画 */
- @keyframes fadeIn {
- from {
- opacity: 0;
- transform: translateY(2px);
- }
- to {
- opacity: 1;
- transform: translateY(0);
- }
- }
-
- /* AI助手介绍 */
- .ai-intro {
- display: flex;
- flex-direction: column;
- align-items: center;
- margin-bottom: 40px;
-
- .ai-avatar {
- width: 160px;
- height: 160px;
- border-radius: 40px;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-bottom: 20px;
- animation: avatar-float 3s ease-in-out infinite;
-
- .ai-avatar-img {
- width: 100%;
- height: 100%;
- object-fit: contain;
- filter: drop-shadow(0 8px 24px rgba(91, 141, 239, 0.2));
- }
- }
-
- @keyframes avatar-float {
- 0%, 100% {
- transform: translateY(0);
- }
- 50% {
- transform: translateY(-8px);
- }
- }
-
- .ai-greeting {
- text-align: center;
-
- h3 {
- font-size: 24px;
- font-weight: 600;
- color: #2C3E50;
- margin: 0 0 8px 0;
- }
-
- p {
- font-size: 16px;
- color: #7C8DB5;
- margin: 0;
- }
- }
- }
- /* 功能卡片 */
- .function-cards {
- display: grid;
- grid-template-columns: repeat(2, 1fr);
- gap: 16px;
- margin-top: 56px;
- max-width: 592px;
-
-
- .function-card {
- background: white;
- width: 288px;
- height: 112px;
- padding: 20px 0px;
- padding-left: 20px;
- border-radius: 12px;
- border: 1px solid #E5E8EB;
- cursor: pointer;
- transition: all 0.3s ease;
- display: flex;
- flex-direction: column;
- box-sizing: border-box;
-
-
- &:hover {
- border-color: #667eea;
- transform: translateY(-2px);
- box-shadow: 0 4px 20px rgba(102, 126, 234, 0.1);
- }
-
- .card-header {
- display: flex;
- align-items: center;
- gap: 16px;
- margin-bottom: 8px;
-
- .card-icon {
- width: 40px;
- height: 40px;
- display: flex;
- align-items: center;
- justify-content: center;
- background: #F3F5FF;
- border-radius: 8px;
- flex-shrink: 0;
-
- .card-icon-img {
- width: 40px;
- height: 40px;
- object-fit: contain;
- }
- }
-
- h4 {
- font-size: 16px;
- font-weight: 600;
- color: #2C3E50;
- margin: 0;
- line-height: 1.5;
- flex: 1;
- }
- }
-
- .card-description {
- margin-left: 55px;
- p {
- font-size: 14px;
- color: #7C8DB5;
- margin: 0;
- line-height: 1.4;
- }
- }
- }
- }
- /* 推荐问题 */
- .recommended-questions {
- display: flex;
- flex-wrap: wrap;
- gap: 12px;
- justify-content: center;
- max-width: 900px;
- margin: 0 auto 12px auto;
- padding: 0;
-
- .question-tag {
- background: white;
- padding: 8px 16px;
- border-radius: 20px;
- border: 1px solid #E5E8EB;
- font-size: 14px;
- color: #5A6C7D;
- cursor: pointer;
- transition: all 0.3s ease;
- display: flex;
- align-items: center;
- gap: 8px;
- white-space: nowrap;
- box-shadow: 0 2px 4px rgba(0,0,0,0.02);
-
- &:hover {
- border-color: #3E7BFA;
- color: #3E7BFA;
- transform: translateY(-1px);
- box-shadow: 0 4px 8px rgba(0,0,0,0.05);
- }
-
- .question-icon {
- width: 16px;
- height: 16px;
- object-fit: contain;
- flex-shrink: 0;
- }
- }
- }
- /* 用户推荐问题 */
- .user-recommend-questions {
- position: absolute;
- bottom: 75px; /* 位于输入框上方 */
- left: 360px; /* 左侧边栏宽度 */
- right: 0;
- max-width: 900px; /* 与输入框容器的最大宽度一致 */
- margin: 0 auto; /* 居中显示 */
- background: white;
- border-radius: 12px;
- padding: 16px 20px;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
- border: 1px solid #E5E8EB;
- z-index: 1; /* 降低z-index,避免覆盖输入框按钮 */
-
- .recommend-list {
- display: flex;
- flex-direction: column;
- gap: 8px;
- max-height: 280px; /* 限制高度,大约5条内容的高度 */
- overflow-y: auto; /* 超过高度时显示滚动条 */
-
- /* 自定义滚动条样式 */
- &::-webkit-scrollbar {
- width: 6px;
- }
-
- &::-webkit-scrollbar-track {
- background: #f1f5f9;
- border-radius: 3px;
- }
-
- &::-webkit-scrollbar-thumb {
- background: #cbd5e1;
- border-radius: 3px;
-
- &:hover {
- background: #94a3b8;
- }
- }
-
- .recommend-item {
- padding: 8px 10px;
- font-size: 16px;
- color: #000;
- cursor: pointer;
- transition: color 0.2s ease;
- line-height: 1.4;
- // border-bottom: 1px solid #F3F4F6;
-
- &:last-child {
- border-bottom: none;
- }
-
- &:hover {
- // color: #3E7BFA;
- background-color: #F5F6F9;
- border-radius: 10px;
- }
- }
- }
- }
- /* 文件预览区域 */
- .file-preview-section {
- margin-bottom: 12px;
-
- .file-preview {
- position: relative;
- display: flex;
- align-items: center;
- background: rgba(255, 255, 255, 0.9);
- border: 1px solid #E5E7EB;
- border-radius: 12px;
- padding: 12px;
- max-width: 400px;
-
- .file-icon {
- font-size: 32px;
- margin-right: 12px;
- width: 48px;
- text-align: center;
-
- .file-icon-img {
- width: 32px;
- height: 32px;
- object-fit: contain;
- }
- }
-
- .file-info {
- flex: 1;
-
- .file-name {
- font-size: 14px;
- font-weight: 500;
- color: #374151;
- margin-bottom: 4px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- max-width: 200px;
- }
-
- .file-size {
- font-size: 12px;
- color: #6B7280;
- margin-bottom: 4px;
- }
-
- }
-
- .remove-file-btn {
- width: 24px;
- height: 24px;
- border: none;
- background: rgba(239, 68, 68, 0.1);
- color: #DC2626;
- border-radius: 50%;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- transition: all 0.2s ease;
-
- &:hover {
- background: rgba(239, 68, 68, 0.2);
- transform: scale(1.1);
- }
-
- .remove-icon {
- font-size: 16px;
- font-weight: bold;
- }
- }
- }
- }
- /* 底部输入区域 */
- .chat-input-section {
- background: transparent;
- padding: 9px 30px;
-
- .input-container {
- max-width: 900px;
- margin: 0 auto;
-
-
- .input-box {
- display: flex;
- flex-direction: column;
- background: white;
- border-radius: 16px;
- padding: 12px 16px;
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
- transition: box-shadow 0.3s ease;
- border: 1px solid transparent;
- min-height: 120px;
-
- &:focus-within {
- box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
- border-color: #E5E8EB;
- }
-
- .attach-btn, .voice-btn, .network-search-btn {
- background: none;
- border: none;
- cursor: pointer;
- padding: 8px;
- border-radius: 6px;
- transition: all 0.3s ease;
- display: flex;
- align-items: center;
- justify-content: center;
- position: relative;
-
- &:hover:not(:disabled) {
- background: rgba(102, 126, 234, 0.1);
- }
-
- &:disabled {
- cursor: not-allowed;
- }
-
- &.recording {
- background: rgba(239, 68, 68, 0.1);
- animation: pulse 1.5s ease-in-out infinite;
- }
-
- &.active {
- background: rgba(62, 123, 250, 0.15);
-
- &:hover:not(:disabled) {
- background: rgba(62, 123, 250, 0.2);
- }
- }
-
- .icon-container {
- width: 20px;
- height: 20px;
- display: flex;
- align-items: center;
- justify-content: center;
- flex-shrink: 0;
- position: relative;
- }
-
- .recording-indicator {
- position: absolute;
- top: -2px;
- right: -2px;
- width: 8px;
- height: 8px;
- background: #ef4444;
- border-radius: 50%;
- animation: blink 1s ease-in-out infinite;
- }
-
- .action-icon {
- width: 20px;
- height: 20px;
- height: 20px !important;
- max-width: 20px !important;
- max-height: 20px !important;
- object-fit: contain;
- flex-shrink: 0;
- }
-
- // 联网搜索SVG图标样式
- .network-search-icon {
- width: 20px;
- height: 20px;
- color: #6B7280;
- transition: color 0.3s ease;
- flex-shrink: 0;
- }
- }
-
- // 联网搜索按钮激活状态下的图标颜色
- .network-search-btn.active .network-search-icon {
- color: #3E7BFA;
- }
-
- .mode-chips {
- display: flex;
- gap: 8px;
- margin-right: 12px;
- }
-
- .mode-chip {
- display: flex;
- align-items: center;
- background: transparent;
- color: #2C3E50;
- padding: 6px 12px;
- border-radius: 20px;
- font-size: 14px;
- font-weight: 500;
- gap: 6px;
- cursor: pointer;
- transition: all 0.2s ease;
- border: 1px solid transparent;
-
- .chip-icon {
- width: 16px;
- height: 16px;
- object-fit: contain;
- /* 将黑色图标转为灰色以匹配原图 */
- filter: invert(40%) sepia(8%) saturate(500%) hue-rotate(180deg) brightness(95%) contrast(85%);
- transition: filter 0.2s ease;
- }
-
- &:hover {
- background: #E8F0FE;
- color: #3E7BFA;
-
- .chip-icon {
- filter: invert(41%) sepia(91%) saturate(3574%) hue-rotate(213deg) brightness(101%) contrast(96%);
- }
- }
- }
- .expand-btn {
- background: none;
- border: none;
- cursor: pointer;
- padding: 8px;
- border-radius: 6px;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-right: 8px;
-
- &:hover:not(:disabled) {
- background: rgba(102, 126, 234, 0.1);
- }
- &:disabled {
- cursor: not-allowed;
- opacity: 0.5;
- }
- }
- .message-input {
- flex: 1;
- width: 100%;
- border: none;
- background: transparent;
- font-size: 15px;
- color: #2C3E50;
- outline: none;
- resize: none;
- font-family: inherit;
- padding: 0 4px;
- margin-bottom: 12px;
-
- &::placeholder {
- color: #A0A6B8;
- }
-
- &:disabled {
- cursor: not-allowed;
- }
- }
- .input-toolbar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- width: 100%;
- .toolbar-left, .toolbar-right {
- display: flex;
- align-items: center;
- gap: 12px;
- }
- .model-link-btn, .attach-btn {
- background: none;
- border: none;
- cursor: pointer;
- padding: 8px;
- border-radius: 6px;
- display: flex;
- align-items: center;
- justify-content: center;
-
- &:hover:not(:disabled) {
- background: rgba(102, 126, 234, 0.1);
- }
-
- &:disabled {
- cursor: not-allowed;
- opacity: 0.5;
- }
- &.active {
- background: rgba(102, 126, 234, 0.1);
- }
- .action-icon {
- width: 20px;
- height: 20px;
- object-fit: contain;
- }
- .active-icon {
- filter: invert(41%) sepia(91%) saturate(3574%) hue-rotate(213deg) brightness(101%) contrast(96%);
- }
- }
- }
-
- .divider {
- width: 1px;
- height: 31px;
- background-color: #D6D5DE;
- margin: 0 4px;
- }
-
- .send-btn {
- background: none;
- border: none;
- cursor: pointer;
- margin-left: 4px;
- // padding: 8px;
- display: flex;
- align-items: center;
- justify-content: center;
- border-radius: 6px;
- transition: background 0.3s ease;
- display: flex;
- align-items: center;
- justify-content: center;
-
- &:hover:not(:disabled) {
- background: rgba(102, 126, 234, 0.1);
- }
-
- &:disabled {
- cursor: not-allowed;
- }
-
- .send-icon-circle {
- width: 36px;
- height: 36px;
- border-radius: 50%;
- background-color: #B0C4DE; /* Disabled state color */
- display: flex;
- align-items: center;
- justify-content: center;
- transition: background-color 0.3s ease;
-
- &.active {
- background-color: #7B9AF3; /* Active state color (matches the light blue in the image) */
- }
-
- svg {
- width: 20px;
- height: 20px;
- }
- }
-
- .stop-text {
- color: #FF4D4F;
- font-size: 14px;
- font-weight: 500;
- padding: 8px 16px;
- white-space: nowrap;
- }
- }
- }
- }
- }
- /* 点赞和点踩按钮的图标颜色变化 */
- .thumbs-up-btn.active .action-icon {
- /* 绿色图标 */
- filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(142deg) brightness(104%) contrast(97%) !important;
- }
- .thumbs-down-btn.active .action-icon {
- /* 红色图标 */
- filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(0deg) brightness(104%) contrast(97%) !important;
- }
- /* 历史记录加载状态样式 */
- .history-loading {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 40px 20px;
- min-height: 200px;
- }
- .history-loading .loading-spinner {
- width: 32px;
- height: 32px;
- border: 3px solid #f3f3f3;
- border-top: 3px solid #409eff;
- border-radius: 50%;
- animation: spin 1s linear infinite;
- margin: 0 auto 16px auto;
- }
- .history-loading .loading-text {
- color: #6B7280;
- font-size: 14px;
- margin: 0;
- font-weight: 400;
- }
- @keyframes spin {
- 0% { transform: rotate(0deg); }
- 100% { transform: rotate(360deg); }
- }
- /* 联网搜索Loading样式 */
- .online-search-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 12px;
- margin-left: 52px;
- width: fit-content;
- }
- .online-search-loading .thinking-animation {
- display: flex;
- gap: 4px;
- }
- .online-search-loading .thinking-animation .dot {
- width: 6px;
- height: 6px;
- background: #9CA3AF;
- border-radius: 50%;
- animation: thinking 1.4s infinite ease-in-out;
- }
- .online-search-loading .thinking-animation .dot:nth-child(1) {
- animation-delay: -0.32s;
- }
- .online-search-loading .thinking-animation .dot:nth-child(2) {
- animation-delay: -0.16s;
- }
- .online-search-loading .thinking-animation .dot:nth-child(3) {
- animation-delay: 0s;
- }
- /* 推荐问题Loading样式 */
- .related-questions-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 12px;
- margin-left: 52px;
- width: fit-content;
- }
- .related-questions-loading .thinking-animation {
- display: flex;
- gap: 4px;
- }
- .related-questions-loading .thinking-animation .dot {
- width: 6px;
- height: 6px;
- background: #9CA3AF;
- border-radius: 50%;
- animation: thinking 1.4s infinite ease-in-out;
- }
- .related-questions-loading .thinking-animation .dot:nth-child(1) {
- animation-delay: -0.32s;
- }
- .related-questions-loading .thinking-animation .dot:nth-child(2) {
- animation-delay: -0.16s;
- }
- .related-questions-loading .thinking-animation .dot:nth-child(3) {
- animation-delay: 0s;
- }
- @keyframes pulse {
- 0%, 100% {
- transform: scale(1);
- opacity: 1;
- }
- 50% {
- transform: scale(1.05);
- opacity: 0.8;
- }
- }
- @keyframes blink {
- 0%, 50% {
- opacity: 1;
- }
- 51%, 100% {
- opacity: 0.3;
- }
- }
- /* ReportGenerator加载状态指示器样式(在AI回复下方左侧) */
- .report-generator-loading {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 12px 16px;
- margin-left: 52px; /* 与AI头像对齐,和提问联想一致 */
- margin-top: 20px;
- }
- .report-generator-loading .loading-dots {
- display: flex;
- gap: 4px;
- }
- .report-generator-loading .loading-dots span {
- width: 6px;
- height: 6px;
- border-radius: 50%;
- background: #5b8def;
- animation: thinking 1.4s infinite ease-in-out;
- }
- .report-generator-loading .loading-dots span:nth-child(1) {
- animation-delay: -0.32s;
- }
- .report-generator-loading .loading-dots span:nth-child(2) {
- animation-delay: -0.16s;
- }
- .report-generator-loading .loading-dots span:nth-child(3) {
- animation-delay: 0s;
- }
- .report-generator-loading .loading-text {
- color: #5b8def;
- font-size: 14px;
- font-weight: 500;
- }
- /* 报告列表内Loading样式 */
- .report-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 20px;
- margin: 12px 0;
- }
- .report-loading .thinking-animation {
- display: flex;
- gap: 6px;
- }
- .report-loading .thinking-animation .dot {
- width: 8px;
- height: 8px;
- border-radius: 50%;
- background: #5b8def;
- animation: thinking 1.4s infinite ease-in-out;
- }
- .report-loading .thinking-animation .dot:nth-child(1) {
- animation-delay: -0.32s;
- }
- .report-loading .thinking-animation .dot:nth-child(2) {
- animation-delay: -0.16s;
- }
- .report-loading .thinking-animation .dot:nth-child(3) {
- animation-delay: 0s;
- }
- /* AI写作文件卡片样式 */
- .ai-writing-block {
- margin-top: 8px;
-
- .ai-writing-status-text {
- font-size: 14px;
- color: #606266;
- margin-bottom: 12px;
- line-height: 1.6;
- }
-
- .ai-writing-file-card {
- display: flex;
- align-items: center;
- background: #F5F7FA;
- border: 1px solid #E4E7ED;
- border-radius: 12px;
- padding: 16px 20px;
- cursor: pointer;
- transition: all 0.3s ease;
- max-width: 360px;
-
- &:hover {
- background: #EDF2FC;
- border-color: #3E7BFA;
- box-shadow: 0 2px 12px rgba(62, 123, 250, 0.15);
- transform: translateY(-1px);
- }
-
- .file-card-icon {
- width: 40px;
- height: 40px;
- background: #2B5797;
- border-radius: 8px;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-right: 14px;
- flex-shrink: 0;
-
- .word-icon {
- color: white;
- font-size: 20px;
- font-weight: 700;
- font-family: 'Segoe UI', sans-serif;
- }
- }
-
- .file-card-info {
- flex: 1;
- min-width: 0;
-
- .file-card-title {
- font-size: 15px;
- font-weight: 600;
- color: #1F2937;
- margin-bottom: 4px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- .file-card-time {
- font-size: 12px;
- color: #9CA3AF;
- }
- }
- }
- }
- /* AI写作侧边栏样式 */
- .ai-writing-sidebar {
- position: relative;
- flex: 0 0 40%;
- width: 40%;
- min-width: 360px;
- max-width: 520px;
- height: 100%;
- background: white;
- box-shadow: -4px 0 24px rgba(0, 0, 0, 0.1);
- z-index: 1;
- display: flex;
- flex-direction: column;
- overflow: hidden;
- border-left: 1px solid #E4E7ED;
-
- .sidebar-header {
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 20px 24px 16px 24px;
- border-bottom: 1px solid #E4E7ED;
- flex-shrink: 0;
-
- .sidebar-title {
- font-size: 18px;
- font-weight: 600;
- color: #1F2937;
- margin: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- flex: 1;
- margin-right: 16px;
- }
-
- .sidebar-header-actions {
- display: flex;
- align-items: center;
- gap: 8px;
-
- .sidebar-close-btn {
- width: 32px;
- height: 32px;
- border: none;
- background: #F5F7FA;
- border-radius: 8px;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- transition: all 0.2s ease;
-
- &:hover {
- background: #E4E7ED;
- }
- }
- }
- }
-
- .sidebar-toolbar {
- display: flex;
- align-items: center;
- padding: 10px 24px;
- border-bottom: 1px solid #F0F2F5;
- gap: 12px;
- flex-shrink: 0;
-
- .toolbar-label {
- font-size: 14px;
- color: #606266;
- margin-right: 4px;
- }
-
- .toolbar-font-size {
- font-size: 13px;
- color: #909399;
- margin-right: 8px;
- }
-
- .toolbar-divider {
- width: 1px;
- height: 20px;
- background: #E4E7ED;
- margin: 0 4px;
- }
-
- .toolbar-btn {
- width: 32px;
- height: 32px;
- border: none;
- background: transparent;
- border-radius: 6px;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 15px;
- color: #606266;
- transition: all 0.2s ease;
-
- &:hover {
- background: #F5F7FA;
- }
- }
- }
-
- .sidebar-content {
- flex: 1;
- overflow-y: auto;
- padding: 24px;
-
- .sidebar-doc-content {
- font-size: 15px;
- line-height: 1.8;
- color: #303133;
- white-space: pre-wrap;
- word-break: break-word;
-
- :deep(h1), :deep(h2), :deep(h3) {
- margin: 16px 0 8px 0;
- color: #1F2937;
- }
-
- :deep(p) {
- margin: 8px 0;
- }
-
- :deep(ul), :deep(ol) {
- padding-left: 24px;
- margin: 8px 0;
- }
-
- :deep(li) {
- margin: 4px 0;
- }
- }
-
- .sidebar-generating-hint {
- display: flex;
- align-items: center;
- margin-top: 24px;
- color: #3E7BFA;
- font-size: 14px;
-
- .generating-text-hint {
- margin-right: 4px;
- }
-
- .generating-dots {
- display: flex;
- gap: 2px;
-
- .dot {
- animation: dot-blink 1.4s infinite ease-in-out;
-
- &:nth-child(1) { animation-delay: 0s; }
- &:nth-child(2) { animation-delay: 0.2s; }
- &:nth-child(3) { animation-delay: 0.4s; }
- }
- }
- }
- }
- }
- @media (max-width: 1200px) {
- .chat-main-area {
- flex-direction: column;
- }
- .ai-writing-sidebar {
- flex: 0 0 auto;
- width: 100%;
- min-width: 0;
- max-width: none;
- height: 45vh;
- border-left: none;
- border-top: 1px solid #E4E7ED;
- }
- }
- @keyframes dot-blink {
- 0%, 80%, 100% { opacity: 0.3; }
- 40% { opacity: 1; }
- }
- /* 侧边栏滑入滑出动画 */
- .sidebar-slide-enter-active,
- .sidebar-slide-leave-active {
- transition: transform 0.3s ease;
- }
- .sidebar-slide-enter-from,
- .sidebar-slide-leave-to {
- transform: translateX(100%);
- }
- .sidebar-slide-enter-to,
- .sidebar-slide-leave-from {
- transform: translateX(0);
- }
- /* 规范引用样式 */
- :deep(.standard-reference) {
- background-color: #EAEAEE !important;
- color: #616161 !important;
- font-size: 0.75rem !important;
- padding: 3px 8px !important;
- border-radius: 6px !important;
- cursor: pointer !important;
- display: inline-block !important;
- margin: 4px 2px !important;
- border: 1px solid #EAEAEE !important;
- font-weight: 500 !important;
- transition: all 0.2s ease !important;
- line-height: 1.4 !important;
- max-width: 680px !important;
- white-space: nowrap !important;
- overflow: hidden !important;
- text-overflow: ellipsis !important;
- //向下移动
- transform: translateY(12px) !important;
- }
- :deep(.standard-reference:hover) {
- background-color: #d1d5db !important;
- border-color: #d1d5db !important;
- }
- </style>
|