m-Chat.vue 193 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255
  1. <template>
  2. <div class="mobile-chat">
  3. <!-- 移动端AI问答页面 -->
  4. <MobileHeader title="AI问答" @back="goBack" @menu="showHistoryDrawer" />
  5. <div class="mobile-content">
  6. <!-- 通用历史记录抽屉 -->
  7. <MobileHistoryDrawer
  8. :visible="!isSending && !hasTypingMessage && showHistory"
  9. title="历史记录"
  10. :historyData="historyData"
  11. :loading="isLoadingHistory"
  12. @close="showHistory = false"
  13. @createNewTask="startNewChat"
  14. @handleHistoryItem="handleHistoryItem"
  15. @deleteHistoryItem="deleteHistoryItem"
  16. />
  17. <!-- 初始状态:AI助手介绍和功能卡片 -->
  18. <div v-if="!showChat" class="initial-content">
  19. <!-- AI助手介绍 -->
  20. <div class="ai-intro">
  21. <div class="ai-avatar">
  22. <img :src="aiAvatarIcon" alt="AI头像" class="ai-avatar-img">
  23. </div>
  24. <div class="ai-greeting">
  25. <h3>我是蜀道安全管理AI智能助手,您的得力帮手</h3>
  26. <p>我可以帮您处理这些事情</p>
  27. </div>
  28. </div>
  29. <!-- 功能卡片 -->
  30. <div class="function-cards">
  31. <div
  32. v-for="(card, index) in functionCards"
  33. :key="card.id || index"
  34. class="function-card"
  35. @click="handleFunctionCard(card.function_title)"
  36. >
  37. <div class="card-header">
  38. <div class="card-icon">
  39. <img :src="getFunctionCardIcon(card.function_title)" :alt="card.function_title" class="card-icon-img">
  40. </div>
  41. <h4>{{ card.function_title }}</h4>
  42. </div>
  43. <div class="card-description">
  44. <p>{{ card.function_content }}</p>
  45. </div>
  46. </div>
  47. <!-- 如果没有数据,显示默认卡片 -->
  48. <div v-if="functionCards.length === 0" class="function-card" @click="handleFunctionCard('桥梁结构设计问题')">
  49. <div class="card-header">
  50. <div class="card-icon">
  51. <img :src="bridgeIcon" alt="桥梁结构设计问题" class="card-icon-img">
  52. </div>
  53. <h4>桥梁结构设计问题</h4>
  54. </div>
  55. <div class="card-description">
  56. <p>各类桥梁结构设计,计算与分析</p>
  57. </div>
  58. </div>
  59. <div v-if="functionCards.length === 0" class="function-card" @click="handleFunctionCard('桥梁施工技术咨询')">
  60. <div class="card-header">
  61. <div class="card-icon">
  62. <img :src="constructionIcon" alt="施工技术咨询" class="card-icon-img">
  63. </div>
  64. <h4>施工技术咨询</h4>
  65. </div>
  66. <div class="card-description">
  67. <p>桥梁施工方法,工艺与技术要点</p>
  68. </div>
  69. </div>
  70. <div v-if="functionCards.length === 0" class="function-card" @click="handleFunctionCard('材料与力学问题')">
  71. <div class="card-header">
  72. <div class="card-icon">
  73. <img :src="materialIcon" alt="材料与力学问题" class="card-icon-img">
  74. </div>
  75. <h4>材料与力学问题</h4>
  76. </div>
  77. <div class="card-description">
  78. <p>建筑材料性能与结构力学分析</p>
  79. </div>
  80. </div>
  81. <div v-if="functionCards.length === 0" class="function-card" @click="handleFunctionCard('规范标准查询')">
  82. <div class="card-header">
  83. <div class="card-icon">
  84. <img :src="standardIcon" alt="规范标准查询" class="card-icon-img">
  85. </div>
  86. <h4>规范标准查询</h4>
  87. </div>
  88. <div class="card-description">
  89. <p>行业规范,标准解读与应用</p>
  90. </div>
  91. </div>
  92. </div>
  93. </div>
  94. <!-- 聊天对话区域 -->
  95. <div v-else class="chat-messages">
  96. <div
  97. v-for="(message, index) in chatMessages"
  98. :key="index"
  99. :class="['message-item', message.type]"
  100. >
  101. <!-- 用户消息 -->
  102. <div v-if="message.type === 'user'" class="user-message">
  103. <div class="message-content">
  104. <!-- 文本内容 -->
  105. <div v-if="message.content" class="message-text">{{ message.content }}</div>
  106. </div>
  107. <div class="message-actions">
  108. <button class="action-btn copy-btn" @click="copyUserMessage(message)" title="复制">
  109. <img :src="copyIcon" alt="复制" class="action-icon">
  110. </button>
  111. <button class="action-btn edit-btn" @click="editUserMessage(message)" title="编辑">
  112. <img :src="editIcon" alt="编辑" class="action-icon">
  113. </button>
  114. </div>
  115. </div>
  116. <!-- AI消息 -->
  117. <div v-else-if="message.type === 'ai'" class="ai-message">
  118. <!-- 网络搜索胶囊 - 在输出框上方 -->
  119. <div v-if="message.webSearchRaw && message.webSearchRaw.total > 0" class="web-search-capsule-outer">
  120. <WebSearchCapsule
  121. :total="message.webSearchRaw.total"
  122. :results="message.webSearchRaw.results"
  123. :isExpanded="false"
  124. @toggle="handleWebSearchToggle(message.webSearchRaw)"
  125. />
  126. </div>
  127. <!-- AI消息主体 -->
  128. <div class="ai-message-main">
  129. <!-- AI头像 -->
  130. <div class="ai-avatar-small">
  131. <img :src="aiAvatarIcon" alt="AI" class="ai-icon">
  132. </div>
  133. <!-- 白色气泡容器 - 所有内容都在里面 -->
  134. <div class="message-content" :data-message-index="index" :ref="el => messageContentRefs[index] = el">
  135. <!-- AI响应内容 -->
  136. <div class="ai-response-content">
  137. <!-- 进度统计卡片 -->
  138. <div
  139. v-if="message.showStats"
  140. class="stats-card"
  141. >
  142. <div class="stats-left">
  143. <StatusAvatar
  144. :status="getAvatarStatus(message.currentStatus, message.progress)"
  145. :size="28"
  146. class="stats-avatar"
  147. />
  148. <span v-html="message.statusMessage" class="status-text"></span>
  149. </div>
  150. <!-- 进度条 -->
  151. <div v-if="message.progress < 100" class="progress-capsule-inline">
  152. <div class="progress-bar-mini">
  153. <div class="progress-fill" :style="{ width: message.progress + '%' }"></div>
  154. <div class="progress-dot" :style="{ left: message.progress + '%' }"></div>
  155. </div>
  156. <span class="progress-percentage">{{ message.progress }}%</span>
  157. </div>
  158. </div>
  159. <!-- 问题总结 -->
  160. <div v-if="message.summary" class="question-summary">
  161. <StreamMarkdown :content="message.summary" :streaming="false" />
  162. </div>
  163. <!-- 报告生成中的Loading动画 - 当还没有报告时显示 -->
  164. <div v-if="message.isTyping && (!message.reports || message.reports.length === 0) && message.progress < 100" class="report-loading">
  165. <span class="loading-text">AI正在思考中...</span>
  166. <div class="thinking-animation">
  167. <span class="dot"></span>
  168. <span class="dot"></span>
  169. <span class="dot"></span>
  170. </div>
  171. </div>
  172. <!-- 报告列表 -->
  173. <div v-if="message.reports && message.reports.length > 0" class="reports-list">
  174. <template v-for="(report, rIndex) in message.reports" :key="`${report.source_file}-${report.file_index}-${rIndex}`">
  175. <!-- 类别标题 -->
  176. <CategoryTitle
  177. v-if="report.type === 'category_title'"
  178. :category="report.category"
  179. :number="report.number"
  180. :count="report.count"
  181. @toggle="(data) => handleCategoryToggle(index, data)"
  182. />
  183. <!-- 文件报告 -->
  184. <FileReportCard
  185. v-else-if="!report.type || report.type !== 'category_title'"
  186. v-show="isCategoryExpanded(index, report.metadata?._displayCategory || report.metadata?.primary_category)"
  187. :report="report"
  188. @preview-file="handleFilePreview"
  189. />
  190. </template>
  191. <!-- 分类下的Loading动画 -->
  192. <div v-if="message.isTyping && message.progress < 100 && hasOnlyCategoryTitles(message.reports)" class="report-loading">
  193. <span class="loading-text">AI正在思考中...</span>
  194. <div class="thinking-animation">
  195. <span class="dot"></span>
  196. <span class="dot"></span>
  197. <span class="dot"></span>
  198. </div>
  199. </div>
  200. </div>
  201. <!-- 网络搜索总结 -->
  202. <div v-if="message.hasWebSearchResults && message.webSearchSummary">
  203. <WebSearchSummary :summary="message.webSearchSummary" />
  204. </div>
  205. <!-- AI文本内容(如果没有报告数据时显示) -->
  206. <div v-if="!message.reports || message.reports.length === 0" class="ai-text">
  207. <div v-if="message.displayContent && message.displayContent.length > 0" class="ai-markdown-content">
  208. <div v-html="message.displayContent"></div>
  209. </div>
  210. </div>
  211. </div>
  212. <!-- 操作按钮 - 在白色气泡内 -->
  213. <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary)" class="divider"></div>
  214. <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary)" class="message-actions">
  215. <div class="left-actions">
  216. <button class="action-btn copy-btn" @click="copyAIMessage(message)" title="复制">
  217. <img :src="copyIcon" alt="复制" class="action-icon">
  218. </button>
  219. <button class="action-btn regenerate-btn" @click="regenerateResponse(index)" :disabled="hasTypingMessage" title="重新生成">
  220. <img :src="regenerateIcon" alt="重新生成" class="action-icon">
  221. </button>
  222. <button v-if="false" class="action-btn voice-btn" @click="handleVoiceRead(message)" :title="isSpeaking(message.id) ? '停止朗读' : '语音朗读'" :class="{ speaking: isSpeaking(message.id) }">
  223. <img :src="voiceIcon" alt="语音朗读" class="action-icon">
  224. </button>
  225. </div>
  226. <div class="right-actions">
  227. <button
  228. class="action-btn thumbs-up-btn"
  229. :class="{ active: message.userFeedback === 'like' }"
  230. @click="handleThumbsUp(message)"
  231. :title="message.userFeedback === 'like' ? '取消点赞' : '点赞'"
  232. >
  233. <img :src="likeIcon" alt="点赞" class="action-icon">
  234. </button>
  235. <button
  236. class="action-btn thumbs-down-btn"
  237. :class="{ active: message.userFeedback === 'dislike' }"
  238. @click="handleThumbsDown(message)"
  239. :title="message.userFeedback === 'dislike' ? '取消点踩' : '点踩'"
  240. >
  241. <img :src="dislikeIcon" alt="踩" class="action-icon">
  242. </button>
  243. </div>
  244. </div>
  245. </div>
  246. </div>
  247. <!-- 推荐问题Loading -->
  248. <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary || (message.reports && message.reports.length > 0)) && isGettingRelatedQuestions && (relatedQuestionsMessageId === message.id || relatedQuestionsMessageId === message.ai_message_id) && aiRelatedQuestions.length === 0" class="related-questions-loading">
  249. <div class="thinking-animation">
  250. <span class="dot"></span>
  251. <span class="dot"></span>
  252. <span class="dot"></span>
  253. </div>
  254. </div>
  255. <!-- 猜你想问 -->
  256. <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary || (message.reports && message.reports.length > 0)) && (relatedQuestionsMessageId === message.id || relatedQuestionsMessageId === message.ai_message_id) && aiRelatedQuestions.length > 0" class="related-questions">
  257. <div
  258. v-for="(question, index) in aiRelatedQuestions"
  259. :key="index"
  260. class="related-question-item"
  261. @click="handleRelatedQuestion(question)"
  262. >
  263. <span>{{ question }}</span>
  264. <svg class="arrow-icon" viewBox="0 0 16 16" fill="none">
  265. <path d="M6 4L10 8L6 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
  266. </svg>
  267. </div>
  268. </div>
  269. </div>
  270. </div>
  271. </div>
  272. <!-- 底部输入区域 -->
  273. <div class="chat-input-section">
  274. <div class="input-container">
  275. <div class="input-box">
  276. <!-- 联网搜索 -->
  277. <button
  278. class="network-search-btn"
  279. :class="{ active: isNetworkSearchEnabled }"
  280. @click="toggleNetworkSearch"
  281. :title="isNetworkSearchEnabled ? '关闭联网搜索' : '启用联网搜索'"
  282. :disabled="isSending || hasTypingMessage"
  283. >
  284. <div class="icon-container">
  285. <img :src="isNetworkSearchEnabled ? networkSearchIconOn : networkSearchIconOff" alt="联网搜索" class="action-icon">
  286. </div>
  287. </button>
  288. <div class="divider"></div>
  289. <input
  290. type="text"
  291. placeholder="请在此处发送消息"
  292. class="message-input"
  293. v-model="messageText"
  294. @keyup.enter="sendMessage"
  295. :disabled="isSending || hasTypingMessage"
  296. maxlength="2000"
  297. >
  298. <button class="voice-btn" @click="handleVoiceClick" :disabled="isSending || hasTypingMessage" :class="{ 'recording': isListening }">
  299. <div class="icon-container">
  300. <img :src="voiceInputIcon" alt="语音" class="action-icon">
  301. <div v-if="isListening" class="recording-indicator"></div>
  302. </div>
  303. </button>
  304. <div class="divider"></div>
  305. <button
  306. v-if="!isSending"
  307. class="send-btn"
  308. @click="sendMessage"
  309. :disabled="hasTypingMessage || !messageText.trim()"
  310. >
  311. <img :src="messageText.trim() ? sendIconFilled : sendIconEmpty" alt="发送" class="send-icon">
  312. </button>
  313. <button
  314. v-else
  315. class="send-btn stop-btn"
  316. @click="handleStopGeneration"
  317. title="停止生成"
  318. >
  319. <span class="stop-text" style="color: #FF4D4F;">停止</span>
  320. </button>
  321. </div>
  322. </div>
  323. </div>
  324. </div>
  325. <!-- 移动端轻提示 -->
  326. <MobileToast
  327. :visible="showToast"
  328. :message="toastMessage"
  329. :duration="toastDuration"
  330. @close="showToast = false"
  331. />
  332. <!-- 删除确认弹窗 -->
  333. <DeleteConfirmModal
  334. :visible="showDeleteModal"
  335. :title="deleteConfirmTitle"
  336. :message="deleteConfirmMessage"
  337. @confirm="confirmDelete"
  338. @cancel="cancelDelete"
  339. @close="cancelDelete"
  340. />
  341. <!-- 网络搜索弹窗 -->
  342. <div v-if="showWebSearchModal" class="web-search-modal-overlay" @click="showWebSearchModal = false">
  343. <div class="web-search-modal" @click.stop>
  344. <div class="web-search-modal-header">
  345. <h3>联网搜索结果</h3>
  346. <button class="close-btn" @click="showWebSearchModal = false">✕</button>
  347. </div>
  348. <div class="web-search-modal-content">
  349. <div v-if="currentWebSearchData && currentWebSearchData.results" class="search-results">
  350. <div class="search-count">找到 {{ currentWebSearchData.total || currentWebSearchData.results.length }} 个相关结果</div>
  351. <div
  352. v-for="(result, index) in currentWebSearchData.results"
  353. :key="index"
  354. class="search-result-item"
  355. @click="handleSearchResultClick(result)"
  356. >
  357. <div class="result-header">
  358. <div class="result-index">{{ index + 1 }}</div>
  359. <div class="result-title">{{ result.title }}</div>
  360. </div>
  361. <div class="result-content">{{ result.content || result.snippet }}</div>
  362. <div class="result-footer">
  363. <span class="result-url">{{ formatUrl(result.url || result.link) }}</span>
  364. <span v-if="result.score" class="result-score">{{ (result.score * 100).toFixed(1) }}%</span>
  365. </div>
  366. </div>
  367. </div>
  368. </div>
  369. </div>
  370. </div>
  371. <!-- 网页预览弹窗 -->
  372. <div v-if="showWebPreview" class="web-preview-overlay" @click="showWebPreview = false">
  373. <div class="web-preview-modal" @click.stop>
  374. <div class="web-preview-header">
  375. <h3>{{ previewTitle }}</h3>
  376. <button class="close-btn" @click="showWebPreview = false">✕</button>
  377. </div>
  378. <div class="web-preview-content">
  379. <iframe v-if="previewUrl" :src="previewUrl" frameborder="0" class="preview-iframe"></iframe>
  380. <div v-else class="iframe-error">
  381. <p>无法加载网页预览</p>
  382. <button class="open-link-btn" @click="openInNewTab">在新标签页中打开</button>
  383. </div>
  384. </div>
  385. </div>
  386. </div>
  387. <!-- 文件预览弹窗 -->
  388. <div v-if="showFilePreview" class="file-preview-overlay" @click="showFilePreview = false">
  389. <div class="file-preview-modal" @click.stop>
  390. <div class="file-preview-header">
  391. <div class="header-left">
  392. <svg class="file-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
  393. <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z" />
  394. </svg>
  395. <div class="header-text">
  396. <h3>文件预览</h3>
  397. <span v-if="previewFileName" class="file-name">{{ previewFileName }}</span>
  398. </div>
  399. </div>
  400. <button class="close-btn" @click="showFilePreview = false">✕</button>
  401. </div>
  402. <div class="file-preview-content">
  403. <div v-if="fileLoading" class="file-loading">
  404. <div class="loading-spinner"></div>
  405. <p>加载中...</p>
  406. </div>
  407. <div v-else-if="fileError" class="file-error">
  408. <svg class="error-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
  409. <path d="M12,2C17.53,2 22,6.47 22,12C22,17.53 17.53,22 12,22C6.47,22 2,17.53 2,12C2,6.47 6.47,2 12,2M15.59,7L12,10.59L8.41,7L7,8.41L10.59,12L7,15.59L8.41,17L12,13.41L15.59,17L17,15.59L13.41,12L17,8.41L15.59,7Z" />
  410. </svg>
  411. <p>{{ fileError }}</p>
  412. </div>
  413. <MobilePdfViewer
  414. v-else-if="previewFilePath && previewFileName.toLowerCase().endsWith('.pdf')"
  415. :url="previewFilePath"
  416. />
  417. <iframe
  418. v-else-if="previewFilePath"
  419. :src="previewFilePath"
  420. frameborder="0"
  421. class="file-iframe"
  422. @load="fileLoading = false"
  423. @error="fileError = '文件加载失败'"
  424. ></iframe>
  425. <div v-else class="file-empty">
  426. <svg class="empty-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
  427. <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z" />
  428. </svg>
  429. <p>暂无预览内容</p>
  430. </div>
  431. </div>
  432. </div>
  433. </div>
  434. </div>
  435. </template>
  436. <script setup>
  437. import { useRouter, useRoute } from 'vue-router'
  438. import MobileHeader from '@/components/MobileHeader.vue'
  439. import DeleteConfirmModal from '@/components/DeleteConfirmModal.vue'
  440. import MobileToast from '@/components/MobileToast.vue'
  441. import MobileHistoryDrawer from '@/components/MobileHistoryDrawer.vue'
  442. import CategoryTitle from '@/components/CategoryTitle.vue'
  443. import FileReportCard from '@/components/FileReportCard.vue'
  444. import StreamMarkdown from '@/components/StreamMarkdown.vue'
  445. import WebSearchCapsule from '@/components/WebSearchCapsule.vue'
  446. import WebSearchSummary from '@/components/WebSearchSummary.vue'
  447. import StatusAvatar from '@/components/StatusAvatar.vue'
  448. import MobilePdfViewer from '@/components/MobilePdfViewer.vue'
  449. import { ref, onMounted, watch, nextTick, computed, onBeforeUnmount, onActivated, onDeactivated } from 'vue'
  450. import { apis } from '@/request/apis.js'
  451. // ===== 已删除:getUserId - 不再需要,改用token =====
  452. // import { getUserId } from '@/utils/userManager.js'
  453. import { useSpeechRecognition } from '@/composables/useSpeechRecognition'
  454. import { createSSEConnection, closeSSEConnection } from '@/utils/sse'
  455. import { getApiPrefix } from '@/utils/apiConfig'
  456. import { renderMarkdown } from '@/utils/markdown'
  457. import { stopSSEStream, updateAIMessageContent } from '@/utils/api.js'
  458. import { getToken, getTokenType } from '@/utils/auth.js'
  459. import Vditor from 'vditor'
  460. import 'vditor/dist/index.css'
  461. import 'katex/dist/katex.min.css'
  462. // 导入图片资源 - 与PC端保持一致
  463. import aiAvatarIcon from '@/assets/Chat/29.png'
  464. import bridgeIcon from '@/assets/Chat/4.png'
  465. import constructionIcon from '@/assets/Chat/5.png'
  466. import materialIcon from '@/assets/Chat/6.png'
  467. import standardIcon from '@/assets/Chat/7.png'
  468. import deleteIcon from '@/assets/AIWriting/8.png'
  469. import sendIconEmpty from '@/assets/Chat/15.png'
  470. import sendIconFilled from '@/assets/Chat/16.png'
  471. // 对话操作图标
  472. import copyIcon from '@/assets/AIWriting/5.png'
  473. import editIcon from '@/assets/AIWriting/6.png'
  474. import regenerateIcon from '@/assets/AIWriting/7.png'
  475. import voiceIcon from '@/assets/AIWriting/9.png'
  476. import likeIcon from '@/assets/AIWriting/10.png'
  477. import dislikeIcon from '@/assets/AIWriting/11.png'
  478. // 语音输入图标
  479. import voiceInputIcon from '@/assets/Chat/18.png'
  480. // 联网搜索图标
  481. import networkSearchIconOn from '@/assets/Chat/24.png'
  482. import networkSearchIconOff from '@/assets/Chat/25.png'
  483. const router = useRouter()
  484. const route = useRoute()
  485. const goBack = () => {
  486. router.go(-1)
  487. }
  488. // 显示历史记录抽屉的方法
  489. const showHistoryDrawer = () => {
  490. if (!isSending.value && !hasTypingMessage.value) {
  491. showHistory.value = true
  492. }
  493. // AI处理中时不执行任何操作,不记录点击意图
  494. }
  495. const showHistory = ref(false)
  496. // 历史记录相关状态
  497. const historyData = ref([])
  498. const historyTotal = ref(0)
  499. const isLoadingHistory = ref(false)
  500. // 聊天相关状态
  501. const showChat = ref(false)
  502. const chatMessages = ref([])
  503. const messageText = ref('')
  504. const isSending = ref(false)
  505. const ai_conversation_id = ref(0)
  506. // 删除确认弹窗状态
  507. const showDeleteModal = ref(false)
  508. const deleteTargetItem = ref(null) // 要删除的历史记录项
  509. const deleteType = ref('') // 删除类型:'history' 或 'message'
  510. // 网络搜索弹窗
  511. const showWebSearchModal = ref(false)
  512. const currentWebSearchData = ref(null)
  513. // 网页预览弹窗
  514. const showWebPreview = ref(false)
  515. const previewUrl = ref('')
  516. const previewTitle = ref('')
  517. // 文件预览相关
  518. const showFilePreview = ref(false)
  519. const previewFilePath = ref('')
  520. const previewFileName = ref('')
  521. const fileLoading = ref(false)
  522. const fileError = ref('')
  523. // 处理文件预览
  524. const handleFilePreview = (file) => {
  525. console.log('预览文件:', file)
  526. if (!file) return
  527. // 重置状态
  528. fileLoading.value = true
  529. fileError.value = ''
  530. // 设置文件信息
  531. if (typeof file === 'string') {
  532. previewFilePath.value = file
  533. previewFileName.value = file.split('/').pop() || '未知文件'
  534. } else {
  535. previewFilePath.value = file.url || file.filePath || ''
  536. previewFileName.value = file.name || file.fileName || '未知文件'
  537. }
  538. // 显示弹窗
  539. showFilePreview.value = true
  540. // 如果不是PDF(PDF由组件处理加载状态),iframe需要手动处理loading
  541. if (!previewFileName.value.toLowerCase().endsWith('.pdf')) {
  542. // iframe加载会在onload中设置fileLoading = false
  543. } else {
  544. // PDF组件自己处理loading,这里先设为false,让组件接管
  545. fileLoading.value = false
  546. }
  547. }
  548. // 消息内容引用
  549. const messageContentRefs = ref({})
  550. // 语音识别功能
  551. const {
  552. isSupported: speechSupported,
  553. isListening,
  554. transcript,
  555. error: speechError,
  556. startListening,
  557. stopListening,
  558. speakText,
  559. stopSpeaking
  560. } = useSpeechRecognition()
  561. // 语音合成相关状态
  562. const speakingMessageId = ref(null)
  563. const currentAudio = ref(null)
  564. const audioQueue = ref([])
  565. const isPlayingQueue = ref(false)
  566. // Toast状态
  567. const showToast = ref(false)
  568. const toastMessage = ref('')
  569. const toastDuration = ref(2000)
  570. // 功能卡片和热点问题数据
  571. const functionCards = ref([])
  572. const hotQuestions = ref([])
  573. // 联网搜索相关
  574. const isNetworkSearchEnabled = ref(true) // 联网搜索是否启用,默认为true
  575. const onlineSearchResults = ref({}) // 存储每个消息的联网搜索结果
  576. const isGettingOnlineSearch = ref(false) // 是否正在获取联网搜索结果
  577. const onlineSearchLoadingMessages = ref(new Set()) // 记录正在加载联网搜索的消息ID
  578. const expandedOnlineSearchResults = ref({}) // 记录每个消息的联网搜索结果展开状态
  579. const expandedSearchSources = ref({}) // 记录每个消息的搜索来源展开状态
  580. // AI回复相关推荐问题
  581. const aiRelatedQuestions = ref([]) // AI回复后的相关推荐问题
  582. const isGettingRelatedQuestions = ref(false) // 是否正在获取相关推荐问题
  583. const relatedQuestionsMessageId = ref(null) // 关联的消息ID
  584. const isAIReplyProcessComplete = ref(false) // AI回复流程是否完成
  585. // SSE连接管理
  586. let sseConnection = null
  587. // 报告生成相关状态
  588. const categoryExpandStates = ref({}) // 分类展开状态
  589. const currentQuestion = ref('') // 当前问题
  590. const streamingReports = ref(new Map()) // 流式报告缓存
  591. const reportTypewriters = new Map() // 存储每个报告字段的打字机定时器
  592. const typewriterIntervals = new Map() // 存储打字机定时器
  593. // 功能卡片图标计数器
  594. let functionCardIconIndex = 0
  595. // 计算属性 - 是否有正在打字的AI消息
  596. const hasTypingMessage = computed(() => {
  597. const result = chatMessages.value.some(message => message.type === 'ai' && message.isTyping)
  598. console.log('hasTypingMessage计算:', result, '聊天消息:', chatMessages.value.map(m => ({ type: m.type, isTyping: m.isTyping })))
  599. return result
  600. })
  601. // 删除确认消息
  602. const deleteConfirmMessage = computed(() => {
  603. if (deleteType.value === 'history') {
  604. const title = deleteTargetItem.value?.item?.title || ''
  605. return `确定要删除历史记录"${title}"吗?删除后将无法恢复。`
  606. } else if (deleteType.value === 'message') {
  607. return '确定要删除这条消息吗?删除后将无法恢复。'
  608. }
  609. return '确定要删除吗?删除后将无法恢复。'
  610. })
  611. // 删除确认标题
  612. const deleteConfirmTitle = computed(() => {
  613. if (deleteType.value === 'history') {
  614. return '删除历史记录'
  615. } else if (deleteType.value === 'message') {
  616. return '删除消息'
  617. }
  618. return '删除确认'
  619. })
  620. // 格式化文件大小
  621. const formatFileSize = (bytes) => {
  622. if (bytes === 0) return '0 Bytes'
  623. const k = 1024
  624. const sizes = ['Bytes', 'KB', 'MB', 'GB']
  625. const i = Math.floor(Math.log(bytes) / Math.log(k))
  626. return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  627. }
  628. // 处理文件标签格式的回显
  629. const processFileDisplay = (text, file) => {
  630. if (!file) {
  631. // 如果没有文件对象,尝试从文本中提取文件信息
  632. return processFileDisplayFromText(text)
  633. }
  634. // 查找文件标签并替换为显示格式
  635. const fileDisplay = `
  636. 📄 文件信息:
  637. 文件名:${file.name}
  638. 文件大小:${formatFileSize(file.size)}
  639. 文件类型:${file.type}
  640. 📝 文件内容:
  641. ${file.content}
  642. ---
  643. `
  644. // 替换文件标签为显示格式
  645. let processedText = text
  646. .replace(/<word>.*?<\/word>/gs, fileDisplay)
  647. .replace(/<filename>.*?<\/filename>/g, '')
  648. .replace(/<filesize>.*?<\/filesize>/g, '')
  649. return processedText
  650. }
  651. // 从文本中提取文件信息并转换为显示格式
  652. const processFileDisplayFromText = (text) => {
  653. // 提取文件名
  654. const filenameMatch = text.match(/<filename>(.*?)<\/filename>/)
  655. const filename = filenameMatch ? filenameMatch[1] : '未知文件'
  656. // 提取文件大小
  657. const filesizeMatch = text.match(/<filesize>(.*?)<\/filesize>/)
  658. const filesize = filesizeMatch ? parseInt(filesizeMatch[1]) : 0
  659. // 提取文件内容
  660. const wordMatch = text.match(/<word>(.*?)<\/word>/s)
  661. const fileContent = wordMatch ? wordMatch[1].trim() : '无内容'
  662. // 创建文件显示格式
  663. const fileDisplay = `
  664. 📄 文件信息:
  665. 文件名:${filename}
  666. 文件大小:${formatFileSize(filesize)}
  667. 文件类型:${filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '未知'}
  668. 📝 文件内容:
  669. ${fileContent}
  670. ---
  671. `
  672. // 替换文件标签为显示格式
  673. let processedText = text
  674. .replace(/<word>.*?<\/word>/gs, fileDisplay)
  675. .replace(/<filename>.*?<\/filename>/g, '')
  676. .replace(/<filesize>.*?<\/filesize>/g, '')
  677. return processedText
  678. }
  679. // 使用Vditor渲染Markdown内容
  680. const renderWithVditor = (content) => {
  681. return new Promise((resolve) => {
  682. try {
  683. console.log('开始使用Vditor渲染,内容长度:', content.length)
  684. console.log('原始内容:', content)
  685. // 创建一个临时的DOM元素
  686. const tempDiv = document.createElement('div')
  687. tempDiv.style.display = 'none'
  688. document.body.appendChild(tempDiv)
  689. // 使用Vditor.preview方法渲染 - 简化配置
  690. Vditor.preview(tempDiv, content, {
  691. mode: 'light',
  692. markdown: {
  693. toc: false,
  694. mark: false,
  695. footnotes: false,
  696. autoSpace: false,
  697. fixTermTypo: false,
  698. chinesePunct: false,
  699. linkBase: '',
  700. linkPrefix: '',
  701. listStyle: false,
  702. paragraphBeginningSpace: false
  703. },
  704. theme: {
  705. current: 'light',
  706. path: 'https://cdn.jsdelivr.net/npm/vditor@3.10.9/dist/css/content-theme'
  707. },
  708. after: () => {
  709. // 获取Vditor渲染的结果并进行规范引用处理
  710. let html = tempDiv.innerHTML
  711. // 处理规范引用 - 将<file></file>标签内容转换为可点击的规范引用
  712. html = processStandardReferences(html)
  713. console.log('Vditor渲染完成,HTML长度:', html.length)
  714. console.log('HTML预览:', html.substring(0, 200) + '...')
  715. // 清理临时元素
  716. document.body.removeChild(tempDiv)
  717. // 等待DOM更新后绑定点击事件
  718. nextTick(() => {
  719. bindStandardReferenceEvents()
  720. })
  721. resolve(html)
  722. }
  723. })
  724. } catch (error) {
  725. console.error('Vditor渲染错误:', error)
  726. // 渲染失败时使用简单HTML转换
  727. const fallbackHtml = content.replace(/\n/g, '<br>')
  728. resolve(fallbackHtml)
  729. }
  730. })
  731. }
  732. // LaTeX公式转换函数
  733. const convertLatexToDisplay = (text) => {
  734. if (!text) return text
  735. let convertedText = text
  736. // 希腊字母转换
  737. const greekLetters = {
  738. '\\alpha': 'α', '\\beta': 'β', '\\gamma': 'γ', '\\delta': 'δ', '\\epsilon': 'ε',
  739. '\\varepsilon': 'ε', '\\zeta': 'ζ', '\\eta': 'η', '\\theta': 'θ', '\\iota': 'ι',
  740. '\\kappa': 'κ', '\\lambda': 'λ', '\\mu': 'μ', '\\nu': 'ν', '\\xi': 'ξ',
  741. '\\pi': 'π', '\\rho': 'ρ', '\\sigma': 'σ', '\\tau': 'τ', '\\upsilon': 'υ',
  742. '\\phi': 'φ', '\\chi': 'χ', '\\psi': 'ψ', '\\omega': 'ω',
  743. '\\Gamma': 'Γ', '\\Delta': 'Δ', '\\Theta': 'Θ', '\\Lambda': 'Λ', '\\Xi': 'Ξ',
  744. '\\Pi': 'Π', '\\Sigma': 'Σ', '\\Upsilon': 'Υ', '\\Phi': 'Φ', '\\Psi': 'Ψ', '\\Omega': 'Ω'
  745. }
  746. // 转换希腊字母
  747. for (const [latex, symbol] of Object.entries(greekLetters)) {
  748. const regex = new RegExp(latex.replace(/\\/g, '\\\\'), 'g')
  749. convertedText = convertedText.replace(regex, symbol)
  750. }
  751. // 分数转换 \frac{a}{b} → a/b
  752. convertedText = convertedText.replace(/\\frac\{([^}]+)\}\{([^}]+)\}/g, '$1/$2')
  753. // 根号转换 \sqrt{a} → √a
  754. convertedText = convertedText.replace(/\\sqrt\{([^}]+)\}/g, '√$1')
  755. // 积分符号转换
  756. convertedText = convertedText.replace(/\\int/g, '∫')
  757. convertedText = convertedText.replace(/\\sum/g, '∑')
  758. convertedText = convertedText.replace(/\\prod/g, '∏')
  759. convertedText = convertedText.replace(/\\partial/g, '∂')
  760. convertedText = convertedText.replace(/\\nabla/g, '∇')
  761. convertedText = convertedText.replace(/\\infty/g, '∞')
  762. // 其他数学符号
  763. convertedText = convertedText.replace(/\\pm/g, '±')
  764. convertedText = convertedText.replace(/\\times/g, '×')
  765. convertedText = convertedText.replace(/\\div/g, '÷')
  766. convertedText = convertedText.replace(/\\leq/g, '≤')
  767. convertedText = convertedText.replace(/\\geq/g, '≥')
  768. convertedText = convertedText.replace(/\\neq/g, '≠')
  769. convertedText = convertedText.replace(/\\approx/g, '≈')
  770. convertedText = convertedText.replace(/\\equiv/g, '≡')
  771. convertedText = convertedText.replace(/\\propto/g, '∝')
  772. // 集合符号
  773. convertedText = convertedText.replace(/\\in/g, '∈')
  774. convertedText = convertedText.replace(/\\notin/g, '∉')
  775. convertedText = convertedText.replace(/\\subset/g, '⊂')
  776. convertedText = convertedText.replace(/\\supset/g, '⊃')
  777. convertedText = convertedText.replace(/\\cup/g, '∪')
  778. convertedText = convertedText.replace(/\\cap/g, '∩')
  779. convertedText = convertedText.replace(/\\emptyset/g, '∅')
  780. // 逻辑符号
  781. convertedText = convertedText.replace(/\\land/g, '∧')
  782. convertedText = convertedText.replace(/\\lor/g, '∨')
  783. convertedText = convertedText.replace(/\\neg/g, '¬')
  784. convertedText = convertedText.replace(/\\rightarrow/g, '→')
  785. convertedText = convertedText.replace(/\\leftarrow/g, '←')
  786. convertedText = convertedText.replace(/\\leftrightarrow/g, '↔')
  787. convertedText = convertedText.replace(/\\forall/g, '∀')
  788. convertedText = convertedText.replace(/\\exists/g, '∃')
  789. console.log('LaTeX转换:', text, '→', convertedText)
  790. return convertedText
  791. }
  792. // 处理AI回复中的特殊字符和表情符号
  793. const processAIResponse = (text) => {
  794. if (!text) return text
  795. console.log('原始AI回复:', text)
  796. console.log('原始文本长度:', text.length)
  797. console.log('原始文本字符码:', Array.from(text).map(char => char.charCodeAt(0)))
  798. try {
  799. // 方法1:尝试直接解码
  800. if (text.includes('%')) {
  801. const decoded = decodeURIComponent(text)
  802. console.log('URL解码后:', decoded)
  803. text = decoded
  804. }
  805. // 方法2:处理可能的编码问题
  806. if (text.includes('??')) {
  807. // 如果包含问号,尝试修复编码
  808. const cleaned = text.replace(/\?\?/g, '')
  809. console.log('清理问号后:', cleaned)
  810. text = cleaned
  811. }
  812. // 方法3:处理Unicode转义序列
  813. if (text.includes('\\u')) {
  814. const unicodeDecoded = text.replace(/\\u[\dA-F]{4}/gi, (match) => {
  815. return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16))
  816. })
  817. console.log('Unicode解码后:', unicodeDecoded)
  818. text = unicodeDecoded
  819. }
  820. // 方法4:处理HTML实体(包括&lt;、&gt;等)
  821. if (text.includes('&')) {
  822. console.log('检测到&符号,可能包含HTML实体')
  823. const textarea = document.createElement('textarea')
  824. textarea.innerHTML = text
  825. const htmlDecoded = textarea.value
  826. console.log('HTML解码后:', htmlDecoded)
  827. // 检查是否解码成功
  828. if (htmlDecoded !== text) {
  829. console.log('HTML实体解码成功,内容已变化')
  830. text = htmlDecoded
  831. } else {
  832. console.log('HTML实体解码未生效,可能不是HTML实体')
  833. }
  834. }
  835. // 方法5:处理其他可能的编码问题
  836. if (text.includes('\uFFFD')) {
  837. console.log('检测到替换字符,尝试修复')
  838. // 替换字符通常表示编码错误
  839. const fixed = text.replace(/\uFFFD/g, '')
  840. console.log('修复替换字符后:', fixed)
  841. text = fixed
  842. }
  843. // 方法6:LaTeX公式转换(新增)
  844. const latexConverted = convertLatexToDisplay(text)
  845. console.log('LaTeX转换后:', latexConverted)
  846. console.log('最终处理结果:', latexConverted)
  847. return latexConverted
  848. } catch (error) {
  849. console.error('处理AI回复时出错:', error)
  850. return text
  851. }
  852. }
  853. // 处理规范引用 - 将<file></file>标签内容转换为可点击的规范引用
  854. const processStandardReferences = (html) => {
  855. if (!html) return html
  856. console.log('开始处理规范引用,HTML长度:', html.length)
  857. // 处理<file></file>标签为可点击的标准引用
  858. const processedHtml = html.replace(/<file>(.*?)<\/file>/g, (match, content) => {
  859. console.log('发现文件引用:', content)
  860. // 检查是否已经是处理过的规范引用
  861. if (/^<span\s+class="standard-reference"/i.test(content)) {
  862. return match
  863. }
  864. // 检查是否是标准格式:书名号+内容+括号+编号
  865. const standardMatch = content.match(/^([《「『【]?[\s\S]*?[》」』】]?)[\s]*\(([^)]+)\)$/)
  866. if (standardMatch) {
  867. const standardName = standardMatch[1]
  868. const standardNumber = standardMatch[2]
  869. console.log('标准格式规范:', { standardName, standardNumber })
  870. return `<span class="standard-reference" data-standard="${content}" data-name="${standardName}" data-number="${standardNumber}" title="点击查看标准详情" style="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;">${content}</span>`
  871. }
  872. // 普通文件引用格式
  873. console.log('普通文件引用格式:', content)
  874. return `<span class="standard-reference" data-reference="${content}" title="点击查看详情" style="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;">${content}</span>`
  875. })
  876. console.log('规范引用处理完成')
  877. return processedHtml
  878. }
  879. // 将Markdown格式转换为HTML格式
  880. const markdownToHtml = (text) => {
  881. if (!text) return text
  882. console.log('开始转换Markdown:', text)
  883. let html = text
  884. // 检查是否包含Markdown格式
  885. const hasMarkdown = /(?:^|<br>)#{1,6}\s*/.test(html) || /\*\*.*?\*\*/.test(html) || /^\s*[-*]\s+/.test(html)
  886. console.log('Markdown格式检测结果:', hasMarkdown)
  887. // 检查是否已经包含HTML标签(如<strong>、<em>等)
  888. const hasHtmlTags = /<[^>]*>/.test(html)
  889. console.log('HTML标签检测结果:', hasHtmlTags)
  890. // 如果包含Markdown格式,进行转换
  891. if (hasMarkdown) {
  892. console.log('检测到Markdown格式,进行Markdown转换')
  893. // 转换标题
  894. html = html.replace(/^#{6}\s*(.+)$/gm, '<h6>$1</h6>')
  895. html = html.replace(/^#{5}\s*(.+)$/gm, '<h5>$1</h5>')
  896. html = html.replace(/^#{4}\s*(.+)$/gm, '<h4>$1</h4>')
  897. html = html.replace(/^#{3}\s*(.+)$/gm, '<h3>$1</h3>')
  898. html = html.replace(/^#{2}\s*(.+)$/gm, '<h2>$1</h2>')
  899. html = html.replace(/^#{1}\s*(.+)$/gm, '<h1>$1</h1>')
  900. // 转换加粗
  901. html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  902. // 转换斜体
  903. html = html.replace(/\*(.*?)\*/g, '<em>$1</em>')
  904. // 转换列表
  905. html = html.replace(/^\s*[-*]\s+(.+)$/gm, '<li>$1</li>')
  906. html = html.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>')
  907. // 转换代码
  908. html = html.replace(/`(.*?)`/g, '<code>$1</code>')
  909. console.log('Markdown转换完成:', html)
  910. } else if (hasHtmlTags) {
  911. console.log('检测到HTML标签,跳过Markdown转换')
  912. } else {
  913. console.log('未检测到特殊格式,保持原文本')
  914. }
  915. // 处理换行
  916. html = html.replace(/\n/g, '<br>')
  917. console.log('最终HTML:', html)
  918. return html
  919. }
  920. // 格式化时间函数
  921. const formatTime = (timestamp) => {
  922. if (!timestamp) return ''
  923. const date = new Date(timestamp)
  924. const now = new Date()
  925. const diff = now - date
  926. // 如果是今天
  927. if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
  928. return date.toLocaleTimeString('zh-CN', {
  929. hour: '2-digit',
  930. minute: '2-digit'
  931. })
  932. }
  933. // 如果是昨天
  934. if (diff < 48 * 60 * 60 * 1000 && date.getDate() === now.getDate() - 1) {
  935. return '昨天 ' + date.toLocaleTimeString('zh-CN', {
  936. hour: '2-digit',
  937. minute: '2-digit'
  938. })
  939. }
  940. // 其他情况显示日期
  941. return date.toLocaleDateString('zh-CN', {
  942. month: '2-digit',
  943. day: '2-digit'
  944. })
  945. }
  946. // 生成对话标题
  947. const generateConversationTitle = (content) => {
  948. if (!content) return '新对话'
  949. // 取前30个字符作为标题
  950. const title = content.replace(/<[^>]*>/g, '').trim()
  951. return title.length > 30 ? title.substring(0, 30) + '...' : title
  952. }
  953. // 时间格式化(增强解析与本地日判断:今天/昨天/M月D日 HH:MM)
  954. const parseToDate = (input) => {
  955. if (!input) return null
  956. if (typeof input === 'number') {
  957. const ms = input < 1e12 ? input * 1000 : input
  958. return new Date(ms)
  959. }
  960. if (typeof input === 'string') {
  961. // 优先尝试标准解析
  962. let d = new Date(input)
  963. if (!isNaN(d)) return d
  964. // 兼容 "YYYY-MM-DD HH:mm:ss"
  965. const normalized = input.replace(/-/g, '/').replace('T', ' ')
  966. d = new Date(normalized)
  967. if (!isNaN(d)) return d
  968. }
  969. return new Date(input)
  970. }
  971. const formatHistoryTime = (timestamp) => {
  972. const date = parseToDate(timestamp)
  973. if (!date || isNaN(date)) return '未知时间'
  974. const now = new Date()
  975. const isToday = date.toDateString() === now.toDateString()
  976. const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
  977. const isYesterday = date.toDateString() === yesterday.toDateString()
  978. if (isToday) {
  979. return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  980. }
  981. if (isYesterday) {
  982. return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  983. }
  984. const month = date.getMonth() + 1
  985. const day = date.getDate()
  986. const time = date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  987. return `${month}月${day}日 ${time}`
  988. }
  989. // 获取历史记录列表
  990. const getHistoryRecordList = async () => {
  991. try {
  992. console.log('📋 开始获取移动端AI问答历史记录列表...')
  993. isLoadingHistory.value = true
  994. const startTime = performance.now()
  995. const response = await apis.getHistoryRecord({
  996. // ===== 已删除:user_id - 后端从token解析 =====
  997. ai_conversation_id: 0, // 0表示获取对话列表
  998. business_type: 0 // AI问答类型
  999. })
  1000. const endTime = performance.now()
  1001. console.log(`📋 移动端AI问答历史记录API调用耗时: ${(endTime - startTime).toFixed(2)}ms`)
  1002. console.log('📋 移动端历史记录列表响应:', response)
  1003. if (response.statusCode === 200) {
  1004. // 设置历史记录总数
  1005. historyTotal.value = response.total || 0
  1006. // 转换后端数据为前端格式
  1007. historyData.value = response.data.map(conversation => ({
  1008. id: conversation.id,
  1009. title: generateConversationTitle(conversation.content),
  1010. time: formatHistoryTime(conversation.updated_at),
  1011. businessType: conversation.business_type,
  1012. isActive: false,
  1013. // 保存原始数据用于后续查询
  1014. rawData: conversation
  1015. }))
  1016. // 高亮当前对话
  1017. if (ai_conversation_id.value) {
  1018. historyData.value.forEach(item => { item.isActive = item.id === ai_conversation_id.value })
  1019. }
  1020. console.log(`✅ 移动端AI问答历史记录列表已设置: ${historyData.value.length}条记录,总数: ${historyTotal.value}`)
  1021. } else {
  1022. console.error('❌ 获取移动端历史记录列表失败:', response.statusCode)
  1023. }
  1024. } catch (error) {
  1025. console.error('❌ 获取移动端历史记录列表失败:', error)
  1026. } finally {
  1027. isLoadingHistory.value = false
  1028. }
  1029. }
  1030. // 渲染Markdown内容
  1031. const renderMarkdownContent = (content) => {
  1032. try {
  1033. let html = renderMarkdown(content)
  1034. html = processStandardReferences(html)
  1035. nextTick(() => {
  1036. bindStandardReferenceEvents()
  1037. })
  1038. return html
  1039. } catch (error) {
  1040. console.error('Markdown渲染失败:', error)
  1041. return content.replace(/\n/g, '<br>')
  1042. }
  1043. }
  1044. // 解析搜索来源
  1045. const parseSearchSources = (searchSourceStr) => {
  1046. try {
  1047. if (!searchSourceStr || typeof searchSourceStr !== 'string' || !searchSourceStr.trim()) {
  1048. return null
  1049. }
  1050. const sources = JSON.parse(searchSourceStr)
  1051. if (!Array.isArray(sources)) {
  1052. return null
  1053. }
  1054. const validSources = sources.filter(source =>
  1055. source && typeof source === 'object' && source.title && source.content
  1056. )
  1057. return validSources.length > 0 ? validSources : null
  1058. } catch (error) {
  1059. console.error('解析搜索来源失败:', error)
  1060. return null
  1061. }
  1062. }
  1063. // 转换用户反馈状态
  1064. const convertUserFeedback = (feedback) => {
  1065. switch (parseInt(feedback)) {
  1066. case 2: return 'like'
  1067. case 3: return 'dislike'
  1068. default: return null
  1069. }
  1070. }
  1071. // 转换前端反馈状态为后端格式
  1072. const convertFeedbackToBackend = (feedback) => {
  1073. switch (feedback) {
  1074. case 'like': return 2
  1075. case 'dislike': return 3
  1076. default: return 0
  1077. }
  1078. }
  1079. // 处理历史记录点击
  1080. // 获取历史对话消息(与PC端完全一致)
  1081. const getConversationMessages = async (conversationId) => {
  1082. try {
  1083. const response = await apis.getHistoryRecord({
  1084. // ===== 已删除:user_id - 后端从token解析 =====
  1085. ai_conversation_id: conversationId,
  1086. business_type: 0
  1087. })
  1088. if (response.statusCode === 200) {
  1089. if (!response.data || !Array.isArray(response.data)) {
  1090. console.error('响应数据格式错误')
  1091. return false
  1092. }
  1093. const messages = await Promise.all(response.data.map(async (message, index) => {
  1094. const userFeedback = convertUserFeedback(message.user_feedback)
  1095. // 如果是用户消息且包含文件标签,提取文件信息
  1096. let file = null
  1097. let userContent = message.content
  1098. // 获取前一条用户消息作为AI消息的问题上下文
  1099. let userQuestion = null
  1100. if (message.type === 'ai' && index > 0) {
  1101. const prevMessage = response.data[index - 1]
  1102. if (prevMessage && prevMessage.type === 'user') {
  1103. // 提取用户实际问题(去除文件标签)
  1104. if (prevMessage.content.includes('</filesize>')) {
  1105. const userMessageMatch = prevMessage.content.split('</filesize>')[1]
  1106. userQuestion = userMessageMatch ? userMessageMatch.trim() : prevMessage.content
  1107. } else {
  1108. userQuestion = prevMessage.content
  1109. }
  1110. }
  1111. }
  1112. if (message.type === 'user' && message.content.includes('</filesize>')) {
  1113. // 提取文件信息
  1114. const filenameMatch = message.content.match(/<filename>(.*?)<\/filename>/)
  1115. const filesizeMatch = message.content.match(/<filesize>(.*?)<\/filesize>/)
  1116. const wordMatch = message.content.match(/<word>(.*?)<\/word>/s)
  1117. if (filenameMatch && filesizeMatch) {
  1118. const filename = filenameMatch[1]
  1119. const filesize = parseInt(filesizeMatch[1])
  1120. const fileContent = wordMatch ? wordMatch[1].trim() : ''
  1121. // 创建文件对象
  1122. file = {
  1123. name: filename,
  1124. size: filesize,
  1125. type: filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '.docx',
  1126. icon: getFileIcon(filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '.docx'),
  1127. content: fileContent
  1128. }
  1129. // 提取用户实际说的话(</filesize>标签后的内容)
  1130. const userMessageMatch = message.content.split('</filesize>')[1]
  1131. userContent = userMessageMatch ? userMessageMatch.trim() : ''
  1132. }
  1133. }
  1134. // 为AI消息准备displayContent
  1135. let displayContent = userContent || ''
  1136. let reports = []
  1137. let summary = message.summary || '' // 从后端恢复summary字段
  1138. if (message.type === 'ai') {
  1139. try {
  1140. const contentStr = message.content || ''
  1141. // 尝试解析content为JSON
  1142. if (contentStr.trim().startsWith('[') || contentStr.trim().startsWith('{')) {
  1143. try {
  1144. const parsedContent = JSON.parse(contentStr)
  1145. // 检查是否是新格式(包含reports和webSearch数据)
  1146. if (parsedContent.reports && Array.isArray(parsedContent.reports)) {
  1147. reports = parsedContent.reports
  1148. // 恢复网络搜索数据
  1149. if (parsedContent.webSearchRaw) {
  1150. message.webSearchRaw = parsedContent.webSearchRaw
  1151. }
  1152. if (parsedContent.webSearchSummary) {
  1153. message.webSearchSummary = parsedContent.webSearchSummary
  1154. message.hasWebSearchResults = parsedContent.hasWebSearchResults || false
  1155. }
  1156. // ===== 🔧 修复:从content JSON中恢复summary =====
  1157. if (parsedContent.summary) {
  1158. summary = parsedContent.summary
  1159. }
  1160. } else if (Array.isArray(parsedContent)) {
  1161. // 旧格式,直接是reports数组
  1162. reports = parsedContent
  1163. } else {
  1164. throw new Error('Not an array or valid format')
  1165. }
  1166. } catch (jsonError) {
  1167. // JSON解析失败,当作普通Markdown文本处理
  1168. let processedContent = contentStr
  1169. .replace(/\\n/g, '\n')
  1170. .replace(/\\t/g, '\t')
  1171. .replace(/\\r/g, '\r')
  1172. displayContent = renderMarkdownContent(processedContent)
  1173. }
  1174. } else {
  1175. // 不是JSON格式,直接按Markdown处理
  1176. let processedContent = contentStr
  1177. .replace(/\\n/g, '\n')
  1178. .replace(/\\t/g, '\t')
  1179. .replace(/\\r/g, '\r')
  1180. displayContent = renderMarkdownContent(processedContent)
  1181. }
  1182. } catch (error) {
  1183. console.error('历史记录处理失败:', error)
  1184. displayContent = message.content || ''
  1185. }
  1186. }
  1187. // 如果有reports,计算相关统计信息
  1188. let totalFiles = 0
  1189. let completedCount = 0
  1190. let progress = 100
  1191. if (reports.length > 0) {
  1192. // 过滤掉category_title类型,只统计实际报告
  1193. const actualReports = reports.filter(r => r.type !== 'category_title')
  1194. totalFiles = actualReports.length
  1195. completedCount = actualReports.filter(r => r.status === 'completed').length
  1196. progress = totalFiles > 0 ? Math.round((completedCount / totalFiles) * 100) : 100
  1197. }
  1198. return {
  1199. type: message.type, // 'user' 或 'ai'
  1200. content: userContent, // 使用提取的用户消息
  1201. displayContent: displayContent,
  1202. reports: reports, // 添加reports数组
  1203. summary: summary, // 添加summary字段
  1204. totalFiles: totalFiles, // 总文件数
  1205. completedCount: completedCount, // 完成数
  1206. progress: progress, // 进度
  1207. file: file, // 添加文件对象
  1208. isTyping: false,
  1209. id: message.id,
  1210. ai_message_id: message.type === 'ai' ? message.id : undefined, // AI消息的后端ID
  1211. userFeedback: userFeedback,
  1212. userQuestion: userQuestion, // AI消息对应的用户问题
  1213. searchSources: message.type === 'ai' && message.search_source ? parseSearchSources(message.search_source) : null, // 解析搜索来源
  1214. // 保存原始数据
  1215. rawData: message,
  1216. // 网络搜索数据(如果有)
  1217. webSearchRaw: message.webSearchRaw || null,
  1218. webSearchSummary: message.webSearchSummary || null,
  1219. hasWebSearchResults: message.hasWebSearchResults || false,
  1220. webSearchTotal: message.webSearchRaw?.total || 0,
  1221. // 状态管理(历史记录默认完成状态)
  1222. showStats: totalFiles > 0,
  1223. currentStatus: 'completed',
  1224. statusMessage: totalFiles > 0
  1225. ? (message.webSearchRaw?.total > 0
  1226. ? ` <span class="ai-name">蜀道安全管理AI智能助手</span>已为您分析 <span class="file-count">${totalFiles}</span> 个知识库文件,以及 <span class="file-count">${message.webSearchRaw.total}</span> 个相关网络资源`
  1227. : ` <span class="ai-name">蜀道安全管理AI智能助手</span>已为您分析 <span class="file-count">${totalFiles}</span> 个知识库文件`)
  1228. : ''
  1229. }
  1230. }))
  1231. chatMessages.value = messages
  1232. ai_conversation_id.value = conversationId
  1233. const lastAIMessage = messages.filter(msg => msg.type === 'ai').pop()
  1234. // 恢复所有AI消息的联网搜索结果、推荐问题和分类展开状态
  1235. messages.forEach((message, index) => {
  1236. if (message.type === 'ai' && message.rawData) {
  1237. // 恢复联网搜索结果
  1238. if (message.rawData.search_source) {
  1239. try {
  1240. const searchResults = JSON.parse(message.rawData.search_source)
  1241. if (Array.isArray(searchResults) && searchResults.length > 0) {
  1242. onlineSearchResults.value[message.id] = searchResults
  1243. }
  1244. } catch (error) {
  1245. console.error('解析搜索结果失败:', error)
  1246. }
  1247. }
  1248. // 恢复reports的分类展开状态
  1249. if (message.reports && message.reports.length > 0) {
  1250. if (!categoryExpandStates.value[index]) {
  1251. categoryExpandStates.value[index] = {}
  1252. }
  1253. const categories = message.reports
  1254. .filter(r => r.type === 'category_title')
  1255. .map(r => r.category)
  1256. categories.forEach(category => {
  1257. categoryExpandStates.value[index][category] = true
  1258. })
  1259. }
  1260. // 恢复推荐问题(只处理最后一条AI消息)
  1261. if (message === lastAIMessage) {
  1262. let questions = []
  1263. // 尝试从guess_you_want字段恢复(文本格式,换行分隔)
  1264. if (message.rawData.guess_you_want) {
  1265. try {
  1266. questions = message.rawData.guess_you_want.trim()
  1267. .split('\n')
  1268. .map(q => q.trim())
  1269. .filter(q => q.length > 0)
  1270. .filter((q, index, arr) => arr.indexOf(q) === index)
  1271. .slice(0, 3)
  1272. } catch (error) {
  1273. console.error('解析guess_you_want失败:', error)
  1274. }
  1275. }
  1276. // 如果guess_you_want没有数据,尝试从relate_question恢复(JSON格式)
  1277. if (questions.length === 0 && message.rawData.relate_question) {
  1278. try {
  1279. const relatedQuestions = JSON.parse(message.rawData.relate_question)
  1280. if (Array.isArray(relatedQuestions) && relatedQuestions.length > 0) {
  1281. questions = relatedQuestions.slice(0, 3)
  1282. }
  1283. } catch (error) {
  1284. console.error('解析relate_question失败:', error)
  1285. }
  1286. }
  1287. // 设置推荐问题
  1288. if (questions.length > 0) {
  1289. aiRelatedQuestions.value = questions
  1290. // 使用ai_message_id以确保显示条件匹配
  1291. relatedQuestionsMessageId.value = message.ai_message_id || message.id
  1292. console.log('✅ 从历史记录恢复推荐问题:', questions)
  1293. console.log('✅ relatedQuestionsMessageId:', relatedQuestionsMessageId.value)
  1294. }
  1295. }
  1296. }
  1297. })
  1298. return true
  1299. }
  1300. } catch (error) {
  1301. console.error('加载历史记录失败:', error)
  1302. showToastMessage('加载历史记录失败,请稍后重试', 2000)
  1303. return false
  1304. }
  1305. }
  1306. // 清除所有打字机定时器
  1307. const clearAllTypeIntervals = () => {
  1308. typewriterIntervals.forEach((interval, messageId) => {
  1309. clearInterval(interval)
  1310. })
  1311. typewriterIntervals.clear()
  1312. reportTypewriters.forEach((interval, key) => {
  1313. clearInterval(interval)
  1314. })
  1315. reportTypewriters.clear()
  1316. }
  1317. const handleHistoryItem = async (historyItem) => {
  1318. if (isSending.value) return
  1319. if (speakingMessageId.value) {
  1320. stopAllAudio()
  1321. speakingMessageId.value = null
  1322. }
  1323. clearAllTypeIntervals()
  1324. // 设置激活状态
  1325. historyData.value.forEach(item => {
  1326. item.isActive = item.id === historyItem.id
  1327. })
  1328. // 关闭历史记录弹窗(移动端特有)
  1329. showHistory.value = false
  1330. // 清空当前消息
  1331. chatMessages.value = []
  1332. aiRelatedQuestions.value = []
  1333. relatedQuestionsMessageId.value = null
  1334. // 加载历史对话
  1335. const success = await getConversationMessages(historyItem.id)
  1336. if (success) {
  1337. showChat.value = true
  1338. await nextTick()
  1339. scrollToBottom()
  1340. } else {
  1341. showToastMessage('加载历史记录失败', 2000)
  1342. }
  1343. }
  1344. // 新建对话
  1345. const startNewChat = () => {
  1346. console.log('开始新建对话')
  1347. // 停止任何正在进行的朗读
  1348. if (speakingMessageId.value) {
  1349. stopAllAudio()
  1350. speakingMessageId.value = null
  1351. }
  1352. // 关闭历史记录弹窗
  1353. showHistory.value = false
  1354. // 重置聊天状态
  1355. chatMessages.value = []
  1356. ai_conversation_id.value = 0
  1357. messageText.value = ''
  1358. // 清除联网搜索结果
  1359. onlineSearchResults.value = {}
  1360. expandedOnlineSearchResults.value = {}
  1361. // 清除推荐问题
  1362. aiRelatedQuestions.value = []
  1363. relatedQuestionsMessageId.value = null
  1364. // 清除所有历史记录的选中状态
  1365. historyData.value.forEach((item) => {
  1366. item.isActive = false
  1367. })
  1368. // 切换到初始状态(显示功能卡片)
  1369. showChat.value = false
  1370. console.log('新建对话完成')
  1371. }
  1372. // 删除历史记录
  1373. const deleteHistoryItem = async (historyItem, index) => {
  1374. try {
  1375. console.log('开始删除移动端历史记录:', historyItem)
  1376. const response = await apis.deleteHistoryRecord({
  1377. // ===== 已删除:user_id - 后端从token解析 =====
  1378. ai_conversation_id: historyItem.id
  1379. })
  1380. if (response.statusCode === 200) {
  1381. // 从本地数据中移除
  1382. historyData.value.splice(index, 1)
  1383. historyTotal.value = Math.max(0, historyTotal.value - 1)
  1384. // 如果删除的是当前激活的历史记录,执行新建任务
  1385. if (historyItem.isActive) {
  1386. console.log('删除激活的历史记录,执行新建任务')
  1387. startNewChat()
  1388. }
  1389. console.log('✅ 移动端历史记录删除成功')
  1390. // 轻提示
  1391. showToastMessage('删除成功')
  1392. } else {
  1393. console.error('❌ 删除移动端历史记录失败:', response)
  1394. }
  1395. } catch (error) {
  1396. console.error('❌ 删除移动端历史记录失败:', error)
  1397. }
  1398. }
  1399. // 自动发送消息功能
  1400. const autoSendMessage = async (message) => {
  1401. if (!message || !message.trim()) return
  1402. console.log('移动端自动发送消息:', message)
  1403. // 显示聊天界面
  1404. showChat.value = true
  1405. // 如果是新对话,清除所有历史记录的选中状态
  1406. if (chatMessages.value.length === 0) {
  1407. historyData.value.forEach((item) => {
  1408. item.isActive = false
  1409. })
  1410. }
  1411. // 设置消息文本
  1412. messageText.value = message
  1413. // 使用nextTick确保DOM更新后再发送消息
  1414. // await nextTick()
  1415. // 发送消息
  1416. await sendMessage()
  1417. }
  1418. // ========== 语音合成相关函数 ==========
  1419. // 获取TTS服务地址(自动判断是否使用代理)
  1420. const getTTSUrl = () => {
  1421. // 在开发环境中使用代理,生产环境中使用直接地址
  1422. const isDevelopment = import.meta.env.DEV
  1423. if (isDevelopment) {
  1424. return '/api/tts/voice' // 使用Vite代理
  1425. } else {
  1426. return window.location.origin + '/tts/voice' // 生产环境直接地址
  1427. }
  1428. }
  1429. // 测试TTS服务连接
  1430. const testTTSConnection = async () => {
  1431. // 自动获取TTS服务地址
  1432. const ttsUrl = getTTSUrl()
  1433. try {
  1434. console.log('开始测试TTS服务连接...')
  1435. console.log('使用代理地址:', ttsUrl)
  1436. // 使用简单的测试文本
  1437. const testText = '测试'
  1438. const controller = new AbortController()
  1439. const timeoutId = setTimeout(() => controller.abort(), 8000) // 8秒超时
  1440. // 准备请求头,添加认证 Token
  1441. const headers = { 'Content-Type': 'application/json' }
  1442. const token = getToken()
  1443. const tokenType = getTokenType()
  1444. if (token && tokenType) {
  1445. // 确保 Bearer 首字母大写
  1446. const bearerType = tokenType.charAt(0).toUpperCase() + tokenType.slice(1).toLowerCase()
  1447. headers['Authorization'] = `${bearerType} ${token}`
  1448. }
  1449. const response = await fetch(ttsUrl, {
  1450. method: 'POST',
  1451. headers,
  1452. body: JSON.stringify({
  1453. text: testText
  1454. }),
  1455. signal: controller.signal
  1456. })
  1457. clearTimeout(timeoutId)
  1458. console.log('TTS连接测试结果:', {
  1459. status: response.status,
  1460. statusText: response.statusText,
  1461. headers: Object.fromEntries(response.headers.entries()),
  1462. url: ttsUrl
  1463. })
  1464. if (response.ok) {
  1465. const blob = await response.blob()
  1466. console.log('TTS服务连接正常,测试音频大小:', blob.size, 'bytes')
  1467. return { success: true, message: 'TTS服务连接正常' }
  1468. } else {
  1469. return { success: false, message: `TTS服务响应错误: ${response.status} ${response.statusText}` }
  1470. }
  1471. } catch (error) {
  1472. console.error('TTS连接测试失败:', error)
  1473. let message = 'TTS服务连接失败'
  1474. if (error.name === 'AbortError') {
  1475. message = 'TTS服务连接超时'
  1476. } else if (error.message.includes('Failed to fetch')) {
  1477. message = '无法连接到TTS服务,请检查网络或服务状态'
  1478. } else {
  1479. message = `TTS服务连接失败: ${error.message}`
  1480. }
  1481. return { success: false, message }
  1482. }
  1483. }
  1484. // 调用TTS接口进行语音合成(带重试机制)
  1485. const callTTSAPI = async (text, retryCount = 0) => {
  1486. // 自动获取TTS服务地址
  1487. const ttsUrl = getTTSUrl()
  1488. const maxRetries = 2 // 最大重试次数
  1489. try {
  1490. console.log(`开始调用TTS接口,文本长度: ${text.length}, 重试次数: ${retryCount}`)
  1491. console.log('TTS接口地址:', ttsUrl)
  1492. // 添加超时控制 - 减少超时时间,提高响应速度
  1493. const controller = new AbortController()
  1494. const timeoutId = setTimeout(() => controller.abort(), 15000) // 15秒超时
  1495. // 准备请求头,添加认证 Token
  1496. const headers = { 'Content-Type': 'application/json' }
  1497. const token = getToken()
  1498. const tokenType = getTokenType()
  1499. if (token && tokenType) {
  1500. // 确保 Bearer 首字母大写
  1501. const bearerType = tokenType.charAt(0).toUpperCase() + tokenType.slice(1).toLowerCase()
  1502. headers['Authorization'] = `${bearerType} ${token}`
  1503. }
  1504. const response = await fetch(ttsUrl, {
  1505. method: 'POST',
  1506. headers,
  1507. body: JSON.stringify({
  1508. text: text
  1509. }),
  1510. signal: controller.signal
  1511. })
  1512. clearTimeout(timeoutId)
  1513. console.log('TTS接口响应状态:', response.status, response.statusText)
  1514. if (!response.ok) {
  1515. const errorText = await response.text().catch(() => '无法读取错误信息')
  1516. throw new Error(`TTS接口调用失败: ${response.status} ${response.statusText} - ${errorText}`)
  1517. }
  1518. // 检查响应类型
  1519. const contentType = response.headers.get('content-type')
  1520. console.log('响应Content-Type:', contentType)
  1521. if (!contentType || !contentType.includes('audio')) {
  1522. console.warn('响应可能不是音频格式:', contentType)
  1523. }
  1524. // 获取音频数据
  1525. const audioBlob = await response.blob()
  1526. console.log('TTS接口调用成功,音频大小:', audioBlob.size, 'bytes')
  1527. console.log('音频类型:', audioBlob.type)
  1528. if (audioBlob.size === 0) {
  1529. throw new Error('TTS接口返回的音频数据为空')
  1530. }
  1531. // 创建音频URL
  1532. const audioUrl = URL.createObjectURL(audioBlob)
  1533. return audioUrl
  1534. } catch (error) {
  1535. console.error(`TTS接口调用失败 (重试${retryCount}/${maxRetries}):`, error)
  1536. // 如果是网络错误或超时,且还有重试次数,则重试
  1537. if (retryCount < maxRetries && (
  1538. error.name === 'AbortError' ||
  1539. error.message.includes('Failed to fetch') ||
  1540. error.message.includes('NetworkError')
  1541. )) {
  1542. console.log(`准备重试TTS请求,等待${(retryCount + 1) * 1000}ms...`)
  1543. await new Promise(resolve => setTimeout(resolve, (retryCount + 1) * 1000))
  1544. return callTTSAPI(text, retryCount + 1)
  1545. }
  1546. // 提供更详细的错误信息
  1547. let errorMessage = '语音合成失败'
  1548. if (error.name === 'AbortError') {
  1549. errorMessage = '语音合成请求超时,请检查网络连接或稍后重试'
  1550. } else if (error.message.includes('Failed to fetch')) {
  1551. errorMessage = '无法连接到语音合成服务,请检查网络连接或联系管理员'
  1552. } else if (error.message.includes('CORS')) {
  1553. errorMessage = '跨域请求被阻止,请联系管理员配置服务器'
  1554. } else if (error.message.includes('NetworkError')) {
  1555. errorMessage = '网络错误,请检查网络连接'
  1556. } else if (error.message.includes('TTS接口调用失败')) {
  1557. errorMessage = error.message
  1558. } else {
  1559. errorMessage = `语音合成失败: ${error.message}`
  1560. }
  1561. // 抛出包含详细信息的错误
  1562. const detailedError = new Error(errorMessage)
  1563. detailedError.originalError = error
  1564. throw detailedError
  1565. }
  1566. }
  1567. // 清理文本内容,移除HTML标签和非文本字符
  1568. const cleanTextForTTS = (text) => {
  1569. if (!text) return ''
  1570. // 移除HTML标签
  1571. let cleanText = text.replace(/<[^>]*>/g, '')
  1572. // 移除多余的空白字符
  1573. cleanText = cleanText.replace(/\s+/g, ' ').trim()
  1574. // 移除特殊字符,保留中文、英文、数字和基本标点
  1575. cleanText = cleanText.replace(/[^\u4e00-\u9fa5a-zA-Z0-9\s,。!?、;:""''()【】《》]/g, '')
  1576. return cleanText
  1577. }
  1578. // 将长文本分块处理(第一块较小,后续块较大)
  1579. const splitTextIntoChunks = (text) => {
  1580. if (text.length <= 60) {
  1581. return [text]
  1582. }
  1583. const chunks = []
  1584. let currentChunk = ''
  1585. let isFirstChunk = true
  1586. // 按句子分割
  1587. const sentences = text.split(/[。!?]/)
  1588. for (const sentence of sentences) {
  1589. if (sentence.trim().length === 0) continue
  1590. const sentenceWithPunctuation = sentence + (sentence.match(/[。!?]$/) ? '' : '。')
  1591. // 第一块限制为60字,后续块限制为200字
  1592. const maxLength = isFirstChunk ? 60 : 200
  1593. if (currentChunk.length + sentenceWithPunctuation.length <= maxLength) {
  1594. currentChunk += sentenceWithPunctuation
  1595. } else {
  1596. if (currentChunk.length > 0) {
  1597. chunks.push(currentChunk.trim())
  1598. currentChunk = sentenceWithPunctuation
  1599. isFirstChunk = false // 第一块已完成
  1600. } else {
  1601. // 如果单个句子就超过最大长度,强制分割
  1602. const maxLen = isFirstChunk ? 60 : 200
  1603. chunks.push(sentenceWithPunctuation.substring(0, maxLen))
  1604. currentChunk = sentenceWithPunctuation.substring(maxLen)
  1605. isFirstChunk = false
  1606. }
  1607. }
  1608. }
  1609. if (currentChunk.trim().length > 0) {
  1610. chunks.push(currentChunk.trim())
  1611. }
  1612. return chunks
  1613. }
  1614. // 播放音频
  1615. const playAudio = (audioUrl) => {
  1616. return new Promise((resolve, reject) => {
  1617. const audio = new Audio(audioUrl)
  1618. currentAudio.value = audio
  1619. audio.onended = () => {
  1620. console.log('音频播放完成')
  1621. currentAudio.value = null
  1622. resolve()
  1623. }
  1624. audio.onerror = (error) => {
  1625. console.error('音频播放失败:', error)
  1626. currentAudio.value = null
  1627. reject(error)
  1628. }
  1629. audio.onloadstart = () => {
  1630. console.log('开始加载音频')
  1631. }
  1632. audio.oncanplay = () => {
  1633. console.log('音频可以播放')
  1634. }
  1635. // 开始播放
  1636. audio.play().catch(error => {
  1637. console.error('音频播放启动失败:', error)
  1638. currentAudio.value = null
  1639. reject(error)
  1640. })
  1641. })
  1642. }
  1643. // 停止所有音频播放
  1644. const stopAllAudio = () => {
  1645. try {
  1646. // 停止当前播放的音频
  1647. if (currentAudio.value) {
  1648. currentAudio.value.pause()
  1649. currentAudio.value.currentTime = 0
  1650. currentAudio.value = null
  1651. }
  1652. // 清空音频队列
  1653. audioQueue.value = []
  1654. isPlayingQueue.value = false
  1655. // 停止浏览器原生语音合成(备用)
  1656. window.speechSynthesis && window.speechSynthesis.cancel()
  1657. console.log('所有音频播放已停止')
  1658. } catch (e) {
  1659. console.warn('停止音频播放时出错:', e)
  1660. }
  1661. }
  1662. // 优化后的并行预加载音频并播放队列
  1663. const playAudioQueue = async (chunks, messageId) => {
  1664. console.log(`开始优化播放 ${chunks.length} 个音频片段`)
  1665. // 检查是否还在朗读状态
  1666. if (speakingMessageId.value !== messageId) {
  1667. console.log('朗读被中断,停止处理')
  1668. return
  1669. }
  1670. try {
  1671. // 第一步:立即预加载第一块并开始播放
  1672. console.log('立即预加载并播放第一块')
  1673. const firstChunk = chunks[0]
  1674. const firstAudioUrl = await callTTSAPI(firstChunk)
  1675. // 检查是否还在朗读状态
  1676. if (speakingMessageId.value !== messageId) {
  1677. URL.revokeObjectURL(firstAudioUrl)
  1678. return
  1679. }
  1680. // 开始播放第一块的同时,并行预加载后续所有块
  1681. console.log('开始播放第一块,同时预加载后续块')
  1682. const remainingChunks = chunks.slice(1)
  1683. // 并行预加载剩余所有音频片段
  1684. const remainingPromises = remainingChunks.map(async (chunk, index) => {
  1685. try {
  1686. console.log(`预加载第 ${index + 2}/${chunks.length} 块音频`)
  1687. const audioUrl = await callTTSAPI(chunk)
  1688. return { index: index + 1, audioUrl, chunk }
  1689. } catch (error) {
  1690. console.error(`第 ${index + 2} 块音频预加载失败:`, error)
  1691. return { index: index + 1, audioUrl: null, chunk, error }
  1692. }
  1693. })
  1694. // 播放第一块音频
  1695. console.log('播放第 1/1 块音频')
  1696. await playAudio(firstAudioUrl)
  1697. URL.revokeObjectURL(firstAudioUrl)
  1698. // 检查是否还在朗读状态
  1699. if (speakingMessageId.value !== messageId) {
  1700. console.log('朗读被中断,清理预加载的音频')
  1701. // 清理已预加载的音频URL
  1702. const remainingResults = await Promise.allSettled(remainingPromises)
  1703. remainingResults.forEach(result => {
  1704. if (result.status === 'fulfilled' && result.value.audioUrl) {
  1705. URL.revokeObjectURL(result.value.audioUrl)
  1706. }
  1707. })
  1708. return
  1709. }
  1710. // 等待所有预加载完成
  1711. console.log('等待所有音频预加载完成...')
  1712. const remainingResults = await Promise.allSettled(remainingPromises)
  1713. // 再次检查是否还在朗读状态
  1714. if (speakingMessageId.value !== messageId) {
  1715. console.log('朗读被中断,停止播放队列')
  1716. // 清理已预加载的音频URL
  1717. remainingResults.forEach(result => {
  1718. if (result.status === 'fulfilled' && result.value.audioUrl) {
  1719. URL.revokeObjectURL(result.value.audioUrl)
  1720. }
  1721. })
  1722. return
  1723. }
  1724. // 按顺序播放剩余的音频片段
  1725. console.log('开始播放剩余音频片段')
  1726. isPlayingQueue.value = true
  1727. for (const result of remainingResults) {
  1728. // 再次检查是否还在朗读状态
  1729. if (speakingMessageId.value !== messageId) {
  1730. console.log('朗读被中断,停止播放队列')
  1731. break
  1732. }
  1733. if (result.status === 'fulfilled' && result.value.audioUrl) {
  1734. try {
  1735. console.log(`播放第 ${result.value.index + 1}/${chunks.length} 块音频`)
  1736. await playAudio(result.value.audioUrl)
  1737. URL.revokeObjectURL(result.value.audioUrl)
  1738. } catch (error) {
  1739. console.error(`第 ${result.value.index + 1} 块音频播放失败:`, error)
  1740. }
  1741. } else {
  1742. console.warn(`第 ${result.value.index + 1} 块音频预加载失败,跳过播放`)
  1743. }
  1744. }
  1745. isPlayingQueue.value = false
  1746. console.log('音频队列播放完成')
  1747. } catch (error) {
  1748. console.error('音频队列播放失败:', error)
  1749. isPlayingQueue.value = false
  1750. }
  1751. }
  1752. // 语音朗读相关方法
  1753. const handleVoiceRead = async (message) => {
  1754. if (speakingMessageId.value === message.id) {
  1755. // 如果正在朗读这条消息,则停止
  1756. stopAllAudio()
  1757. speakingMessageId.value = null
  1758. } else {
  1759. // 如果朗读其他消息,先停止当前朗读
  1760. if (speakingMessageId.value) {
  1761. stopAllAudio()
  1762. speakingMessageId.value = null
  1763. }
  1764. // 开始朗读新消息
  1765. const textToRead = message.displayContent || message.content
  1766. if (textToRead && textToRead.trim()) {
  1767. try {
  1768. // 清理文本内容
  1769. const cleanText = cleanTextForTTS(textToRead)
  1770. console.log('清理后的文本:', cleanText)
  1771. if (cleanText.length === 0) {
  1772. showToastMessage('文本内容为空,无法进行语音合成')
  1773. return
  1774. }
  1775. // 设置朗读状态
  1776. speakingMessageId.value = message.id
  1777. // 如果文本较短(小于60字),直接合成
  1778. if (cleanText.length <= 60) {
  1779. console.log('文本较短,直接合成语音')
  1780. const audioUrl = await callTTSAPI(cleanText)
  1781. await playAudio(audioUrl)
  1782. // 清理URL对象
  1783. URL.revokeObjectURL(audioUrl)
  1784. } else {
  1785. // 如果文本较长,使用并行预加载分块处理
  1786. console.log('文本较长,使用并行预加载分块处理')
  1787. const chunks = splitTextIntoChunks(cleanText)
  1788. console.log(`文本分为 ${chunks.length} 块`)
  1789. // 使用新的并行预加载播放方法
  1790. await playAudioQueue(chunks, message.id)
  1791. }
  1792. } catch (error) {
  1793. console.error('语音合成失败:', error)
  1794. showToastMessage('语音合成失败,请稍后重试')
  1795. } finally {
  1796. // 清除朗读状态
  1797. speakingMessageId.value = null
  1798. isPlayingQueue.value = false
  1799. }
  1800. }
  1801. }
  1802. }
  1803. // 检查消息是否正在朗读
  1804. const isSpeaking = (messageId) => {
  1805. return speakingMessageId.value === messageId
  1806. }
  1807. // ========== 联网搜索相关函数 ==========
  1808. // 切换联网搜索状态
  1809. // 处理网络搜索胶囊点击
  1810. const handleWebSearchToggle = (webSearchData) => {
  1811. console.log('点击网络搜索胶囊,数据:', webSearchData)
  1812. currentWebSearchData.value = webSearchData
  1813. showWebSearchModal.value = true
  1814. }
  1815. // 处理搜索结果点击
  1816. const handleSearchResultClick = (result) => {
  1817. previewTitle.value = result.title
  1818. previewUrl.value = result.url || result.link
  1819. showWebPreview.value = true
  1820. }
  1821. // 格式化URL显示
  1822. const formatUrl = (url) => {
  1823. if (!url) return ''
  1824. try {
  1825. const urlObj = new URL(url)
  1826. return urlObj.hostname + urlObj.pathname
  1827. } catch (e) {
  1828. return url
  1829. }
  1830. }
  1831. // 在新标签页打开链接
  1832. const openInNewTab = () => {
  1833. if (previewUrl.value) {
  1834. window.open(previewUrl.value, '_blank')
  1835. showWebPreview.value = false
  1836. }
  1837. }
  1838. // 处理文件预览
  1839. const handleFilePreview = (data) => {
  1840. console.log('移动端打开文件预览:', data)
  1841. // 重置状态
  1842. fileError.value = ''
  1843. fileLoading.value = false
  1844. // 处理不同类型的输入参数
  1845. if (typeof data === 'string') {
  1846. previewFilePath.value = data
  1847. previewFileName.value = ''
  1848. } else if (data && data.filePath) {
  1849. previewFilePath.value = data.filePath
  1850. previewFileName.value = data.fileName || ''
  1851. } else {
  1852. fileError.value = '文件路径为空'
  1853. previewFilePath.value = ''
  1854. previewFileName.value = ''
  1855. }
  1856. // 显示加载状态
  1857. if (previewFilePath.value) {
  1858. fileLoading.value = true
  1859. // 设置超时,如果5秒后还在加载,显示错误
  1860. setTimeout(() => {
  1861. if (fileLoading.value) {
  1862. fileLoading.value = false
  1863. fileError.value = '😔 抱歉,未找到文件链接,正在快马加鞭修复中!'
  1864. }
  1865. }, 5000)
  1866. }
  1867. showFilePreview.value = true
  1868. }
  1869. const toggleNetworkSearch = () => {
  1870. isNetworkSearchEnabled.value = !isNetworkSearchEnabled.value
  1871. console.log('联网搜索状态:', isNetworkSearchEnabled.value ? '已启用' : '已关闭')
  1872. // 使用Toast提示
  1873. if (isNetworkSearchEnabled.value) {
  1874. showToastMessage('联网搜索已启用')
  1875. } else {
  1876. showToastMessage('联网搜索已关闭')
  1877. }
  1878. }
  1879. // 切换联网搜索结果展开状态
  1880. const toggleOnlineSearchResults = (messageId) => {
  1881. expandedOnlineSearchResults.value[messageId] = !expandedOnlineSearchResults.value[messageId]
  1882. console.log('联网搜索结果展开状态:', expandedOnlineSearchResults.value[messageId] ? '已展开' : '已收起')
  1883. }
  1884. // 打开联网搜索结果链接
  1885. const openSearchResult = (url) => {
  1886. if (!url || url.trim() === '') {
  1887. console.warn('联网搜索结果URL为空或无效:', url)
  1888. showToastMessage('链接无效')
  1889. return
  1890. }
  1891. try {
  1892. // 确保URL包含协议
  1893. let targetUrl = url.trim()
  1894. if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
  1895. targetUrl = 'https://' + targetUrl
  1896. }
  1897. console.log('打开联网搜索结果链接:', targetUrl)
  1898. window.open(targetUrl, '_blank', 'noopener,noreferrer')
  1899. } catch (error) {
  1900. console.error('打开联网搜索结果链接失败:', error)
  1901. showToastMessage('打开链接失败')
  1902. }
  1903. }
  1904. // 联网搜索功能
  1905. const performOnlineSearch = async (userInput, messageId) => {
  1906. if (!userInput || userInput.trim() === '') {
  1907. console.log('用户输入为空,跳过搜索')
  1908. return
  1909. }
  1910. if (!messageId) {
  1911. console.error('消息ID为空,无法进行联网搜索')
  1912. return
  1913. }
  1914. try {
  1915. console.log('开始联网搜索,用户输入:', userInput, '消息ID:', messageId)
  1916. isGettingOnlineSearch.value = true
  1917. onlineSearchLoadingMessages.value.add(messageId)
  1918. const response = await apis.onlineSearch({
  1919. keywords: userInput.trim()
  1920. })
  1921. console.log('联网搜索结果:', response)
  1922. if (response.statusCode === 200 && response.results) {
  1923. try {
  1924. // 解析搜索结果
  1925. const results = response.results
  1926. // 处理数据格式,确保有必要的字段
  1927. const processedResults = results.map((result, index) => ({
  1928. title: result.title || `搜索结果 ${index + 1}`,
  1929. snippet: result.content || result.snippet || '暂无内容',
  1930. url: result.url || null
  1931. }))
  1932. onlineSearchResults.value[messageId] = processedResults
  1933. // 设置联网搜索结果默认收起
  1934. expandedOnlineSearchResults.value[messageId] = false
  1935. console.log('联网搜索结果已保存,消息ID:', messageId, '结果数量:', processedResults.length)
  1936. console.log('处理后的搜索结果:', processedResults)
  1937. console.log('联网搜索结果已设置为默认收起')
  1938. // 保存联网搜索结果到数据库
  1939. try {
  1940. const saveData = {
  1941. id: messageId,
  1942. ai_conversation_id: ai_conversation_id.value,
  1943. search_source: JSON.stringify(processedResults)
  1944. }
  1945. const saveResponse = await apis.saveOnlineSearchResult(saveData)
  1946. console.log('联网搜索结果保存到数据库成功:', saveResponse)
  1947. } catch (saveError) {
  1948. console.error('保存联网搜索结果到数据库失败:', saveError)
  1949. }
  1950. // 联网搜索完成后,强制滚动到底部显示搜索结果
  1951. setTimeout(() => {
  1952. scrollToBottom()
  1953. }, 100)
  1954. // 联网搜索完成后,获取推荐问题
  1955. setTimeout(async () => {
  1956. console.log('联网搜索完成,开始获取推荐问题,消息ID:', messageId)
  1957. // 需要获取AI回复内容来生成推荐问题
  1958. const aiMessage = chatMessages.value.find(msg => msg.id === messageId)
  1959. if (aiMessage && aiMessage.content) {
  1960. await getAIRelatedQuestions(userInput, aiMessage.content, messageId)
  1961. }
  1962. }, 500) // 延迟500ms让联网搜索结果先显示
  1963. } catch (parseError) {
  1964. console.error('解析联网搜索结果失败:', parseError)
  1965. onlineSearchResults.value[messageId] = []
  1966. }
  1967. } else {
  1968. console.error('联网搜索失败:', response.statusCode)
  1969. onlineSearchResults.value[messageId] = []
  1970. }
  1971. } catch (error) {
  1972. console.error('联网搜索请求失败:', error)
  1973. onlineSearchResults.value[messageId] = []
  1974. } finally {
  1975. isGettingOnlineSearch.value = false
  1976. onlineSearchLoadingMessages.value.delete(messageId)
  1977. }
  1978. }
  1979. // ========== 报告生成相关函数 ==========
  1980. // 分类展开/收起处理
  1981. const handleCategoryToggle = (messageIndex, data) => {
  1982. if (!categoryExpandStates.value[messageIndex]) {
  1983. categoryExpandStates.value[messageIndex] = {}
  1984. }
  1985. categoryExpandStates.value[messageIndex][data.category] = data.expanded
  1986. }
  1987. const isCategoryExpanded = (messageIndex, category) => {
  1988. if (!category) return true
  1989. if (!categoryExpandStates.value[messageIndex]) {
  1990. categoryExpandStates.value[messageIndex] = {}
  1991. return true
  1992. }
  1993. return categoryExpandStates.value[messageIndex][category] !== false
  1994. }
  1995. // 检查reports数组是否只包含分类标题,没有实际报告
  1996. const hasOnlyCategoryTitles = (reports) => {
  1997. if (!reports || reports.length === 0) return false
  1998. return reports.every(r => r.type === 'category_title')
  1999. }
  2000. // 将消息状态映射到头像状态
  2001. const getAvatarStatus = (currentStatus, progress) => {
  2002. if (progress === 100) return 'completed'
  2003. switch (currentStatus) {
  2004. case 'querying_kb':
  2005. case 'web_searching':
  2006. return 'searching'
  2007. case 'analyzing_files':
  2008. case 'analyzing_web':
  2009. return 'analyzing'
  2010. case 'deep_thinking':
  2011. return 'thinking'
  2012. case 'outputting':
  2013. return 'analyzing'
  2014. case 'completed':
  2015. return 'completed'
  2016. case 'error':
  2017. return 'error'
  2018. default:
  2019. return 'idle'
  2020. }
  2021. }
  2022. // 更新AI消息状态和进度
  2023. const updateMessageStatus = (aiMessage, status, customMessage = null) => {
  2024. const statusConfig = {
  2025. querying_kb: {
  2026. message: '🔍 <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析知识库……',
  2027. progress: 10
  2028. },
  2029. web_searching: {
  2030. message: '🌐 <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您联网分析……',
  2031. progress: 15
  2032. },
  2033. data_retrieved: {
  2034. message: null,
  2035. progress: 30
  2036. },
  2037. analyzing_files: {
  2038. message: '😊 <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析文件内容……',
  2039. progress: 45
  2040. },
  2041. analyzing_web: {
  2042. message: '🤔 <span class="ai-name">蜀道安全管理AI智能助手</span>正在分析联网数据……',
  2043. progress: 70
  2044. },
  2045. deep_thinking: {
  2046. message: '❓ <span class="ai-name">蜀道安全管理AI智能助手</span>正在深度思考中,请您稍等片刻……',
  2047. progress: 75
  2048. },
  2049. outputting: {
  2050. message: '😄 <span class="ai-name">蜀道安全管理AI智能助手</span>正在整理分析中!',
  2051. progress: 90
  2052. },
  2053. completed: {
  2054. message: null,
  2055. progress: 100
  2056. }
  2057. }
  2058. const config = statusConfig[status]
  2059. if (config) {
  2060. aiMessage.currentStatus = status
  2061. if (status === 'data_retrieved') {
  2062. const kbCount = aiMessage.totalFiles || 0
  2063. const webCount = aiMessage.webSearchTotal || 0
  2064. if (webCount > 0) {
  2065. aiMessage.statusMessage = `<span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析 <span class="file-count">${kbCount}</span> 个知识库文件,以及 <span class="file-count">${webCount}</span> 个相关网络资源`
  2066. } else {
  2067. aiMessage.statusMessage = `<span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析 <span class="file-count">${kbCount}</span> 个知识库文件`
  2068. }
  2069. } else if (status === 'completed') {
  2070. const kbCount = aiMessage.totalFiles || 0
  2071. const webCount = aiMessage.webSearchTotal || 0
  2072. if (webCount > 0) {
  2073. aiMessage.statusMessage = `✅ <span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${kbCount}</span> 个知识库文件,以及 <span class="file-count">${webCount}</span> 个相关网络资源`
  2074. } else {
  2075. aiMessage.statusMessage = `✅ <span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${kbCount}</span> 个知识库文件`
  2076. }
  2077. } else {
  2078. aiMessage.statusMessage = customMessage || config.message
  2079. }
  2080. aiMessage.progress = config.progress
  2081. }
  2082. }
  2083. // 打字机效果函数
  2084. const startReportFieldTypewriter = (report, field, fullContent, speed = 50) => {
  2085. return new Promise((resolve) => {
  2086. const key = `${report.file_index}_${field}`
  2087. // 如果已经有打字机在运行,先清除
  2088. if (reportTypewriters.has(key)) {
  2089. clearInterval(reportTypewriters.get(key))
  2090. reportTypewriters.delete(key)
  2091. }
  2092. // 初始化打字机状态
  2093. if (!report._typewriterStates) {
  2094. report._typewriterStates = {}
  2095. }
  2096. let currentIndex = 0
  2097. report._typewriterStates[field] = { currentIndex: 0, isTyping: true }
  2098. const interval = setInterval(() => {
  2099. if (currentIndex < fullContent.length) {
  2100. const charsToAdd = Math.max(1, Math.floor(speed / 10))
  2101. currentIndex = Math.min(currentIndex + charsToAdd, fullContent.length)
  2102. // 更新显示内容
  2103. report.report[field] = fullContent.substring(0, currentIndex)
  2104. report._typewriterStates[field].currentIndex = currentIndex
  2105. } else {
  2106. // 打字完成
  2107. clearInterval(interval)
  2108. reportTypewriters.delete(key)
  2109. report._typewriterStates[field].isTyping = false
  2110. report.report[field] = fullContent
  2111. resolve()
  2112. }
  2113. }, 1000 / 60) // 60fps
  2114. reportTypewriters.set(key, interval)
  2115. })
  2116. }
  2117. // SSE消息处理函数
  2118. const handleSSEMessage = (data, aiMessageIndex) => {
  2119. const aiMessage = chatMessages.value[aiMessageIndex]
  2120. if (!aiMessage) return
  2121. // 🔍 调试:打印SSE返回的完整数据对象
  2122. console.log('🔍 SSE事件完整数据:', {
  2123. type: data.type,
  2124. conversation_id: data.conversation_id,
  2125. message_id: data.message_id,
  2126. ai_conversation_id: data.ai_conversation_id,
  2127. ai_message_id: data.ai_message_id,
  2128. allKeys: Object.keys(data)
  2129. })
  2130. // 捕获conversation_id(后端返回的字段名,可能是conversation_id或ai_conversation_id)
  2131. const conversationId = data.conversation_id || data.ai_conversation_id
  2132. if (conversationId) {
  2133. if (ai_conversation_id.value === 0) {
  2134. ai_conversation_id.value = conversationId
  2135. console.log('✅ SSE收到conversation_id并赋值:', conversationId)
  2136. }
  2137. }
  2138. // 捕获message_id(后端返回的字段名,可能是message_id或ai_message_id)
  2139. const messageId = data.message_id || data.ai_message_id
  2140. if (messageId) {
  2141. if (!aiMessage.ai_message_id) {
  2142. aiMessage.ai_message_id = messageId
  2143. console.log('✅ SSE收到message_id并赋值:', messageId)
  2144. console.log(' - aiMessage.id (前端临时ID):', aiMessage.id)
  2145. console.log(' - aiMessage.ai_message_id (后端ID):', aiMessage.ai_message_id)
  2146. // 同时更新rawData对象,确保操作按钮能够使用正确的ID
  2147. if (!aiMessage.rawData) {
  2148. aiMessage.rawData = {}
  2149. }
  2150. aiMessage.rawData.id = messageId
  2151. console.log(' - aiMessage.rawData.id:', aiMessage.rawData.id)
  2152. }
  2153. }
  2154. switch (data.type) {
  2155. case 'intent':
  2156. // 检查是否为专业问题
  2157. if (data.is_professional_question === false) {
  2158. // 非专业问题:立即隐藏状态显示组件
  2159. aiMessage.showStats = false
  2160. // 非专业问题,只输出summary字段内容并终止流程
  2161. const summaryContent = data.summary || '抱歉,我暂时无法回答您的问题。'
  2162. // 只设置summary,不设置content和displayContent,避免重复显示
  2163. aiMessage.summary = summaryContent
  2164. aiMessage.isTyping = false // 停止加载动画
  2165. // 保存到数据库
  2166. if (aiMessage.ai_message_id) {
  2167. updateAIMessageContent(aiMessage.ai_message_id, summaryContent, summaryContent)
  2168. .catch(err => console.error('回写AI消息失败:', err))
  2169. }
  2170. // 关闭SSE连接
  2171. if (sseConnection) {
  2172. closeSSEConnection(sseConnection)
  2173. sseConnection = null
  2174. }
  2175. // 重置发送状态
  2176. isSending.value = false
  2177. streamingReports.value.clear()
  2178. // 重置AI回复流程状态
  2179. isAIReplyProcessComplete.value = true
  2180. // ===== 🎯 非专业问题也要更新历史记录和获取推荐问题 =====
  2181. // 更新历史记录
  2182. if (ai_conversation_id.value && ai_conversation_id.value !== 0) {
  2183. // 先清除所有高亮
  2184. historyData.value.forEach((item) => {
  2185. item.isActive = false
  2186. })
  2187. // 获取第一条用户消息作为标题
  2188. const firstUserMessage = chatMessages.value.find(msg => msg.type === 'user')
  2189. const title = firstUserMessage ? firstUserMessage.content.substring(0, 20) + '...' : '新对话'
  2190. // 检查是否已存在
  2191. const existingIndex = historyData.value.findIndex(item => item.id === ai_conversation_id.value)
  2192. if (existingIndex === -1) {
  2193. // 不存在,在最前面插入新项
  2194. const newItem = {
  2195. id: ai_conversation_id.value,
  2196. title: title,
  2197. time: formatTime(new Date().toISOString()),
  2198. businessType: 0,
  2199. isActive: true,
  2200. rawData: {
  2201. id: ai_conversation_id.value,
  2202. content: firstUserMessage?.content || '',
  2203. updated_at: new Date().toISOString()
  2204. }
  2205. }
  2206. historyData.value.unshift(newItem)
  2207. console.log('✅ 非专业问题:已在列表最前面插入新历史记录')
  2208. } else {
  2209. // 已存在,设为高亮并移到最前面
  2210. const existingItem = historyData.value.splice(existingIndex, 1)[0]
  2211. existingItem.isActive = true
  2212. existingItem.time = formatTime(new Date().toISOString())
  2213. historyData.value.unshift(existingItem)
  2214. console.log('✅ 非专业问题:已将历史记录移到最前面')
  2215. }
  2216. // 更新历史记录总数
  2217. historyTotal.value = historyData.value.length
  2218. }
  2219. // 获取推荐问题
  2220. const lastUserMessage = chatMessages.value.filter(msg => msg.type === 'user').pop()
  2221. if (lastUserMessage && aiMessage.ai_message_id && summaryContent) {
  2222. getAIRelatedQuestions(lastUserMessage.content, summaryContent, aiMessage.ai_message_id)
  2223. }
  2224. return // 终止处理
  2225. }
  2226. // 专业问题:意图识别完成,更新为查询知识库状态
  2227. updateMessageStatus(aiMessage, 'querying_kb')
  2228. // 如果启用联网搜索,稍后会更新为web_searching状态
  2229. // (当收到web_search_raw事件时)
  2230. // 保存问题总结并使用打字机效果
  2231. if (data.summary) {
  2232. const fullSummary = data.summary
  2233. aiMessage._fullSummary = fullSummary
  2234. aiMessage.summary = ''
  2235. // 使用打字机效果显示问题总结
  2236. startReportFieldTypewriter(
  2237. { file_index: 'summary', report: aiMessage, _typewriterStates: {} },
  2238. 'summary',
  2239. fullSummary,
  2240. 50
  2241. ).catch(err => {
  2242. console.error('问题总结打字机效果失败:', err)
  2243. aiMessage.summary = fullSummary
  2244. })
  2245. }
  2246. break
  2247. case 'documents':
  2248. aiMessage.totalFiles = data.total
  2249. aiMessage.completedCount = 0
  2250. // 收到文档数据后的状态处理
  2251. if (isNetworkSearchEnabled.value) {
  2252. // 如果启用了联网搜索,更新状态为联网搜索中
  2253. updateMessageStatus(aiMessage, 'web_searching')
  2254. // 等待web_search_raw事件后再更新为data_retrieved
  2255. } else {
  2256. // 如果没有联网搜索,直接显示检索结果
  2257. updateMessageStatus(aiMessage, 'data_retrieved')
  2258. }
  2259. break
  2260. case 'category_title':
  2261. // 第一个分类标题时,说明开始分析文件
  2262. if (aiMessage.reports.length === 0) {
  2263. // 只有在当前状态进度 >= data_retrieved的进度时,才更新为analyzing_files
  2264. // 这样确保data_retrieved状态能被看到
  2265. if (aiMessage.progress >= 30) {
  2266. updateMessageStatus(aiMessage, 'analyzing_files')
  2267. }
  2268. }
  2269. const categoryTitle = {
  2270. type: 'category_title',
  2271. category: data.category,
  2272. number: data.number,
  2273. count: data.count,
  2274. source_file: `【${data.number}、${data.category}】(共${data.count}个文件)`,
  2275. file_index: -1,
  2276. status: 'category'
  2277. }
  2278. aiMessage.reports.push(categoryTitle)
  2279. // 初始化该分类为展开状态
  2280. if (!categoryExpandStates.value[aiMessageIndex]) {
  2281. categoryExpandStates.value[aiMessageIndex] = {}
  2282. }
  2283. categoryExpandStates.value[aiMessageIndex][data.category] = true
  2284. // 保存当前分类名称,用于后续报告匹配
  2285. aiMessage.currentCategory = data.category
  2286. break
  2287. case 'report_start':
  2288. // 调试日志:查看完整的数据结构
  2289. console.log('🔍 [DEBUG] report_start 数据:', {
  2290. file_index: data.file_index,
  2291. source_file: data.source_file,
  2292. file_path: data.file_path,
  2293. metadata: data.metadata,
  2294. 完整data: data
  2295. })
  2296. const placeholderReport = {
  2297. file_index: data.file_index,
  2298. total_files: aiMessage.totalFiles,
  2299. source_file: data.source_file,
  2300. file_path: data.file_path,
  2301. similarity: data.similarity,
  2302. metadata: {
  2303. ...data.metadata,
  2304. _displayCategory: aiMessage.currentCategory // 存储当前显示的分类名
  2305. },
  2306. report: {
  2307. display_name: '',
  2308. summary: '',
  2309. analysis: '',
  2310. clauses: ''
  2311. },
  2312. status: 'streaming'
  2313. }
  2314. aiMessage.reports.push(placeholderReport)
  2315. streamingReports.value.set(data.file_index, aiMessage.reports.length - 1)
  2316. break
  2317. case 'report_chunk':
  2318. // 不再处理report_chunk,等待完整的report消息后用打字机效果显示
  2319. // 这样可以避免与打字机效果冲突
  2320. break
  2321. case 'report':
  2322. // 第一个报告开始时,更新到深度思考状态
  2323. if (aiMessage.reports.filter(r => r.status === 'completed').length === 0) {
  2324. updateMessageStatus(aiMessage, 'deep_thinking')
  2325. }
  2326. const reportData = data.data || data
  2327. // 调试日志:查看完整的report数据
  2328. console.log('🔍 [DEBUG] report 数据:', {
  2329. file_index: reportData.file_index,
  2330. source_file: reportData.source_file,
  2331. file_path: reportData.file_path,
  2332. metadata: reportData.metadata,
  2333. 完整reportData: reportData
  2334. })
  2335. const idx = streamingReports.value.get(reportData.file_index)
  2336. let targetReport
  2337. if (idx !== undefined) {
  2338. const displayCategory = aiMessage.reports[idx].metadata?._displayCategory
  2339. const fullSummary = reportData.report?.summary || ''
  2340. const fullAnalysis = reportData.report?.analysis || ''
  2341. const fullClauses = reportData.report?.clauses || ''
  2342. const fullDisplayName = reportData.report?.display_name || ''
  2343. // 创建带空内容的报告对象,保留所有原始字段
  2344. aiMessage.reports[idx] = {
  2345. ...reportData, // 保留所有原始字段,包括可能的链接字段
  2346. report: {
  2347. display_name: fullDisplayName, // 直接显示
  2348. summary: '',
  2349. analysis: '',
  2350. clauses: ''
  2351. },
  2352. status: 'completed',
  2353. metadata: {
  2354. ...reportData.metadata, // 保留所有metadata字段
  2355. _displayCategory: displayCategory || aiMessage.currentCategory
  2356. },
  2357. _fullContent: {
  2358. display_name: fullDisplayName,
  2359. summary: fullSummary,
  2360. analysis: fullAnalysis,
  2361. clauses: fullClauses
  2362. }
  2363. }
  2364. targetReport = aiMessage.reports[idx]
  2365. streamingReports.value.delete(reportData.file_index)
  2366. } else {
  2367. const fullSummary = reportData.report?.summary || ''
  2368. const fullAnalysis = reportData.report?.analysis || ''
  2369. const fullClauses = reportData.report?.clauses || ''
  2370. const fullDisplayName = reportData.report?.display_name || ''
  2371. const newReport = {
  2372. ...reportData, // 保留所有原始字段,包括可能的链接字段
  2373. report: {
  2374. display_name: fullDisplayName, // 直接显示
  2375. summary: '',
  2376. analysis: '',
  2377. clauses: ''
  2378. },
  2379. status: 'completed',
  2380. metadata: {
  2381. ...reportData.metadata, // 保留所有metadata字段
  2382. _displayCategory: aiMessage.currentCategory
  2383. },
  2384. _fullContent: {
  2385. display_name: fullDisplayName,
  2386. summary: fullSummary,
  2387. analysis: fullAnalysis,
  2388. clauses: fullClauses
  2389. }
  2390. }
  2391. aiMessage.reports.push(newReport)
  2392. targetReport = newReport
  2393. }
  2394. // 使用顺序打字机效果:概述 -> 解析 -> 相关条款
  2395. if (targetReport._fullContent && !targetReport._typewriterCompleted) {
  2396. // 标记打字机已启动,防止重复触发
  2397. targetReport._typewriterStarted = true
  2398. // 先打概述(速度200 = 每次20个字符,极快)
  2399. startReportFieldTypewriter(targetReport, 'summary', targetReport._fullContent.summary || '', 200)
  2400. .then(() => {
  2401. // 概述完成后打解析
  2402. return startReportFieldTypewriter(targetReport, 'analysis', targetReport._fullContent.analysis || '', 200)
  2403. })
  2404. .then(() => {
  2405. // 解析完成后打相关条款
  2406. if (targetReport._fullContent.clauses) {
  2407. return startReportFieldTypewriter(targetReport, 'clauses', targetReport._fullContent.clauses || '', 200)
  2408. }
  2409. })
  2410. .then(() => {
  2411. // 全部完成,标记为已完成
  2412. targetReport._typewriterCompleted = true
  2413. })
  2414. .catch(err => {
  2415. console.error('报告打字机效果失败:', err)
  2416. // 失败时直接显示完整内容
  2417. targetReport.report.summary = targetReport._fullContent.summary || ''
  2418. targetReport.report.analysis = targetReport._fullContent.analysis || ''
  2419. targetReport.report.clauses = targetReport._fullContent.clauses || ''
  2420. targetReport._typewriterCompleted = true
  2421. })
  2422. console.log('📝 [DEBUG] 报告打字机已启动:', {
  2423. file_index: targetReport.file_index,
  2424. summary_length: targetReport._fullContent.summary?.length || 0,
  2425. analysis_length: targetReport._fullContent.analysis?.length || 0,
  2426. clauses_length: targetReport._fullContent.clauses?.length || 0
  2427. })
  2428. }
  2429. // 更新进度
  2430. aiMessage.completedCount = aiMessage.reports.filter(r => r.status === 'completed' && r.type !== 'category_title').length
  2431. const reportProgress = aiMessage.totalFiles > 0 ? (aiMessage.completedCount / aiMessage.totalFiles) : 0
  2432. // 根据报告完成度更新状态
  2433. if (reportProgress >= 1) {
  2434. // 所有报告完成,进入输出阶段
  2435. updateMessageStatus(aiMessage, 'outputting')
  2436. } else if (reportProgress >= 0.5) {
  2437. // 过半,深度思考
  2438. updateMessageStatus(aiMessage, 'deep_thinking')
  2439. } else {
  2440. // 继续分析文件
  2441. const currentProgress = 30 + Math.round(reportProgress * 30) // 30%~60%
  2442. aiMessage.progress = currentProgress
  2443. }
  2444. break
  2445. case 'web_search_raw':
  2446. // 处理网络搜索原始数据
  2447. if (data.results && data.results.length > 0) {
  2448. aiMessage.webSearchRaw = {
  2449. results: data.results || [],
  2450. keywords: data.keywords || [],
  2451. total: data.total || 0
  2452. }
  2453. aiMessage.webSearchTotal = data.total || 0
  2454. // 更新状态显示:已检索到数据(联网搜索完成)
  2455. const statusMsg = `<span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${aiMessage.totalFiles || 0}</span> 个知识库文件,以及 <span class="file-count">${aiMessage.webSearchTotal}</span> 个相关网络资源`
  2456. updateMessageStatus(aiMessage, 'data_retrieved', statusMsg)
  2457. console.log(`[网络搜索] 收到原始数据: ${data.total} 条结果`)
  2458. } else {
  2459. // 如果没有搜索结果,也要更新状态,但只显示知识库文件数
  2460. const statusMsg = `<span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${aiMessage.totalFiles || 0}</span> 个知识库文件`
  2461. updateMessageStatus(aiMessage, 'data_retrieved', statusMsg)
  2462. console.log('[网络搜索] 无搜索结果,仅使用知识库')
  2463. }
  2464. break
  2465. case 'web_search_summary':
  2466. // 处理网络搜索AI总结 - 使用更快的打字机效果
  2467. if (data.has_results && data.summary) {
  2468. // 检查是否已经有内容,避免重复触发
  2469. if (aiMessage._webSearchSummaryCompleted) {
  2470. console.log('[网络搜索] 总结已完成,跳过重复打字机')
  2471. break
  2472. }
  2473. // 保存完整内容
  2474. aiMessage._fullWebSearchSummary = data.summary
  2475. aiMessage.webSearchSummary = '' // 先置空,通过打字机填充
  2476. aiMessage.hasWebSearchResults = true
  2477. // 使用更快的打字机效果(速度200 = 每次20个字符)
  2478. const summaryReport = {
  2479. file_index: 'web_search_summary',
  2480. report: aiMessage,
  2481. _typewriterStates: {}
  2482. }
  2483. startReportFieldTypewriter(summaryReport, 'webSearchSummary', data.summary, 200)
  2484. .then(() => {
  2485. // 标记为已完成,防止重复触发
  2486. aiMessage._webSearchSummaryCompleted = true
  2487. })
  2488. .catch(err => {
  2489. console.error('网络搜索总结打字机效果失败:', err)
  2490. aiMessage.webSearchSummary = data.summary
  2491. aiMessage._webSearchSummaryCompleted = true
  2492. })
  2493. console.log('[网络搜索] 收到AI总结,长度:', data.summary.length)
  2494. // 网络搜索总结已接收,准备保存并更新为完成状态
  2495. updateMessageStatus(aiMessage, 'outputting')
  2496. // 保存完整数据到后端 - 使用完整的summary而不是打字机过程中的部分内容
  2497. if (aiMessage.ai_message_id) {
  2498. const contentData = {
  2499. reports: aiMessage.reports || [],
  2500. webSearchRaw: aiMessage.webSearchRaw || null,
  2501. webSearchSummary: aiMessage._fullWebSearchSummary || data.summary, // 使用完整的webSearchSummary
  2502. hasWebSearchResults: true,
  2503. // ===== 🔧 修复:将summary也包含在content JSON中 =====
  2504. summary: aiMessage.summary || aiMessage._fullSummary || ''
  2505. }
  2506. const collectedContent = JSON.stringify(contentData)
  2507. // 同时保存summary字段(作为单独字段)
  2508. const summaryToSave = aiMessage.summary || aiMessage._fullSummary || ''
  2509. updateAIMessageContent(aiMessage.ai_message_id, collectedContent, summaryToSave)
  2510. .then((response) => {
  2511. console.log('[网络搜索] AI消息保存成功,更新为完成状态')
  2512. // 保存成功后,更新状态为completed
  2513. updateMessageStatus(aiMessage, 'completed')
  2514. aiMessage.isTyping = false
  2515. isSending.value = false
  2516. streamingReports.value.clear()
  2517. // 重置AI回复流程状态
  2518. isAIReplyProcessComplete.value = true
  2519. })
  2520. .catch(err => {
  2521. console.error('[网络搜索] AI消息保存失败:', err)
  2522. // 即使保存失败,也更新为完成状态
  2523. updateMessageStatus(aiMessage, 'completed')
  2524. aiMessage.isTyping = false
  2525. isSending.value = false
  2526. })
  2527. } else {
  2528. // 没有ai_message_id时,直接更新为完成状态
  2529. updateMessageStatus(aiMessage, 'completed')
  2530. aiMessage.isTyping = false
  2531. isSending.value = false
  2532. }
  2533. }
  2534. break
  2535. case 'error':
  2536. showToastMessage(data.message || '发生错误', 2000)
  2537. isSending.value = false
  2538. break
  2539. case 'completed':
  2540. console.log('[SSE] 收到completed事件')
  2541. isSending.value = false
  2542. streamingReports.value.clear()
  2543. aiMessage.isTyping = false
  2544. // 只有在还未完成时才更新状态
  2545. if (aiMessage.progress < 100) {
  2546. updateMessageStatus(aiMessage, 'completed')
  2547. }
  2548. showToastMessage('报告生成完成', 2000)
  2549. break
  2550. case 'interrupted':
  2551. isSending.value = false
  2552. streamingReports.value.clear()
  2553. aiMessage.isTyping = false
  2554. showToastMessage(data.message || '报告生成已中断', 2000)
  2555. break
  2556. }
  2557. }
  2558. // SSE错误处理
  2559. const handleSSEError = (error) => {
  2560. console.error('❌ SSE连接异常断开:', error)
  2561. // 清理SSE连接
  2562. if (sseConnection) {
  2563. closeSSEConnection(sseConnection)
  2564. sseConnection = null
  2565. }
  2566. isSending.value = false
  2567. streamingReports.value.clear()
  2568. // 将所有正在打字的AI消息标记为完成
  2569. chatMessages.value.forEach(message => {
  2570. if (message.type === 'ai' && message.isTyping) {
  2571. message.isTyping = false
  2572. }
  2573. })
  2574. // 重置AI回复流程状态
  2575. isAIReplyProcessComplete.value = true
  2576. // 这是非预期的连接断开(网络错误、后端崩溃等)
  2577. showToastMessage('连接已断开', 2000)
  2578. }
  2579. // SSE完成处理
  2580. const handleSSEComplete = () => {
  2581. isSending.value = false
  2582. chatMessages.value.forEach(message => {
  2583. if (message.type === 'ai' && message.isTyping) {
  2584. // 确保进度设置为100%
  2585. if (message.showStats && message.reports && message.reports.length > 0) {
  2586. message.progress = 100
  2587. console.log('✅ SSE完成,设置进度为100%')
  2588. }
  2589. // 只有在进度达到100%或没有报告时才停止typing状态
  2590. if (message.progress >= 100 || !message.showStats) {
  2591. message.isTyping = false
  2592. }
  2593. if (message.ai_message_id) {
  2594. // 构建完整的内容数据,包含报告、网络搜索结果和summary
  2595. const contentData = {
  2596. reports: message.reports || [],
  2597. webSearchRaw: message.webSearchRaw || null,
  2598. // 使用完整的webSearchSummary,而不是打字机过程中的部分内容
  2599. webSearchSummary: message._fullWebSearchSummary || message.webSearchSummary || null,
  2600. hasWebSearchResults: message.hasWebSearchResults || false,
  2601. // ===== 🔧 修复:将summary也包含在content JSON中 =====
  2602. summary: message.summary || message._fullSummary || ''
  2603. }
  2604. const collectedContent = message.reports && message.reports.length > 0
  2605. ? JSON.stringify(contentData)
  2606. : message.content
  2607. if (collectedContent) {
  2608. // 同时保存summary字段(作为单独字段)
  2609. const summaryToSave = message.summary || message._fullSummary || ''
  2610. updateAIMessageContent(message.ai_message_id, collectedContent, summaryToSave)
  2611. .catch(err => console.error('回写AI消息失败:', err))
  2612. }
  2613. }
  2614. }
  2615. })
  2616. isAIReplyProcessComplete.value = true
  2617. // ===== 🎯 更新历史记录列表并高亮 =====
  2618. console.log('📝 AI回复完成,准备更新历史记录')
  2619. console.log(' - ai_conversation_id:', ai_conversation_id.value)
  2620. if (ai_conversation_id.value && ai_conversation_id.value !== 0) {
  2621. console.log('✅ 开始更新历史记录列表')
  2622. // 先清除所有高亮
  2623. historyData.value.forEach((item) => {
  2624. item.isActive = false
  2625. })
  2626. // 获取第一条用户消息作为标题
  2627. const firstUserMessage = chatMessages.value.find(msg => msg.type === 'user')
  2628. const title = firstUserMessage ? firstUserMessage.content.substring(0, 20) + '...' : '新对话'
  2629. console.log('📝 生成的标题:', title)
  2630. // 检查是否已存在
  2631. const existingIndex = historyData.value.findIndex(item => item.id === ai_conversation_id.value)
  2632. console.log('🔍 检查是否已存在,索引:', existingIndex)
  2633. if (existingIndex === -1) {
  2634. // 不存在,在最前面插入新项
  2635. const newItem = {
  2636. id: ai_conversation_id.value,
  2637. title: title,
  2638. time: formatTime(new Date().toISOString()),
  2639. businessType: 0,
  2640. isActive: true,
  2641. rawData: {
  2642. id: ai_conversation_id.value,
  2643. content: firstUserMessage?.content || '',
  2644. updated_at: new Date().toISOString()
  2645. }
  2646. }
  2647. console.log('📦 准备插入的新项:', newItem)
  2648. historyData.value.unshift(newItem)
  2649. console.log('✅ 已在列表最前面插入新历史记录并设为高亮')
  2650. console.log('📊 更新后的历史记录数量:', historyData.value.length)
  2651. } else {
  2652. // 已存在,设为高亮并移到最前面
  2653. console.log('🔄 历史记录已存在,将其移到最前面')
  2654. const existingItem = historyData.value.splice(existingIndex, 1)[0]
  2655. existingItem.isActive = true
  2656. existingItem.time = formatTime(new Date().toISOString())
  2657. historyData.value.unshift(existingItem)
  2658. console.log('✅ 已将现有历史记录移到最前面并设为高亮')
  2659. }
  2660. // 更新历史记录总数
  2661. historyTotal.value = historyData.value.length
  2662. console.log('📊 最终历史记录总数:', historyTotal.value)
  2663. } else {
  2664. console.warn('⚠️ ai_conversation_id 为 0 或未设置,跳过历史记录更新')
  2665. }
  2666. // ===== 🎯 获取AI相关推荐问题 =====
  2667. console.log('🎯 准备获取AI相关推荐问题')
  2668. // 找到最后一条用户消息和最后一条AI消息
  2669. const lastUserMessage = chatMessages.value.filter(msg => msg.type === 'user').pop()
  2670. const lastAIMessage = chatMessages.value.filter(msg => msg.type === 'ai').pop()
  2671. if (lastUserMessage && lastAIMessage && lastAIMessage.ai_message_id) {
  2672. console.log('📝 找到最后一条用户消息和AI消息')
  2673. console.log(' - 用户消息:', lastUserMessage.content)
  2674. console.log(' - AI消息ID:', lastAIMessage.ai_message_id)
  2675. // 构建AI回复内容用于生成推荐问题
  2676. let aiReplyContent = ''
  2677. // 优先使用summary字段
  2678. if (lastAIMessage.summary) {
  2679. aiReplyContent = lastAIMessage.summary
  2680. }
  2681. // 其次使用content字段
  2682. else if (lastAIMessage.content) {
  2683. aiReplyContent = lastAIMessage.content
  2684. }
  2685. // 如果有reports,使用reports的summary
  2686. else if (lastAIMessage.reports && lastAIMessage.reports.length > 0) {
  2687. const summaries = lastAIMessage.reports
  2688. .filter(r => r.report && r.report.summary)
  2689. .map(r => r.report.summary)
  2690. .slice(0, 3) // 只取前3个
  2691. aiReplyContent = summaries.join('\n\n')
  2692. }
  2693. if (aiReplyContent && aiReplyContent.trim()) {
  2694. console.log('📝 AI回复内容长度:', aiReplyContent.length)
  2695. // 获取AI相关推荐问题
  2696. getAIRelatedQuestions(
  2697. lastUserMessage.content,
  2698. aiReplyContent,
  2699. lastAIMessage.ai_message_id
  2700. )
  2701. } else {
  2702. console.warn('⚠️ AI回复内容为空,跳过推荐问题获取')
  2703. }
  2704. } else {
  2705. console.warn('⚠️ 未找到有效的用户消息或AI消息,跳过推荐问题获取')
  2706. }
  2707. }
  2708. // SSE中断处理
  2709. const handleSSEInterrupted = (data) => {
  2710. if (sseConnection) {
  2711. closeSSEConnection(sseConnection)
  2712. sseConnection = null
  2713. }
  2714. isSending.value = false
  2715. streamingReports.value.clear()
  2716. chatMessages.value.forEach(message => {
  2717. if (message.type === 'ai' && message.isTyping) {
  2718. message.isTyping = false
  2719. // 中断时设置为完成状态
  2720. updateMessageStatus(message, 'completed')
  2721. // 保留已接收的网络搜索数据
  2722. // 即使中断,也要确保已接收的webSearchRaw和webSearchSummary能够显示
  2723. if (message.webSearchRaw || message.webSearchSummary) {
  2724. console.log('✅ 保留已接收的网络搜索数据')
  2725. }
  2726. if (message.ai_message_id) {
  2727. // 构建完整的内容数据,包含报告、网络搜索结果和summary
  2728. const contentData = {
  2729. reports: message.reports || [],
  2730. webSearchRaw: message.webSearchRaw || null,
  2731. // 使用完整的webSearchSummary,而不是打字机过程中的部分内容
  2732. webSearchSummary: message._fullWebSearchSummary || message.webSearchSummary || null,
  2733. hasWebSearchResults: message.hasWebSearchResults || false,
  2734. // ===== 🔧 修复:将summary也包含在content JSON中 =====
  2735. summary: message.summary || message._fullSummary || ''
  2736. }
  2737. const collectedContent = message.reports && message.reports.length > 0
  2738. ? JSON.stringify(contentData)
  2739. : message.content
  2740. if (collectedContent) {
  2741. // 同时保存summary字段(作为单独字段)
  2742. const summaryToSave = message.summary || message._fullSummary || ''
  2743. updateAIMessageContent(message.ai_message_id, collectedContent, summaryToSave)
  2744. .catch(err => console.error('回写AI消息失败:', err))
  2745. }
  2746. }
  2747. }
  2748. })
  2749. isAIReplyProcessComplete.value = true
  2750. showToastMessage(data.message || '报告生成已中断', 2000)
  2751. }
  2752. // 停止报告生成
  2753. const handleStopGeneration = async () => {
  2754. if (!sseConnection || ai_conversation_id.value === undefined || ai_conversation_id.value === null) {
  2755. return
  2756. }
  2757. if (sseConnection) {
  2758. closeSSEConnection(sseConnection)
  2759. sseConnection = null
  2760. }
  2761. isSending.value = false
  2762. streamingReports.value.clear()
  2763. chatMessages.value.forEach(message => {
  2764. if (message.type === 'ai' && message.isTyping) {
  2765. message.isTyping = false
  2766. // 停止时设置为完成状态
  2767. updateMessageStatus(message, 'completed')
  2768. // 保留已接收的网络搜索数据
  2769. // 即使停止,也要确保已接收的webSearchRaw和webSearchSummary能够显示
  2770. if (message.webSearchRaw || message.webSearchSummary) {
  2771. console.log('✅ 停止时保留已接收的网络搜索数据')
  2772. }
  2773. // 回写数据到后端,包含网络搜索结果和summary
  2774. if (message.ai_message_id) {
  2775. const contentData = {
  2776. reports: message.reports || [],
  2777. webSearchRaw: message.webSearchRaw || null,
  2778. // 使用完整的webSearchSummary,而不是打字机过程中的部分内容
  2779. webSearchSummary: message._fullWebSearchSummary || message.webSearchSummary || null,
  2780. hasWebSearchResults: message.hasWebSearchResults || false,
  2781. // ===== 🔧 修复:将summary也包含在content JSON中 =====
  2782. summary: message.summary || message._fullSummary || ''
  2783. }
  2784. const collectedContent = message.reports && message.reports.length > 0
  2785. ? JSON.stringify(contentData)
  2786. : message.content
  2787. if (collectedContent) {
  2788. // 同时保存summary字段(作为单独字段)
  2789. const summaryToSave = message.summary || message._fullSummary || ''
  2790. updateAIMessageContent(message.ai_message_id, collectedContent, summaryToSave)
  2791. .catch(err => console.error('回写AI消息失败:', err))
  2792. }
  2793. }
  2794. }
  2795. })
  2796. isAIReplyProcessComplete.value = true
  2797. showToastMessage('已停止生成', 2000)
  2798. // ===== 已删除:getUserId() - stopSSEStream 函数需要更新 =====
  2799. stopSSEStream(null, ai_conversation_id.value)
  2800. .catch(error => console.warn('停止请求失败:', error))
  2801. }
  2802. // ReportGenerator提交处理
  2803. const handleReportGeneratorSubmit = async (data) => {
  2804. isSending.value = true
  2805. currentQuestion.value = data.question
  2806. // 添加用户消息
  2807. chatMessages.value.push({
  2808. id: Date.now(),
  2809. type: 'user',
  2810. content: data.question,
  2811. timestamp: new Date().toISOString()
  2812. })
  2813. // 添加AI消息占位符
  2814. const aiMessageIndex = chatMessages.value.length
  2815. chatMessages.value.push({
  2816. id: Date.now() + 1,
  2817. type: 'ai',
  2818. userQuestion: data.question, // 用户问题
  2819. summary: '',
  2820. totalFiles: 0,
  2821. webSearchTotal: 0,
  2822. progress: 0,
  2823. completedCount: 0,
  2824. reports: [],
  2825. isTyping: true,
  2826. content: '',
  2827. displayContent: '',
  2828. timestamp: new Date().toISOString(),
  2829. // 新增:状态管理
  2830. currentStatus: 'querying_kb', // 当前状态
  2831. statusMessage: '🔍 蜀道安全管理AI智能助手正在为您分析知识库……', // 状态消息
  2832. showStats: true, // 是否显示统计卡片
  2833. // 新增:后端消息ID(初始为null,从SSE接收后赋值)
  2834. ai_message_id: null,
  2835. rawData: null,
  2836. userFeedback: null
  2837. })
  2838. try {
  2839. const apiPrefix = getApiPrefix()
  2840. const url = `${apiPrefix}/report/complete-flow`
  2841. // 构建 POST 请求体
  2842. const requestBody = {
  2843. user_question: data.question,
  2844. window_size: data.windowSize,
  2845. n_results: 2,
  2846. ai_conversation_id: ai_conversation_id.value,
  2847. is_network_search_enabled: isNetworkSearchEnabled.value
  2848. }
  2849. console.log('📤 发起 SSE POST 请求:', {
  2850. url,
  2851. body: requestBody
  2852. })
  2853. sseConnection = createSSEConnection(url, {
  2854. onMessage: (eventData) => handleSSEMessage(eventData, aiMessageIndex),
  2855. onError: handleSSEError,
  2856. onComplete: handleSSEComplete,
  2857. onInterrupted: handleSSEInterrupted
  2858. }, {
  2859. body: requestBody
  2860. })
  2861. } catch (error) {
  2862. console.error('启动失败:', error)
  2863. showToastMessage(`启动失败: ${error.message}`, 2000)
  2864. isSending.value = false
  2865. }
  2866. }
  2867. // ========== 推荐问题相关函数 ==========
  2868. // 处理推荐问题点击
  2869. const handleRelatedQuestion = (question) => {
  2870. console.log('点击推荐问题:', question)
  2871. // 清除相关推荐问题
  2872. aiRelatedQuestions.value = []
  2873. relatedQuestionsMessageId.value = null
  2874. // 将问题设置到输入框并自动发送
  2875. messageText.value = question
  2876. sendMessage()
  2877. }
  2878. // 获取AI回复相关推荐问题
  2879. const getAIRelatedQuestions = async (userMessage, aiReply, messageId) => {
  2880. if (!userMessage || !aiReply || !messageId) {
  2881. console.log('参数不完整,跳过相关推荐问题获取')
  2882. return
  2883. }
  2884. try {
  2885. console.log('开始获取AI回复相关推荐问题')
  2886. console.log('用户问题:', userMessage)
  2887. console.log('AI回复:', aiReply.substring(0, 100) + '...')
  2888. console.log('消息ID:', messageId)
  2889. isGettingRelatedQuestions.value = true
  2890. // 设计提示词让大模型返回3条相关推荐问题(与PC端一致)
  2891. const prompt = `基于以下对话内容,直接生成3条相关的推荐问题。
  2892. 【对话内容】
  2893. 用户问题:${userMessage}
  2894. AI回复:${aiReply}
  2895. 【生成要求】
  2896. - 直接输出3个问题,每个问题一行
  2897. - 问题要与原问题相关但有所延伸
  2898. - 问题要具体、实用,符合中文表达习惯
  2899. - 不要包含任何编号、标题、说明文字
  2900. - 不要重复上述指令内容`
  2901. const response = await apis.guessYouWant({
  2902. message: prompt,
  2903. // ===== 已删除:user_id - 后端从token解析 =====
  2904. ai_message_id: messageId
  2905. })
  2906. console.log('AI相关推荐问题响应:', response)
  2907. if (response.statusCode === 200 && response.data && response.data.reply) {
  2908. // 解析大模型返回的推荐问题
  2909. const replyText = response.data.reply.trim()
  2910. const questions = replyText.split('\n')
  2911. .map(q => q.trim())
  2912. .filter(q => q.length > 0)
  2913. .filter((q, index, arr) => arr.indexOf(q) === index) // 去重
  2914. .slice(0, 3) // 只取前3个
  2915. if (questions.length > 0) {
  2916. aiRelatedQuestions.value = questions
  2917. relatedQuestionsMessageId.value = messageId
  2918. console.log('✅ AI相关推荐问题数据已设置:', aiRelatedQuestions.value)
  2919. console.log('✅ relatedQuestionsMessageId设置为:', relatedQuestionsMessageId.value)
  2920. console.log('✅ messageId类型:', typeof messageId, '值:', messageId)
  2921. // 强制更新DOM
  2922. nextTick(() => {
  2923. console.log('✅ DOM已更新,推荐问题应该显示了')
  2924. scrollToBottom()
  2925. })
  2926. } else {
  2927. console.log('解析推荐问题失败,使用默认问题')
  2928. aiRelatedQuestions.value = []
  2929. relatedQuestionsMessageId.value = null
  2930. }
  2931. } else {
  2932. console.error('获取AI相关推荐问题失败:', response.statusCode)
  2933. aiRelatedQuestions.value = []
  2934. relatedQuestionsMessageId.value = null
  2935. }
  2936. } catch (error) {
  2937. console.error('获取AI相关推荐问题失败:', error)
  2938. aiRelatedQuestions.value = []
  2939. relatedQuestionsMessageId.value = null
  2940. } finally {
  2941. isGettingRelatedQuestions.value = false
  2942. }
  2943. }
  2944. // 页面卸载事件处理函数
  2945. const handlePageUnload = () => {
  2946. if (speakingMessageId.value) {
  2947. stopAllAudio()
  2948. speakingMessageId.value = null
  2949. }
  2950. }
  2951. // 页面可见性变化处理函数
  2952. const handleVisibilityChange = () => {
  2953. if (document.hidden && speakingMessageId.value) {
  2954. stopAllAudio()
  2955. speakingMessageId.value = null
  2956. }
  2957. }
  2958. // 处理中括号引用点击
  2959. const handleStandardReferenceClick = async (event) => {
  2960. const target = event.target
  2961. if (target.classList.contains('standard-reference')) {
  2962. // 只有点击标准引用时才阻止事件冒泡和默认行为
  2963. event.preventDefault()
  2964. event.stopPropagation()
  2965. const standard = target.getAttribute('data-standard')
  2966. const reference = target.getAttribute('data-reference')
  2967. // 添加调试信息
  2968. console.log('点击的元素:', target)
  2969. console.log('元素的HTML:', target.outerHTML)
  2970. console.log('data-standard属性:', standard)
  2971. console.log('data-reference属性:', reference)
  2972. console.log('所有data属性:', target.dataset)
  2973. console.log('点击了标准引用:', standard || reference)
  2974. // 确定要查询的文件名
  2975. let fileName = ''
  2976. if (standard) {
  2977. fileName = standard
  2978. } else if (reference) {
  2979. // 如果是普通引用,使用完整的引用标题作为文件名
  2980. fileName = reference
  2981. }
  2982. if (fileName) {
  2983. try {
  2984. // 调用后端接口获取文件链接
  2985. const response = await apis.getFileLink({ fileName })
  2986. console.log('获取文件链接响应:', response)
  2987. if (response.statusCode === 200 && response.data) {
  2988. const fileLink = response.data
  2989. console.log('获取到文件链接:', fileLink)
  2990. // 如果有文件链接,打开预览
  2991. if (fileLink) {
  2992. // 在新窗口中打开文件链接
  2993. window.open(fileLink, '_blank')
  2994. // showToastMessage('正在打开文件预览...')
  2995. } else {
  2996. showToastMessage('暂无文件')
  2997. }
  2998. } else {
  2999. showToastMessage('暂无文件')
  3000. }
  3001. } catch (error) {
  3002. console.error('获取文件链接失败:', error)
  3003. showToastMessage('获取文件失败,请稍后重试')
  3004. }
  3005. }
  3006. }
  3007. }
  3008. // 绑定规范引用点击事件
  3009. const bindStandardReferenceEvents = () => {
  3010. const references = document.querySelectorAll('.standard-reference')
  3011. console.log('找到规范引用元素数量:', references.length)
  3012. references.forEach((ref, index) => {
  3013. // 移除之前的事件监听器
  3014. ref.removeEventListener('click', handleStandardReferenceClick)
  3015. // 添加新的点击事件监听器
  3016. ref.addEventListener('click', handleStandardReferenceClick)
  3017. console.log(`绑定规范引用 ${index + 1}:`, ref.textContent)
  3018. })
  3019. }
  3020. // 页面加载时不再自动加载历史记录,改为点击菜单时加载
  3021. onMounted(async () => {
  3022. try {
  3023. console.log('🚀 移动端AI问答页面初始化,加载功能卡片...')
  3024. await getFunctionCards()
  3025. // 添加页面卸载和可见性变化事件监听器,在刷新时停止语音朗读
  3026. window.addEventListener('beforeunload', handlePageUnload)
  3027. window.addEventListener('unload', handlePageUnload)
  3028. document.addEventListener('visibilitychange', handleVisibilityChange)
  3029. // 添加规范引用点击事件监听器
  3030. document.addEventListener('click', handleStandardReferenceClick)
  3031. // 添加滚动监听,实现进度卡片悬浮效果
  3032. // 移动端使用 window 滚动而不是容器滚动
  3033. console.log('✅ 移动端:添加 window 滚动监听')
  3034. // 测试TTS服务连接
  3035. try {
  3036. const ttsTest = await testTTSConnection()
  3037. if (ttsTest.success) {
  3038. console.log('✅ 移动端TTS服务连接正常')
  3039. } else {
  3040. console.warn('⚠️ 移动端TTS服务连接异常:', ttsTest.message)
  3041. }
  3042. } catch (error) {
  3043. console.warn('⚠️ 移动端TTS服务连接测试失败:', error)
  3044. }
  3045. // 检查是否有自动发送的消息
  3046. const autoMessage = route.query.autoMessage
  3047. if (autoMessage) {
  3048. console.log('检测到移动端自动发送消息:', autoMessage)
  3049. // 立即清除URL中的autoMessage参数,防止刷新时重复发送
  3050. router.replace({
  3051. path: route.path,
  3052. query: { ...route.query, autoMessage: undefined }
  3053. })
  3054. // 延迟一下,确保组件完全挂载
  3055. // setTimeout(() => {
  3056. // autoSendMessage(autoMessage)
  3057. // }, 100)
  3058. autoSendMessage(autoMessage)
  3059. }
  3060. console.log('✅ 移动端AI问答页面初始化完成')
  3061. } catch (error) {
  3062. console.error('❌ 移动端AI问答页面初始化失败:', error)
  3063. }
  3064. })
  3065. // 监听历史记录抽屉显示状态,显示时加载数据
  3066. watch(showHistory, async (newVal) => {
  3067. if (newVal && historyData.value.length === 0) {
  3068. console.log('📋 历史记录抽屉打开,开始加载数据...')
  3069. await getHistoryRecordList()
  3070. }
  3071. })
  3072. // 监听语音识别错误
  3073. watch(transcript, (newVal) => {
  3074. if (!newVal || isListening.value) return
  3075. messageText.value = newVal
  3076. })
  3077. watch(speechError, (newVal) => {
  3078. if (newVal) {
  3079. console.error('语音识别错误:', newVal)
  3080. showToastMessage(newVal)
  3081. }
  3082. })
  3083. // 根据功能卡片标题返回对应的图标
  3084. const getFunctionCardIcon = (title) => {
  3085. // 按顺序循环使用4个图标
  3086. const icons = [bridgeIcon, constructionIcon, materialIcon, standardIcon]
  3087. const icon = icons[functionCardIconIndex % icons.length]
  3088. functionCardIconIndex++
  3089. return icon
  3090. }
  3091. // 点击功能卡片
  3092. const handleFunctionCard = (cardType) => {
  3093. console.log('点击功能卡片:', cardType)
  3094. // 重置聊天状态,准备创建新的对话
  3095. chatMessages.value = []
  3096. ai_conversation_id.value = 0
  3097. // 显示聊天界面
  3098. showChat.value = true
  3099. // 直接使用卡片类型作为消息内容
  3100. const message = `请详细介绍${cardType}的相关内容`
  3101. messageText.value = message
  3102. // 自动发送消息
  3103. sendMessage()
  3104. }
  3105. // 调用流式聊天接口
  3106. const callStreamChatWithDB = async (messageToAI, aiMessage, userMessage, currentMessage, responseContent, onlineSearchContent = null) => {
  3107. try {
  3108. console.log('开始调用流式聊天接口...')
  3109. // 重置状态
  3110. responseContent.value = ''
  3111. aiMessage.content = ''
  3112. aiMessage.isTyping = true
  3113. aiMessage.isStreaming = true // 确保标记为流式
  3114. const response = await fetch('/apiv1/stream/chat-with-db', {
  3115. method: 'POST',
  3116. headers: {
  3117. 'Content-Type': 'application/json',
  3118. },
  3119. body: JSON.stringify({
  3120. message: messageToAI,
  3121. // ===== 已删除:user_id - 后端从token解析 =====
  3122. ai_conversation_id: ai_conversation_id.value,
  3123. business_type: 0, // AI问答类型
  3124. ai_message_id: aiMessage.id,
  3125. online_search_content: onlineSearchContent // 添加联网搜索内容
  3126. })
  3127. })
  3128. if (!response.ok) {
  3129. throw new Error(`HTTP错误: ${response.status}`)
  3130. }
  3131. const reader = response.body.getReader()
  3132. const decoder = new TextDecoder('utf-8')
  3133. let buffer = ''
  3134. let isStreamComplete = false
  3135. // 【核心修改】创建专门的内容更新函数 - 先接收完所有数据
  3136. const updateContent = (newContent) => {
  3137. if (!newContent) return
  3138. // 处理转义的换行符
  3139. const processedContent = newContent.replace(/\\n/g, '\n')
  3140. // 累加到总内容,但不立即显示
  3141. responseContent.value += processedContent
  3142. console.log('接收内容:', processedContent, '总长度:', responseContent.value.length)
  3143. }
  3144. // 【新增】接收完所有数据后的逐字渲染函数
  3145. const renderContentCharByChar = (fullContent) => {
  3146. if (!fullContent) {
  3147. console.log('renderContentCharByChar: 内容为空')
  3148. return Promise.resolve()
  3149. }
  3150. console.log('renderContentCharByChar: 开始渲染,内容长度:', fullContent.length)
  3151. const processedContent = fullContent.replace(/\\n/g, '\n')
  3152. // 清空当前内容,准备逐字显示
  3153. aiMessage.content = ''
  3154. aiMessage.displayContent = '' // 同时清空displayContent
  3155. console.log('renderContentCharByChar: 已清空aiMessage.content和displayContent')
  3156. return new Promise((resolve) => {
  3157. let currentIndex = 0
  3158. let isRendering = true // 添加渲染状态标志
  3159. const renderNextChar = async () => {
  3160. // 检查是否还在渲染状态
  3161. if (!isRendering) {
  3162. console.log('renderContentCharByChar: 渲染已停止')
  3163. return
  3164. }
  3165. if (currentIndex < processedContent.length) {
  3166. const char = processedContent[currentIndex]
  3167. aiMessage.content += char
  3168. console.log(`renderContentCharByChar: 添加字符 ${currentIndex + 1}/${processedContent.length}: "${char}", 当前内容长度: ${aiMessage.content.length}`)
  3169. // 【关键修复】实时进行Markdown渲染,添加超时保护
  3170. try {
  3171. const renderPromise = renderWithVditor(aiMessage.content)
  3172. const timeoutPromise = new Promise((_, reject) =>
  3173. setTimeout(() => reject(new Error('渲染超时')), 1000) // 1秒超时
  3174. )
  3175. const htmlReply = await Promise.race([renderPromise, timeoutPromise])
  3176. aiMessage.displayContent = htmlReply
  3177. } catch (error) {
  3178. console.error('Markdown渲染失败:', error)
  3179. // 如果渲染失败,使用纯文本,但继续渲染
  3180. aiMessage.displayContent = aiMessage.content
  3181. }
  3182. // 每次添加一个字符都触发更新
  3183. chatMessages.value = [...chatMessages.value]
  3184. // 滚动到底部
  3185. setTimeout(scrollToBottom, 0)
  3186. currentIndex++
  3187. // 使用setTimeout而不是await,避免阻塞Vue更新
  3188. setTimeout(renderNextChar, 10) // 10ms 每个字,加快速度
  3189. } else {
  3190. // 渲染完成
  3191. console.log('renderContentCharByChar: 渲染完成')
  3192. isRendering = false
  3193. resolve()
  3194. }
  3195. }
  3196. // 开始渲染
  3197. console.log('renderContentCharByChar: 开始第一个字符')
  3198. renderNextChar()
  3199. // 添加超时保护,防止无限卡住
  3200. setTimeout(() => {
  3201. if (isRendering) {
  3202. console.warn('renderContentCharByChar: 渲染超时,强制完成')
  3203. isRendering = false
  3204. resolve()
  3205. }
  3206. }, 30000) // 30秒超时
  3207. })
  3208. }
  3209. while (!isStreamComplete) {
  3210. const { done, value } = await reader.read()
  3211. if (done) {
  3212. console.log('流读取完成')
  3213. isStreamComplete = true
  3214. break
  3215. }
  3216. const chunk = decoder.decode(value, { stream: true })
  3217. console.log('原始数据块:', chunk)
  3218. buffer += chunk
  3219. const lines = buffer.split('\n')
  3220. buffer = lines.pop() || ''
  3221. for (const line of lines) {
  3222. if (line.trim() === '') continue
  3223. console.log('处理数据行:', line)
  3224. if (line.startsWith('data: ')) {
  3225. const data = line.substring(6)
  3226. if (data === '[DONE]') {
  3227. console.log('收到结束信号 [DONE]')
  3228. isStreamComplete = true
  3229. break
  3230. }
  3231. try {
  3232. const parsed = JSON.parse(data)
  3233. if (parsed.type === 'initial') {
  3234. console.log('收到初始响应:', parsed)
  3235. if (parsed.ai_conversation_id) {
  3236. ai_conversation_id.value = parsed.ai_conversation_id
  3237. }
  3238. if (parsed.ai_message_id) {
  3239. const oldMessageId = aiMessage.id
  3240. aiMessage.id = parsed.ai_message_id
  3241. // 将搜索结果从旧ID迁移到新ID
  3242. if (onlineSearchResults.value[oldMessageId]) {
  3243. onlineSearchResults.value[parsed.ai_message_id] = onlineSearchResults.value[oldMessageId]
  3244. expandedOnlineSearchResults.value[parsed.ai_message_id] = expandedOnlineSearchResults.value[oldMessageId] || false
  3245. // 删除旧ID的搜索结果
  3246. delete onlineSearchResults.value[oldMessageId]
  3247. delete expandedOnlineSearchResults.value[oldMessageId]
  3248. console.log('搜索结果已从旧ID迁移到新ID:', oldMessageId, '->', parsed.ai_message_id)
  3249. // 使用新的ai_message_id重新保存到数据库
  3250. try {
  3251. const saveData = {
  3252. id: parsed.ai_message_id,
  3253. ai_conversation_id: ai_conversation_id.value,
  3254. search_source: JSON.stringify(onlineSearchResults.value[parsed.ai_message_id])
  3255. }
  3256. const saveResponse = await apis.saveOnlineSearchResult(saveData)
  3257. console.log('使用新ID保存联网搜索结果到数据库成功:', saveResponse)
  3258. } catch (saveError) {
  3259. console.error('使用新ID保存联网搜索结果到数据库失败:', saveError)
  3260. }
  3261. }
  3262. }
  3263. continue
  3264. }
  3265. if (parsed.error) {
  3266. throw new Error(parsed.error)
  3267. }
  3268. // 【修改】只累加内容,不立即逐字输出
  3269. if (parsed.choices && parsed.choices.length > 0) {
  3270. const choice = parsed.choices[0]
  3271. if (choice.delta && choice.delta.content) {
  3272. updateContent(choice.delta.content)
  3273. }
  3274. if (choice.finish_reason) {
  3275. console.log('收到完成信号:', choice.finish_reason)
  3276. isStreamComplete = true
  3277. break
  3278. }
  3279. } else if (parsed.content) {
  3280. updateContent(parsed.content)
  3281. } else {
  3282. const textContent = String(parsed)
  3283. if (textContent && textContent !== '[object Object]') {
  3284. updateContent(textContent)
  3285. }
  3286. }
  3287. } catch (e) {
  3288. console.log('作为文本内容处理:', data)
  3289. updateContent(data)
  3290. }
  3291. } else {
  3292. console.log('处理纯文本内容:', line)
  3293. updateContent(line)
  3294. }
  3295. }
  3296. if (isStreamComplete) break
  3297. }
  3298. // 流式响应完成
  3299. console.log('流式响应完成,开始逐字渲染,最终内容长度:', responseContent.value.length)
  3300. // 开始逐字渲染(保持isTyping = true来显示光标)
  3301. await renderContentCharByChar(responseContent.value)
  3302. // 渲染完成后设置状态
  3303. aiMessage.isTyping = false
  3304. aiMessage.isStreaming = false
  3305. // 【简化】后续处理
  3306. await processFinalResponse(aiMessage, responseContent.value, userMessage, !!onlineSearchContent)
  3307. } catch (error) {
  3308. console.error('调用流式聊天接口失败:', error)
  3309. aiMessage.isTyping = false
  3310. aiMessage.isStreaming = false
  3311. aiMessage.content = '抱歉,网络连接出现问题,请检查网络后重试。'
  3312. aiMessage.displayContent = await renderWithVditor(aiMessage.content)
  3313. }
  3314. }
  3315. // 提取后续处理逻辑到单独函数
  3316. const processFinalResponse = async (aiMessage, finalContent, userMessage, hasOnlineSearch = false) => {
  3317. const processedReply = processAIResponse(finalContent)
  3318. aiMessage.content = finalContent
  3319. // 只有在displayContent为空或没有HTML标签时才重新渲染
  3320. if (!aiMessage.displayContent || !aiMessage.displayContent.includes('<')) {
  3321. const htmlReply = await renderWithVditor(processedReply)
  3322. aiMessage.displayContent = htmlReply
  3323. }
  3324. // 只需要在最后更新一次
  3325. chatMessages.value = [...chatMessages.value]
  3326. // 获取历史记录
  3327. await getHistoryRecordList()
  3328. if (ai_conversation_id.value > 0) {
  3329. historyData.value.forEach((item) => {
  3330. item.isActive = item.id === ai_conversation_id.value
  3331. })
  3332. }
  3333. // 启动后续流程
  3334. setTimeout(async () => {
  3335. isAIReplyProcessComplete.value = false
  3336. // 如果还没有进行联网搜索,则进行联网搜索
  3337. if (!hasOnlineSearch && isNetworkSearchEnabled.value) {
  3338. await performOnlineSearch(userMessage.content, aiMessage.id)
  3339. }
  3340. // 获取推荐问题
  3341. await getAIRelatedQuestions(userMessage.content, processedReply, aiMessage.id)
  3342. setTimeout(() => {
  3343. scrollToBottom()
  3344. isAIReplyProcessComplete.value = true
  3345. console.log('AI回复流程完成')
  3346. }, 100)
  3347. }, 200)
  3348. }
  3349. // 发送消息
  3350. // 发送消息 - 使用SSE接口
  3351. const sendMessage = async () => {
  3352. if (!messageText.value.trim() || isSending.value) return
  3353. console.log('📤 移动端发送消息:', messageText.value)
  3354. // 清除推荐问题
  3355. aiRelatedQuestions.value = []
  3356. relatedQuestionsMessageId.value = null
  3357. isSending.value = true
  3358. showChat.value = true
  3359. // 如果是新对话,清除所有历史记录的选中状态
  3360. if (chatMessages.value.length === 0) {
  3361. historyData.value.forEach((item) => {
  3362. item.isActive = false
  3363. })
  3364. expandedSearchSources.value = {}
  3365. expandedOnlineSearchResults.value = {}
  3366. onlineSearchResults.value = {}
  3367. }
  3368. // 保存当前消息并清空输入框
  3369. const currentMessage = messageText.value
  3370. messageText.value = ''
  3371. // 调用ReportGenerator的SSE接口
  3372. await handleReportGeneratorSubmit({
  3373. question: currentMessage,
  3374. windowSize: 3,
  3375. nResults: 10
  3376. })
  3377. scrollToBottom()
  3378. }
  3379. // 开始打字效果(非流式接口使用)
  3380. const startTypingEffect = async (aiMessage, htmlReply, processedReply, currentMessage) => {
  3381. console.log('开始打字效果,HTML长度:', htmlReply.length)
  3382. // 开始打字效果 - 按完整HTML标签或文本块显示,避免标签分割
  3383. const textBlocks = []
  3384. let currentBlock = ''
  3385. let inTag = false
  3386. let tagContent = ''
  3387. // 将HTML内容分割成完整的块
  3388. for (let i = 0; i < htmlReply.length; i++) {
  3389. const char = htmlReply[i]
  3390. if (char === '<') {
  3391. // 如果之前有文本内容,先保存
  3392. if (currentBlock && !inTag) {
  3393. textBlocks.push({ type: 'text', content: currentBlock })
  3394. currentBlock = ''
  3395. }
  3396. inTag = true
  3397. tagContent = char
  3398. } else if (char === '>') {
  3399. // 标签结束
  3400. tagContent += char
  3401. textBlocks.push({ type: 'tag', content: tagContent })
  3402. inTag = false
  3403. tagContent = ''
  3404. } else if (inTag) {
  3405. // 在标签内
  3406. tagContent += char
  3407. } else {
  3408. // 普通文本
  3409. currentBlock += char
  3410. }
  3411. }
  3412. // 保存最后一个文本块
  3413. if (currentBlock) {
  3414. textBlocks.push({ type: 'text', content: currentBlock })
  3415. }
  3416. // 检查是否有未闭合的标签
  3417. if (tagContent) {
  3418. textBlocks.push({ type: 'tag', content: tagContent })
  3419. }
  3420. console.log('分割后的文本块:', textBlocks)
  3421. let currentBlockIndex = 0
  3422. let currentCharIndex = 0
  3423. const typeInterval = setInterval(() => {
  3424. if (currentBlockIndex < textBlocks.length) {
  3425. const currentBlock = textBlocks[currentBlockIndex]
  3426. if (currentBlock.type === 'tag') {
  3427. // 标签直接显示,不分字符
  3428. console.log('显示HTML标签:', currentBlock.content)
  3429. aiMessage.displayContent += currentBlock.content
  3430. currentBlockIndex++
  3431. currentCharIndex = 0
  3432. } else {
  3433. // 文本按字符显示
  3434. if (currentCharIndex < currentBlock.content.length) {
  3435. const newContent = aiMessage.displayContent + currentBlock.content[currentCharIndex]
  3436. aiMessage.displayContent = newContent
  3437. currentCharIndex++
  3438. } else {
  3439. // 当前文本块完成,移动到下一个
  3440. currentBlockIndex++
  3441. currentCharIndex = 0
  3442. }
  3443. }
  3444. // 强制触发Vue响应式更新
  3445. chatMessages.value = [...chatMessages.value]
  3446. // 自动滚动到底部
  3447. scrollToBottom()
  3448. } else {
  3449. // 所有块都显示完成
  3450. aiMessage.isTyping = false
  3451. aiMessage.content = processedReply // 保存完整内容
  3452. clearInterval(typeInterval)
  3453. console.log('打字完成,最终displayContent:', aiMessage.displayContent)
  3454. // 强制触发Vue响应式更新,确保hasTypingMessage计算属性更新
  3455. chatMessages.value = [...chatMessages.value]
  3456. console.log('打字完成,强制更新响应式数据')
  3457. // AI回复完成后,进行联网搜索(如果启用)
  3458. if (isNetworkSearchEnabled.value) {
  3459. console.log('开始联网搜索,消息ID:', aiMessage.id, '用户输入:', currentMessage)
  3460. performOnlineSearch(currentMessage, aiMessage.id)
  3461. // 联网搜索启用时,推荐问题会在联网搜索完成后获取
  3462. } else {
  3463. // 联网搜索未启用时,直接获取推荐问题
  3464. setTimeout(async () => {
  3465. console.log('联网搜索未启用,开始获取推荐问题,消息ID:', aiMessage.id)
  3466. await getAIRelatedQuestions(currentMessage, processedReply, aiMessage.id)
  3467. }, 1000)
  3468. }
  3469. // AI回复完成后,获取最新的历史记录
  3470. getHistoryRecordList()
  3471. }
  3472. }, 50) // 每50ms显示一个字符
  3473. }
  3474. // 滚动到底部
  3475. const scrollToBottom = () => {
  3476. nextTick(() => {
  3477. const chatContainer = document.querySelector('.chat-messages')
  3478. if (chatContainer) {
  3479. chatContainer.scrollTop = chatContainer.scrollHeight
  3480. }
  3481. })
  3482. }
  3483. // 获取功能卡片数据
  3484. const getFunctionCards = async () => {
  3485. try {
  3486. console.log('开始获取功能卡片...')
  3487. const response = await apis.getFunctionCard({ function_type: 0 }) // 0为AI问答类型
  3488. console.log('功能卡片响应:', response)
  3489. if (response.statusCode === 200) {
  3490. functionCards.value = response.data
  3491. console.log('功能卡片数据已设置:', functionCards.value)
  3492. } else {
  3493. console.error('获取功能卡片失败:', response.statusCode)
  3494. }
  3495. } catch (error) {
  3496. console.error('获取功能卡片失败:', error)
  3497. }
  3498. }
  3499. // 获取热点问题数据
  3500. const getHotQuestions = async () => {
  3501. try {
  3502. console.log('开始获取热点问题...')
  3503. const response = await apis.getHotQuestion({ question_type: 0 }) // 0为AI问答类型
  3504. console.log('热点问题响应:', response)
  3505. if (response.statusCode === 200) {
  3506. hotQuestions.value = response.data
  3507. console.log('热点问题数据已设置:', hotQuestions.value)
  3508. } else {
  3509. console.error('获取热点问题失败:', response.statusCode)
  3510. }
  3511. } catch (error) {
  3512. console.error('获取热点问题失败:', error)
  3513. }
  3514. }
  3515. // Toast显示函数
  3516. const showToastMessage = (message, duration = 2000) => {
  3517. // 立即关闭当前提示(如果有的话)
  3518. showToast.value = false
  3519. // 使用 nextTick 确保关闭动画完成后再显示新提示
  3520. nextTick(() => {
  3521. toastMessage.value = message
  3522. toastDuration.value = duration
  3523. showToast.value = true
  3524. })
  3525. }
  3526. // 复制到剪贴板
  3527. const copyToClipboard = async (text) => {
  3528. try {
  3529. await navigator.clipboard.writeText(text)
  3530. showToastMessage('复制成功')
  3531. } catch (error) {
  3532. console.error('复制失败:', error)
  3533. showToastMessage('复制失败', 'error')
  3534. }
  3535. }
  3536. // 复制用户消息
  3537. const copyUserMessage = (message) => {
  3538. copyToClipboard(message.content)
  3539. }
  3540. // 复制AI消息
  3541. const copyAIMessage = (message) => {
  3542. // 优先使用summary(非专业问题的回复),然后是displayContent,最后是content
  3543. let textToCopy = message.summary || message.displayContent || message.content
  3544. // 如果包含HTML标签,转换为纯文本
  3545. if (textToCopy && textToCopy.includes('<')) {
  3546. // 创建临时DOM元素来提取纯文本
  3547. const tempDiv = document.createElement('div')
  3548. tempDiv.innerHTML = textToCopy
  3549. textToCopy = tempDiv.textContent || tempDiv.innerText || textToCopy
  3550. }
  3551. // 如果还是没有内容,尝试从reports中提取
  3552. if (!textToCopy && message.reports && message.reports.length > 0) {
  3553. textToCopy = message.reports
  3554. .filter(r => r.type !== 'category_title')
  3555. .map(r => r.report || '')
  3556. .join('\n\n')
  3557. }
  3558. // 如果有网络搜索总结,也添加进去
  3559. if (message.webSearchSummary) {
  3560. textToCopy = textToCopy
  3561. ? `${textToCopy}\n\n【网络搜索总结】\n${message.webSearchSummary}`
  3562. : message.webSearchSummary
  3563. }
  3564. if (textToCopy && textToCopy.trim()) {
  3565. copyToClipboard(textToCopy)
  3566. } else {
  3567. showToastMessage('暂无可复制的内容')
  3568. }
  3569. }
  3570. // 编辑用户消息
  3571. const editUserMessage = (message) => {
  3572. console.log('编辑用户消息:', message.content)
  3573. messageText.value = message.content
  3574. // 聚焦到输入框
  3575. nextTick(() => {
  3576. const inputElement = document.querySelector('.message-input')
  3577. if (inputElement) {
  3578. inputElement.focus()
  3579. inputElement.setSelectionRange(inputElement.value.length, inputElement.value.length)
  3580. }
  3581. })
  3582. }
  3583. // 语音输入相关方法
  3584. // 语音输入相关方法
  3585. const handleVoiceClick = () => {
  3586. console.log('点击语音按钮')
  3587. // 移除对 speechSupported.value 的直接检查,让 startListening 内部去处理
  3588. // 因为 speechSupported 初始值为 false,且没有自动初始化,直接检查会导致误判
  3589. if (isListening.value) {
  3590. // 如果正在录音,则停止
  3591. stopVoiceInput()
  3592. } else {
  3593. // 开始语音输入
  3594. startVoiceInput()
  3595. }
  3596. }
  3597. const startVoiceInput = () => {
  3598. console.log('开始语音输入')
  3599. // 开始语音识别
  3600. const success = startListening()
  3601. if (!success) {
  3602. // 如果启动失败,优先显示内部错误信息
  3603. if (speechError.value) {
  3604. showToastMessage(speechError.value)
  3605. } else {
  3606. showToastMessage('语音识别启动失败,请检查麦克风权限')
  3607. }
  3608. }
  3609. }
  3610. const stopVoiceInput = () => {
  3611. console.log('停止语音输入')
  3612. stopListening()
  3613. // 语音识别完成后,将结果填入输入框
  3614. if (transcript.value.trim()) {
  3615. messageText.value = transcript.value
  3616. }
  3617. }
  3618. // 重新生成AI回复
  3619. const regenerateResponse = async (messageIndex) => {
  3620. console.log('重新生成回复,消息索引:', messageIndex)
  3621. // 找到对应的用户消息
  3622. if (messageIndex > 0) {
  3623. const userMessage = chatMessages.value[messageIndex - 1]
  3624. if (userMessage && userMessage.type === 'user') {
  3625. console.log('重新发送用户消息:', userMessage.content)
  3626. // 恢复消息文本
  3627. messageText.value = userMessage.content
  3628. // 调用sendMessage函数重新发送
  3629. await sendMessage()
  3630. }
  3631. }
  3632. }
  3633. // 删除弹窗相关方法
  3634. const handleDeleteClick = (messageIndex) => {
  3635. console.log('点击删除按钮,消息索引:', messageIndex)
  3636. // 检查是否只剩一句AI回复和一句用户发言
  3637. if (chatMessages.value.length === 2) {
  3638. showToastMessage('第一句话无法删除', 'warning')
  3639. return
  3640. }
  3641. // 设置删除类型和要删除的消息索引
  3642. deleteType.value = 'message'
  3643. deleteTargetItem.value = { messageIndex }
  3644. showDeleteModal.value = true
  3645. }
  3646. // 点赞和点踩功能
  3647. const handleThumbsUp = async (message) => {
  3648. console.log('点赞消息:', message.id)
  3649. // 如果已经点赞,则取消点赞
  3650. if (message.userFeedback === 'like') {
  3651. message.userFeedback = null
  3652. } else {
  3653. // 设置点赞,取消点踩
  3654. message.userFeedback = 'like'
  3655. }
  3656. // 强制触发Vue响应式更新
  3657. chatMessages.value = [...chatMessages.value]
  3658. // 同步反馈到后端
  3659. await syncFeedbackToBackend(message)
  3660. }
  3661. const handleThumbsDown = async (message) => {
  3662. console.log('点踩消息:', message.id)
  3663. // 如果已经点踩,则取消点踩
  3664. if (message.userFeedback === 'dislike') {
  3665. message.userFeedback = null
  3666. } else {
  3667. // 设置点踩,取消点赞
  3668. message.userFeedback = 'dislike'
  3669. }
  3670. // 强制触发Vue响应式更新
  3671. chatMessages.value = [...chatMessages.value]
  3672. // 同步反馈到后端
  3673. await syncFeedbackToBackend(message)
  3674. }
  3675. // 同步用户反馈到后端
  3676. const syncFeedbackToBackend = async (message) => {
  3677. try {
  3678. console.log('🔍 syncFeedbackToBackend 收到的message对象:', {
  3679. id: message.id,
  3680. ai_message_id: message.ai_message_id,
  3681. rawData: message.rawData,
  3682. rawData_id: message.rawData?.id
  3683. })
  3684. // 优先使用ai_message_id,其次使用rawData.id
  3685. const messageId = message.ai_message_id || (message.rawData && message.rawData.id)
  3686. if (!messageId) {
  3687. console.warn('❌ 消息缺少ID,无法同步反馈')
  3688. console.warn(' - message.ai_message_id:', message.ai_message_id)
  3689. console.warn(' - message.rawData:', message.rawData)
  3690. return
  3691. }
  3692. const feedback = convertFeedbackToBackend(message.userFeedback)
  3693. console.log('✅ 同步反馈到后端:', {
  3694. messageId: messageId,
  3695. feedback: feedback
  3696. })
  3697. // 调用后端点赞点踩接口
  3698. const response = await apis.likeAndDislike({
  3699. id: messageId,
  3700. user_feedback: feedback
  3701. })
  3702. if (response.statusCode === 200) {
  3703. console.log('反馈同步成功')
  3704. // 根据反馈类型显示不同提示
  3705. if (feedback === 2) {
  3706. showToastMessage('点赞成功')
  3707. } else if (feedback === 3) {
  3708. showToastMessage('点踩成功')
  3709. } else {
  3710. showToastMessage('已取消反馈')
  3711. }
  3712. } else {
  3713. console.error('反馈同步失败:', response.msg)
  3714. showToastMessage('反馈提交失败,请稍后重试', 'error')
  3715. }
  3716. } catch (error) {
  3717. console.error('同步反馈失败:', error)
  3718. showToastMessage('反馈提交失败,请稍后重试', 'error')
  3719. }
  3720. }
  3721. // 统一的确认删除函数
  3722. const confirmDelete = async () => {
  3723. if (!deleteTargetItem.value) return
  3724. if (deleteType.value === 'history') {
  3725. await confirmDeleteHistory()
  3726. } else if (deleteType.value === 'message') {
  3727. await confirmDeleteMessage()
  3728. }
  3729. }
  3730. // 确认删除历史记录
  3731. const confirmDeleteHistory = async () => {
  3732. const { item: historyItem, index } = deleteTargetItem.value
  3733. try {
  3734. // 调用删除接口
  3735. const response = await apis.deleteHistoryRecord({
  3736. ai_conversation_id: historyItem.id
  3737. })
  3738. if (response.statusCode === 200) {
  3739. // 删除成功,从列表中移除
  3740. historyData.value.splice(index, 1)
  3741. // 如果删除的是当前激活的历史记录,执行新建任务
  3742. if (historyItem.isActive) {
  3743. console.log('删除激活的历史记录,执行新建任务')
  3744. startNewChat()
  3745. }
  3746. console.log('历史记录删除成功')
  3747. showToastMessage('删除成功')
  3748. } else {
  3749. console.error('删除历史记录失败:', response.msg)
  3750. showToastMessage(response.msg || '删除失败', 'error')
  3751. }
  3752. } catch (error) {
  3753. console.error('删除历史记录失败:', error)
  3754. showToastMessage('删除失败,请稍后重试', 'error')
  3755. } finally {
  3756. // 关闭弹窗并清除目标项
  3757. showDeleteModal.value = false
  3758. deleteTargetItem.value = null
  3759. deleteType.value = ''
  3760. }
  3761. }
  3762. // 确认删除消息
  3763. const confirmDeleteMessage = async () => {
  3764. const { messageIndex } = deleteTargetItem.value
  3765. try {
  3766. const aiMessage = chatMessages.value[messageIndex]
  3767. // 检查是否有id
  3768. if (aiMessage && aiMessage.id) {
  3769. try {
  3770. // 调用后端删除接口
  3771. const response = await apis.deleteConversation({
  3772. ai_message_id: aiMessage.id
  3773. })
  3774. if (response.statusCode === 200) {
  3775. // 后端删除成功,从前端数组中删除AI消息和对应的用户消息
  3776. // 删除AI消息
  3777. chatMessages.value.splice(messageIndex, 1)
  3778. // 删除对应的用户消息(前一条)
  3779. if (messageIndex > 0) {
  3780. chatMessages.value.splice(messageIndex - 1, 1)
  3781. }
  3782. console.log('删除成功')
  3783. showToastMessage('删除成功')
  3784. } else {
  3785. console.error('删除失败:', response.msg)
  3786. showToastMessage('删除失败,请稍后重试', 'error')
  3787. }
  3788. } catch (error) {
  3789. console.error('删除接口调用失败:', error)
  3790. showToastMessage('删除失败,请稍后重试', 'error')
  3791. }
  3792. } else {
  3793. console.log('没有id,仅从前端删除')
  3794. // 没有id的情况,仅从前端删除
  3795. chatMessages.value.splice(messageIndex, 1)
  3796. showToastMessage('删除成功')
  3797. }
  3798. } catch (error) {
  3799. console.error('删除消息失败:', error)
  3800. showToastMessage('删除失败,请稍后重试', 'error')
  3801. } finally {
  3802. // 关闭弹窗并清除目标项
  3803. showDeleteModal.value = false
  3804. deleteTargetItem.value = null
  3805. deleteType.value = ''
  3806. }
  3807. }
  3808. // 取消删除
  3809. const cancelDelete = () => {
  3810. showDeleteModal.value = false
  3811. deleteTargetItem.value = null
  3812. deleteType.value = ''
  3813. }
  3814. // 组件销毁前,强制停止任何朗读
  3815. onBeforeUnmount(() => {
  3816. if (speakingMessageId.value) {
  3817. stopAllAudio()
  3818. speakingMessageId.value = null
  3819. }
  3820. // 清理页面卸载和可见性变化事件监听器
  3821. window.removeEventListener('beforeunload', handlePageUnload)
  3822. window.removeEventListener('unload', handlePageUnload)
  3823. document.removeEventListener('visibilitychange', handleVisibilityChange)
  3824. // 清理规范引用点击事件监听器
  3825. document.removeEventListener('click', handleStandardReferenceClick)
  3826. })
  3827. // 页面重新激活时,重新渲染所有AI消息的markdown内容
  3828. onActivated(async () => {
  3829. console.log('🔄 移动端页面重新激活,检查并重新渲染markdown内容')
  3830. // 等待DOM更新
  3831. await nextTick()
  3832. // 重新渲染所有AI消息的markdown内容
  3833. for (const message of chatMessages.value) {
  3834. if (message.type === 'ai' && message.content) {
  3835. try {
  3836. // 对于已完成的消息(!isTyping),重新渲染markdown
  3837. if (!message.isTyping) {
  3838. console.log('重新渲染已完成AI消息markdown:', message.id)
  3839. const processedReply = processAIResponse(message.content)
  3840. const processedReplyWithFileDisplay = processFileDisplay(processedReply, message.file)
  3841. const htmlReply = await renderWithVditor(processedReplyWithFileDisplay)
  3842. message.displayContent = htmlReply
  3843. } else {
  3844. // 对于正在输出的消息(isTyping为true),保持其当前状态和显示内容
  3845. // 如果已有部分内容但displayContent为空,则重新渲染已输出的部分
  3846. if (message.content && (!message.displayContent || message.displayContent.trim() === '')) {
  3847. console.log('🔄 恢复正在输出的AI消息显示:', message.id, '已输出内容长度:', message.content.length)
  3848. const processedReply = processAIResponse(message.content)
  3849. const processedReplyWithFileDisplay = processFileDisplay(processedReply, message.file)
  3850. const htmlReply = await renderWithVditor(processedReplyWithFileDisplay)
  3851. message.displayContent = htmlReply
  3852. } else {
  3853. console.log('✅ 保持正在输出的AI消息状态:', message.id, 'isTyping:', message.isTyping)
  3854. }
  3855. }
  3856. // 重新绑定规范引用点击事件
  3857. setTimeout(() => {
  3858. bindStandardReferenceEvents()
  3859. }, 100)
  3860. } catch (error) {
  3861. console.error('❌ 重新渲染markdown失败:', error)
  3862. // 如果重新渲染失败,保持原有内容
  3863. }
  3864. }
  3865. }
  3866. // 强制触发Vue响应式更新
  3867. chatMessages.value = [...chatMessages.value]
  3868. // 滚动到底部,确保用户能看到最新内容
  3869. await nextTick()
  3870. scrollToBottom()
  3871. console.log('✅ 移动端页面重新激活完成,markdown内容已重新渲染')
  3872. })
  3873. </script>
  3874. <style lang="less" scoped>
  3875. .mobile-chat {
  3876. min-height: 100vh;
  3877. background: #EBF3FF;
  3878. font-family: "Alibaba PuHuiTi 3.0", sans-serif;
  3879. overflow-x: hidden; // 防止水平滚动
  3880. -webkit-overflow-scrolling: touch; // iOS平滑滚动
  3881. touch-action: manipulation; // 禁用双击缩放
  3882. }
  3883. /* 使用通用 MobileHeader 组件后,移除页面内头部样式 */
  3884. .mobile-content {
  3885. padding: 20px;
  3886. text-align: center;
  3887. position: relative;
  3888. padding-bottom: 80px; // 减少底部预留空间
  3889. .coming-soon {
  3890. font-size: 20px;
  3891. color: #666;
  3892. margin-top: 50px;
  3893. }
  3894. }
  3895. /* AI助手介绍 */
  3896. .ai-intro {
  3897. display: flex;
  3898. flex-direction: column;
  3899. align-items: center;
  3900. margin-bottom: 30px;
  3901. .ai-avatar {
  3902. width: 180px;
  3903. height: 180px;
  3904. border-radius: 20px;
  3905. display: flex;
  3906. align-items: center;
  3907. justify-content: center;
  3908. margin-bottom: 16px;
  3909. animation: avatar-float 3s ease-in-out infinite;
  3910. .ai-avatar-img {
  3911. width: 100%;
  3912. height: 100%;
  3913. object-fit: contain;
  3914. filter: drop-shadow(0 4px 16px rgba(91, 141, 239, 0.2));
  3915. }
  3916. }
  3917. @keyframes avatar-float {
  3918. 0%, 100% {
  3919. transform: translateY(0);
  3920. }
  3921. 50% {
  3922. transform: translateY(-8px);
  3923. }
  3924. }
  3925. .ai-greeting {
  3926. text-align: center;
  3927. h3 {
  3928. font-size: 18px;
  3929. font-weight: 600;
  3930. color: #1f2937;
  3931. margin: 0 0 8px 0;
  3932. }
  3933. p {
  3934. font-size: 14px;
  3935. color: #6b7280;
  3936. margin: 0;
  3937. }
  3938. }
  3939. }
  3940. /* 功能卡片 */
  3941. .function-cards {
  3942. display: grid;
  3943. grid-template-columns: repeat(2, 1fr);
  3944. gap: 12px;
  3945. margin-top: 30px;
  3946. .function-card {
  3947. background: white;
  3948. padding: 16px;
  3949. border-radius: 12px;
  3950. border: 1px solid #E5E8EB;
  3951. cursor: pointer;
  3952. transition: all 0.3s ease;
  3953. display: flex;
  3954. flex-direction: column;
  3955. justify-content: center;
  3956. text-align: left;
  3957. &:hover {
  3958. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  3959. transform: translateY(-2px);
  3960. }
  3961. .card-header {
  3962. display: flex;
  3963. align-items: center;
  3964. margin-bottom: 8px;
  3965. .card-icon {
  3966. width: 32px;
  3967. height: 32px;
  3968. margin-right: 12px;
  3969. .card-icon-img {
  3970. width: 100%;
  3971. height: 100%;
  3972. object-fit: cover;
  3973. }
  3974. }
  3975. h4 {
  3976. font-size: 16px;
  3977. font-weight: 600;
  3978. color: #1f2937;
  3979. margin: 0;
  3980. flex: 1;
  3981. }
  3982. }
  3983. .card-description {
  3984. p {
  3985. font-size: 14px;
  3986. color: #6b7280;
  3987. margin: 0;
  3988. line-height: 1.4;
  3989. // 超出两行显示省略号
  3990. display: -webkit-box;
  3991. -webkit-line-clamp: 1;
  3992. line-clamp: 1;
  3993. -webkit-box-orient: vertical;
  3994. overflow: hidden;
  3995. }
  3996. }
  3997. }
  3998. }
  3999. /* 聊天消息区域 */
  4000. .chat-messages {
  4001. max-height: calc(100vh - 180px); // 减少底部空间
  4002. overflow-y: auto;
  4003. padding: 20px 0;
  4004. margin-bottom: 10px; // 减少底部边距
  4005. .message-item {
  4006. margin-bottom: 20px;
  4007. &.user {
  4008. display: flex;
  4009. justify-content: flex-end;
  4010. .user-message {
  4011. background: #3e7bfa;
  4012. color: white;
  4013. padding: 12px 16px;
  4014. border-radius: 18px 18px 4px 18px;
  4015. max-width: 80%;
  4016. text-align: left;
  4017. .message-content {
  4018. .message-text {
  4019. font-size: 20px;
  4020. line-height: 1.4;
  4021. word-wrap: break-word;
  4022. }
  4023. }
  4024. .message-actions {
  4025. margin-top: 8px;
  4026. display: flex;
  4027. gap: 8px;
  4028. justify-content: flex-end;
  4029. .action-btn {
  4030. background: transparent;
  4031. border: none;
  4032. color: white;
  4033. padding: 4px;
  4034. border-radius: 4px;
  4035. cursor: pointer;
  4036. display: flex;
  4037. align-items: center;
  4038. justify-content: center;
  4039. transition: all 0.2s ease;
  4040. .action-icon {
  4041. width: 20px;
  4042. height: 20px;
  4043. object-fit: contain;
  4044. filter: brightness(0) invert(1); // 将图标变为白色
  4045. }
  4046. }
  4047. }
  4048. }
  4049. }
  4050. }
  4051. }
  4052. /* AI消息样式 */
  4053. .ai-message {
  4054. display: flex;
  4055. flex-direction: column;
  4056. gap: 0;
  4057. overflow-x: hidden;
  4058. max-width: 100%;
  4059. .ai-message-main {
  4060. display: flex;
  4061. gap: 12px;
  4062. overflow-x: hidden;
  4063. max-width: 100%;
  4064. }
  4065. .ai-avatar-small {
  4066. width: 52px;
  4067. height: 52px;
  4068. flex-shrink: 0;
  4069. .ai-icon {
  4070. width: 100%;
  4071. height: 100%;
  4072. object-fit: contain;
  4073. }
  4074. }
  4075. // 网络搜索胶囊外层容器
  4076. .web-search-capsule-outer {
  4077. margin-bottom: 8px;
  4078. display: flex;
  4079. justify-content: flex-start;
  4080. padding-left: 62px; // 为头像留空间
  4081. overflow-x: hidden;
  4082. max-width: 100%;
  4083. }
  4084. // AI消息主体容器
  4085. .ai-message-main {
  4086. display: flex;
  4087. gap: 10px;
  4088. align-items: flex-start;
  4089. margin-bottom: 16px;
  4090. overflow-x: hidden;
  4091. max-width: 100%;
  4092. }
  4093. // AI头像样式 - 移动端(用户已设置为52px)
  4094. .ai-avatar-small {
  4095. width: 52px;
  4096. height: 52px;
  4097. flex-shrink: 0;
  4098. animation: avatar-pulse 2s ease-in-out infinite;
  4099. .ai-icon {
  4100. width: 100%;
  4101. height: 100%;
  4102. object-fit: contain;
  4103. filter: drop-shadow(0 2px 8px rgba(91, 141, 239, 0.15));
  4104. }
  4105. }
  4106. @keyframes avatar-pulse {
  4107. 0%, 100% {
  4108. transform: scale(1);
  4109. }
  4110. 50% {
  4111. transform: scale(1.05);
  4112. }
  4113. }
  4114. // 白色气泡容器 - 包裹所有AI内容
  4115. .message-content {
  4116. flex: 1;
  4117. min-width: 0;
  4118. max-width: 100%;
  4119. background: white;
  4120. border-radius: 12px;
  4121. padding: 16px;
  4122. box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  4123. text-align: left;
  4124. overflow-x: hidden;
  4125. word-wrap: break-word;
  4126. overflow-wrap: break-word;
  4127. }
  4128. // AI响应内容容器
  4129. .ai-response-content {
  4130. text-align: left;
  4131. }
  4132. // 进度统计卡片(白色背景)
  4133. .stats-card {
  4134. display: flex;
  4135. flex-direction: column;
  4136. gap: 12px;
  4137. padding: 12px 16px;
  4138. background: #f8f9fa;
  4139. border-radius: 8px;
  4140. margin-bottom: 12px;
  4141. border: 1px solid #e8ecf1;
  4142. transition: box-shadow 0.3s ease;
  4143. }
  4144. .stats-left {
  4145. display: flex;
  4146. align-items: center;
  4147. gap: 10px;
  4148. width: 100%;
  4149. span {
  4150. font-size: 13px;
  4151. font-weight: 500;
  4152. color: #2d3748;
  4153. flex: 1;
  4154. line-height: 1.4;
  4155. }
  4156. }
  4157. .stats-avatar {
  4158. flex-shrink: 0;
  4159. }
  4160. .status-text {
  4161. font-size: 13px;
  4162. font-weight: 500;
  4163. color: #2d3748;
  4164. }
  4165. .stats-left :deep(.ai-name) {
  4166. color: #5b8def !important;
  4167. font-weight: 600 !important;
  4168. }
  4169. .stats-left :deep(.file-count) {
  4170. color: #5b8def !important;
  4171. font-weight: 600 !important;
  4172. }
  4173. .stats-right {
  4174. flex-shrink: 0;
  4175. }
  4176. // 问题总结卡片
  4177. .question-summary {
  4178. margin-bottom: 12px;
  4179. padding: 12px 16px;
  4180. background: white;
  4181. border-radius: 12px;
  4182. box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  4183. font-size: 14px;
  4184. line-height: 1.8;
  4185. color: #606266;
  4186. }
  4187. .reports-list {
  4188. margin-top: 12px;
  4189. }
  4190. // AI文本内容
  4191. .ai-text {
  4192. text-align: left;
  4193. max-width: 100%;
  4194. overflow-x: hidden;
  4195. word-wrap: break-word;
  4196. .ai-markdown-content {
  4197. text-align: left;
  4198. max-width: 100%;
  4199. overflow-x: hidden;
  4200. word-wrap: break-word;
  4201. * {
  4202. text-align: left !important;
  4203. max-width: 100%;
  4204. word-wrap: break-word;
  4205. }
  4206. }
  4207. }
  4208. .question-summary {
  4209. text-align: left;
  4210. margin-bottom: 12px;
  4211. max-width: 100%;
  4212. overflow-x: hidden;
  4213. word-wrap: break-word;
  4214. * {
  4215. text-align: left !important;
  4216. max-width: 100%;
  4217. word-wrap: break-word;
  4218. }
  4219. }
  4220. // 分隔线
  4221. .divider {
  4222. height: 1px;
  4223. background: #e5e7eb;
  4224. margin: 12px 0;
  4225. }
  4226. // 进度条内联样式(在白色卡片内)
  4227. .progress-capsule-inline {
  4228. display: flex;
  4229. align-items: center;
  4230. gap: 10px;
  4231. background: rgba(91, 141, 239, 0.08);
  4232. border: 1px solid rgba(91, 141, 239, 0.2);
  4233. padding: 6px 12px;
  4234. border-radius: 20px;
  4235. width: 100%;
  4236. max-width: 100%;
  4237. }
  4238. .progress-bar-mini {
  4239. position: relative;
  4240. flex: 1;
  4241. min-width: 60px;
  4242. height: 6px;
  4243. background: rgba(91, 141, 239, 0.15);
  4244. border-radius: 3px;
  4245. overflow: visible;
  4246. }
  4247. .progress-fill {
  4248. height: 100%;
  4249. background: linear-gradient(90deg, #5b8def 0%, #4a7ad8 100%);
  4250. border-radius: 3px;
  4251. transition: width 0.6s ease;
  4252. box-shadow: 0 0 8px rgba(91, 141, 239, 0.3);
  4253. }
  4254. .progress-dot {
  4255. position: absolute;
  4256. top: 50%;
  4257. transform: translate(-50%, -50%);
  4258. width: 12px;
  4259. height: 12px;
  4260. background: white;
  4261. border: 2px solid #5b8def;
  4262. border-radius: 50%;
  4263. box-shadow: 0 2px 6px rgba(91, 141, 239, 0.4);
  4264. transition: left 0.6s ease;
  4265. z-index: 1;
  4266. }
  4267. .progress-percentage {
  4268. font-weight: 600;
  4269. min-width: 35px;
  4270. text-align: right;
  4271. color: #5b8def;
  4272. font-size: 12px;
  4273. }
  4274. .report-loading {
  4275. display: flex;
  4276. flex-direction: row;
  4277. align-items: center;
  4278. justify-content: flex-start;
  4279. gap: 12px;
  4280. padding: 12px 0;
  4281. margin-top: 12px;
  4282. margin-bottom: 8px;
  4283. .loading-text {
  4284. color: #6B7280;
  4285. font-size: 14px;
  4286. font-weight: 500;
  4287. }
  4288. .thinking-animation {
  4289. display: flex;
  4290. gap: 4px;
  4291. .dot {
  4292. width: 6px;
  4293. height: 6px;
  4294. background: #9CA3AF;
  4295. border-radius: 50%;
  4296. animation: thinking 1.4s infinite ease-in-out;
  4297. &:nth-child(1) { animation-delay: -0.32s; }
  4298. &:nth-child(2) { animation-delay: -0.16s; }
  4299. &:nth-child(3) { animation-delay: 0s; }
  4300. }
  4301. }
  4302. }
  4303. .message-content {
  4304. background: white;
  4305. color: #374151;
  4306. padding: 12px 6px;
  4307. border-radius: 0px 18px 18px 18px;
  4308. max-width: calc(100vw - 120px);
  4309. width: fit-content;
  4310. min-width: 120px;
  4311. word-wrap: break-word;
  4312. line-height: 1.5;
  4313. font-size: 14px;
  4314. box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  4315. white-space: normal;
  4316. overflow-wrap: break-word;
  4317. word-break: break-word;
  4318. text-align: left;
  4319. .ai-text {
  4320. min-height: 20px;
  4321. line-height: 1.5;
  4322. .typing-indicator {
  4323. color: #9CA3AF;
  4324. font-style: italic;
  4325. font-size: 14px;
  4326. display: flex;
  4327. align-items: center;
  4328. gap: 8px;
  4329. white-space: normal;
  4330. word-wrap: break-word;
  4331. overflow-wrap: break-word;
  4332. .thinking-animation {
  4333. .dot {
  4334. display: inline-block;
  4335. width: 4px;
  4336. height: 4px;
  4337. border-radius: 50%;
  4338. background: #9CA3AF;
  4339. margin: 0 1px;
  4340. animation: thinking 1.4s infinite ease-in-out;
  4341. &:nth-child(1) { animation-delay: -0.32s; }
  4342. &:nth-child(2) { animation-delay: -0.16s; }
  4343. }
  4344. }
  4345. }
  4346. }
  4347. .divider {
  4348. width: 100%;
  4349. height: 1px;
  4350. background: #E5E7EB;
  4351. margin: 8px 0;
  4352. }
  4353. .message-actions {
  4354. display: flex;
  4355. justify-content: space-between;
  4356. align-items: center;
  4357. margin-top: 8px;
  4358. .left-actions {
  4359. display: flex;
  4360. gap: 8px;
  4361. flex-wrap: wrap;
  4362. }
  4363. .right-actions {
  4364. display: flex;
  4365. gap: 4px;
  4366. }
  4367. .action-btn {
  4368. background: transparent;
  4369. border: none;
  4370. color: #6B7280;
  4371. padding: 6px;
  4372. border-radius: 4px;
  4373. cursor: pointer;
  4374. display: flex;
  4375. align-items: center;
  4376. justify-content: center;
  4377. transition: all 0.3s ease;
  4378. &:disabled {
  4379. opacity: 0.5;
  4380. cursor: not-allowed;
  4381. }
  4382. .action-icon {
  4383. width: 20px;
  4384. height: 20px;
  4385. object-fit: contain;
  4386. }
  4387. &.thumbs-up-btn {
  4388. transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  4389. &.active {
  4390. .action-icon {
  4391. filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(142deg) brightness(104%) contrast(97%);
  4392. }
  4393. }
  4394. }
  4395. &.thumbs-down-btn {
  4396. transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  4397. &.active {
  4398. .action-icon {
  4399. filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(0deg) brightness(104%) contrast(97%);
  4400. }
  4401. }
  4402. }
  4403. }
  4404. }
  4405. }
  4406. }
  4407. /* 底部输入区域 */
  4408. .chat-input-section {
  4409. position: fixed;
  4410. bottom: 20px; // 减少底部距离
  4411. left: 0;
  4412. right: 0;
  4413. background: #EBF3FF;
  4414. padding: 8px 20px; // 减少内边距
  4415. z-index: 1;
  4416. transform: translateZ(0); // 启用硬件加速
  4417. -webkit-transform: translateZ(0); // Safari兼容
  4418. will-change: transform; // 提示浏览器优化
  4419. .input-container {
  4420. max-width: 100%;
  4421. .input-box {
  4422. display: flex;
  4423. align-items: center;
  4424. gap: 4px; // 减少间距
  4425. background: white;
  4426. border-radius: 16px;
  4427. padding: 8px 12px; // 减少左右padding
  4428. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  4429. transition: box-shadow 0.3s ease;
  4430. border: 1px solid #3E7BFA;
  4431. height: 57px; // 恢复原来的高度
  4432. transform: translateZ(0); // 启用硬件加速
  4433. -webkit-transform: translateZ(0); // Safari兼容
  4434. will-change: transform; // 提示浏览器优化
  4435. &:focus-within {
  4436. box-shadow: 0 2px 12px rgba(62, 123, 250, 0.2);
  4437. }
  4438. .message-input {
  4439. flex: 1;
  4440. border: none;
  4441. background: transparent;
  4442. font-size: 16px !important; // 强制字体大小
  4443. color: #2C3E50;
  4444. outline: none;
  4445. transition: opacity 0.3s ease;
  4446. line-height: 1.4 !important; // 强制行高
  4447. height: auto !important; // 自动高度
  4448. &::placeholder {
  4449. color: #A0A6B8;
  4450. font-size: 16px !important;
  4451. }
  4452. &:disabled {
  4453. cursor: not-allowed;
  4454. }
  4455. }
  4456. .divider {
  4457. width: 1px;
  4458. height: 31px;
  4459. background-color: #D6D5DE;
  4460. margin: 0 2px; // 减少margin
  4461. }
  4462. .voice-btn, .network-search-btn {
  4463. background: none;
  4464. border: none;
  4465. cursor: pointer;
  4466. padding: 6px; // 减少padding
  4467. border-radius: 6px;
  4468. transition: all 0.3s ease;
  4469. display: flex;
  4470. align-items: center;
  4471. justify-content: center;
  4472. position: relative;
  4473. &:hover:not(:disabled) {
  4474. background: rgba(102, 126, 234, 0.1);
  4475. }
  4476. &:disabled {
  4477. cursor: not-allowed;
  4478. opacity: 0.5;
  4479. }
  4480. .icon-container {
  4481. width: 20px;
  4482. height: 20px;
  4483. display: flex;
  4484. align-items: center;
  4485. justify-content: center;
  4486. position: relative;
  4487. .action-icon {
  4488. width: 20px;
  4489. height: 20px;
  4490. object-fit: contain;
  4491. }
  4492. }
  4493. }
  4494. .voice-btn {
  4495. &.recording {
  4496. background: rgba(239, 68, 68, 0.1);
  4497. animation: pulse 1.5s ease-in-out infinite;
  4498. }
  4499. &.speaking {
  4500. color: #dc2626;
  4501. background: rgba(239, 68, 68, 0.08);
  4502. .action-icon {
  4503. filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(0deg) brightness(104%) contrast(97%);
  4504. }
  4505. }
  4506. .icon-container {
  4507. .recording-indicator {
  4508. position: absolute;
  4509. top: -2px;
  4510. right: -2px;
  4511. width: 8px;
  4512. height: 8px;
  4513. background: #ef4444;
  4514. border-radius: 50%;
  4515. animation: blink 1s ease-in-out infinite;
  4516. }
  4517. }
  4518. }
  4519. .network-search-btn {
  4520. &.active {
  4521. background: rgba(62, 123, 250, 0.1);
  4522. .action-icon {
  4523. color: #3E7BFA;
  4524. }
  4525. }
  4526. }
  4527. .send-btn {
  4528. background: none;
  4529. border: none;
  4530. cursor: pointer;
  4531. border-radius: 6px;
  4532. transition: background 0.3s ease;
  4533. display: flex;
  4534. align-items: center;
  4535. justify-content: center;
  4536. padding: 4px; // 添加少量padding
  4537. &:hover:not(:disabled) {
  4538. background: rgba(102, 126, 234, 0.1);
  4539. }
  4540. &:disabled {
  4541. cursor: not-allowed;
  4542. }
  4543. .send-icon {
  4544. width: 80px; // 减少宽度
  4545. height: 36px; // 减少高度
  4546. object-fit: contain;
  4547. }
  4548. }
  4549. }
  4550. }
  4551. }
  4552. /* 思考动画 */
  4553. @keyframes thinking {
  4554. 0%, 80%, 100% {
  4555. transform: scale(0);
  4556. }
  4557. 40% {
  4558. transform: scale(1);
  4559. }
  4560. }
  4561. /* 语音输入动画 */
  4562. @keyframes pulse {
  4563. 0% {
  4564. transform: scale(1);
  4565. }
  4566. 50% {
  4567. transform: scale(1.05);
  4568. }
  4569. 100% {
  4570. transform: scale(1);
  4571. }
  4572. }
  4573. @keyframes blink {
  4574. 0%, 50% {
  4575. opacity: 1;
  4576. }
  4577. 51%, 100% {
  4578. opacity: 0.3;
  4579. }
  4580. }
  4581. /* 联网搜索Loading样式 */
  4582. .online-search-loading {
  4583. display: flex;
  4584. align-items: center;
  4585. justify-content: flex-start; // 左对齐
  4586. padding: 12px;
  4587. margin-left: 44px; /* 与AI头像对齐 */
  4588. width: fit-content;
  4589. }
  4590. .online-search-loading .thinking-animation {
  4591. display: flex;
  4592. gap: 4px;
  4593. }
  4594. .online-search-loading .thinking-animation .dot {
  4595. width: 6px;
  4596. height: 6px;
  4597. background: #9CA3AF;
  4598. border-radius: 50%;
  4599. animation: thinking 1.4s infinite ease-in-out;
  4600. }
  4601. .online-search-loading .thinking-animation .dot:nth-child(1) {
  4602. animation-delay: -0.32s;
  4603. }
  4604. .online-search-loading .thinking-animation .dot:nth-child(2) {
  4605. animation-delay: -0.16s;
  4606. }
  4607. .online-search-loading .thinking-animation .dot:nth-child(3) {
  4608. animation-delay: 0s;
  4609. }
  4610. /* 联网搜索结果样式 */
  4611. .online-search-results {
  4612. margin: 8px 0 12px 0;
  4613. margin-top: 10px;
  4614. background: white;
  4615. border-radius: 12px;
  4616. box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  4617. margin-left: 44px; /* 与AI头像对齐 */
  4618. overflow-x: auto; /* 支持横向滑动 */
  4619. overflow-y: hidden; /* 禁用纵向滚动 */
  4620. width: fit-content;
  4621. max-width: calc(100vw - 120px);
  4622. max-height: 200px; /* 限制最大高度 */
  4623. .online-search-header {
  4624. display: flex;
  4625. align-items: center;
  4626. justify-content: center;
  4627. padding: 12px;
  4628. cursor: pointer;
  4629. transition: background-color 0.2s ease;
  4630. font-size: 14px;
  4631. color: #37415180;
  4632. &:hover {
  4633. background-color: #f9fafb;
  4634. }
  4635. .expand-icon {
  4636. margin-left: 8px;
  4637. transition: transform 0.2s ease;
  4638. color: #6b7280;
  4639. &.expanded {
  4640. transform: rotate(180deg);
  4641. }
  4642. }
  4643. }
  4644. .online-search-content {
  4645. border-top: 1px solid #e5e7eb;
  4646. max-height: 150px; /* 限制内容区域高度 */
  4647. overflow-y: auto; /* 内容过多时纵向滚动 */
  4648. .search-results-section {
  4649. padding: 12px;
  4650. display: flex;
  4651. flex-direction: column;
  4652. gap: 8px;
  4653. .section-title {
  4654. font-size: 14px;
  4655. font-weight: 600;
  4656. color: #374151;
  4657. margin-bottom: 8px;
  4658. display: block;
  4659. }
  4660. .search-results-container {
  4661. display: flex;
  4662. gap: 8px;
  4663. overflow-x: auto;
  4664. overflow-y: hidden;
  4665. padding-bottom: 4px;
  4666. /* 自定义滚动条样式 */
  4667. &::-webkit-scrollbar {
  4668. height: 4px;
  4669. }
  4670. &::-webkit-scrollbar-track {
  4671. background: #f1f1f1;
  4672. border-radius: 2px;
  4673. }
  4674. &::-webkit-scrollbar-thumb {
  4675. background: #c1c1c1;
  4676. border-radius: 2px;
  4677. }
  4678. &::-webkit-scrollbar-thumb:hover {
  4679. background: #a8a8a8;
  4680. }
  4681. }
  4682. .search-result-card {
  4683. background: #f9fafb;
  4684. border-radius: 8px;
  4685. padding: 12px;
  4686. cursor: pointer;
  4687. transition: all 0.2s ease;
  4688. border: 1px solid #e5e7eb;
  4689. width: 200px; /* 设置最小宽度 */
  4690. flex-shrink: 0; /* 防止卡片收缩 */
  4691. text-align: left;
  4692. &:hover {
  4693. background: #f3f4f6;
  4694. border-color: #d1d5db;
  4695. }
  4696. &:last-child {
  4697. margin-bottom: 0;
  4698. }
  4699. .result-title {
  4700. font-size: 14px;
  4701. font-weight: 600;
  4702. color: #1f2937;
  4703. margin-bottom: 6px;
  4704. line-height: 1.4;
  4705. display: -webkit-box;
  4706. -webkit-line-clamp: 2;
  4707. line-clamp: 2;
  4708. -webkit-box-orient: vertical;
  4709. overflow: hidden;
  4710. }
  4711. .result-snippet {
  4712. font-size: 13px;
  4713. color: #6b7280;
  4714. line-height: 1.4;
  4715. // margin-bottom: 6px;
  4716. display: -webkit-box;
  4717. -webkit-line-clamp: 2;
  4718. line-clamp: 3;
  4719. -webkit-box-orient: vertical;
  4720. overflow: hidden;
  4721. }
  4722. .result-url {
  4723. font-size: 12px;
  4724. color: #9ca3af;
  4725. line-height: 1.3;
  4726. word-break: break-all;
  4727. }
  4728. }
  4729. }
  4730. }
  4731. }
  4732. /* 推荐问题Loading样式 */
  4733. .related-questions-loading {
  4734. display: flex;
  4735. align-items: center;
  4736. justify-content: flex-start; // 左对齐
  4737. padding: 12px;
  4738. margin-left: 62px; /* 与AI消息白色气泡对齐 (52px头像 + 10px gap) */
  4739. width: fit-content;
  4740. }
  4741. .related-questions-loading .thinking-animation {
  4742. display: flex;
  4743. gap: 4px;
  4744. }
  4745. .related-questions-loading .thinking-animation .dot {
  4746. width: 6px;
  4747. height: 6px;
  4748. background: #9CA3AF;
  4749. border-radius: 50%;
  4750. animation: thinking 1.4s infinite ease-in-out;
  4751. }
  4752. .related-questions-loading .thinking-animation .dot:nth-child(1) {
  4753. animation-delay: -0.32s;
  4754. }
  4755. .related-questions-loading .thinking-animation .dot:nth-child(2) {
  4756. animation-delay: -0.16s;
  4757. }
  4758. .related-questions-loading .thinking-animation .dot:nth-child(3) {
  4759. animation-delay: 0s;
  4760. }
  4761. /* 推荐问题样式 */
  4762. .related-questions {
  4763. margin: 0px 0 12px 0;
  4764. // margin-top: 0px;
  4765. margin-left: 62px; /* 与AI消息白色气泡对齐 (52px头像 + 10px gap) */
  4766. width: fit-content;
  4767. max-width: calc(100vw - 120px);
  4768. .related-question-item {
  4769. background: rgba(0,0,0,.05); /* 与PC端一致的背景色 */
  4770. border-radius: 12px;
  4771. padding: 12px 16px;
  4772. margin-bottom: 8px;
  4773. cursor: pointer;
  4774. transition: all 0.2s ease;
  4775. border: 1px solid #e9ecef; /* 与PC端一致的边框色 */
  4776. box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  4777. display: flex;
  4778. align-items: center;
  4779. justify-content: space-between;
  4780. &:hover {
  4781. background: #e9ecef; /* 与PC端一致的悬停背景色 */
  4782. border-color: #dee2e6; /* 与PC端一致的悬停边框色 */
  4783. transform: translateY(-1px);
  4784. box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  4785. }
  4786. &:last-child {
  4787. margin-bottom: 0;
  4788. }
  4789. span {
  4790. font-size: 14px;
  4791. color: #374151;
  4792. line-height: 1.4;
  4793. flex: 1;
  4794. margin-right: 8px;
  4795. text-align: left; /* 确保文字居左对齐 */
  4796. }
  4797. .arrow-icon {
  4798. width: 16px;
  4799. height: 16px;
  4800. color: #9ca3af;
  4801. flex-shrink: 0;
  4802. transition: transform 0.2s ease;
  4803. }
  4804. &:hover .arrow-icon {
  4805. transform: translateX(2px);
  4806. color: #6b7280;
  4807. }
  4808. }
  4809. }
  4810. /* 规范引用样式 */
  4811. :deep(.standard-reference) {
  4812. background-color: #EAEAEE !important;
  4813. color: #616161 !important;
  4814. font-size: 0.75rem !important;
  4815. padding: 3px 8px !important;
  4816. border-radius: 6px !important;
  4817. cursor: pointer !important;
  4818. display: inline-block !important;
  4819. margin: 4px 2px !important;
  4820. border: 1px solid #EAEAEE !important;
  4821. font-weight: 500 !important;
  4822. transition: all 0.2s ease !important;
  4823. line-height: 1.4 !important;
  4824. }
  4825. :deep(.standard-reference:hover) {
  4826. background-color: #d1d5db !important;
  4827. border-color: #d1d5db !important;
  4828. }
  4829. /* 进度统计卡片样式 - 移动端适配 */
  4830. .stats-card {
  4831. background: white;
  4832. border-radius: 8px;
  4833. padding: 12px 16px;
  4834. margin-bottom: 16px;
  4835. display: flex;
  4836. flex-direction: column;
  4837. gap: 8px;
  4838. border: 1px solid #e8ecf1;
  4839. transition: all 0.3s ease, box-shadow 0.3s ease;
  4840. &.is-sticky {
  4841. /* position, top, left, width, zIndex 由 inline style 动态设置 */
  4842. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  4843. border-bottom: 2px solid #5b8def;
  4844. animation: slideDown 0.3s ease;
  4845. }
  4846. @keyframes slideDown {
  4847. from {
  4848. transform: translateY(-10px);
  4849. opacity: 0;
  4850. }
  4851. to {
  4852. transform: translateY(0);
  4853. opacity: 1;
  4854. }
  4855. }
  4856. .stats-left {
  4857. display: flex;
  4858. align-items: center;
  4859. gap: 8px;
  4860. flex: 1;
  4861. min-width: 0;
  4862. .stats-avatar {
  4863. flex-shrink: 0;
  4864. }
  4865. .status-text {
  4866. font-size: 13px;
  4867. line-height: 1.4;
  4868. color: #374151;
  4869. flex: 1;
  4870. min-width: 0;
  4871. :deep(.ai-name) {
  4872. font-weight: 600;
  4873. color: #1f2937;
  4874. }
  4875. :deep(.file-count) {
  4876. font-weight: 600;
  4877. color: #3e7bfa;
  4878. }
  4879. }
  4880. }
  4881. .progress-capsule-inline {
  4882. display: flex;
  4883. align-items: center;
  4884. gap: 8px;
  4885. .progress-bar-mini {
  4886. flex: 1;
  4887. height: 4px;
  4888. background: #e5e7eb;
  4889. border-radius: 2px;
  4890. position: relative;
  4891. overflow: hidden;
  4892. .progress-fill {
  4893. height: 100%;
  4894. background: linear-gradient(90deg, #3e7bfa 0%, #5b8eff 100%);
  4895. border-radius: 2px;
  4896. transition: width 0.3s ease;
  4897. }
  4898. .progress-dot {
  4899. position: absolute;
  4900. top: 50%;
  4901. transform: translate(-50%, -50%);
  4902. width: 8px;
  4903. height: 8px;
  4904. background: #3e7bfa;
  4905. border-radius: 50%;
  4906. box-shadow: 0 0 0 2px rgba(62, 123, 250, 0.2);
  4907. transition: left 0.3s ease;
  4908. }
  4909. }
  4910. .progress-percentage {
  4911. font-size: 12px;
  4912. font-weight: 600;
  4913. color: #3e7bfa;
  4914. min-width: 40px;
  4915. text-align: right;
  4916. }
  4917. }
  4918. .stats-right {
  4919. display: flex;
  4920. justify-content: flex-end;
  4921. }
  4922. }
  4923. /* 问题总结样式 - 移动端适配 */
  4924. .question-summary {
  4925. background: #f9fafb;
  4926. // border-left: 3px solid #3e7bfa;
  4927. padding: 12px;
  4928. margin-bottom: 12px;
  4929. border-radius: 8px;
  4930. font-size: 14px;
  4931. line-height: 1.6;
  4932. color: #374151;
  4933. }
  4934. /* 报告Loading动画 - 移动端适配 */
  4935. .report-loading {
  4936. display: flex;
  4937. flex-direction: column;
  4938. align-items: center;
  4939. justify-content: center;
  4940. padding: 20px;
  4941. gap: 12px;
  4942. .loading-text {
  4943. font-size: 14px;
  4944. color: #6b7280;
  4945. }
  4946. .thinking-animation {
  4947. display: flex;
  4948. gap: 6px;
  4949. .dot {
  4950. width: 8px;
  4951. height: 8px;
  4952. border-radius: 50%;
  4953. background: #3e7bfa;
  4954. animation: thinking 1.4s infinite ease-in-out;
  4955. &:nth-child(1) { animation-delay: -0.32s; }
  4956. &:nth-child(2) { animation-delay: -0.16s; }
  4957. &:nth-child(3) { animation-delay: 0s; }
  4958. }
  4959. }
  4960. }
  4961. /* 报告列表样式 - 移动端适配 */
  4962. .reports-list {
  4963. margin-bottom: 12px;
  4964. }
  4965. /* AI markdown内容样式 */
  4966. .ai-markdown-content {
  4967. font-size: 14px;
  4968. line-height: 1.6;
  4969. color: #374151;
  4970. }
  4971. /* 网络搜索弹窗样式 */
  4972. .web-search-modal-overlay {
  4973. position: fixed;
  4974. top: 0;
  4975. left: 0;
  4976. right: 0;
  4977. bottom: 0;
  4978. background: rgba(0, 0, 0, 0.5);
  4979. display: flex;
  4980. align-items: center;
  4981. justify-content: center;
  4982. z-index: 9999;
  4983. padding: 20px;
  4984. }
  4985. .web-search-modal {
  4986. background: white;
  4987. border-radius: 12px;
  4988. width: 100%;
  4989. max-width: 500px;
  4990. max-height: 80vh;
  4991. display: flex;
  4992. flex-direction: column;
  4993. box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  4994. }
  4995. .web-search-modal-header {
  4996. display: flex;
  4997. justify-content: space-between;
  4998. align-items: center;
  4999. padding: 16px 20px;
  5000. border-bottom: 1px solid #e5e7eb;
  5001. h3 {
  5002. margin: 0;
  5003. font-size: 18px;
  5004. font-weight: 600;
  5005. color: #1f2937;
  5006. }
  5007. .close-btn {
  5008. background: none;
  5009. border: none;
  5010. font-size: 24px;
  5011. color: #6b7280;
  5012. cursor: pointer;
  5013. padding: 0;
  5014. width: 32px;
  5015. height: 32px;
  5016. display: flex;
  5017. align-items: center;
  5018. justify-content: center;
  5019. border-radius: 50%;
  5020. transition: all 0.2s;
  5021. &:active {
  5022. background: #f3f4f6;
  5023. color: #1f2937;
  5024. }
  5025. }
  5026. }
  5027. .web-search-modal-content {
  5028. flex: 1;
  5029. overflow-y: auto;
  5030. padding: 20px;
  5031. }
  5032. .search-results {
  5033. .search-count {
  5034. font-size: 14px;
  5035. color: #6b7280;
  5036. margin-bottom: 16px;
  5037. padding-bottom: 12px;
  5038. border-bottom: 1px solid #e5e7eb;
  5039. }
  5040. .search-result-item {
  5041. padding: 16px;
  5042. margin-bottom: 12px;
  5043. background: #f8f9fa;
  5044. border-radius: 8px;
  5045. border: 1px solid #e4e7ed;
  5046. cursor: pointer;
  5047. transition: all 0.2s;
  5048. &:active {
  5049. background: white;
  5050. border-color: #5b8def;
  5051. transform: scale(0.98);
  5052. }
  5053. .result-header {
  5054. display: flex;
  5055. align-items: flex-start;
  5056. gap: 12px;
  5057. margin-bottom: 8px;
  5058. }
  5059. .result-index {
  5060. flex-shrink: 0;
  5061. width: 24px;
  5062. height: 24px;
  5063. border-radius: 50%;
  5064. background: linear-gradient(135deg, #5b8def 0%, #0063f7 100%);
  5065. color: white;
  5066. display: flex;
  5067. align-items: center;
  5068. justify-content: center;
  5069. font-size: 12px;
  5070. font-weight: 600;
  5071. }
  5072. .result-title {
  5073. flex: 1;
  5074. font-size: 15px;
  5075. font-weight: 600;
  5076. color: #303133;
  5077. line-height: 1.5;
  5078. overflow: hidden;
  5079. text-overflow: ellipsis;
  5080. display: -webkit-box;
  5081. -webkit-line-clamp: 2;
  5082. line-clamp: 2;
  5083. -webkit-box-orient: vertical;
  5084. }
  5085. .result-content {
  5086. font-size: 13px;
  5087. color: #606266;
  5088. line-height: 1.6;
  5089. margin-bottom: 12px;
  5090. overflow: hidden;
  5091. text-overflow: ellipsis;
  5092. display: -webkit-box;
  5093. -webkit-line-clamp: 3;
  5094. line-clamp: 3;
  5095. -webkit-box-orient: vertical;
  5096. }
  5097. .result-footer {
  5098. display: flex;
  5099. align-items: center;
  5100. gap: 8px;
  5101. font-size: 12px;
  5102. color: #909399;
  5103. }
  5104. .result-url {
  5105. flex: 1;
  5106. overflow: hidden;
  5107. text-overflow: ellipsis;
  5108. white-space: nowrap;
  5109. }
  5110. .result-score {
  5111. flex-shrink: 0;
  5112. padding: 2px 8px;
  5113. background: #f0f2f5;
  5114. border-radius: 4px;
  5115. font-weight: 500;
  5116. color: #606266;
  5117. }
  5118. }
  5119. }
  5120. /* 网页预览弹窗样式 */
  5121. .web-preview-overlay {
  5122. position: fixed;
  5123. top: 0;
  5124. left: 0;
  5125. right: 0;
  5126. bottom: 0;
  5127. background: rgba(0, 0, 0, 0.7);
  5128. display: flex;
  5129. align-items: center;
  5130. justify-content: center;
  5131. z-index: 10000;
  5132. padding: 10px;
  5133. }
  5134. .web-preview-modal {
  5135. background: white;
  5136. border-radius: 12px;
  5137. width: 100%;
  5138. height: 90vh;
  5139. display: flex;
  5140. flex-direction: column;
  5141. box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  5142. }
  5143. .web-preview-header {
  5144. display: flex;
  5145. justify-content: space-between;
  5146. align-items: center;
  5147. padding: 16px 20px;
  5148. border-bottom: 1px solid #e5e7eb;
  5149. h3 {
  5150. margin: 0;
  5151. font-size: 16px;
  5152. font-weight: 600;
  5153. color: #1f2937;
  5154. overflow: hidden;
  5155. text-overflow: ellipsis;
  5156. white-space: nowrap;
  5157. flex: 1;
  5158. margin-right: 12px;
  5159. }
  5160. .close-btn {
  5161. background: none;
  5162. border: none;
  5163. font-size: 24px;
  5164. color: #6b7280;
  5165. cursor: pointer;
  5166. padding: 0;
  5167. width: 32px;
  5168. height: 32px;
  5169. display: flex;
  5170. align-items: center;
  5171. justify-content: center;
  5172. border-radius: 50%;
  5173. transition: all 0.2s;
  5174. flex-shrink: 0;
  5175. &:active {
  5176. background: #f3f4f6;
  5177. color: #1f2937;
  5178. }
  5179. }
  5180. }
  5181. .web-preview-content {
  5182. flex: 1;
  5183. overflow: hidden;
  5184. .preview-iframe {
  5185. width: 100%;
  5186. height: 100%;
  5187. border: none;
  5188. }
  5189. .iframe-error {
  5190. width: 100%;
  5191. height: 100%;
  5192. display: flex;
  5193. flex-direction: column;
  5194. align-items: center;
  5195. justify-content: center;
  5196. background: #f5f7fa;
  5197. p {
  5198. font-size: 16px;
  5199. color: #606266;
  5200. margin-bottom: 20px;
  5201. }
  5202. .open-link-btn {
  5203. padding: 10px 24px;
  5204. background: #3e7bfa;
  5205. color: white;
  5206. border: none;
  5207. border-radius: 6px;
  5208. font-size: 14px;
  5209. cursor: pointer;
  5210. &:active {
  5211. background: #2563eb;
  5212. }
  5213. }
  5214. }
  5215. }
  5216. /* 文件预览弹窗样式 */
  5217. .file-preview-overlay {
  5218. position: fixed;
  5219. top: 0;
  5220. left: 0;
  5221. right: 0;
  5222. bottom: 0;
  5223. background: rgba(0, 0, 0, 0.7);
  5224. display: flex;
  5225. align-items: center;
  5226. justify-content: center;
  5227. z-index: 10000;
  5228. padding: 10px;
  5229. }
  5230. .file-preview-modal {
  5231. background: white;
  5232. border-radius: 12px;
  5233. width: 100%;
  5234. height: 90vh;
  5235. display: flex;
  5236. flex-direction: column;
  5237. box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  5238. animation: slideUp 0.3s ease;
  5239. }
  5240. .file-preview-header {
  5241. display: flex;
  5242. justify-content: space-between;
  5243. align-items: center;
  5244. padding: 16px 20px;
  5245. border-bottom: 1px solid #e5e7eb;
  5246. .header-left {
  5247. display: flex;
  5248. align-items: center;
  5249. gap: 12px;
  5250. flex: 1;
  5251. min-width: 0;
  5252. }
  5253. .file-icon {
  5254. width: 24px;
  5255. height: 24px;
  5256. color: #5b8def;
  5257. flex-shrink: 0;
  5258. }
  5259. .header-text {
  5260. display: flex;
  5261. flex-direction: column;
  5262. gap: 4px;
  5263. min-width: 0;
  5264. flex: 1;
  5265. h3 {
  5266. margin: 0;
  5267. font-size: 16px;
  5268. font-weight: 600;
  5269. color: #1f2937;
  5270. }
  5271. .file-name {
  5272. font-size: 12px;
  5273. color: #6b7280;
  5274. background: #f3f4f6;
  5275. padding: 4px 10px;
  5276. border-radius: 10px;
  5277. overflow: hidden;
  5278. text-overflow: ellipsis;
  5279. white-space: nowrap;
  5280. max-width: 250px;
  5281. }
  5282. }
  5283. .close-btn {
  5284. background: none;
  5285. border: none;
  5286. font-size: 24px;
  5287. color: #6b7280;
  5288. cursor: pointer;
  5289. padding: 0;
  5290. width: 32px;
  5291. height: 32px;
  5292. display: flex;
  5293. align-items: center;
  5294. justify-content: center;
  5295. border-radius: 50%;
  5296. transition: all 0.2s;
  5297. flex-shrink: 0;
  5298. &:active {
  5299. background: #f3f4f6;
  5300. color: #1f2937;
  5301. }
  5302. }
  5303. }
  5304. .file-preview-content {
  5305. flex: 1;
  5306. overflow: hidden;
  5307. position: relative;
  5308. display: flex;
  5309. align-items: center;
  5310. justify-content: center;
  5311. .file-iframe {
  5312. width: 100%;
  5313. height: 100%;
  5314. border: none;
  5315. }
  5316. .file-loading {
  5317. display: flex;
  5318. flex-direction: column;
  5319. align-items: center;
  5320. justify-content: center;
  5321. gap: 16px;
  5322. .loading-spinner {
  5323. width: 40px;
  5324. height: 40px;
  5325. border: 3px solid #f3f3f3;
  5326. border-top: 3px solid #5b8def;
  5327. border-radius: 50%;
  5328. animation: spin 1s linear infinite;
  5329. }
  5330. p {
  5331. color: #909399;
  5332. font-size: 14px;
  5333. margin: 0;
  5334. }
  5335. }
  5336. .file-error {
  5337. display: flex;
  5338. flex-direction: column;
  5339. align-items: center;
  5340. justify-content: center;
  5341. gap: 16px;
  5342. .error-icon {
  5343. width: 48px;
  5344. height: 48px;
  5345. color: #f56c6c;
  5346. }
  5347. p {
  5348. color: #f56c6c;
  5349. font-size: 14px;
  5350. margin: 0;
  5351. }
  5352. }
  5353. .file-empty {
  5354. display: flex;
  5355. flex-direction: column;
  5356. align-items: center;
  5357. justify-content: center;
  5358. gap: 16px;
  5359. .empty-icon {
  5360. width: 48px;
  5361. height: 48px;
  5362. color: #c0c4cc;
  5363. }
  5364. p {
  5365. color: #909399;
  5366. font-size: 14px;
  5367. margin: 0;
  5368. }
  5369. }
  5370. }
  5371. @keyframes spin {
  5372. 0% { transform: rotate(0deg); }
  5373. 100% { transform: rotate(360deg); }
  5374. }
  5375. </style>