m-Chat.vue 192 KB

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