index.vue 211 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341
  1. <template>
  2. <div class="pptist-student-viewer" :class="{ 'fullscreen': isFullscreen }">
  3. <!-- Loading状态显示 -->
  4. <div v-if="isLoading" class="loading-overlay">
  5. <div class="loading-content">
  6. <div class="loading-spinner"></div>
  7. <div class="loading-text">{{ lang.ssCourseLoading }}</div>
  8. </div>
  9. </div>
  10. <!-- 左侧导航栏 -->
  11. <div class="layout-content-left" v-show="type == '1' || (type == '2' && !isFollowModeActive)" :class="{ collapsed: slidePanelCollapsed }">
  12. <div class="thumbnails">
  13. <div class="viewer-header slide-header">
  14. <h3 v-show="!slidePanelCollapsed">{{ lang.ssCourseOutline }}</h3>
  15. <button class="collapse-btn" @click="slidePanelCollapsed = !slidePanelCollapsed" :title="slidePanelCollapsed ? lang.ssExpand : lang.ssCollapse" style="right: 8px;">
  16. <span v-if="slidePanelCollapsed">
  17. <img src="@/assets/img/arrow.svg">
  18. </span>
  19. <span v-else>
  20. <img src="@/assets/img/arrow.svg" style="transform: rotate(180deg);">
  21. </span>
  22. </button>
  23. </div>
  24. <div v-if="!slidePanelCollapsed" class="panel-content">
  25. <div class="thumbnail-list">
  26. <div v-for="(slide, index) in slides" :key="slide.id" class="thumbnail-item"
  27. :class="{ 'active': slideIndex === index }" @click="goToSlide(index)">
  28. <div class="label">{{ fillDigit(index + 1, 2) }}</div>
  29. <ThumbnailSlide class="thumbnail" :slide="slide" :size="168" :visible="true" @click="goToSlide(index)" />
  30. </div>
  31. </div>
  32. </div>
  33. </div>
  34. </div>
  35. <!-- 中间放映区域 -->
  36. <div class="layout-content-center">
  37. <div class="viewer-header" :class="{ 'hidden': isFullscreen }" style="display: none;">
  38. <div class="slide-title">{{ lang.ssSlidePage }} {{ slideIndex + 1 }}</div>
  39. <div class="viewer-controls">
  40. <button @click="previousSlide" :disabled="slideIndex === 0" :title="lang.ssPrevPage" v-if="!isFollowModeActive || props.type == '1'">
  41. <IconLeftTwo class="control-icon" />
  42. </button>
  43. <button @click="nextSlide" :disabled="slideIndex === slides.length - 1" :title="lang.ssNextPage" v-if="!isFollowModeActive || props.type == '1'">
  44. <IconRightTwo class="control-icon" />
  45. </button>
  46. <!-- <button @click="resetZoom" title="重置缩放">
  47. <IconUndo class="control-icon" />
  48. </button> -->
  49. <button @click="enterFullscreen" :title="lang.ssFullscreen">
  50. <IconFullScreenOne class="control-icon" />
  51. </button>
  52. <!-- 只有创建人才显示跟随模式按钮 -->
  53. <button
  54. v-if="isCreator"
  55. @click="toggleFollowMode"
  56. :class="{ 'follow-active': isFollowModeActive }"
  57. >
  58. {{ isFollowModeActive ? lang.ssFollowOff : lang.ssFollowOn }}
  59. </button>
  60. <!-- <button @click="backToEditor" class="back-btn" title="返回编辑">
  61. <IconEdit class="control-icon" />
  62. </button> -->
  63. </div>
  64. </div>
  65. <div class="viewer-canvas" ref="viewerCanvasRef">
  66. <!-- 全屏时:使用放映功能 -->
  67. <!-- <ScreenSlideList :slideWidth="slideWidth"
  68. :slideHeight="slideHeight" :animationIndex="0" :turnSlideToId="() => { }"
  69. :manualExitFullscreen="() => { }" /> -->
  70. <!-- 不全屏时:使用编辑模式的显示比例和居中逻辑 -->
  71. <div class="slide-list-wrap" ref="slideListWrapRef" :class="{'slide-list-wrap-n': !isFullscreen, 'laser-pen': laserPen }" :style="{
  72. width: isFullscreen ? '100%' : (slideWidth * canvasScale) + 'px',
  73. height: isFullscreen ? '100%' : (slideHeight * canvasScale) + 'px',
  74. left: isFullscreen ? '0' : `${(containerWidth - slideWidth * canvasScale) / 2}px`,
  75. top: isFullscreen ? '0' : `${(containerHeight - slideHeight * canvasScale) / 2}px`
  76. }" @mousemove="handleLaserMove">
  77. <div class="homework-check-box" :class="{ 'fullscreen-mode': isFullscreen, 'fs-expanded': hwBoxExpanded }" v-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo && (props.type == '1' || (props.type == '2' && currentIsResultArray.can && !is_cast_screen))" :style="{
  78. top: isFullscreen ? '0' : `0`
  79. }" @click="isFullscreen && (hwBoxExpanded = !hwBoxExpanded)">
  80. <div class="homework-check-box-item" @click.stop="openChoiceQuestionDetail2(slideIndex); hwBoxExpanded = false" :class="{'active': !choiceQuestionDetailDialogOpenList.includes(slideIndex)}">
  81. <div class="homework-check-box-item-title">{{ lang.ssQuestion }}</div>
  82. </div>
  83. <div class="homework-check-box-item" @click.stop="openChoiceQuestionDetail3(slideIndex); hwBoxExpanded = false" :class="{'active': choiceQuestionDetailDialogOpenList.includes(slideIndex)}">
  84. <div class="homework-check-box-item-title">{{ lang.ssResult }}</div>
  85. </div>
  86. </div>
  87. <div class="aiBtn" ref="aiBtnRef" v-if="isQuestionFrame && hasWork && props.type == '2' && aiAssistant"
  88. :style="{ right: aiBtnPosition.x + 'px', bottom: aiBtnPosition.y + 'px' }" @click="openAiChat">
  89. <IconComment class="aiBtn-icon" />
  90. <span>{{ lang.ssAiChat }}</span>
  91. </div>
  92. <aiChat v-show="visibleAIChat" :position="aiBtnPosition" @close="visibleAIChat = false" :userid="props.userid" :workJson="myWork" :visible="visibleAIChat" :cid="props.cid" :courseid="props.courseid"/>
  93. <!-- -->
  94. <div class="viewport" v-if="false">
  95. <div class="background" :style="backgroundStyle"></div>
  96. <ScreenElement v-for="(element, index) in elementList" :key="element.id" :elementInfo="element"
  97. :elementIndex="index + 1" :animationIndex="0" :turnSlideToId="() => { }"
  98. :manualExitFullscreen="() => { }" :is-visible="slideIndex === index" />
  99. </div>
  100. <ScreenSlideList :style="{ width: isFullscreen ? '100%' : slideWidth2 * canvasScale + 'px', height: isFullscreen ? '100%' : slideHeight2 * canvasScale + 'px', margin: '0 auto' }" :slideWidth="isFullscreen ? slideWidth * canvasScale : slideWidth2 * canvasScale" :slideHeight="isFullscreen ? slideHeight * canvasScale : slideHeight2 * canvasScale"
  101. :animationIndex="0" :turnSlideToId="() => { }" :manualExitFullscreen="() => { }" :slideIndex="slideIndex" v-show="!choiceQuestionDetailDialogOpenList.includes(slideIndex)"/>
  102. <choiceQuestionDetailDialog ref="choiceQuestionDetailDialogRef" v-if="choiceQuestionDetailDialogOpenList.includes(slideIndex) && !currentSlideHasEnglishSpeaking" :roleType="props.type" :cid="props.cid" :courseid="props.courseid" :workId="workId" :workUrl="workUrl" :userId="props.userid" :courseDetail="courseDetail" :workArray="workArray" @changeWorkIndex="changeWorkIndex" v-model:visible="choiceQuestionDetailDialogOpenList" :unsubmittedStudents="unsubmittedStudents" :showData="answerTheResultRef" :slideIndex="slideIndex" :workIndex="0" :style="{ width: isFullscreen ? '100%' : slideWidth2 * canvasScale + 'px', height: isFullscreen ? '100%' : slideHeight2 * canvasScale + 'px', margin: '0 auto' }" :slideWidth="isFullscreen ? slideWidth * canvasScale : slideWidth2 * canvasScale" :slideHeight="isFullscreen ? slideHeight * canvasScale : slideHeight2 * canvasScale" :resultArray="currentIsResultArray" @setIsResultArray="setIsResultArray2" :isCreator="isCreator" @successLike="successLike" @sendMessage="sendMessage" :isFollowModeActive="isFollowModeActive"/>
  103. <SpeakingClassPanel
  104. v-else-if="choiceQuestionDetailDialogOpenList.includes(slideIndex) && currentSlideToolType === TOPIC_DISCUSSION_TOOL_TYPE"
  105. ref="speakingPanelRef"
  106. :configId="currentSlideConfigId"
  107. :slideIndex="slideIndex"
  108. :studentArray="studentArray"
  109. :courseId="props.courseid"
  110. :slideWidth="isFullscreen ? slideWidth * canvasScale : slideWidth2 * canvasScale"
  111. :slideHeight="isFullscreen ? slideHeight * canvasScale : slideHeight2 * canvasScale"
  112. :style="{ margin: '0 auto' }"
  113. />
  114. <ArticleReadingClassPanel
  115. v-else-if="choiceQuestionDetailDialogOpenList.includes(slideIndex) && currentSlideToolType === ARTICLE_READING_TOOL_TYPE"
  116. ref="articleReadingPanelRef"
  117. :configId="currentSlideConfigId"
  118. :slideIndex="slideIndex"
  119. :studentArray="studentArray"
  120. :courseId="props.courseid || ''"
  121. :slideWidth="isFullscreen ? slideWidth * canvasScale : slideWidth2 * canvasScale"
  122. :slideHeight="isFullscreen ? slideHeight * canvasScale : slideHeight2 * canvasScale"
  123. :style="{ margin: '0 auto' }"
  124. />
  125. <div class="slide-bottom" v-if="!isFullscreen">
  126. <div class="slide-bottom-center" v-if="!isFullscreen && (!isFollowModeActive || props.type == '1')">
  127. <div class="slide-bottom-center-item">
  128. <img src="@/assets/img/left-a.svg" alt="" @click="previousSlide">
  129. <div class="slide-bottom-center-item-page">
  130. <span>{{ slideIndex + 1 }}</span>
  131. <span>/</span>
  132. <span>{{ slides.length }}</span>
  133. </div>
  134. <img src="@/assets/img/right-a.svg" alt="" @click="nextSlide">
  135. </div>
  136. </div>
  137. <div class="slide-bottom-right" v-if="!isFullscreen">
  138. <Refresh class="tool-btn" v-tooltip="lang.ssRefresh" @click="handleRefreshPage" v-if="currentSlideHasIframe && !currentSlideHasEnglishSpeaking"/>
  139. <!-- <UpTwo @click="handleHomeworkSubmit" v-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo && !isSubmitting" class="tool-btn upBtn" v-tooltip="lang.ssSubmitHW"/> -->
  140. <svg @click="handleHomeworkSubmit" v-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo && !isSubmitting && !currentSlideHasEnglishSpeaking" class="tool-btn upBtn" v-tooltip="lang.ssSubmitHW" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
  141. <!-- Document body -->
  142. <path d="M15 10 L15 90 Q15 95 20 95 L80 95 Q85 95 85 90 L85 35 L60 10 Z"
  143. fill="none" stroke="currentColor" stroke-width="6" stroke-linejoin="round" stroke-linecap="round"/>
  144. <!-- Folded corner -->
  145. <path d="M60 10 L60 35 L85 35"
  146. fill="none" stroke="currentColor" stroke-width="6" stroke-linejoin="round" stroke-linecap="round"/>
  147. <!-- Upload arrow shaft -->
  148. <line x1="50" y1="72" x2="50" y2="45"
  149. stroke="currentColor" stroke-width="6" stroke-linecap="round"/>
  150. <!-- Arrow head -->
  151. <polyline points="37,57 50,43 63,57"
  152. fill="none" stroke="currentColor" stroke-width="6" stroke-linejoin="round" stroke-linecap="round"/>
  153. <!-- Bottom lines -->
  154. <line x1="36" y1="80" x2="64" y2="80"
  155. stroke="currentColor" stroke-width="6" stroke-linecap="round"/>
  156. <line x1="36" y1="88" x2="64" y2="88"
  157. stroke="currentColor" stroke-width="6" stroke-linecap="round"/>
  158. </svg>
  159. <IconLoading v-else-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo && !currentSlideHasEnglishSpeaking" class="tool-btn loading" v-tooltip="lang.ssSubmitting"></IconLoading>
  160. <IconStopwatchStart v-if="props.type == '1' && courseDetail.userid == props.userid && isFollowModeActive" class="tool-btn" v-tooltip="lang.ssTimer" @click="timerlVisible = !timerlVisible" />
  161. <IconWrite v-if="isFollowModeActive && props.type == '1' && courseDetail.userid == props.userid" class="tool-btn" v-tooltip="lang.ssPenTool" @click="writingBoardToolVisible = true" />
  162. <!-- <IconMagic v-if="isFollowModeActive && props.type == '1' && courseDetail.userid == props.userid" class="tool-btn" v-tooltip="lang.ssLaserPen" :class="{ 'active': laserPen }" @click="toggleLaserPen" /> -->
  163. <IconTips v-if="props.type == '1' && props.userid != 'undefined'" class="tool-btn" v-tooltip="lang.ssAiHelper" :class="{ 'active': !workPanelCollapsed }" @click="workPanelCollapsed = !workPanelCollapsed" />
  164. <IconFullScreenOne class="tool-btn" v-tooltip="lang.ssOpenFull" @click="enterFullscreen" />
  165. </div>
  166. </div>
  167. </div>
  168. <!-- 全屏时的左右下角工具按钮 -->
  169. <div v-if="isFullscreen && (!isFollowModeActive || props.type == '1')" class="tools-left">
  170. <IconLeftTwo class="tool-btn" theme="two-tone" :fill="['#111', '#fff']" @click="previousSlide" />
  171. <IconRightTwo class="tool-btn" theme="two-tone" :fill="['#111', '#fff']" @click="nextSlide" />
  172. </div>
  173. <!-- 作业提交按钮 - 当当前幻灯片包含iframe时显示(排除B站视频) -->
  174. <div v-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo && isFullscreen && !currentSlideHasEnglishSpeaking" class="homework-submit-btn" :class="{ 'submitting': isSubmitting }"
  175. :style="{ right: getHomeworkButtonRight() + 'px' }" @click="handleHomeworkSubmit"
  176. v-tooltip="isSubmitting ? lang.ssHwSubmitting : lang.ssHwSubmit">
  177. <!-- <IconEdit v-if="!isSubmitting" class="tool-btn" />
  178. <div v-else class="loading-spinner"></div> -->
  179. <span class="btn-text">{{ isSubmitting ? lang.ssSubmittingEll : lang.ssSubmit }}</span>
  180. </div>
  181. <!-- 刷新iframe按钮 -->
  182. <div class="refresh-page-btn"
  183. v-if="currentSlideHasIframe && isFullscreen && !currentSlideHasEnglishSpeaking"
  184. :style="{ right: getRefreshButtonRight() + 'px' }"
  185. @click="handleRefreshPage"
  186. v-tooltip="lang.ssRefreshIframe">
  187. <Refresh class="tool-btn" />
  188. <span class="btn-text">{{ lang.ssRefresh }}</span>
  189. </div>
  190. <!-- 功能组件 -->
  191. <SlideThumbnails v-if="slideThumbnailModelVisible" :turnSlideToIndex="goToSlide"
  192. @close="slideThumbnailModelVisible = false" />
  193. <WritingBoardTool
  194. :slideWidth="slideWidth"
  195. :slideHeight="slideHeight"
  196. v-if="writingBoardToolVisible || (props.type == '2' && isFollowModeActive && writingBoardSyncDataURL && writingBoardSyncDataURL.trim() !== '')"
  197. :readonly="props.type == '2'"
  198. :syncDataURL="props.type == '2' ? writingBoardSyncDataURL : null"
  199. :syncBlackboard="props.type == '2' ? writingBoardSyncBlackboard : null"
  200. @close="handleWritingBoardClose"
  201. @drawing-end="handleDrawingEnd"
  202. @blackboard-change="handleBlackboardChange"
  203. />
  204. <CountdownTimer
  205. v-if="timerlVisible"
  206. @close="timerlVisible = false"
  207. @timer-start="onTimerStart"
  208. @timer-pause="onTimerPause"
  209. @timer-reset="onTimerReset"
  210. @timer-stop="onTimerStop"
  211. @timer-finish="onTimerFinish"
  212. @timer-update="onTimerUpdate"
  213. />
  214. <div v-if="isFullscreen && (!isFollowModeActive || props.type == '1')" class="tools-right" :class="{ 'visible': rightToolsVisible }"
  215. @mouseleave="rightToolsVisible = false" @mouseenter="rightToolsVisible = true">
  216. <div class="content">
  217. <div class="tool-btn page-number" @click="slideThumbnailModelVisible = true">
  218. {{ lang.ssSlidePage }} {{slideIndex + 1}} / {{slides.length}}
  219. </div>
  220. <IconWrite class="tool-btn" v-if="isFollowModeActive && props.type == '1' && courseDetail.userid == props.userid" v-tooltip="lang.ssPenTool" @click="writingBoardToolVisible = true" />
  221. <IconMagic class="tool-btn" v-if="isFollowModeActive && props.type == '1' && courseDetail.userid == props.userid" v-tooltip="lang.ssLaserPen" :class="{ 'active': laserPen }" @click="toggleLaserPen" />
  222. <IconStopwatchStart v-if="(props.type == '1' && courseDetail.userid == props.userid && isFollowModeActive)" class="tool-btn" v-tooltip="lang.ssTimer" @click="timerlVisible = !timerlVisible" />
  223. <IconOffScreenOne class="tool-btn" v-tooltip="lang.ssExitFull" @click="enterFullscreen" />
  224. </div>
  225. </div>
  226. </div>
  227. </div>
  228. <div class="layout-content-right" v-show="type == '1' && props.userid != 'undefined'" :class="{ collapsed: workPanelCollapsed }">
  229. <div class="thumbnails">
  230. <div class="viewer-header right-panel-header">
  231. <button class="collapse-btn" @click="workPanelCollapsed = !workPanelCollapsed" :title="workPanelCollapsed ? lang.ssExpand : lang.ssCollapse" v-if="rightPanelMode != ''" style="left: 8px;">
  232. <span v-if="workPanelCollapsed">
  233. <img src="@/assets/img/arrow.svg" style="transform: rotate(180deg);">
  234. </span>
  235. <span v-else>
  236. <img src="@/assets/img/arrow.svg">
  237. </span>
  238. </button>
  239. <!-- 标签页切换按钮 -->
  240. <div v-show="!workPanelCollapsed" class="tab-switcher">
  241. <!-- <button
  242. v-if="currentSlideHasIframe && !currentSlideHasBilibiliVideo"
  243. v-show="currentSlideHasIframe"
  244. class="tab-btn"
  245. :class="{ active: rightPanelMode === 'homework' }"
  246. @click="switchToHomework"
  247. :title="lang.ssAnswerRes"
  248. >
  249. {{ lang.ssAnswerRes }}
  250. </button> -->
  251. <button
  252. class="tab-btn"
  253. :class="{ active: rightPanelMode === 'dialogue' }"
  254. @click="switchToDialogue"
  255. :title="lang.ssDialogArea"
  256. >
  257. {{ lang.ssDialogArea }}
  258. </button>
  259. <!-- <button
  260. v-if="isChoiceQuestion"
  261. class="tab-btn"
  262. :class="{ active: rightPanelMode === 'choice' }"
  263. @click="switchToChoice"
  264. title="统计"
  265. >
  266. 统计
  267. </button> -->
  268. </div>
  269. </div>
  270. <!-- 侧边导航标签 - 无论展开还是收缩都显示在左侧 -->
  271. <!-- <div class="side-nav-tabs">
  272. <button
  273. v-if="currentSlideHasIframe"
  274. class="side-nav-btn"
  275. :class="{ active: rightPanelMode === 'homework' }"
  276. @click="switchToHomework"
  277. title="作业"
  278. >
  279. <img :src="rightPanelMode === 'homework' ? homeworkActiveIcon : homeworkIcon" alt="作业">
  280. </button>
  281. <button
  282. v-if="isChoiceQuestion"
  283. class="side-nav-btn"
  284. :class="{ active: rightPanelMode === 'choice' }"
  285. @click="switchToChoice"
  286. title="统计"
  287. >
  288. <img :src="rightPanelMode === 'choice' ? choiceActiveIcon : choiceIcon" alt="统计">
  289. </button>
  290. <button
  291. class="side-nav-btn"
  292. :class="{ active: rightPanelMode === 'dialogue' }"
  293. @click="switchToDialogue"
  294. title="对话"
  295. >
  296. <img :src="rightPanelMode === 'dialogue' ? dialogueActiveIcon : dialogueIcon" alt="对话">
  297. </button>
  298. </div> -->
  299. <!-- 回答结果内容 -->
  300. <div v-show="!workPanelCollapsed && rightPanelMode === 'homework'" class="panel-content">
  301. <div v-if="workLoading" class="homework-loading">{{ lang.ssHwLoading }}</div>
  302. <answerTheResult :toolType="toolType" :workId="workId" :workArray="workArray" :unsubmittedStudents="unsubmittedStudents" :slideIndex="slideIndex" v-else ref="answerTheResultRef" @openChoiceQuestionDetail="openChoiceQuestionDetail" @openWorkModal="openWorkModal"/>
  303. <!--<div class="homework-title">已提交</div>
  304. <div v-if="workLoading" class="homework-loading">正在加载作业...</div>
  305. <div v-else>
  306. <div v-if="workArray && workArray.length" class="homework-grid">
  307. <button class="homework-btn" v-for="(work, idx) in workArray" :key="work.id ?? idx" :title="work.name" @click="openWorkModal(work)">
  308. <span class="homework-btn__text">{{ work.name }}</span>
  309. </button>
  310. </div>
  311. <div class="homework-empty" v-else>
  312. 暂无作业提交
  313. </div>
  314. </div>-->
  315. <!--<div v-if="unsubmittedStudents && unsubmittedStudents.length > 0" class="homework-title" style="margin-top: 20px;">未提交</div>
  316. <div v-if="unsubmittedStudents && unsubmittedStudents.length > 0">
  317. <div v-if="studentLoading" class="homework-loading">正在加载学生信息...</div>
  318. <div v-else>
  319. <div class="homework-grid">
  320. <button class="homework-btn unsubmitted" v-for="(student, idx) in unsubmittedStudents" :key="student.id ?? idx" :title="student.name" disabled>
  321. <span class="homework-btn__text">{{ student.name }}</span>
  322. </button>
  323. </div>
  324. </div>
  325. </div>-->
  326. </div>
  327. <!-- 对话区内容 -->
  328. <div v-show="!workPanelCollapsed && rightPanelMode === 'dialogue'" class="panel-content">
  329. <DialoguePanel :userid="props.userid" :courseid="props.courseid" :fileid="pptJsonFileid"/>
  330. </div>
  331. <!-- 选择题统计内容 -->
  332. <div v-show="!workPanelCollapsed && rightPanelMode === 'choice'" class="panel-content">
  333. <ChoiceStatistics :workArray="workArray" :elementList="elementList" />
  334. </div>
  335. </div>
  336. </div>
  337. <!-- 右上角计时状态指示器(块状样式) -->
  338. <div
  339. v-if="timerIndicator.visible"
  340. class="timer-indicator"
  341. :class="{ 'countdown': timerIndicator.isCountdown, 'timeout': timerIndicator.isCountdown && timerIndicator.remainingSec !== null && timerIndicator.remainingSec <= 0 }"
  342. :style="{ right: getTimerIndicatorRight() + 'px', top: isFullscreen ? '16px' : '12px' }"
  343. >
  344. <div class="blocks">
  345. <template v-if="timerBlocksVisibility().showH">
  346. <span class="block">{{ timerBlocks().h }}</span>
  347. <span class="colon"></span>
  348. </template>
  349. <template v-if="timerBlocksVisibility().showM">
  350. <span class="block">{{ timerBlocks().m }}</span>
  351. <span class="colon"></span>
  352. </template>
  353. <span class="block">{{ timerBlocks().s }}</span>
  354. </div>
  355. </div>
  356. </div>
  357. <ShotWorkModal v-model:visible="visibleShot" :work="selectedWork" />
  358. <QAWorkModal v-model:visible="visibleQA" :work="selectedWork" />
  359. <ChoiceWorkModal v-model:visible="visibleChoice" :work="selectedWork" />
  360. <AIWorkModal v-model:visible="visibleAI" :work="selectedWork" />
  361. <!-- 学生端激光笔覆盖层(拦截点击) -->
  362. <div
  363. v-if="props.type == '2' && laserPenOverlay.visible"
  364. class="laser-pointer-overlay"
  365. :style="laserOverlayStyle"
  366. >
  367. <div class="laser-pointer-dot" ref="laserDotRef"></div>
  368. </div>
  369. <!-- 在适当位置添加连接状态指示器 -->
  370. <div class="connection-status" v-if="connectionStatus !== 'connected'">
  371. <div class="status-indicator" :class="connectionStatus">
  372. <span v-if="connectionStatus === 'connecting'">{{ lang.ssConnecting }}</span>
  373. <span v-else-if="connectionStatus === 'disconnected'">{{ lang.ssConnLost }}</span>
  374. </div>
  375. <button v-if="connectionStatus === 'disconnected'" @click="manualReconnect" class="reconnect-btn">
  376. {{ lang.ssReconnect }}
  377. </button>
  378. </div>
  379. <div class="connection-status" v-if="false">
  380. <div class="status-indicator" :class="'disconnected'">
  381. <span>{{ lang.ssConnLost }}</span>
  382. </div>
  383. <button @click="manualReconnect" class="reconnect-btn">
  384. {{ lang.ssReconnect }}
  385. </button>
  386. </div>
  387. <messageInstruction ref="messageInstructionRef" />
  388. </template>
  389. <script lang="ts" setup>
  390. import { computed, ref, onMounted, onUnmounted, nextTick, inject, watch, provide, shallowRef } from 'vue'
  391. import { storeToRefs } from 'pinia'
  392. import { useSlidesStore } from '@/store'
  393. import { ElementTypes } from '@/types/slides'
  394. import { fillDigit } from '@/utils/common'
  395. import ThumbnailSlide from '@/views/components/ThumbnailSlide/index.vue'
  396. import ScreenSlideList from '@/views/Screen/ScreenSlideList.vue'
  397. import ScreenElement from '@/views/Screen/ScreenElement.vue'
  398. import SlideThumbnails from '@/views/Screen/SlideThumbnails.vue'
  399. import WritingBoardTool from '@/views/Screen/WritingBoardTool.vue'
  400. import CountdownTimer from '@/views/Screen/CountdownTimer.vue'
  401. import useSlideBackgroundStyle from '@/hooks/useSlideBackgroundStyle'
  402. import useImport from '@/hooks/useImport'
  403. import message from '@/utils/message'
  404. import api, { API_URL } from '@/services/course'
  405. import axios from '@/services/config'
  406. import {currentVersion, lang} from '@/main'
  407. import ShotWorkModal from './components/ShotWorkModal.vue'
  408. import QAWorkModal from './components/QAWorkModal.vue'
  409. import ChoiceWorkModal from './components/ChoiceWorkModal.vue'
  410. import AIWorkModal from './components/AIWorkModal.vue'
  411. import DialoguePanel from './components/DialoguePanel.vue'
  412. import ChoiceStatistics from './components/ChoiceStatistics.vue'
  413. import * as Y from 'yjs'
  414. import { WebsocketProvider } from 'y-websocket'
  415. import { Refresh } from '@icon-park/vue-next'
  416. import answerTheResult from './components/answerTheResult.vue'
  417. import choiceQuestionDetailDialog from './components/choiceQuestionDetailDialog.vue'
  418. import SpeakingClassPanel from './components/SpeakingClassPanel/index.vue'
  419. import ArticleReadingClassPanel from './components/ArticleReadingClassPanel/index.vue'
  420. import {
  421. ARTICLE_READING_TOOL_TYPE,
  422. TOPIC_DISCUSSION_TOOL_TYPE,
  423. isArticleReadingTool,
  424. isTopicDiscussionTool,
  425. } from '@/configs/englishSpeakingTools'
  426. import aiChat from './components/aiChat.vue'
  427. import messageInstruction from '@/utils/components/messageInstruction.vue'
  428. const messageInstructionRef = ref<typeof messageInstruction>()
  429. // 生成标准 UUID v4 格式(36位,符合 [0-9a-fA-F-] 格式)
  430. const generateUUID = (): string => {
  431. // 优先使用浏览器原生 API
  432. if (typeof crypto !== 'undefined' && crypto.randomUUID) {
  433. return crypto.randomUUID()
  434. }
  435. // 降级方案:手动生成 UUID v4
  436. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
  437. const r = (Math.random() * 16) | 0
  438. const v = c === 'x' ? r : (r & 0x3) | 0x8
  439. return v.toString(16)
  440. })
  441. }
  442. // 导入图片资源
  443. import homeworkIcon from '@/assets/img/homework.png'
  444. import homeworkActiveIcon from '@/assets/img/homework-active.png'
  445. import dialogueIcon from '@/assets/img/dialogue.png'
  446. import dialogueActiveIcon from '@/assets/img/dialogue-active.png'
  447. import choiceIcon from '@/assets/img/choice.png'
  448. import choiceActiveIcon from '@/assets/img/choice-active.png'
  449. // 定义组件props
  450. interface Props {
  451. courseid?: string | null
  452. userid?: string | null
  453. oid?: string | null
  454. org?: string | null
  455. cid?: string | null
  456. type?: string | null
  457. }
  458. const props = withDefaults(defineProps<Props>(), {
  459. courseid: null,
  460. userid: null,
  461. oid: null,
  462. org: null,
  463. cid: null,
  464. type: null,
  465. })
  466. // 图标组件通过全局注册,无需导入
  467. const slidesStore = useSlidesStore()
  468. const { slides, slideIndex, currentSlide, viewportSize, viewportRatio } = storeToRefs(slidesStore)
  469. // 添加容器引用,用于计算幻灯片尺寸
  470. const viewerCanvasRef = ref<HTMLElement>()
  471. // 放映相关的状态
  472. const canvasScale = ref(1) // 画布缩放比例
  473. const isFullscreen = ref(false) // 是否全屏
  474. const hwBoxExpanded = ref(false) // 全屏下作业工具栏展开状态
  475. const containerWidth = ref(0) // 容器宽度
  476. const containerHeight = ref(0) // 容器高度
  477. // 全屏工具相关状态
  478. const rightToolsVisible = ref(false)
  479. const writingBoardToolVisible = ref(false)
  480. const timerlVisible = ref(false)
  481. const slideThumbnailModelVisible = ref(false)
  482. const laserPen = ref(false)
  483. // 学生端激光笔覆盖层与位置(百分比)
  484. const laserPenOverlay = ref<{ visible: boolean; xPct: number; yPct: number }>({ visible: false, xPct: 0, yPct: 0 })
  485. const laserDotRef = ref<HTMLElement | null>(null)
  486. let laserMoveRafId: number | null = null
  487. let lastLayout: { w: number; h: number } | null = null
  488. // 学生端覆盖层矩形(固定定位)
  489. const laserOverlayRect = ref<{ left: number; top: number; width: number; height: number }>({ left: 0, top: 0, width: 0, height: 0 })
  490. const laserOverlayStyle = computed(() => ({
  491. position: 'fixed' as const,
  492. left: laserOverlayRect.value.left + 'px',
  493. top: laserOverlayRect.value.top + 'px',
  494. width: laserOverlayRect.value.width + 'px',
  495. height: laserOverlayRect.value.height + 'px',
  496. pointerEvents: 'auto' as const,
  497. zIndex: 1000
  498. }))
  499. const refreshLaserOverlayRect = () => {
  500. const wrap = (viewerCanvasRef.value?.querySelector('.slide-list-wrap') as HTMLElement) || null
  501. if (!wrap) return
  502. const rect = wrap.getBoundingClientRect()
  503. laserOverlayRect.value = { left: rect.left, top: rect.top, width: rect.width, height: rect.height }
  504. }
  505. const updateLaserDotPosition = () => {
  506. if (!laserDotRef.value || !viewerCanvasRef.value) return
  507. const wrap = (viewerCanvasRef.value.querySelector('.slide-list-wrap') as HTMLElement) || viewerCanvasRef.value
  508. const w = wrap.clientWidth
  509. const h = wrap.clientHeight
  510. lastLayout = { w, h }
  511. const left = (laserPenOverlay.value.xPct / 100) * w
  512. const top = (laserPenOverlay.value.yPct / 100) * h
  513. // 减去半径使光点中心对齐
  514. laserDotRef.value.style.transform = `translate3d(${left - 12}px, ${top - 12}px, 0)`
  515. }
  516. const answerTheResultRef = ref(null)
  517. // 计时状态指示器
  518. const timerIndicator = ref<{ visible: boolean; isCountdown: boolean; startAt: string | null; durationSec: number | null; elapsedSec: number | null; remainingSec: number | null; finished: boolean }>({
  519. visible: false,
  520. isCountdown: false,
  521. startAt: null,
  522. durationSec: null,
  523. elapsedSec: null,
  524. remainingSec: null,
  525. finished: false,
  526. })
  527. const timerInterval = ref<number | null>(null)
  528. // 作业提交状态
  529. const isSubmitting = ref(false)
  530. // 进入当前幻灯片(作业页)的时间戳,用于计算作业提交耗时(秒)
  531. const slideEnterTime = ref(0)
  532. // 控制组件显示的开关
  533. const showSlideList = ref(true)
  534. const slideWidth = ref(0)
  535. const slideHeight = ref(0)
  536. const slideWidth2 = ref(0)
  537. const slideHeight2 = ref(0)
  538. // 添加loading状态
  539. const isLoading = ref(false)
  540. const workLoading = ref(false)
  541. const studentLoading = ref(false)
  542. // 作业数组
  543. type WorkItem = {
  544. id?: string | number
  545. name: string
  546. type: number | string
  547. [key: string]: any
  548. }
  549. const workArray = ref<WorkItem[]>([])
  550. const toolTypeArray = ref<number[]>([45, 15, 73, 72, 78, 79, 831, 832, 84])
  551. // 作业弹窗相关
  552. const selectedWork = ref<any>(null)
  553. const visibleShot = ref(false)
  554. const visibleQA = ref(false)
  555. const visibleChoice = ref(false)
  556. const visibleAI = ref(false)
  557. const choiceQuestionDetailDialogOpenList = ref<number[]>([])
  558. const speakingPanelRef = ref<InstanceType<typeof SpeakingClassPanel> | null>(null)
  559. const articleReadingPanelRef = ref<InstanceType<typeof ArticleReadingClassPanel> | null>(null)
  560. const choiceQuestionDetailDialogRef = ref<InstanceType<typeof choiceQuestionDetailDialog> | null>(null)
  561. provide('notifySpeakingProgress', (status: 'active' | 'completed', payload: { configId: string; sessionId: string }) => {
  562. if (props.type !== '2') return // 只有学生客户端发广播
  563. sendMessage({
  564. type: 'speaking_session_updated',
  565. courseid: props.courseid,
  566. slideIndex: slideIndex.value,
  567. userid: props.userid,
  568. status,
  569. ...payload,
  570. })
  571. })
  572. provide('recordSpeakingStart', async (
  573. sessionId: string,
  574. activityToolType: number = TOPIC_DISCUSSION_TOOL_TYPE,
  575. ) => {
  576. // 老师端 (type=1) 与学生端 (type=2) 都允许写作业记录,方便老师自测/学生提交
  577. if (!sessionId || !props.courseid || !props.userid) return
  578. try {
  579. await api.submitWork({
  580. uid: props.userid as string,
  581. cid: props.courseid as string,
  582. stage: '0',
  583. task: String(slideIndex.value),
  584. tool: '0',
  585. atool: String(activityToolType),
  586. content: sessionId,
  587. type: '21',
  588. })
  589. }
  590. catch (err) {
  591. console.error('[speaking] recordSpeakingStart failed:', err)
  592. }
  593. })
  594. // 提供给子组件使用
  595. provide('choiceQuestionDetailDialogOpenList', choiceQuestionDetailDialogOpenList)
  596. // 当前作业选择/问答题的ID
  597. const workId = ref<string>('')
  598. // 当前作业的url
  599. const workUrl = ref<string>('')
  600. // 当前作业的type
  601. const toolType = ref<string>('')
  602. // 回答结果收缩状态
  603. const workPanelCollapsed = ref(true)
  604. // 幻灯片导航收缩状态
  605. const slidePanelCollapsed = ref(true)
  606. // 右侧面板当前显示的内容:'homework' | 'dialogue' | 'choice'
  607. const rightPanelMode = ref<'homework' | 'dialogue' | 'choice' | ''>('homework')
  608. // 移除定时器相关代码,改用socket监听
  609. const courseDetail = ref<any>({})
  610. const aiAssistant = ref<boolean>(false)
  611. const studentArray = ref<any>([])
  612. const isResultArray = ref<any>([])
  613. const opRes = ref<any>([])
  614. // 跟随模式相关状态
  615. const isCreator = ref(false) // 是否为创建人
  616. const isFollowModeActive = ref(false) // 跟随模式是否开启
  617. const isFirstEnter = ref(true) // 是否首次进入
  618. // 用户信息
  619. const userJson = ref<any>(null)
  620. // 计算未提交作业的学生
  621. const unsubmittedStudents = computed(() => {
  622. if (!studentArray.value || !workArray.value) return []
  623. // 获取已提交作业的学生姓名
  624. const submittedNames = workArray.value.map(work => work.name)
  625. // 过滤出未提交作业的学生
  626. return studentArray.value.filter((student: any) => !submittedNames.includes(student.name))
  627. })
  628. const docSocket = ref<Y.Doc | null>(null)
  629. const yMessage = ref<any | null>(null)
  630. const yTimerState = ref<any | null>(null)
  631. const yLaserState = ref<any | null>(null)
  632. const yWritingBoardState = ref<any | null>(null)
  633. // 独立的数组存储特殊类型的消息
  634. const yTimerMessages = ref<any | null>(null)
  635. const yLaserMessages = ref<any | null>(null)
  636. const yWritingBoardMessages = ref<any | null>(null)
  637. const yIsResultArrayMessages = ref<any | null>(null)
  638. const providerSocket = ref<WebsocketProvider | null>(null)
  639. // 学生端画图同步数据
  640. const writingBoardSyncDataURL = ref<string | null>(null)
  641. const writingBoardSyncBlackboard = ref<boolean | null>(null)
  642. const mId = ref<string | null>(null)
  643. // 画图延迟发送定时器
  644. const drawingDelayTimer = ref<NodeJS.Timeout | null>(null)
  645. // WebSocket重连相关变量
  646. const reconnectAttempts = ref(0)
  647. const maxReconnectAttempts = ref(5) // 最大重连次数
  648. const reconnectInterval = ref(5000) // 重连间隔(毫秒)
  649. const reconnectTimer = ref<NodeJS.Timeout | null>(null)
  650. const isConnecting = ref(false)
  651. const connectionStatus = ref<'disconnected' | 'connecting' | 'connected'>('disconnected')
  652. // 认证 token 相关变量
  653. const authToken = ref<string | null>(null)
  654. const authTokenUpdateTimer = ref<NodeJS.Timeout | null>(null)
  655. const heartbeatTimer = ref<NodeJS.Timeout | null>(null)
  656. const socketCheckTimer = ref<NodeJS.Timeout | null>(null)
  657. // 同步数据最大保留时间(40分钟)
  658. const SYNC_DATA_MAX_AGE = 40 * 60 * 1000 // 40分钟 = 40 * 60 * 1000毫秒
  659. // 切换选择题题目
  660. const changeWorkIndex = (type:number) => {
  661. if (answerTheResultRef.value && answerTheResultRef.value.changeWorkIndex) {
  662. answerTheResultRef.value.changeWorkIndex(type)
  663. }
  664. }
  665. // 切换到回答结果
  666. const switchToHomework = () => {
  667. rightPanelMode.value = 'homework'
  668. if (workPanelCollapsed.value) {
  669. workPanelCollapsed.value = false
  670. }
  671. }
  672. // 切换到对话区
  673. const switchToDialogue = () => {
  674. rightPanelMode.value = 'dialogue'
  675. if (workPanelCollapsed.value) {
  676. workPanelCollapsed.value = false
  677. }
  678. }
  679. // 切换到选择题统计
  680. const switchToChoice = () => {
  681. rightPanelMode.value = 'choice'
  682. if (workPanelCollapsed.value) {
  683. workPanelCollapsed.value = false
  684. }
  685. }
  686. // 自动切换到可用的面板
  687. const autoSwitchToAvailablePanel = () => {
  688. // 如果当前在回答结果但没有iframe,自动切换到其他可用面板
  689. if (rightPanelMode.value === 'homework' && !currentSlideHasIframe.value && !currentSlideHasBilibiliVideo.value) {
  690. if (isChoiceQuestion.value) {
  691. rightPanelMode.value = 'choice'
  692. console.log('自动切换到统计面板')
  693. }
  694. else {
  695. rightPanelMode.value = 'dialogue'
  696. console.log('自动切换到对话面板')
  697. }
  698. }
  699. // 如果当前在统计面板但不是选择题,自动切换到对话面板
  700. else if (rightPanelMode.value === 'choice' && !isChoiceQuestion.value) {
  701. rightPanelMode.value = 'dialogue'
  702. console.log('自动切换到对话面板')
  703. }
  704. // else if (currentSlideHasIframe.value && rightPanelMode.value !== 'homework' && !currentSlideHasBilibiliVideo.value) {
  705. // rightPanelMode.value = 'homework'
  706. // }
  707. }
  708. // 移除定时器相关函数,改用socket监听
  709. // 收缩/展开后重新计算中间画布尺寸(在 DOM 更新并完成过渡后)
  710. watch([() => workPanelCollapsed.value, () => slidePanelCollapsed.value], async () => {
  711. // 等待本次 DOM 更新
  712. await nextTick()
  713. // 先在下一帧计算一次,确保初步布局就绪
  714. requestAnimationFrame(() => {
  715. calculateScale()
  716. })
  717. // 再在过渡结束后(与左右栏 width .2s 过渡一致)复算一次,确保最终尺寸
  718. setTimeout(() => {
  719. calculateScale()
  720. }, 220)
  721. }, { flush: 'post' })
  722. const openWorkModal = (work: WorkItem) => {
  723. selectedWork.value = work
  724. const t = Number(work?.type)
  725. // if (t !== 1) {
  726. // message.warning('暂未开发完成')
  727. // return
  728. // }
  729. visibleShot.value = false
  730. visibleQA.value = false
  731. visibleChoice.value = false
  732. visibleAI.value = false
  733. if (t === 1) {
  734. visibleShot.value = true
  735. }
  736. else if (t === 3) {
  737. visibleQA.value = true
  738. }
  739. else if (t === 8) {
  740. visibleChoice.value = true
  741. }
  742. else if (t === 20) {
  743. visibleAI.value = true
  744. }
  745. else {
  746. message.info(lang.ssHwTypeUnsup)
  747. }
  748. }
  749. // 计算幻灯片尺寸的函数
  750. const calculateSlideSize = () => {
  751. const slideWrapRef = isFullscreen.value ? document.body : viewerCanvasRef.value
  752. const winWidth = slideWrapRef?.clientWidth || 0
  753. const winHeight = slideWrapRef?.clientHeight || 0
  754. const winWidth2 = slideWrapRef && typeof slideWrapRef.clientWidth === 'number' ? slideWrapRef.clientWidth - 40 : 0
  755. const winHeight2 = slideWrapRef && typeof slideWrapRef.clientHeight === 'number' ? slideWrapRef.clientHeight - 60 - 65 - 10 : 0 // 底部栏 顶部高度 底部高度的
  756. // 根据视口比例计算最佳尺寸
  757. if (winHeight / winWidth === viewportRatio.value) {
  758. slideWidth.value = winWidth
  759. slideHeight.value = winHeight
  760. }
  761. else if (winHeight / winWidth > viewportRatio.value) {
  762. slideWidth.value = winWidth
  763. slideHeight.value = winWidth * viewportRatio.value
  764. }
  765. else {
  766. slideWidth.value = winHeight / viewportRatio.value
  767. slideHeight.value = winHeight
  768. }
  769. // 这里的逻辑存在一些问题和可以优化的地方:
  770. // 1. winWidth2 或 winHeight2 可能为0,导致后续计算为NaN。
  771. // 2. slideHeight.value - slideHeight2.value < 85 这个判断,slideHeight2.value 可能还未被合理赋值,导致判断不准确。
  772. // 3. 反复赋值 slideHeight2/slideWidth2,可能导致宽高比被破坏。
  773. // 4. 代码重复,可合并优化。
  774. // 先按比例计算
  775. let tempWidth = 0
  776. let tempHeight = 0
  777. if (winHeight2 / winWidth2 === viewportRatio.value) {
  778. tempWidth = winWidth2
  779. tempHeight = winHeight2
  780. }
  781. else if (winHeight2 / winWidth2 > viewportRatio.value) {
  782. tempWidth = winWidth2
  783. tempHeight = winWidth2 * viewportRatio.value
  784. }
  785. else {
  786. tempHeight = winHeight2
  787. tempWidth = winHeight2 / viewportRatio.value
  788. }
  789. // 检查底部空间
  790. if (slideHeight.value - tempHeight < (60 + 65 + 10)) {
  791. tempHeight = Math.max(slideHeight.value - (60 + 65 + 10), 0)
  792. tempWidth = tempHeight > 0 ? tempHeight / viewportRatio.value : 0
  793. }
  794. slideWidth2.value = tempWidth
  795. slideHeight2.value = tempHeight
  796. console.log('calculateSlideSize', slideWidth.value, slideHeight.value, viewportRatio.value, canvasScale.value)
  797. console.log('calculateSlideSize', slideWidth2.value, slideHeight2.value, viewportRatio.value, canvasScale.value)
  798. }
  799. // 使用编辑模式的缩放逻辑
  800. const calculateScale = () => {
  801. console.log('calculateScale 开始执行')
  802. // 获取容器尺寸
  803. const container = viewerCanvasRef.value || document.querySelector('.viewer-canvas')
  804. if (container) {
  805. containerWidth.value = container.clientWidth
  806. containerHeight.value = container.clientHeight
  807. console.log('容器尺寸:', {
  808. width: containerWidth.value,
  809. height: containerHeight.value
  810. })
  811. // 计算基础尺寸
  812. const baseWidth = viewportSize.value
  813. const baseHeight = viewportSize.value * viewportRatio.value
  814. console.log('基础尺寸:', {
  815. baseWidth,
  816. baseHeight,
  817. viewportSize: viewportSize.value,
  818. viewportRatio: viewportRatio.value
  819. })
  820. // 计算缩放比例,让幻灯片能够合理利用空间
  821. const scaleX = containerWidth.value / baseWidth
  822. const scaleY = containerHeight.value / baseHeight
  823. console.log('原始缩放比例:', { scaleX, scaleY })
  824. // 选择较小的缩放比例,确保幻灯片完全显示且居中,留10%边距
  825. const scale = Math.min(scaleX, scaleY) * 0.9
  826. console.log('最终缩放比例:', scale)
  827. canvasScale.value = isFullscreen.value ? 1 : props.type == '1' ? 1 : 1
  828. // canvasScale.value = 1
  829. }
  830. else {
  831. console.error('找不到容器元素')
  832. }
  833. // 计算幻灯片尺寸
  834. nextTick(() => {
  835. setTimeout(() => {
  836. calculateSlideSize()
  837. if (laserPenOverlay.value.visible) {
  838. refreshLaserOverlayRect()
  839. requestAnimationFrame(updateLaserDotPosition)
  840. }
  841. }, 500)
  842. })
  843. }
  844. // 简化:直接使用放映功能的缩放逻辑
  845. const resetZoom = () => {
  846. calculateScale()
  847. }
  848. // 背景样式
  849. const background = computed(() => currentSlide.value?.background)
  850. const { backgroundStyle } = useSlideBackgroundStyle(background)
  851. // 计算当前幻灯片的元素列表
  852. const elementList = computed(() => {
  853. return currentSlide.value?.elements || []
  854. })
  855. // 检查当前是否为选择题(toolType为45)
  856. const isChoiceQuestion = computed(() => {
  857. const frame = elementList.value.find(element => element.type === ElementTypes.FRAME)
  858. return frame?.toolType === 45
  859. })
  860. const isQuestionFrame = computed(() => {
  861. const frame = elementList.value.find(element => element.type === ElementTypes.FRAME)
  862. return frame?.toolType === 45 || frame?.toolType === 15 || frame?.toolType === 78
  863. })
  864. const hasWork = computed(() => {
  865. return workArray.value.find(work => work.userid === props.userid) !== undefined
  866. })
  867. const myWork = computed(() => {
  868. return workArray.value.find(work => work.userid === props.userid)
  869. })
  870. // AI按钮拖动相关状态
  871. const aiBtnPosition = ref({ x: 80, y: 70 }) // 初始位置(从右下角计算)
  872. const isDragging = ref(false)
  873. const dragStart = ref({ x: 0, y: 0 })
  874. const slideListWrapRef = ref<HTMLElement | null>(null)
  875. const aiBtnRef = ref<HTMLElement | null>(null)
  876. // 处理AI按钮开始拖动
  877. const handleAiBtnPointerDown = (e: PointerEvent) => {
  878. isDragging.value = true
  879. const aiBtn = aiBtnRef.value
  880. if (aiBtn) {
  881. // 设置指针捕获,确保即使鼠标移出元素也能继续接收事件
  882. aiBtn.setPointerCapture(e.pointerId)
  883. }
  884. // 获取slide-list-wrap元素的位置和尺寸
  885. const slideListWrap = slideListWrapRef.value
  886. if (slideListWrap) {
  887. const rect = slideListWrap.getBoundingClientRect()
  888. dragStart.value = {
  889. x: e.clientX - (rect.right - aiBtnPosition.value.x),
  890. y: e.clientY - (rect.bottom - aiBtnPosition.value.y)
  891. }
  892. }
  893. e.preventDefault()
  894. }
  895. // 处理拖动中
  896. const handleAiBtnPointerMove = (e: PointerEvent) => {
  897. if (isDragging.value) {
  898. const slideListWrap = slideListWrapRef.value
  899. if (slideListWrap) {
  900. const rect = slideListWrap.getBoundingClientRect()
  901. // 计算新位置(从slide-list-wrap右下角计算)
  902. const newX = rect.right - (e.clientX - dragStart.value.x)
  903. const newY = rect.bottom - (e.clientY - dragStart.value.y)
  904. // 限制在slide-list-wrap范围内
  905. const aiBtnWidth = 120 // 估计AI按钮宽度
  906. const aiBtnHeight = 40 // 估计AI按钮高度
  907. aiBtnPosition.value = {
  908. x: Math.max(20, Math.min(newX, rect.width - aiBtnWidth)),
  909. y: Math.max(20, Math.min(newY, rect.height - aiBtnHeight))
  910. }
  911. }
  912. }
  913. }
  914. // 处理拖动结束
  915. const handleAiBtnPointerUp = (e: PointerEvent) => {
  916. isDragging.value = false
  917. const aiBtn = aiBtnRef.value
  918. if (aiBtn) {
  919. // 释放指针捕获
  920. aiBtn.releasePointerCapture(e.pointerId)
  921. }
  922. }
  923. // 处理指针取消(如浏览器标签页切换)
  924. const handleAiBtnPointerCancel = (e: PointerEvent) => {
  925. isDragging.value = false
  926. const aiBtn = aiBtnRef.value
  927. if (aiBtn) {
  928. // 释放指针捕获
  929. aiBtn.releasePointerCapture(e.pointerId)
  930. }
  931. }
  932. // 监听isQuestionFrame和hasWork的变化,当按钮显示时添加事件监听器
  933. watch([isQuestionFrame, hasWork], ([newIsQuestionFrame, newHasWork]) => {
  934. if (newIsQuestionFrame && newHasWork) {
  935. // 按钮显示了,添加事件监听器
  936. nextTick(() => {
  937. const aiBtn = aiBtnRef.value
  938. if (aiBtn) {
  939. aiBtn.addEventListener('pointerdown', handleAiBtnPointerDown)
  940. aiBtn.addEventListener('pointermove', handleAiBtnPointerMove)
  941. aiBtn.addEventListener('pointerup', handleAiBtnPointerUp)
  942. aiBtn.addEventListener('pointercancel', handleAiBtnPointerCancel)
  943. }
  944. })
  945. }
  946. else {
  947. // 按钮隐藏了,移除事件监听器
  948. const aiBtn = aiBtnRef.value
  949. if (aiBtn) {
  950. aiBtn.removeEventListener('pointerdown', handleAiBtnPointerDown)
  951. aiBtn.removeEventListener('pointermove', handleAiBtnPointerMove)
  952. aiBtn.removeEventListener('pointerup', handleAiBtnPointerUp)
  953. aiBtn.removeEventListener('pointercancel', handleAiBtnPointerCancel)
  954. }
  955. }
  956. })
  957. onUnmounted(() => {
  958. // 移除事件监听器
  959. const aiBtn = aiBtnRef.value
  960. if (aiBtn) {
  961. aiBtn.removeEventListener('pointerdown', handleAiBtnPointerDown)
  962. aiBtn.removeEventListener('pointermove', handleAiBtnPointerMove)
  963. aiBtn.removeEventListener('pointerup', handleAiBtnPointerUp)
  964. aiBtn.removeEventListener('pointercancel', handleAiBtnPointerCancel)
  965. }
  966. cleanupWebSocketConnection()
  967. })
  968. const visibleAIChat = ref(false)
  969. // 打开AI对话框
  970. const openAiChat = () => {
  971. visibleAIChat.value = !visibleAIChat.value
  972. }
  973. // 检测当前幻灯片是否包含iframe元素
  974. const currentSlideHasIframe = computed(() => {
  975. console.log('elementList.value', elementList.value)
  976. return elementList.value.some(element => element.type === ElementTypes.FRAME)
  977. })
  978. const currentSlideToolType = computed(() => {
  979. const frame = elementList.value.find(element => element.type === ElementTypes.FRAME)
  980. return Number((frame as any)?.toolType) || 0
  981. })
  982. const currentSlideConfigId = computed(() => {
  983. const toolType = currentSlideToolType.value
  984. if (!isTopicDiscussionTool(toolType) && !isArticleReadingTool(toolType)) return ''
  985. const frame = elementList.value.find(element => element.type === ElementTypes.FRAME)
  986. return (frame as any)?.url || ''
  987. })
  988. // 检测当前幻灯片是否包含B站视频
  989. const currentSlideHasBilibiliVideo = computed(() => {
  990. return elementList.value.some(element =>
  991. element.type === ElementTypes.FRAME && (element.toolType === 75 || element.toolType === 74 || element.toolType === 76 || element.toolType === 81)
  992. )
  993. })
  994. // 检测当前幻灯片是否是英语口语(话题讨论或文章朗读):
  995. // 通用作业提交/刷新按钮对这两类都必须保持抑制
  996. const currentSlideHasEnglishSpeaking = computed(() => {
  997. return elementList.value.some(element =>
  998. element.type === ElementTypes.FRAME &&
  999. (isTopicDiscussionTool(element.toolType) || isArticleReadingTool(element.toolType))
  1000. )
  1001. })
  1002. // 检查当前的结果状态
  1003. const currentIsResultArray = computed(() => {
  1004. console.log('isResultArray.value[slideIndex.value]', isResultArray.value[slideIndex.value])
  1005. return isResultArray.value[slideIndex.value] || {}
  1006. })
  1007. // 跳转到指定幻灯片
  1008. const goToSlide = (index: number) => {
  1009. console.log('goToSlide 被调用,目标索引:', index)
  1010. console.log('当前索引:', slideIndex.value, 'slides长度:', slides.value.length)
  1011. // slides 还没加载完时,暂存目标索引,等 slides 就绪后再跳转
  1012. if (slides.value.length === 0) {
  1013. console.warn('goToSlide: slides 未加载,暂存目标索引:', index)
  1014. pendingSlideIndex.value = index
  1015. return
  1016. }
  1017. if (index >= 0 && index < slides.value.length) {
  1018. slidesStore.updateSlideIndex(index)
  1019. console.log('更新后的索引:', slideIndex.value)
  1020. }
  1021. else {
  1022. console.warn('goToSlide: 无效的索引:', index)
  1023. }
  1024. }
  1025. // 暂存的目标幻灯片索引(slides 未就绪时使用)
  1026. const pendingSlideIndex = ref<number | null>(null)
  1027. // slides 加载完成后应用暂存的跳转
  1028. watch(() => slides.value.length, (len) => {
  1029. if (len > 0 && pendingSlideIndex.value !== null) {
  1030. const idx = pendingSlideIndex.value
  1031. pendingSlideIndex.value = null
  1032. if (idx >= 0 && idx < len) {
  1033. console.log('🔄 slides 就绪,应用暂存的跳转索引:', idx)
  1034. slidesStore.updateSlideIndex(idx)
  1035. }
  1036. }
  1037. })
  1038. // 上一页
  1039. const previousSlide = () => {
  1040. if (slideIndex.value > 0) {
  1041. const newIndex = slideIndex.value - 1
  1042. console.log('上一页,从', slideIndex.value, '到', newIndex)
  1043. slidesStore.updateSlideIndex(newIndex)
  1044. }
  1045. }
  1046. // 下一页
  1047. const nextSlide = () => {
  1048. if (slideIndex.value < slides.value.length - 1) {
  1049. const newIndex = slideIndex.value + 1
  1050. console.log('下一页,从', slideIndex.value, '到', newIndex)
  1051. slidesStore.updateSlideIndex(newIndex)
  1052. }
  1053. }
  1054. // 监听幻灯片切换,清除不匹配的画图数据
  1055. watch(() => slideIndex.value, () => {
  1056. if (props.type == '2' && yWritingBoardState.value && currentSlide.value) {
  1057. const snap = yWritingBoardState.value.toJSON()
  1058. console.log('📝 幻灯片切换,检查画图数据:', { snap, currentSlideId: currentSlide.value.id })
  1059. if (snap && snap.slideId === currentSlide.value.id && snap.dataURL) {
  1060. // 当前幻灯片有画图数据,显示
  1061. writingBoardSyncDataURL.value = snap.dataURL
  1062. writingBoardSyncBlackboard.value = snap.blackboard !== undefined ? snap.blackboard : null
  1063. console.log('📝 当前幻灯片有画图数据,显示画图工具,小黑板状态:', writingBoardSyncBlackboard.value)
  1064. }
  1065. else {
  1066. // 当前幻灯片没有画图数据,隐藏
  1067. writingBoardSyncDataURL.value = null
  1068. writingBoardSyncBlackboard.value = null
  1069. console.log('📝 当前幻灯片没有画图数据,隐藏画图工具')
  1070. }
  1071. if (visibleAIChat.value) {
  1072. visibleAIChat.value = false
  1073. }
  1074. }
  1075. })
  1076. // 监听 currentSlide 变化,确保刷新后能获取到画图状态
  1077. watch(() => currentSlide.value?.id, (newSlideId, oldSlideId) => {
  1078. // 记录进入当前幻灯片的时间戳(immediate 保证刷新后 slides 加载完成也能记录)
  1079. if (newSlideId && newSlideId !== oldSlideId) {
  1080. slideEnterTime.value = Date.now()
  1081. }
  1082. // 只在学生端且跟随模式下检查
  1083. if (props.type == '2' && isFollowModeActive.value && yWritingBoardState.value && newSlideId) {
  1084. const snap = yWritingBoardState.value.toJSON()
  1085. console.log('📝 currentSlide变化,检查画图数据:', { snap, newSlideId, oldSlideId })
  1086. if (snap && snap.slideId === newSlideId && snap.dataURL) {
  1087. // 当前幻灯片有画图数据,显示
  1088. writingBoardSyncDataURL.value = snap.dataURL
  1089. writingBoardSyncBlackboard.value = snap.blackboard !== undefined ? snap.blackboard : null
  1090. console.log('📝 currentSlide变化后找到画图数据,显示画图工具,小黑板状态:', writingBoardSyncBlackboard.value)
  1091. }
  1092. else if (snap && snap.slideId !== newSlideId) {
  1093. // 当前幻灯片没有画图数据,隐藏
  1094. writingBoardSyncDataURL.value = null
  1095. writingBoardSyncBlackboard.value = null
  1096. console.log('📝 currentSlide变化后没有匹配的画图数据,隐藏画图工具')
  1097. }
  1098. }
  1099. }, { immediate: true })
  1100. // 监听slideIndex变化,调用getWork
  1101. watch(() => slideIndex.value, (newIndex, oldIndex) => {
  1102. console.log('slideIndex变化,调用getWork', { newIndex, oldIndex })
  1103. if (newIndex !== oldIndex && typeof newIndex === 'number') {
  1104. // 检查新页面是否有iframe
  1105. const hasIframe = currentSlideHasIframe.value
  1106. if (hasIframe) {
  1107. console.log('当前页面有iframe,获取作业数据')
  1108. console.log('触发getWork,当前幻灯片索引:', newIndex)
  1109. getWork()
  1110. }
  1111. if (props.type == '1' && isFollowModeActive.value && isCreator.value) {
  1112. api.updateCourseFollowC(newIndex, props.courseid as string)
  1113. sendMessage({slideIndex: newIndex, courseid: props.courseid, type: 'slideIndex'})
  1114. }
  1115. // 自动切换到可用的面板
  1116. autoSwitchToAvailablePanel()
  1117. if (isSubmitting.value) {
  1118. isSubmitting.value = false
  1119. }
  1120. if (timerlVisible.value) {
  1121. timerlVisible.value = false
  1122. }
  1123. }
  1124. getWorkId()
  1125. }, { immediate: false, deep: false })
  1126. // 监听iframe状态变化,自动切换面板
  1127. watch(() => currentSlideHasIframe.value, (hasIframe) => {
  1128. if (!hasIframe) {
  1129. autoSwitchToAvailablePanel()
  1130. }
  1131. }, { immediate: false })
  1132. // 全屏
  1133. const enterFullscreen = () => {
  1134. if (document.fullscreenElement) {
  1135. document.exitFullscreen()
  1136. }
  1137. else {
  1138. document.documentElement.requestFullscreen()
  1139. }
  1140. }
  1141. // 监听全屏状态变化
  1142. const handleFullscreenChange = () => {
  1143. isFullscreen.value = !!document.fullscreenElement
  1144. if (isFullscreen.value) {
  1145. // 全屏时不需要计算缩放,直接使用放映功能
  1146. console.log('进入全屏模式')
  1147. }
  1148. else {
  1149. // 退出全屏时重置所有工具状态并重新计算缩放比例
  1150. console.log('退出全屏模式,重置工具状态')
  1151. // 重置所有工具状态
  1152. rightToolsVisible.value = false
  1153. writingBoardToolVisible.value = false
  1154. slideThumbnailModelVisible.value = false
  1155. laserPen.value = false
  1156. // 重新计算缩放比例
  1157. nextTick(() => {
  1158. setTimeout(() => {
  1159. calculateScale()
  1160. }, 1000)
  1161. })
  1162. }
  1163. }
  1164. const getWorkId = () => {
  1165. // 修复类型报错:elementList 可能没有 toolType 和 url 字段,需先判断类型
  1166. const element = elementList.value.find((i:any) => i.type === 'frame')
  1167. console.log(element)
  1168. if (
  1169. element &&
  1170. typeof element === 'object' &&
  1171. ('toolType' in element) &&
  1172. (element as any).toolType !== undefined &&
  1173. toolTypeArray.value.includes((element as any).toolType)
  1174. ) {
  1175. // 提取链接中的id参数
  1176. const url = (element as any).url
  1177. let id = ''
  1178. toolType.value = (element as any).toolType
  1179. if (typeof url === 'string') {
  1180. const match = url.match(/[?&]id=([^&]+)/)
  1181. if (match) {
  1182. id = match[1]
  1183. }
  1184. workUrl.value = url
  1185. workId.value = id
  1186. if ((element as any).toolType === 72) {
  1187. workId.value = (element as any).id
  1188. }
  1189. }
  1190. else {
  1191. workId.value = ''
  1192. workUrl.value = ''
  1193. }
  1194. }
  1195. else {
  1196. workId.value = ''
  1197. workUrl.value = ''
  1198. }
  1199. }
  1200. // 处理画图关闭事件
  1201. const handleWritingBoardClose = () => {
  1202. // 学生端只读模式下,不应该响应关闭事件(因为关闭按钮已隐藏)
  1203. // 只有老师端可以关闭
  1204. if (props.type == '2') {
  1205. console.log('📝 学生端收到关闭事件,但只读模式下不应该关闭,忽略')
  1206. return
  1207. }
  1208. writingBoardToolVisible.value = false
  1209. // 老师端关闭时,清空共享状态并通知学生端
  1210. if (props.type == '1' && isFollowModeActive.value && isCreator.value) {
  1211. clearWritingBoardState()
  1212. }
  1213. }
  1214. // 清空画图共享状态(仅创建人)
  1215. const clearWritingBoardState = () => {
  1216. try {
  1217. if (props.type == '1' && isCreator.value && yWritingBoardState.value) {
  1218. docSocket.value?.transact(() => {
  1219. yWritingBoardState.value.clear()
  1220. })
  1221. sendMessage({
  1222. type: 'writing_board_close',
  1223. courseid: props.courseid
  1224. })
  1225. }
  1226. }
  1227. catch (e) {
  1228. console.warn('清空画图状态失败', e)
  1229. }
  1230. }
  1231. // 处理小黑板状态变化(老师端)
  1232. const handleBlackboardChange = (blackboard: boolean) => {
  1233. if (props.type == '1' && isFollowModeActive.value && isCreator.value) {
  1234. // 同步到共享 Map
  1235. if (yWritingBoardState.value) {
  1236. docSocket.value?.transact(() => {
  1237. yWritingBoardState.value.set('blackboard', blackboard)
  1238. })
  1239. }
  1240. // 广播消息
  1241. sendMessage({
  1242. type: 'writing_board_blackboard',
  1243. blackboard: blackboard,
  1244. courseid: props.courseid
  1245. })
  1246. }
  1247. }
  1248. // 处理画图结束事件(老师端)
  1249. const handleDrawingEnd = (dataURL: string) => {
  1250. if (props.type == '1' && isFollowModeActive.value && isCreator.value) {
  1251. // 同步到共享 Map
  1252. if (yWritingBoardState.value) {
  1253. docSocket.value?.transact(() => {
  1254. yWritingBoardState.value.set('slideId', currentSlide.value.id)
  1255. yWritingBoardState.value.set('dataURL', dataURL)
  1256. // 保持小黑板状态
  1257. const currentBlackboard = yWritingBoardState.value.get('blackboard')
  1258. if (currentBlackboard !== undefined) {
  1259. yWritingBoardState.value.set('blackboard', currentBlackboard)
  1260. }
  1261. })
  1262. }
  1263. // 延迟5秒后广播消息,避免频繁发送
  1264. if (drawingDelayTimer.value) {
  1265. clearTimeout(drawingDelayTimer.value)
  1266. }
  1267. drawingDelayTimer.value = setTimeout(() => {
  1268. const currentBlackboard = yWritingBoardState.value?.get('blackboard') || false
  1269. sendMessage({
  1270. type: 'writing_board_update',
  1271. slideId: currentSlide.value.id,
  1272. dataURL: dataURL,
  1273. blackboard: currentBlackboard,
  1274. courseid: props.courseid
  1275. })
  1276. drawingDelayTimer.value = null
  1277. }, 5000) // 延迟5秒发送
  1278. }
  1279. }
  1280. // 应用画图共享状态(任意端)
  1281. const applyWritingBoardStateSnapshot = (snap: any) => {
  1282. console.log('📝 应用画图状态快照:', snap, '当前幻灯片ID:', currentSlide.value?.id, '跟随模式:', isFollowModeActive.value, '用户类型:', props.type)
  1283. if (!snap || !snap.dataURL || typeof snap.dataURL !== 'string' || snap.dataURL.trim() === '') {
  1284. writingBoardSyncDataURL.value = null
  1285. writingBoardSyncBlackboard.value = null
  1286. console.log('📝 画图状态为空,隐藏画图工具')
  1287. return
  1288. }
  1289. const slideId = snap.slideId
  1290. const dataURL = snap.dataURL
  1291. const blackboardState = snap.blackboard !== undefined ? snap.blackboard : null
  1292. // 只有当前幻灯片匹配时才显示
  1293. if (slideId && currentSlide.value && slideId === currentSlide.value.id) {
  1294. writingBoardSyncDataURL.value = dataURL
  1295. writingBoardSyncBlackboard.value = blackboardState
  1296. console.log('📝 画图数据匹配,显示画图工具,数据长度:', dataURL.length, '小黑板状态:', blackboardState, '显示条件:', {
  1297. type: props.type,
  1298. isFollowModeActive: isFollowModeActive.value,
  1299. hasData: !!writingBoardSyncDataURL.value
  1300. })
  1301. }
  1302. else {
  1303. writingBoardSyncDataURL.value = null
  1304. writingBoardSyncBlackboard.value = null
  1305. console.log('📝 画图数据不匹配,隐藏画图工具', { slideId, currentSlideId: currentSlide.value?.id })
  1306. }
  1307. }
  1308. // 切换激光笔模式
  1309. const toggleLaserPen = () => {
  1310. laserPen.value = !laserPen.value
  1311. console.log('激光笔状态:', laserPen.value ? '开启' : '关闭')
  1312. // 老师端广播激光笔开关
  1313. if (props.type == '1') {
  1314. sendMessage({ type: 'laser_toggle', enabled: laserPen.value, courseid: props.courseid })
  1315. // 同步到共享 Map,方便后来者拿到状态
  1316. if (yLaserState.value) {
  1317. if (laserPen.value) {
  1318. const state: any = { enabled: true }
  1319. if (lastSent.x >= 0 && lastSent.y >= 0) {
  1320. state.x = lastSent.x; state.y = lastSent.y
  1321. }
  1322. docSocket.value?.transact(() => {
  1323. Object.entries(state).forEach(([k, v]) => yLaserState.value.set(k, v as any))
  1324. })
  1325. }
  1326. else {
  1327. // 关闭时清空共享状态
  1328. docSocket.value?.transact(() => {
  1329. yLaserState.value.clear()
  1330. })
  1331. }
  1332. }
  1333. }
  1334. }
  1335. // 老师端移动时广播激光笔位置(百分比坐标)
  1336. let sendRafPending = false
  1337. let lastSent = { x: -1, y: -1 }
  1338. const handleLaserMove = (e: MouseEvent) => {
  1339. if (!(props.type == '1' && laserPen.value)) return
  1340. // 始终以中间画布 .slide-list-wrap 为基准,避免外层左右留白导致的偏差
  1341. const wrap = (viewerCanvasRef.value?.querySelector('.slide-list-wrap') as HTMLElement) || (e.currentTarget as HTMLElement)
  1342. const rect = wrap.getBoundingClientRect()
  1343. const x = Math.min(Math.max(e.clientX - rect.left, 0), rect.width)
  1344. const y = Math.min(Math.max(e.clientY - rect.top, 0), rect.height)
  1345. const xPct = (x / rect.width) * 100
  1346. const yPct = (y / rect.height) * 100
  1347. // 小幅度移动忽略(阈值 0.4%)
  1348. if (Math.abs(xPct - lastSent.x) < 0.4 && Math.abs(yPct - lastSent.y) < 0.4) return
  1349. lastSent = { x: xPct, y: yPct }
  1350. if (sendRafPending) return
  1351. sendRafPending = true
  1352. requestAnimationFrame(() => {
  1353. sendRafPending = false
  1354. // sendMessage 中已经直接更新 Map,不需要重复更新
  1355. sendMessage({ type: 'laser_move', x: lastSent.x, y: lastSent.y, courseid: props.courseid })
  1356. })
  1357. }
  1358. // 清空激光笔共享状态(仅创建人)
  1359. const clearLaserState = () => {
  1360. try {
  1361. if (props.type == '1' && isCreator.value && yLaserState.value) {
  1362. docSocket.value?.transact(() => {
  1363. yLaserState.value.clear()
  1364. })
  1365. sendMessage({ type: 'laser_toggle', enabled: false, courseid: props.courseid })
  1366. }
  1367. }
  1368. catch (e) {
  1369. console.warn('清空激光笔状态失败', e)
  1370. }
  1371. }
  1372. // 清空所有同步状态(仅创建人)
  1373. const clearAllSyncStates = () => {
  1374. try {
  1375. if (props.type == '1' && isCreator.value && docSocket.value) {
  1376. console.log('🧹 创建老师退出,清空所有同步状态')
  1377. docSocket.value.transact(() => {
  1378. // ★ 不删除 latest!delete 会传播给学生导致 get('latest') 返回 undefined
  1379. // 旧 latest 会被 sendMessage 的 set('latest', message) 自然覆盖
  1380. const timerMessagesArray = docSocket.value?.getArray?.('timerMessages')
  1381. if (timerMessagesArray) {
  1382. timerMessagesArray.delete(0, timerMessagesArray.length)
  1383. }
  1384. // 清空激光笔消息数组
  1385. const laserMessagesArray = docSocket.value?.getArray?.('laserMessages')
  1386. if (laserMessagesArray) {
  1387. laserMessagesArray.delete(0, laserMessagesArray.length)
  1388. }
  1389. // 清空画图消息数组
  1390. const writingBoardMessagesArray = docSocket.value?.getArray?.('writingBoardMessages')
  1391. if (writingBoardMessagesArray) {
  1392. writingBoardMessagesArray.delete(0, writingBoardMessagesArray.length)
  1393. }
  1394. // 清空计时器状态
  1395. const timerStateMap = docSocket.value?.getMap?.('timerState')
  1396. if (timerStateMap) {
  1397. timerStateMap.clear()
  1398. }
  1399. // 清空激光笔状态
  1400. const laserStateMap = docSocket.value?.getMap?.('laserState')
  1401. if (laserStateMap) {
  1402. laserStateMap.clear()
  1403. }
  1404. // 清空画图状态
  1405. const writingBoardStateMap = docSocket.value?.getMap?.('writingBoardState')
  1406. if (writingBoardStateMap) {
  1407. writingBoardStateMap.clear()
  1408. }
  1409. })
  1410. }
  1411. }
  1412. catch (e) {
  1413. console.warn('清空所有同步状态失败', e)
  1414. }
  1415. }
  1416. // 获取导入导出功能
  1417. const { readJSON, exportJSON2, getFile, getFile2 } = useImport()
  1418. // 根据iframe的URL查找对应的幻灯片索引
  1419. const findSlideIndexByIframeUrl = (iframeUrl: string): number => {
  1420. try {
  1421. console.log('查找iframe对应的幻灯片索引,iframe URL:', iframeUrl)
  1422. // 遍历所有幻灯片,查找包含该iframe URL的幻灯片
  1423. for (let i = 0; i < slides.value.length; i++) {
  1424. const slide = slides.value[i]
  1425. // 检查幻灯片的元素中是否有iframe
  1426. if (slide.elements && slide.elements.length > 0) {
  1427. for (const element of slide.elements) {
  1428. // 检查是否是iframe元素
  1429. if (element.type === ElementTypes.FRAME) {
  1430. // 检查iframe的src是否匹配
  1431. if (element.url === iframeUrl) {
  1432. console.log(`找到匹配的幻灯片,索引: ${i}, 幻灯片ID: ${slide.id}`)
  1433. return i
  1434. }
  1435. }
  1436. }
  1437. }
  1438. }
  1439. // 如果没有找到匹配的幻灯片,返回当前幻灯片索引
  1440. console.log('未找到匹配的幻灯片,使用当前幻灯片索引:', slideIndex.value)
  1441. return slideIndex.value
  1442. }
  1443. catch (error) {
  1444. console.error('查找幻灯片索引时出错:', error)
  1445. return slideIndex.value
  1446. }
  1447. }
  1448. // 处理iframe链接,为包含workPage的iframe添加必要参数
  1449. // 处理iframe链接,为包含workPage的iframe添加必要参数
  1450. const processIframeLinks = async () => {
  1451. try {
  1452. console.log('开始处理iframe链接')
  1453. console.log('当前props:', { courseid: props.courseid, userid: props.userid })
  1454. // 从slides数据中查找包含iframe的元素
  1455. let hasIframe = false
  1456. // 由于有异步操作,需整体用Promise.all处理
  1457. const updatedSlides = await Promise.all(
  1458. slides.value.map(async (slide, slideIndex) => {
  1459. if (slide.elements && slide.elements.length > 0) {
  1460. // 这里不能直接用async map,否则会导致类型不对
  1461. const updatedElements = await Promise.all(
  1462. slide.elements.map(async (element) => {
  1463. // 检查是否是iframe元素
  1464. if (element.type === ElementTypes.FRAME && element.url) {
  1465. const { element: updatedElement, hasIframe: updatedHasIframe } = await elementDone(element, slideIndex)
  1466. // hasIframe = updatedHasIframe
  1467. hasIframe = true
  1468. console.log('更新后的iframe元素:', updatedElement)
  1469. return {
  1470. ...updatedElement,
  1471. isDone: true
  1472. }
  1473. }
  1474. // 不是iframe元素或不需要处理,直接返回
  1475. return element
  1476. })
  1477. )
  1478. // 返回更新后的幻灯片
  1479. return {
  1480. ...slide,
  1481. elements: updatedElements
  1482. }
  1483. }
  1484. // 没有元素的幻灯片直接返回
  1485. return slide
  1486. })
  1487. )
  1488. if (hasIframe) {
  1489. console.log('找到iframe元素,更新slides数据')
  1490. // 更新store中的slides数据
  1491. slidesStore.setSlides(updatedSlides)
  1492. console.log('slides数据更新完成')
  1493. }
  1494. else {
  1495. console.log('未找到包含workPage的iframe元素')
  1496. }
  1497. console.log('iframe链接处理完成')
  1498. }
  1499. catch (error) {
  1500. console.error('处理iframe链接时出错:', error)
  1501. }
  1502. }
  1503. const elementDone = async (element: any, slideIndex: number) => {
  1504. let hasIframe = false
  1505. let _element = {...element}
  1506. let iframeSrc = element.url
  1507. const toolType = element.toolType
  1508. console.log('当前版本:', currentVersion)
  1509. // 替换beta环境域名
  1510. iframeSrc = iframeSrc.replace(/https?:\/\/beta\.pbl\.cocorobo\.cn/g, 'https://pbl.cocorobo.cn')
  1511. // 根据当前版本统一域名
  1512. const versionMap = {
  1513. cn: /cocorobo\.(hk|com)/g,
  1514. hk: /cocorobo\.(cn|com)/g,
  1515. com: /cocorobo\.(cn|hk)/g
  1516. }
  1517. const targetDomain = `cocorobo.${currentVersion}`
  1518. iframeSrc = iframeSrc.replace(versionMap[currentVersion], targetDomain)
  1519. if (iframeSrc.includes('setWorkPage')) {
  1520. iframeSrc = iframeSrc.replace(/setWorkPage/g, 'workPageNew')
  1521. }
  1522. if (iframeSrc.includes('workPage')) {
  1523. hasIframe = true
  1524. console.log(`处理幻灯片 ${slideIndex + 1} 中的iframe链接:`, iframeSrc)
  1525. try {
  1526. // 解析URL,处理hash部分
  1527. let baseUrl = iframeSrc
  1528. let hashPart = ''
  1529. // 分离base URL和hash部分
  1530. if (iframeSrc.includes('#')) {
  1531. const parts = iframeSrc.split('#')
  1532. baseUrl = parts[0]
  1533. hashPart = parts[1]
  1534. // 去除hashPart中的userid参数
  1535. if (hashPart.includes('userid=')) {
  1536. hashPart = hashPart.replace(/[?&]userid=[^&]+/g, '').replace(/^&/, '?')
  1537. }
  1538. }
  1539. // 构建新的hash部分,添加参数
  1540. // 使用当前幻灯片索引作为task参数
  1541. let newHash = hashPart
  1542. if (newHash.includes('?')) {
  1543. // 如果hash中已经有查询参数,添加&
  1544. newHash += `&courseid=${props.courseid || ''}&userid=${props.userid || ''}&stage=0&task=${slideIndex}&tool=0&cid=${props.cid || ''}`
  1545. }
  1546. else {
  1547. // 如果hash中没有查询参数,添加?
  1548. newHash += `?courseid=${props.courseid || ''}&userid=${props.userid || ''}&stage=0&task=${slideIndex}&tool=0&cid=${props.cid || ''}`
  1549. }
  1550. // 构建新的URL
  1551. let newUrl = `${baseUrl}#${newHash}`
  1552. console.log(`幻灯片 ${slideIndex + 1} 的iframe链接已更新:`, newUrl)
  1553. if (window.location.href.includes('beta') && !newUrl.includes('beta')) {
  1554. newUrl = newUrl.replace('pbl.cocorobo.cn', 'beta.pbl.cocorobo.cn')
  1555. }
  1556. else if (newUrl.includes('beta') && !window.location.href.includes('beta')) {
  1557. newUrl = newUrl.replace('beta.pbl.cocorobo.cn', 'pbl.cocorobo.cn')
  1558. }
  1559. // 返回更新后的元素
  1560. _element = {
  1561. ...element,
  1562. url: newUrl
  1563. }
  1564. }
  1565. catch (error) {
  1566. console.error(`处理幻灯片 ${slideIndex + 1} 的iframe链接时出错:`, error)
  1567. return {
  1568. element: _element,
  1569. hasIframe
  1570. }
  1571. }
  1572. }
  1573. else if (iframeSrc.includes('aichat.cocorobo') || iframeSrc.includes('knowledge.cocorobo')) {
  1574. hasIframe = true
  1575. try {
  1576. // 解析URL,处理hash部分
  1577. let baseUrl = iframeSrc
  1578. let hashPart = ''
  1579. let isHashPart = false
  1580. // 分离base URL和hash部分
  1581. if (iframeSrc.includes('#')) {
  1582. const parts = iframeSrc.split('#')
  1583. baseUrl = parts[0]
  1584. hashPart = parts[1]
  1585. isHashPart = true
  1586. }
  1587. // 构建新的hash部分,添加参数
  1588. // 使用当前幻灯片索引作为task参数
  1589. let newHash = hashPart
  1590. if (newHash.includes('?')) {
  1591. // 如果hash中已经有查询参数,添加&
  1592. newHash += `&courseid=${props.courseid || ''}&layout=laptop`
  1593. }
  1594. else {
  1595. // 如果hash中没有查询参数,添加?
  1596. newHash += `?courseid=${props.courseid || ''}&layout=laptop`
  1597. }
  1598. // 构建新的URL
  1599. let newUrl = `${baseUrl}#${newHash}`
  1600. if (!isHashPart) {
  1601. newUrl = `${baseUrl}${newHash}`
  1602. }
  1603. console.log(`幻灯片 ${slideIndex + 1} 的iframe链接已更新:`, newUrl)
  1604. // 返回更新后的元素
  1605. _element = {
  1606. ...element,
  1607. url: newUrl
  1608. }
  1609. }
  1610. catch (error) {
  1611. console.error(`处理幻灯片 ${slideIndex + 1} 的iframe链接时出错:`, error)
  1612. return {
  1613. element: _element,
  1614. hasIframe
  1615. }
  1616. }
  1617. }
  1618. else if (toolType === 76) {
  1619. hasIframe = true
  1620. try {
  1621. // 解析URL,处理hash部分
  1622. let baseUrl = iframeSrc
  1623. let hashPart = ''
  1624. // 分离base URL和hash部分
  1625. if (iframeSrc.includes('#')) {
  1626. const parts = iframeSrc.split('#')
  1627. baseUrl = parts[0]
  1628. hashPart = parts[1]
  1629. }
  1630. // 构建新的hash部分,添加参数
  1631. // 使用当前幻灯片索引作为task参数
  1632. let newHash = hashPart
  1633. if (newHash.includes('?')) {
  1634. // 如果hash中已经有查询参数,添加&
  1635. newHash += `&mode=pptMode`
  1636. }
  1637. else {
  1638. // 如果hash中没有查询参数,添加?
  1639. newHash += `?mode=pptMode`
  1640. }
  1641. // 构建新的URL
  1642. const newUrl = `${baseUrl}#${newHash}`
  1643. console.log(`幻灯片 ${slideIndex + 1} 的iframe链接已更新:`, newUrl)
  1644. // 返回更新后的元素
  1645. _element = {
  1646. ...element,
  1647. url: newUrl
  1648. }
  1649. }
  1650. catch (error) {
  1651. console.error(`处理幻灯片 ${slideIndex + 1} 的iframe链接时出错:`, error)
  1652. return {
  1653. element: _element,
  1654. hasIframe
  1655. }
  1656. }
  1657. }
  1658. else if (toolType === 73) {
  1659. hasIframe = true
  1660. // 先尝试获取iframe的contentWindow,如果获取不到再使用HTML方式
  1661. try {
  1662. // 创建一个临时的iframe来测试是否能获取contentWindow
  1663. const tempIframe = document.createElement('iframe')
  1664. tempIframe.style.display = 'none'
  1665. tempIframe.src = iframeSrc
  1666. // 先将临时iframe添加到body,否则onload事件不会触发
  1667. document.body.appendChild(tempIframe)
  1668. // 等待iframe加载完成
  1669. await new Promise((resolve, reject) => {
  1670. tempIframe.onload = resolve
  1671. tempIframe.onerror = reject
  1672. // 可选:设置超时时间,避免长时间无响应
  1673. setTimeout(() => reject(new Error('Timeout')), 5000)
  1674. })
  1675. // 尝试获取contentWindow
  1676. if (tempIframe.contentWindow && tempIframe.contentWindow.document) {
  1677. console.log(`iframe ${iframeSrc} 可以获取contentWindow,使用直接加载方式`)
  1678. // 移除临时iframe
  1679. document.body.removeChild(tempIframe)
  1680. _element = {
  1681. ...element,
  1682. isHTML: false,
  1683. url: iframeSrc
  1684. }
  1685. }
  1686. else {
  1687. // 加载完成但无法获取contentWindow,也要移除iframe
  1688. document.body.removeChild(tempIframe)
  1689. }
  1690. }
  1691. catch (error) {
  1692. console.log(`iframe ${iframeSrc} 无法获取contentWindow,使用HTML方式:`, error)
  1693. // 如果无法获取contentWindow,使用HTML方式
  1694. let html = null
  1695. try {
  1696. html = await api.getHTML(iframeSrc)
  1697. console.log('getHTML 成功获取内容:', html)
  1698. }
  1699. catch (error) {
  1700. console.log(`getHTML 失败,尝试使用 getFile:`, error)
  1701. try {
  1702. const fileData = await getFile(iframeSrc)
  1703. if (fileData && fileData.data) {
  1704. const uint8Array = new Uint8Array(fileData.data)
  1705. html = new TextDecoder('utf-8').decode(uint8Array)
  1706. console.log('getFile 成功获取内容:', html)
  1707. }
  1708. }
  1709. catch (error2) {
  1710. console.log(`getFile 失败,尝试使用 getHTML:`, error2)
  1711. try {
  1712. const fileData2 = await getFile2(iframeSrc)
  1713. if (fileData2 && fileData2.data) {
  1714. const uint8Array = new Uint8Array(fileData2.data)
  1715. html = new TextDecoder('utf-8').decode(uint8Array)
  1716. console.log('getFile2 成功获取内容:', html)
  1717. }
  1718. }
  1719. catch (error3) {
  1720. console.error('getFile2 也失败:', error3)
  1721. console.error('无法获取内容: getFile、getFile2 和 getHTML 都失败了')
  1722. }
  1723. }
  1724. }
  1725. console.log(`处理幻灯片 ${slideIndex + 1} 中的iframe链接:`, iframeSrc)
  1726. _element = {
  1727. ...element,
  1728. isHTML: true,
  1729. url: html,
  1730. curl: iframeSrc
  1731. }
  1732. }
  1733. }
  1734. return {
  1735. element: _element,
  1736. hasIframe
  1737. }
  1738. }
  1739. // 导入JSON功能
  1740. const importJSON = (jsonData: any) => {
  1741. try {
  1742. console.log('Student importJSON 开始执行')
  1743. const result = readJSON(jsonData, true)
  1744. if (result.success) {
  1745. console.log('Student importJSON 成功,开始重新渲染')
  1746. // 强制重新渲染:先隐藏组件
  1747. showSlideList.value = false
  1748. // 重新计算画布尺寸和缩放比例
  1749. nextTick(() => {
  1750. calculateScale()
  1751. // 延迟500ms后重新显示组件,确保重新渲染完成
  1752. setTimeout(() => {
  1753. showSlideList.value = true
  1754. // 只有当当前页面存在iframe时才获取作业数据
  1755. if (currentSlideHasIframe.value) { // && props.type == '1'
  1756. getWork()
  1757. }
  1758. selectCourseSLook(1)
  1759. console.log('组件重新渲染完成')
  1760. }, 500)
  1761. })
  1762. return true
  1763. }
  1764. console.error('Student importJSON 失败:', result.error)
  1765. return false
  1766. }
  1767. catch (error) {
  1768. console.error('Student importJSON 执行失败:', error)
  1769. return false
  1770. }
  1771. }
  1772. // 导出JSON功能
  1773. const exportJSON = () => {
  1774. try {
  1775. console.log('Student exportJSON 开始执行,调用 useImport.exportJSON2')
  1776. // 直接调用 useImport 中的 exportJSON2 函数
  1777. const exportData = exportJSON2()
  1778. if (exportData) {
  1779. return exportData
  1780. }
  1781. console.error('Student exportJSON 失败: exportJSON2 返回空数据')
  1782. return false
  1783. }
  1784. catch (error) {
  1785. console.error('Student exportJSON 执行失败:', error)
  1786. return false
  1787. }
  1788. }
  1789. // 返回编辑器
  1790. const backToEditor = () => {
  1791. // 通过路由跳转到编辑模式
  1792. window.location.href = '/'
  1793. }
  1794. const submitWork = async (slideIndex: number, atool: string, content: string, type: string) => {
  1795. const res = await api.submitWork({
  1796. uid: props.userid as string,
  1797. cid: props.courseid as string,
  1798. stage: '0',
  1799. task: String(slideIndex), // 转为字符串
  1800. tool: '0',
  1801. atool: atool,
  1802. content: content,
  1803. type: type
  1804. })
  1805. getWork()
  1806. console.log(res)
  1807. }
  1808. // 文件上传到AWS S3的函数
  1809. const uploadFile = (file: File): Promise<string> => {
  1810. return new Promise((resolve, reject) => {
  1811. try {
  1812. // 检查AWS SDK是否可用
  1813. if (!(window as any).AWS) {
  1814. reject(new Error('AWS SDK not loaded'))
  1815. return
  1816. }
  1817. const credentials = {
  1818. accessKeyId: 'AKIATLPEDU37QV5CHLMH',
  1819. secretAccessKey: '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'
  1820. }
  1821. // 配置AWS
  1822. ;(window as any).AWS.config.update(credentials)
  1823. ;(window as any).AWS.config.region = 'cn-northwest-1'
  1824. // 创建S3实例
  1825. const bucket = new (window as any).AWS.S3({ params: { Bucket: 'ccrb' } })
  1826. if (file) {
  1827. // 生成唯一的文件名
  1828. const fileExtension = file.name.split('.').pop()
  1829. const fileName = `${file.name.split('.')[0]}_${Date.now()}.${fileExtension}`
  1830. const params = {
  1831. Key: fileName,
  1832. ContentType: file.type,
  1833. Body: file,
  1834. ACL: 'public-read'
  1835. }
  1836. const options = {
  1837. partSize: 5 * 1024 * 1024, // 2GB分片
  1838. queueSize: 2,
  1839. leavePartsOnError: true
  1840. }
  1841. bucket
  1842. .upload(params, options)
  1843. .on('httpUploadProgress', (evt: any) => {
  1844. // 这里可以添加进度条逻辑
  1845. const progress = Math.round((evt.loaded * 100) / evt.total)
  1846. console.log(`Uploaded: ${progress}%`)
  1847. })
  1848. .send((err: any, data: any) => {
  1849. if (err) {
  1850. console.error('Upload failed:', err)
  1851. message.error(lang.ssFileUploadFail)
  1852. reject(err)
  1853. }
  1854. else {
  1855. console.log('Upload successful:', data.Location)
  1856. resolve(data.Location)
  1857. }
  1858. })
  1859. }
  1860. else {
  1861. reject(new Error('No file provided'))
  1862. }
  1863. }
  1864. catch (error) {
  1865. console.error('Upload error:', error)
  1866. reject(error)
  1867. }
  1868. })
  1869. }
  1870. // 作业提交功能(优化版)
  1871. const handleHomeworkSubmit = async () => {
  1872. console.log('作业提交按钮被点击')
  1873. // 防抖:如果正在提交中,直接返回
  1874. if (isSubmitting.value) {
  1875. console.log('作业正在提交中,忽略重复点击')
  1876. return
  1877. }
  1878. isSubmitting.value = true
  1879. let homeworkContent: string = lang.ssHwSubmit // 默认作业内容
  1880. let hasSubmitWork = false // 标记是否成功提交作业
  1881. try {
  1882. // 获取所有iframe元素
  1883. const iframes = document.querySelectorAll('.viewer-canvas .screen-slide')[slideIndex.value].querySelectorAll('iframe')
  1884. console.log('找到iframe元素数量:', iframes.length)
  1885. if (iframes.length === 0) {
  1886. message.warning('当前页面没有找到iframe元素')
  1887. return
  1888. }
  1889. for (let i = 0; i < iframes.length; i++) {
  1890. const iframe = iframes[i] as HTMLIFrameElement
  1891. const iframeSrc = iframe.src
  1892. console.log(`iframe ${i + 1} 链接:`, iframeSrc)
  1893. // 检查iframe链接是否包含workPage
  1894. if (iframeSrc && iframeSrc.includes('workPage')) {
  1895. console.log('找到包含workPage的iframe,尝试执行submitWork')
  1896. try {
  1897. const iframeWindow = iframe.contentWindow as Window & { submitWork?: (...args: any[]) => unknown }
  1898. if (iframeWindow && typeof iframeWindow.submitWork === 'function') {
  1899. console.log('执行iframe中的submitWork方法,参数可变')
  1900. const iframeSlideIndex = slideIndex.value
  1901. const submitArgs = [iframeSlideIndex]
  1902. // 支持同步和异步submitWork
  1903. const result = await iframeWindow.submitWork(...submitArgs)
  1904. console.log('submitWork同步执行完成')
  1905. // 尝试从结果中获取作业内容
  1906. if (result && typeof result === 'object') {
  1907. homeworkContent = JSON.stringify(result)
  1908. }
  1909. else if (result) {
  1910. homeworkContent = String(result)
  1911. }
  1912. else {
  1913. homeworkContent = lang.ssHwSubmitWp
  1914. }
  1915. messageInstructionRef.value.success(lang.ssHwSubmitSucc)
  1916. hasSubmitWork = true
  1917. // 发送作业提交成功的socket消息
  1918. sendMessage({
  1919. type: 'homework_submitted',
  1920. courseid: props.courseid,
  1921. slideIndex: slideIndex.value,
  1922. userid: props.userid
  1923. })
  1924. break
  1925. }
  1926. else {
  1927. console.log('iframe中没有找到submitWork方法')
  1928. isSubmitting.value = false
  1929. }
  1930. }
  1931. catch (error) {
  1932. console.error('访问iframe内容时出错:', error)
  1933. isSubmitting.value = false
  1934. }
  1935. }
  1936. else if (iframeSrc && (iframeSrc.includes('aichat.cocorobo') || iframeSrc.includes('knowledge.cocorobo'))) {
  1937. console.log('找到包含aichat.cocorobo或knowledge.cocorobo的iframe,尝试执行submitWork')
  1938. // 由于TS类型检查,需通过 any 绕过类型限制
  1939. const iframeWindow = iframe.contentWindow as any
  1940. if (iframeWindow && iframeWindow.exposed_outputs) {
  1941. if (iframeWindow.exposed_outputs.length === 0) {
  1942. message.warning('没有找到作业内容')
  1943. hasSubmitWork = true
  1944. continue
  1945. }
  1946. console.log('执行iframe中的submitWork方法,参数可变')
  1947. const iframeSlideIndex = slideIndex.value
  1948. const jsonString = JSON.stringify(iframeWindow.exposed_outputs)
  1949. // 将 JSON 字符串转成文件并上传
  1950. try {
  1951. const blob = new Blob([jsonString], { type: 'application/json' })
  1952. const file = new File([blob], `ai_work_${Date.now()}.json`, { type: 'application/json' })
  1953. const fileUrl = await uploadFile(file)
  1954. console.log('文件上传成功,链接:', fileUrl)
  1955. homeworkContent = fileUrl // 保存AI作业内容
  1956. // 使用上传后的链接提交作业
  1957. await submitWork(iframeSlideIndex, '72', fileUrl, '20')
  1958. messageInstructionRef.value.success(lang.ssHwSubmitSucc)
  1959. hasSubmitWork = true
  1960. // 发送作业提交成功的socket消息
  1961. sendMessage({
  1962. type: 'homework_submitted',
  1963. courseid: props.courseid,
  1964. slideIndex: slideIndex.value,
  1965. userid: props.userid
  1966. })
  1967. }
  1968. catch (error) {
  1969. console.error('文件上传失败:', error)
  1970. isSubmitting.value = false
  1971. message.error(lang.ssHwSubmitRetry)
  1972. }
  1973. }
  1974. }
  1975. else if (slides.value[slideIndex.value].elements.some((element: any) => element.isHTML)) {
  1976. message.info(lang.ssTryingScreenshot)
  1977. console.log('尝试截图当前页面并提交ISHTML')
  1978. // return
  1979. try {
  1980. // 尝试使用html2canvas,对iframe支持更好
  1981. let imageData: string
  1982. const screenSlides = document.querySelectorAll('.viewer-canvas .screen-slide')
  1983. let iframeElement: HTMLIFrameElement | null = null
  1984. let iframeBody: HTMLElement | null = null
  1985. let iframehtml: HTMLElement | null = null
  1986. // 获取iframe元素
  1987. if (
  1988. screenSlides &&
  1989. screenSlides[slideIndex.value] &&
  1990. screenSlides[slideIndex.value].querySelector('iframe')
  1991. ) {
  1992. iframeElement = screenSlides[slideIndex.value].querySelector('iframe') as HTMLIFrameElement
  1993. }
  1994. else {
  1995. message.error(lang.ssFailedGetIframe)
  1996. throw new Error('未能获取到iframe元素,无法截图')
  1997. }
  1998. // 获取iframe内部的body元素(同源)
  1999. if (
  2000. iframeElement.contentWindow &&
  2001. iframeElement.contentWindow.document &&
  2002. iframeElement.contentWindow.document.body
  2003. ) {
  2004. // 获取页面的所有注释节点
  2005. const comments = []
  2006. const childNodes = iframeElement.contentWindow.document.createTreeWalker(iframeElement.contentWindow.document.body, NodeFilter.SHOW_COMMENT, null)
  2007. while (childNodes.nextNode()) {
  2008. comments.push(childNodes.currentNode)
  2009. }
  2010. // 移除所有注释节点
  2011. comments.forEach(comment => {
  2012. comment?.parentNode?.removeChild(comment)
  2013. })
  2014. iframeBody = iframeElement.contentWindow.document.body as HTMLElement
  2015. iframehtml = iframeElement.contentWindow.document.getElementsByTagName('html')[0] as HTMLElement
  2016. }
  2017. else {
  2018. message.error(lang.ssFailedGetIframeBody)
  2019. throw new Error('未能获取到iframe的body元素,无法截图')
  2020. }
  2021. try {
  2022. const a = iframeBody.getElementsByTagName('img')
  2023. const b = iframeBody.getElementsByTagName('video')
  2024. // const c = iframeBody.getElementsByTagName('canvas')
  2025. iframeBody.style.cssText += 'width:100%;height:100%;position:absolute;top:0;left:0;'
  2026. iframehtml.style.cssText += 'width:100%;height:100%;position:absolute;top:0;left:0;'
  2027. for (let i = 0;i < a.length;i++) {
  2028. a[i].crossOrigin = 'anonymous'
  2029. }
  2030. for (let i = 0;i < b.length;i++) {
  2031. b[i].crossOrigin = 'anonymous'
  2032. }
  2033. // 1. 创建全局禁用动画的 style 标签
  2034. const style = document.createElement('style')
  2035. style.id = 'html2canvas-freeze'
  2036. style.textContent = `
  2037. *, *::before, *::after {
  2038. animation: none !important;
  2039. transition: none !important;
  2040. opacity: 1 !important;
  2041. }
  2042. `
  2043. iframeElement.contentWindow.document.head.appendChild(style)
  2044. // 2. 强制重排,确保禁用生效
  2045. iframeElement.contentWindow.document.body.offsetHeight
  2046. // 3. 如果词云图使用 ECharts 且存在,等它渲染稳定
  2047. if (typeof iframeElement.contentWindow.myChart !== 'undefined' && iframeElement.contentWindow.myChart && !iframeElement.contentWindow.myChart.isDisposed()) {
  2048. // 延迟 500ms 等待 ECharts 内部的 Canvas 动画结束
  2049. await new Promise(resolve => setTimeout(resolve, 500))
  2050. }
  2051. try {
  2052. // 直接对iframe内部的body进行截图
  2053. const html2canvas = await import('html2canvas')
  2054. const canvas = await html2canvas.default(iframeBody, {
  2055. // useCORS: true,
  2056. // allowTaint: true,
  2057. // scale: 1,
  2058. // backgroundColor: '#ffffff',
  2059. // logging: false,
  2060. // foreignObjectRendering: true,
  2061. // removeContainer: true
  2062. scale: 2, // 提高清晰度
  2063. allowTaint: false, // 是否允许跨域污染画布
  2064. useCORS: true, // 尝试跨域加载图片
  2065. logging: true,
  2066. })
  2067. imageData = canvas.toDataURL('image/png', 0.95)
  2068. }
  2069. finally {
  2070. const freezeStyle = iframeElement.contentWindow.document.getElementById('html2canvas-freeze')
  2071. if (freezeStyle) freezeStyle.remove()
  2072. }
  2073. console.log('成功截图iframe内部内容')
  2074. }
  2075. catch (html2canvasError) {
  2076. console.log('html2canvas失败,尝试html-to-image:', html2canvasError)
  2077. message.error(lang.ssHtml2canvasFailed + html2canvasError)
  2078. try {
  2079. // 回退到html-to-image
  2080. const { toPng } = await import('html-to-image')
  2081. imageData = await toPng(iframeBody, {
  2082. quality: 0.95,
  2083. backgroundColor: '#ffffff',
  2084. filter: (node) => {
  2085. if (node.tagName === 'SCRIPT' || node.tagName === 'STYLE') {
  2086. return false
  2087. }
  2088. return true
  2089. }
  2090. })
  2091. console.log('使用html-to-image截图成功')
  2092. }
  2093. catch (htmlToImageError) {
  2094. console.log('html-to-image也失败了,使用canvas绘制方案:', htmlToImageError)
  2095. message.error(lang.ssHtmlToImageFailed + htmlToImageError)
  2096. message.error(lang.ssShotFail)
  2097. return
  2098. /*
  2099. // 最后的备用方案:使用canvas绘制
  2100. const canvas = document.createElement('canvas')
  2101. const ctx = canvas.getContext('2d')
  2102. if (ctx) {
  2103. canvas.width = iframeElement.offsetWidth || 800
  2104. canvas.height = iframeElement.offsetHeight || 600
  2105. // 绘制背景
  2106. const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height)
  2107. gradient.addColorStop(0, '#f8f9fa')
  2108. gradient.addColorStop(1, '#e9ecef')
  2109. ctx.fillStyle = gradient
  2110. ctx.fillRect(0, 0, canvas.width, canvas.height)
  2111. // 绘制边框
  2112. ctx.strokeStyle = '#dee2e6'
  2113. ctx.lineWidth = 3
  2114. ctx.strokeRect(2, 2, canvas.width - 4, canvas.height - 4)
  2115. // 绘制内边框
  2116. ctx.strokeStyle = '#ffffff'
  2117. ctx.lineWidth = 1
  2118. ctx.strokeRect(5, 5, canvas.width - 10, canvas.height - 10)
  2119. // 绘制iframe图标
  2120. ctx.fillStyle = '#6c757d'
  2121. ctx.font = 'bold 48px Arial'
  2122. ctx.textAlign = 'center'
  2123. ctx.fillText('', canvas.width / 2, canvas.height / 2 - 40)
  2124. // 绘制标题
  2125. ctx.font = 'bold 20px Arial'
  2126. ctx.fillStyle = '#495057'
  2127. ctx.fillText('iframe内容', canvas.width / 2, canvas.height / 2 + 20)
  2128. // 绘制URL
  2129. const src = iframeElement.srcf
  2130. if (src) {
  2131. ctx.font = '14px Arial'
  2132. ctx.fillStyle = '#6c757d'
  2133. const url = src.length > 80 ? src.substring(0, 80) + '...' : src
  2134. ctx.fillText(url, canvas.width / 2, canvas.height / 2 + 50)
  2135. }
  2136. // 绘制提示信息
  2137. ctx.font = '12px Arial'
  2138. ctx.fillStyle = '#adb5bd'
  2139. ctx.fillText('(截图失败)', canvas.width / 2, canvas.height / 2 + 80)
  2140. // 绘制装饰性元素
  2141. ctx.strokeStyle = '#dee2e6'
  2142. ctx.lineWidth = 1
  2143. ctx.setLineDash([5, 5])
  2144. ctx.strokeRect(20, 20, canvas.width - 40, canvas.height - 40)
  2145. ctx.setLineDash([])
  2146. imageData = canvas.toDataURL('image/png', 0.95)
  2147. console.log('使用canvas绘制方案截图成功')
  2148. }
  2149. else {
  2150. throw new Error('无法创建canvas上下文')
  2151. }*/
  2152. }
  2153. }
  2154. const _a = iframeBody.getElementsByTagName('img')
  2155. const _b = iframeBody.getElementsByTagName('video')
  2156. for (let i = 0; i < _a.length; i++) {
  2157. _a[i].removeAttribute('crossorigin')
  2158. }
  2159. for (let i = 0; i < _b.length; i++) {
  2160. _b[i].removeAttribute('crossorigin')
  2161. }
  2162. // 将base64字符串转换为File对象
  2163. const base64ToFile = (base64String: string, filename: string): File => {
  2164. const arr = base64String.split(',')
  2165. const mime = arr[0].match(/:(.*?);/)?.[1] || 'image/png'
  2166. const bstr = atob(arr[1])
  2167. let n = bstr.length
  2168. const u8arr = new Uint8Array(n)
  2169. while (n--) {
  2170. u8arr[n] = bstr.charCodeAt(n)
  2171. }
  2172. return new File([u8arr], filename, { type: mime })
  2173. }
  2174. const imageFile = base64ToFile(imageData, `screenshot_${Date.now()}.png`)
  2175. const imageUrl = await uploadFile(imageFile)
  2176. homeworkContent = imageUrl // 保存截图URL作为作业内容
  2177. // 提交截图
  2178. await submitWork(slideIndex.value, '73', imageUrl, '1') // 73表示截图工具,21表示图片类型
  2179. console.log('messageInstructionRef', messageInstructionRef.value)
  2180. messageInstructionRef.value.success(lang.ssShotSucc)
  2181. hasSubmitWork = true
  2182. // 发送作业提交成功的socket消息
  2183. sendMessage({
  2184. type: 'homework_submitted',
  2185. courseid: props.courseid,
  2186. slideIndex: slideIndex.value,
  2187. userid: props.userid
  2188. })
  2189. }
  2190. catch (error) {
  2191. message.error(lang.ssScreenshotSubmitFailed + error)
  2192. console.error('截图提交失败:', error)
  2193. isSubmitting.value = false
  2194. message.error(lang.ssShotFail)
  2195. }
  2196. }
  2197. else {
  2198. // message.info('尝试截图当前页面并提交')
  2199. const screenSlides = document.querySelectorAll('.viewer-canvas .screen-slide')
  2200. let iframeElement: HTMLIFrameElement | null = null
  2201. // 获取iframe元素
  2202. if (
  2203. screenSlides &&
  2204. screenSlides[slideIndex.value] &&
  2205. screenSlides[slideIndex.value].querySelector('iframe')
  2206. ) {
  2207. iframeElement = screenSlides[slideIndex.value].querySelector('iframe') as HTMLIFrameElement
  2208. }
  2209. else {
  2210. message.error(lang.ssFailedGetIframe)
  2211. throw new Error('未能获取到iframe元素,无法截图')
  2212. }
  2213. // 获取iframe内部的body元素(同源)
  2214. if (
  2215. iframeElement.contentWindow &&
  2216. iframeElement.contentWindow.document &&
  2217. iframeElement.contentWindow.document.body
  2218. ) {
  2219. iframeElement.contentWindow.document.body.style.cssText += 'width:100%;height:100%;position:absolute;top:0;left:0;'
  2220. iframeElement.contentWindow.document.getElementsByTagName('html')[0].style.cssText += 'width:100%;height:100%;position:absolute;top:0;left:0;'
  2221. try {
  2222. isSubmitting.value = true
  2223. const _ajs = iframeElement.contentWindow.document.createElement('script')
  2224. _ajs.type = 'text/javascript'
  2225. _ajs.innerHTML =
  2226. 'var _js = document.createElement("script");\n' +
  2227. '_js.type="text/javascript";\n' +
  2228. '_js.src="https://beta.cloud.cocorobo.cn/js/Common/html2canvas-pro.min.js";\n' +
  2229. '_js.onload = function(){\n' +
  2230. ' var a = document.getElementsByTagName("img")\n' +
  2231. ' for(var i = 0;i<a.length;i++){a[i].crossOrigin="anonymous"}\n' +
  2232. ' html2canvas(document.body, {scale: 2,allowTaint: false,useCORS: true,logging: true,}).then(canvas => {\n' +
  2233. ' var base64Url = canvas.toDataURL("image/png");\n' +
  2234. 'var base64 = "<img src=" + base64Url + " />"\n' +
  2235. 'var file = dataURLtoFile_shishi(base64Url, "截图")\n' +
  2236. 'beforeUpload_shishi(file,' +
  2237. "'" +
  2238. props.userid +
  2239. "'" +
  2240. ', ' +
  2241. "'" +
  2242. props.courseid +
  2243. "'" +
  2244. ', ' +
  2245. "'" +
  2246. slideIndex.value +
  2247. "'" +
  2248. ', ' +
  2249. "'0'" +
  2250. ', ' +
  2251. "'73'" +
  2252. ', ' +
  2253. "'1'" +
  2254. ')\n' +
  2255. ' });\n' +
  2256. '}\n' +
  2257. 'document.head.appendChild(_js);\n'
  2258. iframeElement.contentWindow.document.head.appendChild(_ajs)
  2259. return
  2260. }
  2261. catch (error) {
  2262. message.error(lang.ssFailedGetIframeBodyElement)
  2263. throw new Error('获取iframe内部body元素失败,无法截图')
  2264. }
  2265. }
  2266. }
  2267. }
  2268. if (!hasSubmitWork) {
  2269. message.info(lang.ssHwNoFunc)
  2270. }
  2271. else {
  2272. const element = elementList.value.find((i:any) => i.type === 'frame')
  2273. api.addPPTOp2({
  2274. id: props.courseid,
  2275. userid: props.userid || '',
  2276. type: '3',
  2277. index: (element as any).id, // 获取当前ppt页面iframe的id
  2278. data: String(Math.max(0, Math.round((Date.now() - slideEnterTime.value) / 1000))), // 进入作业页面到提交的耗时(秒)
  2279. }).then(res => {
  2280. console.log('res', res)
  2281. })
  2282. }
  2283. isSubmitting.value = false
  2284. }
  2285. catch (error) {
  2286. console.error('作业提交过程中出错:', error)
  2287. message.error('作业提交过程中出错:' + error)
  2288. message.error(lang.ssHwSubmitFail)
  2289. isSubmitting.value = false
  2290. addOp3(1, new Date().getTime(), { courseid: props.courseid, homeworkContent }, 'error')
  2291. }
  2292. finally {
  2293. // isSubmitting.value = false
  2294. getWork(true)
  2295. if (hasSubmitWork) {
  2296. addOp3(1, new Date().getTime(), { courseid: props.courseid, homeworkContent }, 'success')
  2297. }
  2298. else {
  2299. addOp3(1, new Date().getTime(), { courseid: props.courseid, homeworkContent: '未找到可用的作业提交功能' }, 'error')
  2300. }
  2301. }
  2302. }
  2303. const successSubmit = () => {
  2304. messageInstructionRef.value.success(lang.ssHwSubmitSucc)
  2305. sendMessage({
  2306. type: 'homework_submitted',
  2307. courseid: props.courseid,
  2308. slideIndex: slideIndex.value,
  2309. userid: props.userid
  2310. })
  2311. isSubmitting.value = false
  2312. getWork(true)
  2313. }
  2314. const successLike = () => {
  2315. messageInstructionRef.value.success(lang.ssLikeSucc)
  2316. sendMessage({
  2317. type: 'like_updated',
  2318. courseid: props.courseid,
  2319. slideIndex: slideIndex.value,
  2320. userid: props.userid
  2321. })
  2322. getWork(true)
  2323. }
  2324. // 刷新iframe功能
  2325. const handleRefreshPage = () => {
  2326. console.log('刷新iframe按钮被点击')
  2327. try {
  2328. const element = elementList.value.find((i:any) => i.type === 'frame')
  2329. console.log(element)
  2330. if (
  2331. element &&
  2332. typeof element === 'object' &&
  2333. ('toolType' in element) &&
  2334. (element as any).toolType !== undefined &&
  2335. toolTypeArray.value.includes((element as any).toolType)
  2336. ) {
  2337. getWork()
  2338. }
  2339. // 获取当前幻灯片中的所有iframe元素
  2340. const iframes = document.querySelectorAll('.viewer-canvas .screen-slide')[slideIndex.value].querySelectorAll('iframe')
  2341. console.log('找到iframe元素数量:', iframes.length)
  2342. if (iframes.length === 0) {
  2343. message.warning(lang.ssNoIframe)
  2344. return
  2345. }
  2346. let refreshedCount = 0
  2347. // 遍历所有iframe并刷新
  2348. for (let i = 0; i < iframes.length; i++) {
  2349. const iframe = iframes[i] as HTMLIFrameElement
  2350. // 优化刷新方式,避免闪烁和兼容 srcdoc 场景
  2351. if (iframe.src) {
  2352. // 仅当有src属性时刷新
  2353. const originalSrc = iframe.src
  2354. // 通过重新赋值src实现刷新,避免先清空再赋值导致的闪烁
  2355. iframe.src = ''
  2356. setTimeout(() => {
  2357. iframe.src = originalSrc
  2358. console.log(`刷新iframe ${i + 1}:`, originalSrc)
  2359. }, 50)
  2360. refreshedCount++
  2361. }
  2362. else if (iframe.srcdoc) {
  2363. // srcdoc场景下,重新赋值srcdoc内容
  2364. const originalSrcdoc = iframe.srcdoc
  2365. iframe.srcdoc = ''
  2366. setTimeout(() => {
  2367. iframe.srcdoc = originalSrcdoc
  2368. console.log(`iframe ${i + 1} (srcdoc) 刷新完成`)
  2369. }, 50)
  2370. refreshedCount++
  2371. }
  2372. }
  2373. if (refreshedCount > 0) {
  2374. message.success(lang.ssRefreshDone)
  2375. // 如果当前页面有iframe,重新获取作业数据
  2376. if (currentSlideHasIframe.value && props.type == '1') {
  2377. setTimeout(() => {
  2378. getWork()
  2379. }, 500) // 延迟500ms等待iframe加载完成
  2380. }
  2381. isSubmitting.value = false
  2382. }
  2383. else {
  2384. message.info(lang.ssNoIframeRef)
  2385. }
  2386. }
  2387. catch (error) {
  2388. console.error('刷新iframe时出错:', error)
  2389. message.error(lang.ssRefreshFail)
  2390. }
  2391. }
  2392. // 获取作业提交按钮的右侧位置
  2393. const getHomeworkButtonRight = () => {
  2394. if (isFullscreen.value) {
  2395. return 70 // 全屏时按钮在右侧30px
  2396. }
  2397. if (props.type === '1') {
  2398. // 展开回答结果:按钮更靠左;收起时:按钮更靠右侧
  2399. return workPanelCollapsed.value ? 100 : 430
  2400. }
  2401. return 30 // type=2时按钮在右侧30px
  2402. }
  2403. // 获取刷新按钮的右侧位置
  2404. const getRefreshButtonRight = () => {
  2405. if (isFullscreen.value) {
  2406. return 160 // 全屏时按钮在右侧150px
  2407. }
  2408. if (props.type === '1') {
  2409. // 展开回答结果:按钮更靠左;收起时:按钮更靠右侧
  2410. return workPanelCollapsed.value ? 190 : 560
  2411. }
  2412. return 160 // type=2时按钮在右侧150px
  2413. }
  2414. // 键盘快捷键
  2415. const handleKeydown = (e: KeyboardEvent) => {
  2416. // 如果事件发生在输入框中,不处理快捷键
  2417. const target = e.target as HTMLElement
  2418. if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
  2419. return
  2420. }
  2421. console.log('键盘事件:', e.key)
  2422. switch (e.key) {
  2423. case 'ArrowLeft':
  2424. e.preventDefault()
  2425. if (!isFollowModeActive.value || props.type == '1') {
  2426. previousSlide()
  2427. }
  2428. break
  2429. case 'PageUp':
  2430. case 'ArrowUp':
  2431. e.preventDefault()
  2432. if (!isFollowModeActive.value || props.type == '1') {
  2433. previousSlide()
  2434. }
  2435. break
  2436. case 'ArrowRight':
  2437. e.preventDefault()
  2438. if (!isFollowModeActive.value || props.type == '1') {
  2439. nextSlide()
  2440. }
  2441. break
  2442. case 'PageDown':
  2443. case 'ArrowDown':
  2444. case ' ':
  2445. e.preventDefault()
  2446. if (!isFollowModeActive.value || props.type == '1') {
  2447. nextSlide()
  2448. }
  2449. break
  2450. case 'F11':
  2451. e.preventDefault()
  2452. enterFullscreen()
  2453. break
  2454. case 'Escape':
  2455. if (document.fullscreenElement) {
  2456. document.exitFullscreen()
  2457. }
  2458. break
  2459. default:
  2460. break
  2461. }
  2462. }
  2463. // 事件处理函数
  2464. const handleSlidesDataUpdated = () => {
  2465. console.log('收到 slidesDataUpdated 事件')
  2466. // 强制重新渲染:先隐藏组件
  2467. showSlideList.value = false
  2468. nextTick(() => {
  2469. calculateScale()
  2470. // 延迟500ms后重新显示组件,确保重新渲染完成
  2471. setTimeout(() => {
  2472. showSlideList.value = true
  2473. console.log('组件重新渲染完成')
  2474. // 重新处理iframe链接
  2475. processIframeLinks()
  2476. }, 500)
  2477. console.log('slidesDataUpdated 事件处理完成')
  2478. })
  2479. }
  2480. const handleViewportSizeUpdated = (event: any) => {
  2481. console.log('收到 viewportSizeUpdated 事件:', event.detail)
  2482. // 重新计算缩放比例
  2483. nextTick(() => {
  2484. calculateScale()
  2485. console.log('viewportSizeUpdated 事件处理完成')
  2486. })
  2487. }
  2488. const pptJsonFileid = ref<string>('')
  2489. // 上传文件
  2490. const uploadFile2 = async (file: File, pptid: string): Promise<void> => {
  2491. try {
  2492. const uuid = generateUUID()
  2493. const formData = new FormData()
  2494. const timestamp = Date.now()
  2495. const finalExtension = file.name.split('.').pop()?.toLowerCase() || ''
  2496. const baseName = file.name.slice(0, -(finalExtension.length + 1))
  2497. formData.append(
  2498. 'file',
  2499. new File([file], `${baseName}${timestamp}.${finalExtension}`)
  2500. )
  2501. formData.append('collection_ids', JSON.stringify([]))
  2502. formData.append('id', uuid)
  2503. formData.append('metadata', JSON.stringify({ title: file.name }))
  2504. formData.append('ingestion_mode', 'fast')
  2505. formData.append('run_with_orchestration', 'true')
  2506. // 同步知识库
  2507. await axios.post(
  2508. 'https://r2rserver.cocorobo.cn/v3/documents',
  2509. formData,
  2510. {
  2511. headers: {
  2512. 'Content-Type': 'multipart/form-data',
  2513. },
  2514. }
  2515. )
  2516. const ptype = '1' // 根据实际业务定义类型
  2517. const fileid = uuid // 如果需要唯一fileid可以和pptid保持一致或按需更改
  2518. await axios.post(`${API_URL}addPPTFile`, [{
  2519. pptid: pptid,
  2520. ptype: ptype,
  2521. fileid: fileid,
  2522. classid: '',
  2523. task: '',
  2524. tool: ''
  2525. }])
  2526. }
  2527. catch (err) {
  2528. console.error(err)
  2529. throw err
  2530. }
  2531. }
  2532. const checkPPTFile = async (jsonObj: any) => {
  2533. const res = await api.getPPTFile(props.courseid as string, props.cid as string)
  2534. console.log(res)
  2535. const data1 = res[0]
  2536. const data2 = res[1]
  2537. const data3 = res[2]
  2538. console.log(data1, data2, data3)
  2539. if (res[0].length) {
  2540. pptJsonFileid.value = data1[0].fileid
  2541. }
  2542. else {
  2543. const pptJsonFile = new File([jsonObj], courseDetail.value.title + '.txt', { type: 'text/plain' })
  2544. uploadFile2(pptJsonFile, props.courseid as string)
  2545. }
  2546. }
  2547. const getCourseDetail = async () => {
  2548. isLoading.value = true
  2549. try {
  2550. const res = await api.getCourseDetail(props.courseid as string)
  2551. const opRes1 = await api.selectPPTOp({
  2552. id: props.courseid + '-' + props.cid,
  2553. type: '1',
  2554. index: 0
  2555. })
  2556. opRes.value = opRes1[0]
  2557. console.log('操作记录:', opRes1[0])
  2558. console.log('操作记录:', opRes.value)
  2559. console.log(res, opRes.value)
  2560. const courseData = res[0][0]
  2561. courseDetail.value = courseData
  2562. selectWorksStudent()
  2563. checkIsCreator()
  2564. const pptJSONUrl = JSON.parse(courseData.chapters).pptData ? JSON.parse(courseData.chapters).pptData : ''
  2565. aiAssistant.value = JSON.parse(courseData.chapters).aiAssistant ? JSON.parse(courseData.chapters).aiAssistant : false
  2566. console.log(pptJSONUrl)
  2567. if (pptJSONUrl) {
  2568. const pptdata = await getFile(pptJSONUrl)
  2569. // pptdata.data 是 ArrayBuffer,需要先转成字符串再解析为 JSON
  2570. let jsonStr = ''
  2571. if (pptdata && pptdata.data) {
  2572. // 先将 ArrayBuffer 转为字符串
  2573. const uint8Array = new Uint8Array(pptdata.data)
  2574. jsonStr = new TextDecoder('utf-8').decode(uint8Array)
  2575. try {
  2576. const jsonObj = JSON.parse(jsonStr)
  2577. // 生成每页幻灯片的内容描述
  2578. const pptContent = []
  2579. if (jsonObj.slides) {
  2580. jsonObj.slides.forEach((slide: any, index: number) => {
  2581. let slideContent = ''
  2582. if (slide.elements) {
  2583. // 提取文本内容(包括普通文本和形状文本)
  2584. const allTextElements = slide.elements.filter((element: any) =>
  2585. element.type === 'text' || (element.type === 'shape' && element.text?.content)
  2586. )
  2587. if (allTextElements.length > 0) {
  2588. slideContent = allTextElements
  2589. .map((element: any) => {
  2590. const content = element.type === 'text' ? element.content : element.text.content
  2591. return content.replace(/<[^>]*>/g, '')
  2592. })
  2593. .join(' ')
  2594. }
  2595. }
  2596. pptContent.push(`第${index + 1}页: ${slideContent || '内容为空'}`)
  2597. })
  2598. }
  2599. const contentDescription = pptContent.join('\n')
  2600. checkPPTFile(contentDescription)
  2601. importJSON(jsonObj)
  2602. if (isCreator.value) {
  2603. console.log('jsonObj', jsonObj)
  2604. for (let i = 0; i < jsonObj.slides.length; i++) {
  2605. const notTool = [74, 75, 76, 82]
  2606. const elements = jsonObj.slides[i].elements.some((element: any) => {
  2607. return element.type === 'frame' && !notTool.includes(element.toolType)
  2608. })
  2609. let toolType = 0
  2610. if (jsonObj.slides[i].elements.length && jsonObj.slides[i].elements[0].toolType) {
  2611. toolType = jsonObj.slides[i].elements[0].toolType
  2612. }
  2613. const json = {
  2614. isTool: elements,
  2615. can: false,
  2616. like: false,
  2617. anonymous: false,
  2618. answer: false,
  2619. }
  2620. if (toolType === 78) {
  2621. json.anonymous = true
  2622. }
  2623. isResultArray.value[i] = json
  2624. }
  2625. setIsResultArray()
  2626. // 广播消息
  2627. sendMessage({
  2628. type: 'isResultArray',
  2629. isResultArray: JSON.stringify(isResultArray.value),
  2630. courseid: props.courseid
  2631. })
  2632. console.log(isResultArray.value)
  2633. }
  2634. }
  2635. catch (e) {
  2636. console.error('解析pptdata.data失败:', e)
  2637. }
  2638. }
  2639. }
  2640. getWorkId()
  2641. autoSwitchToAvailablePanel()
  2642. }
  2643. catch (error) {
  2644. console.error('获取课程详情失败:', error)
  2645. message.error(lang.ssFetchCourseFail)
  2646. isLoading.value = false
  2647. }
  2648. finally {
  2649. isLoading.value = false
  2650. // if (props.type == '2') {
  2651. // console.log('判断是否是学生进入全屏')
  2652. // function panFull() {
  2653. // console.log('判断是否是学生进入全屏111')
  2654. // if (!document.fullscreenElement) {
  2655. // setTimeout(() => {
  2656. // if (!document.fullscreenElement) {
  2657. // if (document.documentElement.requestFullscreen) {
  2658. // document.documentElement.requestFullscreen()
  2659. // }
  2660. // else if (document.documentElement.mozRequestFullScreen) { // Firefox
  2661. // document.documentElement.mozRequestFullScreen()
  2662. // }
  2663. // else if (document.documentElement.webkitRequestFullscreen) { // Chrome, Safari and Opera
  2664. // document.documentElement.webkitRequestFullscreen()
  2665. // }
  2666. // else if (document.documentElement.msRequestFullscreen) { // IE/Edge
  2667. // document.documentElement.msRequestFullscreen()
  2668. // }
  2669. // panFull()
  2670. // }
  2671. // }, 50)
  2672. // }
  2673. // }
  2674. // nextTick(() => {
  2675. // setTimeout(() => {
  2676. // // enterFullscreen();
  2677. // panFull()
  2678. // }, 50)
  2679. // })
  2680. // }
  2681. }
  2682. }
  2683. const getWorkLoading = ref<any>(false)
  2684. const getWork = async (isUpdate = false) => {
  2685. try {
  2686. if (getWorkLoading.value) {
  2687. return
  2688. }
  2689. if (!isUpdate) {
  2690. workLoading.value = true
  2691. }
  2692. getWorkLoading.value = true
  2693. console.log('getWork 开始执行,参数:', {
  2694. courseid: props.courseid,
  2695. slideIndex: slideIndex.value,
  2696. type: props.type,
  2697. isUpdate
  2698. })
  2699. if (!props.courseid) {
  2700. console.warn('getWork: courseid 未提供,跳过执行')
  2701. if (!isUpdate) workLoading.value = false
  2702. return
  2703. }
  2704. const res = await api.selectSWorks(props.courseid, '0', slideIndex.value.toString())
  2705. console.log('getWork 执行成功,结果:', res)
  2706. const frame = elementList.value.find(element => element.type === ElementTypes.FRAME)
  2707. console.log('frame:', frame)
  2708. const toolType = frame?.toolType ?? ''
  2709. const likeArray = res[1]
  2710. console.log('likeArray', likeArray)
  2711. const newWorkArray = props.cid
  2712. ? res[0].filter((work: any) => {
  2713. // 修复:使用 === 严格相等比较,避免类型转换导致的意外结果
  2714. // 只有当 ttype == '1' 或 (ttype == '2' 且 classid 包含 props.cid) 时才保留
  2715. // 同时满足 atool === toolType 或 toolType 为空
  2716. // return (work.ttype == '1' || (work.ttype == '2' && work.classid.includes(props.cid))) && (work.atool == toolType.value || !toolType.value)
  2717. // work.ttype == '1'
  2718. const ttypeMatch = work.ttype == '1' || (work.ttype == '2' && work.classid && work.classid.includes(props.cid))
  2719. const toolMatch = toolType ? work.atool == toolType : true
  2720. return ttypeMatch && toolMatch
  2721. }).map((work: any) => {
  2722. // 计算点赞数量:likeArray中wid等于当前work.id的记录数
  2723. const likesCount = likeArray.filter((like: any) => like.workId === work.id).length
  2724. // 判断当前用户是否点赞:likeArray中wid等于当前work.id且likesId等于当前用户id
  2725. const isLikes = likeArray.some((like: any) => like.workId === work.id && like.likesId === props.userid)
  2726. return {
  2727. ...work,
  2728. likesCount,
  2729. isLikes
  2730. }
  2731. })
  2732. : res[0].map((work: any) => {
  2733. // 计算点赞数量:likeArray中wid等于当前work.id的记录数
  2734. const likesCount = likeArray.filter((like: any) => like.workId === work.id).length
  2735. // 判断当前用户是否点赞:likeArray中wid等于当前work.id且likesId等于当前用户id
  2736. const isLikes = likeArray.some((like: any) => like.workId === work.id && like.likesId === props.userid)
  2737. return {
  2738. ...work,
  2739. likesCount,
  2740. isLikes
  2741. }
  2742. })
  2743. // 如果是更新模式,只有当数据真正变化时才更新
  2744. if (isUpdate) {
  2745. const hasChanged = checkWorkArrayChanged(workArray.value, newWorkArray)
  2746. if (hasChanged) {
  2747. console.log('检测到作业数据变化,更新显示')
  2748. workArray.value = newWorkArray
  2749. }
  2750. else {
  2751. console.log('作业数据无变化,跳过更新')
  2752. }
  2753. }
  2754. else {
  2755. workArray.value = newWorkArray
  2756. }
  2757. console.log('getWork 执行成功,结果:', workArray.value)
  2758. getWorkLoading.value = false
  2759. }
  2760. catch (error) {
  2761. console.error('getWork 执行失败:', error)
  2762. if (!isUpdate) {
  2763. message.error(lang.ssWorkInfoFail)
  2764. }
  2765. getWorkLoading.value = false
  2766. }
  2767. finally {
  2768. if (!isUpdate) {
  2769. workLoading.value = false
  2770. }
  2771. getWorkLoading.value = false
  2772. }
  2773. }
  2774. const selectWorksStudent = async () => {
  2775. studentLoading.value = true
  2776. try {
  2777. const res = await api.selectWorksStudent(props.oid as string, courseDetail.value.juri as string)
  2778. console.log('selectWorksStudent', res)
  2779. const students = res[0]
  2780. console.log('students', students)
  2781. if (props.cid) {
  2782. studentArray.value = students.filter((student: any) => student.classid.includes(props.cid))
  2783. }
  2784. else {
  2785. studentArray.value = students
  2786. }
  2787. }
  2788. catch (error) {
  2789. console.error('获取学生信息失败:', error)
  2790. message.error(lang.ssStuInfoFail)
  2791. }
  2792. finally {
  2793. studentLoading.value = false
  2794. }
  2795. }
  2796. // 检查作业数组是否发生变化
  2797. const checkWorkArrayChanged = (oldArray: WorkItem[], newArray: WorkItem[]): boolean => {
  2798. if (oldArray.length !== newArray.length) return true
  2799. // 检查每个作业的 id 和 name 是否一致
  2800. for (let i = 0; i < oldArray.length; i++) {
  2801. const oldWork = oldArray[i]
  2802. const newWork = newArray[i]
  2803. if (oldWork.id !== newWork.id || oldWork.name !== newWork.name || oldWork.content !== newWork.content || oldWork.isLikes !== newWork.isLikes || oldWork.likesCount !== newWork.likesCount) {
  2804. return true
  2805. }
  2806. }
  2807. return false
  2808. }
  2809. // 查询课程跟随状态
  2810. const selectCourseSLook = async (type = 2) => {
  2811. const res = await api.selectCourseSLook(props.courseid as string)
  2812. console.log('selectCourseSLook', res)
  2813. if (res[0][0].follow == 2) {
  2814. if (props.type == '2') {
  2815. goToSlide(Number(res[0][0].followC))
  2816. }
  2817. isFollowModeActive.value = true
  2818. if (props.userid == courseDetail.value.userid && props.type == '1') {
  2819. api.updateCourseFollowC(slideIndex.value, props.courseid as string)
  2820. sendMessage({slideIndex: slideIndex.value, courseid: props.courseid, type: 'slideIndex'})
  2821. console.log('设置当前幻灯片为跟随目标:', slideIndex.value)
  2822. }
  2823. if (props.type == '2' && slidePanelCollapsed.value) {
  2824. slidePanelCollapsed.value = false
  2825. }
  2826. }
  2827. else {
  2828. isFollowModeActive.value = false
  2829. if (type === 1 && props.userid == courseDetail.value.userid && props.type == '1') {
  2830. toggleFollowMode()
  2831. }
  2832. }
  2833. if (props.type == '2') {
  2834. message.success(isFollowModeActive.value ? lang.ssFollowOnTip : lang.ssFreeOnTip)
  2835. }
  2836. checkParentMode()
  2837. }
  2838. // 切换跟随模式
  2839. const toggleFollowMode = async () => {
  2840. try {
  2841. const newFollowState = !isFollowModeActive.value
  2842. const sopen = newFollowState ? 2 : 1
  2843. // 调用API更新跟随状态
  2844. const res = await api.updateCourseFollow(sopen, props.courseid as string)
  2845. console.log('更新跟随模式状态:', res)
  2846. sendMessage({sopen: newFollowState, courseid: props.courseid, type: 'sopen'})
  2847. if (res) {
  2848. isFollowModeActive.value = newFollowState
  2849. message.success(newFollowState ? lang.ssFollowOnTip : lang.ssFreeOnTip)
  2850. // 如果开启跟随模式,设置当前幻灯片为跟随目标
  2851. if (newFollowState) {
  2852. await api.updateCourseFollowC(slideIndex.value, props.courseid as string)
  2853. console.log('设置当前幻灯片为跟随目标:', slideIndex.value)
  2854. }
  2855. if (timerlVisible.value) {
  2856. timerlVisible.value = false
  2857. }
  2858. handleWritingBoardClose()
  2859. }
  2860. else {
  2861. message.error(lang.ssOpFailRetry)
  2862. }
  2863. checkParentMode()
  2864. }
  2865. catch (error) {
  2866. console.error('切换跟随模式失败:', error)
  2867. message.error(lang.ssOpFailRetry)
  2868. }
  2869. }
  2870. const checkParentMode = () => {
  2871. // @ts-ignore
  2872. if (window.parent && typeof window.parent.onFreeBrowseChange === 'function') {
  2873. // @ts-ignore
  2874. window.parent.onFreeBrowseChange(!isFollowModeActive.value)
  2875. }
  2876. }
  2877. const setIsResultArray = () => {
  2878. // @ts-ignore
  2879. if (window.parent && typeof window.parent.setIsResultArray === 'function') {
  2880. // @ts-ignore
  2881. window.parent.setIsResultArray(isResultArray.value)
  2882. }
  2883. }
  2884. const setIsResultArray2 = (value: boolean, key: string) => {
  2885. isResultArray.value[slideIndex.value][key] = value
  2886. console.log(isResultArray.value)
  2887. // @ts-ignore
  2888. if (window.parent && typeof window.parent.setIsResultArray === 'function') {
  2889. // @ts-ignore
  2890. window.parent.setIsResultArray(isResultArray.value)
  2891. }
  2892. sendMessage({
  2893. type: 'isResultArray',
  2894. isResultArray: JSON.stringify(isResultArray.value),
  2895. courseid: props.courseid
  2896. })
  2897. }
  2898. const setCan = (Array: any[]) => {
  2899. isResultArray.value = Array
  2900. sendMessage({
  2901. type: 'isResultArray',
  2902. isResultArray: JSON.stringify(isResultArray.value),
  2903. courseid: props.courseid
  2904. })
  2905. }
  2906. const forceLogout = () => {
  2907. cleanupWebSocketConnection()
  2908. sendMessage({ type: 'logout' })
  2909. }
  2910. const forceLogout2 = () => {
  2911. logout()
  2912. }
  2913. const logout = () => {
  2914. // @ts-ignore
  2915. if (window.parent && typeof window.parent.topU.U.MD.U.LO.logoutSystemQ === 'function') {
  2916. // @ts-ignore
  2917. window.parent.topU.U.MD.U.LO.logoutSystemQ()
  2918. }
  2919. }
  2920. // 检查是否为创建人
  2921. const checkIsCreator = () => {
  2922. // 这里可以根据实际业务逻辑判断是否为创建人
  2923. // 比如通过props中的userid与课程创建者ID比较
  2924. if (courseDetail.value && props.userid) {
  2925. isCreator.value = courseDetail.value.userid === props.userid
  2926. }
  2927. }
  2928. /**
  2929. * 初始化消息监听
  2930. */
  2931. const messageInit = () => {
  2932. const doc = docSocket.value
  2933. if (!doc) return
  2934. // ★ 关键:判断当前绑定的共享类型是否属于这个 doc
  2935. // y-websocket 内部重连复用同一个 doc → observe 仍有效,直接返回(避免重复 observe)
  2936. // 只有 doc 被销毁重建(full reconnect)时才全部重新绑定
  2937. const boundDoc = (yMessage.value as any)?.doc
  2938. console.log('🔗 messageInit: doc.guid=', doc.guid, 'boundDoc=', boundDoc?.guid, 'same=', boundDoc === doc)
  2939. if (boundDoc === doc) {
  2940. // 同 doc 重连:补发上线消息即可
  2941. if (props.type === '2') {
  2942. sendMessage({ type: 'class_begin', courseid: props.courseid })
  2943. }
  2944. return
  2945. }
  2946. console.log('🔗 检测到新 Y.Doc,重新绑定所有共享数据监听')
  2947. // ★ 先把旧 doc 上的引用全部置空,杜绝守卫误判指向旧 doc
  2948. yMessage.value = null
  2949. yTimerState.value = null
  2950. yLaserState.value = null
  2951. yWritingBoardState.value = null
  2952. yTimerMessages.value = null
  2953. yLaserMessages.value = null
  2954. yWritingBoardMessages.value = null
  2955. yIsResultArrayMessages.value = null
  2956. // 普通消息(Map,只保留最后一条)
  2957. // 必须使用 messageV3:服务器上 messageV2 累积了旧的 delete('latest') 标记,
  2958. // 导致 get('latest') 永远返回 undefined(Yjs 的 typeMapGet 在最后一个 item 被 deleted 时返回 undefined)
  2959. yMessage.value = doc.getMap('messageV3')
  2960. yMessage.value.observe((e: any) => {
  2961. // 同时兼容 keysChanged 和 changes.keys(不同 Yjs 版本/事件结构)
  2962. const changed = e.keysChanged || e.changes?.keys
  2963. // ★ 打印每个 key 的 action(add/update/delete)和 oldValue
  2964. const keysMap = e.keys || e.changes?.keys
  2965. if (keysMap && keysMap.get) {
  2966. for (const [key, info] of keysMap.entries()) {
  2967. console.log(`🔗 observe key="${key}" action=${info.action} oldValue=`, info.oldValue)
  2968. }
  2969. }
  2970. console.log('🔗 yMessage observe 触发, changed keys:', changed ? Array.from(changed) : 'null')
  2971. if (!changed || !changed.has('latest')) return
  2972. const message = yMessage.value!.get('latest')
  2973. console.log('🔗 yMessage latest:', message, '当前 mId:', mId.value)
  2974. if (message && message.mId !== mId.value) {
  2975. getMessages(message)
  2976. }
  2977. })
  2978. // ★ 追平:连接建立后立即读取当前 latest,
  2979. // 防止老师在学生 observe 注册之前发的消息丢失(尤其是当前所在幻灯片)
  2980. const latest = yMessage.value.get('latest')
  2981. if (latest && latest.mId !== mId.value) {
  2982. console.log('🔗 追平当前 latest 消息:', latest)
  2983. getMessages(latest)
  2984. }
  2985. // 计时器消息数组
  2986. yTimerMessages.value = doc.getArray('timerMessages')
  2987. // 初始化时检查一次是否需要清理
  2988. if (yTimerMessages.value.length > 500 && isCreator.value) {
  2989. smartCleanupMessages(yTimerMessages.value, 500, 'timer', doc)
  2990. }
  2991. yTimerMessages.value.observe((e: any) => {
  2992. if (yTimerMessages.value.length > 500 && isCreator.value) {
  2993. setTimeout(() => {
  2994. if (yTimerMessages.value && yTimerMessages.value.length > 500) {
  2995. smartCleanupMessages(yTimerMessages.value, 500, 'timer', doc)
  2996. }
  2997. }, 0)
  2998. }
  2999. e.changes.added.forEach((i: any) => {
  3000. const message = i.content.getContent()[0]
  3001. if (message.mId !== mId.value) {
  3002. getMessages(message)
  3003. }
  3004. })
  3005. })
  3006. // 激光笔消息数组
  3007. yLaserMessages.value = doc.getArray('laserMessages')
  3008. if (yLaserMessages.value.length > 500 && isCreator.value) {
  3009. smartCleanupMessages(yLaserMessages.value, 500, 'laser', doc)
  3010. }
  3011. yLaserMessages.value.observe((e: any) => {
  3012. if (yLaserMessages.value.length > 500 && isCreator.value) {
  3013. setTimeout(() => {
  3014. if (yLaserMessages.value && yLaserMessages.value.length > 500) {
  3015. smartCleanupMessages(yLaserMessages.value, 500, 'laser', doc)
  3016. }
  3017. }, 0)
  3018. }
  3019. e.changes.added.forEach((i: any) => {
  3020. const message = i.content.getContent()[0]
  3021. // 只处理开关消息,位置消息直接通过 Map 同步
  3022. if (message.type === 'laser_toggle' && message.mId !== mId.value) {
  3023. getMessages(message)
  3024. }
  3025. })
  3026. })
  3027. // 画图消息数组
  3028. yWritingBoardMessages.value = doc.getArray('writingBoardMessages')
  3029. if (yWritingBoardMessages.value.length > 500 && isCreator.value) {
  3030. smartCleanupMessages(yWritingBoardMessages.value, 500, 'writingBoard', doc)
  3031. }
  3032. yWritingBoardMessages.value.observe((e: any) => {
  3033. if (yWritingBoardMessages.value.length > 500 && isCreator.value) {
  3034. setTimeout(() => {
  3035. if (yWritingBoardMessages.value && yWritingBoardMessages.value.length > 500) {
  3036. smartCleanupMessages(yWritingBoardMessages.value, 500, 'writingBoard', doc)
  3037. }
  3038. }, 0)
  3039. }
  3040. e.changes.added.forEach((i: any) => {
  3041. const message = i.content.getContent()[0]
  3042. if (message.mId !== mId.value) {
  3043. getMessages(message)
  3044. }
  3045. })
  3046. })
  3047. // isResultArray 消息数组
  3048. yIsResultArrayMessages.value = doc.getArray('isResultArrayMessages')
  3049. if (yIsResultArrayMessages.value.length > 1 && isCreator.value) {
  3050. smartCleanupMessages(yIsResultArrayMessages.value, 1, 'isResultArray', doc)
  3051. }
  3052. yIsResultArrayMessages.value.observe((e: any) => {
  3053. if (yIsResultArrayMessages.value.length > 1 && isCreator.value) {
  3054. setTimeout(() => {
  3055. if (yIsResultArrayMessages.value && yIsResultArrayMessages.value.length > 1) {
  3056. smartCleanupMessages(yIsResultArrayMessages.value, 1, 'isResultArray', doc)
  3057. }
  3058. }, 0)
  3059. }
  3060. e.changes.added.forEach((i: any) => {
  3061. const message = i.content.getContent()[0]
  3062. if (message.mId !== mId.value) {
  3063. getMessages(message)
  3064. }
  3065. })
  3066. })
  3067. // 如果是首次进入且是创建者,清空所有同步状态
  3068. if (isFirstEnter.value && isCreator.value && docSocket.value) {
  3069. console.log('🧹 首次进入且为创建者,清空所有同步状态')
  3070. docSocket.value.transact(() => {
  3071. // ★ 不删除 latest!delete 会传播给学生导致 get('latest') 返回 undefined
  3072. // 旧 latest 会被 sendMessage 的 set('latest', message) 自然覆盖
  3073. // 清空计时器消息数组
  3074. const timerMessagesArray = docSocket.value?.getArray?.('timerMessages')
  3075. if (timerMessagesArray) {
  3076. timerMessagesArray.delete(0, timerMessagesArray.length)
  3077. }
  3078. // 清空激光笔消息数组
  3079. const laserMessagesArray = docSocket.value?.getArray?.('laserMessages')
  3080. if (laserMessagesArray) {
  3081. laserMessagesArray.delete(0, laserMessagesArray.length)
  3082. }
  3083. // 清空画图消息数组
  3084. const writingBoardMessagesArray = docSocket.value?.getArray?.('writingBoardMessages')
  3085. if (writingBoardMessagesArray) {
  3086. writingBoardMessagesArray.delete(0, writingBoardMessagesArray.length)
  3087. }
  3088. // 清空计时器状态
  3089. const timerStateMap = docSocket.value?.getMap?.('timerState')
  3090. if (timerStateMap) {
  3091. timerStateMap.clear()
  3092. }
  3093. // 清空激光笔状态
  3094. const laserStateMap = docSocket.value?.getMap?.('laserState')
  3095. if (laserStateMap) {
  3096. laserStateMap.clear()
  3097. }
  3098. // 清空画图状态
  3099. const writingBoardStateMap = docSocket.value?.getMap?.('writingBoardState')
  3100. if (writingBoardStateMap) {
  3101. writingBoardStateMap.clear()
  3102. }
  3103. })
  3104. // 标记已不再是首次进入
  3105. isFirstEnter.value = false
  3106. }
  3107. // 计时器状态 Map 并监听
  3108. yTimerState.value = doc.getMap('timerState')
  3109. // 初始状态同步(后加入用户会立即拿到当前 map 值)
  3110. applyTimerStateSnapshot(yTimerState.value.toJSON())
  3111. yTimerState.value.observe(() => {
  3112. applyTimerStateSnapshot(yTimerState.value!.toJSON())
  3113. })
  3114. // 激光笔状态 Map 并监听
  3115. yLaserState.value = doc.getMap('laserState')
  3116. applyLaserStateSnapshot(yLaserState.value.toJSON())
  3117. yLaserState.value.observe(() => {
  3118. applyLaserStateSnapshot(yLaserState.value!.toJSON())
  3119. })
  3120. // 画图状态 Map 并监听
  3121. yWritingBoardState.value = doc.getMap('writingBoardState')
  3122. const wsnap = yWritingBoardState.value.toJSON()
  3123. console.log('📝 初始化画图状态Map,快照:', wsnap, '当前幻灯片:', currentSlide.value?.id)
  3124. nextTick(() => {
  3125. if (currentSlide.value && currentSlide.value.id) {
  3126. applyWritingBoardStateSnapshot(wsnap)
  3127. }
  3128. else {
  3129. let timeoutId: any = null
  3130. const unwatch = watch(() => currentSlide.value?.id, (slideId) => {
  3131. if (slideId) {
  3132. applyWritingBoardStateSnapshot(wsnap)
  3133. unwatch()
  3134. if (timeoutId) clearTimeout(timeoutId)
  3135. }
  3136. }, { immediate: true })
  3137. timeoutId = setTimeout(() => {
  3138. if (currentSlide.value && currentSlide.value.id) {
  3139. applyWritingBoardStateSnapshot(wsnap)
  3140. }
  3141. unwatch()
  3142. }, 3000)
  3143. }
  3144. })
  3145. yWritingBoardState.value.observe(() => {
  3146. const s = yWritingBoardState.value!.toJSON()
  3147. if (currentSlide.value && currentSlide.value.id) {
  3148. applyWritingBoardStateSnapshot(s)
  3149. }
  3150. })
  3151. // 新 doc 绑定完成,补发上线消息
  3152. if (props.type === '2') {
  3153. sendMessage({ type: 'class_begin', courseid: props.courseid })
  3154. }
  3155. }
  3156. /**
  3157. * 判断是否为特殊类型的消息(计时器、激光笔、画图)
  3158. * 注意:laser_move 不通过消息数组,直接通过 Map 同步,所以不包含在这里
  3159. */
  3160. const isSpecialMessageType = (type: string): boolean => {
  3161. const timerTypes = ['timer_start', 'timer_pause', 'timer_reset', 'timer_stop', 'timer_finish', 'timer_update']
  3162. const laserTypes = ['laser_toggle'] // laser_move 直接通过 Map,不通过消息数组
  3163. const writingBoardTypes = ['writing_board_update', 'writing_board_close', 'writing_board_blackboard']
  3164. const isResultArrayTypes = ['isResultArray']
  3165. return timerTypes.includes(type) || laserTypes.includes(type) || writingBoardTypes.includes(type) || isResultArrayTypes.includes(type)
  3166. }
  3167. /**
  3168. * 判断是否为开关类型的消息(需要保留的状态消息)
  3169. */
  3170. const isToggleMessageType = (type: string, category: 'timer' | 'laser' | 'writingBoard' | 'isResultArray'): boolean => {
  3171. if (category === 'laser') {
  3172. return type === 'laser_toggle'
  3173. }
  3174. if (category === 'writingBoard') {
  3175. return type === 'writing_board_close'
  3176. }
  3177. if (category === 'timer') {
  3178. return ['timer_start', 'timer_stop', 'timer_reset'].includes(type)
  3179. }
  3180. if (category === 'isResultArray') {
  3181. return ['isResultArray'].includes(type)
  3182. }
  3183. return false
  3184. }
  3185. /**
  3186. * 智能清理消息数组,保留最新的开关消息
  3187. */
  3188. const smartCleanupMessages = (messageArray: any, maxLength: number, category: 'timer' | 'laser' | 'writingBoard' | 'isResultArray', docSocket: Y.Doc) => {
  3189. if (!messageArray || messageArray.length <= maxLength) return
  3190. const allMessages = messageArray.toArray()
  3191. // 找到所有开关类型的消息及其索引
  3192. const toggleMessages: Array<{ index: number; message: any }> = []
  3193. for (let i = 0; i < allMessages.length; i++) {
  3194. const msg = allMessages[i]
  3195. if (msg && typeof msg === 'object' && msg.type && isToggleMessageType(msg.type, category)) {
  3196. toggleMessages.push({ index: i, message: msg })
  3197. }
  3198. }
  3199. // 如果有关键的开关消息,需要确保它们被保留
  3200. if (toggleMessages.length > 0) {
  3201. // 找到最新的开关消息索引
  3202. const latestToggleIndex = toggleMessages[toggleMessages.length - 1].index
  3203. // 如果最新的开关消息在最后500条内,直接保留最后500条
  3204. if (latestToggleIndex >= allMessages.length - maxLength) {
  3205. const excessCount = allMessages.length - maxLength
  3206. docSocket.transact(() => {
  3207. messageArray.delete(0, excessCount)
  3208. })
  3209. console.log(`🧹 清理了 ${excessCount} 条${category}消息,保留最新${maxLength}条(包含最新开关状态)`)
  3210. }
  3211. else {
  3212. // 如果最新的开关消息不在最后500条内,需要特殊处理
  3213. // 保留从最新开关消息开始到末尾的所有消息
  3214. const keepFromIndex = Math.max(0, latestToggleIndex)
  3215. const excessCount = keepFromIndex
  3216. docSocket.transact(() => {
  3217. messageArray.delete(0, excessCount)
  3218. })
  3219. console.log(`🧹 清理了 ${excessCount} 条${category}消息,保留从最新开关状态开始的所有消息`)
  3220. }
  3221. }
  3222. else {
  3223. // 没有开关消息,直接保留最后500条
  3224. const excessCount = allMessages.length - maxLength
  3225. docSocket.transact(() => {
  3226. messageArray.delete(0, excessCount)
  3227. })
  3228. console.log(`🧹 清理了 ${excessCount} 条${category}消息,保留最新${maxLength}条`)
  3229. }
  3230. }
  3231. /**
  3232. * 获取消息类型对应的数组
  3233. * 注意:laser_move 不通过消息数组,直接通过 Map 同步
  3234. */
  3235. const getMessageArrayByType = (type: string): any | null => {
  3236. const timerTypes = ['timer_start', 'timer_pause', 'timer_reset', 'timer_stop', 'timer_finish', 'timer_update']
  3237. const laserTypes = ['laser_toggle'] // laser_move 直接通过 Map,不通过消息数组
  3238. const writingBoardTypes = ['writing_board_update', 'writing_board_close', 'writing_board_blackboard']
  3239. const isResultArrayTypes = ['isResultArray']
  3240. if (timerTypes.includes(type)) {
  3241. return yTimerMessages.value
  3242. }
  3243. if (laserTypes.includes(type)) {
  3244. return yLaserMessages.value
  3245. }
  3246. if (writingBoardTypes.includes(type)) {
  3247. return yWritingBoardMessages.value
  3248. }
  3249. if (isResultArrayTypes.includes(type)) {
  3250. return yIsResultArrayMessages.value
  3251. }
  3252. return null
  3253. }
  3254. /**
  3255. * 发送消息
  3256. */
  3257. const sendMessage = (obj: any) => {
  3258. if (!docSocket.value) return
  3259. const message = obj
  3260. message.timestamp = new Date().toISOString()
  3261. message.mId = mId.value
  3262. const messageType = message.type
  3263. // laser_move 消息直接通过 Map 同步,不通过消息数组(减少延迟)
  3264. if (messageType === 'laser_move') {
  3265. if (yLaserState.value) {
  3266. docSocket.value.transact(() => {
  3267. yLaserState.value.set('x', message.x)
  3268. yLaserState.value.set('y', message.y)
  3269. })
  3270. }
  3271. return // 不存储到消息数组
  3272. }
  3273. const isSpecial = isSpecialMessageType(messageType)
  3274. docSocket.value.transact(() => {
  3275. if (isSpecial) {
  3276. // 特殊类型消息:存储到对应的独立数组
  3277. const targetArray = getMessageArrayByType(messageType)
  3278. if (targetArray) {
  3279. // 限制特殊消息数组最多 200 条,超出时删除最早的
  3280. const MAX_SPECIAL = 200
  3281. if (targetArray.length >= MAX_SPECIAL) {
  3282. targetArray.delete(0, targetArray.length - MAX_SPECIAL + 1)
  3283. }
  3284. targetArray.push([message])
  3285. }
  3286. }
  3287. else {
  3288. // 普通消息:只保留最后一条
  3289. if (yMessage.value) {
  3290. // 用 Map.set 代替 Array.delete+push,只产生 1 条 update
  3291. yMessage.value.set('latest', message)
  3292. }
  3293. else {
  3294. console.warn('⚠️ sendMessage: yMessage.value 为 null,消息未写入! type:', messageType, 'docSocket:', !!docSocket.value)
  3295. }
  3296. }
  3297. })
  3298. }
  3299. const is_cast_screen = ref(false)
  3300. /**
  3301. * 处理收到的消息
  3302. */
  3303. const getMessages = (msgObj: any) => {
  3304. console.log('message', msgObj)
  3305. // 处理幻灯片切换消息
  3306. if (props.type == '2' && msgObj.type === 'slideIndex') {
  3307. goToSlide(msgObj.slideIndex)
  3308. }
  3309. // 处理跟随模式状态变化
  3310. if (props.type == '2' && msgObj.type === 'sopen') {
  3311. selectCourseSLook()
  3312. }
  3313. if (props.type == '2' && msgObj.type === 'logout') {
  3314. logout()
  3315. }
  3316. // 处理作业提交消息 - 当有人提交作业时,重新获取作业数据
  3317. if (props.type == '1' && msgObj.type === 'homework_submitted' && msgObj.courseid === props.courseid) {
  3318. console.log('收到作业提交消息,重新获取作业数据')
  3319. // 延迟一点时间,确保后端数据已更新
  3320. setTimeout(() => {
  3321. if (currentSlideHasIframe.value) {
  3322. getWork(true) // 传入true表示是更新模式
  3323. }
  3324. }, 1000)
  3325. }
  3326. // 处理点赞消息 - 当有人点赞时,重新获取点赞数据
  3327. if (msgObj.type === 'like_updated' && msgObj.courseid === props.courseid) {
  3328. console.log('收到点赞消息,重新获取点赞数据')
  3329. // 延迟一点时间,确保后端数据已更新
  3330. setTimeout(() => {
  3331. if (currentSlideHasIframe.value) {
  3332. getWork(true) // 传入true表示是更新模式
  3333. }
  3334. }, 1000)
  3335. }
  3336. // 处理英语口语状态更新 - 学生开始/完成对话时,刷新班级答题面板
  3337. if (props.type == '1' && msgObj.type === 'speaking_session_updated' && msgObj.courseid === props.courseid) {
  3338. console.log('收到英语口语状态更新,触发面板刷新')
  3339. speakingPanelRef.value?.scheduleRefetch?.()
  3340. articleReadingPanelRef.value?.scheduleRefetch?.()
  3341. }
  3342. // 计时器消息 - 学生与老师端实时显示
  3343. if (msgObj.type === 'timer_start' && msgObj.courseid === props.courseid) {
  3344. applyTimerStart(JSON.parse(msgObj.payload))
  3345. }
  3346. if (msgObj.type === 'timer_pause' && msgObj.courseid === props.courseid) {
  3347. applyTimerPause()
  3348. }
  3349. if (msgObj.type === 'timer_reset' && msgObj.courseid === props.courseid) {
  3350. applyTimerReset()
  3351. }
  3352. if (msgObj.type === 'timer_stop' && msgObj.courseid === props.courseid) {
  3353. applyTimerStop()
  3354. }
  3355. if (msgObj.type === 'timer_finish' && msgObj.courseid === props.courseid) {
  3356. applyTimerFinish()
  3357. }
  3358. if (msgObj.type === 'timer_update' && msgObj.courseid === props.courseid) {
  3359. applyTimerUpdate(msgObj.payload)
  3360. }
  3361. // 激光笔:老师广播的开关
  3362. if (props.type == '2' && msgObj.type === 'laser_toggle' && msgObj.courseid === props.courseid) {
  3363. laserPenOverlay.value.visible = !!msgObj.enabled
  3364. // 开关时立即刷新一次位置
  3365. if (laserPenOverlay.value.visible) {
  3366. refreshLaserOverlayRect()
  3367. if (laserMoveRafId) cancelAnimationFrame(laserMoveRafId)
  3368. laserMoveRafId = requestAnimationFrame(updateLaserDotPosition)
  3369. }
  3370. }
  3371. // 注意:laser_move 现在直接通过 Map 同步,不通过消息数组,所以这里不需要处理
  3372. // 画图:老师广播的画图数据
  3373. if (props.type == '2' && msgObj.type === 'writing_board_update' && msgObj.courseid === props.courseid) {
  3374. console.log('📝 学生端收到画图更新消息:', { slideId: msgObj.slideId, currentSlideId: currentSlide.value?.id, hasData: !!msgObj.dataURL })
  3375. if (currentSlide.value && msgObj.slideId === currentSlide.value.id) {
  3376. writingBoardSyncDataURL.value = msgObj.dataURL || null
  3377. // 如果消息中包含小黑板状态,也更新
  3378. if (msgObj.blackboard !== undefined) {
  3379. writingBoardSyncBlackboard.value = msgObj.blackboard
  3380. }
  3381. console.log('📝 画图数据匹配当前幻灯片,显示画图工具')
  3382. // 同步到共享 Map
  3383. if (yWritingBoardState.value) {
  3384. docSocket.value?.transact(() => {
  3385. yWritingBoardState.value.set('slideId', msgObj.slideId)
  3386. yWritingBoardState.value.set('dataURL', msgObj.dataURL)
  3387. if (msgObj.blackboard !== undefined) {
  3388. yWritingBoardState.value.set('blackboard', msgObj.blackboard)
  3389. }
  3390. })
  3391. }
  3392. }
  3393. else {
  3394. // 不是当前幻灯片,但也要更新到 Map(供后续切换时使用)
  3395. if (yWritingBoardState.value) {
  3396. docSocket.value?.transact(() => {
  3397. yWritingBoardState.value.set('slideId', msgObj.slideId)
  3398. yWritingBoardState.value.set('dataURL', msgObj.dataURL)
  3399. if (msgObj.blackboard !== undefined) {
  3400. yWritingBoardState.value.set('blackboard', msgObj.blackboard)
  3401. }
  3402. })
  3403. }
  3404. console.log('📝 画图数据不匹配当前幻灯片,已保存到Map供后续使用')
  3405. }
  3406. }
  3407. // 画图:老师关闭画图工具
  3408. if (props.type == '2' && msgObj.type === 'writing_board_close' && msgObj.courseid === props.courseid) {
  3409. writingBoardSyncDataURL.value = null
  3410. writingBoardSyncBlackboard.value = null
  3411. // 清空共享 Map
  3412. if (yWritingBoardState.value) {
  3413. docSocket.value?.transact(() => {
  3414. yWritingBoardState.value.clear()
  3415. })
  3416. }
  3417. }
  3418. // 画图:老师切换小黑板状态
  3419. if (props.type == '2' && msgObj.type === 'writing_board_blackboard' && msgObj.courseid === props.courseid) {
  3420. writingBoardSyncBlackboard.value = msgObj.blackboard || false
  3421. // 同步到共享 Map
  3422. if (yWritingBoardState.value) {
  3423. docSocket.value?.transact(() => {
  3424. yWritingBoardState.value.set('blackboard', msgObj.blackboard)
  3425. })
  3426. }
  3427. }
  3428. // 获取是否展开结果数组
  3429. if (props.type == '2' && msgObj.type === 'isResultArray' && msgObj.courseid === props.courseid) {
  3430. try {
  3431. console.error('是否展开结果数组:', msgObj.isResultArray || '[]')
  3432. const newResultArray = JSON.parse(msgObj.isResultArray || '[]')
  3433. // 值未变化时跳过下游逻辑
  3434. if (JSON.stringify(newResultArray) === JSON.stringify(isResultArray.value)) return
  3435. isResultArray.value = newResultArray
  3436. }
  3437. catch (error) {
  3438. console.error('解析是否展开结果数组失败:', error)
  3439. isResultArray.value = []
  3440. }
  3441. if (isResultArray.value.length > 0 ) {
  3442. const result = isResultArray.value[slideIndex.value]
  3443. console.log('是否展开结果数组:', result)
  3444. if (!result.can && choiceQuestionDetailDialogOpenList.value.includes(slideIndex.value)) {
  3445. openChoiceQuestionDetail2(slideIndex.value)
  3446. }
  3447. else {
  3448. getWork(true)
  3449. }
  3450. }
  3451. }
  3452. // 投屏
  3453. if (props.type == '2' && msgObj.type === 'cast_screen' && msgObj.courseid === props.courseid) {
  3454. if (is_cast_screen.value) return // 已在投屏中,忽略重复消息
  3455. openChoiceQuestionDetail3(slideIndex.value)
  3456. setTimeout(() => {
  3457. is_cast_screen.value = true
  3458. choiceQuestionDetailDialogRef.value?.castScreen?.(msgObj.workerData)
  3459. }, 500)
  3460. }
  3461. // 退出投屏
  3462. if (props.type == '2' && msgObj.type === 'exit_cast_screen' && msgObj.courseid === props.courseid) {
  3463. if (!is_cast_screen.value) return // 未在投屏中,忽略重复退出消息
  3464. openChoiceQuestionDetail3(slideIndex.value)
  3465. setTimeout(() => {
  3466. is_cast_screen.value = false
  3467. choiceQuestionDetailDialogRef.value?.exitCastScreen?.()
  3468. }, 500)
  3469. }
  3470. if (opRes.value && opRes.value.length === 0 && msgObj.type === 'class_begin' && isCreator.value && props.cid) {
  3471. console.log('操作记录:', opRes.value)
  3472. api.addPPTOp({
  3473. id: props.courseid + '-' + props.cid,
  3474. type: '1',
  3475. index: 0,
  3476. data: new Date().toISOString()
  3477. }).then(() => {
  3478. const opRes1 = api.selectPPTOp({
  3479. id: props.courseid + '-' + props.cid,
  3480. type: '1',
  3481. index: 0
  3482. }).then(res => {
  3483. console.log('操作记录:', res)
  3484. opRes.value = res[0]
  3485. console.log('操作记录:', opRes.value)
  3486. })
  3487. })
  3488. }
  3489. // ★ 老师收到学生 class_begin 后,回发当前幻灯片,确保学生有 latest 可跟随
  3490. if (msgObj.type === 'class_begin' && isCreator.value) {
  3491. const curIndex = slidesStore.slideIndex ?? 0
  3492. sendMessage({ slideIndex: curIndex, courseid: props.courseid, type: 'slideIndex' })
  3493. console.log('🔗 老师响应 class_begin,回发 slideIndex:', curIndex)
  3494. }
  3495. }
  3496. // 打开作业查看详细
  3497. const openChoiceQuestionDetail = (index:number) => {
  3498. if (!choiceQuestionDetailDialogOpenList.value.includes(index)) {
  3499. choiceQuestionDetailDialogOpenList.value.push(index)
  3500. }
  3501. else {
  3502. choiceQuestionDetailDialogOpenList.value = choiceQuestionDetailDialogOpenList.value.filter(i => i !== index)
  3503. }
  3504. }
  3505. // 打开作业查看详细
  3506. const openChoiceQuestionDetail2 = (index:number) => {
  3507. if (!choiceQuestionDetailDialogOpenList.value.includes(index)) {
  3508. // choiceQuestionDetailDialogOpenList.value.push(index)
  3509. }
  3510. else {
  3511. choiceQuestionDetailDialogOpenList.value = choiceQuestionDetailDialogOpenList.value.filter(i => i !== index)
  3512. }
  3513. }
  3514. // 打开作业查看详细
  3515. const openChoiceQuestionDetail3 = (index:number) => {
  3516. if (!choiceQuestionDetailDialogOpenList.value.includes(index)) {
  3517. choiceQuestionDetailDialogOpenList.value.push(index)
  3518. }
  3519. }
  3520. const handlePageUnload = () => {
  3521. if (isCreator.value && timerIndicator.value.visible && props.type === '1') {
  3522. sendMessage({ type: 'timer_stop', courseid: props.courseid })
  3523. }
  3524. // 创建老师刷新/关闭页面时,清空所有同步状态
  3525. if (isCreator.value && props.type === '1') {
  3526. clearAllSyncStates()
  3527. }
  3528. // 清理画图延迟发送定时器
  3529. if (drawingDelayTimer.value) {
  3530. clearTimeout(drawingDelayTimer.value)
  3531. drawingDelayTimer.value = null
  3532. }
  3533. }
  3534. // 检测浏览器类型
  3535. const detectBrowser = () => {
  3536. const ua = navigator.userAgent
  3537. // 按优先级顺序检测
  3538. if (ua.includes('Edg/') || ua.includes('Edge/')) {
  3539. return 'Microsoft Edge'
  3540. }
  3541. if (ua.includes('Firefox')) {
  3542. return 'Mozilla Firefox'
  3543. }
  3544. if (ua.includes('Trident') || ua.includes('MSIE')) {
  3545. return 'Internet Explorer'
  3546. }
  3547. if (ua.includes('360EE')) {
  3548. return '360 Browser (极速模式)'
  3549. }
  3550. if (ua.includes('360SE')) {
  3551. return '360 Browser (安全模式)'
  3552. }
  3553. if (ua.includes('SLBrowser')) {
  3554. return 'QQ Browser'
  3555. }
  3556. if (ua.includes('UCBrowser')) {
  3557. return 'UC Browser'
  3558. }
  3559. if (ua.includes('Opera') || ua.includes('OPR/')) {
  3560. return 'Opera'
  3561. }
  3562. if (ua.includes('Chrome') && !ua.includes('Edg/')) {
  3563. return 'Google Chrome'
  3564. }
  3565. if (ua.includes('Safari/') && !ua.includes('Chrome')) {
  3566. return 'Safari'
  3567. }
  3568. return 'Other Browser'
  3569. }
  3570. // 用户数据上报功能
  3571. const addOp3 = async (userTime: any, loadTime: any, object: any, status: any) => {
  3572. if (!props.userid) return
  3573. try {
  3574. if (!userJson.value || !userJson.value.accountNumber) {
  3575. const res = await axios.get('https://pbl.cocorobo.cn/api/pbl/selectUser2', {
  3576. params: { userid: props.userid }
  3577. })
  3578. if (res == 201 || res.length == 0) {
  3579. // message.error('登录已过期,请重新登录')
  3580. return
  3581. }
  3582. userJson.value = res[0][0]
  3583. console.log(userJson.value)
  3584. console.log(res[0][0])
  3585. }
  3586. }
  3587. catch (e) {
  3588. console.log(e)
  3589. if (e === 123) {
  3590. return
  3591. }
  3592. setTimeout(() => {
  3593. addOp3(userTime, loadTime, object, status)
  3594. }, 10000)
  3595. return
  3596. }
  3597. const _time = new Date()
  3598. .toLocaleString('zh-CN', { hour12: false, timeZone: 'Asia/Shanghai' })
  3599. .replace(/\//g, '-')
  3600. const browser = detectBrowser()
  3601. const params = {
  3602. userid: props.userid,
  3603. username: userJson.value.username,
  3604. accountNumber: userJson.value.accountNumber,
  3605. org: userJson.value.orgName,
  3606. school: userJson.value.schoolName,
  3607. role: userJson.value.type == '1' ? '老师' : '学生',
  3608. browser,
  3609. userTime: userTime == '1' ? _time : userTime, // 使用时间 1次的就1 其次传秒
  3610. loadTime, // load的时间没有就''
  3611. object: JSON.stringify(object), // 执行信息传json
  3612. status // 成功返回success。失败返回error的信息
  3613. }
  3614. console.log('params', params)
  3615. axios
  3616. .post('https://pbl.cocorobo.cn/api/mongo/updateUserData2', [params])
  3617. .then(res => {
  3618. if (res.status === 1) {
  3619. console.log('保存成功')
  3620. }
  3621. else {
  3622. console.log('保存失败')
  3623. }
  3624. })
  3625. .catch(e => {
  3626. console.log('保存失败')
  3627. console.log(e)
  3628. })
  3629. }
  3630. onMounted(() => {
  3631. document.addEventListener('keydown', handleKeydown)
  3632. // 处理URL参数
  3633. if (props.courseid || props.type) {
  3634. console.log('收到URL参数:', { courseid: props.courseid, type: props.type })
  3635. // 这里可以根据courseid和type进行相应的处理
  3636. // 比如加载特定的课程数据、设置特定的显示模式等
  3637. if (props.courseid) {
  3638. console.log('课程ID:', props.courseid)
  3639. // TODO: 根据courseid加载对应的课程数据
  3640. }
  3641. if (props.type) {
  3642. console.log('类型:', props.type)
  3643. // TODO: 根据type设置特定的显示模式或功能
  3644. }
  3645. }
  3646. getCourseDetail()
  3647. // 计算初始缩放比例
  3648. nextTick(() => {
  3649. calculateScale()
  3650. // 处理iframe链接
  3651. processIframeLinks()
  3652. // 初始化时检查并自动切换到可用面板
  3653. autoSwitchToAvailablePanel()
  3654. })
  3655. // 监听窗口大小变化
  3656. window.addEventListener('resize', calculateScale)
  3657. // 监听全屏状态变化
  3658. document.addEventListener('fullscreenchange', handleFullscreenChange)
  3659. // 监听幻灯片数据更新事件(来自useImport的readJSON)
  3660. window.addEventListener('slidesDataUpdated', handleSlidesDataUpdated)
  3661. // 监听视口尺寸更新事件
  3662. window.addEventListener('viewportSizeUpdated', handleViewportSizeUpdated)
  3663. // 将导入导出功能暴露到window上,方便调试和外部调用
  3664. ; (window as any).PPTistStudent = {
  3665. importJSON,
  3666. exportJSON,
  3667. slides: slidesStore.slides,
  3668. currentSlide: computed(() => slidesStore.currentSlide),
  3669. slideIndex: computed(() => slidesStore.slideIndex),
  3670. goToSlide,
  3671. previousSlide,
  3672. nextSlide,
  3673. enterFullscreen,
  3674. toggleLaserPen,
  3675. // 添加URL参数到全局对象中
  3676. courseid: props.courseid,
  3677. type: props.type,
  3678. successSubmit,
  3679. toggleFollowMode,
  3680. // 添加重连功能
  3681. manualReconnect,
  3682. connectionStatus: computed(() => connectionStatus.value),
  3683. forceLogout,
  3684. forceLogout2,
  3685. setCan,
  3686. // Yjs 诊断函数:控制台调用 PPTistStudent.diagnoseYjs()
  3687. diagnoseYjs: () => {
  3688. const doc = docSocket.value
  3689. if (!doc) {
  3690. console.log('════════ Yjs 诊断 ════════\ndocSocket.value 为 null')
  3691. return null
  3692. }
  3693. const msgV3Type = doc.share.get('messageV3')
  3694. const oldMsgType = doc.share.get('message')
  3695. const report = {
  3696. '1. doc.guid': doc.guid,
  3697. '2. yMessage.value === doc.share.get("messageV3")': yMessage.value === msgV3Type,
  3698. '3. yMessage.value?.doc?.guid': yMessage.value?.doc?.guid,
  3699. '4. doc.store.clients.size': doc.store.clients.size,
  3700. '5a. share.get("messageV3") 类型': msgV3Type?.constructor?.name,
  3701. '5b. share.get("message") 类型': oldMsgType?.constructor?.name,
  3702. '6. messageV3.size': msgV3Type?.size,
  3703. '7. messageV3?.get("latest")': msgV3Type?.get?.('latest'),
  3704. '8. yMessage.value?.get("latest")': yMessage.value?.get?.('latest'),
  3705. '9. doc 里所有顶层 key': Array.from(doc.share.entries()).map(([k, v]: [string, any]) => k + ':' + v.constructor.name),
  3706. '10. provider synced': providerSocket.value?.synced,
  3707. '11. ws.readyState': providerSocket.value?.ws?.readyState,
  3708. }
  3709. console.log('════════ Yjs 诊断 ════════')
  3710. for (const [k, v] of Object.entries(report)) {
  3711. console.log(k + ':', typeof v === 'object' ? JSON.stringify(v) : v)
  3712. }
  3713. return report
  3714. },
  3715. }
  3716. console.log('PPTist Student View 已加载,可通过 window.PPTistStudent 访问功能')
  3717. console.log('URL参数:', { courseid: props.courseid, type: props.type })
  3718. // 初始化WebSocket连接
  3719. if (api.yweb_socket) {
  3720. createWebSocketConnection()
  3721. }
  3722. // 创建人离开页面时,广播停止计时
  3723. // beforeunload 事件(页面刷新或关闭)
  3724. // window.addEventListener('beforeunload', handlePageUnload)
  3725. // visibilitychange 事件(适用于 iframe 嵌套场景,当外层页面返回时触发)
  3726. const handleVisibilityChange = () => {
  3727. if (document.hidden && isCreator.value) {
  3728. // 页面被隐藏时,清空所有同步状态
  3729. clearAllSyncStates()
  3730. if (timerIndicator.value.visible) {
  3731. sendMessage({ type: 'timer_stop', courseid: props.courseid })
  3732. }
  3733. }
  3734. }
  3735. document.addEventListener('visibilitychange', handleVisibilityChange)
  3736. // pagehide 事件(作为补充,某些浏览器中比 beforeunload 更可靠)
  3737. window.addEventListener('pagehide', () => {
  3738. console.log('pagehide')
  3739. handlePageUnload()
  3740. })
  3741. // 存储清理函数,方便在 onUnmounted 中移除
  3742. ;(window as any).__pptistStudentUnloadHandlers = {
  3743. // beforeunload: handlePageUnload,
  3744. visibilitychange: handleVisibilityChange,
  3745. pagehide: handlePageUnload
  3746. }
  3747. })
  3748. onUnmounted(() => {
  3749. document.removeEventListener('keydown', handleKeydown)
  3750. window.removeEventListener('resize', calculateScale)
  3751. document.removeEventListener('fullscreenchange', handleFullscreenChange)
  3752. // 移除幻灯片数据更新事件监听器
  3753. window.removeEventListener('slidesDataUpdated', handleSlidesDataUpdated)
  3754. // 移除视口尺寸更新事件监听器
  3755. window.removeEventListener('viewportSizeUpdated', handleViewportSizeUpdated)
  3756. // 清理WebSocket连接
  3757. if (reconnectTimer.value) {
  3758. clearTimeout(reconnectTimer.value)
  3759. reconnectTimer.value = null
  3760. }
  3761. // 清理认证 token 更新定时器
  3762. if (authTokenUpdateTimer.value) {
  3763. clearTimeout(authTokenUpdateTimer.value)
  3764. authTokenUpdateTimer.value = null
  3765. }
  3766. // 清理心跳定时器
  3767. if (heartbeatTimer.value) {
  3768. clearInterval(heartbeatTimer.value)
  3769. heartbeatTimer.value = null
  3770. }
  3771. // 清理 socket 连接检查定时器
  3772. if (socketCheckTimer.value) {
  3773. clearInterval(socketCheckTimer.value)
  3774. socketCheckTimer.value = null
  3775. }
  3776. // if (providerSocket.value) {
  3777. // providerSocket.value.destroy()
  3778. // providerSocket.value = null
  3779. // }
  3780. // 清理画图延迟发送定时器
  3781. if (drawingDelayTimer.value) {
  3782. clearTimeout(drawingDelayTimer.value)
  3783. drawingDelayTimer.value = null
  3784. }
  3785. // 清理页面卸载相关的事件监听器
  3786. if ((window as any).__pptistStudentUnloadHandlers) {
  3787. const handlers = (window as any).__pptistStudentUnloadHandlers
  3788. // window.removeEventListener('beforeunload', handlers.beforeunload)
  3789. document.removeEventListener('visibilitychange', handlers.visibilitychange)
  3790. window.removeEventListener('pagehide', handlers.pagehide)
  3791. delete (window as any).__pptistStudentUnloadHandlers
  3792. }
  3793. // 清理window上的引用
  3794. if ((window as any).PPTistStudent) {
  3795. delete (window as any).PPTistStudent
  3796. console.log('PPTist Student View 已卸载,window.PPTistStudent 已清理')
  3797. }
  3798. if (timerInterval.value) {
  3799. clearInterval(timerInterval.value)
  3800. timerInterval.value = null
  3801. }
  3802. handlePageUnload()
  3803. })
  3804. // 获取认证 token
  3805. const getAuthToken = async (): Promise<string> => {
  3806. try {
  3807. // 使用代理路径避免跨域问题
  3808. // 开发环境:通过 vite 代理 /yjs-auth/auth/token -> https://yjsredis.cocorobo.cn/auth/token
  3809. // 生产环境:需要配置服务器代理或使用后端 API
  3810. // 兼容性修复:不直接使用 import.meta.env.DEV
  3811. let isDev = false
  3812. // 判断如果有 window 对象且以 localhost/127.0.0.1 开头,则认为是开发环境
  3813. if (typeof window !== 'undefined') {
  3814. const hostname = window.location.hostname
  3815. if (
  3816. hostname === 'localhost' ||
  3817. hostname === '127.0.0.1' ||
  3818. hostname === '::1' ||
  3819. /^192\.168\.\d+\.\d+$/.test(hostname)
  3820. ) {
  3821. isDev = true
  3822. }
  3823. }
  3824. let authUrl = ''
  3825. // if (isDev) {
  3826. // // 开发环境使用 vite 代理
  3827. // authUrl = '/yjs-auth/auth/token'
  3828. // }
  3829. // else {
  3830. // 生产环境:如果服务器有代理则使用代理,否则直接访问(需要服务器配置 CORS)
  3831. // 或者通过后端 API 获取 token
  3832. let baseUrl = 'https://yjsredis.cocorobo.cn/'
  3833. baseUrl = baseUrl.replace(/\/+$/, '')
  3834. authUrl = `${baseUrl}/auth/token`
  3835. // }
  3836. console.log('🔐 获取认证 token,URL:', authUrl)
  3837. const response = await axios.get(authUrl)
  3838. console.log('🔐 获取认证 token 成功', response)
  3839. return response
  3840. }
  3841. catch (error) {
  3842. console.error('🔐 获取认证 token 失败:', error)
  3843. throw error
  3844. }
  3845. }
  3846. // 定期更新认证 token
  3847. const updateAuthToken = async () => {
  3848. try {
  3849. if (!providerSocket.value) return
  3850. const newToken = await getAuthToken()
  3851. authToken.value = newToken
  3852. // 更新 provider 的 auth 参数
  3853. if (providerSocket.value.params) {
  3854. providerSocket.value.params.yauth = newToken
  3855. }
  3856. console.log('🔐 认证 token 已更新')
  3857. // 30分钟后再次更新
  3858. // if (authTokenUpdateTimer.value) {
  3859. // clearTimeout(authTokenUpdateTimer.value)
  3860. // }
  3861. authTokenUpdateTimer.value = setTimeout(updateAuthToken, 30 * 60 * 1000) as unknown as NodeJS.Timeout
  3862. // authTokenUpdateTimer.value = setTimeout(updateAuthToken, 10 * 1000) as unknown as NodeJS.Timeout
  3863. }
  3864. catch (error) {
  3865. console.error('🔐 更新认证 token 失败:', error)
  3866. // 失败后1秒重试
  3867. if (authTokenUpdateTimer.value) {
  3868. clearTimeout(authTokenUpdateTimer.value)
  3869. }
  3870. authTokenUpdateTimer.value = setTimeout(updateAuthToken, 10 * 1000) as unknown as NodeJS.Timeout
  3871. }
  3872. }
  3873. // 手动重连
  3874. const manualReconnect = () => {
  3875. if (isConnecting.value) return
  3876. reconnectAttempts.value = 0 // 重置重连次数
  3877. createWebSocketConnection()
  3878. }
  3879. // 清理 WebSocket 连接(提取为独立函数)
  3880. const cleanupWebSocketConnection = () => {
  3881. if (providerSocket.value) {
  3882. // 销毁连接
  3883. providerSocket.value.destroy()
  3884. providerSocket.value = null
  3885. }
  3886. if (docSocket.value) {
  3887. // 注意:doc 会被 provider.destroy() 自动销毁,不需要手动 destroy
  3888. // 但如果 provider 已经被销毁,这里置空即可
  3889. docSocket.value.destroy()
  3890. docSocket.value = null
  3891. }
  3892. // ★ 关键:doc 已销毁,必须把绑定在旧 doc 上的共享类型引用全部置空,
  3893. // 否则重连后 messadocSocket.value.guid === yMessazeInit() 的 if (!yXxx.value) 守卫会跳过绑定,
  3894. // 新 doc 收到更新时 observe 回调不会触发(表现为突然收不到消息)
  3895. yMessage.value = null
  3896. yTimerState.value = null
  3897. yLaserState.value = null
  3898. yWritingBoardState.value = null
  3899. yTimerMessages.value = null
  3900. yLaserMessages.value = null
  3901. yWritingBoardMessages.value = null
  3902. yIsResultArrayMessages.value = null
  3903. }
  3904. // 创建WebSocket连接
  3905. const createWebSocketConnection = async (type = 1) => {
  3906. if (!api.yweb_socket || isConnecting.value) return
  3907. isConnecting.value = true
  3908. connectionStatus.value = 'connecting'
  3909. try {
  3910. // 清理之前的连接
  3911. // if (providerSocket.value && type == 1) {
  3912. // providerSocket.value.destroy()
  3913. // providerSocket.value = null
  3914. // }
  3915. cleanupWebSocketConnection()
  3916. // 清理之前的 token 更新定时器
  3917. if (authTokenUpdateTimer.value) {
  3918. clearTimeout(authTokenUpdateTimer.value)
  3919. authTokenUpdateTimer.value = null
  3920. }
  3921. // 获取认证 token
  3922. try {
  3923. authToken.value = await getAuthToken()
  3924. console.log('🔐 认证 token 获取成功,准备连接 WebSocket')
  3925. }
  3926. catch (error) {
  3927. console.error('🔐 获取认证 token 失败,连接可能失败:', error)
  3928. connectionStatus.value = 'disconnected'
  3929. isConnecting.value = false
  3930. handleDisconnection()
  3931. return
  3932. }
  3933. docSocket.value = new Y.Doc()
  3934. docSocket.value.gc = true
  3935. providerSocket.value = new WebsocketProvider(
  3936. api.yweb_socket,
  3937. 'PPT' + props.courseid,
  3938. docSocket.value,
  3939. {
  3940. params: { yauth: authToken.value },
  3941. resyncInterval: 5000, // 每 5 秒用标准协议请求服务器状态(代替畸形心跳)
  3942. maxBackoffTime: 5000, // 重连最长退避 5 秒
  3943. }
  3944. )
  3945. providerSocket.value.awareness.setLocalState(null)
  3946. providerSocket.value.awareness.destroy() // 完全禁用 awareness
  3947. // ★ 三层日志之一:raw websocket 消息(确认数据到达浏览器)
  3948. const _ws = (providerSocket.value as any).ws
  3949. if (_ws && !_ws.__logged) {
  3950. _ws.__logged = true // 防止重复绑定
  3951. // 包一层 onmessage,抓 provider 处理异常
  3952. const _origOnMsg = _ws.onmessage
  3953. if (typeof _origOnMsg === 'function') {
  3954. _ws.onmessage = function(ev: MessageEvent) {
  3955. try {
  3956. _origOnMsg.call(_ws, ev)
  3957. }
  3958. catch (e: any) {
  3959. console.error('❌ provider onmessage 异常:', e?.message || e, e?.stack || '')
  3960. }
  3961. }
  3962. }
  3963. _ws.addEventListener('message', (ev: MessageEvent) => {
  3964. try {
  3965. const data = new Uint8Array(ev.data)
  3966. const msgType = data[0]
  3967. const typeNames: any = { 0: 'sync', 1: 'awareness', 2: 'queryAwareness' }
  3968. let detail = ''
  3969. if (msgType === 0) {
  3970. const sub = data[1]
  3971. detail = ({ 0: 'step1(请求缺失)', 1: 'step2(服务器推送)', 2: 'update' } as any)[sub] || 'unknown'
  3972. }
  3973. console.log(`📥 ws raw: ${typeNames[msgType] || msgType} ${detail} (${data.length} bytes)`)
  3974. // ★ 诊断:sync update 到达时手动解码 + applyUpdate,看是不是重复数据
  3975. if (msgType === 0 && data[1] === 2) {
  3976. const doc = docSocket.value
  3977. if (doc) {
  3978. // 解码 varint 提取 update bytes
  3979. let pos = 2 // 跳过 msgType + subType
  3980. let updateLen = 0
  3981. let shift = 0
  3982. while (pos < data.length) {
  3983. const b = data[pos++]
  3984. updateLen |= (b & 0x7f) << shift
  3985. if (b < 0x80) break
  3986. shift += 7
  3987. }
  3988. const updateBytes = data.slice(pos, pos + updateLen)
  3989. // ★ 用 Y.decodeUpdate 解码 update(不创建 temp doc,不触发 applyUpdate 的 DELETE)
  3990. try {
  3991. const { structs } = Y.decodeUpdate(updateBytes)
  3992. console.log(`📦 解码: updateBytes=${updateBytes.length}, structs=${structs.length}`)
  3993. for (const struct of structs) {
  3994. const arr = struct?.content?.arr
  3995. console.log(`📦 struct: type=${struct?.content?.constructor?.name}, parentSub=${struct?.parentSub}, arr=${arr ? JSON.stringify(arr)?.slice(0, 150) : '无'}`)
  3996. if (arr && Array.isArray(arr)) {
  3997. for (const val of arr) {
  3998. if (val && typeof val === 'object' && val.type && val.mId) {
  3999. console.log(`📦 ✅ 从 update 提取消息: type=${val.type}, mId=${val.mId}, 当前 mId=${mId.value}`)
  4000. if (val.mId !== mId.value) {
  4001. getMessages(val)
  4002. }
  4003. }
  4004. }
  4005. }
  4006. }
  4007. }
  4008. catch (e) {
  4009. console.log('📦 update 解码失败:', e)
  4010. }
  4011. }
  4012. }
  4013. }
  4014. catch (e) {
  4015. console.log('📥 ws raw: parse error', e)
  4016. }
  4017. })
  4018. }
  4019. // ★ 三层日志之二:Y.Doc update 事件 — 列出所有根类型的 size,看更新到底改了哪个
  4020. docSocket.value.on('update', (update: Uint8Array, origin: any) => {
  4021. const originName = origin?.constructor?.name || (origin === providerSocket.value ? 'ws-provider' : typeof origin)
  4022. const share = (docSocket.value as any)?.share
  4023. const sizes: string[] = []
  4024. if (share) {
  4025. for (const [name, type] of share.entries()) {
  4026. const sz = type.size ?? type.length ?? '?'
  4027. const latest = type.get?.('latest')
  4028. sizes.push(`${name}=${sz}${latest ? '(' + latest.type + ')' : ''}`)
  4029. }
  4030. }
  4031. console.log(`📥 Y.Doc update: ${update.length} bytes, origin: ${originName}, types: [${sizes.join(', ')}]`)
  4032. })
  4033. // 清理可能残留的旧心跳定时器
  4034. if (heartbeatTimer.value) {
  4035. clearInterval(heartbeatTimer.value)
  4036. heartbeatTimer.value = null
  4037. }
  4038. // 启动定期更新 token
  4039. // 30分钟后再次更新
  4040. if (authTokenUpdateTimer.value) {
  4041. clearTimeout(authTokenUpdateTimer.value)
  4042. }
  4043. authTokenUpdateTimer.value = setTimeout(updateAuthToken, 30 * 60 * 1000) as unknown as NodeJS.Timeout
  4044. // authTokenUpdateTimer.value = setTimeout(updateAuthToken, 10 * 1000) as unknown as NodeJS.Timeout
  4045. providerSocket.value.on('status', (event: any) => {
  4046. console.log('👉 WebSocket状态:', event.status)
  4047. if (event.status === 'connected') {
  4048. console.log('👉连接成功websocket(teachingMode)')
  4049. connectionStatus.value = 'connected'
  4050. isConnecting.value = false
  4051. reconnectAttempts.value = 0 // 重置重连次数
  4052. // 清理重连定时器
  4053. if (reconnectTimer.value) {
  4054. clearTimeout(reconnectTimer.value)
  4055. reconnectTimer.value = null
  4056. }
  4057. mId.value = Math.random().toString(36).substr(2, 9)
  4058. messageInit()
  4059. console.log('🔗 connected 后: yMessage.value =', yMessage.value ? '已绑定' : 'null', 'doc.guid=', docSocket.value?.guid)
  4060. // 连接成功后,读取当前计时器状态(Map)
  4061. if (docSocket.value) {
  4062. initializeYjsData()
  4063. }
  4064. // if (type == 1) {
  4065. // setTimeout(() => {
  4066. // createWebSocketConnection(2)
  4067. // }, 1000)
  4068. // }
  4069. }
  4070. else if (event.status === 'disconnected') {
  4071. console.log('👉 连接断开,等待自动重连...')
  4072. isConnecting.value = false
  4073. }
  4074. // else if (event.status === 'disconnected') {
  4075. // console.log('👉 WebSocket连接断开')
  4076. // connectionStatus.value = 'disconnected'
  4077. // isConnecting.value = false
  4078. // setTimeout(() => {
  4079. // createWebSocketConnection(2)
  4080. // }, 5000)
  4081. // }
  4082. // else if (event.status === 'closed') {
  4083. // console.log('👉 WebSocket连接断开closed')
  4084. // updateAuthToken().then(() => {
  4085. // providerSocket.value.connect() // 尝试重新连接
  4086. // })
  4087. // }
  4088. })
  4089. // ✅ 只记录日志,不干预状态
  4090. providerSocket.value.on('connection-error', (error: any) => {
  4091. console.error('👉 WebSocket 连接错误(将自动重连):', error)
  4092. })
  4093. providerSocket.value.on('connection-close', (event: any) => {
  4094. console.log('👉 WebSocket 连接关闭(将自动重连):', event)
  4095. })
  4096. // ★ synced 事件:在服务器状态同步完成(sync step 2 已应用到 Y.Doc)后触发
  4097. // 'connected' 在 onopen 时就触发,此时 sync 尚未完成,messageInit 的 catch-up 读不到数据
  4098. // 'synced' 才是做 catch-up 的正确时机——确保服务器上的 latest 已写入本地 Y.Doc
  4099. providerSocket.value.on('sync', (isSynced: boolean) => {
  4100. if (!isSynced) return
  4101. console.log('🔗 Yjs sync 完成,开始 catch-up')
  4102. // ★ 诊断:枚举 doc.share 里所有根类型,给每个都加 observe
  4103. const share = (docSocket.value as any).share
  4104. if (share) {
  4105. console.log('🔗 根类型列表:')
  4106. for (const [name, type] of share.entries()) {
  4107. console.log(` ${name}: ${type.constructor.name}, size: ${type.size ?? type.length ?? '?'}`)
  4108. // 给每个根类型加 observe,看哪个在动
  4109. if (type.observe && !type.__diagObserved) {
  4110. type.__diagObserved = true
  4111. type.observe((e: any) => {
  4112. const changed = e.keysChanged || e.changes?.keys
  4113. console.log(`🔗 [${name}] observe 触发! changed:`, changed ? Array.from(changed) : e)
  4114. })
  4115. }
  4116. }
  4117. }
  4118. // catch-up:读取服务器同步过来的 latest 消息
  4119. if (yMessage.value) {
  4120. const latest = yMessage.value.get('latest')
  4121. console.log('🔗 synced catch-up latest:', latest)
  4122. if (latest && latest.mId !== mId.value) {
  4123. console.log('🔗 synced catch-up: 处理 latest 消息', latest.type)
  4124. getMessages(latest)
  4125. }
  4126. }
  4127. // catch-up:读取计时器、激光笔、画图状态
  4128. if (yTimerState.value) {
  4129. const snapshot = yTimerState.value.toJSON()
  4130. applyTimerStateSnapshot(snapshot)
  4131. }
  4132. if (yLaserState.value) {
  4133. const laserSnap = yLaserState.value.toJSON()
  4134. if (laserSnap.visible !== undefined) {
  4135. laserPenOverlay.value.visible = !!laserSnap.visible
  4136. }
  4137. }
  4138. // 学生端补发上线消息,让老师知道学生已就绪
  4139. if (props.type === '2') {
  4140. console.log('🔗 sync handler: yMessage.value =', yMessage.value ? '已绑定' : 'null', 'doc.guid=', docSocket.value?.guid)
  4141. sendMessage({ type: 'class_begin', courseid: props.courseid })
  4142. // ★ 确认 class_begin 是否真的写入了 messageV3
  4143. const msgV3 = (docSocket.value as any)?.share?.get?.('messageV3')
  4144. console.log('🔗 学生发送 class_begin 后, messageV3.size:', msgV3?.size, 'latest:', msgV3?.get?.('latest')?.type)
  4145. }
  4146. // ★ 老师端:sync 完成后补发当前幻灯片,确保 messageV3 的 latest 有值
  4147. // 解决:服务器上 latest 被 clearAllSyncStates 删除后,新连入学生拿到空 Map 无法跟随
  4148. if (props.type === '1') {
  4149. const curIndex = slidesStore.slideIndex ?? 0
  4150. sendMessage({ slideIndex: curIndex, courseid: props.courseid, type: 'slideIndex' })
  4151. console.log('🔗 老师补发当前幻灯片 slideIndex:', curIndex)
  4152. }
  4153. // 自动运行 Yjs 诊断
  4154. (window as any).PPTistStudent?.diagnoseYjs?.()
  4155. })
  4156. // 监听连接错误
  4157. // providerSocket.value.on('connection-error', (error: any) => {
  4158. // console.error('👉 WebSocket连接错误:', error)
  4159. // connectionStatus.value = 'disconnected'
  4160. // isConnecting.value = false
  4161. // setTimeout(() => {
  4162. // createWebSocketConnection(2)
  4163. // }, 5000)
  4164. // })
  4165. // 监听连接关闭
  4166. // providerSocket.value.on('connection-close', (error: any) => {
  4167. // console.error('👉 WebSocket连接关闭:', error)
  4168. // connectionStatus.value = 'disconnected'
  4169. // isConnecting.value = false
  4170. // setTimeout(() => {
  4171. // updateAuthToken().then(() => {
  4172. // providerSocket.value.connect() // 尝试重新连接
  4173. // })
  4174. // }, 5000)
  4175. // })
  4176. }
  4177. catch (error) {
  4178. console.error('👉 创建WebSocket连接失败:', error)
  4179. connectionStatus.value = 'disconnected'
  4180. isConnecting.value = false
  4181. // setTimeout(() => {
  4182. // createWebSocketConnection(2)
  4183. // }, 5000)
  4184. cleanupWebSocketConnection()
  4185. setTimeout(createWebSocketConnection, 5000)
  4186. }
  4187. // 启动 socket 连接检查定时器
  4188. // startSocketCheckTimer()
  4189. }
  4190. // ✅ 提取业务初始化逻辑
  4191. const initializeYjsData = () => {
  4192. if (!docSocket.value) return
  4193. yTimerState.value = docSocket.value.getMap('timerState')
  4194. const snapshot = yTimerState.value.toJSON()
  4195. applyTimerStateSnapshot(snapshot)
  4196. // 激光笔 map
  4197. yLaserState.value = docSocket.value.getMap('laserState')
  4198. const ls = yLaserState.value.toJSON()
  4199. applyLaserStateSnapshot(ls)
  4200. yLaserState.value.observe(() => {
  4201. const s = yLaserState.value.toJSON()
  4202. applyLaserStateSnapshot(s)
  4203. })
  4204. // 画图 map
  4205. yWritingBoardState.value = docSocket.value.getMap('writingBoardState')
  4206. const ws = yWritingBoardState.value.toJSON()
  4207. console.log('📝 WebSocket连接成功,读取画图状态:', ws, '当前幻灯片:', currentSlide.value?.id)
  4208. // 延迟应用,确保 currentSlide 已初始化
  4209. nextTick(() => {
  4210. // 如果 currentSlide 还没准备好,再等一帧
  4211. if (currentSlide.value && currentSlide.value.id) {
  4212. applyWritingBoardStateSnapshot(ws)
  4213. }
  4214. else {
  4215. // 如果还没准备好,等待 currentSlide 变化(最多等待3秒)
  4216. let timeoutId: any = null
  4217. const unwatch = watch(() => currentSlide.value?.id, (slideId) => {
  4218. if (slideId) {
  4219. applyWritingBoardStateSnapshot(ws)
  4220. unwatch()
  4221. if (timeoutId) clearTimeout(timeoutId)
  4222. }
  4223. }, { immediate: true })
  4224. // 3秒后如果还没准备好,强制应用一次
  4225. timeoutId = setTimeout(() => {
  4226. if (currentSlide.value && currentSlide.value.id) {
  4227. applyWritingBoardStateSnapshot(ws)
  4228. }
  4229. unwatch()
  4230. }, 3000)
  4231. }
  4232. })
  4233. yWritingBoardState.value.observe(() => {
  4234. const s = yWritingBoardState.value.toJSON()
  4235. if (currentSlide.value && currentSlide.value.id) {
  4236. applyWritingBoardStateSnapshot(s)
  4237. }
  4238. })
  4239. }
  4240. // 处理连接断开
  4241. const handleDisconnection = () => {
  4242. if (reconnectAttempts.value < maxReconnectAttempts.value) {
  4243. reconnectAttempts.value++
  4244. console.log(`👉 尝试重连 (${reconnectAttempts.value}/${maxReconnectAttempts.value})`)
  4245. reconnectTimer.value = setTimeout(() => {
  4246. createWebSocketConnection()
  4247. }, reconnectInterval.value) as unknown as NodeJS.Timeout
  4248. }
  4249. else {
  4250. console.error('👉 WebSocket重连次数已达上限,停止重连')
  4251. // 可以在这里显示用户提示
  4252. message.error( lang.ssNetError )
  4253. }
  4254. }
  4255. // 启动 socket 连接检查定时器
  4256. const startSocketCheckTimer = () => {
  4257. // 清理之前的定时器
  4258. if (socketCheckTimer.value) {
  4259. clearInterval(socketCheckTimer.value)
  4260. socketCheckTimer.value = null
  4261. }
  4262. // 每10秒检查一次 socket 连接状态
  4263. socketCheckTimer.value = setInterval(() => {
  4264. if (providerSocket.value) {
  4265. // 直接检查 providerSocket 的连接状态
  4266. // WebsocketProvider 有一个 connected 属性来表示连接状态
  4267. const isConnected = (providerSocket.value as any).ws.readyState
  4268. console.log('🔍 定时器检查 socket 连接状态:', isConnected)
  4269. if (isConnected !== 1) {
  4270. console.log('🔍 定时器检查发现 socket 未连接,执行重连')
  4271. createWebSocketConnection(2)
  4272. }
  4273. }
  4274. }, 10000) as unknown as NodeJS.Timeout
  4275. }
  4276. // 工具函数:格式化时间
  4277. const formatTime = (totalSec: number) => {
  4278. const m = Math.floor(totalSec / 60)
  4279. const s = Math.floor(totalSec % 60)
  4280. return `${fillDigit(m, 2)}:${fillDigit(s, 2)}`
  4281. }
  4282. // 块状时间显示
  4283. const timerBlocks = () => {
  4284. const total = timerIndicator.value.isCountdown
  4285. ? Math.max(timerIndicator.value.remainingSec || 0, 0)
  4286. : Math.max(timerIndicator.value.elapsedSec || 0, 0)
  4287. const h = Math.floor(total / 3600)
  4288. const m = Math.floor((total % 3600) / 60)
  4289. const s = Math.floor(total % 60)
  4290. return {
  4291. h: fillDigit(h, 2),
  4292. m: fillDigit(m, 2),
  4293. s: fillDigit(s, 2),
  4294. }
  4295. }
  4296. // 块可见性:始终显示时分秒
  4297. const timerBlocksVisibility = () => {
  4298. return {
  4299. showH: true,
  4300. showM: true,
  4301. }
  4302. }
  4303. // 根据布局避免遮挡右侧面板
  4304. const getTimerIndicatorRight = () => {
  4305. if (isFullscreen.value) {
  4306. return 16
  4307. }
  4308. if (props.type === '1') {
  4309. // 右侧面板展开时向左让位
  4310. return workPanelCollapsed.value ? 65 : 420
  4311. }
  4312. return 65
  4313. }
  4314. // 计时器本地更新
  4315. const startLocalTick = (isCountdown: boolean) => {
  4316. if (timerInterval.value) {
  4317. clearInterval(timerInterval.value)
  4318. timerInterval.value = null
  4319. }
  4320. timerInterval.value = setInterval(() => {
  4321. if (isCountdown) {
  4322. if (timerIndicator.value.remainingSec !== null) {
  4323. const newRemaining = (timerIndicator.value.remainingSec as number) - 1
  4324. timerIndicator.value.remainingSec = Math.max(newRemaining, 0)
  4325. // 时间到了,标记为完成但保持显示
  4326. if (newRemaining <= 0) {
  4327. timerIndicator.value.finished = true
  4328. timerIndicator.value.remainingSec = 0
  4329. // 保持 visible 为 true,不隐藏
  4330. timerIndicator.value.visible = true
  4331. }
  4332. }
  4333. }
  4334. else {
  4335. if (timerIndicator.value.elapsedSec !== null) {
  4336. timerIndicator.value.elapsedSec = (timerIndicator.value.elapsedSec as number) + 1
  4337. }
  4338. }
  4339. }, 1000) as unknown as number
  4340. }
  4341. // CountdownTimer 事件(仅创建人触发发送)
  4342. const onTimerStart = (payload: { isCountdown: boolean; startAt: string; durationSec?: number }) => {
  4343. timerIndicator.value.visible = true
  4344. timerIndicator.value.isCountdown = payload.isCountdown
  4345. timerIndicator.value.startAt = payload.startAt
  4346. timerIndicator.value.durationSec = payload.isCountdown ? (payload.durationSec || 0) : null
  4347. timerIndicator.value.elapsedSec = payload.isCountdown ? null : 0
  4348. timerIndicator.value.remainingSec = payload.isCountdown ? (payload.durationSec || 0) : null
  4349. timerIndicator.value.finished = false
  4350. startLocalTick(payload.isCountdown)
  4351. if (isCreator.value) {
  4352. sendMessage({ type: 'timer_start', courseid: props.courseid, payload: JSON.stringify(payload) })
  4353. // 持久化状态到 YMap(带运行状态与基线)
  4354. const isCd = payload.isCountdown
  4355. const state: any = {
  4356. visible: true,
  4357. isCountdown: isCd,
  4358. status: 'running',
  4359. startAt: payload.startAt,
  4360. durationSec: isCd ? (payload.durationSec || 0) : null,
  4361. finished: false,
  4362. stopped: false,
  4363. }
  4364. if (isCd) {
  4365. state.remainingBaseSec = payload.durationSec || 0
  4366. state.elapsedBaseSec = null
  4367. }
  4368. else {
  4369. state.elapsedBaseSec = 0
  4370. state.remainingBaseSec = null
  4371. }
  4372. setTimerState(state)
  4373. }
  4374. }
  4375. const onTimerPause = () => {
  4376. if (timerInterval.value) {
  4377. clearInterval(timerInterval.value)
  4378. timerInterval.value = null
  4379. }
  4380. if (isCreator.value) {
  4381. sendMessage({ type: 'timer_pause', courseid: props.courseid })
  4382. // 将当前显示值作为基线写入,并标记暂停
  4383. const isCd = !!timerIndicator.value.isCountdown
  4384. const payload: any = {
  4385. ...getTimerState(),
  4386. status: 'paused',
  4387. pausedAt: new Date().toISOString(),
  4388. finished: !!timerIndicator.value.finished,
  4389. stopped: false,
  4390. }
  4391. if (isCd) {
  4392. payload.remainingBaseSec = Math.max(Number(timerIndicator.value.remainingSec || 0), 0)
  4393. payload.elapsedBaseSec = null
  4394. }
  4395. else {
  4396. payload.elapsedBaseSec = Math.max(Number(timerIndicator.value.elapsedSec || 0), 0)
  4397. payload.remainingBaseSec = null
  4398. }
  4399. setTimerState(payload)
  4400. }
  4401. }
  4402. const onTimerReset = () => {
  4403. if (timerInterval.value) {
  4404. clearInterval(timerInterval.value)
  4405. timerInterval.value = null
  4406. }
  4407. timerIndicator.value = { visible: false, isCountdown: false, startAt: null, durationSec: null, elapsedSec: null, remainingSec: null, finished: false }
  4408. if (isCreator.value) {
  4409. sendMessage({ type: 'timer_reset', courseid: props.courseid })
  4410. clearTimerState()
  4411. }
  4412. }
  4413. const onTimerStop = () => {
  4414. if (timerInterval.value) {
  4415. clearInterval(timerInterval.value)
  4416. timerInterval.value = null
  4417. }
  4418. timerIndicator.value = { visible: false, isCountdown: false, startAt: null, durationSec: null, elapsedSec: null, remainingSec: null, finished: false }
  4419. if (isCreator.value) {
  4420. sendMessage({ type: 'timer_stop', courseid: props.courseid })
  4421. clearTimerState()
  4422. }
  4423. }
  4424. const onTimerFinish = () => {
  4425. timerIndicator.value.finished = true
  4426. // 保持 visible 为 true,时间到了也不消失
  4427. timerIndicator.value.visible = true
  4428. if (timerIndicator.value.isCountdown) {
  4429. timerIndicator.value.remainingSec = 0
  4430. }
  4431. if (timerInterval.value) {
  4432. clearInterval(timerInterval.value)
  4433. timerInterval.value = null
  4434. }
  4435. if (isCreator.value) {
  4436. sendMessage({ type: 'timer_finish', courseid: props.courseid })
  4437. const snap = getTimerState()
  4438. setTimerState({ ...snap, status: 'finished', finished: true, stopped: true, remainingBaseSec: 0 })
  4439. }
  4440. }
  4441. const onTimerUpdate = (payload: { durationSec: number }) => {
  4442. if (isCreator.value && timerIndicator.value.visible && timerIndicator.value.isCountdown) {
  4443. // 重新设置开始时间,重置整个计时
  4444. const newStartAt = new Date().toISOString()
  4445. // 更新本地状态
  4446. timerIndicator.value.startAt = newStartAt
  4447. timerIndicator.value.durationSec = payload.durationSec
  4448. timerIndicator.value.remainingSec = payload.durationSec
  4449. timerIndicator.value.finished = false
  4450. // 重新开始本地计时
  4451. startLocalTick(true)
  4452. // 更新 YMap 状态
  4453. const snap = getTimerState()
  4454. setTimerState({
  4455. ...snap,
  4456. status: 'running',
  4457. startAt: newStartAt,
  4458. durationSec: payload.durationSec,
  4459. remainingBaseSec: payload.durationSec,
  4460. finished: false,
  4461. })
  4462. // 发送消息通知其他用户(使用 timer_start 消息重新开始计时)
  4463. sendMessage({
  4464. type: 'timer_start',
  4465. courseid: props.courseid,
  4466. payload: JSON.stringify({
  4467. isCountdown: true,
  4468. startAt: newStartAt,
  4469. durationSec: payload.durationSec
  4470. })
  4471. })
  4472. }
  4473. }
  4474. // 消息应用(任意端)
  4475. const applyTimerStart = (payload: { isCountdown: boolean; startAt: string; durationSec?: number }) => {
  4476. timerIndicator.value.visible = true
  4477. timerIndicator.value.isCountdown = payload.isCountdown
  4478. timerIndicator.value.startAt = payload.startAt
  4479. timerIndicator.value.durationSec = payload.isCountdown ? (payload.durationSec || 0) : null
  4480. // 以消息时间为基准纠正进度
  4481. const startTs = new Date(payload.startAt).getTime()
  4482. const nowTs = Date.now()
  4483. if (payload.isCountdown) {
  4484. const elapsed = Math.floor((nowTs - startTs) / 1000)
  4485. timerIndicator.value.remainingSec = Math.max((payload.durationSec || 0) - elapsed, 0)
  4486. timerIndicator.value.elapsedSec = null
  4487. }
  4488. else {
  4489. timerIndicator.value.elapsedSec = Math.floor((nowTs - startTs) / 1000)
  4490. timerIndicator.value.remainingSec = null
  4491. }
  4492. timerIndicator.value.finished = false
  4493. startLocalTick(payload.isCountdown)
  4494. }
  4495. const applyTimerPause = () => {
  4496. if (timerInterval.value) {
  4497. clearInterval(timerInterval.value)
  4498. timerInterval.value = null
  4499. }
  4500. }
  4501. const applyTimerReset = () => {
  4502. if (timerInterval.value) {
  4503. clearInterval(timerInterval.value)
  4504. timerInterval.value = null
  4505. }
  4506. timerIndicator.value = { visible: false, isCountdown: false, startAt: null, durationSec: null, elapsedSec: null, remainingSec: null, finished: false }
  4507. }
  4508. const applyTimerStop = () => {
  4509. if (timerInterval.value) {
  4510. clearInterval(timerInterval.value)
  4511. timerInterval.value = null
  4512. }
  4513. timerIndicator.value = { visible: false, isCountdown: false, startAt: null, durationSec: null, elapsedSec: null, remainingSec: null, finished: false }
  4514. }
  4515. const applyTimerFinish = () => {
  4516. timerIndicator.value.finished = true
  4517. // 保持 visible 为 true,时间到了也不消失
  4518. timerIndicator.value.visible = true
  4519. if (timerIndicator.value.isCountdown) {
  4520. timerIndicator.value.remainingSec = 0
  4521. }
  4522. if (timerInterval.value) {
  4523. clearInterval(timerInterval.value)
  4524. timerInterval.value = null
  4525. }
  4526. }
  4527. const applyTimerUpdate = (payload: { durationSec: number; startAt?: string }) => {
  4528. if (timerIndicator.value.visible && timerIndicator.value.isCountdown) {
  4529. const newStartAt = payload.startAt || new Date().toISOString()
  4530. // 更新状态
  4531. timerIndicator.value.startAt = newStartAt
  4532. timerIndicator.value.durationSec = payload.durationSec
  4533. timerIndicator.value.remainingSec = payload.durationSec
  4534. timerIndicator.value.finished = false
  4535. // 重新开始本地计时
  4536. startLocalTick(true)
  4537. }
  4538. }
  4539. // 应用激光笔共享状态(任意端)
  4540. const applyLaserStateSnapshot = (snap: any) => {
  4541. if (!snap) return
  4542. const enabled = snap.enabled !== undefined ? !!snap.enabled : laserPenOverlay.value.visible
  4543. const x = typeof snap.x === 'number' ? snap.x : null
  4544. const y = typeof snap.y === 'number' ? snap.y : null
  4545. if (props.type == '2') {
  4546. // 更新开关状态
  4547. if (snap.enabled !== undefined) {
  4548. laserPenOverlay.value.visible = enabled
  4549. }
  4550. // 如果激光笔是开启状态,更新位置
  4551. if (laserPenOverlay.value.visible && x != null && y != null) {
  4552. laserPenOverlay.value.xPct = x
  4553. laserPenOverlay.value.yPct = y
  4554. refreshLaserOverlayRect()
  4555. if (laserMoveRafId) cancelAnimationFrame(laserMoveRafId)
  4556. laserMoveRafId = requestAnimationFrame(updateLaserDotPosition)
  4557. }
  4558. }
  4559. }
  4560. // YMap 状态应用
  4561. const applyTimerStateSnapshot = (snap: any) => {
  4562. if (!snap || !snap.visible) {
  4563. return
  4564. }
  4565. const isCountdown = !!snap.isCountdown
  4566. const status = snap.status as string | undefined
  4567. const startAt = snap.startAt as string
  4568. const durationSec = isCountdown ? Number(snap.durationSec || 0) : null
  4569. const finished = !!snap.finished
  4570. const elapsedBaseSec = snap.elapsedBaseSec != null ? Number(snap.elapsedBaseSec) : null
  4571. const remainingBaseSec = snap.remainingBaseSec != null ? Number(snap.remainingBaseSec) : null
  4572. timerIndicator.value.visible = true
  4573. timerIndicator.value.isCountdown = isCountdown
  4574. timerIndicator.value.startAt = startAt
  4575. timerIndicator.value.durationSec = durationSec
  4576. const startTs = new Date(startAt).getTime()
  4577. const nowTs = Date.now()
  4578. if (isCountdown) {
  4579. if (status === 'paused') {
  4580. timerIndicator.value.remainingSec = Math.max(remainingBaseSec || 0, 0)
  4581. timerIndicator.value.elapsedSec = null
  4582. timerIndicator.value.finished = !!finished || (timerIndicator.value.remainingSec as number) <= 0
  4583. if (timerInterval.value) {
  4584. clearInterval(timerInterval.value); timerInterval.value = null
  4585. }
  4586. return
  4587. }
  4588. const base = remainingBaseSec != null ? remainingBaseSec : (durationSec || 0)
  4589. const elapsed = Math.floor((nowTs - startTs) / 1000)
  4590. timerIndicator.value.remainingSec = Math.max(base - elapsed, 0)
  4591. timerIndicator.value.elapsedSec = null
  4592. if (finished || (timerIndicator.value.remainingSec as number) <= 0) {
  4593. timerIndicator.value.finished = true
  4594. timerIndicator.value.remainingSec = 0
  4595. // 保持 visible 为 true,时间到了也不消失
  4596. timerIndicator.value.visible = true
  4597. if (timerInterval.value) {
  4598. clearInterval(timerInterval.value); timerInterval.value = null
  4599. }
  4600. }
  4601. else {
  4602. timerIndicator.value.finished = false
  4603. startLocalTick(true)
  4604. }
  4605. }
  4606. else {
  4607. if (status === 'paused') {
  4608. timerIndicator.value.elapsedSec = Math.max(elapsedBaseSec || 0, 0)
  4609. timerIndicator.value.remainingSec = null
  4610. timerIndicator.value.finished = !!finished
  4611. if (timerInterval.value) {
  4612. clearInterval(timerInterval.value); timerInterval.value = null
  4613. }
  4614. return
  4615. }
  4616. const base = elapsedBaseSec != null ? elapsedBaseSec : 0
  4617. const elapsed = Math.floor((nowTs - startTs) / 1000)
  4618. timerIndicator.value.elapsedSec = base + elapsed
  4619. timerIndicator.value.remainingSec = null
  4620. if (finished) {
  4621. if (timerInterval.value) {
  4622. clearInterval(timerInterval.value); timerInterval.value = null
  4623. }
  4624. timerIndicator.value.finished = true
  4625. }
  4626. else {
  4627. timerIndicator.value.finished = false
  4628. startLocalTick(false)
  4629. }
  4630. }
  4631. }
  4632. // 读写 YMap 工具
  4633. const getTimerState = () => {
  4634. if (!yTimerState.value) return {}
  4635. return yTimerState.value.toJSON()
  4636. }
  4637. const setTimerState = (state: any) => {
  4638. if (!yTimerState.value) return
  4639. docSocket.value?.transact(() => {
  4640. Object.entries(state).forEach(([k, v]) => yTimerState.value.set(k, v as any))
  4641. yTimerState.value.set('visible', true)
  4642. })
  4643. }
  4644. const clearTimerState = () => {
  4645. if (!yTimerState.value) return
  4646. docSocket.value?.transact(() => {
  4647. yTimerState.value.clear()
  4648. })
  4649. }
  4650. </script>
  4651. <style lang="scss" scoped>
  4652. .pptist-student-viewer {
  4653. height: 100vh;
  4654. display: flex;
  4655. background-color: #f4f4f4;
  4656. padding: 15px 0;
  4657. box-sizing: border-box;
  4658. // 全屏模式样式
  4659. &.fullscreen {
  4660. padding: 0;
  4661. .layout-content-left {
  4662. display: none; // 全屏时隐藏左侧导航栏
  4663. }
  4664. .layout-content-right {
  4665. display: none; // 全屏时隐藏左侧导航栏
  4666. }
  4667. .viewer-header {
  4668. display: none; // 全屏时隐藏顶部标题栏
  4669. }
  4670. }
  4671. // 激光笔模式样式
  4672. }
  4673. .layout-content-left {
  4674. width: 200px;
  4675. height: 100%;
  4676. background-color: #fff;
  4677. border-radius: 0 5px 0 5px;
  4678. overflow: hidden;
  4679. transition: width .2s ease;
  4680. margin: 10px;
  4681. }
  4682. .layout-content-left.collapsed {
  4683. width: 48px;
  4684. margin-left: 0;
  4685. }
  4686. .slide-header {
  4687. display: flex;
  4688. align-items: center;
  4689. justify-content: space-between;
  4690. }
  4691. /* 收缩时头部仅显示按钮,并保持按钮在可用宽度内水平居中 */
  4692. .layout-content-left.collapsed .slide-header {
  4693. justify-content: center;
  4694. padding: 8px;
  4695. }
  4696. .layout-content-right {
  4697. width: 350px;
  4698. height: 100%;
  4699. background-color: #fff;
  4700. border-radius: 5px 0 5px 0;
  4701. overflow: hidden;
  4702. transition: width .2s ease;
  4703. position: relative;
  4704. margin: 10px;
  4705. }
  4706. .panel-content {
  4707. margin-right: 0;
  4708. // padding: 0 8px;
  4709. height: calc(100% - 65px);
  4710. overflow: auto;
  4711. }
  4712. .layout-content-right.collapsed {
  4713. width: 52px;
  4714. margin-right: 0px;
  4715. }
  4716. .right-panel-header {
  4717. display: flex;
  4718. align-items: center;
  4719. justify-content: space-between;
  4720. }
  4721. /* 侧边导航标签样式 */
  4722. .side-nav-tabs {
  4723. position: absolute;
  4724. right: 0;
  4725. top: 60px;
  4726. bottom: 0;
  4727. width: 52px;
  4728. display: flex;
  4729. flex-direction: column;
  4730. gap: 8px;
  4731. padding: 8px 0;
  4732. align-items: center;
  4733. background: #fff;
  4734. border-left: 1px solid #e0e0e0;
  4735. z-index: 10;
  4736. }
  4737. .side-nav-btn {
  4738. width: 45px;
  4739. height: 45px;
  4740. min-height: 45px;
  4741. border: 1px solid #d9d9d9;
  4742. background: #fff;
  4743. border-radius: 6px;
  4744. cursor: pointer;
  4745. transition: all 0.2s;
  4746. display: flex;
  4747. align-items: center;
  4748. justify-content: center;
  4749. padding: 8px;
  4750. gap: 8px;
  4751. overflow: hidden;
  4752. &:hover {
  4753. border-color: #1890ff;
  4754. transform: scale(1.02);
  4755. }
  4756. &.active {
  4757. border-color: #3681fc;
  4758. background: #3681fc;
  4759. box-shadow: 0 0 0 2px rgba(54, 129, 252, 0.2);
  4760. }
  4761. img {
  4762. width: 25px;
  4763. height: 25px;
  4764. object-fit: contain;
  4765. flex-shrink: 0;
  4766. }
  4767. span {
  4768. font-size: 12px;
  4769. font-weight: 500;
  4770. color: #333;
  4771. white-space: nowrap;
  4772. overflow: hidden;
  4773. text-overflow: ellipsis;
  4774. }
  4775. &.active span {
  4776. color: #fff;
  4777. }
  4778. }
  4779. /* 收缩时头部仅显示按钮,并保持按钮在可用宽度内水平居中 */
  4780. .layout-content-right.collapsed .right-panel-header {
  4781. justify-content: center;
  4782. padding: 8px;
  4783. }
  4784. /* 收缩状态下的切换按钮 */
  4785. .collapsed-tabs {
  4786. display: flex;
  4787. flex-direction: column;
  4788. gap: 8px;
  4789. // padding: 8px;
  4790. align-items: center;
  4791. }
  4792. .collapsed-tab-btn {
  4793. width: 32px;
  4794. height: 32px;
  4795. border: 1px solid #d9d9d9;
  4796. background: #fff;
  4797. border-radius: 6px;
  4798. cursor: pointer;
  4799. transition: all 0.2s;
  4800. display: flex;
  4801. align-items: center;
  4802. justify-content: center;
  4803. padding: 0;
  4804. overflow: hidden;
  4805. &:hover {
  4806. border-color: #1890ff;
  4807. transform: scale(1.05);
  4808. }
  4809. &.active {
  4810. border-color: #3681fc;
  4811. background: #3681fc;
  4812. box-shadow: 0 0 0 2px rgba(54, 129, 252, 0.2);
  4813. }
  4814. img {
  4815. width: 20px;
  4816. height: 20px;
  4817. object-fit: contain;
  4818. transition: transform 0.2s;
  4819. }
  4820. &:hover img {
  4821. transform: scale(1.1);
  4822. }
  4823. }
  4824. .collapse-btn {
  4825. display: inline-flex;
  4826. align-items: center;
  4827. justify-content: center;
  4828. width: 32px;
  4829. height: 32px;
  4830. // border: 1px solid #d9d9d9;
  4831. border: none;
  4832. border-radius: 8px;
  4833. background: #fff;
  4834. color: #333;
  4835. cursor: pointer;
  4836. line-height: 1;
  4837. font-weight: 700;
  4838. position: absolute;
  4839. }
  4840. .collapse-btn:hover {
  4841. // border-color: #1890ff;
  4842. // color: #1890ff;
  4843. }
  4844. .homework-title {
  4845. padding: 12px 12px 0 12px;
  4846. color: #333;
  4847. font-size: 14px;
  4848. font-weight: 600;
  4849. }
  4850. .homework-grid {
  4851. display: grid;
  4852. grid-template-columns: repeat(4, 1fr);
  4853. gap: 16px;
  4854. padding: 12px;
  4855. }
  4856. .homework-btn {
  4857. display: inline-flex;
  4858. align-items: center;
  4859. justify-content: center;
  4860. width: 100%;
  4861. min-width: 0;
  4862. height: 35px;
  4863. border: 1px solid #2f80ed;
  4864. color: #2f80ed;
  4865. background: #fff;
  4866. border-radius: 8px;
  4867. cursor: pointer;
  4868. font-weight: 600;
  4869. overflow: hidden;
  4870. padding: 0 10px;
  4871. text-align: center;
  4872. }
  4873. .homework-btn__text {
  4874. display: block;
  4875. max-width: 100%;
  4876. overflow: hidden;
  4877. white-space: nowrap;
  4878. text-overflow: ellipsis;
  4879. }
  4880. .homework-btn:hover {
  4881. box-shadow: 0 2px 10px rgba(0,0,0,0.08);
  4882. }
  4883. .homework-btn.unsubmitted {
  4884. border-color: #d9d9d9;
  4885. color: #999;
  4886. background: #f5f5f5;
  4887. cursor: not-allowed;
  4888. }
  4889. .homework-btn.unsubmitted:hover {
  4890. box-shadow: none;
  4891. transform: none;
  4892. }
  4893. .homework-loading {
  4894. padding: 12px;
  4895. color: #666;
  4896. font-size: 13px;
  4897. }
  4898. .homework-empty {
  4899. padding: 12px;
  4900. color: #999;
  4901. font-size: 13px;
  4902. }
  4903. .thumbnails {
  4904. padding: 0;
  4905. height: 100%;
  4906. .viewer-header {
  4907. margin-bottom: 16px;
  4908. h3 {
  4909. margin: 0;
  4910. font-size: 16px;
  4911. font-weight: 600;
  4912. color: #333;
  4913. text-align: center;
  4914. width: 100%;
  4915. }
  4916. }
  4917. .thumbnail-list {
  4918. width: 100%;
  4919. padding: 0 16px;
  4920. box-sizing: border-box;
  4921. .thumbnail-item {
  4922. position: relative;
  4923. margin-bottom: 12px;
  4924. cursor: pointer;
  4925. border-radius: 8px;
  4926. overflow: hidden;
  4927. transition: all 0.2s ease;
  4928. border: 2px solid rgba(24, 144, 255, 0.2);
  4929. &:hover {
  4930. transform: translateY(-2px);
  4931. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  4932. border-color: rgba(24, 144, 255, 0.4);
  4933. }
  4934. &.active {
  4935. border: 2px solid #1890ff;
  4936. box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
  4937. }
  4938. .label {
  4939. position: absolute;
  4940. top: 8px;
  4941. left: 8px;
  4942. background-color: rgba(0, 0, 0, 0.6);
  4943. color: #fff;
  4944. padding: 2px 6px;
  4945. border-radius: 4px;
  4946. font-size: 12px;
  4947. font-weight: 600;
  4948. z-index: 1;
  4949. }
  4950. .thumbnail {
  4951. width: 100%;
  4952. height: auto;
  4953. }
  4954. }
  4955. }
  4956. .page-number {
  4957. text-align: center;
  4958. margin-top: 16px;
  4959. padding: 8px;
  4960. background-color: #f0f0f0;
  4961. border-radius: 4px;
  4962. font-size: 14px;
  4963. color: #666;
  4964. }
  4965. .progress-bar {
  4966. margin-top: 12px;
  4967. height: 6px;
  4968. background-color: #f0f0f0;
  4969. border-radius: 3px;
  4970. overflow: hidden;
  4971. .progress-fill {
  4972. height: 100%;
  4973. background: linear-gradient(90deg, #1890ff, #40a9ff);
  4974. border-radius: 3px;
  4975. transition: width 0.3s ease;
  4976. }
  4977. }
  4978. }
  4979. .layout-content-center {
  4980. flex: 1;
  4981. display: flex;
  4982. flex-direction: column;
  4983. background-color: #000;
  4984. }
  4985. .viewer-header {
  4986. height: 45px;
  4987. background-color: #fff;
  4988. border-bottom: 1px solid #e0e0e0;
  4989. display: flex;
  4990. align-items: center;
  4991. justify-content: space-between;
  4992. padding: 0 8px;
  4993. transition: transform 0.3s ease;
  4994. position: relative;
  4995. &.hidden {
  4996. transform: translateY(-100%);
  4997. }
  4998. .slide-title {
  4999. font-size: 18px;
  5000. font-weight: 600;
  5001. color: #333;
  5002. }
  5003. .viewer-controls {
  5004. display: flex;
  5005. gap: 12px;
  5006. button {
  5007. padding: 8px 12px;
  5008. border: 1px solid #d9d9d9;
  5009. border-radius: 6px;
  5010. background-color: #fff;
  5011. color: #333;
  5012. cursor: pointer;
  5013. transition: all 0.2s ease;
  5014. display: flex;
  5015. align-items: center;
  5016. justify-content: center;
  5017. min-width: 40px;
  5018. height: 36px;
  5019. &:hover:not(:disabled) {
  5020. border-color: #1890ff;
  5021. color: #1890ff;
  5022. }
  5023. &:disabled {
  5024. opacity: 0.5;
  5025. cursor: not-allowed;
  5026. }
  5027. &.back-btn {
  5028. background-color: #1890ff;
  5029. color: #fff;
  5030. border-color: #1890ff;
  5031. &:hover {
  5032. background-color: #40a9ff;
  5033. border-color: #40a9ff;
  5034. }
  5035. }
  5036. &.follow-active {
  5037. background-color: #3681fc;
  5038. color: #fff !important;
  5039. border-color: #3681fc;
  5040. &:hover {
  5041. background-color: #2d6fd9;
  5042. border-color: #2d6fd9;
  5043. color: #fff !important;
  5044. }
  5045. }
  5046. .control-icon {
  5047. font-size: 16px;
  5048. }
  5049. }
  5050. }
  5051. }
  5052. .viewer-canvas {
  5053. flex: 1;
  5054. position: relative;
  5055. background-color: rgb(244, 244, 244);
  5056. overflow: hidden;
  5057. // 全屏时隐藏滚动条和边框
  5058. &.fullscreen-mode {
  5059. overflow: hidden !important;
  5060. background-color: transparent !important;
  5061. }
  5062. }
  5063. .slide-list-wrap {
  5064. position: absolute;
  5065. overflow: hidden;
  5066. background-color: #fff;
  5067. box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.01), 0 0 12px 0 rgba(0, 0, 0, 0.1);
  5068. border-radius: 8px;
  5069. /* 全屏时去掉圆角 */
  5070. .pptist-student-viewer.fullscreen & {
  5071. border-radius: 0;
  5072. }
  5073. }
  5074. .slide-list-wrap-n{
  5075. border: 5px solid #595959;
  5076. background: #000;
  5077. padding: 65px 0 0 0;
  5078. box-sizing: border-box;
  5079. }
  5080. /* 学生端激光笔覆盖层与小圆点样式(拦截点击) */
  5081. .laser-pointer-overlay {
  5082. position: fixed;
  5083. inset: 0;
  5084. z-index: 1000;
  5085. pointer-events: auto;
  5086. }
  5087. .laser-pointer-dot {
  5088. position: absolute;
  5089. width: 24px;
  5090. height: 24px;
  5091. pointer-events: none;
  5092. /* 复用 .laser-pen 的光点视觉(使用与 cursor 相同的图) */
  5093. background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABHNCSVQICAgIfAhkiAAACCJJREFUWIXtmLuO3MYShv/qZl9IzqwXo2BkSAtsIK+z8wwOBcOJ9C56Cr2LlThQcgBnfofVBnswXlgTaLHaIdk3dtcJOKOzd8n2MeDABRDDgKz/m+pudv0N/BN/Luj/kYSZJQBxJR8DKESU/2zuPwTIzAKnpxqHhxUuLir0vYSUAkS0ewA5F7Rtxv7+iNPTEYeHkYjKXwrIzHK9XtultRohaKSkkFIVhqGCEAIxTvm0ZpRSTNOMUGqEUgnGxLX3cblc+t9T2S8GXK1W9dP53OLiwoLZhMtLQ4CiGBVKkchZIOcpn5QMKQuEyKx1YiCZvb0AooD9ff/rZuMPDg7cl+hWn3uAmQWABut1g/PzOnZdTd5bMY6aQtAIQQGQGEd5bYirKgPIZExiY2IKIbK1XpeinzaN2s7b4XPD/iAgM0ucn7fYbNrQ963Juaauq8k5i3E01PcG46iQs0TO1wGlzJAyo6oS2jagqgLGUQNQwTllvJeYzwUz9w8N+b2AzCxwft6i72fBuZkYhnbcbBqKsSbvazhnEIJBzqrEqGQpAlO1AaKShShC6wQpE4UQUNcBKenReyXm8yoIIYwQtNXq7qvkQxVssNm0wbmZuLiYUQgtnGtps2ngfQ3vLaVkEKOmGKcqMtMWkEnKTFonaB3Z+4AQPFmreD6vSAghxpECAFMKY7EoALovBlytVjXW6yb0fSuGoaUQWrq8nKHvW/R9S943xbmavJ+qmNIO8FMFIWXert7A1gYxjprHsSLmaTHt7UF0HYdSilmv82q1ynctnFuAzCzx8aPF+Xltcq7HzaaBcy36vsUwzKjrZhiGRgxDA+8tUjIUgkbOEqVMgEIUkjLDmAjvgwjBI6WKxlHybp5KyVRKMcaMGIb0dLFIzBxvzsdbgOv12i69t7HrpgURY02bTYO+b6nrZui6qZLONdz3jTg5ORDHx0f48OExQpgBAIzp8OjRez46Oi7Pnq1ot5BKETQVgYmosJRj6rrEQNJCxLX3EUB/LyAzC3z8qOGcIe8tOWdpmm81ed9gGJpdJdF1rXz79jucnX1za454P8fZ2ZzOzr6Rx8fvyvPnP38afiEKVVXmqhrJ+wSlIqoqYj73S2s1M7urC0ZcS3x6qhGCDpeXBuOoMY4Gzhl4b4tzNYahgXMNuq4Vb978cCfczTg7+0a8efMDuq6Fcw2GoSnO1fDewjmDcTQYx0kzBI3TU3319euAh4cVUlIEKApBU98bhGAoJSO8N/Dect834u3b73B+/vVn4XZxfv61ePv2O+77Bt5b4b2hlKbcfW8oBE2AQkoKh4fXRvU64MVFhZQqilEhBLX9CCvEqLer1YiTk4MvqtxdlTw5OcAWDDFq5DxphDBtmSlNzcddgMws0fcyDEOFUiQAiZxliVGVGFVJSXEImo6Pj3433Dbo+PiIQ9AlJbXLi5wnrVIm7b6X223wOiAAASkFhBDIWWAcJXKWshQhcpYiZ0k5S3z48PhO9ZcvgV9+ma6XL+8m/PDhMW1ziW1u5Cy3WpO2lOIq11VAAhEhRkLO0z0RgVmAefotRXz6lNyMV6+AxWK6Xr26GzCEGXZb4i7nTifnSXv6Tn7qssTdmf4+cRWQwczQmiHldM/MICogmn6FKDDmzj0Tr18D5+fT9fr13WrGdBCiXMu505Fy0mZmTJYBwPUPdUHOBaUUSFlQVRlS5rzbtqTMJGXGo0fvcXY2vyX+44/T9VA8evSepcy8zcdCFDG1ZBlSTto5FwC3P9RElNG22TTNCCEygAwps9A6Ca2TUCqRMZGPjo4fprg/+OjomIyJQqm0ywspJy0hJu22zVf34+tzcH9/hFIja51gTEJVJUiZoHWEMQFKhfLs2QpPnrz73XRPnrwrz56toFSAMQFaR0g5aRiTWOsEpUbs749XX7u51Y1QKjGQ2JjIbRtgTGClQrE2wFpPbTuU589/xmLx2xfDLRa/lefPf6a2HWCtL9YG3oJy2wY2JjKQoFTC6ekDgIeHEcZEs7cXUFURVTV1wtZ6UdcOTTOgrgfMZn158eKnL6rkkyfvyosXP2E261HXA5pmEHXtYK1HXU9WoKomTWMiDg/j1devbStEVN6/fx+XRIGt9RhHjZQ0Wat4HCsax//1fEQlf//9v8XJyTF9rt1q2+mPtW2PphnY2gHWOrbWcV17ttaDKKy9j4/398u9gACwXC49Pn7UuhQNQI3eT206s2DadptCFEiZqaoS/+tfvnz77X/oRsPKUmYyJpJSAdZ6NM2Aphl4Pu/QND3P5wO0dmo2c5jNHPb3/fKrr/xNnluARJRXq5V/2jQqOKfE1kPsPC8zM1VVLkqNwpiAEAxbq+hGy89SZtq2/MXaIOrasbUDmqZH2/Zo257bdghSOtM07tfNxh/s799yd3d6koODA8fM0ngvw9bgYG9vatOJClfVSFUVYe3UldxhmiBlxtY0kVLTlLHW8Xw+oG17NqYvs1lv6rrHcjkcEN1p5B9ydQPmc2GEoABAdB1TKYWlnDph5wJvbSdPpwvXbCcLUXhrO2FMQF0HttZBa8dtO5TZrDdt26FtewDDfRD3AhJRYeYemKxh2Bqc1HVTm17Xn4y7yFnyDeMurhh33hp3rmuvZjMXpHSmrqehXiz6h04XHjxZIKLMzB0Wi2LW64xhSAwkVFXEOGpo/dmjD2yPPlBVka31mM2caRqH5XLAnz362FUSQLdarfLTxSJpISLmcx8uLw217R8/PLpnzt3S/5KHdvG3Pn67Afr3PMB8APgvOwL+J/5s/BeEBm1u1Gu4+QAAAABJRU5ErkJggg==);
  5094. background-repeat: no-repeat;
  5095. background-position: center center;
  5096. background-size: contain;
  5097. /* 居中到指针 */
  5098. transform: translate3d(-12px, -12px, 0);
  5099. will-change: transform;
  5100. }
  5101. .laser-pen {
  5102. cursor: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABHNCSVQICAgIfAhkiAAACCJJREFUWIXtmLuO3MYShv/qZl9IzqwXo2BkSAtsIK+z8wwOBcOJ9C56Cr2LlThQcgBnfofVBnswXlgTaLHaIdk3dtcJOKOzd8n2MeDABRDDgKz/m+pudv0N/BN/Luj/kYSZJQBxJR8DKESU/2zuPwTIzAKnpxqHhxUuLir0vYSUAkS0ewA5F7Rtxv7+iNPTEYeHkYjKXwrIzHK9XtultRohaKSkkFIVhqGCEAIxTvm0ZpRSTNOMUGqEUgnGxLX3cblc+t9T2S8GXK1W9dP53OLiwoLZhMtLQ4CiGBVKkchZIOcpn5QMKQuEyKx1YiCZvb0AooD9ff/rZuMPDg7cl+hWn3uAmQWABut1g/PzOnZdTd5bMY6aQtAIQQGQGEd5bYirKgPIZExiY2IKIbK1XpeinzaN2s7b4XPD/iAgM0ucn7fYbNrQ963Juaauq8k5i3E01PcG46iQs0TO1wGlzJAyo6oS2jagqgLGUQNQwTllvJeYzwUz9w8N+b2AzCxwft6i72fBuZkYhnbcbBqKsSbvazhnEIJBzqrEqGQpAlO1AaKShShC6wQpE4UQUNcBKenReyXm8yoIIYwQtNXq7qvkQxVssNm0wbmZuLiYUQgtnGtps2ngfQ3vLaVkEKOmGKcqMtMWkEnKTFonaB3Z+4AQPFmreD6vSAghxpECAFMKY7EoALovBlytVjXW6yb0fSuGoaUQWrq8nKHvW/R9S943xbmavJ+qmNIO8FMFIWXert7A1gYxjprHsSLmaTHt7UF0HYdSilmv82q1ynctnFuAzCzx8aPF+Xltcq7HzaaBcy36vsUwzKjrZhiGRgxDA+8tUjIUgkbOEqVMgEIUkjLDmAjvgwjBI6WKxlHybp5KyVRKMcaMGIb0dLFIzBxvzsdbgOv12i69t7HrpgURY02bTYO+b6nrZui6qZLONdz3jTg5ORDHx0f48OExQpgBAIzp8OjRez46Oi7Pnq1ot5BKETQVgYmosJRj6rrEQNJCxLX3EUB/LyAzC3z8qOGcIe8tOWdpmm81ed9gGJpdJdF1rXz79jucnX1za454P8fZ2ZzOzr6Rx8fvyvPnP38afiEKVVXmqhrJ+wSlIqoqYj73S2s1M7urC0ZcS3x6qhGCDpeXBuOoMY4Gzhl4b4tzNYahgXMNuq4Vb978cCfczTg7+0a8efMDuq6Fcw2GoSnO1fDewjmDcTQYx0kzBI3TU3319euAh4cVUlIEKApBU98bhGAoJSO8N/Dect834u3b73B+/vVn4XZxfv61ePv2O+77Bt5b4b2hlKbcfW8oBE2AQkoKh4fXRvU64MVFhZQqilEhBLX9CCvEqLer1YiTk4MvqtxdlTw5OcAWDDFq5DxphDBtmSlNzcddgMws0fcyDEOFUiQAiZxliVGVGFVJSXEImo6Pj3433Dbo+PiIQ9AlJbXLi5wnrVIm7b6X223wOiAAASkFhBDIWWAcJXKWshQhcpYiZ0k5S3z48PhO9ZcvgV9+ma6XL+8m/PDhMW1ziW1u5Cy3WpO2lOIq11VAAhEhRkLO0z0RgVmAefotRXz6lNyMV6+AxWK6Xr26GzCEGXZb4i7nTifnSXv6Tn7qssTdmf4+cRWQwczQmiHldM/MICogmn6FKDDmzj0Tr18D5+fT9fr13WrGdBCiXMu505Fy0mZmTJYBwPUPdUHOBaUUSFlQVRlS5rzbtqTMJGXGo0fvcXY2vyX+44/T9VA8evSepcy8zcdCFDG1ZBlSTto5FwC3P9RElNG22TTNCCEygAwps9A6Ca2TUCqRMZGPjo4fprg/+OjomIyJQqm0ywspJy0hJu22zVf34+tzcH9/hFIja51gTEJVJUiZoHWEMQFKhfLs2QpPnrz73XRPnrwrz56toFSAMQFaR0g5aRiTWOsEpUbs749XX7u51Y1QKjGQ2JjIbRtgTGClQrE2wFpPbTuU589/xmLx2xfDLRa/lefPf6a2HWCtL9YG3oJy2wY2JjKQoFTC6ekDgIeHEcZEs7cXUFURVTV1wtZ6UdcOTTOgrgfMZn158eKnL6rkkyfvyosXP2E261HXA5pmEHXtYK1HXU9WoKomTWMiDg/j1devbStEVN6/fx+XRIGt9RhHjZQ0Wat4HCsax//1fEQlf//9v8XJyTF9rt1q2+mPtW2PphnY2gHWOrbWcV17ttaDKKy9j4/398u9gACwXC49Pn7UuhQNQI3eT206s2DadptCFEiZqaoS/+tfvnz77X/oRsPKUmYyJpJSAdZ6NM2Aphl4Pu/QND3P5wO0dmo2c5jNHPb3/fKrr/xNnluARJRXq5V/2jQqOKfE1kPsPC8zM1VVLkqNwpiAEAxbq+hGy89SZtq2/MXaIOrasbUDmqZH2/Zo257bdghSOtM07tfNxh/s799yd3d6koODA8fM0ngvw9bgYG9vatOJClfVSFUVYe3UldxhmiBlxtY0kVLTlLHW8Xw+oG17NqYvs1lv6rrHcjkcEN1p5B9ydQPmc2GEoABAdB1TKYWlnDph5wJvbSdPpwvXbCcLUXhrO2FMQF0HttZBa8dtO5TZrDdt26FtewDDfRD3AhJRYeYemKxh2Bqc1HVTm17Xn4y7yFnyDeMurhh33hp3rmuvZjMXpHSmrqehXiz6h04XHjxZIKLMzB0Wi2LW64xhSAwkVFXEOGpo/dmjD2yPPlBVka31mM2caRqH5XLAnz362FUSQLdarfLTxSJpISLmcx8uLw217R8/PLpnzt3S/5KHdvG3Pn67Afr3PMB8APgvOwL+J/5s/BeEBm1u1Gu4+QAAAABJRU5ErkJggg==) 20 20, default !important;
  5103. }
  5104. .slide-bottom{
  5105. height: 60px;
  5106. background: #000;
  5107. position: relative;
  5108. z-index: 10;
  5109. posttion: relative;
  5110. }
  5111. .slide-bottom-center{
  5112. position: absolute;
  5113. left: 50%;
  5114. top: 50%;
  5115. transform: translate(-50%, -50%);
  5116. }
  5117. .slide-bottom-center-item{
  5118. display: flex;
  5119. align-items: center;
  5120. justify-content: center;
  5121. gap: 15px;
  5122. img{
  5123. width: 24px;
  5124. height: 24px;
  5125. cursor: pointer;
  5126. }
  5127. .slide-bottom-center-item-page{
  5128. color: #fff;
  5129. font-size: 16px;
  5130. font-weight: 600;
  5131. display: flex;
  5132. gap: 5px;
  5133. }
  5134. }
  5135. .slide-bottom-right{
  5136. position: absolute;
  5137. right: 20px;
  5138. top: 50%;
  5139. transform: translateY(-50%);
  5140. display: flex;
  5141. align-items: center;
  5142. justify-content: center;
  5143. gap: 15px;
  5144. font-size: 24px;
  5145. color: #fff;
  5146. .tool-btn {
  5147. cursor: pointer;
  5148. &:hover,
  5149. &.active {
  5150. color: #1890ff;
  5151. }
  5152. &+.tool-btn {
  5153. margin-left: 15px;
  5154. }
  5155. }
  5156. .upBtn{
  5157. // border-bottom: 3px solid #fff;
  5158. // padding-bottom: 3px;
  5159. width: 24px;
  5160. height: 24px;
  5161. &:hover,
  5162. &.active {
  5163. border-color: #1890ff;
  5164. }
  5165. }
  5166. .tool-btn.loading {
  5167. animation: icon-rotate 1s linear infinite;
  5168. }
  5169. @keyframes icon-rotate {
  5170. 100% { transform: rotate(360deg); }
  5171. }
  5172. }
  5173. .upBtn :deep(svg) {
  5174. width: calc(1em - 3px) !important;
  5175. height: calc(1em - 3px) !important;
  5176. }
  5177. .loading-indicator {
  5178. position: absolute;
  5179. top: 50%;
  5180. left: 50%;
  5181. transform: translate(-50%, -50%);
  5182. display: flex;
  5183. align-items: center;
  5184. justify-content: center;
  5185. z-index: 10;
  5186. .loading-text {
  5187. color: #666;
  5188. font-size: 14px;
  5189. background-color: rgba(255, 255, 255, 0.9);
  5190. padding: 12px 20px;
  5191. border-radius: 6px;
  5192. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  5193. }
  5194. }
  5195. // 全屏模式样式
  5196. .fullscreen-slide {
  5197. // 使用放映功能的默认样式
  5198. }
  5199. // 全屏工具按钮样式,直接复制放映功能的样式
  5200. .tools-left {
  5201. position: fixed;
  5202. bottom: 8px;
  5203. left: 8px;
  5204. font-size: 25px;
  5205. color: #666;
  5206. z-index: 10;
  5207. .tool-btn {
  5208. opacity: .3;
  5209. cursor: pointer;
  5210. transition: opacity 0.3s;
  5211. &:hover {
  5212. opacity: .95;
  5213. }
  5214. &+.tool-btn {
  5215. margin-left: 8px;
  5216. }
  5217. }
  5218. }
  5219. .tools-right {
  5220. height: 66px;
  5221. position: fixed;
  5222. bottom: -66px;
  5223. right: 0;
  5224. z-index: 5;
  5225. padding: 8px;
  5226. transition: bottom 0.3s;
  5227. &.visible {
  5228. bottom: 0;
  5229. }
  5230. &::after {
  5231. content: '';
  5232. width: 100%;
  5233. height: 66px;
  5234. position: absolute;
  5235. left: 0;
  5236. top: -66px;
  5237. }
  5238. .content {
  5239. width: 100%;
  5240. height: 100%;
  5241. display: flex;
  5242. justify-content: center;
  5243. align-items: center;
  5244. border-radius: 4px;
  5245. font-size: 25px;
  5246. background-color: #fff;
  5247. color: #333;
  5248. padding: 8px 10px;
  5249. box-shadow: 0 2px 12px 0 rgb(56, 56, 56, .2);
  5250. border: 1px solid #e2e6ed;
  5251. }
  5252. .tool-btn {
  5253. cursor: pointer;
  5254. &:hover,
  5255. &.active {
  5256. color: #1890ff;
  5257. }
  5258. &+.tool-btn {
  5259. margin-left: 15px;
  5260. }
  5261. }
  5262. .page-number {
  5263. font-size: 12px;
  5264. padding: 0 12px;
  5265. cursor: pointer;
  5266. }
  5267. }
  5268. // 右上角计时状态指示器样式
  5269. .timer-indicator {
  5270. position: fixed;
  5271. z-index: 1000;
  5272. // background: rgba(0, 0, 0, 0.75);
  5273. color: #fff;
  5274. border-radius: 8px;
  5275. padding: 8px 10px;
  5276. display: flex;
  5277. align-items: center;
  5278. gap: 10px;
  5279. // border: 1px solid rgba(255, 255, 255, 0.15);
  5280. .label {
  5281. font-size: 12px;
  5282. opacity: .9;
  5283. margin-right: 2px;
  5284. white-space: nowrap;
  5285. }
  5286. .blocks {
  5287. display: flex;
  5288. align-items: center;
  5289. gap: 8px;
  5290. }
  5291. .block {
  5292. min-width: 45px;
  5293. height: 35px;
  5294. padding: 0 8px;
  5295. border-radius: 6px;
  5296. background: #111;
  5297. display: inline-flex;
  5298. align-items: center;
  5299. justify-content: center;
  5300. font-weight: 700;
  5301. font-size: 22px;
  5302. letter-spacing: 1px;
  5303. }
  5304. .colon {
  5305. position: relative;
  5306. width: 6px;
  5307. display: inline-flex;
  5308. align-items: center;
  5309. justify-content: center;
  5310. }
  5311. .colon::before,
  5312. .colon::after {
  5313. content: '';
  5314. width: 4px;
  5315. height: 4px;
  5316. border-radius: 50%;
  5317. background: #000;
  5318. display: block;
  5319. opacity: .9;
  5320. position: absolute;
  5321. left: 0;
  5322. }
  5323. .colon::before { top: 4px; }
  5324. .colon::after { bottom: 4px; }
  5325. // 全屏尺寸略大
  5326. .pptist-student-viewer.fullscreen & .block {
  5327. min-width: 40px;
  5328. height: 30px;
  5329. font-size: 18px;
  5330. }
  5331. &.countdown .block {
  5332. background: #222;
  5333. }
  5334. &.timeout .block,
  5335. &.timeout .colon {
  5336. background: #ff4d4f;
  5337. color: #fff;
  5338. }
  5339. }
  5340. .viewport {
  5341. position: relative;
  5342. width: 100%;
  5343. height: 100%;
  5344. background-color: #fff;
  5345. }
  5346. .background {
  5347. width: 100%;
  5348. height: 100%;
  5349. background-position: center;
  5350. position: absolute;
  5351. }
  5352. // 响应式设计
  5353. @media (max-width: 768px) {
  5354. .layout-content-left {
  5355. width: 160px;
  5356. }
  5357. .layout-content-right {
  5358. width: 160px;
  5359. }
  5360. .viewer-header {
  5361. padding: 0 16px;
  5362. .slide-title {
  5363. font-size: 16px;
  5364. }
  5365. .viewer-controls button {
  5366. padding: 6px 12px;
  5367. font-size: 14px;
  5368. }
  5369. }
  5370. }
  5371. /* 作业提交按钮样式 */
  5372. .homework-submit-btn {
  5373. position: fixed;
  5374. bottom: 160px;
  5375. z-index: 100;
  5376. background: #191a19;
  5377. color: white;
  5378. padding: 5px 20px;
  5379. border-radius: 5px;
  5380. cursor: pointer;
  5381. display: flex;
  5382. align-items: center;
  5383. gap: 8px;
  5384. border: 2px solid #191a19;
  5385. transition: all 0.3s ease;
  5386. font-size: 16px;
  5387. font-weight: 500;
  5388. &:hover:not(.submitting) {
  5389. transform: translateY(-2px);
  5390. box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
  5391. }
  5392. &:active:not(.submitting) {
  5393. transform: translateY(0);
  5394. }
  5395. &.submitting {
  5396. cursor: not-allowed;
  5397. opacity: 0.8;
  5398. background: linear-gradient(135deg, #999 0%, #666 100%);
  5399. }
  5400. .btn-text {
  5401. white-space: nowrap;
  5402. }
  5403. .tool-btn {
  5404. background: transparent;
  5405. color: white;
  5406. width: 20px;
  5407. height: 20px;
  5408. font-size: 16px;
  5409. &:hover {
  5410. background: transparent;
  5411. transform: none;
  5412. }
  5413. }
  5414. .loading-spinner {
  5415. width: 20px;
  5416. height: 20px;
  5417. border: 2px solid rgba(255, 255, 255, 0.3);
  5418. border-top: 2px solid white;
  5419. border-radius: 50%;
  5420. animation: spin 1s linear infinite;
  5421. }
  5422. }
  5423. /* 刷新网页按钮样式 */
  5424. .refresh-page-btn {
  5425. position: fixed;
  5426. bottom: 160px;
  5427. z-index: 100;
  5428. color: #000;
  5429. padding: 5px 20px;
  5430. border-radius: 5px;
  5431. background: #fff;
  5432. cursor: pointer;
  5433. display: flex;
  5434. align-items: center;
  5435. gap: 8px;
  5436. border: 2px solid #e9e9e9;
  5437. transition: all 0.3s ease;
  5438. font-size: 16px;
  5439. font-weight: 500;
  5440. &:hover {
  5441. transform: translateY(-2px);
  5442. box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
  5443. }
  5444. &:active {
  5445. transform: translateY(0);
  5446. }
  5447. .btn-text {
  5448. white-space: nowrap;
  5449. }
  5450. .tool-btn {
  5451. background: transparent;
  5452. color: #000;
  5453. width: 20px;
  5454. height: 20px;
  5455. font-size: 16px;
  5456. display: flex;
  5457. align-items: center;
  5458. &:hover {
  5459. background: transparent;
  5460. transform: none;
  5461. }
  5462. }
  5463. }
  5464. /* Loading状态样式 */
  5465. .loading-overlay {
  5466. position: absolute;
  5467. top: 0;
  5468. left: 0;
  5469. right: 0;
  5470. bottom: 0;
  5471. background: rgba(255, 255, 255, 0.95);
  5472. display: flex;
  5473. align-items: center;
  5474. justify-content: center;
  5475. z-index: 1000;
  5476. .loading-spinner {
  5477. width: 40px;
  5478. height: 40px;
  5479. border: 4px solid #f3f3f3;
  5480. border-top: 4px solid #1890ff;
  5481. border-radius: 50%;
  5482. animation: spin 1s linear infinite;
  5483. margin: 0 auto 16px;
  5484. }
  5485. }
  5486. .loading-content {
  5487. text-align: center;
  5488. color: #666;
  5489. }
  5490. .loading-text {
  5491. font-size: 14px;
  5492. color: #666;
  5493. }
  5494. @keyframes spin {
  5495. 0% { transform: rotate(0deg); }
  5496. 100% { transform: rotate(360deg); }
  5497. }
  5498. /* 标签页切换器样式 */
  5499. .tab-switcher {
  5500. display: flex;
  5501. flex: 1;
  5502. margin-right: 12px;
  5503. border-bottom: 1px solid #e0e0e0;
  5504. padding-bottom: 0;
  5505. height: 100%;
  5506. justify-content: center;
  5507. gap: 20px;
  5508. }
  5509. .tab-btn {
  5510. // flex: 1;
  5511. // padding: 12px 16px;
  5512. border: none;
  5513. background: transparent;
  5514. color: #666;
  5515. cursor: pointer;
  5516. transition: all 0.2s ease;
  5517. font-size: 14px;
  5518. font-weight: 500;
  5519. text-align: center;
  5520. white-space: nowrap;
  5521. position: relative;
  5522. border-radius: 0;
  5523. &:hover {
  5524. color: #333;
  5525. }
  5526. &.active {
  5527. color: #333;
  5528. font-weight: 600;
  5529. &::after {
  5530. content: '';
  5531. position: absolute;
  5532. bottom: -1px;
  5533. left: 0;
  5534. right: 0;
  5535. height: 2px;
  5536. background: #333;
  5537. border-radius: 1px;
  5538. }
  5539. }
  5540. }
  5541. // 在适当位置添加连接状态指示器
  5542. .connection-status {
  5543. position: fixed;
  5544. top: 10px;
  5545. right: 10px;
  5546. background-color: rgba(255, 255, 255, 0.9);
  5547. border-radius: 5px;
  5548. padding: 5px 10px;
  5549. display: flex;
  5550. align-items: center;
  5551. z-index: 1000;
  5552. .status-indicator {
  5553. // 胶囊浅蓝底 + 蓝色文字
  5554. padding: 5px 12px 5px 22px;
  5555. border-radius: 5px;
  5556. margin-right: 10px;
  5557. display: flex;
  5558. justify-content: center;
  5559. align-items: center;
  5560. position: relative;
  5561. background: transparent; // 根据具体状态设置渐变
  5562. // 边框去除
  5563. // border: 1px solid rgba(59, 111, 255, 0.35);
  5564. box-shadow: 0 2px 8px rgba(59, 111, 255, 0.15);
  5565. // 左侧状态圆点(不同状态不同颜色)
  5566. &::before {
  5567. content: "";
  5568. position: absolute;
  5569. left: 8px;
  5570. width: 8px;
  5571. height: 8px;
  5572. border-radius: 50%;
  5573. background-color: #1890ff; // 默认使用连接中蓝色
  5574. box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.12);
  5575. }
  5576. &.connected::before {
  5577. background-color: #52c41a; // 原始绿色
  5578. box-shadow: 0 0 0 2px rgba(82, 196, 26, 0.18);
  5579. }
  5580. &.connecting::before {
  5581. background-color: #1890ff; // 原始蓝色
  5582. box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.18);
  5583. }
  5584. &.disconnected::before {
  5585. background-color: #ff4d4f; // 原始红色
  5586. box-shadow: 0 0 0 2px rgba(255, 77, 79, 0.18);
  5587. }
  5588. span {
  5589. color: #1890ff; // 默认蓝色,具体状态里覆盖
  5590. font-size: 12px;
  5591. // font-weight: 600;
  5592. letter-spacing: 0.2px;
  5593. }
  5594. // 以原始主色为基础的浅色渐变与文字色
  5595. &.connected {
  5596. background: rgba(82, 196, 26, 0.15);
  5597. span { color: #52c41a; }
  5598. }
  5599. &.connecting {
  5600. background: rgba(24, 144, 255, 0.15);
  5601. span { color: #1890ff; }
  5602. }
  5603. &.disconnected {
  5604. background: rgba(255, 77, 79, 0.15);
  5605. span { color: #ff4d4f; }
  5606. }
  5607. }
  5608. .reconnect-btn {
  5609. background: linear-gradient(180deg, #eaf2ff 0%, #ddebff 100%);
  5610. color: #3b6fff;
  5611. border: none;
  5612. border-radius: 5px;
  5613. padding: 6px 14px;
  5614. cursor: pointer;
  5615. transition: all 0.2s ease;
  5616. // font-weight: 600;
  5617. box-shadow: 0 2px 8px rgba(59, 111, 255, 0.15);
  5618. &:hover {
  5619. background: linear-gradient(180deg, #e2edff 0%, #d3e4ff 100%);
  5620. border-color: rgba(59, 111, 255, 0.55);
  5621. box-shadow: 0 4px 12px rgba(59, 111, 255, 0.2);
  5622. }
  5623. }
  5624. }
  5625. .homework-check-box {
  5626. position: absolute;
  5627. top: 0;
  5628. left: 50%;
  5629. transform: translate(-50%, 0);
  5630. display: flex;
  5631. align-items: center;
  5632. // box-shadow: 0px 3px 4px 3px #f2f2f2;
  5633. padding: 8px;
  5634. border-radius: 0 0 5px 5px;
  5635. background: #fff;
  5636. z-index: 999;
  5637. transition: max-height 0.3s ease, padding 0.3s ease, overflow 0s;
  5638. &.fullscreen-mode {
  5639. overflow: hidden;
  5640. max-height: 5px;
  5641. padding: 0;
  5642. background: #f6c82b;
  5643. border-radius: 0;
  5644. transition: max-height 0.3s ease, padding 0.3s ease;
  5645. cursor: pointer;
  5646. .homework-check-box-item-title{
  5647. display: none;
  5648. }
  5649. &:hover {
  5650. max-height: 80px;
  5651. padding: 8px;
  5652. background: #fff;
  5653. border-radius: 0 0 5px 5px;
  5654. .homework-check-box-item-title{
  5655. display: block;
  5656. }
  5657. }
  5658. &.fs-expanded {
  5659. max-height: 80px;
  5660. padding: 8px;
  5661. background: #fff;
  5662. border-radius: 0 0 5px 5px;
  5663. .homework-check-box-item-title{
  5664. display: block;
  5665. }
  5666. }
  5667. }
  5668. .homework-check-box-item{
  5669. padding: 10px 18px;
  5670. border-radius: 5px;
  5671. font-weight: 600;
  5672. cursor: pointer;
  5673. transition: all 0.3s ease;
  5674. &.active{
  5675. background: #f6c82b;
  5676. }
  5677. &:hover{
  5678. background: #fff;
  5679. color: #f6c82b;
  5680. }
  5681. }
  5682. .homework-check-box-item-title{}
  5683. }
  5684. .aiBtn {
  5685. position: absolute;
  5686. display: flex;
  5687. align-items: center;
  5688. background: #fff;
  5689. z-index: 9999;
  5690. border-radius: 50px;
  5691. border: 3px solid #f6c82b;
  5692. padding: 10px 15px;
  5693. font-weight: 600;
  5694. gap: 5px;
  5695. cursor: move;
  5696. user-select: none;
  5697. touch-action: none; /* 防止触摸设备上的默认行为 */
  5698. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  5699. .aiBtn-icon{
  5700. font-size: 16px;
  5701. color: #f6c82b;
  5702. }
  5703. &:hover {
  5704. background: #f9f9f9;
  5705. }
  5706. &:active {
  5707. transform: scale(0.98);
  5708. }
  5709. }
  5710. </style>