| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598 |
- <template>
- <div class="chat-container">
- <!-- 最左侧边栏 -->
- <Sidebar />
- <!-- 中间历史记录区域 -->
- <div class="history-sidebar">
- <div class="history-header">
- <span class="section-title">历史记录</span>
- <img
- src="@/assets/Chat/2.png"
- alt="新建任务"
- class="new-chat-btn"
- :class="{ 'disabled': isPolishing }"
- @click="createNewChat"
- />
- </div>
- <div class="history-list">
- <!-- 历史记录加载状态 -->
- <div v-if="isLoadingHistory && historyTotal === 0" class="history-loading">
- <div class="loading-spinner"></div>
- <div class="loading-text">正在加载历史记录...</div>
- </div>
-
- <!-- 有历史记录时显示 -->
- <div
- v-else-if="historyTotal > 0"
- v-for="(item, index) in historyData"
- :key="item.id"
- :class="['history-item', { active: item.isActive }]"
- @click="item.isActive ? null : (isGenerating || isPolishing ? null : handleHistoryItem(item))"
- :style="{ cursor: item.isActive || isPolishing ? 'default' : 'pointer' }"
- >
- <div class="history-content">
- <div class="history-title">{{ item.title }}</div>
- <div class="history-time">{{ item.time }}</div>
- </div>
- <div
- class="delete-btn"
- @click.stop="deleteHistoryItem(item, index)"
- :class="{ 'always-visible': item.isActive }"
- >
- <img src="/src/assets/AIWriting/8.png" alt="删除" class="delete-icon" />
- </div>
- </div>
-
- <!-- 无历史记录时显示空状态 -->
- <div v-else class="empty-history">
- <img src="@/assets/Chat/22.png" alt="暂无数据" class="empty-icon">
- <div class="empty-text">暂无数据</div>
- </div>
- </div>
- </div>
- <!-- 右侧工作区域 -->
- <div class="main-work">
- <!-- 头部 -->
- <div class="work-header">
- <h2>AI写作</h2>
- </div>
- <!-- 工作内容区域 -->
- <div class="work-content">
- <!-- 主界面:AI写作工作区 -->
- <div v-if="currentView === 'main'" class="ai-writing-card">
- <!-- 文档生成区域 -->
- <div class="document-generation">
- <h3>帮我写作</h3>
- <p class="subtitle">智能生成办公文档,提升办公效能,高效创作</p>
- <div class="input-area">
- <div class="template-input-container"
- contenteditable="true"
- @input="handleTemplateInput"
- @copy="handleCopy"
- placeholder="请在这里输入您的写作要求..."></div>
- <div class="input-actions">
- <div class="left-actions">
- <button class="attachment-btn" @click="triggerFileUpload" :disabled="isSending">
- <img src="@/assets/AIWriting/4.png" alt="附件" class="action-icon" />
- </button>
- <!-- 文件预览区域 - 显示在输入框右边 -->
- <div v-if="selectedFile" class="file-preview-inline">
- <div class="file-info-inline">
- <img v-if="selectedFile.icon && typeof selectedFile.icon === 'string' && selectedFile.icon.includes('.png')" :src="selectedFile.icon" alt="文档图标" class="file-icon-inline-img">
- <span v-else class="file-icon-inline">{{ selectedFile.icon }}</span>
- <span class="file-name-inline">{{ selectedFile.name }}</span>
- <button class="remove-file-inline" @click="removeSelectedFile">
- <span class="remove-icon">×</span>
- </button>
- </div>
- </div>
- </div>
- <div class="right-actions">
- <button class="voice-btn" @click="handleVoiceClick" :disabled="isSending" :class="{ 'recording': isListening }">
- <div class="icon-container">
- <img src="@/assets/Chat/18.png" alt="语音" class="action-icon" />
- <div v-if="isListening" class="recording-indicator"></div>
- </div>
- </button>
- <div class="divider"></div>
- <button class="send-btn" @click="sendAIWritingRequest" :disabled="isGenerating || isSending">
- <img
- :src="hasInputContent ? sendIconFilled : sendIconEmpty"
- alt="发送"
- class="action-icon"
- />
- <span v-if="isGenerating" class="generating-text">生成中...</span>
- </button>
- </div>
- </div>
- </div>
- <p class="hint-text">提示:请输入关键字,AI将根据关键字生成文档</p>
- </div>
- <!-- 文档模板区域 -->
- <div class="document-templates">
- <div class="template-tabs">
- <div
- v-for="tab in tabs"
- :key="tab.key"
- :class="['tab-item', { active: activeTab === tab.key }]"
- @click="switchTab(tab.key)"
- >
- {{ tab.name }}
- </div>
- </div>
- <div class="template-cards">
- <div
- v-for="template in filteredTemplates"
- :key="template.id"
- class="template-card"
- >
- <img
- :src="template.image"
- :alt="template.name"
- class="template-image"
- />
- <button
- :class="['use-template-btn', template.buttonClass]"
- @click="useTemplate(template.name)"
- >
- 使用此模板
- </button>
- </div>
- </div>
- </div>
- </div>
- <!-- 步骤三:富文本编辑器 -->
- <div v-if="currentView === 'editor'" class="editor-view">
- <!-- 全屏Loading遮罩 -->
- <div v-if="isGenerating" class="editor-full-loading">
- <div class="loading-spinner"></div>
- <div class="loading-text">正在生成文档,请稍候...</div>
- </div>
-
- <!-- 历史记录切换Loading遮罩 -->
- <div v-if="isLoadingHistoryItem" class="editor-full-loading">
- <div class="loading-spinner"></div>
- <div class="loading-text">正在加载历史记录,请稍候...</div>
- </div>
-
- <div class="editor-header">
- <div class="editor-title">
- <h3>文档编辑</h3>
- <p class="editor-subtitle" v-if="!isGenerating">AI已为您生成内容,您可以直接编辑和完善</p>
- <p class="editor-subtitle" v-else>AI正在生成内容,请稍候...</p>
- </div>
- <div class="editor-actions">
- <!-- <button class="back-btn" @click="backToMain">
- <img src="@/assets/Chat/2.png" alt="返回" class="action-icon" />
- 返回
- </button> -->
- <button class="save-btn" @click="saveDocument" :disabled="isPolishing">
- <!-- <img src="@/assets/Chat/16.png" alt="保存" class="action-icon" /> -->
- 保存文档
- </button>
- <button class="download-btn" @click="downloadDocument" :disabled="isPolishing">
- <img src="@/assets/Exam/13.png" alt="下载Word" class="download-icon" />
- </button>
- </div>
- </div>
-
- <div class="editor-content">
-
- <div class="rich-editor-container" :class="{ 'polishing': isPolishing }">
- <!-- 编辑器 -->
- <div>
- <Toolbar
- class="rich-editor-toolbar"
- :editor="editorRef"
- :defaultConfig="toolbarConfig"
- :mode="mode"
- />
- <Editor
- style="height: calc(100vh - 280px); overflow-y: auto;"
- v-model="editorContent"
- :defaultConfig="editorConfig"
- :mode="mode"
- @onCreated="handleCreated"
- @onChange="handleChange"
- />
- </div>
- </div>
- </div>
-
-
- <!-- AI扩写输入框 -->
- <div
- v-if="showPolishInput && selectedText.trim()"
- class="ai-polish-input"
- :style="{
- left: polishInputPosition.x + 'px',
- top: polishInputPosition.y + 'px'
- }"
- @click.stop
- >
- <div class="polish-input-container">
- <div class="input-wrapper">
- <input
- type="text"
- v-model="polishCustomPrompt"
- placeholder="请输入要求(可选)"
- class="polish-input-field"
- :disabled="isPolishing"
- @keyup.enter="handlePolishText"
- @click.stop="handlePolishInputClick"
- @focus="handlePolishInputFocus"
- @blur="handlePolishInputBlur"
- maxlength="200"
- />
- <div class="char-counter">{{ polishCustomPrompt.length }}/200</div>
- </div>
- <div class="button-group">
- <button
- class="polish-send-btn"
- @click.stop="handlePolishText"
- :disabled="isPolishing"
- >
- {{ isPolishing && polishingType === 'polish' ? '正在扩写' : 'AI扩写' }}
- </button>
- <button
- class="polish-send-btn continue-btn"
- @click.stop="handleContinueText"
- :disabled="isPolishing"
- >
- {{ isPolishing && polishingType === 'continue' ? '正在续写' : 'AI续写' }}
- </button>
- </div>
- </div>
- </div>
- </div>
- <!-- 详情页:聊天对话和文档内容 -->
- <div v-if="currentView === 'detail'" class="detail-view">
- <!-- 历史记录切换Loading遮罩 -->
- <div v-if="isLoadingHistoryItem" class="detail-loading">
- <div class="loading-spinner"></div>
- <div class="loading-text">正在加载历史记录,请稍候...</div>
- </div>
-
- <!-- 主要内容区域:动态布局 -->
- <div class="main-content1" :class="{ 'with-document': showDocumentPreview }">
- <!-- 左侧:聊天对话区域 -->
- <div class="left-column">
- <div class="chat-area">
- <!-- 显示对话历史 -->
- <div
- v-for="(message, index) in selectedHistoryItem?.messages"
- :key="index"
- :class="['message-item', message.type]"
- >
- <!-- 用户消息 -->
- <div v-if="message.type === 'user'" class="user-message">
- <div class="message-content">
- <!-- 文件显示 -->
- <div v-if="message.file" class="message-file">
- <div class="file-display">
- <div class="file-icon">{{ message.file.icon }}</div>
- <div class="file-details">
- <div class="file-name">{{ message.file.name }}</div>
- <div class="file-size">{{ formatFileSize(message.file.size) }}</div>
- </div>
- </div>
- </div>
- <!-- 文本内容 -->
- <div v-if="message.content" class="message-text">{{ message.content }}</div>
- </div>
- <!-- <div class="message-time">{{ message.time }}</div> -->
- <!-- 用户消息的操作按钮 -->
- <div class="action-buttons">
- <button class="action-btn copy-btn" @click="copyUserMessage(message)">
- <img
- src="@/assets/AIWriting/5.png"
- alt="复制"
- class="action-icon"
- />
- 复制
- </button>
- <button class="action-btn edit-btn" @click="editUserMessage(message)">
- <img
- src="@/assets/AIWriting/6.png"
- alt="编辑"
- class="action-icon"
- />
- 编辑
- </button>
- </div>
- </div>
- <!-- AI消息 -->
- <div v-else-if="message.type === 'ai'" class="ai-message">
- <div class="ai-avatar">
- <img
- src="@/assets/AIWriting/15.png"
- alt="AI头像"
- class="avatar-img"
- />
- </div>
- <div class="message-content">
- <!-- 开头文字 -->
- <div v-if="message.parsedContent?.openingText" class="opening-text" v-html="filterInternalTags(message.parsedContent.openingText)">
- </div>
-
- <!-- 文档信息卡片 - 可点击显示预览 -->
- <div
- v-if="message.parsedContent?.hasDocument"
- class="document-info clickable"
- @click="toggleDocumentPreview(message.parsedContent)"
- >
- <div class="doc-icon">
- <img
- src="@/assets/AIWriting/14.png"
- alt="文档图标"
- class="info-icon"
- />
- </div>
- <div class="doc-details">
- <div class="doc-title">
- {{ message.parsedContent?.documentTitle || selectedHistoryItem?.documentContent?.title || "文档标题" }}
- </div>
- <div class="doc-time">创建时间: {{ getMessageTime(message) }}</div>
- </div>
- </div>
- <!-- 结尾文字 -->
- <div v-if="message.parsedContent?.closingText" class="closing-text" v-html="filterInternalTags(message.parsedContent.closingText)">
- </div>
- <!-- 操作按钮区域 -->
- <div class="action-buttons">
- <div class="left-actions">
- <button class="action-btn copy-btn" @click="copyAIMessage(message)">
- <img
- src="@/assets/AIWriting/5.png"
- alt="复制"
- class="action-icon"
- />
- 复制
- </button>
- <button class="action-btn regenerate-btn" @click="regenerateResponse(index)" :disabled="isGenerating">
- <img
- src="@/assets/AIWriting/7.png"
- alt="重新生成"
- class="action-icon"
- />
- 重新生成
- </button>
- <button class="action-btn delete-btn" @click="handleDeleteClick(index)">
- <img
- src="@/assets/AIWriting/8.png"
- alt="删除"
- class="action-icon"
- />
- 删除
- </button>
- <button class="action-btn voice-btn" @click="handleVoiceRead(message)">
- <img
- src="@/assets/AIWriting/9.png"
- alt="语音朗读"
- class="action-icon"
- />
- {{ isSpeaking(message.id) ? '停止朗读' : '语音朗读' }}
- </button>
- </div>
- <div class="right-actions">
- <button
- class="action-btn thumbs-up-btn"
- :class="{ active: message.userFeedback === 'like' }"
- @click="handleThumbsUp(message)"
- >
- <img src="@/assets/AIWriting/10.png" alt="点赞" class="action-icon">
- </button>
- <button
- class="action-btn thumbs-down-btn"
- :class="{ active: message.userFeedback === 'dislike' }"
- @click="handleThumbsDown(message)"
- >
- <img src="@/assets/AIWriting/11.png" alt="踩" class="action-icon">
- </button>
- </div>
- </div>
- </div>
- </div>
- </div>
- <!-- 生成中状态 -->
- <div v-if="isGenerating" class="message-item generating">
- <div class="ai-avatar">
- <img
- src="@/assets/AIWriting/15.png"
- alt="AI头像"
- class="avatar-img"
- />
- </div>
- <div class="message-content">
- <span class="generating-text">AI正在思考中...</span>
- <div class="loading-dots">
- <span></span>
- <span></span>
- <span></span>
- </div>
- </div>
- </div>
- </div>
- <!-- 输入框区域 - 固定在底部 -->
- <div class="input-section">
- <!-- 文件预览区域 - 放在输入框上方 -->
- <div v-if="selectedFile" class="file-preview-section">
- <div class="file-preview">
- <div class="file-icon">
- <img v-if="selectedFile.icon && typeof selectedFile.icon === 'string' && selectedFile.icon.includes('.png')" :src="selectedFile.icon" alt="文档图标" class="file-icon-img">
- <span v-else>{{ selectedFile.icon }}</span>
- </div>
- <div class="file-info">
- <div class="file-name">{{ selectedFile.name }}</div>
- <div class="file-size">{{ formatFileSize(selectedFile.size) }}</div>
- </div>
- <button class="remove-file-btn" @click="removeSelectedFile">
- <span class="remove-icon">×</span>
- </button>
- </div>
- </div>
-
- <div class="input-container">
- <button class="attachment-btn" @click="triggerFileUpload" :disabled="isGenerating">
- <img src="@/assets/Chat/9.png" alt="上传文件" class="action-icon" />
- </button>
- <input
- v-model="detailInputText"
- type="text"
- placeholder="请在此处发送消息 (Enter键也可发送)"
- class="message-input"
- @keydown.enter="sendDetailMessage"
- @input="handleDetailInput"
- maxlength="2000"
- :disabled="isGenerating"
- />
- <button class="voice-btn" @click="handleVoiceClick" :disabled="isGenerating" :class="{ 'recording': isListening }">
- <div class="icon-container">
- <img src="@/assets/Chat/18.png" alt="语音" class="action-icon" />
- <div v-if="isListening" class="recording-indicator"></div>
- </div>
- </button>
- <div class="divider"></div>
- <button class="send-btn" @click="sendDetailMessage" :disabled="isGenerating || !detailInputText.trim()">
- <img
- :src="detailInputText.trim() && !isGenerating ? sendIconFilled : sendIconEmpty"
- class="action-icon"
- alt="发送"
- />
- </button>
- </div>
- </div>
- </div>
- <!-- 右侧:文档内容区域 - 动态显示 -->
- <div v-if="showDocumentPreview" class="right-column">
- <div class="document-header">
- <h3 class="doc-title">
- <!-- {{ selectedDocument?.documentTitle || selectedHistoryItem?.documentContent?.title || "文档标题" }} -->
- 文件详情
- </h3>
- <div class="doc-actions">
- <button class="action-btn" @click="copyDocumentContent">
- <img src="@/assets/AIWriting/12.png" alt="复制" class="action-icon" />
- 复制
- </button>
- <button class="action-btn" @click="downloadDocumentAsWord">
- <img src="@/assets/AIWriting/13.png" alt="下载" class="action-icon" />
- 下载
- </button>
- <button class="action-btn close-btn" @click="closeDocumentPreview">
- <img src="@/assets/AIWriting/16.png" alt="关闭" class="action-icon" />
- </button>
- </div>
- </div>
- <div class="document-body">
- <div
- v-if="selectedDocument?.documentContent"
- v-for="section in selectedDocument.documentContent.sections"
- :key="`selected-${section.title}`"
- class="doc-section"
- >
- <div class="section-content" v-html="formatDocumentContent(section.content)"></div>
- </div>
- <!-- 如果没有选中文档,显示历史记录中的文档 -->
- <div
- v-else-if="selectedHistoryItem?.documentContent"
- v-for="section in selectedHistoryItem.documentContent.sections"
- :key="`history-${section.title}`"
- class="doc-section"
- >
- <div class="section-content" v-html="formatDocumentContent(section.content)"></div>
- </div>
- <!-- 如果都没有,尝试从AI消息中获取文档内容 -->
- <div
- v-else-if="getDocumentContentFromMessages()"
- v-for="section in getDocumentContentFromMessages().sections"
- :key="`message-${section.title}`"
- class="doc-section"
- >
- <div class="section-content" v-html="formatDocumentContent(section.content)"></div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
-
- <!-- 删除确认弹窗 -->
- <DeleteConfirmModal
- :visible="showDeleteModal"
- :title="deleteConfirmTitle"
- :message="deleteConfirmMessage"
- @confirm="confirmDelete"
- @cancel="cancelDelete"
- @close="cancelDelete"
- />
-
- <!-- 隐藏的文件输入框 -->
- <input
- ref="fileInput"
- type="file"
- accept=".docx"
- style="display: none"
- @change="handleFileSelect"
- />
- </div>
- </template>
- <script setup>
- import { ref, computed, nextTick, onMounted, onBeforeUnmount, watch, reactive } from "vue";
- import Sidebar from "@/components/Sidebar.vue";
- import DeleteConfirmModal from "@/components/DeleteConfirmModal.vue";
- import { apis } from "@/request/apis.js";
- import { ElMessage } from 'element-plus';
- // 导入语音识别组件
- import { useSpeechRecognition } from '@/composables/useSpeechRecognition';
- // 导入发送按钮图标
- import sendIconEmpty from "@/assets/Chat/15.png";
- import sendIconFilled from "@/assets/Chat/16.png";
- import wordDocIcon from "@/assets/Chat/26.png";
- // 导入 wangeditor
- import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
- import '@wangeditor/editor/dist/css/style.css'
- // wangeditor 可以直接处理 HTML,无需 Markdown 转换
- // 响应式数据
- const messageText = ref("");
- const inputText = ref("");
- const purposeText = ref("项目进展总结"); // 目的字段的默认值
- const contentText = ref("工作内容、成果、风险卡点及解决方案"); // 内容字段的默认值
- const templateContent = ref(""); // 整个模板输入框的文本内容
- const activeTab = ref("all");
- const currentView = ref("main"); // 当前视图:main-主界面,detail-详情页,editor-富文本编辑器
- const selectedHistoryItem = ref(null); // 选中的历史记录项
- const detailInputText = ref(""); // 详情页输入框文本
- const showDocumentPreview = ref(false); // 控制是否显示文档预览
- // 富文本编辑器相关状态
- const editorContent = ref(""); // 富文本编辑器内容
- const isEditorReady = ref(false); // 编辑器是否准备就绪
- const richEditor = ref(null); // 富文本编辑器 DOM 引用
- // wangeditor 编辑器内置撤销重做功能
- // wangeditor 编辑器引用
- const editorRef = ref(null);
- const mode = 'default'; // 或 'simple'
- // 添加文本选择事件监听
- onMounted(() => {
- // 监听全局文本选择事件
- document.addEventListener('selectionchange', handleSelectionChange);
- // 监听鼠标移动事件
- document.addEventListener('mousemove', handleMouseMove);
- // 监听鼠标按下事件
- document.addEventListener('mousedown', handleMouseDown);
- // 监听鼠标松开事件
- document.addEventListener('mouseup', handleMouseUp);
- // 监听滚动事件,滚动时隐藏润色输入框和高亮框
- document.addEventListener('scroll', handleScroll, true);
- // 监听键盘事件,退格键时隐藏润色输入框
- document.addEventListener('keydown', handleKeyDown);
- // 监听输入法事件,支持中文输入
- document.addEventListener('compositionstart', handleCompositionStart);
- document.addEventListener('compositionupdate', handleCompositionUpdate);
- document.addEventListener('compositionend', handleCompositionEnd);
- });
- onBeforeUnmount(() => {
- // 清理事件监听
- document.removeEventListener('selectionchange', handleSelectionChange);
- document.removeEventListener('mousemove', handleMouseMove);
- document.removeEventListener('mousedown', handleMouseDown);
- document.removeEventListener('mouseup', handleMouseUp);
- document.removeEventListener('scroll', handleScroll, true);
- document.removeEventListener('keydown', handleKeyDown);
- document.removeEventListener('compositionstart', handleCompositionStart);
- document.removeEventListener('compositionupdate', handleCompositionUpdate);
- document.removeEventListener('compositionend', handleCompositionEnd);
- });
- // wangeditor 工具栏配置
- const toolbarConfig = {
- excludeKeys: [
- 'group-video',
- 'group-more-style',
- 'fullScreen',
- 'emotion', // 表情
- 'insertLink', // 插入链接
- 'insertImage', // 插入图片
- 'uploadImage', // 上传图片
- 'insertTable', // 插入表格
- 'codeBlock', // 插入代码块
- 'divider', // 分割线
- 'undo', // 撤销
- 'redo' // 重做
- ]
- };
- // wangeditor 编辑器配置
- const editorConfig = {
- placeholder: '请输入内容...',
- readOnly: false,
- autoFocus: false,
- scroll: true,
- // 禁用所有弹出菜单
- hoverbarKeys: {
- text: {
- menuKeys: []
- },
- link: {
- menuKeys: []
- },
- image: {
- menuKeys: []
- },
- table: {
- menuKeys: []
- },
- video: {
- menuKeys: []
- }
- },
- // 禁用右键菜单
- MENU_CONF: {
- // 配置颜色
- color: {
- colors: ['#000000', '#333333', '#666666', '#999999', '#cccccc', '#ffffff', '#ff0000', '#00ff00', '#0000ff']
- },
- // 配置字体
- fontFamily: {
- fontFamilyList: ['黑体', '楷体', '仿宋', '微软雅黑', 'Arial', 'Tahoma', 'Verdana']
- },
- // 配置字号
- fontSize: {
- fontSizeList: ['12px', '13px', '14px', '15px', '16px', '19px', '22px', '24px', '32px', '48px']
- },
- // 禁用图片上传
- uploadImage: {
- server: '', // 空字符串禁用上传
- allowedFileTypes: [], // 不允许任何文件类型
- maxFileSize: 0, // 最大文件大小为0,禁用上传
- maxNumberOfFiles: 0, // 最大文件数量为0,禁用上传
- fieldName: '', // 空字段名
- meta: {},
- metaWithUrl: false,
- withCredentials: false,
- timeout: 0,
- headers: {},
- customInsert: () => {}, // 空函数,禁用自定义插入
- customBrowseAndUpload: () => {}, // 空函数,禁用浏览和上传
- customUpload: () => {} // 空函数,禁用自定义上传
- }
- }
- };
- // 删除相关状态
- const showDeleteModal = ref(false); // 控制是否显示删除确认弹窗
- const deleteTargetItem = ref(null); // 要删除的目标项
- const deleteType = ref(''); // 删除类型:'history' 或 'message'
- // AI写作相关状态
- const isGenerating = ref(false); // 是否正在生成
- const aiResponse = ref(""); // AI回复内容
- const showAIResponse = ref(false); // 是否显示AI回复
- const isLoadingHistory = ref(false); // 是否正在加载历史记录
- const isLoadingHistoryItem = ref(false); // 是否正在加载历史记录项
- // AI扩写相关状态
- const showPolishInput = ref(false); // 是否显示AI扩写输入框
- const selectedText = ref(""); // 选中的文本
- const polishInputPosition = ref({ x: 0, y: 0 }); // 扩写输入框位置
- const isPolishing = ref(false); // 是否正在扩写/续写
- const polishingType = ref(''); // 当前操作类型:'polish'(扩写)或 'continue'(续写)
- const mousePosition = ref({ x: 0, y: 0 }); // 鼠标位置
- const isMouseDown = ref(false); // 鼠标是否按下
- const savedSelection = ref(null); // 保存的选区信息
- const polishCustomPrompt = ref(""); // 用户自定义扩写/续写提示词
- const showCustomHighlight = ref(false); // 是否显示自定义高亮
- const customHighlightElement = ref(null); // 自定义高亮元素
- const isLoadingHistoryContent = ref(false); // 是否正在加载历史记录内容(用于防止弹窗误显示)
- // 文件上传相关状态
- const fileInput = ref(null);
- const selectedFile = ref(null);
- const isUploadingFile = ref(false);
- const isSending = ref(false); // 控制发送状态
- const fileContent = ref('') // 存储文件内容
- // ===== 已删除:getUserId - 不再需要,改用token =====
- // import { getUserId } from '@/utils/userManager.js'
- // 文件处理配置
- const fileConfig = reactive({
- maxSize: 20 * 1024 * 1024, // 20MB
- allowedTypes: ['.docx'] // 只允许.docx格式的Word文档
- })
- // 语音功能相关状态
- const speakingMessageId = ref(null); // 记录正在朗读的消息ID
- // 语音功能
- const {
- isSupported: speechSupported,
- isListening,
- isSpeaking: speechIsSpeaking,
- transcript,
- error: speechError,
- startListening,
- stopListening,
- speakText,
- stopSpeaking
- } = useSpeechRecognition();
- ;
- // 防抖定时器
- let debounceTimer = null;
- // 详情页输入防抖定时器
- let detailInputDebounceTimer = null;
- // 格式检测防抖定时器
- let formatDetectionTimer = null;
- //对话id
- const ai_conversation_id = ref(0)
- //业务类型
- const business_type = ref(2)
- // 计算属性:获取完整的输入文本
- const fullInputText = computed(() => {
- // 直接返回用户输入的内容,如果没有输入则返回空字符串
- return templateContent.value || "";
- });
- // 计算属性:判断是否有输入内容
- const hasInputContent = computed(() => {
- // 检查是否有用户输入的内容,包括默认模板文字
- const userInput = templateContent.value.trim();
-
- // 只要有内容就认为有输入,包括默认模板文字
- return userInput.length > 0;
- });
- // 历史记录数据
- const historyData = ref([])
- const historyTotal = ref(0) // 历史记录总数
- // 获取历史记录列表
- const getHistoryRecordList = async () => {
- try {
- console.log('📋 开始获取AI写作历史记录列表...')
- isLoadingHistory.value = true
- const startTime = performance.now()
-
- const response = await apis.getHistoryRecord({
- // ===== 已删除:user_id - 后端从token解析 =====
- ai_conversation_id: 0, // 0表示获取对话列表
- business_type: 2 // AI写作类型
- })
-
- const endTime = performance.now()
- console.log(`📋 AI写作历史记录API调用耗时: ${(endTime - startTime).toFixed(2)}ms`)
- console.log('📋 AI写作历史记录列表响应:', response)
-
- if (response.statusCode === 200) {
- // 设置历史记录总数
- historyTotal.value = response.total || 0
-
- // 转换后端数据为前端格式
- historyData.value = response.data.map(conversation => ({
- id: conversation.id,
- title: generateConversationTitle(conversation.content),
- time: formatTime(conversation.updated_at),
- businessType: conversation.business_type,
- isActive: false,
- // 保存原始数据用于后续查询
- rawData: conversation
- }))
- console.log(`✅ AI写作历史记录列表已设置: ${historyData.value.length}条记录,总数: ${historyTotal.value}`)
- } else {
- console.error('❌ 获取AI写作历史记录列表失败:', response.statusCode)
- }
- } catch (error) {
- console.error('❌ 获取AI写作历史记录列表失败:', error)
- } finally {
- isLoadingHistory.value = false
- }
- }
- // 获取指定对话的详细消息
- const getConversationMessages = async (conversationId) => {
- try {
- console.log('开始获取AI写作对话消息,conversationId:', conversationId)
- const response = await apis.getHistoryRecord({
- // ===== 已删除:user_id - 后端从token解析 =====
- ai_conversation_id: conversationId,
- business_type: 2 // AI写作类型
- })
- console.log('AI写作对话消息响应:', response)
- console.log('响应数据结构:', {
- statusCode: response.statusCode,
- data: response.data,
- dataType: Array.isArray(response.data) ? 'array' : typeof response.data,
- dataLength: Array.isArray(response.data) ? response.data.length : 'N/A'
- })
-
- if (response.statusCode === 200) {
- // 检查数据是否存在
- if (!response.data || !Array.isArray(response.data)) {
- console.error('响应数据格式错误:', response.data)
- return false
- }
-
- // 转换后端消息数据为前端格式
- const messages = response.data.map(message => {
- const userFeedback = convertUserFeedback(message.user_feedback)
- console.log(`消息 ${message.id} 的反馈状态:`, {
- raw: message.user_feedback,
- converted: userFeedback
- })
-
- // 对于AI消息,需要解析文档结构
- let parsedContent = null
- if (message.type === 'ai') {
- try {
- parsedContent = parseAIResponse(message.content)
-
- // 如果解析后没有文档结构,确保至少显示AI的回复内容
- if (!parsedContent.hasDocument && !parsedContent.openingText && !parsedContent.closingText) {
- parsedContent = {
- hasDocument: false,
- documentContent: null,
- openingText: message.content, // 将整个回复作为开头文本显示
- documentText: "",
- closingText: ""
- }
- }
- } catch (error) {
- console.error('解析AI回复失败:', error)
- parsedContent = {
- hasDocument: false,
- documentContent: null,
- openingText: message.content, // 将整个回复作为开头文本显示
- documentText: "",
- closingText: ""
- }
- }
- }
-
- // 如果是用户消息且包含文件标签,提取文件信息
- let file = null
- let userContent = message.content
-
- if (message.type === 'user' && message.content.includes('</filesize>')) {
- // 提取文件信息
- const filenameMatch = message.content.match(/<filename>(.*?)<\/filename>/)
- const filesizeMatch = message.content.match(/<filesize>(.*?)<\/filesize>/)
- const wordMatch = message.content.match(/<word>(.*?)<\/word>/s)
-
- if (filenameMatch && filesizeMatch) {
- const filename = filenameMatch[1]
- const filesize = parseInt(filesizeMatch[1])
- const fileContent = wordMatch ? wordMatch[1].trim() : ''
-
- // 创建文件对象
- file = {
- name: filename,
- size: filesize,
- type: filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '.docx',
- icon: getFileIcon(filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '.docx'),
- content: fileContent
- }
-
- // 提取用户实际说的话(</filesize>标签后的内容)
- const userMessageMatch = message.content.split('</filesize>')[1]
- userContent = userMessageMatch ? userMessageMatch.trim() : ''
- }
- }
-
- const messageObj = {
- type: message.type, // 'user' 或 'ai'
- content: userContent, // 使用提取的用户消息
- displayContent: message.type === 'ai' ? message.content : userContent,
- file: file, // 添加文件对象
- isTyping: false,
- id: message.id,
- userFeedback: userFeedback,
- parsedContent: parsedContent, // 添加解析后的内容
- created_at: message.created_at, // 添加创建时间字段
- isFromBackend: true, // 标记这是从后端获取的消息
- // 保存原始数据
- rawData: message
- };
-
-
- return messageObj;
- })
-
- // 设置聊天消息
- selectedHistoryItem.value.messages = messages
- console.log('AI写作对话消息已设置:', selectedHistoryItem.value.messages)
- console.log('消息数量:', messages.length)
- console.log('currentView状态:', currentView.value)
-
- // 更新对话ID
- ai_conversation_id.value = conversationId
-
- // 从AI消息中提取文档内容,设置到历史记录项上
- const aiMessage = messages.find(msg => msg.type === 'ai' && msg.parsedContent?.hasDocument);
- if (aiMessage && aiMessage.parsedContent) {
- selectedHistoryItem.value.documentContent = aiMessage.parsedContent.documentContent;
- selectedHistoryItem.value.hasDocument = aiMessage.parsedContent.hasDocument;
- }
-
- return true
- } else {
- console.error('获取AI写作对话消息失败:', response.statusCode)
- return false
- }
- } catch (error) {
- console.error('获取AI写作对话消息失败:', error)
- return false
- }
- }
- // 生成对话标题(从内容中提取)
- const generateConversationTitle = (content) => {
- if (!content) return '未知对话'
-
- // 检查是否包含文件标签格式
- if (content.includes('</filesize>')) {
- // 提取</filesize>标签后面的内容
- const userMessage = content.split('</filesize>')[1]
- if (userMessage && userMessage.trim()) {
- // 清理多余的空格和换行
- const cleanMessage = userMessage.replace(/\s+/g, ' ').trim()
-
- // 提取第一句话作为标题
- const firstSentence = cleanMessage.split(/[。!?\n]/)[0]
-
- // 限制标题长度
- if (firstSentence.length > 30) {
- return firstSentence.substring(0, 30) + '...'
- }
-
- return firstSentence || '新对话'
- }
- }
-
- // 如果没有文件标签,使用原来的方法
- let cleanContent = content.replace(/<[^>]*>/g, '')
- cleanContent = cleanContent.replace(/\s+/g, ' ').trim()
-
- // 提取第一句话作为标题
- const firstSentence = cleanContent.split(/[。!?\n]/)[0]
-
- // 限制标题长度
- if (firstSentence.length > 30) {
- return firstSentence.substring(0, 30) + '...'
- }
-
- return firstSentence || '新对话'
- }
- // 格式化时间
- const formatTime = (timestamp) => {
- if (!timestamp) return '未知时间'
-
- // 处理时间戳
- let date
- if (typeof timestamp === 'string') {
- // 如果是ISO字符串格式,直接创建Date对象
- date = new Date(timestamp)
- } else {
- // 如果是数字时间戳
- let timestampMs = timestamp
- if (timestamp.toString().length === 10) {
- timestampMs = timestamp * 1000
- } else if (timestamp.toString().length === 11) {
- timestampMs = timestamp * 1000
- } else if (timestamp.toString().length === 13) {
- // 13位时间戳,直接使用
- } else {
- timestampMs = timestamp * 1000
- }
- date = new Date(timestampMs)
- }
-
- const now = new Date()
-
- // 获取今天的开始时间(0点0分0秒)
- const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
- // 获取昨天的开始时间
- const yesterdayStart = new Date(todayStart.getTime() - 24 * 60 * 60 * 1000)
-
- // 今天的对话(日期相同)
- if (date >= todayStart) {
- return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
- }
-
- // 昨天的对话(日期是昨天)
- if (date >= yesterdayStart && date < todayStart) {
- return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
- }
-
- // 更早的对话:显示为 "8月30日 15:30" 格式
- const month = date.getMonth() + 1 // getMonth() 返回 0-11
- const day = date.getDate()
- const time = date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
-
- return `${month}月${day}日 ${time}`
- }
- // 根据消息来源显示时间
- const getMessageTime = (message) => {
- // 如果是从后端获取的消息且有created_at字段,使用formatTime格式化
- if (message.isFromBackend && message.created_at) {
- return formatTime(message.created_at)
- }
-
- // 否则使用原来的time字段(新创建的消息)
- return message.time || '未知时间'
- }
- // 转换用户反馈状态
- const convertUserFeedback = (feedback) => {
- console.log('转换用户反馈状态:', feedback, '类型:', typeof feedback)
- switch (parseInt(feedback)) {
- case 2: return 'like' // 满意(赞)
- case 3: return 'dislike' // 不满意(踩)
- case 0:
- default: return null // 无反馈
- }
- }
- // 转换前端反馈状态为后端格式
- const convertFeedbackToBackend = (feedback) => {
- switch (feedback) {
- case 'like': return 2 // 满意(赞)
- case 'dislike': return 3 // 不满意(踩)
- default: return 0 // 无反馈
- }
- }
- // 删除确认消息
- const deleteConfirmMessage = computed(() => {
- if (deleteType.value === 'history') {
- const title = deleteTargetItem.value?.item?.title || ''
- return `确定要删除历史记录"${title}"吗?删除后将无法恢复。`
- } else if (deleteType.value === 'message') {
- return '确定要删除这条消息吗?删除后将无法恢复。'
- }
- return '确定要删除吗?删除后将无法恢复。'
- })
- // 删除确认标题
- const deleteConfirmTitle = computed(() => {
- if (deleteType.value === 'history') {
- return '删除历史记录'
- } else if (deleteType.value === 'message') {
- return '删除消息'
- }
- return '删除确认'
- })
- // 删除历史记录
- const deleteHistoryItem = (historyItem, index) => {
- console.log('准备删除历史记录:', historyItem)
-
- // 设置要删除的项目并显示确认弹窗
- deleteTargetItem.value = { item: historyItem, index: index }
- deleteType.value = 'history'
- showDeleteModal.value = true
- }
- // 删除相关方法
- const handleDeleteClick = (messageIndex) => {
- console.log('点击删除按钮,消息索引:', messageIndex)
-
- // 检查是否只剩一句AI回复和一句用户发言
- if (selectedHistoryItem.value?.messages?.length === 2) {
- ElMessage.warning('第一句话无法删除')
- return
- }
-
- // 设置删除类型和要删除的消息索引
- deleteType.value = 'message'
- deleteTargetItem.value = { messageIndex: messageIndex }
- showDeleteModal.value = true
- }
- // 统一的确认删除函数
- const confirmDelete = async () => {
- if (!deleteTargetItem.value) return
-
- if (deleteType.value === 'history') {
- await confirmDeleteHistory()
- } else if (deleteType.value === 'message') {
- await confirmDeleteMessage()
- }
- }
- // 确认删除历史记录
- const confirmDeleteHistory = async () => {
- const { item: historyItem, index } = deleteTargetItem.value
-
- try {
- // 调用删除接口
- const response = await apis.deleteHistoryRecord({
- ai_conversation_id: historyItem.id
- })
-
- if (response.statusCode === 200) {
- // 删除成功,从列表中移除
- historyData.value.splice(index, 1)
-
- // 如果删除的是当前激活的历史记录,需要清空聊天界面并调用新建任务
- if (historyItem.isActive) {
- await createNewChat()
- }
-
- console.log('历史记录删除成功')
- ElMessage.success('删除成功')
- } else {
- console.error('删除历史记录失败:', response.msg)
- ElMessage.error(response.msg || '删除失败')
- }
- } catch (error) {
- console.error('删除历史记录失败:', error)
- ElMessage.error('删除失败,请稍后重试')
- } finally {
- // 关闭弹窗并清除目标项
- showDeleteModal.value = false
- deleteTargetItem.value = null
- deleteType.value = ''
- }
- }
- // 确认删除消息
- const confirmDeleteMessage = async () => {
- const { messageIndex } = deleteTargetItem.value
-
- try {
- const aiMessage = selectedHistoryItem.value?.messages?.[messageIndex]
- console.log('aiMessage:', aiMessage)
-
- // 检查是否有id(统一使用id字段)
- if (aiMessage && aiMessage.id) {
- console.log('准备调用后端删除接口,id:', aiMessage.id)
- try {
- // 调用后端删除接口
- const response = await apis.deleteConversation({
- ai_message_id: aiMessage.id
- })
- console.log('后端删除接口响应:', response)
-
- if (response.statusCode === 200) {
- // 后端删除成功,从前端数组中删除AI消息和对应的用户消息
- // 删除AI消息
- selectedHistoryItem.value.messages.splice(messageIndex, 1)
- // 删除对应的用户消息(前一条)
- if (messageIndex > 0) {
- selectedHistoryItem.value.messages.splice(messageIndex - 1, 1)
- }
-
- // 如果正在预览文档,关闭预览
- if (showDocumentPreview.value) {
- showDocumentPreview.value = false
- selectedDocument.value = null
- console.log('删除对话时关闭文档预览')
- }
-
- console.log('删除成功')
- ElMessage.success('删除成功')
- } else {
- console.error('删除失败:', response.msg)
- ElMessage.error('删除失败,请稍后重试')
- }
- } catch (error) {
- console.error('删除接口调用失败:', error)
- ElMessage.error('删除失败,请稍后重试')
- }
- } else {
- console.log('没有id,仅从前端删除')
- // 没有id的情况,仅从前端删除
- selectedHistoryItem.value.messages.splice(messageIndex, 1)
-
- // 如果正在预览文档,关闭预览
- if (showDocumentPreview.value) {
- showDocumentPreview.value = false
- selectedDocument.value = null
- console.log('删除对话时关闭文档预览')
- }
-
- ElMessage.success('删除成功')
- }
- } catch (error) {
- console.error('删除消息失败:', error)
- ElMessage.error('删除失败,请稍后重试')
- } finally {
- // 关闭弹窗并清除目标项
- showDeleteModal.value = false
- deleteTargetItem.value = null
- deleteType.value = ''
- }
- }
- // 取消删除
- const cancelDelete = () => {
- showDeleteModal.value = false
- deleteTargetItem.value = null
- deleteType.value = ''
- }
- // 从用户输入内容生成标题
- const generateTitleFromContent = (content) => {
- if (!content || !content.trim()) return 'AI写作任务'
-
- // 清理HTML标签
- const cleanContent = content.replace(/<[^>]*>/g, '')
-
- // 提取第一句话作为标题
- const firstSentence = cleanContent.split(/[。!?\n]/)[0]
-
- // 限制标题长度
- if (firstSentence.length > 30) {
- return firstSentence.substring(0, 30) + '...'
- }
-
- return firstSentence || 'AI写作任务'
- }
- // 后端返回的是HTML格式,无需Markdown转换
- // 模板标签配置
- const tabs = [
- { key: "all", name: "全部" },
- { key: "announcement", name: "公告" },
- { key: "notification", name: "通知" },
- { key: "summary", name: "总结报告" },
- { key: "meeting", name: "会议纪要" },
- { key: "speech", name: "决定" },
- ];
- import announcementIcon from '@/assets/AIWriting/3.png'
- import notificationIcon from '@/assets/AIWriting/2.png'
- import summaryIcon from '@/assets/AIWriting/1.png'
- import meetingIcon from '@/assets/AIWriting/18.png'
- import speechIcon from '@/assets/AIWriting/19.png'
- // 模板数据配置
- const templates = [
- {
- id: 1,
- name: "公告模板",
- image: announcementIcon,
- category: "announcement",
- buttonClass: "announcement-btn"
- },
- {
- id: 2,
- name: "通知模板",
- image: notificationIcon,
- category: "notification",
- buttonClass: "notification-btn"
- },
- {
- id: 3,
- name: "工作汇报模板",
- image: summaryIcon,
- category: "summary",
- buttonClass: "report-btn"
- },
- {
- id: 4,
- name: "会议纪要模版",
- image: meetingIcon,
- category: "meeting",
- buttonClass: "announcement-btn"
- },
- {
- id: 5,
- name: "决定模版",
- image: speechIcon,
- category: "speech",
- buttonClass: "notification-btn"
- }
- ];
- // 根据当前选中的标签筛选模板
- const filteredTemplates = computed(() => {
- if (activeTab.value === "all") {
- return templates;
- }
- return templates.filter(template => template.category === activeTab.value);
- });
- // 方法
- const createNewChat = async () => {
- console.log("创建新AI写作任务");
-
- // 如果正在生成或扩写/续写,不允许新建
- if (isGenerating.value || isPolishing.value) {
- return
- }
-
- // 隐藏AI扩写输入框
- hidePolishInput();
-
- // 停止当前朗读
- if (speakingMessageId.value) {
- try { window.speechSynthesis && window.speechSynthesis.cancel(); } catch (e) {}
- speakingMessageId.value = null;
- }
-
- // 重置所有状态
- ai_conversation_id.value = 0
- selectedHistoryItem.value = null;
- currentView.value = "main";
- showDocumentPreview.value = false;
- selectedDocument.value = null;
- detailInputText.value = "";
- // 重置输入框内容为默认模板
- const inputElement = document.querySelector('.template-input-container');
- if (inputElement) {
- const defaultTemplate = "<span class=\"editable-highlight\" contenteditable=\"true\">总结主题:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">总结时间:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">主要内容:</span>\n\n请帮我生成一份正式的总结报告,要求格式规范、语言严谨,具体参考以上内容,按照标准工作总结格式生成全文,包含\"工作总结、问题不足、未来计划\"三部分的完整报告。";
- inputElement.innerHTML = defaultTemplate;
- templateContent.value = defaultTemplate.replace(/<[^>]*>/g, '');
- // 为高亮元素添加样式
- nextTick(() => {
- const highlights = inputElement.querySelectorAll('.editable-highlight');
- highlights.forEach(highlight => {
- highlight.style.backgroundColor = '#3E7BFA10';
- highlight.style.color = '#3E7BFA';
- highlight.style.padding = '4px 8px';
- highlight.style.borderRadius = '6px';
- highlight.style.fontWeight = '500';
- highlight.style.cursor = 'text';
- highlight.style.border = '1px solid transparent';
- highlight.style.display = 'inline-block';
- highlight.style.minWidth = '20px';
- });
- });
- }
- // 清除所有历史记录的选中状态
- historyData.value.forEach((item) => {
- item.isActive = false;
- });
-
- // 刷新历史记录列表
- await getHistoryRecordList();
- };
- // 点击历史记录
- const handleHistoryItem = async (historyItem) => {
- console.log("点击历史记录:", historyItem);
-
- // 如果正在生成,不允许切换
- if (isGenerating.value) {
- return
- }
-
- // 隐藏AI扩写输入框
- hidePolishInput();
-
- // 设置加载标志,防止选择事件触发弹窗
- isLoadingHistoryContent.value = true;
-
- // 显示loading
- isLoadingHistoryItem.value = true;
-
- try {
- // 停止当前朗读
- if (speakingMessageId.value) {
- try { window.speechSynthesis && window.speechSynthesis.cancel(); } catch (e) {}
- speakingMessageId.value = null;
- }
-
- selectedHistoryItem.value = historyItem;
- // 重置文档预览状态,确保界面恢复全屏
- showDocumentPreview.value = false;
- selectedDocument.value = null;
- // 更新数据层的active状态
- historyData.value.forEach((item) => {
- item.isActive = item.id === historyItem.id;
- });
- // 获取该对话的详细消息
- const success = await getConversationMessages(historyItem.id)
-
- if (success) {
- console.log('AI写作历史对话加载成功,直接进入富文本编辑器')
-
- // 获取AI回复内容
- const aiMessage = selectedHistoryItem.value.messages.find(msg => msg.type === 'ai');
- if (aiMessage) {
- // 直接使用AI消息内容,无需解析
-
- // 直接使用AI消息的content,无需解析
- console.log('AI消息内容长度:', aiMessage.content.length);
- console.log('AI消息内容预览:', aiMessage.content.substring(0, 200) + '...');
-
- // 格式化内容并进入富文本编辑器
- const formattedContent = formatContentForEditor(aiMessage.content);
- enterEditor(formattedContent);
- } else {
- // 如果没有AI消息,显示用户消息
- const userMessage = selectedHistoryItem.value.messages.find(msg => msg.type === 'user');
- if (userMessage) {
- const formattedContent = formatContentForEditor(userMessage.content);
- enterEditor(formattedContent);
- } else {
- // 如果都没有,显示默认内容
- enterEditor("<p>暂无内容</p>");
- }
- }
- } else {
- console.error('加载历史对话失败')
- ElMessage.error('加载历史对话失败,请稍后重试');
- }
- } catch (error) {
- console.error('加载AI写作历史对话失败:', error)
- ElMessage.error('加载历史对话时发生错误,请稍后重试');
- } finally {
- // 隐藏loading
- isLoadingHistoryItem.value = false;
-
- // 延迟重置加载标志,确保编辑器内容已完全加载并且选择事件已处理
- setTimeout(() => {
- isLoadingHistoryContent.value = false;
- console.log("历史记录内容加载完成,允许显示扩写弹窗");
- }, 500); // 延迟500ms,确保所有选择事件已处理完毕
- }
- };
- // 返回主界面
- const backToMain = () => {
- currentView.value = "main";
- ai_conversation_id.value = 0
- selectedHistoryItem.value = null;
- showDocumentPreview.value = false; // 关闭文档预览
- selectedDocument.value = null; // 重置选中文档
- // 重置所有历史记录的active状态
- historyData.value.forEach((item) => {
- item.isActive = false;
- });
-
- // 隐藏AI扩写输入框
- hidePolishInput();
-
- // 重置加载标志
- isLoadingHistoryContent.value = false;
-
- // 移除选择变化监听
- removeSelectionListener();
- };
- // wangeditor 编辑器内置格式检测功能
- // wangeditor 编辑器事件处理
- const handleCreated = (editor) => {
- editorRef.value = editor;
- console.log('wangeditor 编辑器创建完成');
- };
- const handleChange = (editor) => {
- // 获取编辑器内容但不立即更新 editorContent.value
- const currentEditorContent = editor.getHtml();
-
- // 调试日志:检查内容变化
- console.log("wangeditor内容变化 - 新内容长度:", currentEditorContent.length);
- console.log("wangeditor内容变化 - 新内容预览:", currentEditorContent.substring(0, 200) + '...');
-
- // 只有在用户主动编辑时才更新 editorContent.value
- // 避免在程序设置内容时被覆盖
- if (isEditorReady.value) {
- editorContent.value = currentEditorContent;
- }
- };
- // 不再需要自定义粘贴处理,wangeditor 会自动处理
- const handleEditorKeydown = (event) => {
- // 处理快捷键
- if (event.ctrlKey || event.metaKey) {
- switch (event.key) {
- case 'z':
- event.preventDefault();
- if (event.shiftKey) {
- redoEditor(); // Ctrl+Shift+Z 重做
- } else {
- undoEditor(); // Ctrl+Z 撤销
- }
- break;
- case 'y':
- event.preventDefault();
- redoEditor(); // Ctrl+Y 重做
- break;
- case 'b':
- event.preventDefault();
- execCommand('bold');
- break;
- case 'i':
- event.preventDefault();
- execCommand('italic');
- break;
- case 'u':
- event.preventDefault();
- execCommand('underline');
- break;
- case 's':
- event.preventDefault();
- saveDocument();
- break;
- }
- }
-
- // 检测当前格式
- setTimeout(() => {
- detectCurrentFormat();
- }, 0);
- };
- // 处理编辑器点击事件
- const handleEditorClick = () => {
- // 立即检测格式(点击时不需要防抖)
- detectCurrentFormat();
- };
- // 处理编辑器选择变化
- const handleEditorSelectionChange = () => {
- // 使用防抖来减少格式检测的频率
- if (formatDetectionTimer) {
- clearTimeout(formatDetectionTimer);
- }
-
- formatDetectionTimer = setTimeout(() => {
- detectCurrentFormat();
- }, 100); // 100ms 防抖延迟,比输入事件更快响应
- };
- // 添加全局选择变化监听
- const addSelectionListener = () => {
- document.addEventListener('selectionchange', handleEditorSelectionChange);
- };
- // 移除全局选择变化监听
- const removeSelectionListener = () => {
- document.removeEventListener('selectionchange', handleEditorSelectionChange);
- };
- // wangeditor 编辑器内置撤销重做功能
- // 保存光标位置
- const saveCursorPosition = () => {
- const selection = window.getSelection();
- if (selection.rangeCount > 0) {
- const range = selection.getRangeAt(0);
- return {
- startContainer: range.startContainer,
- startOffset: range.startOffset,
- endContainer: range.endContainer,
- endOffset: range.endOffset
- };
- }
- return null;
- };
- // 恢复光标位置
- const restoreCursorPosition = (savedPosition) => {
- if (!savedPosition) return;
-
- try {
- const selection = window.getSelection();
- const range = document.createRange();
-
- range.setStart(savedPosition.startContainer, savedPosition.startOffset);
- range.setEnd(savedPosition.endContainer, savedPosition.endOffset);
-
- selection.removeAllRanges();
- selection.addRange(range);
- } catch (error) {
- console.log('恢复光标位置失败:', error);
- }
- };
- // wangeditor 编辑器内置所有格式化功能
- // wangeditor 编辑器内置链接和图片功能
- // wangeditor 编辑器内置字体和字号功能
- const saveDocument = async (options = {}) => {
- const { silent = false } = options
- // 如果正在扩写/续写,不允许保存
- if (isPolishing.value) {
- return;
- }
-
- try {
- // 获取当前编辑器内容
- let content = '';
- if (editorRef.value) {
- try {
- // 强制刷新编辑器内容,确保获取最新内容
- content = editorRef.value.getHtml();
- console.log("保存文档 - 从wangeditor获取内容,长度:", content.length);
- console.log("保存文档 - 内容预览:", content.substring(0, 200) + '...');
- } catch (error) {
- console.log("从wangeditor获取内容失败,使用editorContent:", error);
- content = editorContent.value || '';
- }
- } else {
- content = editorContent.value || '';
- console.log("保存文档 - 从editorContent获取内容,长度:", content.length);
- }
-
- if (!content || content.trim() === '') {
- ElMessage.warning("没有内容可保存");
- return;
- }
-
- console.log("保存文档内容长度:", content.length);
-
- // 获取当前对话ID
- const currentConversationId = selectedHistoryItem.value?.id;
- if (!currentConversationId) {
- ElMessage.error("无法获取对话ID,请重新选择历史记录");
- return;
- }
-
- // 调用保存接口
- const response = await apis.saveEditDocument({
- ai_conversation_id: currentConversationId,
- content: content
- });
-
- if (response && response.data && response.statusCode === 200) {
- if (!silent) {
- ElMessage.success("文档保存成功");
- }
- console.log("文档保存成功,返回内容:", response.data.data);
- } else {
- ElMessage.error("文档保存失败,请重试");
- console.error("保存失败:", response);
- }
- } catch (error) {
- console.error("保存文档失败:", error);
- ElMessage.error("保存文档失败,请检查网络连接");
- }
- };
- // 下载文档功能
- const downloadDocument = async () => {
- // 如果正在扩写/续写,不允许下载
- if (isPolishing.value) {
- return;
- }
-
- try {
- console.log("开始下载文档...");
-
- // 先保存文档到数据库(静默,不提示成功)
- await saveDocument({ silent: true });
-
- // 尝试多种方式获取编辑器内容
- let content = '';
-
- // 方式1: 从DOM获取
- const editorTextContainer = document.querySelector('.w-e-text');
- if (editorTextContainer) {
- content = editorTextContainer.innerHTML;
- console.log("从DOM获取内容长度:", content.length);
- }
-
- // 方式2: 从editorContent获取
- if (!content && editorContent.value) {
- content = editorContent.value;
- console.log("从editorContent获取内容长度:", content.length);
- }
-
- // 方式3: 从wangeditor实例获取
- if (!content && editorRef.value) {
- try {
- content = editorRef.value.getHtml();
- console.log("从wangeditor实例获取内容长度:", content.length);
- } catch (error) {
- console.log("从wangeditor实例获取失败:", error);
- }
- }
-
- console.log("最终下载内容长度:", content.length);
- console.log("最终下载内容预览:", content.substring(0, 200));
-
- if (!content || content.trim() === '') {
- ElMessage.warning("没有可下载的内容");
- return;
- }
-
- // 获取当前文档标题
- const documentTitle = getCurrentDocumentTitle();
-
- // 生成文件名(优先使用文档标题)
- let filename;
- if (documentTitle && documentTitle !== 'AI生成文档') {
- // 清理标题中的特殊字符,确保文件名合法
- const cleanTitle = documentTitle.replace(/[<>:"/\\|?*]/g, '').trim();
- filename = `${cleanTitle}.docx`;
- } else {
- // 如果没有有效标题,使用时间戳
- const now = new Date();
- const timestamp = now.toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '_');
- filename = `AI生成文档_${timestamp}.docx`;
- }
-
- // 生成无水印的Word文档(HTML方式)
- await generateWordWithoutWatermark(content, documentTitle, filename);
-
- } catch (error) {
- console.error("下载Word文档失败:", error);
- ElMessage.error("下载Word文档失败,请重试");
- }
- };
- // 进入富文本编辑器
- const enterEditor = (content) => {
- currentView.value = "editor";
-
- console.log("进入富文本编辑器,内容长度:", content.length);
- console.log("进入富文本编辑器,内容预览:", content.substring(0, 200) + '...');
-
- // 使用 nextTick 确保 DOM 更新后再设置内容
- nextTick(() => {
- // 先设置内容
- editorContent.value = content;
-
- // 延迟设置编辑器内容,确保编辑器已初始化
- setTimeout(() => {
- if (editorRef.value) {
- try {
- // 直接设置 HTML 内容到 wangeditor
- editorRef.value.setHtml(content);
- console.log("wangeditor 内容设置完成");
-
- // 设置完成后才标记编辑器为就绪
- isEditorReady.value = true;
- // 重置生成状态
- isGenerating.value = false;
- } catch (error) {
- console.error("设置 wangeditor 内容失败:", error);
-
- // 如果setHtml失败,尝试重新初始化编辑器
- try {
- console.log("尝试重新初始化编辑器...");
- // 清空编辑器内容
- editorRef.value.clear();
- // 重新设置内容
- editorRef.value.setHtml(content);
- console.log("重新初始化编辑器成功");
- isEditorReady.value = true;
- isGenerating.value = false;
- } catch (retryError) {
- console.error("重新初始化编辑器也失败:", retryError);
- // 最后的降级方案:直接设置editorContent
- editorContent.value = content;
- isEditorReady.value = true;
- isGenerating.value = false;
- }
- }
- } else {
- console.log("editorRef.value 不存在,等待编辑器初始化");
- // 如果编辑器还没初始化,再等一会
- setTimeout(() => {
- if (editorRef.value) {
- try {
- editorRef.value.setHtml(content);
- console.log("延迟设置 wangeditor 内容完成");
-
- // 设置完成后才标记编辑器为就绪
- isEditorReady.value = true;
- // 重置生成状态
- isGenerating.value = false;
- } catch (error) {
- console.error("延迟设置 wangeditor 内容失败:", error);
-
- // 如果延迟设置也失败,尝试重新初始化编辑器
- try {
- console.log("延迟设置失败,尝试重新初始化编辑器...");
- editorRef.value.clear();
- editorRef.value.setHtml(content);
- console.log("延迟重新初始化编辑器成功");
- isEditorReady.value = true;
- isGenerating.value = false;
- } catch (retryError) {
- console.error("延迟重新初始化编辑器也失败:", retryError);
- // 最后的降级方案:直接设置editorContent
- editorContent.value = content;
- isEditorReady.value = true;
- isGenerating.value = false;
- }
- }
- }
- }, 500);
- }
- }, 100);
- });
- };
- // 处理鼠标移动
- const handleMouseMove = (event) => {
- // 检查是否在AI扩写输入框上移动
- if (event.target.closest('.ai-polish-input')) {
- return; // 如果在扩写输入框上移动,不处理
- }
-
- // 只有在鼠标按下时才更新位置,避免按钮位置一直变化
- if (isMouseDown.value) {
- mousePosition.value = {
- x: event.clientX,
- y: event.clientY
- };
- }
- };
- // 处理鼠标按下
- const handleMouseDown = (event) => {
- // 如果正在扩写/续写,禁用文本选择
- if (isPolishing.value) {
- event.preventDefault();
- return;
- }
-
- // 检查是否点击的是AI扩写输入框
- if (event.target.closest('.ai-polish-input')) {
- return; // 如果点击的是扩写输入框,不处理,保持显示
- }
-
- // 如果点击的是工具栏,隐藏AI扩写输入框
- if (event.target.closest('.w-e-toolbar') || event.target.closest('.w-e-bar')) {
- hidePolishInput();
- return;
- }
-
- isMouseDown.value = true;
- // 记录鼠标按下时的位置
- mousePosition.value = {
- x: event.clientX,
- y: event.clientY
- };
- // 只有在点击编辑器内容区域且不在扩写输入框内时才隐藏输入框
- if ((event.target.closest('.w-e-text-container') || event.target.closest('.rich-editor-container'))
- && !event.target.closest('.ai-polish-input')) {
- hidePolishInput();
- }
- };
- // 处理鼠标松开
- const handleMouseUp = () => {
- // 如果正在扩写/续写,不处理鼠标松开事件
- if (isPolishing.value) {
- return;
- }
-
- isMouseDown.value = false;
- // 鼠标松开后检查是否有选中文本
- setTimeout(() => {
- checkSelectionAndShowButton();
- }, 50); // 延迟50ms确保选择完成
- };
- // 检查选择并显示按钮
- const checkSelectionAndShowButton = () => {
- console.log("=== checkSelectionAndShowButton 被调用 ===");
-
- // 如果正在加载历史记录内容,不处理选择
- if (isLoadingHistoryContent.value) {
- console.log("正在加载历史记录内容,跳过选择处理");
- return;
- }
-
- // 如果正在扩写/续写,不处理选择
- if (isPolishing.value) {
- console.log("正在扩写/续写中,跳过选择处理");
- return;
- }
-
- // 如果扩写输入框正在显示,不处理选择
- if (showPolishInput.value) {
- console.log("扩写输入框正在显示,跳过选择处理");
- return;
- }
-
- try {
- const selection = window.getSelection();
- console.log("当前选择:", selection ? selection.toString() : "无选择");
-
- if (selection && selection.toString().trim().length > 0) {
- console.log("检测到选中文本");
-
- const selectedTextContent = selection.toString().trim();
- selectedText.value = selectedTextContent;
-
- // 使用鼠标最后位置作为输入框位置,并考虑屏幕边界
- const polishBoxWidth = 400; // 扩写框最大宽度
- const polishBoxHeight = 60; // 扩写框高度(估算)
- const margin = 10; // 边距
-
- // 获取当前视口尺寸
- const viewportWidth = window.innerWidth;
- const viewportHeight = window.innerHeight;
-
- let x = mousePosition.value.x + margin; // 默认在鼠标右侧
- let y = mousePosition.value.y - 80; // 默认在鼠标上方
-
- // 检查右边界 - 如果右侧空间不够,改为左侧
- if (x + polishBoxWidth > viewportWidth) {
- x = mousePosition.value.x - polishBoxWidth - margin;
- }
-
- // 检查左边界 - 如果左侧也不够,贴左边
- if (x < margin) {
- x = margin;
- }
-
- // 检查上边界 - 如果上方空间不够,改为下方
- if (y < margin) {
- y = mousePosition.value.y + margin;
- }
-
- // 检查下边界 - 如果下方也不够,贴底边
- if (y + polishBoxHeight > viewportHeight - margin) {
- y = viewportHeight - polishBoxHeight - margin;
- }
-
- // 最终边界检查,确保不会超出屏幕
- x = Math.max(margin, Math.min(x, viewportWidth - polishBoxWidth - margin));
- y = Math.max(margin, Math.min(y, viewportHeight - polishBoxHeight - margin));
-
- polishInputPosition.value = { x, y };
-
- showPolishInput.value = true;
- console.log("选中文本:", selectedTextContent);
- console.log("鼠标位置:", mousePosition.value);
- console.log("视口尺寸:", { width: viewportWidth, height: viewportHeight });
- console.log("扩写框位置:", polishInputPosition.value);
-
- // 保存选区信息,包括HTML结构用于精确匹配
- if (selection && selection.rangeCount > 0) {
- try {
- const range = selection.getRangeAt(0);
- // 确保选区在编辑器内
- const editorContainer = editorRef.value?.getEditableContainer?.();
- if (editorContainer && editorContainer.contains(range.commonAncestorContainer)) {
- // 创建临时容器来获取选中内容的HTML
- const tempDiv = document.createElement('div');
- tempDiv.appendChild(range.cloneContents());
- const selectedHtml = tempDiv.innerHTML;
-
- // 获取选中文本的纯文本内容(移除所有HTML标签)
- const selectedPlainText = tempDiv.textContent || tempDiv.innerText || '';
-
- // 检测是否为多格式文本
- const isMultiFormat = selectedHtml.includes('<strong>') ||
- selectedHtml.includes('<em>') ||
- selectedHtml.includes('<b>') ||
- selectedHtml.includes('<i>') ||
- selectedHtml.includes('<span') ||
- selectedHtml.includes('<h1>') ||
- selectedHtml.includes('<h2>') ||
- selectedHtml.includes('<h3>') ||
- selectedHtml.includes('<h4>') ||
- selectedHtml.includes('<h5>') ||
- selectedHtml.includes('<h6>') ||
- selectedHtml.includes('<u>') ||
- selectedHtml.includes('<s>');
-
- savedSelection.value = {
- text: selectedTextContent,
- html: selectedHtml,
- plainText: selectedPlainText, // 保存纯文本内容
- isMultiFormat: isMultiFormat, // 标记是否为多格式文本
- range: range.cloneRange(),
- // 保存更多选区信息用于多格式文本
- startContainer: range.startContainer,
- endContainer: range.endContainer,
- startOffset: range.startOffset,
- endOffset: range.endOffset,
- // 保存完整的HTML内容用于精确匹配
- fullHtml: editorRef.value.getHtml()
- };
- console.log("已保存选区信息:", {
- text: selectedTextContent,
- html: selectedHtml,
- plainText: selectedPlainText,
- isMultiFormat: isMultiFormat,
- startContainer: range.startContainer,
- endContainer: range.endContainer,
- startOffset: range.startOffset,
- endOffset: range.endOffset
- });
-
- // 不显示自定义高亮框,保留浏览器原生选区高亮
- // 这样用户可以直接通过退格键删除选中的文本
- } else {
- console.log("选区不在编辑器内,清除保存的选区");
- savedSelection.value = null;
- }
- } catch (error) {
- console.error("保存选区失败:", error);
- savedSelection.value = null;
- }
- }
-
- // 不自动聚焦到扩写输入框,避免选区丢失
- // 用户需要时可以手动点击输入框进行输入
- } else {
- console.log("没有选中文本,隐藏输入框");
- hidePolishInput();
- }
- } catch (error) {
- console.error("处理文本选择失败:", error);
- hidePolishInput();
- }
- };
- // 处理滚动事件
- const handleScroll = (event) => {
- // 如果扩写输入框正在显示
- if (showPolishInput.value) {
- // 检查是否在编辑器容器内滚动
- const isInEditor = event.target.closest('.w-e-text-container') ||
- event.target.closest('.rich-editor-container') ||
- event.target.closest('.w-e-text-placeholder') ||
- event.target.closest('.w-e-content');
-
- // 如果在编辑器内滚动
- if (isInEditor) {
- // 如果正在扩写/续写过程中,禁用滚动
- if (isPolishing.value) {
- console.log("扩写/续写过程中,禁用编辑器滚动");
- event.preventDefault();
- event.stopPropagation();
- return;
- }
-
- // 扩写/续写完成后允许滚动,但隐藏扩写输入框
- console.log("检测到编辑器内滚动,隐藏扩写输入框");
- hidePolishInput();
- } else {
- console.log("检测到页面滚动,但不隐藏扩写输入框");
- }
- }
- };
- // 处理键盘事件
- const handleKeyDown = (event) => {
- // 如果扩写输入框正在显示
- if (showPolishInput.value) {
- // 检查是否在扩写输入框内(更精确的检查)
- const isInPolishInput = event.target.closest('.ai-polish-input') ||
- event.target.classList.contains('polish-input-field') ||
- event.target.classList.contains('polish-input-container') ||
- event.target.classList.contains('input-wrapper');
-
- // 如果在扩写输入框内,不处理任何键盘事件
- if (isInPolishInput) {
- console.log("在扩写输入框内,不处理键盘事件");
- return;
- }
-
- // 检查是否在编辑器内
- const isInEditor = event.target.closest('.w-e-text-container') ||
- event.target.closest('.rich-editor-container') ||
- event.target.closest('.w-e-text-placeholder');
-
- // 只有在编辑器内才处理键盘事件
- if (isInEditor) {
- // 在编辑器内按退格键、删除键
- if (event.key === 'Backspace' || event.key === 'Delete') {
- console.log("检测到退格/删除键,隐藏扩写输入框");
- hidePolishInput();
- }
- // 在编辑器内输入文字(字母、数字、中文等)
- else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
- console.log("检测到文字输入,隐藏扩写输入框");
- hidePolishInput();
- }
- // 在编辑器内按空格键
- else if (event.key === ' ') {
- console.log("检测到空格键,隐藏扩写输入框");
- hidePolishInput();
- }
- // 在编辑器内按Enter键
- else if (event.key === 'Enter') {
- console.log("检测到Enter键,隐藏扩写输入框");
- hidePolishInput();
- }
- }
- }
- };
- // 处理输入法开始事件
- const handleCompositionStart = (event) => {
- if (showPolishInput.value) {
- // 检查是否在扩写输入框内(更精确的检查)
- const isInPolishInput = event.target.closest('.ai-polish-input') ||
- event.target.classList.contains('polish-input-field') ||
- event.target.classList.contains('polish-input-container') ||
- event.target.classList.contains('input-wrapper');
-
- // 如果在扩写输入框内,不处理
- if (isInPolishInput) {
- console.log("在扩写输入框内,不处理输入法事件");
- return;
- }
-
- // 检查是否在编辑器内
- const isInEditor = event.target.closest('.w-e-text-container') ||
- event.target.closest('.rich-editor-container') ||
- event.target.closest('.w-e-text-placeholder');
-
- // 在编辑器内开始输入法输入时隐藏扩写输入框
- if (isInEditor) {
- console.log("检测到输入法开始,隐藏扩写输入框");
- hidePolishInput();
- }
- }
- };
- // 处理输入法更新事件
- const handleCompositionUpdate = (event) => {
- if (showPolishInput.value) {
- // 检查是否在扩写输入框内(更精确的检查)
- const isInPolishInput = event.target.closest('.ai-polish-input') ||
- event.target.classList.contains('polish-input-field') ||
- event.target.classList.contains('polish-input-container') ||
- event.target.classList.contains('input-wrapper');
-
- // 如果在扩写输入框内,不处理
- if (isInPolishInput) {
- console.log("在扩写输入框内,不处理输入法事件");
- return;
- }
-
- // 检查是否在编辑器内
- const isInEditor = event.target.closest('.w-e-text-container') ||
- event.target.closest('.rich-editor-container') ||
- event.target.closest('.w-e-text-placeholder');
-
- // 在编辑器内输入法更新时隐藏扩写输入框
- if (isInEditor) {
- console.log("检测到输入法更新,隐藏扩写输入框");
- hidePolishInput();
- }
- }
- };
- // 处理输入法结束事件
- const handleCompositionEnd = (event) => {
- if (showPolishInput.value) {
- // 检查是否在扩写输入框内(更精确的检查)
- const isInPolishInput = event.target.closest('.ai-polish-input') ||
- event.target.classList.contains('polish-input-field') ||
- event.target.classList.contains('polish-input-container') ||
- event.target.classList.contains('input-wrapper');
-
- // 如果在扩写输入框内,不处理
- if (isInPolishInput) {
- console.log("在扩写输入框内,不处理输入法事件");
- return;
- }
-
- // 检查是否在编辑器内
- const isInEditor = event.target.closest('.w-e-text-container') ||
- event.target.closest('.rich-editor-container') ||
- event.target.closest('.w-e-text-placeholder');
-
- // 在编辑器内输入法结束时隐藏扩写输入框
- if (isInEditor) {
- console.log("检测到输入法结束,隐藏扩写输入框");
- hidePolishInput();
- }
- }
- };
- // 处理文本选择变化
- const handleSelectionChange = () => {
- console.log("=== handleSelectionChange 被调用 ===");
-
- // 如果正在润色,不处理选择变化
- if (isPolishing.value) {
- console.log("正在润色中,跳过选择变化处理");
- return;
- }
-
- // 如果润色输入框正在显示,不处理选择变化
- if (showPolishInput.value) {
- console.log("润色输入框正在显示,跳过选择变化处理");
- return;
- }
-
- // 只有在鼠标松开后才处理选择变化
- if (!isMouseDown.value) {
- console.log("鼠标已松开,调用 checkSelectionAndShowButton");
- checkSelectionAndShowButton();
- } else {
- console.log("鼠标仍按下,等待松开");
- }
- };
- // 处理扩写输入框点击事件
- const handlePolishInputClick = (event) => {
- // 允许输入框正常聚焦,但阻止事件冒泡
- event.stopPropagation();
-
- // 点击输入框时,显示自定义高亮而不是恢复原生选区
- showCustomHighlight.value = true;
- createCustomHighlight();
- };
- // 处理扩写输入框聚焦事件
- const handlePolishInputFocus = (event) => {
- // 输入框聚焦时,显示自定义高亮
- showCustomHighlight.value = true;
- createCustomHighlight();
- };
- // 处理扩写输入框失焦事件
- const handlePolishInputBlur = (event) => {
- // 输入框失焦时,隐藏自定义高亮,恢复原生选区
- showCustomHighlight.value = false;
- removeCustomHighlight();
-
- // 恢复原生选区
- setTimeout(() => {
- if (savedSelection.value && savedSelection.value.range) {
- try {
- const selection = window.getSelection();
- if (selection) {
- // 清除当前选区
- selection.removeAllRanges();
- // 恢复保存的选区
- selection.addRange(savedSelection.value.range);
- console.log("输入框失焦时恢复选区成功");
- }
- } catch (error) {
- console.error("恢复选区失败:", error);
- }
- }
- }, 10);
- };
- // 创建自定义高亮
- const createCustomHighlight = () => {
- if (!savedSelection.value || !savedSelection.value.range) {
- return;
- }
-
- try {
- const range = savedSelection.value.range;
- const rects = range.getClientRects(); // 使用 getClientRects() 获取多个矩形
-
- // 移除之前的高亮元素
- removeCustomHighlight();
-
- // 如果没有矩形或矩形为空,则使用 getBoundingClientRect() 作为备选
- if (!rects || rects.length === 0) {
- const rect = range.getBoundingClientRect();
- if (rect.width === 0 || rect.height === 0) {
- console.log("选区矩形为空,跳过高亮创建");
- return;
- }
-
- // 创建单个高亮元素
- const highlightElement = document.createElement('div');
- highlightElement.className = 'custom-selection-highlight';
- highlightElement.style.cssText = `
- position: fixed;
- left: ${rect.left}px;
- top: ${rect.top}px;
- width: ${rect.width}px;
- height: ${rect.height}px;
- background-color: rgba(59, 130, 246, 0.2);
- border: 1px solid rgba(59, 130, 246, 0.5);
- border-radius: 2px;
- pointer-events: none;
- z-index: 998;
- transition: all 0.2s ease;
- `;
-
- document.body.appendChild(highlightElement);
- customHighlightElement.value = [highlightElement];
- console.log("自定义高亮创建成功(单个矩形)");
- return;
- }
-
- // 为每个矩形创建高亮元素(多行选择)
- const highlightElements = [];
- for (let i = 0; i < rects.length; i++) {
- const rect = rects[i];
-
- // 跳过宽度或高度为0的矩形
- if (rect.width === 0 || rect.height === 0) {
- continue;
- }
-
- const highlightElement = document.createElement('div');
- highlightElement.className = 'custom-selection-highlight';
- highlightElement.style.cssText = `
- position: fixed;
- left: ${rect.left}px;
- top: ${rect.top}px;
- width: ${rect.width}px;
- height: ${rect.height}px;
- background-color: rgba(59, 130, 246, 0.2);
- border: 1px solid rgba(59, 130, 246, 0.5);
- border-radius: 2px;
- pointer-events: none;
- z-index: 998;
- transition: all 0.2s ease;
- `;
-
- document.body.appendChild(highlightElement);
- highlightElements.push(highlightElement);
- }
-
- // 保存所有高亮元素的引用
- customHighlightElement.value = highlightElements;
-
- console.log(`自定义高亮创建成功(${highlightElements.length}个矩形)`);
- } catch (error) {
- console.error("创建自定义高亮失败:", error);
- }
- };
- // 移除自定义高亮
- const removeCustomHighlight = () => {
- if (customHighlightElement.value) {
- try {
- // 处理多个高亮元素(数组)
- if (Array.isArray(customHighlightElement.value)) {
- customHighlightElement.value.forEach(element => {
- try {
- if (element && element.parentNode) {
- document.body.removeChild(element);
- }
- } catch (e) {
- console.error("移除单个高亮元素失败:", e);
- }
- });
- console.log(`自定义高亮移除成功(${customHighlightElement.value.length}个矩形)`);
- } else {
- // 处理单个高亮元素(向后兼容)
- if (customHighlightElement.value.parentNode) {
- document.body.removeChild(customHighlightElement.value);
- }
- console.log("自定义高亮移除成功");
- }
- customHighlightElement.value = null;
- } catch (error) {
- console.error("移除自定义高亮失败:", error);
- }
- }
- };
- // 隐藏扩写输入框和高亮框
- const hidePolishInput = () => {
- showPolishInput.value = false;
- selectedText.value = "";
- polishCustomPrompt.value = "";
- polishingType.value = ''; // 重置操作类型
- showCustomHighlight.value = false;
- removeCustomHighlight();
- savedSelection.value = null; // 清除保存的选区
- };
- // 处理AI扩写
- const handlePolishText = async () => {
- if (!selectedText.value.trim() || isPolishing.value) {
- return;
- }
-
- try {
- isPolishing.value = true;
- polishingType.value = 'polish'; // 设置为扩写类型
-
- // 构建扩写提示词
- let polishPrompt = `请对以下文本进行扩写,要求:
- 1. 保持原文的核心意思和逻辑结构
- 2. 提升语言的流畅性和专业性
- 3. 优化表达方式,使其更加准确和生动
- 4. 保持原文的语调和风格
- 5. 只返回扩写后的文本,不要添加任何解释或说明`;
- // 如果用户有自定义要求,使用用户的要求
- if (polishCustomPrompt.value.trim()) {
- polishPrompt = `请根据以下要求对文本进行处理:${polishCustomPrompt.value.trim()}
- 要求:
- 1. 保持原文的核心意思和逻辑结构
- 2. 只返回处理后的文本,不要添加任何解释或说明`;
- }
- polishPrompt += `\n\n原文:\n${selectedText.value}`;
- // 调用AI扩写接口
- const response = await apis.reProduceSingleQuestion({
- message: polishPrompt
- });
-
- if (response && response.data && response.data.reply) {
- const polishedText = response.data.reply.trim();
-
- // 使用保存的选区信息或当前选区进行扩写
- if (editorRef.value) {
- try {
- let currentSelection = null;
- let selectedText = "";
-
- // 优先使用当前选区
- const selection = window.getSelection();
- if (selection && selection.toString().trim()) {
- currentSelection = selection;
- selectedText = selection.toString();
- console.log("使用当前选区:", selectedText);
- }
- // 如果当前选区为空,使用保存的选区信息
- else if (savedSelection.value && savedSelection.value.text) {
- selectedText = savedSelection.value.text;
- console.log("使用保存的选区:", selectedText);
- }
-
- if (selectedText) {
- // 检查是否为多格式文本
- // if (savedSelection.value && savedSelection.value.isMultiFormat) {
- // console.log("检测到多格式文本,不建议进行润色");
- // ElMessage.warning("不建议选取多字体进行润色,会造成后续文字结构变化");
- // return;
- // }
-
- // 如果有保存的选区,优先使用wangeditor的API进行精确替换
- if (savedSelection.value && savedSelection.value.range) {
- try {
- // 使用wangeditor的API而不是直接操作DOM,避免与Slate状态冲突
- const editor = editorRef.value;
-
- // 先尝试使用wangeditor的选区恢复API
- if (editor.restoreSelection && typeof editor.restoreSelection === 'function') {
- editor.restoreSelection(savedSelection.value.range);
-
- // 使用wangeditor的insertText方法,它会自动处理Slate状态同步
- editor.insertText(polishedText);
-
- console.log("扩写完成,通过wangeditor restoreSelection + insertText API");
- ElMessage.success("文本扩写完成");
- return;
- } else {
- // 如果restoreSelection不可用,使用字符串替换策略
- throw new Error("wangeditor restoreSelection API不可用");
- }
- } catch (insertError) {
- console.error("使用wangeditor API替换失败,尝试字符串替换:", insertError);
- }
- }
-
- // 如果有当前选区,使用wangeditor的insertText方法
- if (currentSelection) {
- try {
- // 获取当前选区
- const range = currentSelection.getRangeAt(0);
-
- // 检查选区是否在编辑器内
- const editorElement = editorRef.value.getEditableContainer();
- if (editorElement && editorElement.contains(range.commonAncestorContainer)) {
- // 使用wangeditor的insertText方法替换选中内容
- editorRef.value.insertText(polishedText);
- console.log("扩写完成,通过wangeditor insertText API");
-
- // 清除选择
- currentSelection.removeAllRanges();
- return;
- } else {
- throw new Error("选区不在编辑器内");
- }
- } catch (insertError) {
- console.log("insertText失败,尝试字符串替换:", insertError);
- }
- }
-
- // 降级方案:使用字符串替换
- const currentHtml = editorRef.value.getHtml();
- console.log("扩写前内容长度:", currentHtml.length);
-
- let newHtml = currentHtml;
- let replaced = false;
-
- // 添加调试信息
- console.log("扩写调试信息:", {
- selectedText: selectedText,
- currentHtmlLength: currentHtml.length,
- savedSelection: savedSelection.value,
- hasCurrentSelection: !!currentSelection
- });
-
- // 尝试多种替换策略
- // 策略1:使用保存的HTML结构进行精确替换(适用于多格式文本)
- // 为了处理HTML实体编码问题,这里需要对selectedText进行HTML解码再进行比较
- const decodedSelectedHtml = savedSelection.value?.html ? new DOMParser().parseFromString(savedSelection.value.html, 'text/html').documentElement.textContent : '';
- if (savedSelection.value && savedSelection.value.html && (currentHtml.includes(savedSelection.value.html) || currentHtml.includes(decodedSelectedHtml))) {
- if (currentHtml.includes(savedSelection.value.html)) {
- newHtml = currentHtml.replace(savedSelection.value.html, polishedText);
- replaced = true;
- console.log("策略1成功:通过保存的HTML结构替换");
- } else if (currentHtml.includes(decodedSelectedHtml)) {
- newHtml = currentHtml.replace(decodedSelectedHtml, polishedText);
- replaced = true;
- console.log("策略1成功:通过解码后的HTML结构替换");
- }
- }
- // 策略1.5:使用保存的纯文本进行替换(适用于多格式文本)
- else if (savedSelection.value && savedSelection.value.plainText && currentHtml.includes(savedSelection.value.plainText)) {
- newHtml = currentHtml.replace(savedSelection.value.plainText, polishedText);
- replaced = true;
- console.log("策略1.5成功:通过保存的纯文本替换");
- }
- // 策略2:直接字符串替换
- else if (currentHtml.includes(selectedText)) {
- newHtml = currentHtml.replace(selectedText, polishedText);
- replaced = true;
- console.log("策略2成功:直接字符串替换");
- }
- // 策略3:HTML实体替换
- else {
- const htmlEntities = selectedText
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
-
- console.log("策略3尝试:HTML实体替换", {
- htmlEntities: htmlEntities,
- includes: currentHtml.includes(htmlEntities)
- });
-
- if (currentHtml.includes(htmlEntities)) {
- newHtml = currentHtml.replace(htmlEntities, polishedText);
- replaced = true;
- console.log("策略3成功:HTML实体替换");
- } else {
- // 策略4:正则表达式匹配
- const regex = new RegExp(`>[^<]*${selectedText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^<]*<`, 'g');
- const match = currentHtml.match(regex);
- console.log("策略4尝试:正则表达式匹配", {
- regex: regex,
- match: match
- });
-
- if (match) {
- newHtml = currentHtml.replace(match[0], match[0].replace(selectedText, polishedText));
- replaced = true;
- console.log("策略4成功:正则表达式替换");
- }
- // 策略5:尝试模糊匹配(移除HTML标签后匹配)
- else {
- // 清理文本,移除HTML标签进行模糊匹配
- const cleanText = selectedText.replace(/<[^>]*>/g, '').trim();
- const cleanCurrentHtml = currentHtml.replace(/<[^>]*>/g, '');
-
- console.log("策略5尝试:模糊匹配", {
- cleanText: cleanText,
- cleanCurrentHtml: cleanCurrentHtml.substring(0, 200) + '...',
- includes: cleanCurrentHtml.includes(cleanText)
- });
-
- if (cleanCurrentHtml.includes(cleanText)) {
- // 找到包含选中文本的HTML片段进行替换
- const regex = new RegExp(`[^>]*${cleanText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[^<]*`, 'g');
- const match = currentHtml.match(regex);
- if (match) {
- newHtml = currentHtml.replace(match[0], match[0].replace(cleanText, polishedText));
- replaced = true;
- console.log("策略5成功:通过模糊匹配替换");
- }
- }
- }
- }
- }
-
- if (replaced) {
- // 设置新的内容到编辑器,并确保wangeditor状态同步
- try {
- editorRef.value.setHtml(newHtml);
-
- // 强制刷新编辑器状态,避免Slate状态不同步
- setTimeout(() => {
- try {
- // 触发编辑器内容变化事件,确保内部状态更新
- const editorElement = editorRef.value.getEditableContainer();
- if (editorElement) {
- // 触发input事件,让wangeditor知道内容已变化
- const inputEvent = new Event('input', { bubbles: true });
- editorElement.dispatchEvent(inputEvent);
- }
- } catch (syncError) {
- console.log("编辑器状态同步失败:", syncError);
- }
- }, 10);
-
- console.log("润色后内容长度:", newHtml.length);
- console.log("润色完成,通过字符串替换");
- console.log("润色后内容预览:", newHtml.substring(0, 200) + '...');
- } catch (setHtmlError) {
- console.error("设置编辑器内容失败:", setHtmlError);
- ElMessage.error("润色失败,请重试");
- return;
- }
- } else {
- console.log("所有替换策略都失败,未找到匹配的文本");
- ElMessage.warning("未找到选中的文本,请重新选择");
- return;
- }
- } else {
- console.log("没有找到选中的文本");
- ElMessage.warning("请先选择要润色的文本");
- return;
- }
- } catch (error) {
- console.error("润色失败:", error);
- ElMessage.error("润色失败,请重试");
- return;
- }
- }
-
- ElMessage.success("文本润色完成");
- console.log("文本润色完成");
- } else {
- ElMessage.error("润色失败,请重试");
- }
- } catch (error) {
- console.error("AI润色失败:", error);
- ElMessage.error("润色失败,请检查网络连接");
- } finally {
- isPolishing.value = false;
- polishingType.value = ''; // 重置操作类型
- hidePolishInput();
- }
- };
- // 处理AI续写
- const handleContinueText = async () => {
- if (!selectedText.value.trim() || isPolishing.value) {
- return;
- }
-
- try {
- isPolishing.value = true;
- polishingType.value = 'continue'; // 设置为续写类型
-
- // 构建续写提示词
- let continuePrompt = `请对以下文本进行续写,要求:
- 1. 保持原文的语调和风格
- 2. 在原文基础上自然延续,【重要】绝对不要重复原文内容
- 3. 续写的内容应该与原文逻辑连贯
- 4. 增加新的内容,使文章更加完整
- 5. 【重要】只返回续写的内容,不要包含原文,不要添加任何解释或说明
- 6. 【重要】直接开始续写新内容,不要重复原文的最后几个字
- 7. 如果AI无法理解或续写,请返回"无法续写"`;
- // 如果用户有自定义要求,使用用户的要求
- if (polishCustomPrompt.value.trim()) {
- continuePrompt = `请根据以下要求对文本进行续写:${polishCustomPrompt.value.trim()}
- 要求:
- 1. 保持原文的语调和风格
- 2. 【重要】只返回续写的内容,不要包含原文,不要添加任何解释或说明
- 3. 【重要】直接开始续写新内容,不要重复原文
- 4. 如果AI无法理解或续写,请返回"无法续写"`;
- }
- continuePrompt += `\n\n原文:\n${selectedText.value}\n\n请直接开始续写,不要重复原文:`;
- // 调用AI续写接口
- const response = await apis.reProduceSingleQuestion({
- message: continuePrompt
- });
-
- if (response && response.data && response.data.reply) {
- let continuedText = response.data.reply.trim();
-
- console.log("AI返回的原始续写内容:", continuedText);
- console.log("原文:", selectedText.value);
-
- // 处理AI幻觉:如果返回的内容包含原文,则提取续写部分
- if (continuedText.includes(selectedText.value)) {
- console.log("AI返回内容包含原文,开始提取纯续写部分");
- // 找到原文在续写内容中的位置
- const originalTextIndex = continuedText.indexOf(selectedText.value);
- if (originalTextIndex !== -1) {
- // 提取原文后面的部分作为续写内容
- continuedText = continuedText.substring(originalTextIndex + selectedText.value.length).trim();
- console.log("提取后的纯续写内容:", continuedText);
- }
- } else {
- console.log("AI返回内容不包含原文,直接使用");
- }
-
- // 额外处理:移除可能的常见前缀(如"续写:"、"续写内容:"等)
- const prefixPatterns = [
- /^续写[::]/,
- /^续写内容[::]/,
- /^续写部分[::]/,
- /^以下是续写[::]/,
- /^以下是续写内容[::]/
- ];
-
- for (const pattern of prefixPatterns) {
- if (pattern.test(continuedText)) {
- continuedText = continuedText.replace(pattern, '').trim();
- console.log("移除前缀后的续写内容:", continuedText);
- break;
- }
- }
-
- // 如果续写内容为空或包含"无法续写",则提示用户
- if (!continuedText || continuedText === "无法续写" || continuedText.length < 2) {
- ElMessage.warning("AI无法续写此内容,请尝试其他文本或调整要求");
- return;
- }
-
- console.log("最终使用的续写内容:", continuedText);
-
- // 使用光标位置插入法:直接在选区末尾插入续写内容
- if (editorRef.value) {
- try {
- console.log("续写调试信息:", {
- selectedText: selectedText.value,
- continuedText: continuedText,
- hasSavedRange: !!savedSelection.value?.range,
- savedSelection: savedSelection.value
- });
-
- // 策略1:使用保存的Range,在选区末尾插入内容
- if (savedSelection.value && savedSelection.value.range) {
- try {
- const range = savedSelection.value.range;
- const editorElement = editorRef.value.getEditableContainer();
-
- // 确保Range在编辑器内
- if (editorElement && editorElement.contains(range.endContainer)) {
- // 创建一个新Range,定位到原选区的末尾
- const newRange = document.createRange();
- newRange.setStart(range.endContainer, range.endOffset);
- newRange.setEnd(range.endContainer, range.endOffset);
-
- // 在末尾位置插入一个文本节点
- const textNode = document.createTextNode(continuedText);
- newRange.insertNode(textNode);
-
- // 移动光标到插入内容的末尾
- newRange.setStartAfter(textNode);
- newRange.collapse(true);
-
- // 更新编辑器选区
- const selection = window.getSelection();
- if (selection) {
- selection.removeAllRanges();
- selection.addRange(newRange);
- }
-
- // 触发编辑器内容变化事件
- setTimeout(() => {
- try {
- const inputEvent = new Event('input', { bubbles: true });
- editorElement.dispatchEvent(inputEvent);
- } catch (e) {
- console.log("触发input事件失败:", e);
- }
- }, 10);
-
- console.log("续写成功:通过Range在选区末尾插入文本节点");
- ElMessage.success("文本续写完成");
- return;
- } else {
- console.log("Range不在编辑器内,尝试其他策略");
- }
- } catch (rangeError) {
- console.error("使用Range插入失败:", rangeError);
- }
- }
-
- // 策略2:使用HTML结构匹配(作为备选方案)
- const currentHtml = editorRef.value.getHtml();
- let newHtml = currentHtml;
- let replaced = false;
-
- // 如果有保存的HTML结构,直接在其后添加续写内容
- if (savedSelection.value && savedSelection.value.html && currentHtml.includes(savedSelection.value.html)) {
- const htmlWithContinue = savedSelection.value.html + continuedText;
- newHtml = currentHtml.replace(savedSelection.value.html, htmlWithContinue);
- replaced = true;
- console.log("续写成功:通过HTML结构匹配添加续写");
- }
- // 如果有保存的纯文本,进行文本匹配
- else if (savedSelection.value && savedSelection.value.plainText && currentHtml.includes(savedSelection.value.plainText)) {
- const textWithContinue = savedSelection.value.plainText + continuedText;
- newHtml = currentHtml.replace(savedSelection.value.plainText, textWithContinue);
- replaced = true;
- console.log("续写成功:通过纯文本匹配添加续写");
- }
- // 直接使用选中的文本进行匹配
- else if (currentHtml.includes(selectedText.value)) {
- const textWithContinue = selectedText.value + continuedText;
- newHtml = currentHtml.replace(selectedText.value, textWithContinue);
- replaced = true;
- console.log("续写成功:通过直接文本匹配添加续写");
- }
-
- if (replaced) {
- editorRef.value.setHtml(newHtml);
-
- // 强制刷新编辑器状态
- setTimeout(() => {
- try {
- const editorElement = editorRef.value.getEditableContainer();
- if (editorElement) {
- const inputEvent = new Event('input', { bubbles: true });
- editorElement.dispatchEvent(inputEvent);
- }
- } catch (syncError) {
- console.log("编辑器状态同步失败:", syncError);
- }
- }, 10);
-
- console.log("续写完成");
- ElMessage.success("文本续写完成");
- } else {
- console.error("所有策略都失败了");
- console.log("续写失败调试信息:", {
- selectedText: selectedText.value,
- savedSelectionHtml: savedSelection.value?.html,
- savedSelectionPlainText: savedSelection.value?.plainText,
- currentHtmlPreview: currentHtml.substring(0, 500)
- });
- ElMessage.error("续写失败,无法找到选中的文本");
- }
- } catch (error) {
- console.error("续写过程中发生错误:", error);
- ElMessage.error("续写失败,请重试");
- }
- } else {
- console.error("编辑器引用不存在");
- ElMessage.error("续写失败,编辑器未初始化");
- }
- } else {
- ElMessage.error("续写失败,请重试");
- }
- } catch (error) {
- console.error("AI续写失败:", error);
- ElMessage.error("续写失败,请检查网络连接");
- } finally {
- isPolishing.value = false;
- polishingType.value = ''; // 重置操作类型
- hidePolishInput();
- }
- };
- // 格式化内容为富文本编辑器格式 - 简化版本,直接使用 wangeditor
- const formatContentForEditor = (content) => {
- if (!content) return "";
- console.log('formatContentForEditor 输入内容:', content);
-
- console.log('formatContentForEditor 输入内容长度:', content.length);
- console.log('formatContentForEditor 输入内容预览:', content.substring(0, 200) + '...');
-
- // 检测是否为 HTML 格式
- const isHTML = /<[^>]+>/.test(content);
- console.log('检测到HTML格式:', isHTML);
-
- if (isHTML) {
- console.log('直接使用后端返回的HTML内容,无需转换');
- // 直接返回后端生成的HTML内容,wangeditor 可以直接处理
- return content;
- }
-
- // 如果不是 HTML,按普通文本处理
- console.log('按普通文本处理');
- return formatPlainText(content);
- };
- // 普通文本格式化函数
- const formatPlainText = (content) => {
- console.log('开始普通文本处理,内容长度:', content.length);
-
- // 先处理换行符,保持原始结构
- let formatted = content
- .replace(/\n\n\n+/g, '\n\n') // 多个连续换行合并为双换行
- .replace(/\n\n/g, '</p><p>') // 双换行转换为段落
- .replace(/\n/g, '<br>'); // 单换行转换为换行符
-
- // 包装在段落标签中
- if (formatted.trim()) {
- formatted = '<p>' + formatted + '</p>';
- }
-
- // 处理标题格式
- formatted = formatted
- .replace(/<p>(第[一二三四五六七八九十\d]+章[^<]*)<\/p>/g, '<h2>$1</h2>')
- .replace(/<p>(\d+\.\d+[^<]*)<\/p>/g, '<h3>$1</h3>')
- .replace(/<p>(\d+\.\d+\.\d+[^<]*)<\/p>/g, '<h4>$1</h4>')
- .replace(/<p>(一、[^<]*)<\/p>/g, '<h3>$1</h3>')
- .replace(/<p>(二、[^<]*)<\/p>/g, '<h3>$1</h3>')
- .replace(/<p>(三、[^<]*)<\/p>/g, '<h3>$1</h3>')
- .replace(/<p>(四、[^<]*)<\/p>/g, '<h3>$1</h3>')
- .replace(/<p>(五、[^<]*)<\/p>/g, '<h3>$1</h3>');
-
- // 清理空段落
- formatted = formatted.replace(/<p><\/p>/g, '');
- formatted = formatted.replace(/<p>\s*<\/p>/g, '');
-
- console.log('普通文本处理后内容长度:', formatted.length);
- console.log('普通文本处理后内容预览:', formatted.substring(0, 200) + '...');
-
- return formatted;
- };
- // 专门处理包含"-"符号的文本,避免被误认为Markdown列表
- const formatTextWithDashes = (content) => {
- console.log('开始处理包含"-"符号的文本,内容长度:', content.length);
-
- // 先转义所有"-"符号,避免被marked误认为列表
- let processedContent = content.replace(/^- /gm, '\\- '); // 转义行首的"- "
-
- // 然后进行普通文本处理
- return formatPlainText(processedContent);
- };
- // wangeditor 可以直接处理 HTML,无需额外转换
- // 切换标签
- const switchTab = (tabKey) => {
- activeTab.value = tabKey;
- console.log("切换到标签:", tabKey);
- };
- // 使用模板
- const useTemplate = (templateName) => {
- console.log("使用模板:", templateName);
-
- // 根据模板名称填充对应的模板内容
- let content = "";
-
- switch (templateName) {
- case "通知模板":
- content = "<span class=\"editable-highlight\" contenteditable=\"true\">通知主题:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">通知对象:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">具体事项:</span>\n\n请帮我生成一份正式的通知,要求格式规范、语言严谨,具体参考以上内容,按照标准公文格式生成完整通知,包括文号、标题、正文、落款等所有要素。";
- break;
- case "公告模板":
- content = "<span class=\"editable-highlight\" contenteditable=\"true\">公告主题:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">发文单位:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">核心内容:</span>\n\n请帮我生成一份正式的公告,要求格式规范、语言严谨,具体参考以上内容,按照标准公告格式生成全文,包括标题、正文、落款等所有要素。";
- break;
- case "会议纪要模版":
- content = "<span class=\"editable-highlight\" contenteditable=\"true\">会议主题:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">会议时间:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">主要议题:</span>\n\n请帮我生成一份正式的会议纪要,要求格式规范、语言严谨,具体参考以上内容,按照标准会议纪要格式生成全文,包含标题、导语、议定事项和落款。";
- break;
- case "决定模版":
- content = "<span class=\"editable-highlight\" contenteditable=\"true\">决定主题:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">决定依据:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">决定内容:</span>\n\n请帮我生成一份正式的决定,要求格式规范、语言严谨,具体参考以上内容,按照标准决定公文格式生成完整文件。";
- break;
- case "工作汇报模板":
- content = "<span class=\"editable-highlight\" contenteditable=\"true\">总结主题:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">总结时间:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">主要内容:</span>\n\n请帮我生成一份正式的总结报告,要求格式规范、语言严谨,具体参考以上内容,按照标准工作总结格式生成全文,包含\"工作总结、问题不足、未来计划\"三部分的完整报告。";
- break;
- default:
- content = "<span class=\"editable-highlight\" contenteditable=\"true\">公告主题:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">发文单位:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">核心内容:</span>\n\n请帮我生成一份正式的公告,要求格式规范、语言严谨,具体参考以上内容,按照标准公告格式生成全文,包括标题、正文、落款等所有要素。";
- }
-
- // 将模板内容填充到输入框中
- const inputElement = document.querySelector('.template-input-container');
- if (inputElement) {
- // 使用更安全的方式设置HTML内容
- inputElement.innerHTML = content;
-
- // 同时更新templateContent.value,确保发送时使用正确的模板内容
- templateContent.value = content.replace(/<[^>]*>/g, ''); // 移除HTML标签,保留纯文本
-
- // 确保所有editable-highlight元素都有正确的样式
- const highlights = inputElement.querySelectorAll('.editable-highlight');
- highlights.forEach(highlight => {
- highlight.style.backgroundColor = '#3E7BFA10';
- highlight.style.color = '#3E7BFA';
- highlight.style.padding = '4px 8px';
- highlight.style.borderRadius = '6px';
- highlight.style.fontWeight = '500';
- highlight.style.cursor = 'text';
- highlight.style.border = '1px solid transparent';
- highlight.style.display = 'inline-block';
- highlight.style.minWidth = '20px';
- });
-
- inputElement.focus();
-
- // 将光标移动到末尾
- const range = document.createRange();
- const selection = window.getSelection();
- range.selectNodeContents(inputElement);
- range.collapse(false);
- selection.removeAllRanges();
- selection.addRange(range);
-
- console.log('模板已应用,templateContent更新为:', templateContent.value);
- }
- };
- // 当前选中的文档信息
- const selectedDocument = ref(null);
- // 切换文档预览状态
- const toggleDocumentPreview = (documentInfo) => {
- // 如果点击的是当前已选中的文档,则关闭预览
- if (selectedDocument.value && selectedDocument.value === documentInfo) {
- showDocumentPreview.value = false;
- selectedDocument.value = null;
- } else {
- // 否则显示新选中的文档
- selectedDocument.value = documentInfo;
- showDocumentPreview.value = true;
- }
- console.log("切换文档预览状态:", showDocumentPreview.value, "选中文档:", selectedDocument.value);
- };
- // 关闭文档预览
- const closeDocumentPreview = () => {
- showDocumentPreview.value = false;
- selectedDocument.value = null;
- console.log("关闭文档预览");
- };
- // 发送AI写作请求
- const sendAIWritingRequest = async () => {
- if (!hasInputContent.value) {
- console.log("请输入内容");
- return;
- }
-
- // 保存文件引用,因为后面需要传递给AI
- const currentFile = selectedFile.value;
-
- // 直接进入富文本编辑器并显示loading
- currentView.value = 'editor';
- isGenerating.value = true;
-
- // 重置文档预览状态,确保界面恢复全屏
- showDocumentPreview.value = false;
- selectedDocument.value = null;
-
- // 注意:不要在这里清空文件,因为后面创建消息时还需要使用
-
- // 如果是新对话,清除所有历史记录的选中状态
- if (historyData.value.length === 0 || !historyData.value.some(item => item.isActive)) {
- historyData.value.forEach((item) => {
- item.isActive = false;
- });
- console.log('新对话开始,清除所有历史记录的选中状态');
- }
-
- // 创建临时的历史记录项用于显示用户消息
- const tempHistoryItem = {
- id: Date.now(),
- title: generateTitleFromContent(fullInputText.value),
- time: new Date().toLocaleString('zh-CN', {
- hour: '2-digit',
- minute: '2-digit'
- }),
- isActive: false,
- hasDocument: false,
- documentContent: null,
- aiResponse: "",
- userMessage: fullInputText.value,
- file: currentFile, // 使用保存的文件引用
- messages: [
- {
- type: 'user',
- content: fullInputText.value,
- file: currentFile, // 使用保存的文件引用
- time: new Date().toLocaleString('zh-CN', {
- hour: '2-digit',
- minute: '2-digit'
- }),
- id: Date.now(),
- isFromBackend: false // 标记这是新创建的消息
- }
- ]
- };
-
- console.log("创建临时历史记录项,文件信息:", currentFile);
-
- // 设置选中的历史记录项,这样用户消息就能显示出来
- selectedHistoryItem.value = tempHistoryItem;
-
- // 现在可以清空选中的文件了,因为已经保存到消息中
- if (selectedFile.value) {
- removeSelectedFile();
- }
-
- console.log("发送AI写作请求:");
- console.log("完整文本:", fullInputText.value);
- console.log("目的:", purposeText.value);
- console.log("内容:", contentText.value);
- console.log("额外:", templateContent.value);
-
- // 在详情页中调用AI
- await callAIInDetail(tempHistoryItem, null, fullInputText.value, currentFile);
- };
- // 智能提示词生成
- const generateSmartPrompt = () => {
- // 不做意图判断,让AI自己判断用户需求,但要求按照固定格式
- return `请根据用户的需求进行回复。
- 如果用户需要文档,请严格按照以下格式回复:
- <OPENING_START>
- 以下是为您准备的文档,包含相关内容:
- </OPENING_END>
- <DOCUMENT_START>
- [在这里生成完整的Word文档内容,必须包含:
- 1. 文档标题(使用#标记)
- 2. 多个章节(使用##标记)
- 3. 详细内容(使用Markdown格式,支持大小标题、换行、列表、加粗、斜体等富文本效果)
- 4. 确保内容完整,不要中途停止]
- </DOCUMENT_END>
- <CLOSING_START>
- 以上文档采用专业的格式编写,符合办公文档要求。如需调整内容或格式,请告诉我具体需求。
- </CLOSING_END>
- 如果是普通问题,请直接回答,不要使用上述格式。
- 重要提醒:
- 1. 如果生成文档,必须包含三个标签区域:<OPENING_START>开头文本</OPENING_END>、<DOCUMENT_START>文档内容</DOCUMENT_END>、<CLOSING_START>结尾文本</CLOSING_END>
- 2. 确保每个区域都完整,特别是结尾部分不能缺失
- 3. 标签必须严格按照上述格式,不能有任何变化
- 4. 文档内容中不要使用emoji表情符号
- 5. 如果用户明确要求生成文档、报告、通知、方案等办公文档,必须使用上述格式
- 6. 标签名称区分大小写,必须完全匹配
- 示例正确格式:
- <OPENING_START>
- 以下是为您准备的文档,包含相关内容:
- </OPENING_END>
- <DOCUMENT_START>
- # 文档标题
- ## 第一章 概述
- 详细内容...
- ## 第二章 具体内容
- 详细内容...
- </DOCUMENT_END>
- <CLOSING_START>
- 以上文档采用专业的格式编写,符合办公文档要求。如需调整内容或格式,请告诉我具体需求。
- </CLOSING_END>`;
- };
- // 处理模板输入框的input事件
- const handleTemplateInput = (event) => {
- // 清除之前的定时器
- if (debounceTimer) {
- clearTimeout(debounceTimer);
- }
-
- // 设置防抖延迟
- debounceTimer = setTimeout(async () => {
- // 使用nextTick确保DOM更新完成
- await nextTick();
-
- // 获取可编辑区域的纯文本内容,不包含HTML标签
- const text = event.target.innerText || event.target.textContent || '';
-
- // 更新模板内容
- templateContent.value = text;
-
- // 如果文本为空,确保光标在开头
- if (!text.trim()) {
- await nextTick();
- // 将光标移动到开头
- const selection = window.getSelection();
- const range = document.createRange();
-
- // 确保有子节点
- if (event.target.firstChild) {
- range.setStart(event.target.firstChild, 0);
- } else {
- // 如果没有子节点,直接设置到容器
- range.setStart(event.target, 0);
- }
-
- range.collapse(true);
- selection.removeAllRanges();
- selection.addRange(range);
-
- // 聚焦到输入框
- event.target.focus();
- }
- }, 200); // 防抖延迟200ms
- };
- // 处理复制事件
- const handleCopy = (event) => {
- // 获取复制的内容
- const copiedText = event.target.innerText || event.target.textContent;
- // 将复制的内容设置到剪贴板
- event.clipboardData.setData('text/plain', copiedText);
- // 阻止默认的浏览器复制行为
- event.preventDefault();
- console.log("复制成功:", copiedText);
- };
- // 文件处理工具函数
- const validateFile = (file) => {
- // 检查文件大小
- if (file.size > fileConfig.maxSize) {
- throw new Error('文件大小不能超过20MB')
- }
-
- // 检查文件类型
- const fileExtension = '.' + file.name.split('.').pop().toLowerCase()
- if (!fileConfig.allowedTypes.includes(fileExtension)) {
- throw new Error('只支持.docx格式的Word文档。如果是.doc格式,请先另存为.docx格式。')
- }
-
- return fileExtension
- }
- // 读取Word文件内容
- const readWordFile = async (file) => {
- try {
- console.log('开始读取Word文件:', file.name, '文件大小:', file.size)
-
- // 检查文件是否为空
- if (file.size === 0) {
- throw new Error('Word文件为空')
- }
-
- // 使用mammoth.js库读取Word文档
- console.log('正在导入mammoth库...')
- const mammoth = await import('mammoth')
- console.log('mammoth库导入成功')
-
- // 将文件转换为ArrayBuffer
- const arrayBuffer = await file.arrayBuffer()
- console.log('文件转换为ArrayBuffer成功,大小:', arrayBuffer.byteLength)
-
- // 提取文本内容
- console.log('开始提取文本内容...')
- const result = await mammoth.extractRawText({ arrayBuffer })
-
- console.log('Word文件读取完成,内容长度:', result.value.length)
- return result.value
-
- } catch (error) {
- console.error('Word文件读取失败,详细错误:', error)
- console.error('错误堆栈:', error.stack)
-
- // 提供更具体的错误信息
- if (error.message.includes('Invalid file format')) {
- throw new Error('Word文件格式无效或已损坏')
- } else if (error.message.includes('File is empty')) {
- throw new Error('Word文件为空')
- } else {
- throw new Error(`Word文件读取失败: ${error.message}`)
- }
- }
- }
- // 处理文件标签格式的回显
- const processFileDisplay = (text, file) => {
- if (!file) {
- // 如果没有文件对象,尝试从文本中提取文件信息
- return processFileDisplayFromText(text)
- }
-
- // 查找文件标签并替换为显示格式
- const fileDisplay = `
- 📄 文件信息:
- 文件名:${file.name}
- 文件大小:${formatFileSize(file.size)}
- 文件类型:${file.type}
- 📝 文件内容:
- ${file.content}
- ---
- `
-
- // 替换文件标签为显示格式
- let processedText = text
- .replace(/<word>.*?<\/word>/gs, fileDisplay)
- .replace(/<filename>.*?<\/filename>/g, '')
- .replace(/<filesize>.*?<\/filesize>/g, '')
-
- return processedText
- }
- // 从文本中提取文件信息并转换为显示格式
- const processFileDisplayFromText = (text) => {
- // 提取文件名
- const filenameMatch = text.match(/<filename>(.*?)<\/filename>/)
- const filename = filenameMatch ? filenameMatch[1] : '未知文件'
-
- // 提取文件大小
- const filesizeMatch = text.match(/<filesize>(.*?)<\/filesize>/)
- const filesize = filesizeMatch ? parseInt(filesizeMatch[1]) : 0
-
- // 提取文件内容
- const wordMatch = text.match(/<word>(.*?)<\/word>/s)
- const fileContent = wordMatch ? wordMatch[1].trim() : '无内容'
-
- // 创建文件显示格式
- const fileDisplay = `
- 📄 文件信息:
- 文件名:${filename}
- 文件大小:${formatFileSize(filesize)}
- 文件类型:${filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '未知'}
- 📝 文件内容:
- ${fileContent}
- ---
- `
-
- // 替换文件标签为显示格式
- let processedText = text
- .replace(/<word>.*?<\/word>/gs, fileDisplay)
- .replace(/<filename>.*?<\/filename>/g, '')
- .replace(/<filesize>.*?<\/filesize>/g, '')
-
- return processedText
- }
- // 文件上传相关方法
- const triggerFileUpload = () => {
- if (selectedFile.value) {
- ElMessage.warning('只能上传一个文件,请先删除当前文件');
- return;
- }
- fileInput.value?.click();
- };
- const handleFileSelect = async (event) => {
- const file = event.target.files[0];
- if (!file) return;
-
- try {
- // 验证文件
- const fileExtension = validateFile(file)
-
- isUploadingFile.value = true;
- console.log('开始读取文件内容:', file.name);
-
- // 只处理Word文档
- const extractedContent = await readWordFile(file)
-
- // 创建文件信息对象
- selectedFile.value = {
- file,
- name: file.name,
- size: file.size,
- type: fileExtension,
- icon: getFileIcon(fileExtension),
- content: extractedContent // 存储提取的内容
- }
-
- // 显示提取的内容长度
- const contentLength = extractedContent.length
- console.log('文件内容提取完成,字符数:', contentLength)
- ElMessage.success(`文件读取成功`)
-
- } catch (error) {
- console.error('文件读取失败:', error)
- ElMessage.error(error.message || '文件读取失败,请重试')
- } finally {
- isUploadingFile.value = false;
- event.target.value = '';
- }
- };
- const removeSelectedFile = () => {
- if (selectedFile.value) {
- selectedFile.value = null;
- }
- };
- // 获取文件图标
- const getFileIcon = (fileType) => {
- switch (fileType) {
- case '.doc':
- case '.docx':
- return wordDocIcon;
- default:
- return '📎';
- }
- };
- // 语音输入相关方法
- const handleVoiceClick = () => {
- console.log('点击语音按钮');
- if (isListening.value) {
- // 如果正在录音,则停止
- stopVoiceInput();
- } else {
- // 开始语音输入
- startVoiceInput();
- }
- };
- const startVoiceInput = () => {
- console.log('开始语音输入');
-
- // 开始语音识别
- const success = startListening();
- if (!success) {
- ElMessage.error('语音识别启动失败,请检查麦克风权限');
- }
- };
- const stopVoiceInput = () => {
- console.log('停止语音输入');
- stopListening();
-
- // 语音识别完成后,将结果填入输入框
- if (transcript.value.trim()) {
- // 根据当前视图决定填入哪个输入框
- if (currentView.value === 'detail') {
- // 如果在详情页,填入详情页输入框
- detailInputText.value = transcript.value;
- } else {
- // 如果在主页面,填入主页面输入框
- const inputElement = document.querySelector('.template-input-container');
- if (inputElement) {
- inputElement.textContent = transcript.value;
- templateContent.value = transcript.value;
- }
- }
- }
- };
- // 详情页输入处理方法
- const handleDetailInput = (event) => {
- // 清除之前的防抖定时器
- if (detailInputDebounceTimer) {
- clearTimeout(detailInputDebounceTimer);
- }
-
- // 设置防抖延迟
- detailInputDebounceTimer = setTimeout(() => {
- const currentValue = event.target.value;
-
- // 检查是否有重复字符(连续超过3个相同字符)
- const duplicatePattern = /(.)\1{3,}/g;
- if (duplicatePattern.test(currentValue)) {
- // 移除重复字符,只保留最多3个连续相同字符
- const cleanedValue = currentValue.replace(duplicatePattern, (match, char) => char.repeat(3));
- detailInputText.value = cleanedValue;
- ElMessage.warning('检测到重复字符,已自动清理');
- return;
- }
-
- // 长度限制
- if (currentValue.length > 2000) {
- detailInputText.value = currentValue.substring(0, 2000);
- ElMessage.warning('消息长度不能超过2000字');
- }
- }, 100); // 防抖延迟100ms
- };
- // 复制功能
- const copyToClipboard = async (text) => {
- try {
- await navigator.clipboard.writeText(text);
- ElMessage.success('复制成功');
- } catch (err) {
- // 降级方案:使用传统复制方法
- const textArea = document.createElement('textarea');
- textArea.value = text;
- document.body.appendChild(textArea);
- textArea.select();
- document.execCommand('copy');
- document.body.removeChild(textArea);
- ElMessage.success('复制成功');
- }
- };
- // 复制文档内容
- const copyDocumentContent = () => {
- // 优先从documentContent获取,如果没有则从AI消息的parsedContent获取
- let documentContent = selectedHistoryItem.value?.documentContent;
-
- if (!documentContent) {
- // 尝试从AI消息中获取文档内容
- const aiMessage = selectedHistoryItem.value?.messages?.find(msg => msg.type === 'ai' && msg.parsedContent?.hasDocument);
- if (aiMessage && aiMessage.parsedContent) {
- documentContent = aiMessage.parsedContent.documentContent;
- }
- }
-
- if (!documentContent) {
- ElMessage.warning('没有可复制的文档内容');
- return;
- }
-
- try {
- // 构建完整的文档内容
- let fullContent = '';
-
- // 添加标题
- if (documentContent.title) {
- fullContent += `${documentContent.title}\n\n`;
- }
-
- // 添加各个章节内容
- if (documentContent.sections) {
- documentContent.sections.forEach((section, index) => {
- fullContent += `${section.title}\n`;
- // 清理HTML标签,只保留纯文本
- const cleanContent = section.content.replace(/<[^>]*>/g, '');
- fullContent += `${cleanContent}\n\n`;
- });
- }
-
- // 去除markdown格式符号
- fullContent = removeMarkdownFormatting(fullContent);
-
- // 复制到剪贴板
- copyToClipboard(fullContent.trim());
-
- } catch (error) {
- console.error('复制文档内容失败:', error);
- ElMessage.error('复制失败,请重试');
- }
- };
- // 下载文档为Word格式(使用改进的HTML方法)
- const downloadDocumentAsWord = async () => {
- // 优先从documentContent获取,如果没有则从AI消息的parsedContent获取
- let documentContent = selectedHistoryItem.value?.documentContent;
-
- if (!documentContent) {
- // 尝试从AI消息中获取文档内容
- const aiMessage = selectedHistoryItem.value?.messages?.find(msg => msg.type === 'ai' && msg.parsedContent?.hasDocument);
- if (aiMessage && aiMessage.parsedContent) {
- documentContent = aiMessage.parsedContent.documentContent;
- }
- }
-
- if (!documentContent) {
- ElMessage.warning('没有可下载的文档内容');
- return;
- }
-
- try {
- // 创建改进的HTML格式Word文档
- const wordContent = createImprovedWordContent(documentContent);
-
- // 创建Blob对象 - 使用Word兼容的MIME类型
- const blob = new Blob([wordContent], {
- type: 'application/msword'
- });
-
- // 使用file-saver下载
- const { saveAs } = await import('file-saver');
- const fileName = documentContent.title || 'AI生成的文档';
- saveAs(blob, `${fileName}.doc`);
-
- ElMessage.success('下载成功');
-
- } catch (error) {
- console.error('下载文档失败:', error);
- ElMessage.error('下载失败,请重试');
- }
- };
- // 创建改进的HTML格式Word文档内容
- const createImprovedWordContent = (documentContent) => {
- // 创建HTML格式的文档内容,兼容Microsoft Office Word
- let htmlContent = `<!DOCTYPE html>
- <html xmlns:o="urn:schemas-microsoft-com:office:office"
- xmlns:w="urn:schemas-microsoft-com:office:word"
- xmlns="http://www.w3.org/TR/REC-html40">
- <head>
- <meta charset="utf-8">
- <meta name="ProgId" content="Word.Document">
- <meta name="Generator" content="Microsoft Word 15">
- <meta name="Originator" content="Microsoft Word 15">
- <title>${documentContent.title || 'AI生成的文档'}</title>
- <!--[if gte mso 9]>
- <xml>
- <w:WordDocument>
- <w:View>Print</w:View>
- <w:Zoom>100</w:Zoom>
- <w:DoNotOptimizeForBrowser/>
- <w:ValidateAgainstSchemas/>
- <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
- <w:IgnoreMixedContent>false</w:IgnoreMixedContent>
- <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
- <w:Compatibility>
- <w:BreakWrappedTables/>
- <w:SnapToGridInCell/>
- <w:WrapTextWithPunct/>
- <w:UseAsianBreakRules/>
- <w:DontGrowAutofit/>
- </w:Compatibility>
- </w:WordDocument>
- </xml>
- <![endif]-->
- <style>
- @page {
- size: 21cm 29.7cm;
- margin: 2.5cm 2cm 2.5cm 2cm;
- }
- body {
- font-family: "Microsoft YaHei", "宋体", Arial, sans-serif;
- font-size: 14px;
- line-height: 1.6;
- margin: 24px;
- color: #000;
- }
- .header {
- text-align: center;
- margin-bottom: 1.5cm;
- page-break-after: avoid;
- }
- .doc-title {
- font-size: 18pt;
- font-weight: bold;
- margin-bottom: 0.8cm;
- color: #000;
- }
- .section {
- margin-bottom: 1rem;
- page-break-inside: avoid;
- }
- .section-title {
- font-size: 14pt;
- font-weight: bold;
- margin-bottom: 0.5rem;
- color: #000;
- page-break-after: avoid;
- }
- .content {
- margin-bottom: 0.5rem;
- text-align: justify;
- }
- h1 {
- font-size: 16pt;
- font-weight: bold;
- margin: 1rem 0 0.5rem 0;
- color: #000;
- page-break-after: avoid;
- letter-spacing: normal;
- word-spacing: normal;
- }
- h2 {
- font-size: 14pt;
- font-weight: bold;
- margin: 0.8rem 0 0.4rem 0;
- color: #000;
- page-break-after: avoid;
- letter-spacing: normal;
- word-spacing: normal;
- }
- h3 {
- font-size: 12pt;
- font-weight: bold;
- margin: 0.6rem 0 0.3rem 0;
- color: #000;
- page-break-after: avoid;
- letter-spacing: normal;
- word-spacing: normal;
- }
- h4 {
- font-size: 12pt;
- font-weight: bold;
- margin: 0.5rem 0 0.3rem 0;
- color: #000;
- page-break-after: avoid;
- letter-spacing: normal;
- word-spacing: normal;
- }
- strong { font-weight: bold; }
- em { font-style: italic; }
- p {
- margin: 0.5rem 0;
- text-align: justify;
- orphans: 2;
- widows: 2;
- letter-spacing: normal;
- word-spacing: normal;
- }
- .list-item {
- margin: 0.25rem 0;
- text-align: justify;
- }
- table {
- border-collapse: collapse;
- width: 100%;
- margin: 1rem 0;
- page-break-inside: avoid;
- }
- td, th {
- border: 1px solid #000;
- padding: 0.3cm;
- text-align: left;
- font-size: 11pt;
- }
- th {
- background-color: #f0f0f0;
- font-weight: bold;
- }
- ul, ol {
- margin: 0.5rem 0;
- padding-left: 1cm;
- }
- li {
- margin: 0.25rem 0;
- text-align: justify;
- letter-spacing: normal;
- word-spacing: normal;
- }
- </style>
- </head>
- <body>
- <div class='header'>
- <div class='doc-title'>${documentContent.title || 'AI生成的文档'}</div>
- </div>
- `;
-
- // 添加各个章节内容
- if (documentContent.sections) {
- documentContent.sections.forEach((section, index) => {
- htmlContent += `
- <div class='section'>
- <div class='section-title'>${section.title}</div>
- <div class='content'>
- ${formatContentForImprovedWord(section.content)}
- </div>
- </div>
- `;
- });
- }
-
- htmlContent += '</body></html>';
-
- return htmlContent;
- };
- // 格式化内容为改进的Word格式
- const formatContentForImprovedWord = (content) => {
- if (!content) return '';
-
- let formattedContent = content;
-
- // 后端返回的是HTML格式,无需Markdown转换
-
- // 后端返回的是HTML格式,无需Markdown转换
-
- // 将连续的列表项包装在ul或ol标签中
- formattedContent = formattedContent.replace(/(<li>.*<\/li>)/gs, (match) => {
- const hasNumbers = /^\d+\./.test(content);
- const listTag = hasNumbers ? 'ol' : 'ul';
- return `<${listTag}>${match}</${listTag}>`;
- });
-
- // 处理段落
- formattedContent = formattedContent.replace(/\n\n/g, '</p><p>');
- formattedContent = formattedContent.replace(/\n/g, '<br>');
-
- // 包装在段落标签中
- if (formattedContent.trim() && !formattedContent.startsWith('<')) {
- formattedContent = `<p>${formattedContent}</p>`;
- }
-
- return formattedContent;
- };
- // 创建docx文档内容
- const createDocxContent = async (documentContent) => {
- const { Paragraph, TextRun, HeadingLevel, AlignmentType } = await import('docx');
-
- const children = [];
-
- // 添加文档标题
- if (documentContent.title) {
- children.push(
- new Paragraph({
- children: [
- new TextRun({
- text: documentContent.title,
- bold: true,
- size: 32, // 18pt
- }),
- ],
- alignment: AlignmentType.CENTER,
- spacing: {
- after: 400, // 0.5cm
- },
- })
- );
- }
-
- // 添加各个章节
- if (documentContent.sections) {
- for (let index = 0; index < documentContent.sections.length; index++) {
- const section = documentContent.sections[index];
-
- // 添加章节标题
- children.push(
- new Paragraph({
- children: [
- new TextRun({
- text: section.title,
- bold: true,
- size: 28, // 14pt
- }),
- ],
- heading: HeadingLevel.HEADING_2,
- spacing: {
- before: 400, // 0.5cm
- after: 200, // 0.25cm
- },
- })
- );
-
- // 添加章节内容
- if (section.content) {
- const formattedContent = await formatContentForDocx(section.content);
- children.push(...formattedContent);
- }
- }
- }
-
- return children;
- };
- // 格式化内容为docx格式
- const formatContentForDocx = async (content) => {
- const { Paragraph, TextRun, HeadingLevel } = await import('docx');
-
- if (!content) return [];
-
- const children = [];
- const lines = content.split('\n');
-
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i].trim();
-
- if (!line) {
- // 空行
- children.push(
- new Paragraph({
- children: [new TextRun({ text: '' })],
- spacing: { after: 200 },
- })
- );
- continue;
- }
-
- // 检查是否是标题
- if (line.startsWith('# ')) {
- children.push(
- new Paragraph({
- children: [
- new TextRun({
- text: line.substring(2),
- bold: true,
- size: 32,
- }),
- ],
- heading: HeadingLevel.HEADING_1,
- spacing: { before: 400, after: 200 },
- })
- );
- } else if (line.startsWith('## ')) {
- children.push(
- new Paragraph({
- children: [
- new TextRun({
- text: line.substring(3),
- bold: true,
- size: 28,
- }),
- ],
- heading: HeadingLevel.HEADING_2,
- spacing: { before: 300, after: 200 },
- })
- );
- } else if (line.startsWith('### ')) {
- children.push(
- new Paragraph({
- children: [
- new TextRun({
- text: line.substring(4),
- bold: true,
- size: 24,
- }),
- ],
- heading: HeadingLevel.HEADING_3,
- spacing: { before: 200, after: 200 },
- })
- );
- } else if (line.startsWith('- ') || /^\d+\. /.test(line)) {
- // 列表项
- children.push(
- new Paragraph({
- children: [
- new TextRun({
- text: line,
- size: 24,
- }),
- ],
- spacing: { before: 100, after: 100 },
- })
- );
- } else {
- // 普通段落
- const textRuns = parseTextRunsSync(line);
- children.push(
- new Paragraph({
- children: textRuns,
- spacing: { before: 200, after: 200 },
- })
- );
- }
- }
-
- return children;
- };
- // 解析文本运行(处理加粗、斜体等)- 同步版本
- const parseTextRunsSync = (text) => {
- // 简化版本,直接返回普通文本
- return [{
- text: text.replace(/\*\*(.*?)\*\*/g, '$1'), // 移除加粗标记
- size: 24,
- }];
- };
- // 创建Word文档内容(HTML格式)
- const createWordContent = (documentContent) => {
- // 创建HTML格式的文档内容,符合A4纸张格式
- let htmlContent = `
- <html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'>
- <head>
- <meta charset='utf-8'>
- <title>${documentContent.title || 'AI生成的文档'}</title>
- <!--[if gte mso 9]>
- <xml>
- <w:WordDocument>
- <w:View>Print</w:View>
- <w:Zoom>90</w:Zoom>
- <w:DoNotOptimizeForBrowser/>
- </w:WordDocument>
- </xml>
- <![endif]-->
- <style>
- @page {
- size: 21cm 29.7cm;
- margin: 2.5cm 2cm 2.5cm 2cm;
- }
- body {
- font-family: "Microsoft YaHei", "宋体", Arial, sans-serif;
- font-size: 14px;
- line-height: 1.6;
- margin: 24px;
- color: #000;
- }
- .header {
- text-align: center;
- margin-bottom: 1.5cm;
- page-break-after: avoid;
- }
- .doc-title {
- font-size: 18pt;
- font-weight: bold;
- margin-bottom: 0.8cm;
- color: #000;
- }
- .section {
- margin-bottom: 1rem;
- page-break-inside: avoid;
- }
- .section-title {
- font-size: 14pt;
- font-weight: bold;
- margin-bottom: 0.5rem;
- color: #000;
- page-break-after: avoid;
- }
- .content {
- margin-bottom: 0.5rem;
- text-align: justify;
- }
- h1 {
- font-size: 16pt;
- font-weight: bold;
- margin: 1rem 0 0.5rem 0;
- color: #000;
- page-break-after: avoid;
- letter-spacing: normal;
- word-spacing: normal;
- }
- h2 {
- font-size: 14pt;
- font-weight: bold;
- margin: 0.8rem 0 0.4rem 0;
- color: #000;
- page-break-after: avoid;
- letter-spacing: normal;
- word-spacing: normal;
- }
- h3 {
- font-size: 12pt;
- font-weight: bold;
- margin: 0.6rem 0 0.3rem 0;
- color: #000;
- page-break-after: avoid;
- letter-spacing: normal;
- word-spacing: normal;
- }
- h4 {
- font-size: 12pt;
- font-weight: bold;
- margin: 0.5rem 0 0.3rem 0;
- color: #000;
- page-break-after: avoid;
- letter-spacing: normal;
- word-spacing: normal;
- }
- strong { font-weight: bold; }
- em { font-style: italic; }
- p {
- margin: 0.5rem 0;
- text-align: justify;
- orphans: 2;
- widows: 2;
- letter-spacing: normal;
- word-spacing: normal;
- }
- .list-item {
- margin: 0.25rem 0;
- text-align: justify;
- }
- table {
- border-collapse: collapse;
- width: 100%;
- margin: 1rem 0;
- page-break-inside: avoid;
- }
- td, th {
- border: 1px solid #000;
- padding: 0.3cm;
- text-align: left;
- font-size: 11pt;
- }
- th {
- background-color: #f0f0f0;
- font-weight: bold;
- }
- ul, ol {
- margin: 0.5rem 0;
- padding-left: 1cm;
- }
- li {
- margin: 0.25rem 0;
- text-align: justify;
- letter-spacing: normal;
- word-spacing: normal;
- }
- </style>
- </head>
- <body>
- <div class='header'>
- <div class='doc-title'>${documentContent.title || 'AI生成的文档'}</div>
- </div>
- `;
-
- // 添加各个章节内容
- if (documentContent.sections) {
- documentContent.sections.forEach((section, index) => {
- htmlContent += `
- <div class='section'>
- <div class='section-title'>${section.title}</div>
- <div class='content'>
- ${formatContentForWord(section.content)}
- </div>
- </div>
- `;
- });
- }
-
- htmlContent += '</body></html>';
-
- return htmlContent;
- };
- // 格式化内容为Word格式(A4纸张优化)
- const formatContentForWord = (content) => {
- if (!content) return '';
-
- let formattedContent = content;
-
- // 后端返回的是HTML格式,无需Markdown转换
-
- // 后端返回的是HTML格式,无需Markdown转换
-
- // 将连续的列表项包装在ul或ol标签中
- formattedContent = formattedContent.replace(/(<li>.*<\/li>)/gs, (match) => {
- // 检查是否是有序列表(包含数字)
- const hasNumbers = /^\d+\./.test(content);
- const listTag = hasNumbers ? 'ol' : 'ul';
- return `<${listTag}>${match}</${listTag}>`;
- });
-
- // 处理段落 - 将双换行符转换为段落
- formattedContent = formattedContent.replace(/\n\n/g, '</p><p>');
-
- // 处理单换行符
- formattedContent = formattedContent.replace(/\n/g, '<br>');
-
- // 包装在段落标签中
- if (formattedContent.trim() && !formattedContent.startsWith('<')) {
- formattedContent = `<p>${formattedContent}</p>`;
- }
-
- return formattedContent;
- };
- // 去除markdown格式符号的工具函数
- const removeMarkdownFormatting = (text) => {
- if (!text) return '';
-
- return text
- // 去除标题符号 (# ## ### #### ##### ######)
- .replace(/^#{1,6}\s+/gm, '')
- // 去除粗体符号 (**text** 或 __text__)
- .replace(/\*\*(.*?)\*\*/g, '$1')
- .replace(/__(.*?)__/g, '$1')
- // 去除斜体符号 (*text* 或 _text_)
- .replace(/\*(.*?)\*/g, '$1')
- .replace(/_(.*?)_/g, '$1')
- // 去除删除线符号 (~~text~~)
- .replace(/~~(.*?)~~/g, '$1')
- // 去除代码块符号 (```code```)
- .replace(/```[\s\S]*?```/g, '')
- // 去除行内代码符号 (`code`)
- .replace(/`([^`]+)`/g, '$1')
- // 去除链接符号 ([text](url))
- .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
- // 去除图片符号 ()
- .replace(/!\[([^\]]*)\]\([^)]+\)/g, '$1')
- // 去除引用符号 (> text)
- .replace(/^>\s*/gm, '')
- // 去除列表符号 (- * + 或 1. 2. 3.)
- .replace(/^[\s]*[-*+]\s+/gm, '')
- .replace(/^[\s]*\d+\.\s+/gm, '')
- // 去除表格符号 (| 分隔符)
- .replace(/\|/g, ' ')
- // 去除水平分割线 (--- 或 ***)
- .replace(/^[-*]{3,}$/gm, '')
- // 清理多余的空行
- .replace(/\n\s*\n\s*\n/g, '\n\n')
- .trim();
- };
- // 消息操作方法
- const copyUserMessage = (message) => {
- let textToCopy = message.content || '';
-
- // 去除文件标签,只保留用户实际输入的内容
- if (textToCopy.includes('<filename>') && textToCopy.includes('<filesize>')) {
- // 提取用户实际输入的部分(在文件标签之后的内容)
- const parts = textToCopy.split('</filesize>');
- if (parts.length > 1) {
- textToCopy = parts[1].trim();
- } else {
- // 如果没有找到结束标签,尝试其他方式提取
- textToCopy = textToCopy.replace(/<word>.*?<\/word>/s, '').replace(/<filename>.*?<\/filename>/g, '').replace(/<filesize>.*?<\/filesize>/g, '').trim();
- }
- }
-
- // 去除markdown格式符号
- textToCopy = removeMarkdownFormatting(textToCopy);
-
- copyToClipboard(textToCopy);
- };
- const copyAIMessage = (message) => {
- let textToCopy = message.content || '';
-
- // 过滤掉AI写作的内部标签
- textToCopy = textToCopy
- .replace(/<OPENING_START>/g, '')
- .replace(/<\/OPENING_END>/g, '')
- .replace(/<DOCUMENT_START>/g, '')
- .replace(/<\/DOCUMENT_END>/g, '')
- .replace(/<CLOSING_START>/g, '')
- .replace(/<\/CLOSING_START>/g, '') // 处理可能的错误标签格式
- .replace(/<\/CLOSING_END>/g, '')
- .replace(/<\/DOCUMENT_START>/g, '') // 处理错误的</DOCUMENT_START>标签
- .replace(/<CLOSING_END>/g, '') // 处理可能的错误标签格式
- .trim();
-
- // 去除markdown格式符号
- textToCopy = removeMarkdownFormatting(textToCopy);
-
- copyToClipboard(textToCopy);
- };
- const editUserMessage = (message) => {
- console.log('编辑用户消息:', message.content);
- detailInputText.value = message.content;
-
- // 恢复文件信息
- if (message.file) {
- selectedFile.value = message.file;
- console.log('恢复文件信息:', message.file.name);
- }
-
- // 聚焦到输入框
- const inputElement = document.querySelector('.message-input');
- if (inputElement) {
- inputElement.focus();
- inputElement.setSelectionRange(inputElement.value.length, inputElement.value.length);
- }
- };
- const regenerateResponse = async (messageIndex) => {
- console.log('重新生成回复,消息索引:', messageIndex);
-
- // 找到对应的用户消息
- if (messageIndex > 0) {
- const userMessage = selectedHistoryItem.value.messages[messageIndex - 1];
- if (userMessage && userMessage.type === 'user') {
- console.log('重新发送用户消息:', userMessage.content);
-
- // 恢复消息文本和文件信息
- detailInputText.value = userMessage.content;
-
- // 恢复文件信息
- if (userMessage.file) {
- selectedFile.value = userMessage.file;
- console.log('重新生成时恢复文件信息:', userMessage.file.name);
- }
-
- await sendDetailMessage();
- }
- }
- };
- // 语音朗读相关方法
- const handleVoiceRead = (message) => {
- if (speakingMessageId.value === message.id) {
- // 如果正在朗读这条消息,则停止
- try { window.speechSynthesis && window.speechSynthesis.cancel(); } catch (e) {}
- speakingMessageId.value = null;
- } else {
- // 如果朗读其他消息,先停止当前朗读
- if (speakingMessageId.value) {
- try { window.speechSynthesis && window.speechSynthesis.cancel(); } catch (e) {}
- }
-
- // 开始朗读新消息 - 使用过滤后的内容,移除内部标签但保留文档内容
- let textToRead = '';
-
- if (message.parsedContent) {
- // 如果有解析后的内容,组合所有可见文本部分
- const parts = [];
-
- if (message.parsedContent.openingText) {
- parts.push(filterInternalTags(message.parsedContent.openingText));
- }
-
- // 添加文档内容(如果有的话)
- if (message.parsedContent.documentText) {
- parts.push(filterInternalTags(message.parsedContent.documentText));
- }
-
- if (message.parsedContent.closingText) {
- parts.push(filterInternalTags(message.parsedContent.closingText));
- }
-
- textToRead = parts.join(' ');
- } else {
- // 如果没有解析后的内容,直接过滤原始内容
- textToRead = filterInternalTags(message.content || '');
- }
-
- // 进一步清理HTML标签和Markdown标签,确保只朗读纯文本
- textToRead = textToRead
- .replace(/<[^>]*>/g, '') // 移除HTML标签
- .trim();
-
- // 清理Markdown标签
- textToRead = cleanMarkdownForSpeech(textToRead);
-
- if (textToRead) {
- // 创建自定义的语音合成实例,以便监听完成事件
- const utterance = new SpeechSynthesisUtterance(textToRead);
- utterance.lang = 'zh-CN';
- utterance.rate = 0.9;
- utterance.pitch = 1;
- utterance.volume = 1;
-
- // 监听语音合成完成事件
- utterance.onend = () => {
- speakingMessageId.value = null;
- };
-
- utterance.onerror = () => {
- speakingMessageId.value = null;
- };
-
- // 开始朗读
- window.speechSynthesis.speak(utterance);
- speakingMessageId.value = message.id;
- }
- }
- };
- // 检查消息是否正在朗读
- const isSpeaking = (messageId) => {
- return speakingMessageId.value === messageId;
- };
- // 点赞和点踩功能
- const handleThumbsUp = async (message) => {
- console.log('点赞消息:', message.id);
-
- // 如果已经点赞,则取消点赞
- if (message.userFeedback === 'like') {
- message.userFeedback = null;
- } else {
- // 设置点赞,取消点踩
- message.userFeedback = 'like';
- }
-
- // 强制触发Vue响应式更新
- selectedHistoryItem.value.messages = [...selectedHistoryItem.value.messages]
-
- // 同步反馈到后端
- await syncFeedbackToBackend(message);
- };
- const handleThumbsDown = async (message) => {
- console.log('点踩消息:', message.id);
-
- // 如果已经点踩,则取消点踩
- if (message.userFeedback === 'dislike') {
- message.userFeedback = null;
- } else {
- // 设置点踩,取消点赞
- message.userFeedback = 'dislike';
- }
-
- // 强制触发Vue响应式更新
- selectedHistoryItem.value.messages = [...selectedHistoryItem.value.messages]
-
- // 同步反馈到后端
- await syncFeedbackToBackend(message);
- };
- // 同步用户反馈到后端
- const syncFeedbackToBackend = async (message) => {
- try {
- if (!message.rawData || !message.rawData.id) {
- console.warn('消息缺少原始数据,无法同步反馈')
- return
- }
-
- const feedback = convertFeedbackToBackend(message.userFeedback)
- console.log('同步反馈到后端:', {
- messageId: message.rawData.id,
- feedback: feedback
- })
-
- // 调用后端点赞点踩接口
- const response = await apis.likeAndDislike({
- id: message.rawData.id,
- user_feedback: feedback
- })
-
- if (response.statusCode === 200) {
- console.log('反馈同步成功')
- ElMessage.success('反馈提交成功')
- } else {
- console.error('反馈同步失败:', response.msg)
- ElMessage.error('反馈提交失败,请稍后重试')
- }
-
- } catch (error) {
- console.error('同步反馈失败:', error)
- ElMessage.error('反馈同步失败,请稍后重试')
- }
- }
- // 格式化文件大小
- const formatFileSize = (bytes) => {
- if (bytes === 0) return '0 B';
- const k = 1024;
- const sizes = ['B', 'KB', 'MB', 'GB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
- };
- watch(transcript, (newVal) => {
- if (!newVal || isListening.value) return
- if (currentView.value === 'detail') {
- detailInputText.value = newVal
- } else {
- const inputElement = document.querySelector('.template-input-container')
- if (inputElement) {
- inputElement.textContent = newVal
- }
- templateContent.value = newVal
- }
- })
- // 监听语音识别错误
- watch(speechError, (newVal) => {
- if (newVal) {
- console.error('语音识别错误:', newVal);
- ElMessage.error(newVal);
- }
- });
- // 组件挂载后初始化
- onMounted(async () => {
- await nextTick();
- // 初始化输入框的默认模板内容
- const inputElement = document.querySelector('.template-input-container');
- if (inputElement) {
- const defaultTemplate = "<span class=\"editable-highlight\" contenteditable=\"true\">总结主题:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">总结时间:</span>\n<span class=\"editable-highlight\" contenteditable=\"true\">主要内容:</span>\n\n请帮我生成一份正式的总结报告,要求格式规范、语言严谨,具体参考以上内容,按照标准工作总结格式生成全文,包含\"工作总结、问题不足、未来计划\"三部分的完整报告。";
- inputElement.innerHTML = defaultTemplate;
- templateContent.value = defaultTemplate.replace(/<[^>]*>/g, '');
- // 为高亮元素添加样式
- await nextTick();
- const highlights = inputElement.querySelectorAll('.editable-highlight');
- highlights.forEach(highlight => {
- highlight.style.backgroundColor = '#3E7BFA10';
- highlight.style.color = '#3E7BFA';
- highlight.style.padding = '4px 8px';
- highlight.style.borderRadius = '6px';
- highlight.style.fontWeight = '500';
- highlight.style.cursor = 'text';
- highlight.style.border = '1px solid transparent';
- highlight.style.display = 'inline-block';
- highlight.style.minWidth = '20px';
- });
- }
- // 获取历史记录列表
- await getHistoryRecordList();
- });
- // 组件销毁前清理
- onBeforeUnmount(() => {
- // 停止当前朗读
- if (speakingMessageId.value) {
- try { window.speechSynthesis && window.speechSynthesis.cancel(); } catch (e) {}
- speakingMessageId.value = null;
- }
- });
- // 在详情页中调用AI
- const callAIInDetail = async (historyItem, smartPrompt, currentUserMessage = null, file = null) => {
- try {
- // 设置生成状态
- isGenerating.value = true;
-
- // 构建发送给DeepSeek的消息
- // 如果有当前用户消息,使用当前消息;否则使用历史记录中的第一条消息
- const userMessageToSend = currentUserMessage || (historyItem ? historyItem.userMessage : '');
-
- // 构建发送给AI的消息
- let messageToSend = userMessageToSend;
-
- // 如果有文件,使用标签格式
- if (file && file.content) {
- messageToSend = `<word>${file.content}</word><filename>${file.name}</filename><filesize>${file.size}</filesize>${userMessageToSend}`;
- }
-
- // 不再拼接提示词,直接使用用户消息
-
- // 调用DeepSeek API
- const response = await apis.sendDeepseekMessage({
- // ===== 已删除:user_id - 后端从token解析 =====
- ai_conversation_id: ai_conversation_id.value,
- message: messageToSend,
- business_type: 2 // AI写作类型
- });
-
- console.log('DeepSeek API响应:', response);
-
- if (response.statusCode === 200) {
- const aiReply = response.data.reply;
-
- // 更新对话ID
- ai_conversation_id.value = response.data.ai_conversation_id;
-
- // 简化解析逻辑,不做复杂的段落分析
- // 直接使用AI回复内容,无需解析
-
- // 更新历史记录(如果存在)
- if (historyItem) {
- historyItem.aiResponse = aiReply;
- historyItem.hasDocument = true; // 简化:直接标记为有文档
- historyItem.documentContent = {
- title: "AI生成的文档",
- sections: [
- {
- title: "文档内容",
- content: aiReply
- }
- ]
- };
-
- // 添加AI消息到对话历史
- const aiMessage = {
- type: 'ai',
- content: aiReply,
- time: new Date().toLocaleString('zh-CN', {
- hour: '2-digit',
- minute: '2-digit'
- }),
- parsedContent: {
- hasDocument: true,
- documentContent: {
- title: "AI生成的文档",
- sections: [
- {
- title: "文档内容",
- content: aiReply
- }
- ]
- },
- openingText: "",
- documentText: aiReply,
- closingText: "",
- documentTitle: "AI生成的文档"
- },
- id: response.data.ai_message_id || Date.now() + 1, // 优先使用后端返回的ai_message_id,否则使用前端生成的ID
- userFeedback: null, // 用户反馈状态:null, 'like', 'dislike'
- isFromBackend: false // 标记这是新创建的AI消息
- };
-
- historyItem.messages.push(aiMessage);
-
- // 如果是临时历史记录项,更新selectedHistoryItem
- if (selectedHistoryItem.value && selectedHistoryItem.value.id === historyItem.id) {
- selectedHistoryItem.value = historyItem;
- }
- }
-
- // 自动滚动到最新位置
- scrollToBottom();
-
- // AI回复完成后,获取最新的历史记录
- await getHistoryRecordList();
-
- // 如果是新对话,将最新的历史记录设为激活状态
- if (ai_conversation_id.value > 0) {
- historyData.value.forEach((item) => {
- item.isActive = item.id === ai_conversation_id.value;
- });
- console.log('设置最新历史记录为激活状态,conversationId:', ai_conversation_id.value);
- }
-
- console.log("AI写作完成,准备进入富文本编辑器");
-
- // 直接进入富文本编辑器,显示AI生成的内容
- console.log('AI回复内容长度:', aiReply.length);
- console.log('AI回复内容预览:', aiReply.substring(0, 200) + '...');
-
- // 格式化内容为HTML
- const formattedContent = formatContentForEditor(aiReply);
- enterEditor(formattedContent);
- } else {
- console.error("DeepSeek API调用失败:", response);
- alert("AI写作失败,请重试");
- }
- } catch (error) {
- console.error("调用AI时出错:", error);
- alert("调用AI失败,请检查网络连接");
- } finally {
- // 重置生成状态
- isGenerating.value = false;
- }
- };
- // 智能分析AI回复的段落结构
- const parseAIResponse = (aiReply) => {
-
- // 分析文档生成回复的结构 - 优先使用三个标签识别,兼容旧格式
- let openingText = "";
- let documentText = "";
- let closingText = "";
- let documentTitle = "AI生成的文档"; // 默认标题
-
- // 优先查找三个标签格式
- const openingStartTag = '<OPENING_START>';
- const openingEndTag = '</OPENING_END>';
- const docStartTag = '<DOCUMENT_START>';
- const docEndTag = '</DOCUMENT_END>';
- const closingStartTag = '<CLOSING_START>';
- const closingEndTag = '</CLOSING_END>';
-
- if (aiReply.includes(openingStartTag) && aiReply.includes(docStartTag) && aiReply.includes(closingStartTag)) {
- // 使用三个标签格式
- try {
- console.log('检测到三个标签格式,开始解析');
-
- // 提取开头文本
- const openingStart = aiReply.indexOf(openingStartTag) + openingStartTag.length;
- const openingEnd = aiReply.indexOf(openingEndTag);
- if (openingStart < openingEnd) {
- openingText = aiReply.substring(openingStart, openingEnd).trim();
- console.log('提取的开头文本:', openingText);
- } else {
- console.warn('开头标签格式不正确');
- }
-
- // 提取文档内容
- const docStart = aiReply.indexOf(docStartTag) + docStartTag.length;
- let docEnd = aiReply.indexOf(docEndTag);
-
- // 如果没有找到正确的结束标签,尝试查找错误的结束标签
- if (docEnd === -1) {
- docEnd = aiReply.indexOf('</DOCUMENT_START>');
- if (docEnd !== -1) {
- console.log('检测到错误的文档结束标签:</DOCUMENT_START>');
- }
- }
-
- if (docStart < docEnd && docEnd !== -1) {
- documentText = aiReply.substring(docStart, docEnd).trim();
- console.log('提取的文档内容长度:', documentText.length);
- console.log('提取的文档内容预览:', documentText.substring(0, 200) + '...');
-
- // 尝试从文档内容中提取标题
- const titleMatch = documentText.match(/^#\s+(.+)$/m);
- if (titleMatch) {
- documentTitle = titleMatch[1].trim();
- console.log('从Markdown提取的标题:', documentTitle);
- } else {
- // 如果没有Markdown标题,尝试从第一行提取
- const lines = documentText.split('\n');
- if (lines.length > 0 && lines[0].trim()) {
- documentTitle = lines[0].trim();
- console.log('从第一行提取的标题:', documentTitle);
- }
- }
- } else {
- console.warn('文档标签格式不正确');
- }
-
- // 提取结尾文本
- const closingStart = aiReply.indexOf(closingStartTag) + closingStartTag.length;
- const closingEnd = aiReply.indexOf(closingEndTag);
- if (closingStart < closingEnd) {
- closingText = aiReply.substring(closingStart, closingEnd).trim();
- console.log('提取的结尾文本:', closingText);
- } else {
- // 尝试从文档结束标签后提取结尾文本
- let afterDocEnd = aiReply.indexOf(docEndTag) + docEndTag.length;
-
- // 如果没有找到正确的结束标签,尝试查找错误的结束标签
- if (afterDocEnd === docEndTag.length - 1) {
- afterDocEnd = aiReply.indexOf('</DOCUMENT_START>') + '</DOCUMENT_START>'.length;
- }
-
- const remainingText = aiReply.substring(afterDocEnd).trim();
- if (remainingText) {
- closingText = remainingText;
- console.log('从文档结束后提取的结尾文本:', closingText);
- } else {
- console.warn('结尾标签格式不正确');
- }
- }
-
- // 验证解析结果
- if (!openingText || !documentText || !closingText) {
- console.warn('标签解析不完整:', { openingText: !!openingText, documentText: !!documentText, closingText: !!closingText });
- }
- } catch (error) {
- console.error('解析三个标签格式失败:', error);
- }
- } else if (aiReply.includes(docStartTag) && aiReply.includes(docEndTag)) {
- // 兼容只有文档标签的格式
- const startIndex = aiReply.indexOf(docStartTag) + docStartTag.length;
- const endIndex = aiReply.indexOf(docEndTag);
-
- if (startIndex < endIndex) {
- documentText = aiReply.substring(startIndex, endIndex).trim();
-
- // 尝试从文档内容中提取标题
- const titleMatch = documentText.match(/^#\s+(.+)$/m);
- if (titleMatch) {
- documentTitle = titleMatch[1].trim();
- } else {
- // 如果没有Markdown标题,尝试从第一行提取
- const lines = documentText.split('\n');
- if (lines.length > 0 && lines[0].trim()) {
- documentTitle = lines[0].trim();
- }
- }
- }
-
- // 设置开头和结尾文本(不包含标签)
- const beforeDoc = aiReply.substring(0, aiReply.indexOf(docStartTag)).trim();
- const afterDoc = aiReply.substring(aiReply.indexOf(docEndTag) + docEndTag.length).trim();
-
- openingText = beforeDoc;
- closingText = afterDoc;
- } else if (aiReply.includes('<DOCUMENT_START>') && aiReply.includes('</DOCUMENT_START>')) {
- // 特殊情况:处理后端返回<DOCUMENT_START>和</DOCUMENT_START>的错误情况
- console.log('检测到错误的文档标签格式:<DOCUMENT_START>和</DOCUMENT_START>');
-
- const startIndex = aiReply.indexOf('<DOCUMENT_START>') + '<DOCUMENT_START>'.length;
- const endIndex = aiReply.indexOf('</DOCUMENT_START>');
-
- if (startIndex < endIndex) {
- documentText = aiReply.substring(startIndex, endIndex).trim();
-
- // 尝试从文档内容中提取标题
- const titleMatch = documentText.match(/^#\s+(.+)$/m);
- if (titleMatch) {
- documentTitle = titleMatch[1].trim();
- } else {
- // 如果没有Markdown标题,尝试从第一行提取
- const lines = documentText.split('\n');
- if (lines.length > 0 && lines[0].trim()) {
- documentTitle = lines[0].trim();
- }
- }
- }
-
- // 设置开头和结尾文本(不包含标签)
- const beforeDoc = aiReply.substring(0, aiReply.indexOf('<DOCUMENT_START>')).trim();
- const afterDoc = aiReply.substring(aiReply.indexOf('</DOCUMENT_START>') + '</DOCUMENT_START>'.length).trim();
-
- openingText = beforeDoc;
- closingText = afterDoc;
- } else {
- // 兼容旧的格式:使用"以下"和"以上"识别
- const lines = aiReply.split('\n').filter(line => line.trim());
-
- // 查找"以下"开头的段落
- const openingIndex = lines.findIndex(line => line.includes('以下'));
- if (openingIndex !== -1) {
- openingText = lines[openingIndex];
- }
-
- // 查找"以上"开头的段落
- const closingIndex = lines.findIndex(line => line.includes('以上'));
- if (closingIndex !== -1) {
- closingText = lines[closingIndex];
- }
-
- // 中间部分就是文档内容
- if (openingIndex !== -1 && closingIndex !== -1) {
- // 提取中间部分(不包括开头和结尾行)
- const startIndex = openingIndex + 1;
- const endIndex = closingIndex;
- if (startIndex < endIndex) {
- documentText = lines.slice(startIndex, endIndex).join('\n');
-
- // 尝试从文档内容中提取标题
- const titleMatch = documentText.match(/^#\s+(.+)$/m);
- if (titleMatch) {
- documentTitle = titleMatch[1].trim();
- } else {
- // 如果没有Markdown标题,尝试从第一行提取
- const firstLine = documentText.split('\n')[0];
- if (firstLine && firstLine.trim()) {
- documentTitle = firstLine.trim();
- }
- }
- }
- } else if (openingIndex !== -1) {
- // 只有开头,没有结尾
- const startIndex = openingIndex + 1;
- documentText = lines.slice(startIndex).join('\n');
-
- // 尝试提取标题
- const titleMatch = documentText.match(/^#\s+(.+)$/m);
- if (titleMatch) {
- documentTitle = titleMatch[1].trim();
- }
- } else if (closingIndex !== -1) {
- // 只有结尾,没有开头
- documentText = lines.slice(0, closingIndex).join('\n');
-
- // 尝试提取标题
- const titleMatch = documentText.match(/^#\s+(.+)$/m);
- if (titleMatch) {
- documentTitle = titleMatch[1].trim();
- }
- }
- }
-
- // 如果没有检测到标准文档结构,检查是否为HTML格式
- if (!openingText && !closingText && !documentText) {
- // 检测是否为HTML格式
- const isHTML = /<[^>]+>/.test(aiReply);
-
- if (isHTML) {
- // 如果是HTML格式,将其作为文档内容
- console.log('检测到HTML格式,将其作为文档内容');
- return {
- hasDocument: true,
- documentContent: {
- title: "AI生成的文档",
- sections: [
- {
- title: "文档内容",
- content: aiReply
- }
- ]
- },
- openingText: "",
- documentText: aiReply,
- closingText: "",
- documentTitle: "AI生成的文档"
- };
- } else {
- // 如果不是HTML格式,将整个回复作为开头文本
- return {
- hasDocument: false,
- documentContent: null,
- openingText: aiReply, // 将整个回复作为开头文本
- documentText: "",
- closingText: "",
- documentTitle: "AI回复"
- };
- }
- }
-
- const result = {
- hasDocument: documentText.trim().length > 0,
- documentContent: documentText.trim() ? {
- title: documentTitle,
- sections: [
- {
- title: "文档内容",
- content: documentText.trim()
- }
- ]
- } : null,
- openingText: openingText.trim(),
- documentText: documentText.trim(),
- closingText: closingText.trim(),
- documentTitle: documentTitle // 添加文档标题
- };
-
- // 调试日志:输出解析结果
- console.log('parseAIResponse 解析结果:', {
- hasDocument: result.hasDocument,
- documentTextLength: result.documentText.length,
- openingTextLength: result.openingText.length,
- closingTextLength: result.closingText.length,
- documentTitle: result.documentTitle
- });
-
- return result;
- };
- // 从AI消息中获取文档内容的辅助函数
- const getDocumentContentFromMessages = () => {
- if (!selectedHistoryItem.value?.messages) return null;
-
- const aiMessage = selectedHistoryItem.value.messages.find(msg => msg.type === 'ai' && msg.parsedContent?.hasDocument);
- if (aiMessage && aiMessage.parsedContent) {
- return aiMessage.parsedContent.documentContent;
- }
-
- return null;
- };
- // 获取当前文档标题的辅助函数
- const getCurrentDocumentTitle = () => {
- // 从富文本编辑器中提取标题
- let content = '';
-
- // 方式1: 从DOM获取
- const editorTextContainer = document.querySelector('.w-e-text');
- if (editorTextContainer) {
- content = editorTextContainer.innerHTML;
- }
-
- // 方式2: 从editorContent获取
- if (!content && editorContent.value) {
- content = editorContent.value;
- }
-
- // 方式3: 从wangeditor实例获取
- if (!content && editorRef.value) {
- try {
- content = editorRef.value.getHtml();
- } catch (error) {
- console.log("从wangeditor实例获取失败:", error);
- }
- }
-
- if (content) {
- // 尝试从HTML内容中提取标题
- // 查找第一个h1标签
- const h1Match = content.match(/<h1[^>]*>(.*?)<\/h1>/i);
- if (h1Match) {
- const title = h1Match[1].replace(/<[^>]*>/g, '').trim();
- if (title) {
- return title;
- }
- }
-
- // 查找第一个h2标签
- const h2Match = content.match(/<h2[^>]*>(.*?)<\/h2>/i);
- if (h2Match) {
- const title = h2Match[1].replace(/<[^>]*>/g, '').trim();
- if (title) {
- return title;
- }
- }
-
- // 查找第一个h3标签
- const h3Match = content.match(/<h3[^>]*>(.*?)<\/h3>/i);
- if (h3Match) {
- const title = h3Match[1].replace(/<[^>]*>/g, '').trim();
- if (title) {
- return title;
- }
- }
-
- // 如果没有标题标签,尝试从第一段文本中提取
- const firstParagraph = content.match(/<p[^>]*>(.*?)<\/p>/i);
- if (firstParagraph) {
- const text = firstParagraph[1].replace(/<[^>]*>/g, '').trim();
- // 如果第一段文本较短且看起来像标题,则使用它
- if (text && text.length <= 50 && !text.includes('。') && !text.includes(',')) {
- return text;
- }
- }
- }
-
- // 如果都没有找到合适的标题,返回默认值
- return 'AI生成文档';
- };
- // 获取水印文本的辅助函数
- const getWatermarkText = () => {
- // 可以从以下来源获取水印文本:
- // 1. 用户设置
- // 2. 系统配置
- // 3. 文档类型
- // 4. 默认值
-
- // 这里可以根据实际需求进行配置
- const watermarkConfig = {
- default: '机密文档',
- // 可以根据文档类型设置不同的水印
- types: {
- '工作总结': '内部文档',
- '会议纪要': '机密',
- '通知': '正式文档',
- '公告': '公开文档'
- }
- };
-
- // 获取当前文档标题
- const documentTitle = getCurrentDocumentTitle();
-
- // 根据文档标题判断类型
- for (const [type, watermark] of Object.entries(watermarkConfig.types)) {
- if (documentTitle.includes(type)) {
- return watermark;
- }
- }
-
- // 返回默认水印
- return watermarkConfig.default;
- };
- // 使用HTML生成带真正可见水印的Word文档
- const generateWordWithWatermark = async (content, documentTitle, watermarkText, filename) => {
- // 为保持兼容,保留函数但改为调用无水印实现
- try {
- await generateWordWithoutWatermark(content, documentTitle, filename)
- } catch (error) {
- console.error('生成Word文档失败:', error);
- ElMessage.error("生成Word文档失败,请重试");
- }
- };
- // 回退方案:使用HTML生成带水印的Word文档
- const generateWordWithHTMLWatermark = async (content, documentTitle, watermarkText, filename) => {
- // 保留旧接口但移除水印与成功提示
- await generateWordWithoutWatermark(content, documentTitle, filename)
- };
- // 无水印的Word(HTML)生成与下载
- const generateWordWithoutWatermark = async (content, documentTitle, filename) => {
- try {
- const html = createHTMLWithoutWatermark(content, documentTitle)
- const blob = new Blob([html], { type: 'application/msword;charset=utf-8' })
- const url = URL.createObjectURL(blob)
- const link = document.createElement('a')
- link.href = url
- link.download = filename.replace('.docx', '.doc')
- document.body.appendChild(link)
- link.click()
- document.body.removeChild(link)
- URL.revokeObjectURL(url)
- ElMessage.success("Word文档下载成功")
- } catch (error) {
- console.error('生成无水印Word文档失败:', error)
- ElMessage.error("生成Word文档失败,请重试")
- }
- }
- // 创建带有真正可见水印的HTML文档
- const createHTMLWithTrueWatermark = (content, documentTitle, watermarkText) => {
- // 兼容旧函数签名,移除水印,仅输出纯文档
- return createHTMLWithoutWatermark(content, documentTitle)
- };
- const createHTMLWithoutWatermark = (content, documentTitle) => {
- return `<!DOCTYPE html>
- <html xmlns:o="urn:schemas-microsoft-com:office:office"
- xmlns:w="urn:schemas-microsoft-com:office:word"
- xmlns="http://www.w3.org/TR/REC-html40">
- <head>
- <meta charset="UTF-8">
- <meta name="ProgId" content="Word.Document">
- <meta name="Generator" content="Microsoft Word 15">
- <meta name="Originator" content="Microsoft Word 15">
- <title>${documentTitle || 'AI生成文档'}</title>
- <style>
- @page { size: 21cm 29.7cm; margin: 2.54cm 3.18cm 2.54cm 3.18cm; }
- body { font-family: "宋体", "SimSun", serif; font-size: 12pt; line-height: 1.5; color: #000; }
- h1 { font-size: 18pt; font-weight: bold; text-align: center; margin: 24pt 0 18pt 0; }
- h2 { font-size: 16pt; font-weight: bold; margin: 18pt 0 12pt 0; }
- h3 { font-size: 14pt; font-weight: bold; margin: 12pt 0 6pt 0; }
- p { margin: 0 0 6pt 0; text-align: justify; text-indent: 2em; }
- table { border-collapse: collapse; width: 100%; margin: 12pt 0; }
- td, th { border: 1px solid #000; padding: 6pt; }
- </style>
- <!--[if gte mso 9]>
- <xml>
- <w:WordDocument>
- <w:View>Print</w:View>
- <w:Zoom>100</w:Zoom>
- <w:DoNotOptimizeForBrowser/>
- </w:WordDocument>
- </xml>
- <![endif]-->
- </head>
- <body>
- ${content}
- </body>
- </html>`
- }
- // 过滤内部标签,只显示纯文本内容
- const filterInternalTags = (text) => {
- if (!text) return text;
-
- console.log('过滤前的文本:', text);
-
- // 移除所有内部标签(包括可能的变体)
- let filteredText = text
- .replace(/<OPENING_START>/g, '')
- .replace(/<\/OPENING_END>/g, '')
- .replace(/<DOCUMENT_START>/g, '')
- .replace(/<\/DOCUMENT_END>/g, '')
- .replace(/<CLOSING_START>/g, '')
- .replace(/<\/CLOSING_START>/g, '') // 处理可能的错误标签格式
- .replace(/<\/CLOSING_END>/g, '')
- .replace(/<\/DOCUMENT_START>/g, '') // 处理错误的</DOCUMENT_START>标签
- .replace(/<CLOSING_END>/g, '') // 处理可能的错误标签格式
- .trim();
-
- console.log('过滤后的文本:', filteredText);
-
- return filteredText;
- };
- // 清理Markdown标签,用于语音朗读
- const cleanMarkdownForSpeech = (text) => {
- if (!text) return text;
-
- let cleanText = text
- // 移除Markdown标题标记
- .replace(/^#{1,6}\s+/gm, '') // 移除 # ## ### 等标题标记
- // 移除粗体和斜体标记
- .replace(/\*\*([^*]+)\*\*/g, '$1') // 移除 **粗体**
- .replace(/\*([^*]+)\*/g, '$1') // 移除 *斜体*
- .replace(/__([^_]+)__/g, '$1') // 移除 __粗体__
- .replace(/_([^_]+)_/g, '$1') // 移除 _斜体_
- // 移除链接标记
- .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // 移除 [文本](链接)
- // 移除代码块标记
- .replace(/```[\s\S]*?```/g, '') // 移除 ```代码块```
- .replace(/`([^`]+)`/g, '$1') // 移除 `行内代码`
- // 移除列表标记
- .replace(/^[\s]*[-*+]\s+/gm, '') // 移除无序列表标记
- .replace(/^[\s]*\d+\.\s+/gm, '') // 移除有序列表标记
- // 移除引用标记
- .replace(/^>\s*/gm, '') // 移除 > 引用标记
- // 移除水平线
- .replace(/^[-*_]{3,}$/gm, '') // 移除 --- 或 *** 或 ___
- // 移除表格标记
- .replace(/\|/g, ' ') // 移除表格分隔符
- .replace(/^[\s]*[-:]+[\s-:]*$/gm, '') // 移除表格分隔行
- // 清理多余的空格和换行
- .replace(/\n\s*\n/g, '\n') // 合并多个空行
- .replace(/\s+/g, ' ') // 合并多个空格
- .trim();
-
- return cleanText;
- };
- // 格式化文档内容,处理Markdown链接和换行
- const formatDocumentContent = (content) => {
- if (!content) return '';
-
- let formattedContent = content;
-
- // 后端返回的是HTML格式,无需Markdown转换
-
- // 后端返回的是HTML格式,无需Markdown转换
-
- // 过滤emoji表情符号
- formattedContent = formattedContent.replace(/[\u{1F600}-\u{1F64F}]|[\u{1F300}-\u{1F5FF}]|[\u{1F680}-\u{1F6FF}]|[\u{1F1E0}-\u{1F1FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu, '');
-
- // 包装在p标签中,但减少多余的段落
- if (formattedContent.trim()) {
- formattedContent = `<p>${formattedContent}</p>`;
- }
-
- return formattedContent;
- };
- // 发送详情页消息
- const sendDetailMessage = () => {
- if (!detailInputText.value.trim() || isGenerating.value) {
- return;
- }
- // 保存文件引用,因为后面需要传递给AI
- const currentFile = selectedFile.value;
- const newMessage = {
- type: 'user',
- content: detailInputText.value,
- file: currentFile, // 添加文件信息
- time: new Date().toLocaleString('zh-CN', {
- hour: '2-digit',
- minute: '2-digit'
- }),
- id: Date.now(), // 添加唯一ID
- isFromBackend: false // 标记这是新创建的消息
- };
- selectedHistoryItem.value.messages.push(newMessage);
- detailInputText.value = '';
- // 注意:不关闭文档预览,让用户在预览状态下正常聊天
- // 清空选中的文件
- if (selectedFile.value) {
- removeSelectedFile();
- }
- // 自动滚动到最新位置
- scrollToBottom();
- // 直接进入富文本编辑器并显示loading
- currentView.value = "editor";
- isGenerating.value = true;
-
- // 在详情页中调用AI - 传递当前用户输入的消息
- callAIInDetail(selectedHistoryItem.value, null, newMessage.content, currentFile);
- };
- // 自动滚动到最新位置
- const scrollToBottom = () => {
- nextTick(() => {
- const chatArea = document.querySelector('.chat-area');
- if (chatArea) {
- chatArea.scrollTop = chatArea.scrollHeight;
- }
- });
- };
- // 监听消息变化,自动滚动
- const watchMessages = () => {
- if (selectedHistoryItem.value?.messages) {
- scrollToBottom();
- }
- };
- // 使用watch监听消息数组变化
- watch(selectedHistoryItem, (newVal) => {
- watchMessages();
- });
- // 为详情页生成智能提示词
- const generateSmartPromptForDetail = (userMessage) => {
- // 不做意图判断,让AI自己判断,但要求按照固定格式
- return `请根据用户的问题或需求进行回复。
- 如果用户需要文档,请严格按照以下格式回复:
- <OPENING_START>
- 以下是为您准备的文档,包含相关内容:
- </OPENING_END>
- <DOCUMENT_START>
- [在这里生成完整的Word文档内容,必须包含:
- 1. 文档标题(使用#标记)
- 2. 多个章节(使用##标记)
- 3. 详细内容(使用Markdown格式,支持大小标题、换行、列表、加粗、斜体等富文本效果)
- 4. 确保内容完整,不要中途停止]
- </DOCUMENT_END>
- <CLOSING_START>
- 以上文档采用专业的格式编写,符合办公文档要求。如需调整内容或格式,请告诉我具体需求。
- </CLOSING_END>
- 如果是普通问题,请直接回答,不要使用上述格式。
- 重要提醒:
- 1. 如果生成文档,必须包含三个标签区域:<OPENING_START>开头文本</OPENING_END>、<DOCUMENT_START>文档内容</DOCUMENT_END>、<CLOSING_START>结尾文本</CLOSING_END>
- 2. 确保每个区域都完整,特别是结尾部分不能缺失
- 3. 标签必须严格按照上述格式,不能有任何变化
- 4. 文档内容中不要使用emoji表情符号
- 5. 如果用户明确要求生成文档、报告、通知、方案等办公文档,必须使用上述格式
- 6. 标签名称区分大小写,必须完全匹配
- 示例正确格式:
- <OPENING_START>
- 以下是为您准备的文档,包含相关内容:
- </OPENING_END>
- <DOCUMENT_START>
- # 文档标题
- ## 第一章 概述
- 详细内容...
- ## 第二章 具体内容
- 详细内容...
- </DOCUMENT_END>
- <CLOSING_START>
- 以上文档采用专业的格式编写,符合办公文档要求。如需调整内容或格式,请告诉我具体需求。
- </CLOSING_END>`;
- };
- </script>
- <style lang="less" scoped>
- // 删除图标样式
- .delete-icon {
- width: 16px;
- height: 16px;
- }
- .chat-container {
- display: flex;
- height: 100vh;
- font-family: "Alibaba PuHuiTi 3.0", sans-serif;
- }
- /* 工作内容区域 */
- .work-content {
- flex: 1;
- padding: 22px;
- overflow-y: auto;
- display: flex;
- flex-direction: column;
- align-items: center;
- // max-width: 1528px; /* 设置最小宽度,确保内容完整显示 */
-
- /* 隐藏滚动条样式 */
- &::-webkit-scrollbar {
- width: 0;
- background: transparent;
- }
-
- &::-webkit-scrollbar-track {
- background: transparent;
- }
-
- &::-webkit-scrollbar-thumb {
- background: transparent;
- }
- .ai-writing-card {
- background: white;
- width: 100%;
- min-height: 720px; /* 最小高度 */
- max-height: calc(100vh); /* 最大高度,防止超出容器 */
- height: calc(100vh); /* 自适应高度 */
- padding: 25px 236px 35px 272px;
- border-radius: 16px;
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
- max-width: 1528px;
- display: flex;
- flex-direction: column;
- .document-generation {
- margin-bottom: 38px; /* 减少底部间距 */
- text-align: center;
- flex-shrink: 0; /* 防止被压缩 */
- h3 {
- font-size: 30px;
- font-weight: 600;
- color: #1e3d59;
- // margin: 0 0 16px 0;
- }
- .subtitle {
- font-size: 20px;
- color: #b2b2b2;
- margin: 0 0 13px 0;
- line-height: 1.5;
- }
- .input-area {
- border: 2px solid #3e7bfa;
- border-radius: 12px;
- padding: 24px 24px 0 24px;
- height: 205px;
- margin-bottom: 15px;
- .template-input-container {
- text-align: left;
- display: block; /* 改为block布局,避免flex对齐问题 */
- // margin-bottom: 10px;
- height: 120px; /* 固定高度,不再使用min-height */
- border-radius: 8px; /* 大输入框的圆角 */
- background-color: #fff; /* 大输入框的背景色 */
- transition: border-color 0.3s ease;
- cursor: text; /* 显示文本输入光标 */
- outline: none; /* 移除默认轮廓 */
- // padding: 16px; /* 恢复内边距 */
- font-size: 18px;
- line-height: 1.6;
- color: #000;
- overflow-y: auto; /* 添加垂直滚动条 */
- white-space: pre-line; /* 保留换行符,确保每个关键信息独占一行 */
- resize: none; /* 禁止手动调整大小 */
- &:focus-within {
- border-color: #3e7bfa; /* 当内部输入框聚焦时,大框也高亮 */
- }
- &:focus {
- border-color: #3e7bfa; /* 当整个容器聚焦时高亮 */
- }
- /* 支持文本输入 */
- &:empty:before {
- content: attr(placeholder);
- color: #9ca3af;
- pointer-events: none;
- }
- /* 自定义滚动条样式 */
- &::-webkit-scrollbar {
- width: 6px;
- }
- &::-webkit-scrollbar-track {
- background: #f1f1f1;
- border-radius: 3px;
- }
- &::-webkit-scrollbar-thumb {
- background: #c1c1c1;
- border-radius: 3px;
- }
- &::-webkit-scrollbar-thumb:hover {
- background: #a8a8a8;
- }
- .editable-highlight {
- background-color: #3E7BFA10; /* 特殊背景色 */
- color: #3E7BFA; /* 特殊字体颜色 */
- padding: 4px 8px;
- border-radius: 6px;
- font-weight: 500;
- cursor: text;
- transition: all 0.3s ease;
- border: 1px solid transparent;
- display: inline-block; /* 确保正确对齐 */
- min-width: 20px; /* 最小宽度,防止完全消失 */
- &:hover {
- background-color: #3E7BFA20;
- border-color: #3E7BFA30;
- }
- &:focus {
- background-color: #3E7BFA20;
- border-color: #3E7BFA;
- outline: none;
- }
- }
- }
- .text-input {
- width: 100%;
- min-height: 120px;
- border: none;
- outline: none;
- resize: none;
- font-size: 18px;
- line-height: 1.6;
- color: #000000;
- font-family: inherit;
- &::placeholder {
- color: #9ca3af;
- }
- }
- .input-actions {
- display: flex;
- justify-content: space-between;
- align-items: center;
- // margin-top: 16px;
- .left-actions {
- display: flex;
- align-items: center;
- gap: 12px;
-
- .attachment-btn {
- background: none;
- border: none;
- cursor: pointer;
- padding: 8px;
- border-radius: 6px;
- transition: background-color 0.3s ease;
- // &:hover {
- // background-color: #F3F4F6;
- // }
- .action-icon {
- width: 40px;
- height: 40px;
- }
- }
-
- // 文件预览样式 - 显示在输入框右边
- .file-preview-inline {
- display: flex;
- align-items: center;
- background: rgba(255, 255, 255, 0.9);
- border: 1px solid #E5E7EB;
- border-radius: 8px;
- padding: 6px 10px;
- margin-bottom: 5px;
- // margin-left: 8px;
- max-width: 200px;
-
- .file-info-inline {
- display: flex;
- align-items: center;
- gap: 6px;
-
- .file-icon-inline {
- font-size: 16px;
- flex-shrink: 0;
- }
-
- .file-icon-inline-img {
- width: 16px;
- height: 16px;
- object-fit: contain;
- flex-shrink: 0;
- }
-
- .file-name-inline {
- font-size: 12px;
- color: #374151;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- max-width: 120px;
- }
-
- .remove-file-inline {
- width: 16px;
- height: 16px;
- border: none;
- background: rgba(239, 68, 68, 0.1);
- color: #DC2626;
- border-radius: 50%;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- transition: all 0.2s ease;
- flex-shrink: 0;
-
- &:hover {
- background: rgba(239, 68, 68, 0.2);
- transform: scale(1.1);
- }
-
- .remove-icon {
- font-size: 12px;
- font-weight: bold;
- }
- }
- }
- }
- }
- .right-actions {
- display: flex;
- gap: 12px;
- align-items: center;
- .voice-btn {
- background: none;
- border: none;
- cursor: pointer;
- // padding: 8px;
- border-radius: 6px;
- transition: all 0.3s ease;
- position: relative;
- &:hover {
- background-color: #f3f4f6;
- }
- &.recording {
- background: rgba(239, 68, 68, 0.1);
- animation: pulse 1.5s ease-in-out infinite;
- }
- .icon-container {
- position: relative;
- display: flex;
- align-items: center;
- justify-content: center;
- }
- .recording-indicator {
- position: absolute;
- top: -2px;
- right: -2px;
- width: 8px;
- height: 8px;
- background: #ef4444;
- border-radius: 50%;
- animation: blink 1s ease-in-out infinite;
- }
- .action-icon {
- width: 20px;
- height: 20px;
- }
- }
- .divider {
- width: 1px;
- height: 31px;
- background: #d6d5de;
- }
- .send-btn {
- background: none;
- border: none;
- padding: 0;
- cursor: pointer;
- position: relative; /* 为生成中文字定位 */
- &:disabled {
- cursor: not-allowed;
- opacity: 0.6;
- }
- .action-icon {
- width: 90px;
- height: 40px;
- }
- .generating-text {
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- font-size: 12px;
- color: #666;
- white-space: nowrap;
- }
- }
- }
- }
- }
- .hint-text {
- font-size: 14px;
- color: #6b7280;
- margin: 0;
- text-align: start;
- }
- }
- .document-templates {
- flex: 1; /* 允许弹性增长 */
- display: flex;
- flex-direction: column;
- min-height: 0; /* 允许收缩 */
-
- .template-tabs {
- display: flex;
- gap: 40px;
- margin-bottom: 24px;
- border-bottom: 1px solid #e5e7eb;
- flex-shrink: 0; /* 防止被压缩 */
- .tab-item {
- padding: 10px 0;
- font-size: 16px;
- font-weight: 500;
- color: #4b5563;
- cursor: pointer;
- transition: all 0.3s ease;
- border-bottom: 3px solid transparent;
- width: 95px;
- // height: 52px;
- text-align: center;
- &:hover {
- color: #2563eb;
- }
- &.active {
- color: #2563eb;
- border-bottom-color: #2563eb;
- }
- }
- }
- .template-cards {
- display: flex;
- flex-direction: column;
- gap: 18px;
- flex: 1; /* 占满剩余空间 */
- min-height: 0; /* 允许收缩 */
- overflow-y: auto;
-
- /* 隐藏滚动条 */
- &::-webkit-scrollbar {
- display: none;
- }
-
- /* Firefox隐藏滚动条 */
- scrollbar-width: none;
-
- /* IE隐藏滚动条 */
- -ms-overflow-style: none;
- .template-card {
- position: relative;
- border-radius: 12px;
- background: #fafafa;
- // overflow: hidden;
-
- .template-image {
- width: 100%;
- height: auto;
- object-fit: contain;
- display: block;
- }
-
- .use-template-btn {
- position: absolute;
- right: 39px;
- bottom: 51px;
- padding: 8px 16px;
- border: none;
- border-radius: 9999px;
- font-size: 14px;
- font-weight: 500;
- cursor: pointer;
- transition: all 0.3s ease;
- z-index: 10;
-
- &.announcement-btn {
- background: rgba(29, 78, 216, 0.1);
- color: #1d4ed8;
- border: 1px solid #1d4ed8;
-
- &:hover {
- background: rgba(29, 78, 216, 0.2);
- }
- }
-
- &.notification-btn {
- background: rgba(126, 34, 206, 0.1);
- color: #7e22ce;
- border: 1px solid #7e22ce;
-
- &:hover {
- background: rgba(126, 34, 206, 0.2);
- }
- }
-
- &.report-btn {
- background: rgba(194, 65, 12, 0.1);
- color: #c2410c;
- border: 1px solid #c2410c;
- &:hover {
- background: rgba(194, 65, 12, 0.2);
- }
- }
- }
- }
- }
- }
- }
- }
- /* 固定布局,支持横向滚动 */
- .chat-container {
- min-width: 1428px; /* 设置最小宽度,确保内容完整显示 */
- }
- .work-content {
- min-width: 1428px; /* 工作内容区域最小宽度 */
- overflow-x: auto; /* 横向滚动条 */
- }
- .ai-writing-card {
- min-width: 1428px; /* AI写作卡片最小宽度 */
- }
- /* 详情页样式 */
- .detail-view {
- position: relative;
- width: 100%;
- max-width: 1528px;
- background: white;
- border-radius: 16px;
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
- overflow: hidden;
- min-width: 1428px;
- min-height: 800px; /* 最小高度 */
- max-height: calc(100vh - 96px); /* 最大高度,防止超出视窗 */
- height: calc(100vh - 128px); /* 自适应高度 */
- display: flex;
- flex-direction: column;
- transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); // 整体过渡动画
- .main-content1 {
- display: flex;
- flex-direction: row;
- padding: 22px 32px;
- gap: 32px;
- flex: 1;
- position: relative; // 为动画定位
- transition: gap 0.4s cubic-bezier(0.4, 0, 0.2, 1); // gap变化动画
- height: 100%; // 确保占满高度
- overflow: hidden; // 防止内容溢出
- // 默认状态:聊天区域占一半宽度,居中显示
- &:not(.with-document) {
- gap: 0; // 没有分栏时,gap为0
- justify-content: center; // 让内容居中显示
-
- .left-column {
- width: 50%; // 占一半宽度
- margin: 0; // 移除margin居中,保持与有右侧区域时相同的布局
- padding: 0 32px 0 0; // 与有文档时的padding保持一致,只有右边距
- display: flex;
- flex-direction: column;
- align-items: center;
- transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); // 平滑过渡
- transform: translateX(0); // 确保在中心位置
- height: 100%; // 确保占满高度
- }
- }
- // 显示文档预览时:聊天区域向左滑动
- &.with-document {
- gap: 0; // 减少gap,让左右两列更贴近
- .left-column {
- width: 50%; // 保持一半宽度
- padding: 0 32px 0 0;
- align-items: flex-start;
- transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); // 平滑过渡
- transform: translateX(0); // 确保在左侧位置
- height: 100%; // 确保占满高度
- }
- }
- .left-column {
- display: flex;
- flex-direction: column;
- height: 100%; /* 占满整个高度 */
- width: 100%; /* 确保宽度 */
- transition: none; /* 移除过渡动画,提高响应速度 */
- .chat-area {
- flex: 1; /* 占据剩余空间 */
- overflow-y: auto; /* 允许垂直滚动 */
- padding: 20px 0;
- margin-bottom: 0; /* 移除底部边距 */
- min-height: 0; /* 允许收缩 */
- width: 100%;
- max-height: calc(100vh - 320px); /* 设置最大高度,留出输入框空间 */
- transition: none;
- .message-item {
- margin-bottom: 20px;
- width: 100%;
- &.user {
- .user-message {
- display: flex;
- flex-direction: column;
- align-items: flex-end;
- gap: 8px;
- width: 100%;
- .message-content {
- background: #004bff20;
- color: #000;
- padding: 16px;
- border-radius: 8px 0px 8px 8px;
- font-size: 16px;
- line-height: 1.6;
- max-width: 70%;
- min-width: 0;
- text-align: left;
- word-wrap: break-word;
- overflow-wrap: break-word;
-
- .message-file {
- margin-bottom: 12px;
-
- .file-display {
- display: flex;
- align-items: center;
- background: rgba(255, 255, 255, 0.8);
- border: 1px solid #E5E7EB;
- border-radius: 12px;
- padding: 16px;
- max-width: 400px;
-
- .file-icon {
- font-size: 32px;
- margin-right: 16px;
- width: 48px;
- text-align: center;
-
- .file-icon-img {
- width: 32px;
- height: 32px;
- object-fit: contain;
- }
- }
-
- .file-details {
- flex: 1;
-
- .file-name {
- font-size: 14px;
- font-weight: 500;
- color: #374151;
- margin-bottom: 4px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- max-width: 200px;
- }
-
- .file-size {
- font-size: 12px;
- color: #6B7280;
- }
- }
- }
- }
-
- .message-text {
- // margin-top: 8px;
- word-wrap: break-word;
- word-break: break-all;
- overflow-wrap: break-word;
- white-space: pre-wrap;
- max-width: 100%;
- }
- }
- .message-time {
- font-size: 12px;
- color: #6b7280;
- margin-top: 4px;
- text-align: right;
- }
- .action-buttons {
- display: flex;
- // margin-top: 128px;
- align-items: center;
- flex-wrap: wrap;
- // gap: 128px;
- justify-content: flex-end;
- .action-btn {
- background: none;
- color: #6b7280;
- border: none;
- border-radius: 6px;
- padding: 6px 5px;
- font-size: 14px;
- cursor: pointer;
- transition: all 0.3s ease;
- display: flex;
- align-items: center;
- gap: 4px;
- white-space: nowrap;
- &:hover {
- background: #f3f4f6;
- }
- .action-icon {
- width: 16px;
- height: 16px;
- }
- }
- }
- }
- }
- &.ai {
- .ai-message {
- display: flex;
- align-items: flex-start;
- gap: 12px;
- width: 100%;
- .ai-avatar {
- flex-shrink: 0;
-
- .avatar-img {
- width: 40px;
- height: 40px;
- border-radius: 8px;
- background: #3e7bfa;
- display: flex;
- align-items: center;
- justify-content: center;
- color: white;
- font-weight: bold;
- font-size: 16px;
- }
- }
- .message-content {
- background: #fff;
- border: 1px solid #e2e8f0;
- color: #000;
- padding: 16px 20px;
- border-radius: 0px 8px 8px 8px;
- font-size: 16px;
- line-height: 1.6;
- max-width: 70%;
- flex: 1;
- // 表格样式
- table {
- border-collapse: collapse;
- width: 100%;
- margin: 16px 0;
- border: 1px solid #ddd;
- }
- td, th {
- border: 1px solid #ddd;
- padding: 8px 12px;
- text-align: left;
- }
- th {
- background-color: #f8f9fa;
- font-weight: bold;
- }
- tr:nth-child(even) {
- background-color: #f8f9fa;
- }
- .opening-text {
- margin-bottom: 16px;
- color: #374151;
- }
- .closing-text {
- margin-top: 16px;
- color: #374151;
- }
- .document-info {
- display: flex;
- align-items: center;
- gap: 12px;
- padding: 12px 16px;
- background: white;
- border-radius: 8px;
- margin: 16px 0;
- border: 1px solid #e5e7eb;
- cursor: pointer;
- transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
- background-color: #e5e5e550;
- &:hover {
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
- border-color: #3e7bfa;
- transform: translateY(-2px);
- background-color: #f8fafc;
- }
- .info-icon {
- width: 24px;
- height: 24px;
- flex-shrink: 0;
- }
- .doc-details {
- flex: 1;
- .doc-title {
- font-size: 16px;
- font-weight: 600;
- color: #000;
- margin-bottom: 4px;
- }
- .doc-time {
- font-size: 12px;
- color: #6b7280;
- }
- }
- }
- .action-buttons {
- display: flex;
- justify-content: space-between;
- margin-top: 16px;
- border-top: 1px solid #e5e7eb;
- padding-top: 6px;
- align-items: center;
- flex-wrap: wrap;
- // gap: 128px;
- .left-actions {
- display: flex;
- gap: 8px;
- flex-wrap: wrap;
- }
-
- .right-actions {
- display: flex;
- gap: 8px;
- }
- .action-btn {
- background: none;
- color: #6b7280;
- border: none;
- border-radius: 6px;
- padding: 6px 5px;
- font-size: 14px;
- cursor: pointer;
- transition: all 0.3s ease;
- display: flex;
- align-items: center;
- gap: 4px;
- white-space: nowrap;
- &:hover:not(:disabled) {
- background-color: #f3f4f6;
- }
-
- &:disabled {
- cursor: not-allowed;
- opacity: 0.6;
- }
- .action-icon {
- width: 16px;
- height: 16px;
- }
-
- // 点赞和点踩按钮的特殊样式
- &.thumbs-up-btn {
- transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
-
- &:hover:not(:disabled) {
- color: #059669;
- transform: scale(1.1);
- background-color: rgba(5, 150, 105, 0.1);
- }
-
- &.active {
- color: #059669;
- transform: scale(1.2);
-
- .action-icon {
- filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(142deg) brightness(104%) contrast(97%) !important;
- }
- }
-
- &:active {
- transform: scale(0.9);
- transition: all 0.1s ease;
- }
- }
-
- &.thumbs-down-btn {
- transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
-
- &:hover:not(:disabled) {
- color: #dc2626;
- transform: scale(1.1);
- background-color: rgba(220, 38, 38, 0.1);
- }
-
- &.active {
- color: #dc2626;
- transform: scale(1.2);
-
- .action-icon {
- filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(0deg) brightness(104%) contrast(97%) !important;
- }
- }
-
- &:active {
- transform: scale(0.9);
- transition: all 0.1s ease;
- }
- }
- }
- .feedback-icon {
- width: 16px;
- height: 16px;
- cursor: pointer;
- transition: opacity 0.3s ease;
- margin: 0 5px;
- &:hover {
- opacity: 0.7;
- }
- }
- }
- }
- }
- }
- &.generating {
- display: flex;
- align-items: flex-start;
- gap: 12px;
- width: 100%;
- .ai-avatar {
- flex-shrink: 0;
-
- .avatar-img {
- width: 40px;
- height: 40px;
- border-radius: 8px;
- background: #3e7bfa;
- display: flex;
- align-items: center;
- justify-content: center;
- color: white;
- font-weight: bold;
- font-size: 16px;
- }
- }
- .message-content {
- background: #fff;
- border: 1px solid #e2e8f0;
- color: #000;
- padding: 12px 16px;
- border-radius: 12px;
- font-size: 16px;
- line-height: 1.6;
- max-width: fit-content;
- min-width: 120px;
- display: flex;
- align-items: center;
- gap: 12px;
- .generating-text {
- color: #6b7280;
- font-size: 14px;
- white-space: nowrap;
- }
- .loading-dots {
- display: flex;
- gap: 4px;
- span {
- width: 6px;
- height: 6px;
- background: #3e7bfa;
- border-radius: 50%;
- animation: loading 1.4s infinite ease-in-out;
- &:nth-child(1) { animation-delay: -0.32s; }
- &:nth-child(2) { animation-delay: -0.16s; }
- &:nth-child(3) { animation-delay: 0s; }
- }
- }
- }
- }
- }
- @keyframes loading {
- 0%, 80%, 100% {
- transform: scale(0);
- opacity: 0.5;
- }
- 40% {
- transform: scale(1);
- opacity: 1;
- }
- }
- /* 自定义滚动条样式 */
- &::-webkit-scrollbar {
- width: 0; /* 隐藏滚动条 */
- }
- &::-webkit-scrollbar-track {
- display: none; /* 隐藏滚动条轨道 */
- }
- &::-webkit-scrollbar-thumb {
- display: none; /* 隐藏滚动条滑块 */
- }
- &::-webkit-scrollbar-thumb:hover {
- display: none; /* 隐藏滚动条滑块悬停状态 */
- }
- }
- // 输入框区域样式
- .input-section {
- background: white;
- display: flex;
- flex-direction: column;
- align-items: center;
- width: 100%;
- position: sticky; /* 固定在底部 */
- bottom: 0;
- padding-top: 32px; /* 增加上方间距 */
- // padding: 320px 0;
- // border-top: 16px solid #e5e7eb;
- z-index: 10;
- transition: none; /* 移除过渡动画,提高响应速度 */
- will-change: transform; /* 优化渲染性能 */
-
- // 文件预览区域样式
- .file-preview-section {
- margin-bottom: 12px;
- width: 100%;
- max-width: 780px;
-
- .file-preview {
- position: relative;
- display: flex;
- align-items: center;
- background: rgba(255, 255, 255, 0.9);
- border: 1px solid #E5E7EB;
- border-radius: 12px;
- padding: 12px;
- max-width: 400px;
-
- .file-icon {
- font-size: 32px;
- margin-right: 12px;
- width: 48px;
- text-align: center;
-
- .file-icon-img {
- width: 32px;
- height: 32px;
- object-fit: contain;
- }
- }
-
- .file-info {
- flex: 1;
-
- .file-name {
- font-size: 14px;
- font-weight: 500;
- color: #374151;
- margin-bottom: 4px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- max-width: 200px;
- }
-
- .file-size {
- font-size: 12px;
- color: #6B7280;
- }
- }
-
- .remove-file-btn {
- width: 24px;
- height: 24px;
- border: none;
- background: rgba(239, 68, 68, 0.1);
- color: #DC2626;
- border-radius: 50%;
- cursor: pointer;
- display: flex;
- align-items: center;
- justify-content: center;
- transition: all 0.2s ease;
-
- &:hover {
- background: rgba(239, 68, 68, 0.2);
- transform: scale(1.1);
- }
-
- .remove-icon {
- font-size: 16px;
- font-weight: bold;
- }
- }
- }
- }
- .input-container {
- width: 100%;
- max-width: 780px; // 固定最大宽度
- display: flex;
- align-items: center;
- gap: 12px;
- border: 1px solid #3e7bfa;
- border-radius: 16px;
- padding: 12px 16px;
- background: white;
- .attachment-btn,
- .voice-btn {
- background: none;
- border: none;
- cursor: pointer;
- padding: 8px 8px 4px 8px;
- border-radius: 6px;
- transition: all 0.3s ease;
- position: relative;
- &:hover:not(:disabled) {
- background-color: #f3f4f6;
- }
- &.recording {
- background: rgba(239, 68, 68, 0.1);
- animation: pulse 1.5s ease-in-out infinite;
- }
- .icon-container {
- position: relative;
- display: flex;
- align-items: center;
- justify-content: center;
- }
- .recording-indicator {
- position: absolute;
- top: -2px;
- right: -2px;
- width: 8px;
- height: 8px;
- background: #ef4444;
- border-radius: 50%;
- animation: blink 1s ease-in-out infinite;
- }
-
- &:disabled {
- cursor: not-allowed;
- opacity: 0.6;
- }
- .action-icon {
- width: 20px;
- height: 20px;
- object-fit: contain;
- }
- }
- .message-input {
- flex: 1;
- border: none;
- outline: none;
- font-size: 16px;
- color: #374151;
- background: transparent;
- min-width: 0;
- &::placeholder {
- color: #9ca3af;
- }
-
- &:disabled {
- cursor: not-allowed;
- opacity: 0.6;
- background-color: #f9fafb;
- }
- }
- .divider {
- width: 1px;
- height: 31px;
- background: #d6d5de;
- }
- .send-btn {
- background: none;
- border: none;
- cursor: pointer;
- padding: 0;
- border-radius: 6px;
- transition: background-color 0.3s ease;
- min-width: 90px; /* 确保最小宽度 */
- height: 40px; /* 确保高度 */
- display: flex;
- align-items: center;
- justify-content: center;
- &:disabled {
- cursor: not-allowed;
- opacity: 0.6;
- }
- &:hover:not(:disabled) {
- background-color: #f3f4f6;
- }
- .action-icon {
- width: 90px;
- height: 40px;
- object-fit: contain; /* 确保图标不被压缩 */
- }
- }
- }
- }
- }
- .right-column {
- width: 50%; // 改为50%,与左侧列相等
- padding-left: 31px; // 减少左边距,让分隔线更贴近
- border-left: 1px solid #e5e7eb;
- display: flex;
- flex-direction: column;
- transform: translateX(100%); // 初始状态:向右偏移隐藏
- opacity: 0; // 初始状态:透明
- transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); // 平滑过渡
- .document-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: 16px;
- padding-bottom: 16px;
- // border-bottom: 1px solid #e5e7eb;
- transform: translateY(20px); // 初始状态:向下偏移
- opacity: 0; // 初始状态:透明
- transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1) 0.1s; // 延迟动画
- .doc-title {
- font-size: 22px;
- font-weight: 600;
- color: #1f2937;
- margin: 0;
- }
- .doc-actions {
- display: flex;
- gap: 10px;
- align-items: center;
- .action-btn {
- background: none;
- border: none;
- color: #6b7280;
- font-size: 14px;
- cursor: pointer;
- padding: 8px;
- border-radius: 6px;
- transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); // 统一缓动函数
- display: flex;
- align-items: center;
- gap: 6px;
- &:hover {
- background: #f3f4f6;
- color: #374151;
- transform: translateY(-1px); // 悬停时轻微上移
- }
- .action-icon {
- width: 16px;
- height: 16px;
- }
- }
- .close-btn {
- background: none;
- border: none;
- color: #6b7280;
- font-size: 14px;
- cursor: pointer;
- padding: 8px;
- border-radius: 6px;
- transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); // 统一缓动函数
- display: flex;
- align-items: center;
- gap: 6px;
- &:hover {
- background: #f3f4f6;
- color: #374151;
- transform: translateY(-1px); // 悬停时轻微上移
- }
- }
- }
- }
- .document-body {
- transform: translateY(20px); // 初始状态:向下偏移
- opacity: 0; // 初始状态:透明
- transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1) 0.2s; // 延迟动画
- max-height: calc(100vh - 300px); // 设置最大高度
- overflow-y: auto; // 添加垂直滚动条
- .doc-section {
- margin-bottom: 16px; // 减少section之间的间距
- .section-content {
- font-size: 16px;
- line-height: 1.6;
- color: #374151;
- margin: 0;
- text-align: justify;
- padding-right: 16px; // 添加右边距,让文字和滚动条之间有间距
-
- // 调整富文本元素的间距
- h1, h2, h3 {
- margin: 16px 0 8px 0; // 标题的上下间距
- font-weight: 600;
- color: #1f2937;
- }
-
- h1 {
- font-size: 20px;
- }
-
- h2 {
- font-size: 18px;
- }
-
- h3 {
- font-size: 16px;
- }
-
- p {
- margin: 8px 0; // 段落间距
- }
-
- li {
- margin: 4px 0; // 列表项间距
- }
-
- .list-item {
- margin: 4px 0; // 列表项间距
- padding-left: 8px; // 轻微缩进
- }
-
- ul, ol {
- margin: 8px 0;
- padding-left: 20px;
- }
- }
- }
- /* 自定义滚动条样式 */
- &::-webkit-scrollbar {
- width: 6px;
- }
- &::-webkit-scrollbar-track {
- background: #f1f1f1;
- border-radius: 3px;
- }
- &::-webkit-scrollbar-thumb {
- background: #c1c1c1;
- border-radius: 3px;
- }
- &::-webkit-scrollbar-thumb:hover {
- background: #a8a8a8;
- }
- }
- }
- // 当显示文档预览时,右侧列显示
- &.with-document {
- .right-column {
- transform: translateX(0);
- opacity: 1;
- .document-header,
- .document-body {
- transform: translateY(0);
- opacity: 1;
- }
- }
- }
- }
- .history-card {
- display: flex;
- align-items: center;
- gap: 16px;
- padding: 20px 32px;
- background: #f9fafb;
- border-top: 1px solid #e5e7eb;
- border-bottom: 1px solid #e5e7eb;
- .card-icon {
- .doc-icon {
- width: 48px;
- height: 48px;
- }
- }
- .card-content {
- .card-title {
- font-size: 18px;
- font-weight: 600;
- color: #1f2937;
- margin-bottom: 4px;
- }
- .card-time {
- font-size: 14px;
- color: #6b7280;
- }
- }
- }
- .follow-up-text {
- padding: 24px 32px;
- font-size: 16px;
- color: #374151;
- line-height: 1.6;
- background: white;
- }
- }
- /* 中间历史记录栏 */
- .history-sidebar {
- width: 280px;
- background: #e8f0ff;
- display: flex;
- flex-direction: column;
- }
- /* 中间历史记录栏样式 */
- .history-sidebar {
- padding: 24px 16px 0 16px;
- .history-header {
- background: transparent;
-
- .section-title {
- font-size: 16px;
- font-weight: 600;
- color: #2c3e50;
- }
-
- .new-chat-btn {
- width: 248px;
- height: 40px;
- cursor: pointer;
- transition: opacity 0.3s ease;
- object-fit: contain;
- display: block;
- margin-top: 16px;
- margin-bottom: 16px;
-
- &:hover {
- opacity: 0.8;
- }
-
- &.disabled {
- cursor: not-allowed;
- opacity: 0.6;
-
- &:hover {
- opacity: 0.6;
- }
- }
- }
- }
-
- .history-list {
- flex: 1;
- overflow-y: auto;
- width: 248px;
- height: 64px;
-
- /* 隐藏滚动条 */
- &::-webkit-scrollbar {
- display: none;
- }
-
- -ms-overflow-style: none; /* IE and Edge */
- scrollbar-width: none; /* Firefox */
-
- .history-item {
- background: white;
- border-radius: 8px;
- padding: 15px;
- margin-bottom: 8px;
- cursor: pointer;
- transition: all 0.3s ease;
- border-left: 3px solid transparent;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
- display: flex;
- align-items: center;
- justify-content: space-between;
- position: relative;
-
- &:hover {
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
-
- .delete-btn {
- opacity: 1;
- visibility: visible;
- }
- }
-
- &.active {
- border-left-color: #3e7bfa;
- box-shadow: 0 2px 8px rgba(62, 123, 250, 0.2);
- cursor: default;
- opacity: 0.8;
-
- &:hover {
- transform: none;
- box-shadow: 0 2px 8px rgba(62, 123, 250, 0.2);
- }
- }
-
- .history-content {
- flex: 1;
- min-width: 0; // 允许内容收缩
- }
-
- .history-title {
- font-size: 14px;
- line-height: 1.4;
- margin-bottom: 6px;
- color: #2c3e50;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
-
- .history-time {
- font-size: 12px;
- color: #7c8db5;
- }
-
- .delete-btn {
- opacity: 0;
- visibility: hidden;
- transition: all 0.2s ease;
- cursor: pointer;
- padding: 4px;
- border-radius: 4px;
- color: #7c8db5;
- display: flex;
- align-items: center;
- justify-content: center;
- margin-left: 8px;
- flex-shrink: 0;
-
- &:hover {
- color: #ff4757;
- background-color: rgba(255, 71, 87, 0.1);
- }
-
- &.always-visible {
- opacity: 1;
- visibility: visible;
- }
- }
- }
-
- .empty-history {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- margin-top: 236px;
-
- .empty-icon {
- width: 147px;
- height: 148px;
- object-fit: contain;
- margin-bottom: 16px;
- }
-
- .empty-text {
- font-size: 16px;
- color: #9C9FA7;
- text-align: center;
- }
- }
- }
- }
- /* 主工作区域 */
- .main-work {
- flex: 1;
- background: #ebf3ff;
- display: flex;
- flex-direction: column;
- }
- /* 富文本编辑器样式 */
- .editor-view {
- position: relative;
- width: 100%;
- max-width: 1528px;
- background: white;
- border-radius: 12px;
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
- display: flex;
- flex-direction: column;
- // height: calc(100vh - 40px);
- // margin: -20px;
- // overflow: hidden;
- }
- .editor-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 24px 32px;
- border-bottom: 1px solid #e5e7eb;
- background: #f9fafb;
- }
- .editor-title h3 {
- margin: 0;
- font-size: 24px;
- font-weight: 600;
- color: #1f2937;
- }
- .editor-subtitle {
- margin: 4px 0 0 0;
- font-size: 14px;
- color: #6b7280;
- }
- .editor-actions {
- display: flex;
- gap: 12px;
- }
- .back-btn, .save-btn, .download-btn {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 7px 20px;
- border: none;
- border-radius: 8px;
- font-size: 14px;
- font-weight: 500;
- cursor: pointer;
- transition: all 0.2s ease;
- }
- .back-btn {
- background: #f3f4f6;
- color: #374151;
- }
- .back-btn:hover {
- background: #e5e7eb;
- }
- .save-btn {
- background: #3b82f6;
- color: white;
- }
- .save-btn:hover {
- background: #2563eb;
- }
- .download-btn {
- border: none;
- background: transparent;
- cursor: pointer;
- transition: opacity 0.3s ease;
- padding: 0;
- }
- .download-btn:hover {
- opacity: 0.8;
- }
- .download-icon {
- width: 107px;
- height: 34px;
- }
- .action-icon {
- width: 16px;
- height: 16px;
- }
- .editor-content {
- flex: 1;
- display: flex;
- flex-direction: column;
- overflow: auto;
- // background: red;
- min-height: 0;
- padding-bottom: 10px;
- }
- /* 富文本工具栏样式 */
- .editor-toolbar {
- display: flex;
- align-items: center;
- padding: 12px 16px;
- background: #f8f9fa;
- border-bottom: 1px solid #e5e7eb;
- gap: 8px;
- flex-wrap: wrap;
- }
- .toolbar-group {
- display: flex;
- align-items: center;
- gap: 4px;
- }
- .toolbar-divider {
- width: 1px;
- height: 24px;
- background: #d1d5db;
- margin: 0 8px;
- }
- .toolbar-btn {
- display: flex;
- align-items: center;
- justify-content: center;
- width: 32px;
- height: 32px;
- border: 1px solid #d1d5db;
- background: white;
- border-radius: 4px;
- cursor: pointer;
- font-size: 14px;
- font-weight: 500;
- color: #374151;
- transition: all 0.2s ease;
- }
- .toolbar-btn:hover {
- background: #f3f4f6;
- border-color: #9ca3af;
- }
- .toolbar-btn:active {
- background: #e5e7eb;
- transform: translateY(1px);
- }
- .toolbar-btn:disabled {
- background: #f9fafb;
- color: #9ca3af;
- cursor: not-allowed;
- opacity: 0.6;
- }
- .toolbar-btn:disabled:hover {
- background: #f9fafb;
- border-color: #d1d5db;
- transform: none;
- }
- .toolbar-btn strong {
- font-weight: bold;
- }
- .toolbar-btn em {
- font-style: italic;
- }
- .toolbar-btn u {
- text-decoration: underline;
- }
- .font-size-select, .font-family-select {
- height: 32px;
- padding: 4px 8px;
- border: 1px solid #d1d5db;
- background: white;
- border-radius: 4px;
- font-size: 14px;
- color: #374151;
- cursor: pointer;
- transition: all 0.2s ease;
- min-width: 80px;
- }
- .font-size-select:hover, .font-family-select:hover {
- border-color: #9ca3af;
- }
- .font-size-select:focus, .font-family-select:focus {
- outline: none;
- border-color: #3b82f6;
- box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
- }
- .rich-editor-container {
- flex: 1;
- padding: 0px 32px 20px 32px;
- overflow: hidden;
- background: white;
- border-radius: 8px;
- display: flex;
- flex-direction: column;
- min-height: 0;
- }
- /* 富文本编辑器工具栏样式 */
- .rich-editor-toolbar {
- border-bottom: 1px solid #ccc;
- }
- /* wangeditor 编辑器基础样式 */
- .rich-editor-container .w-e-scroll {
- border: 1px solid #e5e7eb !important;
- border-radius: 8px !important;
- font-size: 16px;
- line-height: 1.6;
- background: white !important;
- }
- /* 禁用wangeditor自带的弹出菜单 */
- .rich-editor-container .w-e-hover-bar {
- display: none !important;
- }
- .rich-editor-container .w-e-menu-tooltip {
- display: none !important;
- }
- .rich-editor-container .w-e-menu {
- display: none !important;
- }
- .rich-editor-container .w-e-menu-panel {
- display: none !important;
- }
- .rich-editor-container .w-e-menu-item {
- display: none !important;
- }
- /* 禁用右键菜单 */
- .rich-editor-container .w-e-text-container {
- -webkit-user-select: text !important;
- -moz-user-select: text !important;
- -ms-user-select: text !important;
- user-select: text !important;
- }
- .rich-editor-container .w-e-text-container * {
- -webkit-user-select: text !important;
- -moz-user-select: text !important;
- -ms-user-select: text !important;
- user-select: text !important;
- }
- /* 润色时禁用文本选择 */
- .rich-editor-container.polishing .w-e-text-container {
- -webkit-user-select: none !important;
- -moz-user-select: none !important;
- -ms-user-select: none !important;
- user-select: none !important;
- pointer-events: none !important;
- }
- .rich-editor-container.polishing .w-e-text-container * {
- -webkit-user-select: none !important;
- -moz-user-select: none !important;
- -ms-user-select: none !important;
- user-select: none !important;
- pointer-events: none !important;
- }
- .rich-editor-container .w-e-toolbar {
- border: 1px solid #e5e7eb !important;
- border-bottom: none !important;
- border-radius: 8px 8px 0 0 !important;
- padding: 12px 0 !important;
- background: white !important;
- }
- .rich-editor {
- min-height: 100%;
- padding: 24px;
- border: 1px solid #e5e7eb;
- border-radius: 8px;
- background: white;
- font-size: 16px;
- line-height: 1.6;
- color: #1f2937;
- outline: none;
- transition: border-color 0.2s ease;
- }
- .rich-editor:focus {
- border-color: #3b82f6;
- box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
- }
- .rich-editor h2 {
- font-size: 24px;
- font-weight: 600;
- color: #1f2937;
- margin: 24px 0 16px 0;
- padding-bottom: 8px;
- border-bottom: 2px solid #e5e7eb;
- }
- .rich-editor h3 {
- font-size: 20px;
- font-weight: 600;
- color: #374151;
- margin: 20px 0 12px 0;
- }
- .rich-editor h4 {
- font-size: 18px;
- font-weight: 600;
- color: #4b5563;
- margin: 16px 0 8px 0;
- }
- .rich-editor p {
- margin: 12px 0;
- text-align: justify;
- }
- .rich-editor ul, .rich-editor ol {
- margin: 12px 0;
- padding-left: 24px;
- }
- .rich-editor li {
- margin: 4px 0;
- }
- .rich-editor blockquote {
- margin: 16px 0;
- padding: 16px 20px;
- background: #f9fafb;
- border-left: 4px solid #3b82f6;
- border-radius: 0 8px 8px 0;
- font-style: italic;
- color: #4b5563;
- }
- /* 工作头部 */
- .work-header {
- background: transparent;
- padding: 30px 0px 0px 18px;
-
- h2 {
- margin: 0;
- font-size: 20px;
- font-weight: 600;
- color: #2c3e50;
- }
- }
- /* 响应式设计 */
- /* @media (max-width: 16384px) {
- .history-sidebar {
- width: 4000px;
- }
- }
- @media (max-width: 14400px) {
- .history-sidebar {
- width: 3840px;
- }
- }
- @media (max-width: 12288px) {
- .chat-container {
- flex-direction: column;
- }
- .history-sidebar {
- width: 100%;
- height: 3200px;
- order: 2;
- .history-list {
- .history-item {
- padding: 160px 320px;
- .history-title {
- font-size: 208px;
- }
- }
- }
- }
- .main-work {
- order: 1;
- }
- .work-content {
- padding: 320px 256px;
- }
- } */
- /* 点赞和点踩按钮的图标颜色变化 */
- .thumbs-up-btn.active .action-icon {
- /* 绿色图标 */
- filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(142deg) brightness(104%) contrast(97%) !important;
- }
- .thumbs-down-btn.active .action-icon {
- /* 红色图标 */
- filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(0deg) brightness(104%) contrast(97%) !important;
- }
- /* 历史记录加载状态样式 */
- .history-loading {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 40px 20px;
- min-height: 200px;
- }
- .history-loading .loading-spinner {
- width: 32px;
- height: 32px;
- border: 3px solid #f3f3f3;
- border-top: 3px solid #409eff;
- border-radius: 50%;
- animation: spin 1s linear infinite;
- margin: 0 auto 16px auto;
- }
- .history-loading .loading-text {
- color: #6B7280;
- font-size: 14px;
- margin: 0;
- font-weight: 400;
- }
- /* 编辑器全屏加载状态样式 */
- .editor-full-loading {
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- background: rgba(255, 255, 255, 0.95);
- backdrop-filter: blur(4px);
- z-index: 1000;
- border-radius: 12px;
- }
- .editor-full-loading .loading-spinner {
- width: 48px;
- height: 48px;
- border: 4px solid #f3f3f3;
- border-top: 4px solid #3b82f6;
- border-radius: 50%;
- animation: spin 1s linear infinite;
- margin: 0 auto 24px auto;
- }
- .editor-full-loading .loading-text {
- color: #374151;
- font-size: 18px;
- margin: 0;
- font-weight: 500;
- }
- @keyframes spin {
- 0% { transform: rotate(0deg); }
- 100% { transform: rotate(360deg); }
- }
- /* 详情页加载状态样式 */
- .detail-loading {
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- background: rgba(255, 255, 255, 0.95);
- backdrop-filter: blur(4px);
- z-index: 1000;
- border-radius: 16px;
- }
- .detail-loading .loading-spinner {
- width: 48px;
- height: 48px;
- border: 4px solid #f3f3f3;
- border-top: 4px solid #3b82f6;
- border-radius: 50%;
- animation: spin 1s linear infinite;
- margin: 0 auto 24px auto;
- }
- .detail-loading .loading-text {
- color: #374151;
- font-size: 18px;
- margin: 0;
- font-weight: 500;
- }
- /* AI润色输入框样式 */
- .ai-polish-input {
- position: fixed;
- z-index: 999;
- background: white;
- border-radius: 8px;
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
- transition: all 0.2s ease;
- user-select: none;
- min-width: 300px;
- max-width: 400px;
- }
- .polish-input-container {
- display: flex;
- align-items: center;
- padding: 8px;
- gap: 8px;
- }
- .button-group {
- display: flex;
- align-items: center;
- gap: 6px;
- }
- .input-wrapper {
- flex: 1;
- position: relative;
- }
- .polish-input-field {
- width: 100%;
- border: 1px solid #e5e7eb;
- border-radius: 6px;
- padding: 8px 60px 8px 12px;
- font-size: 14px;
- outline: none;
- transition: border-color 0.2s ease;
- box-sizing: border-box;
- }
- .char-counter {
- position: absolute;
- right: 12px;
- top: 50%;
- transform: translateY(-50%);
- font-size: 12px;
- color: #6b7280;
- pointer-events: none;
- }
- .polish-input-field:focus {
- border-color: #3b82f6;
- box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
- }
- .polish-input-field:disabled {
- background-color: #f9fafb;
- color: #6b7280;
- cursor: not-allowed;
- }
- .polish-send-btn {
- background: #3b82f6;
- color: white;
- border: none;
- cursor: pointer;
- padding: 8px 16px;
- border-radius: 6px;
- font-size: 14px;
- font-weight: 500;
- transition: all 0.2s ease;
- min-width: 80px;
- }
- .polish-send-btn:hover:not(:disabled) {
- background-color: #2563eb;
- }
- .polish-send-btn:disabled {
- cursor: not-allowed;
- opacity: 0.6;
- background-color: #9ca3af;
- }
- .continue-btn {
- background: #10b981;
- }
- .continue-btn:hover:not(:disabled) {
- background-color: #059669;
- }
- .polish-loading {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 8px;
- }
- .polish-loading .loading-spinner {
- width: 16px;
- height: 16px;
- border: 2px solid rgba(255, 255, 255, 0.3);
- border-top: 2px solid white;
- border-radius: 50%;
- animation: spin 1s linear infinite;
- }
- @keyframes pulse {
- 0%, 100% {
- transform: scale(1);
- opacity: 1;
- }
- 50% {
- transform: scale(1.05);
- opacity: 0.8;
- }
- }
- @keyframes blink {
- 0%, 50% {
- opacity: 1;
- }
- 51%, 100% {
- opacity: 0.3;
- }
- }
- /* 响应式设计 */
- </style>
|