m-Chat.vue 189 KB

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