learning-page.component.ts 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731
  1. import { ListeningPoolService } from '../../core/listening-pool.service';
  2. import { WordAudioService } from '../../core/word-audio.service';
  3. import { lessonDateLabel } from '../appointment/lesson-display';
  4. import { TeacherTodayReviewService } from '../../core/teacher-today-review.service';
  5. import { lessonStudySources } from '../appointment/lesson-study-sources';
  6. import { PressSwipeLeftDirective } from '../../shared/press-swipe-left.directive';
  7. import { DropdownDirective } from '../../shared/dropdown.directive';
  8. import { LearningDraft } from '../../core/learning-draft';
  9. import { ReviewPage, reviewCalendar } from '../../core/review-page';
  10. import { CommonModule } from '@angular/common';
  11. import { ChangeDetectionStrategy, Component, computed, inject, OnDestroy, OnInit, signal } from '@angular/core';
  12. import { ActivatedRoute, Router, RouterLink } from '@angular/router';
  13. import {
  14. Activity,
  15. BookOpen,
  16. BrainCircuit,
  17. Check,
  18. CheckCheck,
  19. ChevronLeft,
  20. ChevronRight,
  21. CircleHelp,
  22. Clock3,
  23. Flag,
  24. Headphones,
  25. Library,
  26. LucideAngularModule,
  27. Play,
  28. RefreshCw,
  29. RotateCcw,
  30. Star,
  31. Trash2,
  32. Volume2,
  33. X,
  34. } from 'lucide-angular';
  35. import { catchError, concatMap, finalize, forkJoin, from, map, Observable, of, Subscription, switchMap, tap, throwError, toArray } from 'rxjs';
  36. import { listeningChoices, shuffledStudy } from '../../core/learning-random';
  37. import { ApiError, ApiService } from '../../core/api.service';
  38. import {
  39. AntiForgetCalendarDay,
  40. antiForgetCompleted,
  41. antiForgetDate,
  42. antiForgetTasksOnDate,
  43. buildAntiForgetCalendar,
  44. buildAntiForgetView,
  45. mergeAntiForgetItems,
  46. nearestAntiForgetDate,
  47. } from '../../core/anti-forget';
  48. import { AppUser, PageMeta } from '../../core/models';
  49. import { canStartTeacherLedLearning, isTeacherLedLearningPath } from '../../core/learning-access';
  50. import { isLearningStage, learningReturnUrl } from '../../core/learning-navigation';
  51. import { PlatformService } from '../../core/platform.service';
  52. import { SessionService } from '../../core/session.service';
  53. import { nextReviewWordOrder } from '../../core/review-word-order';
  54. type SourceItem = Record<string, unknown>;
  55. interface WordbookStudent {
  56. userId: number;
  57. honeyName: string;
  58. }
  59. interface LessonBatchResult {
  60. batchId: string;
  61. batchVersion: number;
  62. learned?: number;
  63. resumed?: boolean;
  64. }
  65. interface Word extends SourceItem {
  66. id: string;
  67. wordId: string;
  68. nodeId: string;
  69. word: string;
  70. meaning: string;
  71. phonetic: string;
  72. audio: string;
  73. }
  74. interface LetterChoice {
  75. value: string;
  76. used: boolean;
  77. }
  78. interface ExamOption {
  79. text: string;
  80. value: string | number;
  81. checked?: boolean;
  82. }
  83. interface ExamQuestion extends SourceItem {
  84. ID: string | number;
  85. AskID?: string | number;
  86. QType?: string | number;
  87. QContent: string;
  88. QTitle?: string;
  89. QOption: ExamOption[];
  90. }
  91. interface ExamAnswer {
  92. qid: string | number;
  93. qtype: string | number;
  94. answer: string | number;
  95. result: 0 | 1 | 2;
  96. }
  97. interface MemoryStudentOption {
  98. id: string;
  99. name: string;
  100. taskCount: number;
  101. }
  102. const WORD_CATALOG_CATEGORIES = [
  103. { label: '小学', pid: 8 },
  104. { label: '初中', pid: 9 },
  105. { label: '高中', pid: 10 },
  106. { label: '大学+', pid: 11 },
  107. { label: '出国', pid: 12 },
  108. ] as const;
  109. @Component({
  110. selector: 'app-learning-page',
  111. standalone: true,
  112. imports: [PressSwipeLeftDirective, DropdownDirective, CommonModule, LucideAngularModule, RouterLink],
  113. templateUrl: './learning-page.component.html',
  114. styleUrl: './learning-page.component.scss',
  115. changeDetection: ChangeDetectionStrategy.OnPush,
  116. })
  117. export class LearningPageComponent implements OnInit, OnDestroy {
  118. private static readonly reviewCacheByApi = new WeakMap<ApiService, { identity: string; pages: Map<string, ReviewPage> }>();
  119. readonly meta = inject(ActivatedRoute).snapshot.data['meta'] as PageMeta;
  120. readonly nodes = signal<SourceItem[]>([]);
  121. readonly catalogCategories = WORD_CATALOG_CATEGORIES;
  122. readonly catalogCategoryIndex = signal(0);
  123. readonly selectedNodes = signal<Set<string>>(new Set());
  124. readonly words = signal<Word[]>([]);
  125. readonly wordPreviewPage = signal(1);
  126. readonly wordPreviewTotal = signal(0);
  127. readonly wordPreviewLoading = signal(false);
  128. readonly historyWordRevealed = signal<Set<string>>(new Set());
  129. readonly historyAudioWordId = signal('');
  130. private historyPreviewWords: Word[] = [];
  131. readonly selected = signal<Set<string>>(new Set());
  132. readonly selectionRevealed = signal<Set<string>>(new Set());
  133. readonly selectionAssessment = signal<Record<string, 'known' | 'unknown'>>({});
  134. readonly bulkSelection = signal<Set<string> | null>(null);
  135. readonly bulkSelectCount = signal(100);
  136. private readonly newWordBulkSelection = signal<{bucket: string; count: number; ids: string[]} | null>(null);
  137. readonly knownSaveRetry = signal(false);
  138. private knownSaveContinuation: { continueLearning: boolean; openKnownPass: boolean } | null = null;
  139. private courseSelectionNeedsRebase = false;
  140. readonly bulkCandidates = computed(() => this.visibleCourseWords().filter(word => this.canRelearnCourseWord(word) && this.selectionAssessment()[word.id] !== 'known'));
  141. readonly activeSelectionBucket = signal<'pending' | 'completed'>('pending');
  142. readonly recognizedTab = 4;
  143. readonly coursePassTabs = ['未学习', '已学一遍', '已学第二遍', '已学第三遍', '已认识'];
  144. readonly coursePass = signal(0);
  145. readonly coursePassCounts = signal<number[] | null>(null);
  146. readonly bookPassCounts = signal<number[] | null>(null);
  147. private readonly courseSelectionCache = signal<Word[]>([]);
  148. readonly visibleCourseWords = computed(() => {
  149. const candidates = [...this.words(), ...this.newlyKnownWords()];
  150. return [...new Map(candidates.map(word => [word.id, word])).values()]
  151. .filter(word => this.courseWordPass(word) === this.coursePass());
  152. });
  153. readonly firstPassProgress = computed(() => {
  154. const counts = this.bookPassCounts();
  155. const total = counts?.reduce((sum, n) => sum + n, 0) || 0;
  156. return total && counts ? Math.round((total - counts[0]) / total * 100) : 0;
  157. });
  158. readonly newWordCounts = signal({ pending: 0, completed: 0 });
  159. readonly wordbookStudents = signal<WordbookStudent[]>([]);
  160. readonly wordbookStudentId = signal(0);
  161. readonly wordbookStudentsLoading = signal(false);
  162. readonly wordbookStudentsError = signal('');
  163. readonly wordbookStudentsHaveMore = signal(false);
  164. private wordbookStudentsPage = 0;
  165. private wordbookStudentsRequest?: Subscription;
  166. private readonly newWordPageSize = 30;
  167. private readonly newWordSelectionCache = new Map<string, Word>();
  168. private legacyNewWords: Word[] | null = null;
  169. readonly currentIndex = signal(0);
  170. readonly revealed = signal(false);
  171. readonly completed = signal(false);
  172. readonly lessonLearnedCount = signal(0);
  173. readonly historySources = signal<Array<{label: string; count: number}>>([]);
  174. readonly correct = signal(0);
  175. readonly unknown = signal<Word[]>([]);
  176. readonly loading = signal(false);
  177. readonly calendarLoading = signal(false);
  178. readonly calendarError = signal('');
  179. readonly submitting = signal(false);
  180. readonly selectionLocked = computed(() => this.submitting() || this.knownSaveRetry());
  181. readonly selectionTotal=signal(0);readonly selectionPage=signal(1);readonly selectionLoading=signal(false);private selectionRequest?:Subscription;
  182. readonly error = signal('');
  183. readonly recordWordless = signal(false);
  184. readonly studyStep = signal<1 | 2 | 3>(1);
  185. readonly repetitions = signal<Record<string, number>>({});
  186. readonly studyMeaningRevealed = signal<Set<string>>(new Set());
  187. readonly matchLeft = signal<Word[]>([]);
  188. readonly matchRight = signal<Word[]>([]);
  189. readonly leftChoice = signal('');
  190. readonly rightChoice = signal('');
  191. readonly choicesLoading = signal(false);
  192. readonly choiceOptions = signal<Word[]>([]);
  193. readonly letters = signal<LetterChoice[]>([]);
  194. readonly assembled = signal('');
  195. readonly spellingCorrect = signal(false);
  196. readonly reviewState = signal<Record<string, 0 | 1 | 2>>({});
  197. readonly seen = signal<Set<string>>(new Set());
  198. readonly recordRevealed = signal<Set<string>>(new Set());
  199. readonly calendarItems = signal<SourceItem[]>([]);
  200. readonly memoryStudentId = signal('');
  201. readonly memoryMonth = signal(new Date(new Date().getFullYear(), new Date().getMonth(), 1, 12));
  202. readonly memorySelectedDate = signal('');
  203. readonly reviewScope=signal('');
  204. readonly reviewCompletion=signal<{amount:number;rewardStatus:string;ineligibleReason?:string;unchanged?:boolean}|null>(null);
  205. private reviewReturn: {date?:string;studentId?:string;page?:number;scope?:string;scroll?:number}={};
  206. readonly orderInfo = signal<SourceItem>({});
  207. readonly learnedRecord = signal<SourceItem>({});
  208. readonly antiHistory = signal<SourceItem>({});
  209. readonly myNewWords = signal<SourceItem>({});
  210. readonly examStarted = signal(false);
  211. readonly examSubmitted = signal(false);
  212. readonly askInfo = signal<SourceItem>({});
  213. readonly examHistory = signal<SourceItem[]>([]);
  214. readonly examHistoryLoading = signal(false);
  215. readonly examHistoryError = signal('');
  216. readonly examHistoryMore = signal(false);
  217. readonly examCompareIds = signal<string[]>([]);
  218. readonly comparedExams = computed(() => this.examHistory().filter(r => this.examCompareIds().includes(String(r['GeneralID']))));
  219. readonly examSaveError = signal('');
  220. readonly examDateLabel = lessonDateLabel;
  221. private examHistoryPage = 0;
  222. private examHistoryRequest?: Subscription;
  223. private examLoadRequest?: Subscription;
  224. private examAttemptStamp = '';
  225. private examLogKey = '';
  226. private examAnswerId: string | number | null = null;
  227. readonly previousExam = signal<SourceItem>({});
  228. readonly questions = signal<ExamQuestion[]>([]);
  229. readonly answers = signal<ExamAnswer[]>([]);
  230. readonly timer = signal(10);
  231. readonly examScore = signal(0);
  232. readonly icons = {
  233. Activity,
  234. BookOpen,
  235. BrainCircuit,
  236. Check,
  237. CheckCheck,
  238. ChevronLeft,
  239. ChevronRight,
  240. CircleHelp,
  241. Clock3,
  242. Flag,
  243. Headphones,
  244. Library,
  245. Play,
  246. RefreshCw,
  247. RotateCcw,
  248. Star,
  249. Trash2,
  250. Volume2,
  251. X,
  252. };
  253. readonly antiForgetChart = {
  254. forgettingPath: 'M 26 12 C 38 60 82 88 304 95',
  255. learningPath: 'M 26 98 C 31 80 35 68 40 61 C 47 50 58 43 68 40 C 81 33 95 29 110 27 C 132 22 156 19 179 19 C 210 18 244 17 276 17 C 286 17 296 17 304 17',
  256. continuationPath: 'M 276 12 C 284 15 294 16 304 16',
  257. reviewEvents: [
  258. { day: 2, x: 40, y: 61, path: 'M 26 12 C 30 30 34 49 40 61' },
  259. { day: 4, x: 68, y: 40, path: 'M 40 12 C 47 22 57 35 68 40' },
  260. { day: 7, x: 110, y: 27, path: 'M 68 12 C 79 17 94 24 110 27' },
  261. { day: 12, x: 179, y: 19, path: 'M 110 12 C 128 15 155 19 179 19' },
  262. { day: 19, x: 276, y: 17, path: 'M 179 12 C 205 15 244 17 276 17' },
  263. ],
  264. days: Array.from({ length: 21 }, (_, index) => ({ day: index + 1, x: 26 + index * 13.9 })),
  265. };
  266. readonly current = computed(() => this.words()[this.currentIndex()] ?? null);
  267. readonly completedSelectionWords = computed(() => this.words().filter((word) => this.selectionWordCompleted(word)));
  268. readonly pendingSelectionWords = computed(() => this.words().filter((word) => !this.selectionWordCompleted(word)));
  269. readonly learnedNewWords = computed(() => this.words().filter((word) => this.newWordLearned(word)));
  270. readonly unlearnedNewWords = computed(() => this.words().filter((word) => !this.newWordLearned(word)));
  271. readonly visibleNewWords = computed(() => this.activeSelectionBucket() === 'completed' ? this.learnedNewWords() : this.unlearnedNewWords());
  272. readonly newWordPageCount = computed(() => Math.max(1, Math.ceil(this.selectionTotal() / this.newWordPageSize)));
  273. readonly allVisibleNewWordsSelected = computed(() => {
  274. const bulk = this.newWordBulkSelection();
  275. return Boolean(bulk && bulk.bucket === this.activeSelectionBucket() && bulk.count === this.bulkSelectCount()
  276. && bulk.ids.length && bulk.ids.every(id => this.selected().has(id)));
  277. });
  278. readonly newlyKnownWords = computed(() => (this.isRefineSelectionPage ? this.courseSelectionCache() : this.words()).filter((word) => this.selectionAssessment()[word.id] === 'known'));
  279. readonly selectionActionLabel = computed(() => {
  280. if (this.knownSaveRetry()) return '重试保存';
  281. const hasLearningWords = this.selected().size > 0;
  282. const hasKnownWords = this.newlyKnownWords().length > 0;
  283. if (hasLearningWords && hasKnownWords) return '保存并开始学习';
  284. if (hasKnownWords) return '保存识词结果';
  285. return '开始学习';
  286. });
  287. readonly currentQuestion = computed(() => this.questions()[this.currentIndex()] ?? null);
  288. readonly wordPreviewPageCount = computed(() => Math.max(1, Math.ceil(this.wordPreviewTotal() / this.wordPreviewPageSize)));
  289. readonly wordPreviewPages = computed(() => {
  290. const pageCount = this.wordPreviewPageCount();
  291. if (pageCount <= 3) return Array.from({ length: pageCount }, (_, index) => index + 1);
  292. const start = Math.min(Math.max(1, this.wordPreviewPage() - 1), pageCount - 2);
  293. return Array.from({ length: 3 }, (_, index) => start + index);
  294. });
  295. readonly wordPreviewRangeStart = computed(() => this.wordPreviewTotal()
  296. ? ((this.wordPreviewPage() - 1) * this.wordPreviewPageSize) + 1
  297. : 0);
  298. readonly wordPreviewRangeEnd = computed(() => Math.min(this.wordPreviewPage() * this.wordPreviewPageSize, this.wordPreviewTotal()));
  299. readonly memoryStudents = computed(() => {
  300. if(this.reviewPageData()?.students)return this.reviewPageData()!.students!.map(s=>({id:String(s.id),name:s.name,taskCount:s.taskCount}));
  301. const students = new Map<string, MemoryStudentOption>();
  302. for (const item of this.calendarItems()) {
  303. const id = String(item['yhid'] ?? '').trim();
  304. if (!id) continue;
  305. const current = students.get(id);
  306. if (current) current.taskCount += 1;
  307. else students.set(id, { id, name: this.calendarStudent(item) || `学员 ${id}`, taskCount: 1 });
  308. }
  309. return [...students.values()].sort((left, right) => left.name.localeCompare(right.name, 'zh-CN'));
  310. });
  311. readonly memorySelectedStudentName = computed(() => this.memoryStudents().find((student) => student.id === this.memoryStudentId())?.name || '全部学员');
  312. readonly reviewPageData=signal<ReviewPage|null>(null); readonly reviewListPage=signal(1);
  313. readonly memoryFilteredItems = computed(() => {
  314. const studentId = this.memoryStudentId();
  315. return studentId ? this.calendarItems().filter((item) => String(item['yhid'] ?? '') === studentId) : this.calendarItems();
  316. });
  317. readonly memoryView = computed(() => buildAntiForgetView(this.memoryFilteredItems()));
  318. readonly memorySummary = computed(() => this.memoryView().summary);
  319. readonly memoryCalendar=computed(()=>reviewCalendar(this.reviewPageData()?.dates||[],this.memoryMonth(),this.memorySelectedDate()));
  320. readonly memorySelectedTasks = computed(() => this.reviewScope() === 'overdue' ? this.memoryFilteredItems() : antiForgetTasksOnDate(this.memoryFilteredItems(), this.memorySelectedDate()));
  321. readonly memorySelectedLabel = computed(() => {
  322. const value = this.memorySelectedDate();
  323. if (!value) return '';
  324. const [year, month, day] = value.split('-').map(Number);
  325. return new Intl.DateTimeFormat('zh-CN', { month: 'long', day: 'numeric', weekday: 'short' }).format(new Date(year, month - 1, day, 12));
  326. });
  327. readonly memoryTotalCount = computed(() => this.reviewPageData()?.summary.total||0);
  328. readonly memoryCompletedCount = computed(() => this.reviewPageData()?.summary.completed||0);
  329. readonly memoryDueCount = computed(() => this.reviewPageData()?.summary.due||0);
  330. readonly memoryProgress=computed(()=>{const s=this.reviewPageData()?.summary;return s?.total?Math.round(s.completed/s.total*100):0;});
  331. readonly progress = computed(() => {
  332. const total = this.isMatchingPage ? this.words().length : this.words().length || this.questions().length;
  333. if (!total) return 0;
  334. if (this.isMatchingPage) return Math.round(((total - this.matchLeft().length) / total) * 100);
  335. return Math.round(((this.currentIndex() + (this.completed() ? 1 : 0)) / total) * 100);
  336. });
  337. private readonly route = inject(ActivatedRoute);
  338. private readonly router = inject(Router);
  339. private readonly api = inject(ApiService);
  340. private readonly session = inject(SessionService);
  341. private readonly todayReviews = inject(TeacherTodayReviewService);
  342. private readonly platform = inject(PlatformService);
  343. private readonly listeningPool = inject(ListeningPoolService);
  344. private readonly wordAudio = inject(WordAudioService);
  345. readonly audioPreparing = signal(false);
  346. readonly pointReadAudio = signal<{ wordId: string; phase: 'loading' | 'playing'; since: number } | null>(null);
  347. private audioRequest = 0;
  348. private readonly wordPreviewPageSize = 30;
  349. private examTimer: ReturnType<typeof setInterval> | null = null;
  350. private antiStartedAt = Date.now();
  351. private calendarRequest?: Subscription;
  352. private choiceOptionsRequest?: Subscription;
  353. private choiceOptionsVersion = 0;
  354. private outsideChoicePool: Word[] | null = null;
  355. ngOnInit(): void {
  356. if (isTeacherLedLearningPath(this.meta.path) && !this.isReadOnlyWordView && !this.isReadOnlySelectionPage && !this.canStartPointReading && !this.isNewWordSelfStudyStage) {
  357. this.platform.toast('点读学习由陪练老师在训练时发起', 'error');
  358. void this.router.navigateByUrl('/pages/home/cart');
  359. return;
  360. }
  361. if (this.isCatalogPage && Number(this.session.user()?.groupId) === 1) {
  362. void this.router.navigateByUrl('/pages/home/cart');
  363. return;
  364. }
  365. if(this.isCalendarPage){
  366. this.reviewScope.set(this.query('scope')==='overdue'?'overdue':'');
  367. this.memorySelectedDate.set(this.query('date')||this.dateOnly());
  368. this.memoryStudentId.set(this.query('studentId')||'');
  369. this.reviewListPage.set(Math.max(1,Number(this.query('page'))||1));
  370. const [y,m]=this.memorySelectedDate().split('-').map(Number);this.memoryMonth.set(new Date(y,m-1,1,12));
  371. }
  372. if(this.isRecordPage)this.reviewReturn=history.state?.reviewReturn||{date:this.query('date')||this.dateOnly()};
  373. if (this.isCoachWordbookSelection) this.loadWordbookStudents();
  374. else this.load();
  375. }
  376. ngOnDestroy(): void {
  377. this.stopWordPlayback();
  378. this.calendarRequestId++;this.calendarRequest?.unsubscribe();this.selectionRequest?.unsubscribe();
  379. this.wordbookStudentsRequest?.unsubscribe();
  380. this.choiceOptionsVersion++;
  381. this.choiceOptionsRequest?.unsubscribe();
  382. this.stopExamTimer();
  383. this.examHistoryRequest?.unsubscribe();this.examLoadRequest?.unsubscribe();
  384. }
  385. get isNodePage(): boolean {
  386. return ['pages/stu/index', 'pages/stu/stu_list'].includes(this.meta.path);
  387. }
  388. get isCatalogPage(): boolean {
  389. return this.meta.path === 'pages/stu/index';
  390. }
  391. get isUnitListPage(): boolean {
  392. return this.meta.path === 'pages/stu/stu_list';
  393. }
  394. get isSelectionPage(): boolean {
  395. return ['pages/stu/stu_abc', 'pages/his/his_words', 'pages/member/starshop'].includes(this.meta.path);
  396. }
  397. get isNewWordSelectionPage(): boolean {
  398. return this.meta.path === 'pages/member/starshop';
  399. }
  400. get isCoachWordbookSelection(): boolean {
  401. return this.isNewWordSelectionPage && this.canStartPointReading;
  402. }
  403. private get coachWordbookStudentId(): number {
  404. if (!this.canStartPointReading) return 0;
  405. if (this.isCoachWordbookSelection) return this.wordbookStudentId();
  406. if (!this.isStudyListPage && !this.isMatchingPage && !this.isListeningPage && !this.isSpellingPage) return 0;
  407. const id = Number(this.query('wordbookStudentId'));
  408. return Number.isSafeInteger(id) && id > 0 ? id : 0;
  409. }
  410. loadWordbookStudents(more = false): void {
  411. if (!this.isCoachWordbookSelection || this.wordbookStudentsLoading()) return;
  412. const requestedPage = more ? this.wordbookStudentsPage + 1 : 1;
  413. const preferred = Number(this.query('wordbookStudentId')) || 0;
  414. this.wordbookStudentsLoading.set(true);
  415. this.wordbookStudentsError.set('');
  416. this.wordbookStudentsRequest = this.api.get<WordbookStudent[]>('e_user_list', {
  417. scope: 'wordbook', cpage: requestedPage, psize: 50, selectedStudentId: preferred,
  418. }).pipe(finalize(() => this.wordbookStudentsLoading.set(false))).subscribe({
  419. next: ({result, page}) => {
  420. this.wordbookStudentsPage = requestedPage;
  421. const students = more ? [...this.wordbookStudents(), ...result] : result;
  422. this.wordbookStudents.set([...new Map(students.map(student => [student.userId, student])).values()]);
  423. this.wordbookStudentsHaveMore.set(requestedPage < Number(page?.pageCount ?? 0));
  424. if (!more) {
  425. const selected = students.find(student => student.userId === preferred) ?? students[0];
  426. if (selected) this.selectWordbookStudent(selected.userId);
  427. }
  428. },
  429. error: (error: ApiError) => this.wordbookStudentsError.set(error.message || '学员名单加载失败,请重试'),
  430. });
  431. }
  432. selectWordbookStudent(id: number): void {
  433. if (this.wordbookStudentId() === id || !this.wordbookStudents().some(student => student.userId === id)) return;
  434. this.wordbookStudentId.set(id);
  435. this.load();
  436. }
  437. get isHistoryWordView(): boolean {
  438. return this.meta.path === 'pages/his/his_words';
  439. }
  440. get isRefineSelectionPage(): boolean {
  441. return this.meta.path === 'pages/stu/stu_abc';
  442. }
  443. get isStudyListPage(): boolean {
  444. return this.meta.path === 'pages/stu/stu_con';
  445. }
  446. get isReadOnlySelectionPage(): boolean {
  447. return !this.canStartPointReading && this.isRefineSelectionPage && this.query('readonly') === '1';
  448. }
  449. get canStartPointReading(): boolean {
  450. return canStartTeacherLedLearning(this.session.groupId());
  451. }
  452. get isNewWordSelfStudyStage(): boolean {
  453. if (Number(this.session.groupId()) !== 1
  454. || !['pages/stu/stu_con', 'pages/stu/stu3', 'pages/stu/stu4', 'pages/stu/stu5'].includes(this.meta.path)
  455. || ['nid', 'nids', 'bindingId', 'orderId'].some((key) => this.query(key))) return false;
  456. return this.storageGet('learn_mode') === 'newword'
  457. && this.parseArray(this.storageGet('choose_newword_learn')).length > 0;
  458. }
  459. get isReadOnlyWordView(): boolean {
  460. if (this.isHistoryWordView) return true;
  461. return !this.canStartPointReading && this.isStudyListPage && this.query('readonly') === '1';
  462. }
  463. get isMatchingPage(): boolean {
  464. return this.meta.path === 'pages/stu/stu3';
  465. }
  466. get isListeningPage(): boolean {
  467. return this.meta.path === 'pages/stu/stu4';
  468. }
  469. get isSpellingPage(): boolean {
  470. return ['pages/stu/stu5', 'pages/stu/pl_stu5'].includes(this.meta.path);
  471. }
  472. get spellingStageSkipped(): boolean {
  473. return this.storageGet('skip_spelling_stage') === true;
  474. }
  475. get canSkipSpellingStage(): boolean {
  476. return this.isSpellingPage && (this.canStartPointReading || this.isNewWordSelfStudyStage);
  477. }
  478. get hasNextWordBatch(): boolean {
  479. const currentPage = Number(this.storageGet('_page_current_learn') ?? 1);
  480. const pages = this.parseArray(this.storageGet('_page_word_orilist'));
  481. return Number.isInteger(currentPage) && currentPage > 0
  482. && Array.isArray(pages[currentPage]) && pages[currentPage].length > 0;
  483. }
  484. get stageActionLabel(): string {
  485. if (this.isMatchingPage) return '进入听音识意';
  486. if (this.isListeningPage && !this.spellingStageSkipped) return '进入组合拼写';
  487. if (this.hasNextWordBatch) return '学习下一组单词';
  488. const mode = String(this.storageGet('learn_mode') ?? '');
  489. if (mode === 'newword' || mode === 'history_word') return '完成学习并返回';
  490. return this.canStartPointReading && !this.query('orderId') ? '保存并结束学习' : '查看学习结果';
  491. }
  492. get canReturnToLearningEntry(): boolean {
  493. return isLearningStage(this.meta.path, this.route.snapshot.queryParamMap);
  494. }
  495. returnToLearningEntry(): void {
  496. const legacyOrderId = this.meta.path === 'pages/stu/pl_end' ? this.query('id') : '';
  497. const url = legacyOrderId ? `/pages/shop/get_order?id=${encodeURIComponent(legacyOrderId)}`
  498. : learningReturnUrl(this.route.snapshot.queryParamMap, history.state?.learningReturnUrl);
  499. void this.router.navigateByUrl(url, { replaceUrl: true });
  500. }
  501. get isReviewPage(): boolean {
  502. return ['pages/stu/stu6', 'pages/stu/pl_end'].includes(this.meta.path);
  503. }
  504. get isCalendarPage(): boolean {
  505. return this.meta.path === 'pages/stu/stu_calendar';
  506. }
  507. get isAntiForgetPage(): boolean {
  508. return this.meta.path === 'pages/stu/stu7';
  509. }
  510. get isRecordPage(): boolean {
  511. return this.meta.path === 'pages/stu/record';
  512. }
  513. get isExamPage(): boolean {
  514. return this.meta.path === 'pages/his/exam';
  515. }
  516. get isReportPage(): boolean {
  517. return this.meta.path === 'pages/stu/stu_ok';
  518. }
  519. get selectionLimit(): number {
  520. if (this.isRefineSelectionPage || this.isNewWordSelectionPage) return 100;
  521. return this.words().length;
  522. }
  523. load(): void {
  524. this.selectionRequest?.unsubscribe();this.selectionPage.set(1);this.selectionTotal.set(0);
  525. this.resetPageState();
  526. this.loading.set(true);
  527. this.error.set('');
  528. this.recordWordless.set(false);
  529. if (this.isReportPage) {
  530. this.loading.set(false);
  531. return;
  532. }
  533. if (this.isNodePage) {
  534. this.loadNodes();
  535. return;
  536. }
  537. if (this.isSelectionPage) {
  538. this.loadSelection();
  539. return;
  540. }
  541. if (this.isCalendarPage) {
  542. this.loadCalendar(true);
  543. return;
  544. }
  545. if (this.isAntiForgetPage) {
  546. this.loadAntiForget();
  547. return;
  548. }
  549. if (this.isRecordPage) {
  550. this.loadRecord();
  551. return;
  552. }
  553. if (this.isExamPage) {
  554. this.loadExam();
  555. return;
  556. }
  557. if (this.meta.path === 'pages/stu/pl_end') {
  558. this.loadPracticeEnd();
  559. return;
  560. }
  561. if (this.meta.path === 'pages/stu/stu6') {
  562. this.loadReviewWords();
  563. return;
  564. }
  565. this.loadStageWords();
  566. }
  567. openNode(node: SourceItem): void {
  568. const id = node['NodeID'] ?? node['Nodeid'] ?? node['ID'] ?? node['id'];
  569. if (this.isCatalogPage) {
  570. void this.router.navigate(['/pages/stu/stu_list'], { queryParams: { nid: id } });
  571. return;
  572. }
  573. if (this.isUnitListPage && !this.canStartPointReading) {
  574. void this.router.navigate(['/pages/stu/stu_abc'], {
  575. queryParams: { nids: id, pnid: this.query('nid'), readonly: 1 },
  576. });
  577. return;
  578. }
  579. this.toggleNode(node);
  580. }
  581. openWordPreviewPage(page: number): void {
  582. const target = Math.min(Math.max(1, page), this.wordPreviewPageCount());
  583. if (target === this.wordPreviewPage() || this.wordPreviewLoading()) return;
  584. const previous = this.wordPreviewPage();
  585. this.wordPreviewPage.set(target);
  586. if (this.isHistoryWordView) {
  587. this.stopWordPlayback();
  588. const start = (target - 1) * this.wordPreviewPageSize;
  589. this.words.set(this.historyPreviewWords.slice(start, start + this.wordPreviewPageSize));
  590. setTimeout(() => document.getElementById('readonly-word-title')?.scrollIntoView({ behavior: 'smooth', block: 'start' }));
  591. return;
  592. }
  593. this.wordPreviewLoading.set(true);
  594. this.loadReadOnlyWords(true, previous);
  595. }
  596. selectCatalogCategory(index: number): void {
  597. if (index === this.catalogCategoryIndex()) return;
  598. this.catalogCategoryIndex.set(index);
  599. this.loadNodes();
  600. }
  601. toggleNode(node: SourceItem): void {
  602. const id = this.nodeId(node);
  603. if (!id) return;
  604. this.selectedNodes.update((current) => {
  605. const next = new Set(current);
  606. if (next.has(id)) next.delete(id); else next.add(id);
  607. return next;
  608. });
  609. }
  610. startNodeSelection(): void {
  611. if (!this.selectedNodes().size) {
  612. this.platform.toast('请选择学习单元', 'error');
  613. return;
  614. }
  615. void this.router.navigate(['/pages/stu/stu_abc'], {
  616. queryParams: {
  617. nids: [...this.selectedNodes()].join(','),
  618. pnid: this.query('nid'),
  619. bindingId: this.query('bindingId'),
  620. orderId: this.query('orderId'),
  621. },
  622. });
  623. }
  624. nodeId(node: SourceItem): string {
  625. return String(node['NodeID'] ?? node['Nodeid'] ?? node['ID'] ?? node['id'] ?? '');
  626. }
  627. nodeTitle(node: SourceItem): string {
  628. return String(node['NodeName'] ?? node['Title'] ?? node['name'] ?? '词库');
  629. }
  630. nodeCount(node: SourceItem): string {
  631. return String(node['ItemCount'] ?? node['Count'] ?? node['count'] ?? '');
  632. }
  633. nodeProgress(node: SourceItem): string {
  634. const total = this.nodeTotal(node);
  635. return total > 0 ? `已学 ${this.nodeLearned(node)}/${total} · 进度 ${this.nodeProgressPercent(node)}%` : '';
  636. }
  637. nodeLearned(node: SourceItem): number { return Math.max(0, Number(node['yx_word'] ?? 0)); }
  638. nodeTotal(node: SourceItem): number { return Math.max(0, Number(node['total'] ?? 0)); }
  639. nodeProgressPercent(node: SourceItem): number {
  640. const total = this.nodeTotal(node);
  641. return total ? Math.min(100, Math.round((this.nodeLearned(node) / total) * 100)) : 0;
  642. }
  643. toggleWord(word: Word): void {
  644. if (this.selectionLocked()) return;
  645. const bulk = this.bulkSelection();
  646. if (this.isRefineSelectionPage && bulk !== null) {
  647. const next = new Set(bulk);
  648. if (next.has(word.id)) next.delete(word.id); else next.add(word.id);
  649. this.bulkSelection.set(next);
  650. return;
  651. }
  652. if (this.isRefineSelectionPage && !this.canRelearnCourseWord(word)) return;
  653. const shouldSelect = !this.selected().has(word.id);
  654. if (!this.setWordSelected(word, shouldSelect) || !this.isRefineSelectionPage) return;
  655. if (shouldSelect) this.setSelectionAssessment(word, 'unknown');
  656. else this.clearSelectionAssessment(word);
  657. }
  658. selectionWordRevealed(word: Word): boolean {
  659. return this.selectionRevealed().has(word.id);
  660. }
  661. wordHistoricallyLearned(word: Word): boolean {
  662. return Number(word['w_learned'] ?? 0) > 0;
  663. }
  664. newWordLearned(word: Word): boolean {
  665. return Number(word['xxcs'] ?? 0) >= 2;
  666. }
  667. selectionWordCompleted(word: Word): boolean {
  668. return this.wordHistoricallyLearned(word) || this.selectionAssessment()[word.id] === 'known';
  669. }
  670. courseWordPass(word: Word): number {
  671. return this.selectionAssessment()[word.id] === 'known' ? this.recognizedTab : this.savedCoursePass(word);
  672. }
  673. private savedCoursePass(word: Word): number {
  674. if (word['recognized'] === true) return this.recognizedTab;
  675. return Math.min(3, Math.max(0, Math.floor(Number(word['w_learned']) || 0)));
  676. }
  677. coursePassCount(pass: number): number {
  678. const counts = this.coursePassCounts();
  679. if (!counts) return 0;
  680. const adjustment = this.newlyKnownWords().reduce((total, word) => {
  681. const before = this.savedCoursePass(word), after = this.recognizedTab;
  682. return total + Number(after === pass) - Number(before === pass);
  683. }, 0);
  684. return Math.max(0, counts[pass] + adjustment);
  685. }
  686. canRelearnCourseWord(word: Word): boolean {
  687. return !this.isReadOnlySelectionPage && this.courseWordPass(word) < 3;
  688. }
  689. get coursePassHint(): string {
  690. const pass = this.coursePass();
  691. if (pass === 0) return this.isReadOnlySelectionPage ? '这些单词尚未完成第一遍学习,点击可查看释义。' : '可直接选择“认识”或“不认识”,也可全选本页后批量判断。';
  692. if (pass === this.recognizedTab) return '这些单词已标为认识,可查看释义和听读音。';
  693. if (pass === 3) return '这些单词已完成三遍学习,可查看和听读音。';
  694. return this.isReadOnlySelectionPage ? `这些单词已学${pass}遍,可由老师选词继续学习。` : `选择单词开始第${pass === 1 ? '二' : '三'}遍学习,也可全选本页批量判断。`;
  695. }
  696. selectCoursePass(pass: number): void {
  697. if (this.selectionLocked() || pass === this.coursePass() || pass < 0 || pass >= this.coursePassTabs.length) return;
  698. this.stopWordPlayback();
  699. this.selectionRevealed.set(new Set());
  700. this.bulkSelection.set(null);
  701. this.courseSelectionNeedsRebase = false;
  702. this.selectionRequest?.unsubscribe();
  703. this.coursePass.set(pass);
  704. this.selectionPage.set(1);
  705. this.words.set([]);
  706. this.selectionTotal.set(0);
  707. this.loadSelection();
  708. }
  709. selectionCompletionLabel(word: Word): string {
  710. if (this.courseWordPass(word) === this.recognizedTab) return '已认识';
  711. return this.wordHistoricallyLearned(word) ? `已学${this.courseWordPass(word)}遍` : '本次已认识';
  712. }
  713. revealSelectionWord(word: Word): void {
  714. if (this.isReadOnlySelectionPage) {
  715. this.selectionRevealed.update(current => {
  716. const next = new Set(current);
  717. if (next.has(word.id)) next.delete(word.id); else next.add(word.id);
  718. return next;
  719. });
  720. return;
  721. }
  722. this.play(word);
  723. }
  724. recognizeWord(word: Word): void {
  725. if (this.selectionLocked() || this.selectionLoading() || !this.canRelearnCourseWord(word)) return;
  726. this.markWordKnown(word);
  727. this.startSelected(false);
  728. }
  729. markWordKnown(word: Word): void {
  730. if (this.selectionLocked() || !this.canRelearnCourseWord(word) || this.selectionAssessment()[word.id] === 'known') return;
  731. this.setWordSelected(word, false);
  732. this.setSelectionAssessment(word, 'known');
  733. this.bulkSelection.update(current => current === null ? null : new Set([...current].filter(id => id !== word.id)));
  734. }
  735. markWordUnknown(word: Word): void {
  736. if (this.selectionLocked() || this.isReadOnlySelectionPage || this.savedCoursePass(word) >= 3) return;
  737. if (this.setWordSelected(word, true)) {
  738. this.setSelectionAssessment(word, 'unknown');
  739. this.bulkSelection.update(current => current === null ? null : new Set([...current].filter(id => id !== word.id)));
  740. }
  741. }
  742. courseWordChecked(word: Word): boolean {
  743. return (this.bulkSelection() ?? this.selected()).has(word.id);
  744. }
  745. toggleBulkSelection(): void {
  746. if (this.selectionLocked() || this.selectionLoading() || this.isReadOnlySelectionPage || this.coursePass() >= 3) return;
  747. this.bulkSelection.set(this.bulkSelection() === null ? new Set(this.bulkCandidates().slice(0, this.bulkSelectCount()).map(word => word.id)) : null);
  748. }
  749. changeBulkSelectCount(count: number): void {
  750. if (this.selectionLocked() || this.selectionLoading() || ![20, 50, 100].includes(count)) return;
  751. this.bulkSelectCount.set(count);
  752. if (this.bulkSelection() !== null) this.bulkSelection.set(null);
  753. }
  754. applyBulkAssessment(assessment: 'known' | 'unknown'): void {
  755. if (this.selectionLocked() || this.isReadOnlySelectionPage || this.coursePass() >= 3) return;
  756. const checked = this.bulkSelection();
  757. if (!checked?.size) return;
  758. const candidates = this.bulkCandidates();
  759. const chosen = candidates.filter(word => checked.has(word.id));
  760. if (!chosen.length) return;
  761. if (assessment === 'unknown') {
  762. const combined = new Set([...this.selected(), ...chosen.map(word => word.id)]);
  763. if (combined.size > this.selectionLimit) {
  764. this.platform.toast(`本轮最多学习 ${this.selectionLimit} 个单词,请减少勾选后重试`, 'error');
  765. return;
  766. }
  767. this.bulkSelection.set(null);
  768. for (const word of chosen) this.markWordUnknown(word);
  769. this.startSelected();
  770. return;
  771. }
  772. const remaining = candidates.filter(word => !checked.has(word.id));
  773. this.bulkSelection.set(null);
  774. for (const word of chosen) this.markWordKnown(word);
  775. const canContinue = remaining.length === 0 || (candidates.length <= this.bulkSelectCount()
  776. && new Set([...this.selected(), ...remaining.map(word => word.id)]).size <= Math.min(30, this.bulkSelectCount()));
  777. if (canContinue) for (const word of remaining) this.markWordUnknown(word);
  778. this.startSelected(canContinue, canContinue && this.selected().size === 0);
  779. }
  780. toggleAllWords(): void {
  781. if (this.selectionLocked() || this.selectionLoading() || this.isReadOnlySelectionPage) return;
  782. if (this.isNewWordSelectionPage) {
  783. const previous = this.newWordBulkSelection(), bucket = this.activeSelectionBucket(), count = this.bulkSelectCount();
  784. if (this.allVisibleNewWordsSelected() && previous) {
  785. this.selected.update(current => new Set([...current].filter(id => !previous.ids.includes(id))));
  786. this.newWordBulkSelection.set(null);
  787. return;
  788. }
  789. const uid = this.isCoachWordbookSelection ? this.wordbookStudentId() : this.session.user()?.userId;
  790. if (!uid) return;
  791. const source = this.legacyNewWords
  792. ? of(this.legacyNewWords.filter(word => this.newWordLearned(word) === (bucket === 'completed')).slice(0, count))
  793. : this.api.get<unknown>('e_words_list', {uid, cpage: 1, psize: count, learningStatus: bucket})
  794. .pipe(map(({result}) => this.findList(result).map(item => this.toNewWord(item)).filter(word => word.word).slice(0, count)));
  795. this.selectionLoading.set(true);
  796. this.selectionRequest = source.pipe(finalize(() => this.selectionLoading.set(false))).subscribe({
  797. next: words => {
  798. const next = new Set(this.selected());
  799. if (previous?.bucket === bucket) for (const id of previous.ids) next.delete(id);
  800. const ids: string[] = [];
  801. for (const word of words) {
  802. if (!next.has(word.id) && next.size >= this.selectionLimit) continue;
  803. next.add(word.id);ids.push(word.id);this.newWordSelectionCache.set(word.id, word);
  804. }
  805. this.selected.set(next);
  806. this.newWordBulkSelection.set({bucket, count, ids});
  807. if (ids.length < words.length) this.platform.toast(`本次最多选择 ${this.selectionLimit} 个单词`, 'error');
  808. },
  809. error: () => this.platform.toast('选词失败,请重试', 'error'),
  810. });
  811. return;
  812. }
  813. if (this.selected().size) {
  814. this.selected.set(new Set());
  815. return;
  816. }
  817. this.selected.set(new Set(this.words().slice(0, Math.min(this.bulkSelectCount(), this.selectionLimit)).map((word) => word.id)));
  818. }
  819. startSelected(continueLearning = true, openKnownPass = false): void {
  820. if (this.submitting() || this.selectionLoading() || this.isReadOnlySelectionPage) return;
  821. if (this.isCoachWordbookSelection && !this.wordbookStudentId()) return;
  822. if (this.knownSaveRetry() && this.knownSaveContinuation) {
  823. ({ continueLearning, openKnownPass } = this.knownSaveContinuation);
  824. }
  825. const available = this.isNewWordSelectionPage ? [...this.newWordSelectionCache.values()] : this.isRefineSelectionPage ? this.courseSelectionCache().filter(word => this.canRelearnCourseWord(word) && this.selectionAssessment()[word.id] !== 'known') : this.words();
  826. const chosen = available
  827. .filter((word) => this.selected().has(word.id));
  828. const newlyKnown = this.newlyKnownWords();
  829. if (!chosen.length && !newlyKnown.length) {
  830. this.platform.toast(this.isRefineSelectionPage ? '请先判断单词是否认识,或选择要学习的单词' : '请先选择要学习的单词', 'error');
  831. return;
  832. }
  833. if (this.meta.path === 'pages/stu/stu_abc') {
  834. const student = this.session.student() ?? this.session.user();
  835. if (!student?.userId) {
  836. this.platform.toast('课程信息错误', 'error');
  837. return;
  838. }
  839. this.submitting.set(true);
  840. this.knownSaveContinuation = { continueLearning, openKnownPass };
  841. this.saveWordProgress(newlyKnown, student, 'recognized').subscribe({
  842. next: () => {
  843. this.knownSaveRetry.set(false);
  844. this.knownSaveContinuation = null;
  845. this.submitting.set(false);
  846. if (continueLearning && chosen.length) {
  847. this.beginSelectedFlow(chosen, '');
  848. return;
  849. }
  850. if (openKnownPass) this.selectCoursePass(this.recognizedTab);
  851. this.platform.toast('识词结果已保存', 'success');
  852. },
  853. error: (error: ApiError) => {
  854. this.knownSaveRetry.set(true);
  855. this.submitting.set(false);
  856. this.platform.toast(`${error.message};已保存的批次会保留,请点击“重试保存”完成核对`, 'error');
  857. },
  858. });
  859. return;
  860. }
  861. this.beginSelectedFlow(chosen, this.meta.path === 'pages/member/starshop' ? 'newword' : 'history_word');
  862. }
  863. deleteSelectedNewWords(): void {
  864. if (this.isCoachWordbookSelection) return;
  865. const chosen = [...this.newWordSelectionCache.values()].filter((word) => this.selected().has(word.id));
  866. if (!chosen.length) {
  867. this.platform.toast('请选择单词', 'error');
  868. return;
  869. }
  870. const owner = Number(this.session.user()?.groupId) === 3 ? this.session.student() : this.session.user();
  871. this.api.post('e_add_words', {
  872. uid: owner?.userId,
  873. wordsId: chosen.map((word) => word.wordId).join(','),
  874. ifnew: 0,
  875. kcid: this.query('kcid'),
  876. }).subscribe({
  877. next: () => {
  878. this.platform.toast('已删除', 'success');
  879. this.load();
  880. },
  881. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  882. });
  883. }
  884. private stopWordPlayback(): void {
  885. this.audioRequest++;
  886. this.platform.stopAudio();
  887. this.audioPreparing.set(false);
  888. this.historyAudioWordId.set('');
  889. this.pointReadAudio.set(null);
  890. }
  891. async play(word = this.current()): Promise<void> {
  892. if (this.isReadOnlySelectionPage || (this.isReadOnlyWordView && !this.isHistoryWordView) || !word) return;
  893. const selection = this.isRefineSelectionPage || this.isNewWordSelectionPage;
  894. const pointReading = selection || this.isStudyListPage;
  895. const pending = this.pointReadAudio();
  896. // Study taps may replay once sound starts. On the selection list let the word finish first.
  897. if (pointReading && pending?.wordId === word.id && (selection || pending.phase === 'loading')
  898. && (this.audioPreparing() || Date.now() - pending.since < 8000)) return;
  899. if (pointReading) this.pointReadAudio.set({ wordId: word.id, phase: 'loading', since: Date.now() });
  900. const request = ++this.audioRequest, focusedWord = this.current(), step = this.studyStep();
  901. const active = () => request === this.audioRequest && this.current() === focusedWord && this.studyStep() === step;
  902. this.audioPreparing.set(false);
  903. if (this.isHistoryWordView) this.historyAudioWordId.set(word.id);
  904. const finishPlayback = () => {
  905. this.historyAudioWordId.set('');
  906. if (pointReading) this.pointReadAudio.set(null);
  907. };
  908. const playAudio = async (url: string, silentFailure = false) => {
  909. const playback = this.isHistoryWordView || this.isSelectionPage || this.isStudyListPage
  910. ? this.platform.play(url, silentFailure, {
  911. onEnded: () => {
  912. if (!active()) return;
  913. if (this.isHistoryWordView) this.historyWordRevealed.update(current => new Set(current).add(word.id));
  914. else if (!this.isStudyListPage) this.selectionRevealed.update(current => new Set(current).add(word.id));
  915. finishPlayback();
  916. },
  917. onError: () => {
  918. if (!active()) return;
  919. finishPlayback();
  920. this.platform.toast('音频播放中断,请再点一次单词重试', 'error');
  921. },
  922. })
  923. : this.platform.play(url, silentFailure);
  924. this.prepareWordAudio(word);
  925. const status = await playback;
  926. if (active() && pointReading && status === 'played' && this.pointReadAudio()) {
  927. this.pointReadAudio.set({ wordId: word.id, phase: 'playing', since: Date.now() });
  928. }
  929. return status;
  930. };
  931. const original = word.audio?.trim();
  932. if (original) {
  933. const status = await playAudio(this.wordAudioUrl(original), true);
  934. if (!active()) return;
  935. if (status !== 'failed') {
  936. if (status !== 'played') finishPlayback();
  937. return;
  938. }
  939. } else this.platform.stopAudio();
  940. this.audioPreparing.set(true);
  941. if (this.isHistoryWordView) this.historyAudioWordId.set(word.id);
  942. try {
  943. const url = await this.wordAudio.ensure(word.wordId, !!original);
  944. if (!active()) return;
  945. word.audio = url;
  946. if (pointReading) {
  947. this.audioPreparing.set(false);
  948. this.pointReadAudio.set({ wordId: word.id, phase: 'loading', since: Date.now() });
  949. }
  950. if (!pointReading && original && this.wordAudioUrl(original) === this.wordAudioUrl(url)) {
  951. finishPlayback();
  952. this.platform.toast('音频暂时无法播放,请检查网络后重试', 'error');
  953. return;
  954. }
  955. const status = await playAudio(this.wordAudioUrl(url));
  956. if (active() && status !== 'played') finishPlayback();
  957. } catch (error) {
  958. if (active()) {
  959. finishPlayback();
  960. this.platform.toast(error instanceof Error ? error.message : '读音暂时不可用,请再点喇叭重试', 'error');
  961. }
  962. } finally {
  963. if (request === this.audioRequest) this.audioPreparing.set(false);
  964. }
  965. }
  966. toggleRecordAnswer(word: Word): void {
  967. this.recordRevealed.update((current) => {
  968. const next = new Set(current);
  969. if (next.has(word.id)) next.delete(word.id);
  970. else next.add(word.id);
  971. return next;
  972. });
  973. this.seen.update((current) => new Set(current).add(word.id));
  974. this.play(word);
  975. }
  976. revealStudyMeaning(word: Word): void {
  977. if (this.studyStep() === 3) return;
  978. this.studyMeaningRevealed.update(current => new Set(current).add(word.id));
  979. }
  980. repeatWord(word: Word, index: number): void {
  981. if (this.studyMeaningRevealed().has(word.id)) {
  982. this.studyMeaningRevealed.update(current => {
  983. const revealed = new Set(current);
  984. revealed.delete(word.id);
  985. return revealed;
  986. });
  987. }
  988. const count = this.repetitions()[word.id] ?? 0;
  989. if (this.studyStep() === 1 && index > 0) {
  990. const previous = this.words()[index - 1];
  991. if ((this.repetitions()[previous.id] ?? 0) < 3) {
  992. this.platform.toast('前面还有没读完的单词', 'error');
  993. return;
  994. }
  995. }
  996. this.play(word);
  997. if (count < 3) {
  998. this.repetitions.update((value) => ({ ...value, [word.id]: count + 1 }));
  999. }
  1000. if (this.words().every((item) => (this.repetitions()[item.id] ?? 0) >= 3)) {
  1001. this.finishStudyRound();
  1002. }
  1003. }
  1004. shuffleStudyWords(): void {
  1005. this.stopWordPlayback();
  1006. this.selectionRevealed.set(new Set());
  1007. this.words.set(shuffledStudy(this.words()));
  1008. this.prepareWordAudio(this.words()[0]);
  1009. this.repetitions.set({});
  1010. this.studyMeaningRevealed.set(new Set());
  1011. }
  1012. skipStudyList(): void {
  1013. this.navigateStage('/pages/stu/stu3');
  1014. }
  1015. chooseMatch(side: 'left' | 'right', word: Word): void {
  1016. if (side === 'left') {
  1017. this.leftChoice.set(word.id);
  1018. this.play(word);
  1019. } else {
  1020. this.rightChoice.set(word.id);
  1021. }
  1022. const left = side === 'left' ? word.id : this.leftChoice();
  1023. const right = side === 'right' ? word.id : this.rightChoice();
  1024. if (!left || !right) return;
  1025. if (left !== right) {
  1026. this.platform.toast('答错了,请再试一次', 'error');
  1027. this.leftChoice.set('');
  1028. this.rightChoice.set('');
  1029. return;
  1030. }
  1031. this.platform.playEffect('success');
  1032. this.matchLeft.update((items) => items.filter((item) => item.id !== left));
  1033. this.matchRight.update((items) => items.filter((item) => item.id !== right));
  1034. this.leftChoice.set('');
  1035. this.rightChoice.set('');
  1036. if (this.matchLeft().length === 0) this.completed.set(true);
  1037. }
  1038. chooseMeaning(option: Word): void {
  1039. if (this.choicesLoading() || this.choiceOptions().length !== 4 || this.completed() || !this.choiceOptions().some(w => w.id === option.id)) return;
  1040. const word = this.current();
  1041. if (!word) return;
  1042. if (option.id !== word.id) {
  1043. this.platform.playEffect('error');
  1044. this.platform.toast('答错了,请重新听一遍', 'error');
  1045. this.play(word);
  1046. return;
  1047. }
  1048. this.correct.update((value) => value + 1);
  1049. this.platform.playEffect('success');
  1050. if (this.currentIndex() >= this.words().length - 1) {
  1051. this.completed.set(true);
  1052. return;
  1053. }
  1054. this.currentIndex.update((value) => value + 1);
  1055. void this.play();
  1056. this.prepareChoiceOptions();
  1057. }
  1058. spellLetter(index: number): void {
  1059. if (this.spellingCorrect() || this.letters()[index]?.used) return;
  1060. this.letters.update((items) => items.map((item, itemIndex) => itemIndex === index ? { ...item, used: true } : item));
  1061. const next = this.assembled() + this.letters()[index].value;
  1062. this.assembled.set(next);
  1063. const word = this.current();
  1064. if (!word || next.length < word.word.length) return;
  1065. if (next.toLowerCase() === word.word.toLowerCase()) {
  1066. this.spellingCorrect.set(true);
  1067. this.correct.update((value) => value + 1);
  1068. this.platform.playEffect('success');
  1069. this.platform.toast('拼写正确', 'success');
  1070. return;
  1071. }
  1072. this.platform.playEffect('error');
  1073. this.platform.toast('拼写错了,再试一次', 'error');
  1074. this.prepareSpelling();
  1075. }
  1076. resetSpelling(): void {
  1077. this.prepareSpelling();
  1078. }
  1079. nextSpellingWord(): void {
  1080. if (!this.spellingCorrect()) {
  1081. this.platform.toast('请先完成当前单词', 'error');
  1082. return;
  1083. }
  1084. if (this.currentIndex() >= this.words().length - 1) {
  1085. this.completed.set(true);
  1086. return;
  1087. }
  1088. this.currentIndex.update((value) => value + 1);
  1089. this.prepareSpelling();
  1090. this.play();
  1091. }
  1092. skipPracticeStage(): void {
  1093. if ((!this.isMatchingPage && !this.isListeningPage) || this.completed() || this.submitting()) return;
  1094. this.completed.set(true);
  1095. this.continueAfterStage();
  1096. }
  1097. skipSpellingStage(): void {
  1098. if (!this.canSkipSpellingStage || this.completed() || this.submitting()) return;
  1099. this.storageSet('skip_spelling_stage', true);
  1100. this.completed.set(true);
  1101. this.continueAfterStage();
  1102. }
  1103. continueAfterStage(): void {
  1104. if (this.submitting() || !this.completed()) return;
  1105. if (this.isMatchingPage) {
  1106. this.completed.set(false);
  1107. this.navigateStage('/pages/stu/stu4');
  1108. } else if (this.isListeningPage) {
  1109. this.completed.set(false);
  1110. if (this.spellingStageSkipped) this.finishSpellingFlow();
  1111. else this.navigateStage(this.canStartPointReading ? '/pages/stu/pl_stu5' : '/pages/stu/stu5');
  1112. } else if (this.isSpellingPage) {
  1113. this.finishSpellingFlow();
  1114. }
  1115. }
  1116. reviewValue(word: Word): 0 | 1 | 2 {
  1117. return this.reviewState()[word.id] ?? 0;
  1118. }
  1119. markReview(word: Word, state: 1 | 2): void {
  1120. this.reviewState.update((value) => ({ ...value, [word.id]: state }));
  1121. if (this.query('orderId')) this.storageSet('roundReview:' + this.storageGet('batchId'), this.reviewState());
  1122. }
  1123. markAllKnown(): void {
  1124. const allKnown = this.words().every((word) => this.reviewValue(word) === 1);
  1125. const next: Record<string, 0 | 1 | 2> = {};
  1126. for (const word of this.words()) next[word.id] = allKnown ? 0 : 1;
  1127. this.reviewState.set(next);
  1128. if (this.query('orderId')) this.storageSet('roundReview:' + this.storageGet('batchId'), next);
  1129. }
  1130. reviewCount(state: 1 | 2): number {
  1131. return this.words().filter((word) => this.reviewValue(word) === state).length;
  1132. }
  1133. submitReview(continueLearning = false): void {
  1134. if (this.submitting() || !this.words().length) return;
  1135. if (this.words().some((word) => this.reviewValue(word) === 0)) {
  1136. this.platform.toast('请为每个单词选择掌握情况', 'error');
  1137. return;
  1138. }
  1139. if (this.meta.path === 'pages/stu/pl_end') {
  1140. this.submitPracticeEnd(continueLearning);
  1141. return;
  1142. }
  1143. this.saveLearningRecord();
  1144. }
  1145. toggleSeen(word: Word): void {
  1146. this.revealed.set(!this.revealed());
  1147. this.seen.update((current) => new Set(current).add(word.id));
  1148. this.play(word);
  1149. this.updateAntiProgress(word);
  1150. if (this.seen().size === this.words().length) {
  1151. this.platform.toast(`已完成 ${this.words().length} 个单词的复习`, 'success');
  1152. }
  1153. }
  1154. joinAntiWords(): void {
  1155. const chosen = this.words().filter((word) => this.selected().has(word.id));
  1156. if (!chosen.length) {
  1157. this.platform.toast('请选择需要加入生词本的单词', 'error');
  1158. return;
  1159. }
  1160. const existing = this.parseArray(this.myNewWords()['scnr']);
  1161. const combined = new Map<string, SourceItem>();
  1162. for (const item of existing) combined.set(String(item['GeneralID'] ?? ''), item);
  1163. for (const word of chosen) {
  1164. combined.set(word.wordId, { GeneralID: word.wordId, Title: word.word, check: this.reviewValue(word), gldy: word['gldy'] });
  1165. }
  1166. const user = this.session.user();
  1167. const content: SourceItem = {
  1168. ModelID: 55,
  1169. nodeId: 255,
  1170. inputer: user?.honeyName,
  1171. status: 99,
  1172. Hits: combined.size,
  1173. title: user?.honeyName,
  1174. };
  1175. let action = 'content_add';
  1176. if (this.myNewWords()['GeneralID']) {
  1177. content['GeneralID'] = this.myNewWords()['GeneralID'];
  1178. action = 'content_update';
  1179. }
  1180. this.api.post(action, {
  1181. content: JSON.stringify(content),
  1182. addon: JSON.stringify({ UserID: user?.userId, scnr: JSON.stringify([...combined.values()]) }),
  1183. }).subscribe({
  1184. next: () => this.platform.toast('添加成功', 'success'),
  1185. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  1186. });
  1187. }
  1188. addRecordWords(): void {
  1189. const chosen = this.words().filter((word) => this.selected().has(word.id));
  1190. if (!chosen.length) {
  1191. this.platform.toast('请选择单词', 'error');
  1192. return;
  1193. }
  1194. const owner = Number(this.session.user()?.groupId) === 3 ? this.session.student() : this.session.user();
  1195. this.api.post('e_add_words', {
  1196. uid: owner?.userId,
  1197. wordsId: chosen.map((word) => word.wordId).join(','),
  1198. ifnew: 1,
  1199. kcid: this.query('kcid'),
  1200. }).subscribe({
  1201. next: () => this.platform.toast('添加成功', 'success'),
  1202. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  1203. });
  1204. }
  1205. endRecord(): void {
  1206. if(this.submitting()||this.reviewCompletion())return;
  1207. this.submitting.set(true);
  1208. this.api.post<{amount:number;rewardStatus:string;ineligibleReason?:string;unchanged?:boolean}>('app_review_complete',{id:this.query('gid')}).pipe(finalize(()=>this.submitting.set(false))).subscribe({
  1209. next:({result})=>{this.reviewCache().clear();if(Number(this.session.groupId())===3)this.todayReviews.markCompleted(this.query('gid'));this.reviewCompletion.set(result);},
  1210. error:(e:ApiError)=>this.platform.toast(e.message,'error'),
  1211. });
  1212. }
  1213. get overdueReview():boolean{return Boolean(this.query('plannedDate')&&this.query('plannedDate')<this.dateOnly());}
  1214. canDeactivate():boolean|Promise<boolean>{
  1215. if(!this.isRecordPage||this.reviewCompletion())return true;
  1216. if(this.submitting())return false;
  1217. return this.seen().size||this.selected().size||this.recordRevealed().size?this.platform.confirm('本次复习尚未提交完成,确定离开?'):true;
  1218. }
  1219. returnToReview(today=false):void{
  1220. const r=today?{date:this.dateOnly()}:this.reviewReturn;
  1221. void this.router.navigate(['/pages/stu/stu_calendar'],{queryParams:{date:r.date,studentId:r.studentId,scope:r.scope,page:r.page},state:{reviewScroll:r.scroll},replaceUrl:true});
  1222. }
  1223. calendarTitle(item: SourceItem): string {
  1224. const title = String(item['kc_title'] ?? item['kctitle'] ?? item['kcmc'] ?? '').trim();
  1225. return title ? title.split('@')[0] : '单词复习';
  1226. }
  1227. calendarStudent(item: SourceItem): string {
  1228. return String(item['honeyName'] ?? item['Title'] ?? '').split('@')[0];
  1229. }
  1230. calendarDate(item: SourceItem): string {
  1231. return antiForgetDate(item);
  1232. }
  1233. calendarFirstLearnedAt(item: SourceItem): string {
  1234. const raw = String(
  1235. item['learned_at']
  1236. ?? item['learnedAt']
  1237. ?? item['firstLearnedAt']
  1238. ?? item['learned_date']
  1239. ?? '',
  1240. ).trim();
  1241. if (!raw) return '首次学习:时间未记录';
  1242. const compactDate = raw.match(/^(\d{4})(\d{2})(\d{2})$/);
  1243. if (compactDate) return `首次学习:${compactDate[1]}-${compactDate[2]}-${compactDate[3]}(时间未记录)`;
  1244. const dateOnly = raw.match(/^(\d{4}-\d{2}-\d{2})$/);
  1245. if (dateOnly) return `首次学习:${dateOnly[1]}(时间未记录)`;
  1246. const normalized = /(?:Z|[+-]\d{2}:?\d{2})$/i.test(raw)
  1247. ? raw
  1248. : `${raw.replace(' ', 'T')}+08:00`;
  1249. const value = new Date(normalized);
  1250. if (Number.isNaN(value.getTime())) return `首次学习:${raw}`;
  1251. const parts = new Intl.DateTimeFormat('zh-CN', {
  1252. timeZone: 'Asia/Shanghai',
  1253. year: 'numeric',
  1254. month: '2-digit',
  1255. day: '2-digit',
  1256. hour: '2-digit',
  1257. minute: '2-digit',
  1258. hourCycle: 'h23',
  1259. }).formatToParts(value);
  1260. const part = (type: Intl.DateTimeFormatPartTypes) => parts.find((itemPart) => itemPart.type === type)?.value ?? '';
  1261. return `首次学习:${part('year')}-${part('month')}-${part('day')} ${part('hour')}:${part('minute')}`;
  1262. }
  1263. calendarReviewNumber(item: SourceItem): number {
  1264. for (const key of ['fxcs', 'fxxh', 'reviewNo', 'reviewIndex', 'review_order']) {
  1265. const value = Number(item[key]);
  1266. if (Number.isFinite(value) && value > 0) return Math.round(value);
  1267. }
  1268. const recordId = String(item['xxjlid'] ?? '').trim();
  1269. if (!recordId) return 1;
  1270. const tasks = this.calendarItems()
  1271. .filter((candidate) => String(candidate['xxjlid'] ?? '').trim() === recordId)
  1272. .sort((left, right) => {
  1273. const dateOrder = antiForgetDate(left).localeCompare(antiForgetDate(right));
  1274. if (dateOrder) return dateOrder;
  1275. return Number(left['GeneralID'] ?? 0) - Number(right['GeneralID'] ?? 0);
  1276. });
  1277. const index = tasks.indexOf(item);
  1278. return index >= 0 ? index + 1 : 1;
  1279. }
  1280. calendarReady(item: SourceItem): boolean {
  1281. const due = antiForgetDate(item);
  1282. return Boolean(due && Date.parse(due) <= Date.parse(this.dateOnly()) && Number(item['fxzt'] ?? 0) !== 1);
  1283. }
  1284. calendarCompleted(item: SourceItem): boolean {
  1285. return antiForgetCompleted(item);
  1286. }
  1287. selectMemoryDay(day: AntiForgetCalendarDay): void {
  1288. if (day.date === this.memorySelectedDate() && day.inCurrentMonth) return;
  1289. this.reviewScope.set('');this.memorySelectedDate.set(day.date);
  1290. this.reviewListPage.set(1);this.loadCalendar();
  1291. if (!day.inCurrentMonth) {
  1292. const [year, month] = day.date.split('-').map(Number);
  1293. this.memoryMonth.set(new Date(year, month - 1, 1, 12));
  1294. }
  1295. }
  1296. shiftMemoryMonth(amount: number): void {
  1297. const current = this.memoryMonth();
  1298. const next = new Date(current.getFullYear(), current.getMonth() + amount, 1, 12);
  1299. this.memoryMonth.set(next);
  1300. const monthKey = `${next.getFullYear()}-${String(next.getMonth() + 1).padStart(2, '0')}`;
  1301. const firstTask = (this.reviewPageData()?.dates||[]).map(row=>row.date).filter((date) => date.startsWith(monthKey)).sort()[0];
  1302. this.memorySelectedDate.set(firstTask || `${monthKey}-01`);
  1303. this.reviewListPage.set(1);this.loadCalendar();
  1304. }
  1305. showCurrentMemoryMonth(): void {
  1306. const today = this.dateOnly();
  1307. const [year, month] = today.split('-').map(Number);
  1308. this.memoryMonth.set(new Date(year, month - 1, 1, 12));
  1309. this.reviewScope.set('');this.memorySelectedDate.set(today);
  1310. this.reviewListPage.set(1);this.loadCalendar();
  1311. }
  1312. selectMemoryStudent(event: Event): void {
  1313. this.memoryStudentId.set((event.target as HTMLSelectElement).value);this.reviewListPage.set(1);this.loadCalendar();
  1314. }
  1315. memoryTaskStatus(item: SourceItem): string {
  1316. if (this.calendarCompleted(item)) return '已完成';
  1317. if (!this.calendarReady(item)) return '未到期';
  1318. const overdue = this.calendarDate(item) < this.dateOnly();
  1319. if (!this.canStartPointReading) return overdue ? '逾期补做' : '待复习';
  1320. return overdue ? '逾期补做 · 不计薪' : '待复习 · 当天完成计薪';
  1321. }
  1322. isWritingRecord(): boolean {
  1323. return String(this.orderInfo()['if_writing'] ?? '') === '1';
  1324. }
  1325. openCalendar(item: SourceItem): void {
  1326. if (!this.calendarReady(item) && !this.calendarCompleted(item)) {
  1327. this.platform.toast('还未到复习时间');
  1328. return;
  1329. }
  1330. const studentId = Number(item['yhid'] ?? 0);
  1331. if (!studentId) {
  1332. this.platform.toast('复习任务缺少关联学员', 'error');
  1333. return;
  1334. }
  1335. this.session.setStudent({
  1336. userId: studentId,
  1337. honeyName: this.calendarStudent(item) || '关联学员',
  1338. groupId: 1,
  1339. });
  1340. void this.router.navigate(['/pages/stu/record'], {
  1341. queryParams: { id: item['xxjlid'], gid: item['GeneralID'], kcid: item['kcid'], plannedDate:this.calendarDate(item),date:this.memorySelectedDate() },
  1342. state:{reviewReturn:{date:this.memorySelectedDate(),studentId:this.memoryStudentId(),page:this.reviewListPage(),scope:this.reviewScope(),scroll:window.scrollY}},
  1343. });
  1344. }
  1345. startExam(): void {
  1346. if (!this.questions().length || this.loading() || this.submitting()) return;
  1347. this.examAttemptStamp=new Date().toISOString();this.examLogKey=crypto.randomUUID();this.examAnswerId=null;this.examSaveError.set('');
  1348. this.answers.set(this.questions().map(q=>({qid:q.ID,qtype:String(q.QType??''),answer:'',result:2})));
  1349. this.examStarted.set(true);
  1350. this.examSubmitted.set(false);
  1351. this.currentIndex.set(0);
  1352. this.startExamTimer();
  1353. }
  1354. answerExam(option: ExamOption, optionIndex: number): void {
  1355. if(this.submitting()||this.examSaveError()||this.examSubmitted())return;
  1356. const question = this.currentQuestion();
  1357. if (!question) return;
  1358. const options = question.QOption.map((item, index) => ({ ...item, checked: index === optionIndex }));
  1359. this.questions.update((items) => items.map((item, index) => index === this.currentIndex() ? { ...item, QOption: options, checked: true } : item));
  1360. const result: 0 | 1 = this.cleanText(option.text) === this.cleanText(question.QContent) ? 1 : 0;
  1361. this.setExamAnswer({ qid: question.ID, qtype: String(question.QType ?? ''), answer: option.value, result });
  1362. this.advanceExam();
  1363. }
  1364. skipExamQuestion(): void {
  1365. if(this.submitting()||this.examSaveError()||this.examSubmitted())return;
  1366. const question = this.currentQuestion();
  1367. if (!question) return;
  1368. this.setExamAnswer({ qid: question.ID, qtype: String(question.QType ?? ''), answer: '', result: 2 });
  1369. this.advanceExam();
  1370. }
  1371. submitExam(): void {
  1372. if(this.submitting()||this.examSubmitted())return;
  1373. this.examSaveError.set('');
  1374. if(this.examAnswerId!==null){this.submitting.set(true);this.saveExamLog(this.examAnswerId);return;}
  1375. this.stopExamTimer();
  1376. const ask = this.askInfo();
  1377. const user = this.session.user();
  1378. const answers = this.answers();
  1379. const mu = {
  1380. AskID: ask['ID'],
  1381. Answer: JSON.stringify(answers),
  1382. Remin: '',
  1383. ZType: 0,
  1384. Zstatus: 0,
  1385. Source: '',
  1386. UserID: user?.userId,
  1387. CDate: this.examAttemptStamp,
  1388. };
  1389. this.submitting.set(true);
  1390. this.api.post<string | number>('vote_add', { mu: JSON.stringify(mu) }).subscribe({
  1391. next: ({ result }) => {this.examAnswerId=result;this.saveExamLog(result);},
  1392. error: (error: ApiError) => {
  1393. this.submitting.set(false);this.examSaveError.set(error.message);
  1394. },
  1395. });
  1396. }
  1397. restart(): void {
  1398. if (this.isExamPage) {
  1399. this.loadExam();
  1400. return;
  1401. }
  1402. this.load();
  1403. }
  1404. leave(): void {
  1405. this.clearLearningStorage();
  1406. void this.router.navigateByUrl('/pages/home/index', { replaceUrl: true });
  1407. }
  1408. private loadNodes(): void {
  1409. this.loading.set(true);
  1410. this.error.set('');
  1411. this.nodes.set([]);
  1412. this.selectedNodes.set(new Set());
  1413. const pid = this.isCatalogPage
  1414. ? WORD_CATALOG_CATEGORIES[this.catalogCategoryIndex()].pid
  1415. : this.query('nid') || this.query('pid');
  1416. const params: Record<string, unknown> = { pid, cpage: 1, psize: 100 };
  1417. if (this.isUnitListPage) {
  1418. const learner = this.canStartPointReading ? this.session.student() : this.session.user();
  1419. if (!learner?.userId) {
  1420. this.loading.set(false);
  1421. this.error.set('未找到当前学员,请返回学习记录重新选择学员');
  1422. return;
  1423. }
  1424. params['ifunit'] = 1;
  1425. params['userId'] = learner.userId;
  1426. params['bindingId'] = this.query('bindingId');
  1427. }
  1428. this.api.get<unknown>('node_list', params).pipe(finalize(() => this.loading.set(false))).subscribe({
  1429. next: (nodes) => {
  1430. const rows = this.findList(nodes.result);
  1431. if (this.isUnitListPage && !this.canStartPointReading && !rows.length && pid) {
  1432. void this.router.navigate(['/pages/stu/stu_abc'], {
  1433. queryParams: { nids: pid, readonly: 1 },
  1434. replaceUrl: true,
  1435. });
  1436. return;
  1437. }
  1438. this.nodes.set(rows);
  1439. },
  1440. error: (error: ApiError) => this.error.set(error.message
  1441. || (this.isCatalogPage ? '词库暂时无法加载,请稍后重试' : '学习单元暂时无法加载,请稍后重试')),
  1442. });
  1443. }
  1444. loadMoreSelection(): void {
  1445. if (this.selectionLocked() || this.selectionLoading() || this.words().length >= this.selectionTotal()) return;
  1446. this.bulkSelection.set(null);
  1447. if (this.isRefineSelectionPage && this.courseSelectionNeedsRebase) {
  1448. const previousPage = this.selectionPage();
  1449. this.selectionPage.set(1);
  1450. this.loadSelection(false, previousPage);
  1451. return;
  1452. }
  1453. this.selectionPage.update(page => page + 1);
  1454. this.loadSelection(true);
  1455. }
  1456. selectNewWordBucket(bucket: 'pending' | 'completed'): void {
  1457. if (this.activeSelectionBucket() === bucket) return;
  1458. this.stopWordPlayback();
  1459. this.selectionRequest?.unsubscribe();
  1460. this.activeSelectionBucket.set(bucket);
  1461. this.selectionPage.set(1);
  1462. this.selectionTotal.set(this.newWordCounts()[bucket]);
  1463. this.words.set([]);
  1464. if (this.legacyNewWords) { this.showLegacyNewWordPage(); return; }
  1465. this.loadSelection();
  1466. }
  1467. goToNewWordPage(page: number): void {
  1468. if (this.selectionLoading() || page < 1 || page > this.newWordPageCount() || page === this.selectionPage()) return;
  1469. this.stopWordPlayback();
  1470. this.selectionPage.set(page);
  1471. if (this.legacyNewWords) { this.showLegacyNewWordPage(); return; }
  1472. this.loadSelection();
  1473. }
  1474. private showLegacyNewWordPage(): void {
  1475. const all = this.legacyNewWords ?? [];
  1476. const pending = all.filter((word) => !this.newWordLearned(word));
  1477. const completed = all.filter((word) => this.newWordLearned(word));
  1478. const bucket = this.activeSelectionBucket() === 'completed' ? completed : pending;
  1479. const start = (this.selectionPage() - 1) * this.newWordPageSize;
  1480. this.newWordCounts.set({ pending: pending.length, completed: completed.length });
  1481. this.selectionTotal.set(bucket.length);
  1482. this.words.set(bucket.slice(start, start + this.newWordPageSize));
  1483. this.prepareWordAudio(this.words()[0]);
  1484. for (const word of all) this.newWordSelectionCache.set(word.id, word);
  1485. this.error.set('');
  1486. this.selectionLoading.set(false);
  1487. this.loading.set(false);
  1488. }
  1489. private loadLegacyNewWords(uid: number | undefined, page = 1, collected: Word[] = []): void {
  1490. const size = 500;
  1491. this.selectionRequest = this.api.get<unknown>('e_words_list', { uid, cpage: page, psize: size }).subscribe({
  1492. next: ({ result, page: pageInfo }) => {
  1493. const incoming = this.findList(result).map((item) => this.toNewWord(item)).filter((word) => word.word);
  1494. const all = [...collected, ...incoming];
  1495. const total = Number(pageInfo?.itemCount ?? all.length);
  1496. if (!Number.isFinite(total) || (!incoming.length && all.length < total)) {
  1497. this.error.set('生词本数据未加载完整,请重试');
  1498. this.selectionLoading.set(false);
  1499. this.loading.set(false);
  1500. return;
  1501. }
  1502. if (all.length < total) {
  1503. this.loadLegacyNewWords(uid, page + 1, all);
  1504. return;
  1505. }
  1506. this.legacyNewWords = all;
  1507. this.showLegacyNewWordPage();
  1508. },
  1509. error: (error: ApiError) => {
  1510. this.error.set(error.message || '生词本加载失败,请重试');
  1511. this.selectionLoading.set(false);
  1512. this.loading.set(false);
  1513. },
  1514. });
  1515. }
  1516. private loadSelection(more=false, rebaseFromPage?: number): void {
  1517. const accept=(result:unknown,total:unknown)=>{const incoming=this.findList(result).map(item=>this.meta.path==='pages/member/starshop'?this.toNewWord(item):this.toWord(item)).filter(w=>w.word);this.words.set(more?[...this.words(),...incoming]:incoming);this.selectionTotal.set(Number(total)||this.words().length);};
  1518. const failure=(error:ApiError)=>{if(rebaseFromPage!==undefined){this.selectionPage.set(rebaseFromPage);this.platform.toast(error.message,'error');}else if(more){this.selectionPage.update(p=>p-1);this.platform.toast(error.message,'error');}else this.error.set(error.message);};
  1519. if (this.meta.path === 'pages/stu/stu_abc') {
  1520. const student = this.session.student() ?? this.session.user();this.selectionLoading.set(true);
  1521. this.selectionRequest=this.api.get<unknown>('e_ck_list',{checkwords:2,nids:this.query('nids')||this.query('nid'),pnid:this.query('pnid'),learningPass:this.coursePass(),includeRecognized:true,modelId:52,cpage:this.selectionPage(),psize:100,compact:true,uid:student?.userId}).pipe(finalize(()=>{this.selectionLoading.set(false);this.loading.set(false);})).subscribe({next:({result,page})=>{
  1522. accept(result,page?.itemCount);
  1523. if (!more) this.prepareWordAudio(this.visibleCourseWords()[0]);
  1524. if (rebaseFromPage !== undefined) this.courseSelectionNeedsRebase = false;
  1525. const merged=new Map(this.courseSelectionCache().map(word=>[word.id,word]));
  1526. for(const word of this.words()) merged.set(word.id,word);
  1527. this.courseSelectionCache.set([...merged.values()]);
  1528. const counts=page?.['passCounts'],bookCounts=page?.['bookPassCounts'];
  1529. if(Array.isArray(counts)&&counts.length===this.coursePassTabs.length&&Array.isArray(bookCounts)&&bookCounts.length===this.coursePassTabs.length){
  1530. this.coursePassCounts.set(counts.map(Number));this.bookPassCounts.set(bookCounts.map(Number));
  1531. }
  1532. this.error.set('');
  1533. },error:failure});return;
  1534. }
  1535. if (this.meta.path === 'pages/his/his_words') {
  1536. this.api.post<unknown>('e_record_detail', { id: this.query('id'), includeLessonStudyAccess: true }).pipe(finalize(() => this.loading.set(false))).subscribe({
  1537. next: ({ result, addon }) => {
  1538. const words = this.findList(result).map((item) => this.toWord(item)).filter((word) => word.word);
  1539. this.historyPreviewWords = words;
  1540. this.words.set(words.slice(0, this.wordPreviewPageSize));
  1541. this.wordPreviewTotal.set(words.length);
  1542. const sourceAddon = this.findList(addon)[0];
  1543. if (sourceAddon) {
  1544. this.orderInfo.set(sourceAddon);
  1545. if (sourceAddon['GeneralID'] && sourceAddon['canReadLessonStudy'] !== false) {
  1546. this.api.get<any>('app_lesson_study', { orderId: String(sourceAddon['GeneralID']) }).subscribe({
  1547. next: ({ result }) => this.historySources.set(lessonStudySources(result)),
  1548. error: () => this.historySources.set([]),
  1549. });
  1550. }
  1551. }
  1552. },
  1553. error: (error: ApiError) => this.error.set(error.message),
  1554. });
  1555. return;
  1556. }
  1557. const uid = this.isCoachWordbookSelection ? this.wordbookStudentId() : this.session.user()?.userId;
  1558. this.selectionLoading.set(true);
  1559. this.selectionRequest=this.api.get<unknown>('e_words_list',{uid,cpage:this.selectionPage(),psize:this.newWordPageSize,learningStatus:this.activeSelectionBucket(),compact:true}).subscribe({
  1560. next: ({result,page}) => {
  1561. const incoming = this.findList(result).map((item) => this.toNewWord(item)).filter((word) => word.word);
  1562. const pendingCount = Number(page?.['pendingCount']);
  1563. const completedCount = Number(page?.['completedCount']);
  1564. const total = Number(page?.itemCount ?? incoming.length);
  1565. const validCounts = Number.isFinite(pendingCount) && Number.isFinite(completedCount)
  1566. && pendingCount >= 0 && completedCount >= 0 && pendingCount + completedCount >= total
  1567. && (incoming.length > 0 || total === 0 || this.selectionPage() > Math.ceil(total / this.newWordPageSize));
  1568. if (!validCounts) {
  1569. this.loadLegacyNewWords(uid);
  1570. return;
  1571. }
  1572. this.words.set(incoming);
  1573. this.prepareWordAudio(incoming[0]);
  1574. for (const word of incoming) this.newWordSelectionCache.set(word.id, word);
  1575. const counts = {pending: pendingCount, completed: completedCount};
  1576. this.newWordCounts.set(counts);
  1577. this.selectionTotal.set(total);
  1578. this.error.set('');
  1579. this.selectionLoading.set(false);
  1580. this.loading.set(false);
  1581. },
  1582. error: (error: ApiError) => {
  1583. failure(error);
  1584. this.selectionLoading.set(false);
  1585. this.loading.set(false);
  1586. },
  1587. });
  1588. }
  1589. private loadStageWords(): void {
  1590. const nid = this.coachWordbookStudentId ? '' : this.query('nid');
  1591. if (nid && this.isReadOnlyWordView) {
  1592. this.loadReadOnlyWords();
  1593. return;
  1594. }
  1595. if (nid) {
  1596. this.api.get<unknown>('content_list', { nid, modelId: 52, cpage: 1, psize: 300 }).pipe(finalize(() => this.loading.set(false))).subscribe({
  1597. next: ({ result }) => this.initializeStage(this.findList(result).map((item) => this.toWord(item)).filter((word) => word.word)),
  1598. error: (error: ApiError) => this.error.set(error.message),
  1599. });
  1600. return;
  1601. }
  1602. const stored = this.readLearningWords();
  1603. this.loading.set(false);
  1604. if (!stored.length) {
  1605. this.error.set('请先选择本次学习的单词');
  1606. return;
  1607. }
  1608. this.initializeStage(stored);
  1609. }
  1610. private loadReadOnlyWords(pageChange = false, previousPage = 1): void {
  1611. const learner = this.session.student() ?? this.session.user();
  1612. this.api.get<unknown>('e_ck_list', {
  1613. checkwords: 2,
  1614. nids: this.query('nid'),
  1615. modelId: 52,
  1616. cpage: this.wordPreviewPage(),
  1617. psize: this.wordPreviewPageSize,
  1618. uid: learner?.userId,
  1619. }).pipe(finalize(() => {
  1620. if (pageChange) this.wordPreviewLoading.set(false);
  1621. else this.loading.set(false);
  1622. })).subscribe({
  1623. next: ({ result, page }) => {
  1624. const words = this.findList(result).map((item) => this.toWord(item)).filter((word) => word.word);
  1625. this.words.set(words);
  1626. this.wordPreviewTotal.set(Math.max(words.length, Number(page?.itemCount ?? 0)));
  1627. if (pageChange) {
  1628. setTimeout(() => document.getElementById('readonly-word-title')?.scrollIntoView({ behavior: 'smooth', block: 'start' }));
  1629. }
  1630. },
  1631. error: (error: ApiError) => {
  1632. if (pageChange) {
  1633. this.wordPreviewPage.set(previousPage);
  1634. this.platform.toast('该页单词加载失败,请重试', 'error');
  1635. return;
  1636. }
  1637. this.error.set(error.message);
  1638. },
  1639. });
  1640. }
  1641. private initializeStage(source: Word[]): void {
  1642. if (!source.length) {
  1643. this.error.set('本关暂无单词,请返回重新选择学习内容');
  1644. return;
  1645. }
  1646. const words = this.isStudyListPage ? source : this.shuffle(source);
  1647. this.words.set(words);
  1648. if (!this.isListeningPage && !this.isSpellingPage) this.prepareWordAudio(words[0]);
  1649. if (this.isStudyListPage) {
  1650. this.studyStep.set(1);
  1651. this.repetitions.set({});
  1652. this.studyMeaningRevealed.set(new Set());
  1653. } else if (this.isMatchingPage) {
  1654. this.matchLeft.set(this.shuffle(words));
  1655. this.matchRight.set(this.shuffle(words));
  1656. // Load public distractors while the matching activity is already usable.
  1657. const round = [...this.readAllLearningWords(), ...words];
  1658. this.listeningPool.load(round.map(word => word.id)).subscribe({ error: () => undefined });
  1659. } else if (this.isListeningPage) {
  1660. void this.play();
  1661. this.prepareChoiceOptions();
  1662. } else if (this.isSpellingPage) {
  1663. this.prepareSpelling();
  1664. void this.play();
  1665. }
  1666. }
  1667. private finishStudyRound(): void {
  1668. if (this.studyStep() < 3) {
  1669. const next = (this.studyStep() + 1) as 2 | 3;
  1670. this.selectionRevealed.set(new Set());
  1671. this.pointReadAudio.set(null);
  1672. this.studyStep.set(next);
  1673. this.words.set(shuffledStudy(this.words()));
  1674. this.prepareWordAudio(this.words()[0]);
  1675. this.repetitions.set({});
  1676. this.studyMeaningRevealed.set(new Set());
  1677. this.platform.toast(next === 2 ? '进入乱序学习' : '进入中文挑战', 'success');
  1678. return;
  1679. }
  1680. this.navigateStage('/pages/stu/stu3');
  1681. }
  1682. private prepareWordAudio(word: Word | undefined): void {
  1683. if (!word || this.isReadOnlySelectionPage || (this.isReadOnlyWordView && !this.isHistoryWordView)) return;
  1684. const words = this.words(), index = words.findIndex(item => item.id === word.id);
  1685. const nearby = [word, ...words.slice(Math.max(0, index + 1), Math.max(0, index + 1) + 2)];
  1686. this.platform.preloadAudio(nearby.filter(item => item.audio?.trim()).map(item => this.wordAudioUrl(item.audio)));
  1687. }
  1688. retryListeningChoices(): void { this.outsideChoicePool = null; this.prepareChoiceOptions(true); }
  1689. private prepareChoiceOptions(refresh = false): void {
  1690. this.choiceOptionsRequest?.unsubscribe();
  1691. const version = ++this.choiceOptionsVersion;
  1692. const current = this.current();
  1693. if (!current) {
  1694. this.choiceOptions.set([]);
  1695. return;
  1696. }
  1697. const round = [...this.readAllLearningWords(), ...this.words()];
  1698. const apply = (pool: Word[]) => {
  1699. if (version !== this.choiceOptionsVersion || this.current() !== current || this.completed()) return;
  1700. this.choiceOptions.set(listeningChoices(current, round, pool, items => this.shuffle(items)));
  1701. this.choicesLoading.set(false);
  1702. };
  1703. if (this.outsideChoicePool !== null) { apply(this.outsideChoicePool); return; }
  1704. this.choiceOptions.set([]);
  1705. this.choicesLoading.set(true);
  1706. this.choiceOptionsRequest = this.listeningPool.load(round.map(word => word.id), refresh).subscribe({
  1707. next: ({ result }) => {
  1708. if (version !== this.choiceOptionsVersion || this.current() !== current || this.completed()) return;
  1709. this.outsideChoicePool = this.findList(result).map(item => this.toWord(item));
  1710. apply(this.outsideChoicePool);
  1711. },
  1712. error: () => {
  1713. apply([]);
  1714. this.platform.toast('拓展选项暂未加载,本题使用已选词汇', 'info');
  1715. },
  1716. });
  1717. }
  1718. private prepareSpelling(): void {
  1719. const word = this.current();
  1720. this.assembled.set('');
  1721. this.spellingCorrect.set(false);
  1722. this.letters.set(this.shuffle((word?.word ?? '').split('').map((value) => ({ value, used: false }))));
  1723. }
  1724. private finishSpellingFlow(): void {
  1725. const currentPage = Number(this.storageGet('_page_current_learn') ?? 1);
  1726. const mode = String(this.storageGet('learn_mode') ?? '');
  1727. if (mode === 'newword') {
  1728. const studentId = this.coachWordbookStudentId;
  1729. const learner = studentId ? {userId: studentId} : this.canStartPointReading ? this.session.student() : this.session.user();
  1730. this.submitting.set(true);
  1731. this.saveWordProgress(this.words(), learner).pipe(finalize(() => this.submitting.set(false))).subscribe({
  1732. next: () => {
  1733. if (this.hasNextWordBatch) {
  1734. this.completed.set(false);
  1735. this.storageSet('_page_current_learn', currentPage + 1);
  1736. this.navigateStage('/pages/stu/stu_con');
  1737. return;
  1738. }
  1739. this.completed.set(false);
  1740. this.clearLearningStorage();
  1741. const queryParams = studentId ? {wordbookStudentId: studentId} : {};
  1742. void this.router.navigate(['/pages/member/starshop'], { queryParams, replaceUrl: true });
  1743. },
  1744. error: (error: ApiError) => {
  1745. this.completed.set(true);
  1746. this.platform.toast(error.message || '学习结果保存失败,请重试', 'error');
  1747. },
  1748. });
  1749. return;
  1750. }
  1751. if (this.hasNextWordBatch) {
  1752. this.completed.set(false);
  1753. this.storageSet('_page_current_learn', currentPage + 1);
  1754. this.navigateStage('/pages/stu/stu_con');
  1755. return;
  1756. }
  1757. if (mode === 'history_word') {
  1758. this.completed.set(false);
  1759. this.clearLearningStorage();
  1760. void this.router.navigateByUrl('/pages/his/his', { replaceUrl: true });
  1761. } else if (this.meta.path === 'pages/stu/pl_stu5' || (this.isListeningPage && this.canStartPointReading && this.storageGet('skip_spelling_stage') === true)) {
  1762. if (this.query('orderId')) {
  1763. this.createPracticeLearningRecord();
  1764. } else {
  1765. this.createStandalonePracticeLearningRecord();
  1766. }
  1767. } else {
  1768. this.navigateStage('/pages/stu/stu6');
  1769. }
  1770. }
  1771. private loadReviewWords(): void {
  1772. const words = this.readAllLearningWords();
  1773. this.words.set(words);
  1774. this.loading.set(false);
  1775. if (!words.length) {
  1776. this.error.set('请先选择本次学习的单词');
  1777. return;
  1778. }
  1779. const user = this.session.user();
  1780. this.api.get<unknown>('content_list', {
  1781. modelId: 56,
  1782. psize: 2,
  1783. myfield2: `UserId=${(this.canStartPointReading ? this.session.student() : user)?.userId}|dqrq=${this.compactDate()}`,
  1784. }).subscribe({
  1785. next: ({ result }) => this.learnedRecord.set(this.findList(result)[0] ?? {}),
  1786. error: (error:ApiError) => this.error.set(error.message),
  1787. });
  1788. }
  1789. private updateUnitRecord(): Observable<unknown> {
  1790. const nids = this.query('nids');
  1791. const bookId = this.query('pnid');
  1792. if (!nids || !bookId) return of(null);
  1793. const wordIds: Record<string, string> = {};
  1794. for (const nodeId of nids.split(',')) {
  1795. wordIds[nodeId] = this.words().filter((word) => word.nodeId === nodeId).map((word) => word.wordId).join(',');
  1796. }
  1797. return this.api.post('unit_record_update', {
  1798. nids,
  1799. userId: (this.canStartPointReading ? this.session.student() : this.session.user())?.userId,
  1800. bookId,
  1801. wordIds: JSON.stringify(wordIds),
  1802. });
  1803. }
  1804. private saveLearningRecord(): void {
  1805. const user = this.session.user();
  1806. const student = Number(user?.groupId) === 3 ? this.session.student() : null;
  1807. const owner = student ?? user;
  1808. const existing = this.learnedRecord();
  1809. const oldItems = this.parseArray(existing['xxqs']);
  1810. const records = new Map<string, SourceItem>();
  1811. for (const item of oldItems) records.set(String(item['GeneralID'] ?? ''), item);
  1812. for (const word of this.words()) {
  1813. records.set(word.wordId, { GeneralID: word.wordId, Title: word.word, check: this.reviewValue(word) });
  1814. }
  1815. const xxqs = [...records.values()];
  1816. const learned = xxqs.length;
  1817. const ygg = xxqs.filter((item) => Number(item['check']) === 1).length;
  1818. const djq = xxqs.filter((item) => Number(item['check']) === 2).length;
  1819. const content: SourceItem = {
  1820. ModelID: 56,
  1821. nodeId: 291,
  1822. inputer: user?.honeyName,
  1823. status: 99,
  1824. Hits: learned,
  1825. title: owner?.honeyName,
  1826. };
  1827. let action = 'content_add_zt';
  1828. if (existing['GeneralID']) {
  1829. content['GeneralID'] = existing['GeneralID'];
  1830. content['UpDateTime'] = this.dateOnly();
  1831. action = 'content_update';
  1832. }
  1833. const addon: SourceItem = {
  1834. con: `完成了${learned}个单词的学习@${this.dateTime()}`,
  1835. dqrq: this.compactDate(),
  1836. pl: student ? user?.userId : 0,
  1837. UserID: owner?.userId,
  1838. learned,
  1839. ygg,
  1840. djq,
  1841. xxqs: JSON.stringify(xxqs),
  1842. };
  1843. if (!existing['xxqs']) addon['fxrl'] = '';
  1844. this.submitting.set(true);
  1845. this.saveWordProgress(this.words(), owner).pipe(
  1846. switchMap(()=>this.updateUnitRecord()),
  1847. switchMap(() => this.api.post(action, { content: JSON.stringify(content), addon: JSON.stringify(addon) })),
  1848. finalize(() => this.submitting.set(false)),
  1849. ).subscribe({
  1850. next: () => {
  1851. this.platform.toast('提交成功', 'success');
  1852. void this.router.navigate(['/pages/member/myorder'], { queryParams: { pnid: this.query('pnid') }, replaceUrl: true });
  1853. },
  1854. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  1855. });
  1856. }
  1857. private loadPracticeEnd(): void {
  1858. const orderId = this.query('orderId') || this.query('id');
  1859. this.api.get<unknown>('e_order_detail', {id: orderId}).pipe(switchMap(({result}) => {
  1860. const order = this.findList(result)[0] ?? (result as SourceItem);
  1861. const studentId = Number(order?.['szyh']);
  1862. if (!studentId) return throwError(() => new ApiError('预约记录缺少学员信息'));
  1863. this.orderInfo.set(order);
  1864. if (this.session.student()?.userId !== studentId) this.session.setStudent({userId: studentId, groupId: 1, honeyName: String(order['HoneyName'] || '学员')});
  1865. return this.api.get<any>('app_lesson_study', {orderId});
  1866. }), finalize(() => this.loading.set(false))).subscribe({
  1867. next: ({result}) => {
  1868. this.lessonLearnedCount.set(Number(result.record?.learned || 0));
  1869. const batch = result.batches.find((b: any) => b.batchId === (this.query('batchId') || this.storageGet('batchId')))
  1870. || result.batches.find((b: any) => b.status === 'draft' && (!this.query('bindingId') || b.bindingId === this.query('bindingId')));
  1871. if (!batch) { this.error.set('未找到待确认批次,请返回课程查看已保存成果'); return; }
  1872. this.storageSet('batchId', batch.batchId); this.storageSet('batchVersion', batch.version);
  1873. this.orderInfo.update(order => ({...order, learningCourseId: batch.courseId || this.query('pnid') || this.query('kcid') || order['kcid']}));
  1874. const words = batch.words.map((w: SourceItem) => this.toWord(w));
  1875. this.words.set(words);
  1876. const local = (this.storageGet('roundReview:' + batch.batchId) || {}) as Record<string, 0 | 1 | 2>;
  1877. this.reviewState.set(Object.fromEntries(words.map((w: Word) => [w.id, local[w.id] ?? Number(w['check']) ?? 0])));
  1878. }, error: (e: ApiError) => this.error.set(e.message),
  1879. });
  1880. }
  1881. private submitPracticeEnd(continueLearning = false): void {
  1882. this.submitting.set(true);
  1883. this.saveLessonBatch(this.query('mastery') ? 'mastery' : 'confirm', this.words()).pipe(
  1884. switchMap(() => this.query('mastery') ? of(null) : this.saveWordProgress(this.words(), this.session.student())),
  1885. finalize(() => this.submitting.set(false)),
  1886. ).subscribe({next: () => {
  1887. this.clearLearningStorage();
  1888. this.platform.toast(`本轮已保存,本节累计 ${this.lessonLearnedCount()} 个词`, 'success');
  1889. void this.router.navigate(['/pages/shop/get_order'], {queryParams: {id: this.query('orderId') || this.query('id'), ...(continueLearning || this.query('mastery') ? {} : {feedback: '1'})}, replaceUrl: true});
  1890. }, error: (e: ApiError) => this.platform.toast(e.message, 'error')});
  1891. }
  1892. private saveLessonBatch(mode: 'draft' | 'open-draft' | 'confirm' | 'mastery', words: Word[]): Observable<LessonBatchResult> {
  1893. const opening = mode === 'open-draft';
  1894. const batchId = opening ? crypto.randomUUID() : String(this.storageGet('batchId') || crypto.randomUUID());
  1895. const version = opening ? 0 : Number(this.storageGet('batchVersion') || 0);
  1896. if (!opening) this.storageSet('batchId', batchId);
  1897. const xxqs = words.map(w => ({GeneralID: w.wordId, Title: w.word, check: mode === 'confirm' || mode === 'mastery' ? this.reviewValue(w) : 0}));
  1898. return this.api.post<LessonBatchResult>('stu_record_update_v2', {
  1899. orderId: this.query('orderId') || this.query('id'), uid: this.session.student()?.userId,
  1900. batchId, saveMode: mode, expectedVersion: version,
  1901. requestKey: this.draft().command('batch:' + batchId + ':' + version + ':' + mode + ':' + JSON.stringify(xxqs)),
  1902. addon: JSON.stringify({bindingId: this.query('bindingId'), xxqs}),
  1903. }).pipe(map(({result}) => {
  1904. if (opening && !result.resumed) this.clearLearningStorage();
  1905. this.storageSet('batchId', result.batchId || batchId);
  1906. this.storageSet('batchVersion', result.batchVersion);
  1907. if (result.learned !== undefined) this.lessonLearnedCount.set(Number(result.learned));
  1908. return result;
  1909. }));
  1910. }
  1911. private createPracticeLearningRecord(): void {
  1912. this.submitting.set(true);
  1913. this.saveLessonBatch('draft', this.readAllLearningWords()).pipe(finalize(() => this.submitting.set(false))).subscribe({
  1914. next: () => this.navigateStage('/pages/stu/pl_end'),
  1915. error: (e: ApiError) => this.platform.toast(e.message, 'error'),
  1916. });
  1917. }
  1918. private createStandalonePracticeLearningRecord(): void {
  1919. const allWords = this.readAllLearningWords();
  1920. const user = this.session.user();
  1921. const student = this.session.student();
  1922. if (Number(user?.groupId) === 3 && !student?.userId) {
  1923. this.platform.toast('请先选择学员', 'error');
  1924. return;
  1925. }
  1926. const owner = Number(user?.groupId) === 3 ? student : user;
  1927. const xxqs = allWords.map((word) => ({ GeneralID: word.wordId, Title: word.word, check: 0 }));
  1928. const content: SourceItem = {
  1929. ModelID: 56,
  1930. nodeId: 291,
  1931. inputer: user?.honeyName,
  1932. status: 99,
  1933. Hits: xxqs.length,
  1934. title: owner?.honeyName,
  1935. };
  1936. const addon: SourceItem = {
  1937. con: `完成了${xxqs.length}个单词的学习@${this.dateTime()}`,
  1938. dqrq: this.compactDate(),
  1939. pl: Number(user?.groupId) === 3 ? user?.userId : 0,
  1940. UserID: owner?.userId,
  1941. learned: xxqs.length,
  1942. ygg: 0,
  1943. djq: 0,
  1944. xxqs: JSON.stringify(xxqs),
  1945. fxrl: '',
  1946. createReviewPlan: false,
  1947. bindingId: this.query('bindingId') || undefined,
  1948. };
  1949. this.submitting.set(true);
  1950. this.saveWordProgress(allWords, owner).pipe(
  1951. switchMap(() => this.api.post('content_add_zt', {
  1952. content: JSON.stringify(content),
  1953. addon: JSON.stringify(addon),
  1954. })),
  1955. finalize(() => this.submitting.set(false)),
  1956. ).subscribe({
  1957. next: () => {
  1958. this.clearLearningStorage();
  1959. this.platform.toast('学习记录已保存', 'success');
  1960. void this.router.navigateByUrl('/pages/his/his', { replaceUrl: true });
  1961. },
  1962. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  1963. });
  1964. }
  1965. private loadRecord(): void {
  1966. const user = this.session.user();
  1967. const learnerId = Number(user?.groupId) === 3 ? this.session.student()?.userId : user?.userId;
  1968. const recordId = this.query('id');
  1969. const detailParams = { id: recordId, studentId: learnerId };
  1970. const hasWords = (result: unknown) => this.findList(result).some((item) => this.toWord(item).word);
  1971. const notesReview = (detail: {addon?: unknown}) => this.findList(detail.addon)[0]?.['reviewContentMode'] === 'notes';
  1972. let originalRecord: SourceItem | undefined;
  1973. this.api.post<unknown>('e_record_detail', detailParams).pipe(
  1974. switchMap((detail) => hasWords(detail.result) || notesReview(detail) ? of(detail) : this.api.get<unknown>('content_get', { id: recordId }).pipe(
  1975. map(({ result }) => {
  1976. originalRecord = this.findList(result)[0];
  1977. return { ...detail, result: this.parseArray(originalRecord?.['xxqs']) };
  1978. }),
  1979. catchError(() => of(detail)),
  1980. )),
  1981. switchMap((detail) => hasWords(detail.result) || notesReview(detail) ? of(detail) : this.api.post<unknown>('app_learning_overview', {
  1982. studentId: learnerId, page: 1, pageSize: 1, refresh: true,
  1983. }).pipe(
  1984. switchMap(() => this.api.post<unknown>('e_record_detail', detailParams)),
  1985. catchError(() => of(detail)),
  1986. )),
  1987. finalize(() => this.loading.set(false)),
  1988. ).subscribe({
  1989. next: ({ result, addon }) => {
  1990. const words = this.findList(result).map((item) => this.toWord(item)).filter((word) => word.word);
  1991. if (!words.length) {
  1992. if (notesReview({addon})) {
  1993. this.orderInfo.set(this.findList(addon)[0] ?? {});
  1994. this.recordWordless.set(true);
  1995. this.error.set('');
  1996. return;
  1997. }
  1998. const wordless = originalRecord && 'xxqs' in originalRecord
  1999. && !this.parseArray(originalRecord['xxqs']).length
  2000. && Number(originalRecord['learned'] ?? 0) === 0;
  2001. this.recordWordless.set(Boolean(wordless));
  2002. const writingRecord = wordless && String(originalRecord?.['con'] ?? '').includes('写作');
  2003. this.error.set(wordless
  2004. ? `${writingRecord ? '这条任务关联的是写作学习记录,原本没有单词' : '这条任务关联的原学习记录没有保存单词'},无法进行单词复习。任务进度不会被修改。`
  2005. : '这条复习任务暂时没有读取到单词,请点击重新加载;任务进度不会被修改。');
  2006. return;
  2007. }
  2008. this.words.set(words);
  2009. const key = `xiaoshu.review.order.${learnerId}.${this.query('id')}`;
  2010. let previous: string[][] = [];
  2011. try {
  2012. const stored: unknown = JSON.parse(localStorage.getItem(key) ?? '[]');
  2013. if (Array.isArray(stored)) previous = stored.filter((order): order is string[] =>
  2014. Array.isArray(order) && order.every((id) => typeof id === 'string'));
  2015. } catch { /* A damaged or unavailable local cache should not block review. */ }
  2016. try {
  2017. const ordered = nextReviewWordOrder(words, previous, (word) => word.id);
  2018. this.words.set(ordered.words);
  2019. try { localStorage.setItem(key, JSON.stringify(ordered.history)); } catch { /* Review still works without local storage. */ }
  2020. } catch { /* Keep the original words visible if ordering fails. */ }
  2021. this.orderInfo.set(this.findList(addon)[0] ?? {});
  2022. },
  2023. error: (error: ApiError) => this.error.set(error.message),
  2024. });
  2025. }
  2026. turnReviewPage(delta:number):void{this.reviewListPage.update(p=>Math.max(1,Math.min(this.reviewPageData()?.page.pageCount||1,p+delta)));this.loadCalendar();}
  2027. retryCalendar(): void { this.loadCalendar(false, true); }
  2028. private reviewCache(): Map<string, ReviewPage> {
  2029. const identity = `${this.session.token()}|${this.session.user()?.userId ?? ''}|${this.dateOnly()}|${this.api.dataRevision ?? 0}`;
  2030. let cache = LearningPageComponent.reviewCacheByApi.get(this.api);
  2031. if (!cache || cache.identity !== identity) {
  2032. cache = { identity, pages: new Map() };
  2033. LearningPageComponent.reviewCacheByApi.set(this.api, cache);
  2034. }
  2035. return cache.pages;
  2036. }
  2037. private loadCalendar(initial = false, force = false): void {
  2038. const requestId=++this.calendarRequestId;
  2039. this.calendarRequest?.unsubscribe();
  2040. this.calendarError.set('');
  2041. const date = this.memorySelectedDate() || this.dateOnly();
  2042. const key = `${this.memoryStudentId()}|${date}|${this.reviewListPage()}|${this.reviewScope()}`;
  2043. const cache = this.reviewCache();
  2044. const cached = force ? undefined : cache.get(key);
  2045. if (cached) {
  2046. this.reviewPageData.set(cached);this.calendarItems.set(cached.items);this.restoreReviewScroll();
  2047. if(!this.memorySelectedDate())this.memorySelectedDate.set(date);
  2048. this.loading.set(false);this.calendarLoading.set(false);
  2049. return;
  2050. }
  2051. if (initial) this.loading.set(true); else this.calendarLoading.set(true);
  2052. this.calendarRequest = this.api.post<ReviewPage>('app_review_page',{uid:this.session.user()?.userId,studentId:this.memoryStudentId()||undefined,date,scope:this.reviewScope()||undefined,page:this.reviewListPage(),pageSize:20}).pipe(finalize(()=>{
  2053. if(requestId!==this.calendarRequestId)return;
  2054. if(initial)this.loading.set(false);else this.calendarLoading.set(false);
  2055. })).subscribe({next:({result})=>{
  2056. if(requestId!==this.calendarRequestId)return;
  2057. cache.set(key,result);
  2058. this.reviewPageData.set(result);this.calendarItems.set(result.items);this.restoreReviewScroll();
  2059. if(!this.memorySelectedDate())this.memorySelectedDate.set(this.dateOnly());
  2060. },error:(e:ApiError)=>{
  2061. if(requestId!==this.calendarRequestId)return;
  2062. if(initial)this.error.set(e.message);else this.calendarError.set(e.message);
  2063. }});
  2064. }
  2065. private calendarRequestId=0;
  2066. private restoredReviewScroll=false;
  2067. private restoreReviewScroll():void{if(this.restoredReviewScroll)return;this.restoredReviewScroll=true;const top=Number(history.state?.reviewScroll);if(Number.isFinite(top)&&top>0)setTimeout(()=>window.scrollTo({top,behavior:'instant'}));}
  2068. private loadAntiForget(): void {
  2069. const user = this.session.user();
  2070. const date = this.query('date') || this.compactDate();
  2071. this.antiStartedAt = Date.now();
  2072. this.api.get<unknown>('content_list', {
  2073. nid: 76,
  2074. modelId: 54,
  2075. myfield: `fxrl=${date}`,
  2076. myfield2: `UserId=${user?.userId}`,
  2077. cpage: 1,
  2078. psize: 30,
  2079. orders: 'CreateTime=asc',
  2080. }).pipe(finalize(() => this.loading.set(false))).subscribe({
  2081. next: ({ result }) => {
  2082. const words: Word[] = [];
  2083. for (const record of this.findList(result)) {
  2084. for (const item of this.parseArray(record['xxqs'])) words.push(this.toWord({ ...item, recordId: record['GeneralID'] }));
  2085. }
  2086. this.words.set(words.filter((word) => word.word));
  2087. },
  2088. error: (error: ApiError) => this.error.set(error.message),
  2089. });
  2090. if (this.query('hid')) {
  2091. this.api.get<unknown>('content_get', { id: this.query('hid') }).subscribe({
  2092. next: ({ result }) => this.antiHistory.set(this.findList(result)[0] ?? {}),
  2093. error: () => undefined,
  2094. });
  2095. }
  2096. this.api.get<unknown>('content_list', { nid: 255, modelId: 55, cpage: 1, psize: 30, myfield2: `UserId=${user?.userId}`, orders: 'CreateTime=asc' }).subscribe({
  2097. next: ({ result }) => this.myNewWords.set(this.findList(result)[0] ?? {}),
  2098. error: () => undefined,
  2099. });
  2100. }
  2101. private updateAntiProgress(word: Word): void {
  2102. const historyId = this.query('hid');
  2103. if (!historyId) return;
  2104. const seenWords = this.words().filter((item) => this.seen().has(item.id));
  2105. const previousIds = String(this.antiHistory()['xxjlid'] ?? '').split(',').filter(Boolean);
  2106. const recordId = String(word['recordId'] ?? '');
  2107. if (recordId && !previousIds.includes(recordId)) previousIds.push(recordId);
  2108. const scqs = seenWords.map((item) => ({ GeneralID: item.wordId, Title: item.word, gldy: item['gldy'] }));
  2109. const wordIds = `,${scqs.map((item) => item.GeneralID).join(',')},`;
  2110. this.api.post('content_update', {
  2111. content: JSON.stringify({ GeneralID: historyId }),
  2112. addon: JSON.stringify({
  2113. xxjlid: previousIds.join(','),
  2114. scqs: JSON.stringify(scqs),
  2115. yxx: scqs.length,
  2116. scqs2: wordIds,
  2117. times: Math.round((Date.now() - this.antiStartedAt) / 1000),
  2118. num: this.words().length,
  2119. }),
  2120. }).subscribe({ error: () => undefined });
  2121. }
  2122. loadExamHistory(more = false): void {
  2123. if(more && this.examHistoryLoading())return;
  2124. this.examHistoryRequest?.unsubscribe();this.examHistoryLoading.set(true);this.examHistoryError.set('');
  2125. const page=more?this.examHistoryPage+1:1;
  2126. this.examHistoryRequest=this.api.get<{items:SourceItem[];hasMore:boolean}>('app_exam_history',{page}).pipe(finalize(()=>this.examHistoryLoading.set(false))).subscribe({
  2127. next:({result})=>{
  2128. if(!result || !Array.isArray(result.items)){this.examHistoryError.set('测试记录返回异常,请重试');return;}
  2129. this.examHistoryPage=page;this.examHistoryMore.set(result.hasMore);
  2130. this.examHistory.set(more?[...this.examHistory(),...result.items]:result.items);
  2131. if(!more){this.previousExam.set(result.items.find(r=>r['resultAvailable'])||{});this.examCompareIds.set(result.items.filter(r=>r['resultAvailable']).slice(0,2).map(r=>String(r['GeneralID'])));}
  2132. },error:(e:ApiError)=>this.examHistoryError.set(e.message),
  2133. });
  2134. }
  2135. toggleExamComparison(item:SourceItem):void {
  2136. const id=String(item['GeneralID']);if(!item['resultAvailable'])return;
  2137. this.examCompareIds.update(ids=>ids.includes(id)?ids.filter(x=>x!==id):[...ids.slice(-1),id]);
  2138. }
  2139. private loadExam(): void {
  2140. this.stopExamTimer();this.examLoadRequest?.unsubscribe();this.examStarted.set(false);this.examSubmitted.set(false);this.examSaveError.set('');
  2141. this.loading.set(true);this.error.set('');this.questions.set([]);this.turnAskId();
  2142. const askId = Number(this.storageGet('askId') ?? 1);
  2143. this.loadExamHistory();
  2144. this.examLoadRequest=forkJoin({ask:this.api.get<unknown>('vote_ask',{id:askId}),questions:this.api.get<unknown>('vote_question',{askid:askId})}).pipe(finalize(()=>this.loading.set(false))).subscribe({
  2145. next:({ask,questions})=>{this.askInfo.set(this.findList(ask.result)[0]??{});const items=this.shuffle(this.findList(questions.result).map(item=>this.toQuestion(item)));this.questions.set(items);this.answers.set(items.map(q=>({qid:q.ID,qtype:String(q.QType??''),answer:'',result:2})));},
  2146. error:(e:ApiError)=>this.error.set(e.message),
  2147. });
  2148. }
  2149. private turnAskId(): void {
  2150. const current = Number(this.storageGet('askId') ?? 0);
  2151. this.storageSet('askId', current === 1 ? 2 : 1);
  2152. }
  2153. examScoreValue(exam: SourceItem): number {
  2154. return Number(exam['df'] ?? 0);
  2155. }
  2156. examAnalysis(exam: SourceItem): string {
  2157. const score = this.examScoreValue(exam);
  2158. if (score === 0) return '当前处于零基础阶段,可以从最常用的基础词汇开始建立词汇库。';
  2159. if (score <= 2) return '词汇量约为 100-200,处于英语入门或小学一、二年级水平。';
  2160. if (score <= 6) return '词汇量约为 200-400,相当于小学三、四年级水平。';
  2161. if (score <= 12) return '词汇量约为 400-600,相当于小学五、六年级水平。';
  2162. if (score <= 15) return '词汇量约为 600-900,相当于初一水平。';
  2163. if (score <= 18) return '词汇量约为 1000-1500,相当于初二水平。';
  2164. if (score <= 21) return '词汇量约为 1600-1800,相当于初三水平。';
  2165. if (score <= 33) return '词汇量约为 1800-2500,相当于高一水平。';
  2166. if (score <= 39) return '词汇量约为 2500-3000,相当于高二水平。';
  2167. if (score <= 42) return '词汇量约为 3000-3500,相当于高三一般水平。';
  2168. return '词汇量约为 3500-4500,达到高三较高或大学四级水平。';
  2169. }
  2170. examAdvice(exam: SourceItem): string {
  2171. const score = this.examScoreValue(exam);
  2172. if (score <= 6) return '建议先系统学习自然拼读并背诵小学、初中基础词汇,打牢读、认、写基础。';
  2173. if (score <= 12) return '建议重点背诵初中词汇,并通过简单阅读和听力练习持续扩展词汇量。';
  2174. if (score <= 21) return '建议继续背诵初高中核心词汇,配合英文阅读、听力和写作练习巩固运用。';
  2175. if (score <= 39) return '建议学习高二、高三词汇,并通过时文外刊、国家地理和 TED 演讲提升理解与表达。';
  2176. return '建议拓展大学四、六级或雅思托福词汇,通过 BBC、VOA 和英文原著把新词用于真实语境。';
  2177. }
  2178. private setExamAnswer(answer: ExamAnswer): void {
  2179. this.answers.update((items) => items.map((item, index) => index === this.currentIndex() ? answer : item));
  2180. }
  2181. private advanceExam(): void {
  2182. if (this.currentIndex() >= this.questions().length - 1) {
  2183. this.submitExam();
  2184. return;
  2185. }
  2186. this.currentIndex.update((value) => value + 1);
  2187. this.startExamTimer();
  2188. }
  2189. private startExamTimer(): void {
  2190. this.stopExamTimer();
  2191. this.timer.set(10);
  2192. this.examTimer = setInterval(() => {
  2193. if (this.timer() <= 1) {
  2194. this.skipExamQuestion();
  2195. } else {
  2196. this.timer.update((value) => value - 1);
  2197. }
  2198. }, 1000);
  2199. }
  2200. private stopExamTimer(): void {
  2201. if (this.examTimer) clearInterval(this.examTimer);
  2202. this.examTimer = null;
  2203. }
  2204. private saveExamLog(answerId: string | number): void {
  2205. const user = this.session.user();
  2206. const answers = this.answers();
  2207. const score = answers.filter((item) => item.result === 1).length;
  2208. const previous = this.previousExam();
  2209. this.examScore.set(score);
  2210. const content: SourceItem = { ModelID: 61, nodeId: 389, inputer: user?.honeyName, status: 99, Hits: 1, title: user?.honeyName };
  2211. const addon = {
  2212. askid: this.currentQuestion()?.AskID ?? this.askInfo()['ID'],
  2213. prev_score: previous['df'] ?? 0,
  2214. totalScore: answers.length,
  2215. wrong: answers.filter((item) => item.result === 0).length,
  2216. dontKnow: answers.filter((item) => item.result === 2).length,
  2217. answerid: answerId || 0,
  2218. df: score,
  2219. UserID: user?.userId,
  2220. };
  2221. this.api.post('content_add', { requestKey:this.examLogKey,content: JSON.stringify(content), addon: JSON.stringify(addon) }).pipe(finalize(() => this.submitting.set(false))).subscribe({
  2222. next: () => {
  2223. this.examStarted.set(false);
  2224. this.examSubmitted.set(true);
  2225. this.platform.toast('答题结果已保存', 'success');this.loadExamHistory();
  2226. },
  2227. error: (error: ApiError) => this.examSaveError.set(error.message),
  2228. });
  2229. }
  2230. private beginSelectedFlow(chosen: Word[], mode: '' | 'newword' | 'history_word'): void {
  2231. if (this.query('orderId') && !mode) {
  2232. this.submitting.set(true);
  2233. this.saveLessonBatch('open-draft', chosen).pipe(finalize(() => this.submitting.set(false))).subscribe({
  2234. next: result => {
  2235. if (result.resumed) {
  2236. this.platform.toast('还有待确认批次,请先确认掌握状态');
  2237. this.navigateStage('/pages/stu/pl_end');
  2238. return;
  2239. }
  2240. this.beginSelectedStages(chosen, mode, true);
  2241. },
  2242. error: (e: ApiError) => this.platform.toast(e.message, 'error'),
  2243. });
  2244. return;
  2245. }
  2246. this.beginSelectedStages(chosen, mode);
  2247. }
  2248. private beginSelectedStages(chosen: Word[], mode: '' | 'newword' | 'history_word', preserveBatch = false): void {
  2249. if (!preserveBatch) this.clearLearningStorage();
  2250. if (mode) this.storageSet('learn_mode', mode);
  2251. const pages: Word[][] = [];
  2252. for (let index = 0; index < chosen.length; index += 6) pages.push(chosen.slice(index, index + 6));
  2253. const storageKey = mode === 'newword' ? 'choose_newword_learn' : mode === 'history_word' ? 'choose_hisword_learn' : 'choose_word_learn';
  2254. this.storageSet(storageKey, pages[0] ?? chosen);
  2255. this.storageSet('_page_current_learn', 1);
  2256. this.storageSet('_page_total_page', pages.length);
  2257. this.storageSet('_page_word_orilist', pages);
  2258. sessionStorage.setItem(this.learningStorageKey('selectedWords'), JSON.stringify(pages[0] ?? chosen));
  2259. const wordbookStudentId = mode === 'newword' ? this.coachWordbookStudentId : 0;
  2260. void this.router.navigate(['/pages/stu/stu_con'], {
  2261. replaceUrl: true,
  2262. state: { learningReturnUrl: this.router.url },
  2263. queryParams: wordbookStudentId ? {wordbookStudentId} : {
  2264. nids: this.query('nids') || this.query('nid'),
  2265. pnid: this.query('pnid'),
  2266. bindingId: this.query('bindingId'),
  2267. orderId: this.query('orderId'),
  2268. },
  2269. });
  2270. }
  2271. private navigateStage(path: string): void {
  2272. const wordbookStudentId = this.coachWordbookStudentId;
  2273. void this.router.navigate([path], {
  2274. replaceUrl: true,
  2275. state: { learningReturnUrl: history.state?.learningReturnUrl },
  2276. queryParams: wordbookStudentId ? {wordbookStudentId} : {
  2277. nid: this.query('nid'),
  2278. nids: this.query('nids'),
  2279. pnid: this.query('pnid'),
  2280. bindingId: this.query('bindingId'),
  2281. orderId: this.query('orderId') || this.query('id'),
  2282. },
  2283. });
  2284. }
  2285. private readLearningWords(): Word[] {
  2286. const currentPage = Number(this.storageGet('_page_current_learn') ?? 1);
  2287. const pages = this.parseArray(this.storageGet('_page_word_orilist'));
  2288. if (pages.length) {
  2289. const page = pages[currentPage - 1];
  2290. if (Number.isInteger(currentPage) && currentPage > 0 && Array.isArray(page)) {
  2291. const mode = String(this.storageGet('learn_mode') ?? '');
  2292. const key = mode === 'newword' ? 'choose_newword_learn' : mode === 'history_word' ? 'choose_hisword_learn' : 'choose_word_learn';
  2293. this.storageSet(key, page);
  2294. sessionStorage.setItem(this.learningStorageKey('selectedWords'), JSON.stringify(page));
  2295. return page.map((item) => this.toWord(item as SourceItem));
  2296. }
  2297. return [];
  2298. }
  2299. const mode = String(this.storageGet('learn_mode') ?? '');
  2300. const key = mode === 'newword' ? 'choose_newword_learn' : mode === 'history_word' ? 'choose_hisword_learn' : 'choose_word_learn';
  2301. const stored = this.parseArray(this.storageGet(key));
  2302. if (stored.length) return stored.map((item) => this.toWord(item));
  2303. return this.parseArray(sessionStorage.getItem(this.learningStorageKey('selectedWords'))).map((item) => this.toWord(item));
  2304. }
  2305. private readAllLearningWords(): Word[] {
  2306. const pages = this.parseArray(this.storageGet('_page_word_orilist'));
  2307. if (pages.length && pages.every((page) => Array.isArray(page))) {
  2308. return pages.flatMap((page) => (page as SourceItem[]).map((item) => this.toWord(item)));
  2309. }
  2310. return this.readLearningWords();
  2311. }
  2312. private clearLearningStorage(): void { this.draft().clear(); }
  2313. private resetPageState(): void {
  2314. this.stopWordPlayback();
  2315. this.outsideChoicePool = null;
  2316. this.choicesLoading.set(false);
  2317. this.choiceOptionsVersion++;
  2318. this.choiceOptionsRequest?.unsubscribe();
  2319. this.stopExamTimer();
  2320. this.nodes.set([]);
  2321. this.selectedNodes.set(new Set());
  2322. this.words.set([]);
  2323. this.historyPreviewWords = [];
  2324. this.historyWordRevealed.set(new Set());
  2325. this.historySources.set([]);
  2326. this.wordPreviewPage.set(1);
  2327. this.wordPreviewTotal.set(0);
  2328. this.wordPreviewLoading.set(false);
  2329. this.calendarLoading.set(false);
  2330. this.calendarError.set('');
  2331. this.selected.set(new Set());
  2332. this.newWordSelectionCache.clear();
  2333. this.newWordBulkSelection.set(null);
  2334. this.newWordCounts.set({ pending: 0, completed: 0 });
  2335. this.legacyNewWords = null;
  2336. this.selectionRevealed.set(new Set());
  2337. this.selectionAssessment.set({});
  2338. this.bulkSelection.set(null);
  2339. this.knownSaveRetry.set(false);
  2340. this.knownSaveContinuation = null;
  2341. this.courseSelectionNeedsRebase = false;
  2342. this.activeSelectionBucket.set('pending');
  2343. this.coursePass.set(0);
  2344. this.coursePassCounts.set(null);
  2345. this.bookPassCounts.set(null);
  2346. this.courseSelectionCache.set([]);
  2347. this.currentIndex.set(0);
  2348. this.revealed.set(false);
  2349. this.completed.set(false);
  2350. this.correct.set(0);
  2351. this.unknown.set([]);
  2352. this.studyStep.set(1);
  2353. this.repetitions.set({});
  2354. this.studyMeaningRevealed.set(new Set());
  2355. this.matchLeft.set([]);
  2356. this.matchRight.set([]);
  2357. this.leftChoice.set('');
  2358. this.rightChoice.set('');
  2359. this.choiceOptions.set([]);
  2360. this.reviewState.set({});
  2361. this.seen.set(new Set());
  2362. this.recordRevealed.set(new Set());
  2363. this.calendarItems.set([]);
  2364. if(!this.isCalendarPage)this.memoryStudentId.set('');
  2365. this.reviewCompletion.set(null);
  2366. this.examStarted.set(false);
  2367. this.examSubmitted.set(false);
  2368. }
  2369. private toWord(item: SourceItem): Word {
  2370. const detailValue = Array.isArray(item['detail']) ? item['detail'][0] : item['detail'];
  2371. const detail = detailValue && typeof detailValue === 'object' ? detailValue as SourceItem : {};
  2372. const source = { ...detail, ...item };
  2373. const id = String(item['GeneralID'] ?? detail['GeneralID'] ?? item['ID'] ?? item['id'] ?? item['gid'] ?? item['Title'] ?? detail['Title'] ?? '');
  2374. const wordId = String(detail['GeneralID'] ?? item['GeneralID'] ?? item['gldy'] ?? id);
  2375. return {
  2376. ...source,
  2377. detail,
  2378. id,
  2379. wordId,
  2380. nodeId: String(item['NodeID'] ?? detail['NodeID'] ?? item['nodeId'] ?? ''),
  2381. word: String(item['Title'] ?? detail['Title'] ?? item['word'] ?? detail['word'] ?? item['Word'] ?? ''),
  2382. meaning: [item['sy'], detail['sy'], item['jssy'], detail['jssy'], item['Translate'], detail['Translate'], item['Meaning'], item['meaning']]
  2383. .map(value => String(value ?? '').trim()).find(Boolean) || '',
  2384. phonetic: [item['yb'], detail['yb'], item['Phonetic'], detail['Phonetic'], item['phonetic'], detail['phonetic']].map(value => String(value ?? '').trim()).find(Boolean) || '',
  2385. audio: [typeof item['audio'] === 'string' ? item['audio'] : '', item['yp'], detail['yp'], item['dy'], detail['dy']].map(value => String(value ?? '').trim()).find(Boolean) || '',
  2386. };
  2387. }
  2388. private toNewWord(item: SourceItem): Word {
  2389. const detailValue = Array.isArray(item['detail']) ? item['detail'][0] : item['detail'];
  2390. const detail = detailValue && typeof detailValue === 'object' ? detailValue as SourceItem : {};
  2391. const detailTitle = String(detail['Title'] ?? '').trim();
  2392. const storedTitle = String(item['Title'] ?? '').split('@')[0].trim();
  2393. // The envelope identifies a practice record; selection and study need the vocabulary ID.
  2394. // Normalize GeneralID too so stored words keep the same identity in subsequent stages.
  2395. return this.toWord({
  2396. ...item,
  2397. GeneralID: detail['GeneralID'] ?? item['scid'] ?? item['GeneralID'],
  2398. Title: detailTitle || storedTitle,
  2399. });
  2400. }
  2401. private toQuestion(item: SourceItem): ExamQuestion {
  2402. let options: ExamOption[] = [];
  2403. const raw = item['QOption'];
  2404. if (Array.isArray(raw)) {
  2405. options = raw as ExamOption[];
  2406. } else if (typeof raw === 'string') {
  2407. try { options = JSON.parse(raw) as ExamOption[]; } catch { options = []; }
  2408. }
  2409. return {
  2410. ...item,
  2411. ID: String(item['ID'] ?? item['GeneralID'] ?? ''),
  2412. AskID: String(item['AskID'] ?? ''),
  2413. QType: String(item['QType'] ?? ''),
  2414. QTitle: String(item['QTitle'] ?? ''),
  2415. QContent: this.cleanText(String(item['QContent'] ?? '')),
  2416. QOption: options,
  2417. };
  2418. }
  2419. private wordAudioUrl(path: string): string {
  2420. if (/^(data:|https?:\/\/|\/)/i.test(path)) return this.api.assetUrl(path);
  2421. return this.api.assetUrl(/^UploadFiles\//i.test(path) ? path : `UploadFiles/${path}`);
  2422. }
  2423. private setWordSelected(word: Word, shouldSelect: boolean): boolean {
  2424. const current = this.selected();
  2425. if (shouldSelect && !current.has(word.id) && current.size >= this.selectionLimit) {
  2426. this.platform.toast(`本次最多选择 ${this.selectionLimit} 个单词`, 'error');
  2427. return false;
  2428. }
  2429. const next = new Set(current);
  2430. if (shouldSelect) next.add(word.id);
  2431. else next.delete(word.id);
  2432. this.selected.set(next);
  2433. return true;
  2434. }
  2435. private setSelectionAssessment(word: Word, assessment: 'known' | 'unknown'): void {
  2436. this.selectionAssessment.update((current) => ({ ...current, [word.id]: assessment }));
  2437. }
  2438. private clearSelectionAssessment(word: Word): void {
  2439. this.selectionAssessment.update((current) => Object.fromEntries(Object.entries(current).filter(([id]) => id !== word.id)) as Record<string, 'known' | 'unknown'>);
  2440. }
  2441. private saveWordProgress(words: Word[], owner: Pick<AppUser, 'userId'> | null | undefined, mode: 'practice' | 'recognized' = 'practice'): Observable<unknown> {
  2442. if (!words.length) return of(null);
  2443. const batches: Word[][] = [];
  2444. for (let index = 0; index < words.length; index += 100) batches.push(words.slice(index, index + 100));
  2445. return from(batches).pipe(concatMap(batch => this.api.post('e_add_words', {
  2446. uid: owner?.userId,
  2447. wordsId: batch.map((word) => word.wordId).join(','),
  2448. kcid: (this.meta.path === 'pages/stu/pl_end' ? this.orderInfo()['learningCourseId'] : '') || this.query('pnid') || this.query('kcid') || this.orderInfo()['kcid'],
  2449. save: 1,
  2450. ...(mode === 'recognized' ? {recognized: true} : {}),
  2451. ...(this.coachWordbookStudentId ? {scope: 'wordbook'} : {}),
  2452. requestKey:this.draft().command((mode === 'recognized' ? 'recognize:' : 'learn:')+batch.map(w=>w.wordId+'@'+this.savedCoursePass(w)).sort().join(',')),
  2453. }).pipe(tap(() => { if (mode === 'recognized') this.commitKnownWords(batch); }))), toArray());
  2454. }
  2455. private commitKnownWords(words: Word[]): void {
  2456. if (this.isRefineSelectionPage) this.courseSelectionNeedsRebase = true;
  2457. const ids = new Set(words.map(word => word.id));
  2458. const update = (current: Word[]) => current.map(word => ids.has(word.id) ? {...word, recognized: true, w_learned: Math.max(1, Number(word['w_learned']) || 0)} : word);
  2459. this.words.update(update);
  2460. this.courseSelectionCache.update(update);
  2461. const changes = this.coursePassTabs.map(() => 0);
  2462. for (const word of words) { changes[this.savedCoursePass(word)]--; changes[this.recognizedTab]++; }
  2463. const advance = (counts: number[] | null) => counts ? counts.map((count, pass) => Math.max(0, count + changes[pass])) : null;
  2464. this.coursePassCounts.update(advance);
  2465. this.bookPassCounts.update(advance);
  2466. this.selectionAssessment.update(current => Object.fromEntries(Object.entries(current).filter(([id]) => !ids.has(id))) as Record<string, 'known' | 'unknown'>);
  2467. }
  2468. private findList(value: unknown): SourceItem[] {
  2469. if (Array.isArray(value)) return value as SourceItem[];
  2470. if (value && typeof value === 'object') {
  2471. for (const nested of Object.values(value)) {
  2472. if (Array.isArray(nested)) return nested as SourceItem[];
  2473. if (nested && typeof nested === 'object') {
  2474. for (const child of Object.values(nested)) if (Array.isArray(child)) return child as SourceItem[];
  2475. }
  2476. }
  2477. }
  2478. return [];
  2479. }
  2480. private parseArray(value: unknown): SourceItem[] {
  2481. if (Array.isArray(value)) return value as SourceItem[];
  2482. if (typeof value !== 'string' || !value) return [];
  2483. try {
  2484. const parsed = JSON.parse(value) as unknown;
  2485. return Array.isArray(parsed) ? parsed as SourceItem[] : [];
  2486. } catch {
  2487. return [];
  2488. }
  2489. }
  2490. private shuffle<T>(items: T[]): T[] {
  2491. const copy = [...items];
  2492. for (let index = copy.length - 1; index > 0; index -= 1) {
  2493. const target = Math.floor(Math.random() * (index + 1));
  2494. [copy[index], copy[target]] = [copy[target], copy[index]];
  2495. }
  2496. return copy;
  2497. }
  2498. private draft():LearningDraft {
  2499. const wordbookStudentId = this.coachWordbookStudentId;
  2500. if (wordbookStudentId) return new LearningDraft(`xiaoshu.learning.${this.session.user()?.userId}.${wordbookStudentId}.wordbook`);
  2501. const learner=this.canStartPointReading?this.session.student():this.session.user();
  2502. return new LearningDraft(`xiaoshu.learning.${this.session.user()?.userId}.${learner?.userId}.${this.query('orderId') ? this.query('orderId') + '.' + (this.query('bindingId') || 'unbound') : this.query('bindingId') || 'practice'}`);
  2503. }
  2504. private learningStorageKey(key:string):string{return this.draft().key(key);}
  2505. private storageGet(key:string):unknown{return this.draft().get(key);}
  2506. private storageSet(key:string,value:unknown):void{this.draft().set(key,value);}
  2507. private query(name: string): string {
  2508. return this.route.snapshot.queryParamMap.get(name) ?? '';
  2509. }
  2510. private cleanText(value: string): string {
  2511. return value.replace(/<\/?[^>]*>/g, '').replace(/&nbsp;/gi, '').trim();
  2512. }
  2513. private dateOnly(): string {
  2514. const date = new Date();
  2515. return `${date.getFullYear()}-${this.pad(date.getMonth() + 1)}-${this.pad(date.getDate())}`;
  2516. }
  2517. private compactDate(): string {
  2518. return this.dateOnly().replaceAll('-', '');
  2519. }
  2520. private dateTime(seconds = false): string {
  2521. const date = new Date();
  2522. return `${this.dateOnly()} ${this.pad(date.getHours())}:${this.pad(date.getMinutes())}${seconds ? `:${this.pad(date.getSeconds())}` : ''}`;
  2523. }
  2524. private pad(value: number): string {
  2525. return String(value).padStart(2, '0');
  2526. }
  2527. }