learning-page.component.ts 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  1. import { DropdownDirective } from '../../shared/dropdown.directive';
  2. import { LearningDraft } from '../../core/learning-draft';
  3. import { ReviewPage, reviewCalendar } from '../../core/review-page';
  4. import { CommonModule } from '@angular/common';
  5. import { ChangeDetectionStrategy, Component, computed, inject, OnDestroy, OnInit, signal } from '@angular/core';
  6. import { ActivatedRoute, Router } from '@angular/router';
  7. import {
  8. Activity,
  9. BookOpen,
  10. BrainCircuit,
  11. Check,
  12. CheckCheck,
  13. ChevronLeft,
  14. ChevronRight,
  15. CircleHelp,
  16. Clock3,
  17. Flag,
  18. Headphones,
  19. Library,
  20. LucideAngularModule,
  21. Play,
  22. RefreshCw,
  23. RotateCcw,
  24. Star,
  25. Trash2,
  26. Volume2,
  27. X,
  28. } from 'lucide-angular';
  29. import { catchError, finalize, forkJoin, Observable, of, Subscription, switchMap, throwError } from 'rxjs';
  30. import { GAME_AUDIO } from '../../core/app.constants';
  31. import { ApiError, ApiService } from '../../core/api.service';
  32. import {
  33. AntiForgetCalendarDay,
  34. antiForgetCompleted,
  35. antiForgetDate,
  36. antiForgetTasksOnDate,
  37. buildAntiForgetCalendar,
  38. buildAntiForgetView,
  39. mergeAntiForgetItems,
  40. nearestAntiForgetDate,
  41. } from '../../core/anti-forget';
  42. import { AppUser, PageMeta } from '../../core/models';
  43. import { canStartTeacherLedLearning, isTeacherLedLearningPath } from '../../core/learning-access';
  44. import { isLearningStage, learningReturnUrl } from '../../core/learning-navigation';
  45. import { PlatformService } from '../../core/platform.service';
  46. import { SessionService } from '../../core/session.service';
  47. type SourceItem = Record<string, unknown>;
  48. interface Word extends SourceItem {
  49. id: string;
  50. wordId: string;
  51. nodeId: string;
  52. word: string;
  53. meaning: string;
  54. phonetic: string;
  55. audio: string;
  56. }
  57. interface LetterChoice {
  58. value: string;
  59. used: boolean;
  60. }
  61. interface ExamOption {
  62. text: string;
  63. value: string | number;
  64. checked?: boolean;
  65. }
  66. interface ExamQuestion extends SourceItem {
  67. ID: string | number;
  68. AskID?: string | number;
  69. QType?: string | number;
  70. QContent: string;
  71. QTitle?: string;
  72. QOption: ExamOption[];
  73. }
  74. interface ExamAnswer {
  75. qid: string | number;
  76. qtype: string | number;
  77. answer: string | number;
  78. result: 0 | 1 | 2;
  79. }
  80. interface MemoryStudentOption {
  81. id: string;
  82. name: string;
  83. taskCount: number;
  84. }
  85. const WORD_CATALOG_CATEGORIES = [
  86. { label: '小学', pid: 8 },
  87. { label: '初中', pid: 9 },
  88. { label: '高中', pid: 10 },
  89. { label: '大学+', pid: 11 },
  90. { label: '出国', pid: 12 },
  91. ] as const;
  92. @Component({
  93. selector: 'app-learning-page',
  94. standalone: true,
  95. imports: [DropdownDirective, CommonModule, LucideAngularModule],
  96. templateUrl: './learning-page.component.html',
  97. styleUrl: './learning-page.component.scss',
  98. changeDetection: ChangeDetectionStrategy.OnPush,
  99. })
  100. export class LearningPageComponent implements OnInit, OnDestroy {
  101. readonly meta = inject(ActivatedRoute).snapshot.data['meta'] as PageMeta;
  102. readonly nodes = signal<SourceItem[]>([]);
  103. readonly catalogCategories = WORD_CATALOG_CATEGORIES;
  104. readonly catalogCategoryIndex = signal(0);
  105. readonly selectedNodes = signal<Set<string>>(new Set());
  106. readonly words = signal<Word[]>([]);
  107. readonly wordPreviewPage = signal(1);
  108. readonly wordPreviewTotal = signal(0);
  109. readonly wordPreviewLoading = signal(false);
  110. readonly selected = signal<Set<string>>(new Set());
  111. readonly selectionRevealed = signal<Set<string>>(new Set());
  112. readonly selectionAssessment = signal<Record<string, 'known' | 'unknown'>>({});
  113. readonly activeSelectionBucket = signal<'pending' | 'completed'>('pending');
  114. readonly currentIndex = signal(0);
  115. readonly revealed = signal(false);
  116. readonly completed = signal(false);
  117. readonly correct = signal(0);
  118. readonly unknown = signal<Word[]>([]);
  119. readonly loading = signal(false);
  120. readonly calendarLoading = signal(false);
  121. readonly calendarError = signal('');
  122. readonly submitting = signal(false);
  123. readonly selectionTotal=signal(0);readonly selectionPage=signal(1);readonly selectionLoading=signal(false);private selectionRequest?:Subscription;
  124. readonly error = signal('');
  125. readonly studyStep = signal<1 | 2 | 3>(1);
  126. readonly repetitions = signal<Record<string, number>>({});
  127. readonly matchLeft = signal<Word[]>([]);
  128. readonly matchRight = signal<Word[]>([]);
  129. readonly leftChoice = signal('');
  130. readonly rightChoice = signal('');
  131. readonly choiceOptions = signal<Word[]>([]);
  132. readonly letters = signal<LetterChoice[]>([]);
  133. readonly assembled = signal('');
  134. readonly spellingCorrect = signal(false);
  135. readonly reviewState = signal<Record<string, 0 | 1 | 2>>({});
  136. readonly seen = signal<Set<string>>(new Set());
  137. readonly recordRevealed = signal<Set<string>>(new Set());
  138. readonly calendarItems = signal<SourceItem[]>([]);
  139. readonly memoryStudentId = signal('');
  140. readonly memoryMonth = signal(new Date(new Date().getFullYear(), new Date().getMonth(), 1, 12));
  141. readonly memorySelectedDate = signal('');
  142. readonly orderInfo = signal<SourceItem>({});
  143. readonly learnedRecord = signal<SourceItem>({});
  144. readonly antiHistory = signal<SourceItem>({});
  145. readonly myNewWords = signal<SourceItem>({});
  146. readonly examStarted = signal(false);
  147. readonly examSubmitted = signal(false);
  148. readonly askInfo = signal<SourceItem>({});
  149. readonly previousExam = signal<SourceItem>({});
  150. readonly questions = signal<ExamQuestion[]>([]);
  151. readonly answers = signal<ExamAnswer[]>([]);
  152. readonly timer = signal(10);
  153. readonly examScore = signal(0);
  154. readonly icons = {
  155. Activity,
  156. BookOpen,
  157. BrainCircuit,
  158. Check,
  159. CheckCheck,
  160. ChevronLeft,
  161. ChevronRight,
  162. CircleHelp,
  163. Clock3,
  164. Flag,
  165. Headphones,
  166. Library,
  167. Play,
  168. RefreshCw,
  169. RotateCcw,
  170. Star,
  171. Trash2,
  172. Volume2,
  173. X,
  174. };
  175. readonly antiForgetChart = {
  176. forgettingPath: 'M 26 12 C 38 60 82 88 304 95',
  177. 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',
  178. continuationPath: 'M 276 12 C 284 15 294 16 304 16',
  179. reviewEvents: [
  180. { day: 2, x: 40, y: 61, path: 'M 26 12 C 30 30 34 49 40 61' },
  181. { day: 4, x: 68, y: 40, path: 'M 40 12 C 47 22 57 35 68 40' },
  182. { day: 7, x: 110, y: 27, path: 'M 68 12 C 79 17 94 24 110 27' },
  183. { day: 12, x: 179, y: 19, path: 'M 110 12 C 128 15 155 19 179 19' },
  184. { day: 19, x: 276, y: 17, path: 'M 179 12 C 205 15 244 17 276 17' },
  185. ],
  186. days: Array.from({ length: 21 }, (_, index) => ({ day: index + 1, x: 26 + index * 13.9 })),
  187. };
  188. readonly current = computed(() => this.words()[this.currentIndex()] ?? null);
  189. readonly completedSelectionWords = computed(() => this.words().filter((word) => this.selectionWordCompleted(word)));
  190. readonly pendingSelectionWords = computed(() => this.words().filter((word) => !this.selectionWordCompleted(word)));
  191. readonly newlyKnownWords = computed(() => this.words().filter((word) => !this.wordHistoricallyLearned(word) && this.selectionAssessment()[word.id] === 'known'));
  192. readonly selectionActionLabel = computed(() => {
  193. const hasLearningWords = this.selected().size > 0;
  194. const hasKnownWords = this.newlyKnownWords().length > 0;
  195. if (hasLearningWords && hasKnownWords) return '保存并开始学习';
  196. if (hasKnownWords) return '保存识词结果';
  197. return '开始学习';
  198. });
  199. readonly currentQuestion = computed(() => this.questions()[this.currentIndex()] ?? null);
  200. readonly wordPreviewPageCount = computed(() => Math.max(1, Math.ceil(this.wordPreviewTotal() / this.wordPreviewPageSize)));
  201. readonly wordPreviewPages = computed(() => {
  202. const pageCount = this.wordPreviewPageCount();
  203. if (pageCount <= 3) return Array.from({ length: pageCount }, (_, index) => index + 1);
  204. const start = Math.min(Math.max(1, this.wordPreviewPage() - 1), pageCount - 2);
  205. return Array.from({ length: 3 }, (_, index) => start + index);
  206. });
  207. readonly wordPreviewRangeStart = computed(() => this.wordPreviewTotal()
  208. ? ((this.wordPreviewPage() - 1) * this.wordPreviewPageSize) + 1
  209. : 0);
  210. readonly wordPreviewRangeEnd = computed(() => Math.min(this.wordPreviewPage() * this.wordPreviewPageSize, this.wordPreviewTotal()));
  211. readonly memoryStudents = computed(() => {
  212. if(this.reviewPageData()?.students)return this.reviewPageData()!.students!.map(s=>({id:String(s.id),name:s.name,taskCount:s.taskCount}));
  213. const students = new Map<string, MemoryStudentOption>();
  214. for (const item of this.calendarItems()) {
  215. const id = String(item['yhid'] ?? '').trim();
  216. if (!id) continue;
  217. const current = students.get(id);
  218. if (current) current.taskCount += 1;
  219. else students.set(id, { id, name: this.calendarStudent(item) || `学员 ${id}`, taskCount: 1 });
  220. }
  221. return [...students.values()].sort((left, right) => left.name.localeCompare(right.name, 'zh-CN'));
  222. });
  223. readonly memorySelectedStudentName = computed(() => this.memoryStudents().find((student) => student.id === this.memoryStudentId())?.name || '全部学员');
  224. readonly reviewPageData=signal<ReviewPage|null>(null); readonly reviewListPage=signal(1);
  225. readonly memoryFilteredItems = computed(() => {
  226. const studentId = this.memoryStudentId();
  227. return studentId ? this.calendarItems().filter((item) => String(item['yhid'] ?? '') === studentId) : this.calendarItems();
  228. });
  229. readonly memoryView = computed(() => buildAntiForgetView(this.memoryFilteredItems()));
  230. readonly memorySummary = computed(() => this.memoryView().summary);
  231. readonly memoryCalendar=computed(()=>reviewCalendar(this.reviewPageData()?.dates||[],this.memoryMonth(),this.memorySelectedDate()));
  232. readonly memorySelectedTasks = computed(() => antiForgetTasksOnDate(this.memoryFilteredItems(), this.memorySelectedDate()));
  233. readonly memorySelectedLabel = computed(() => {
  234. const value = this.memorySelectedDate();
  235. if (!value) return '';
  236. const [year, month, day] = value.split('-').map(Number);
  237. return new Intl.DateTimeFormat('zh-CN', { month: 'long', day: 'numeric', weekday: 'short' }).format(new Date(year, month - 1, day, 12));
  238. });
  239. readonly memoryTotalCount = computed(() => this.reviewPageData()?.summary.total||0);
  240. readonly memoryCompletedCount = computed(() => this.reviewPageData()?.summary.completed||0);
  241. readonly memoryDueCount = computed(() => this.reviewPageData()?.summary.due||0);
  242. readonly memoryProgress=computed(()=>{const s=this.reviewPageData()?.summary;return s?.total?Math.round(s.completed/s.total*100):0;});
  243. readonly progress = computed(() => {
  244. const total = this.isMatchingPage ? this.words().length : this.words().length || this.questions().length;
  245. if (!total) return 0;
  246. if (this.isMatchingPage) return Math.round(((total - this.matchLeft().length) / total) * 100);
  247. return Math.round(((this.currentIndex() + (this.completed() ? 1 : 0)) / total) * 100);
  248. });
  249. private readonly route = inject(ActivatedRoute);
  250. private readonly router = inject(Router);
  251. private readonly api = inject(ApiService);
  252. private readonly session = inject(SessionService);
  253. private readonly platform = inject(PlatformService);
  254. private readonly wordPreviewPageSize = 30;
  255. private examTimer: ReturnType<typeof setInterval> | null = null;
  256. private antiStartedAt = Date.now();
  257. private calendarRequest?: Subscription;
  258. ngOnInit(): void {
  259. if (isTeacherLedLearningPath(this.meta.path) && !this.isReadOnlyWordView && !this.isReadOnlySelectionPage && !this.canStartPointReading) {
  260. this.platform.toast('点读学习由陪练老师在上课时发起', 'error');
  261. void this.router.navigateByUrl('/pages/home/cart');
  262. return;
  263. }
  264. if (this.isCatalogPage && Number(this.session.user()?.groupId) === 1) {
  265. void this.router.navigateByUrl('/pages/home/cart');
  266. return;
  267. }
  268. this.load();
  269. }
  270. ngOnDestroy(): void {
  271. this.calendarRequestId++;this.calendarRequest?.unsubscribe();this.selectionRequest?.unsubscribe();
  272. this.stopExamTimer();
  273. this.platform.stopAudio();
  274. }
  275. get isNodePage(): boolean {
  276. return ['pages/stu/index', 'pages/stu/stu_list'].includes(this.meta.path);
  277. }
  278. get isCatalogPage(): boolean {
  279. return this.meta.path === 'pages/stu/index';
  280. }
  281. get isUnitListPage(): boolean {
  282. return this.meta.path === 'pages/stu/stu_list';
  283. }
  284. get isSelectionPage(): boolean {
  285. return ['pages/stu/stu_abc', 'pages/his/his_words', 'pages/member/starshop'].includes(this.meta.path);
  286. }
  287. get isHistoryWordView(): boolean {
  288. return this.meta.path === 'pages/his/his_words';
  289. }
  290. get isRefineSelectionPage(): boolean {
  291. return this.meta.path === 'pages/stu/stu_abc';
  292. }
  293. get isStudyListPage(): boolean {
  294. return this.meta.path === 'pages/stu/stu_con';
  295. }
  296. get isReadOnlySelectionPage(): boolean {
  297. return !this.canStartPointReading && this.isRefineSelectionPage && this.query('readonly') === '1';
  298. }
  299. get canStartPointReading(): boolean {
  300. return canStartTeacherLedLearning(this.session.groupId());
  301. }
  302. get isReadOnlyWordView(): boolean {
  303. if (this.isHistoryWordView) return true;
  304. return !this.canStartPointReading && this.isStudyListPage && this.query('readonly') === '1';
  305. }
  306. get isMatchingPage(): boolean {
  307. return this.meta.path === 'pages/stu/stu3';
  308. }
  309. get isListeningPage(): boolean {
  310. return this.meta.path === 'pages/stu/stu4';
  311. }
  312. get isSpellingPage(): boolean {
  313. return ['pages/stu/stu5', 'pages/stu/pl_stu5'].includes(this.meta.path);
  314. }
  315. get hasNextWordBatch(): boolean {
  316. const currentPage = Number(this.storageGet('_page_current_learn') ?? 1);
  317. const pages = this.parseArray(this.storageGet('_page_word_orilist'));
  318. return Number.isInteger(currentPage) && currentPage > 0
  319. && Array.isArray(pages[currentPage]) && pages[currentPage].length > 0;
  320. }
  321. get stageActionLabel(): string {
  322. if (this.isMatchingPage) return '进入听音识意';
  323. if (this.isListeningPage) return '进入组合拼写';
  324. if (this.hasNextWordBatch) return '学习下一组单词';
  325. const mode = String(this.storageGet('learn_mode') ?? '');
  326. if (mode === 'newword' || mode === 'history_word') return '完成学习并返回';
  327. return this.meta.path === 'pages/stu/pl_stu5' && !this.query('orderId') ? '保存并结束学习' : '查看学习结果';
  328. }
  329. get canReturnToLearningEntry(): boolean {
  330. return isLearningStage(this.meta.path, this.route.snapshot.queryParamMap);
  331. }
  332. returnToLearningEntry(): void {
  333. const legacyOrderId = this.meta.path === 'pages/stu/pl_end' ? this.query('id') : '';
  334. const url = legacyOrderId ? `/pages/shop/get_order?id=${encodeURIComponent(legacyOrderId)}`
  335. : learningReturnUrl(this.route.snapshot.queryParamMap, history.state?.learningReturnUrl);
  336. void this.router.navigateByUrl(url, { replaceUrl: true });
  337. }
  338. get isReviewPage(): boolean {
  339. return ['pages/stu/stu6', 'pages/stu/pl_end'].includes(this.meta.path);
  340. }
  341. get isCalendarPage(): boolean {
  342. return this.meta.path === 'pages/stu/stu_calendar';
  343. }
  344. get isAntiForgetPage(): boolean {
  345. return this.meta.path === 'pages/stu/stu7';
  346. }
  347. get isRecordPage(): boolean {
  348. return this.meta.path === 'pages/stu/record';
  349. }
  350. get isExamPage(): boolean {
  351. return this.meta.path === 'pages/his/exam';
  352. }
  353. get isReportPage(): boolean {
  354. return this.meta.path === 'pages/stu/stu_ok';
  355. }
  356. get selectionLimit(): number {
  357. return this.meta.path === 'pages/stu/stu_abc' ? 30 : this.words().length;
  358. }
  359. load(): void {
  360. this.selectionRequest?.unsubscribe();this.selectionPage.set(1);this.selectionTotal.set(0);
  361. this.resetPageState();
  362. this.loading.set(true);
  363. this.error.set('');
  364. if (this.isReportPage) {
  365. this.loading.set(false);
  366. return;
  367. }
  368. if (this.isNodePage) {
  369. this.loadNodes();
  370. return;
  371. }
  372. if (this.isSelectionPage) {
  373. this.loadSelection();
  374. return;
  375. }
  376. if (this.isCalendarPage) {
  377. this.loadCalendar(true);
  378. return;
  379. }
  380. if (this.isAntiForgetPage) {
  381. this.loadAntiForget();
  382. return;
  383. }
  384. if (this.isRecordPage) {
  385. this.loadRecord();
  386. return;
  387. }
  388. if (this.isExamPage) {
  389. this.loadExam();
  390. return;
  391. }
  392. if (this.meta.path === 'pages/stu/pl_end') {
  393. this.loadPracticeEnd();
  394. return;
  395. }
  396. if (this.meta.path === 'pages/stu/stu6') {
  397. this.loadReviewWords();
  398. return;
  399. }
  400. this.loadStageWords();
  401. }
  402. openNode(node: SourceItem): void {
  403. const id = node['NodeID'] ?? node['Nodeid'] ?? node['ID'] ?? node['id'];
  404. if (this.isCatalogPage) {
  405. void this.router.navigate(['/pages/stu/stu_list'], { queryParams: { nid: id } });
  406. return;
  407. }
  408. if (this.isUnitListPage && !this.canStartPointReading) {
  409. void this.router.navigate(['/pages/stu/stu_abc'], {
  410. queryParams: { nids: id, pnid: this.query('nid'), readonly: 1 },
  411. });
  412. return;
  413. }
  414. this.toggleNode(node);
  415. }
  416. openWordPreviewPage(page: number): void {
  417. const target = Math.min(Math.max(1, page), this.wordPreviewPageCount());
  418. if (target === this.wordPreviewPage() || this.wordPreviewLoading()) return;
  419. const previous = this.wordPreviewPage();
  420. this.wordPreviewPage.set(target);
  421. this.wordPreviewLoading.set(true);
  422. this.loadReadOnlyWords(true, previous);
  423. }
  424. selectCatalogCategory(index: number): void {
  425. if (index === this.catalogCategoryIndex()) return;
  426. this.catalogCategoryIndex.set(index);
  427. this.loadNodes();
  428. }
  429. toggleNode(node: SourceItem): void {
  430. const id = this.nodeId(node);
  431. if (!id) return;
  432. this.selectedNodes.update((current) => {
  433. const next = new Set(current);
  434. if (next.has(id)) next.delete(id); else next.add(id);
  435. return next;
  436. });
  437. }
  438. startNodeSelection(): void {
  439. if (!this.selectedNodes().size) {
  440. this.platform.toast('请选择学习单元', 'error');
  441. return;
  442. }
  443. void this.router.navigate(['/pages/stu/stu_abc'], {
  444. queryParams: {
  445. nids: [...this.selectedNodes()].join(','),
  446. pnid: this.query('nid'),
  447. bindingId: this.query('bindingId'),
  448. orderId: this.query('orderId'),
  449. },
  450. });
  451. }
  452. nodeId(node: SourceItem): string {
  453. return String(node['NodeID'] ?? node['Nodeid'] ?? node['ID'] ?? node['id'] ?? '');
  454. }
  455. nodeTitle(node: SourceItem): string {
  456. return String(node['NodeName'] ?? node['Title'] ?? node['name'] ?? '词库');
  457. }
  458. nodeCount(node: SourceItem): string {
  459. return String(node['ItemCount'] ?? node['Count'] ?? node['count'] ?? '');
  460. }
  461. nodeProgress(node: SourceItem): string {
  462. const total = this.nodeTotal(node);
  463. return total > 0 ? `已学 ${this.nodeLearned(node)}/${total} · 进度 ${this.nodeProgressPercent(node)}%` : '';
  464. }
  465. nodeLearned(node: SourceItem): number { return Math.max(0, Number(node['yx_word'] ?? 0)); }
  466. nodeTotal(node: SourceItem): number { return Math.max(0, Number(node['total'] ?? 0)); }
  467. nodeProgressPercent(node: SourceItem): number {
  468. const total = this.nodeTotal(node);
  469. return total ? Math.min(100, Math.round((this.nodeLearned(node) / total) * 100)) : 0;
  470. }
  471. toggleWord(word: Word): void {
  472. const shouldSelect = !this.selected().has(word.id);
  473. if (!this.setWordSelected(word, shouldSelect) || !this.isRefineSelectionPage) return;
  474. if (shouldSelect) this.setSelectionAssessment(word, 'unknown');
  475. else this.clearSelectionAssessment(word);
  476. }
  477. selectionWordRevealed(word: Word): boolean {
  478. return this.selectionRevealed().has(word.id);
  479. }
  480. wordHistoricallyLearned(word: Word): boolean {
  481. return Number(word['w_learned'] ?? 0) > 0;
  482. }
  483. selectionWordCompleted(word: Word): boolean {
  484. return this.wordHistoricallyLearned(word) || this.selectionAssessment()[word.id] === 'known';
  485. }
  486. selectionCompletionLabel(word: Word): string {
  487. return this.wordHistoricallyLearned(word) ? '历史已学完' : '本次已认识';
  488. }
  489. revealSelectionWord(word: Word): void {
  490. this.selectionRevealed.update((current) => {
  491. const next = new Set(current);
  492. if (next.has(word.id)) next.delete(word.id);
  493. else next.add(word.id);
  494. return next;
  495. });
  496. this.play(word);
  497. }
  498. markWordKnown(word: Word): void {
  499. this.setWordSelected(word, false);
  500. this.setSelectionAssessment(word, 'known');
  501. }
  502. markWordUnknown(word: Word): void {
  503. if (this.setWordSelected(word, true)) this.setSelectionAssessment(word, 'unknown');
  504. }
  505. toggleAllWords(): void {
  506. if (this.selected().size) {
  507. this.selected.set(new Set());
  508. return;
  509. }
  510. this.selected.set(new Set(this.words().slice(0, this.selectionLimit).map((word) => word.id)));
  511. }
  512. startSelected(): void {
  513. const chosen = this.pendingSelectionWords().filter((word) => this.selected().has(word.id));
  514. const newlyKnown = this.newlyKnownWords();
  515. if (!chosen.length && !newlyKnown.length) {
  516. this.platform.toast('请先判断单词是否认识,或选择要学习的单词', 'error');
  517. return;
  518. }
  519. if (this.meta.path === 'pages/stu/stu_abc') {
  520. const student = this.session.student() ?? this.session.user();
  521. if (!student?.userId) {
  522. this.platform.toast('课程信息错误', 'error');
  523. return;
  524. }
  525. this.submitting.set(true);
  526. this.persistWordsAsLearned(newlyKnown, student).pipe(finalize(() => this.submitting.set(false))).subscribe({
  527. next: () => {
  528. if (newlyKnown.length) this.commitKnownWords(newlyKnown);
  529. if (chosen.length) {
  530. this.beginSelectedFlow(chosen, '');
  531. return;
  532. }
  533. this.platform.toast('识词结果已保存', 'success');
  534. },
  535. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  536. });
  537. return;
  538. }
  539. this.beginSelectedFlow(chosen, this.meta.path === 'pages/member/starshop' ? 'newword' : 'history_word');
  540. }
  541. deleteSelectedNewWords(): void {
  542. const chosen = this.words().filter((word) => this.selected().has(word.id));
  543. if (!chosen.length) {
  544. this.platform.toast('请选择单词', 'error');
  545. return;
  546. }
  547. const owner = Number(this.session.user()?.groupId) === 3 ? this.session.student() : this.session.user();
  548. this.api.post('e_add_words', {
  549. uid: owner?.userId,
  550. wordsId: chosen.map((word) => word.wordId).join(','),
  551. ifnew: 0,
  552. kcid: this.query('kcid'),
  553. }).subscribe({
  554. next: () => {
  555. this.platform.toast('已删除', 'success');
  556. this.load();
  557. },
  558. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  559. });
  560. }
  561. play(word = this.current()): void {
  562. if (!word?.audio) {
  563. this.platform.toast('该单词暂无音频', 'error');
  564. return;
  565. }
  566. this.platform.play(this.wordAudioUrl(word.audio));
  567. }
  568. toggleRecordAnswer(word: Word): void {
  569. this.recordRevealed.update((current) => {
  570. const next = new Set(current);
  571. if (next.has(word.id)) next.delete(word.id);
  572. else next.add(word.id);
  573. return next;
  574. });
  575. this.seen.update((current) => new Set(current).add(word.id));
  576. this.play(word);
  577. }
  578. repeatWord(word: Word, index: number): void {
  579. const count = this.repetitions()[word.id] ?? 0;
  580. if (this.studyStep() === 1 && index > 0) {
  581. const previous = this.words()[index - 1];
  582. if ((this.repetitions()[previous.id] ?? 0) < 3) {
  583. this.platform.toast('前面还有没读完的单词', 'error');
  584. return;
  585. }
  586. }
  587. this.play(word);
  588. if (count < 3) {
  589. this.repetitions.update((value) => ({ ...value, [word.id]: count + 1 }));
  590. }
  591. if (this.words().every((item) => (this.repetitions()[item.id] ?? 0) >= 3)) {
  592. this.finishStudyRound();
  593. }
  594. }
  595. shuffleStudyWords(): void {
  596. this.words.set(this.shuffle(this.words()));
  597. this.repetitions.set({});
  598. }
  599. skipStudyList(): void {
  600. this.navigateStage('/pages/stu/stu3');
  601. }
  602. chooseMatch(side: 'left' | 'right', word: Word): void {
  603. if (side === 'left') {
  604. this.leftChoice.set(word.id);
  605. this.play(word);
  606. } else {
  607. this.rightChoice.set(word.id);
  608. }
  609. const left = side === 'left' ? word.id : this.leftChoice();
  610. const right = side === 'right' ? word.id : this.rightChoice();
  611. if (!left || !right) return;
  612. if (left !== right) {
  613. this.platform.toast('答错了,请再试一次', 'error');
  614. this.leftChoice.set('');
  615. this.rightChoice.set('');
  616. return;
  617. }
  618. this.platform.play(this.api.assetUrl(GAME_AUDIO.success));
  619. this.matchLeft.update((items) => items.filter((item) => item.id !== left));
  620. this.matchRight.update((items) => items.filter((item) => item.id !== right));
  621. this.leftChoice.set('');
  622. this.rightChoice.set('');
  623. if (this.matchLeft().length === 0) this.completed.set(true);
  624. }
  625. chooseMeaning(option: Word): void {
  626. const word = this.current();
  627. if (!word) return;
  628. if (option.id !== word.id) {
  629. this.platform.play(this.api.assetUrl(GAME_AUDIO.error));
  630. this.platform.toast('答错了,请重新听一遍', 'error');
  631. this.play(word);
  632. return;
  633. }
  634. this.correct.update((value) => value + 1);
  635. this.platform.play(this.api.assetUrl(GAME_AUDIO.success));
  636. if (this.currentIndex() >= this.words().length - 1) {
  637. this.completed.set(true);
  638. return;
  639. }
  640. this.currentIndex.update((value) => value + 1);
  641. this.prepareChoiceOptions();
  642. setTimeout(() => this.play(), 150);
  643. }
  644. spellLetter(index: number): void {
  645. if (this.spellingCorrect() || this.letters()[index]?.used) return;
  646. this.letters.update((items) => items.map((item, itemIndex) => itemIndex === index ? { ...item, used: true } : item));
  647. const next = this.assembled() + this.letters()[index].value;
  648. this.assembled.set(next);
  649. const word = this.current();
  650. if (!word || next.length < word.word.length) return;
  651. if (next.toLowerCase() === word.word.toLowerCase()) {
  652. this.spellingCorrect.set(true);
  653. this.correct.update((value) => value + 1);
  654. this.platform.play(this.api.assetUrl(GAME_AUDIO.success));
  655. this.platform.toast('拼写正确', 'success');
  656. return;
  657. }
  658. this.platform.play(this.api.assetUrl(GAME_AUDIO.error));
  659. this.platform.toast('拼写错了,再试一次', 'error');
  660. this.prepareSpelling();
  661. }
  662. resetSpelling(): void {
  663. this.prepareSpelling();
  664. }
  665. nextSpellingWord(): void {
  666. if (!this.spellingCorrect()) {
  667. this.platform.toast('请先完成当前单词', 'error');
  668. return;
  669. }
  670. if (this.currentIndex() >= this.words().length - 1) {
  671. this.completed.set(true);
  672. return;
  673. }
  674. this.currentIndex.update((value) => value + 1);
  675. this.prepareSpelling();
  676. this.play();
  677. }
  678. skipSpellingWord(): void {
  679. if (this.meta.path !== 'pages/stu/pl_stu5') return;
  680. if (this.currentIndex() >= this.words().length - 1) {
  681. this.completed.set(true);
  682. return;
  683. }
  684. this.currentIndex.update((value) => value + 1);
  685. this.prepareSpelling();
  686. setTimeout(() => this.play(), 120);
  687. }
  688. continueAfterStage(): void {
  689. if (this.submitting() || !this.completed()) return;
  690. if (this.isMatchingPage) {
  691. this.completed.set(false);
  692. this.navigateStage('/pages/stu/stu4');
  693. } else if (this.isListeningPage) {
  694. this.completed.set(false);
  695. const path = Number(this.session.user()?.groupId) === 3 ? '/pages/stu/pl_stu5' : '/pages/stu/stu5';
  696. this.navigateStage(path);
  697. } else if (this.isSpellingPage) {
  698. this.finishSpellingFlow();
  699. }
  700. }
  701. reviewValue(word: Word): 0 | 1 | 2 {
  702. return this.reviewState()[word.id] ?? 0;
  703. }
  704. markReview(word: Word, state: 1 | 2): void {
  705. this.reviewState.update((value) => ({ ...value, [word.id]: state }));
  706. }
  707. markAllKnown(): void {
  708. const allKnown = this.words().every((word) => this.reviewValue(word) === 1);
  709. const next: Record<string, 0 | 1 | 2> = {};
  710. for (const word of this.words()) next[word.id] = allKnown ? 0 : 1;
  711. this.reviewState.set(next);
  712. }
  713. reviewCount(state: 1 | 2): number {
  714. return this.words().filter((word) => this.reviewValue(word) === state).length;
  715. }
  716. submitReview(): void {
  717. if (this.submitting() || !this.words().length) return;
  718. if (this.words().some((word) => this.reviewValue(word) === 0)) {
  719. this.platform.toast('请为每个单词选择掌握情况', 'error');
  720. return;
  721. }
  722. if (this.meta.path === 'pages/stu/pl_end') {
  723. this.submitPracticeEnd();
  724. return;
  725. }
  726. this.saveLearningRecord();
  727. }
  728. toggleSeen(word: Word): void {
  729. this.revealed.set(!this.revealed());
  730. this.seen.update((current) => new Set(current).add(word.id));
  731. this.play(word);
  732. this.updateAntiProgress(word);
  733. if (this.seen().size === this.words().length) {
  734. this.platform.toast(`已完成 ${this.words().length} 个单词的复习`, 'success');
  735. }
  736. }
  737. joinAntiWords(): void {
  738. const chosen = this.words().filter((word) => this.selected().has(word.id));
  739. if (!chosen.length) {
  740. this.platform.toast('请选择需要加入生词本的单词', 'error');
  741. return;
  742. }
  743. const existing = this.parseArray(this.myNewWords()['scnr']);
  744. const combined = new Map<string, SourceItem>();
  745. for (const item of existing) combined.set(String(item['GeneralID'] ?? ''), item);
  746. for (const word of chosen) {
  747. combined.set(word.wordId, { GeneralID: word.wordId, Title: word.word, check: this.reviewValue(word), gldy: word['gldy'] });
  748. }
  749. const user = this.session.user();
  750. const content: SourceItem = {
  751. ModelID: 55,
  752. nodeId: 255,
  753. inputer: user?.honeyName,
  754. status: 99,
  755. Hits: combined.size,
  756. title: user?.honeyName,
  757. };
  758. let action = 'content_add';
  759. if (this.myNewWords()['GeneralID']) {
  760. content['GeneralID'] = this.myNewWords()['GeneralID'];
  761. action = 'content_update';
  762. }
  763. this.api.post(action, {
  764. content: JSON.stringify(content),
  765. addon: JSON.stringify({ UserID: user?.userId, scnr: JSON.stringify([...combined.values()]) }),
  766. }).subscribe({
  767. next: () => this.platform.toast('添加成功', 'success'),
  768. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  769. });
  770. }
  771. addRecordWords(): void {
  772. const chosen = this.words().filter((word) => this.selected().has(word.id));
  773. if (!chosen.length) {
  774. this.platform.toast('请选择单词', 'error');
  775. return;
  776. }
  777. const owner = Number(this.session.user()?.groupId) === 3 ? this.session.student() : this.session.user();
  778. this.api.post('e_add_words', {
  779. uid: owner?.userId,
  780. wordsId: chosen.map((word) => word.wordId).join(','),
  781. ifnew: 1,
  782. kcid: this.query('kcid'),
  783. }).subscribe({
  784. next: () => this.platform.toast('添加成功', 'success'),
  785. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  786. });
  787. }
  788. endRecord(): void {
  789. if(this.submitting())return;
  790. const now = this.dateTime();
  791. this.submitting.set(true);
  792. this.api.post('content_update', {
  793. content: JSON.stringify({ ModelID: 60, nodeId: 388, status: 99, GeneralID: this.query('gid'), UpDateTime: now }),
  794. addon: JSON.stringify({ fxzt: 1, wcsj: now }),
  795. }).pipe(finalize(() => this.submitting.set(false))).subscribe({
  796. next: () => void this.router.navigateByUrl('/pages/stu/stu_calendar'),
  797. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  798. });
  799. }
  800. calendarTitle(item: SourceItem): string {
  801. const title = String(item['kc_title'] ?? item['kctitle'] ?? item['kcmc'] ?? '').trim();
  802. return title ? title.split('@')[0] : '单词复习';
  803. }
  804. calendarStudent(item: SourceItem): string {
  805. return String(item['honeyName'] ?? item['Title'] ?? '').split('@')[0];
  806. }
  807. calendarDate(item: SourceItem): string {
  808. return antiForgetDate(item);
  809. }
  810. calendarFirstLearnedAt(item: SourceItem): string {
  811. const raw = String(
  812. item['learned_at']
  813. ?? item['learnedAt']
  814. ?? item['firstLearnedAt']
  815. ?? item['learned_date']
  816. ?? '',
  817. ).trim();
  818. if (!raw) return '首次学习:时间未记录';
  819. const compactDate = raw.match(/^(\d{4})(\d{2})(\d{2})$/);
  820. if (compactDate) return `首次学习:${compactDate[1]}-${compactDate[2]}-${compactDate[3]}(时间未记录)`;
  821. const dateOnly = raw.match(/^(\d{4}-\d{2}-\d{2})$/);
  822. if (dateOnly) return `首次学习:${dateOnly[1]}(时间未记录)`;
  823. const normalized = /(?:Z|[+-]\d{2}:?\d{2})$/i.test(raw)
  824. ? raw
  825. : `${raw.replace(' ', 'T')}+08:00`;
  826. const value = new Date(normalized);
  827. if (Number.isNaN(value.getTime())) return `首次学习:${raw}`;
  828. const parts = new Intl.DateTimeFormat('zh-CN', {
  829. timeZone: 'Asia/Shanghai',
  830. year: 'numeric',
  831. month: '2-digit',
  832. day: '2-digit',
  833. hour: '2-digit',
  834. minute: '2-digit',
  835. hourCycle: 'h23',
  836. }).formatToParts(value);
  837. const part = (type: Intl.DateTimeFormatPartTypes) => parts.find((itemPart) => itemPart.type === type)?.value ?? '';
  838. return `首次学习:${part('year')}-${part('month')}-${part('day')} ${part('hour')}:${part('minute')}`;
  839. }
  840. calendarReviewNumber(item: SourceItem): number {
  841. for (const key of ['fxcs', 'fxxh', 'reviewNo', 'reviewIndex', 'review_order']) {
  842. const value = Number(item[key]);
  843. if (Number.isFinite(value) && value > 0) return Math.round(value);
  844. }
  845. const recordId = String(item['xxjlid'] ?? '').trim();
  846. if (!recordId) return 1;
  847. const tasks = this.calendarItems()
  848. .filter((candidate) => String(candidate['xxjlid'] ?? '').trim() === recordId)
  849. .sort((left, right) => {
  850. const dateOrder = antiForgetDate(left).localeCompare(antiForgetDate(right));
  851. if (dateOrder) return dateOrder;
  852. return Number(left['GeneralID'] ?? 0) - Number(right['GeneralID'] ?? 0);
  853. });
  854. const index = tasks.indexOf(item);
  855. return index >= 0 ? index + 1 : 1;
  856. }
  857. calendarReady(item: SourceItem): boolean {
  858. const due = String(item['kywsj'] ?? '').slice(0, 10);
  859. return Boolean(due && Date.parse(due) <= Date.parse(this.dateOnly()) && Number(item['fxzt'] ?? 0) !== 1);
  860. }
  861. calendarCompleted(item: SourceItem): boolean {
  862. return antiForgetCompleted(item);
  863. }
  864. selectMemoryDay(day: AntiForgetCalendarDay): void {
  865. if (day.date === this.memorySelectedDate() && day.inCurrentMonth) return;
  866. this.memorySelectedDate.set(day.date);
  867. this.reviewListPage.set(1);this.loadCalendar();
  868. if (!day.inCurrentMonth) {
  869. const [year, month] = day.date.split('-').map(Number);
  870. this.memoryMonth.set(new Date(year, month - 1, 1, 12));
  871. }
  872. }
  873. shiftMemoryMonth(amount: number): void {
  874. const current = this.memoryMonth();
  875. const next = new Date(current.getFullYear(), current.getMonth() + amount, 1, 12);
  876. this.memoryMonth.set(next);
  877. const monthKey = `${next.getFullYear()}-${String(next.getMonth() + 1).padStart(2, '0')}`;
  878. const firstTask = (this.reviewPageData()?.dates||[]).map(row=>row.date).filter((date) => date.startsWith(monthKey)).sort()[0];
  879. this.memorySelectedDate.set(firstTask || `${monthKey}-01`);
  880. this.reviewListPage.set(1);this.loadCalendar();
  881. }
  882. showCurrentMemoryMonth(): void {
  883. const today = this.dateOnly();
  884. const [year, month] = today.split('-').map(Number);
  885. this.memoryMonth.set(new Date(year, month - 1, 1, 12));
  886. this.memorySelectedDate.set(today);
  887. this.reviewListPage.set(1);this.loadCalendar();
  888. }
  889. selectMemoryStudent(event: Event): void {
  890. this.memoryStudentId.set((event.target as HTMLSelectElement).value);this.reviewListPage.set(1);this.loadCalendar();
  891. }
  892. memoryTaskStatus(item: SourceItem): string {
  893. if (this.calendarCompleted(item)) return '已完成';
  894. return this.calendarReady(item) ? '待复习' : '未到期';
  895. }
  896. isWritingRecord(): boolean {
  897. return String(this.orderInfo()['if_writing'] ?? '') === '1';
  898. }
  899. openCalendar(item: SourceItem): void {
  900. if (!this.calendarReady(item) && !this.calendarCompleted(item)) {
  901. this.platform.toast('还未到复习时间');
  902. return;
  903. }
  904. const studentId = Number(item['yhid'] ?? 0);
  905. if (!studentId) {
  906. this.platform.toast('复习任务缺少关联学员', 'error');
  907. return;
  908. }
  909. this.session.setStudent({
  910. userId: studentId,
  911. honeyName: this.calendarStudent(item) || '关联学员',
  912. groupId: 1,
  913. });
  914. void this.router.navigate(['/pages/stu/record'], {
  915. queryParams: { id: item['xxjlid'], gid: item['GeneralID'], kcid: item['kcid'] },
  916. });
  917. }
  918. startExam(): void {
  919. if (!this.questions().length) return;
  920. this.examStarted.set(true);
  921. this.examSubmitted.set(false);
  922. this.currentIndex.set(0);
  923. this.startExamTimer();
  924. }
  925. answerExam(option: ExamOption, optionIndex: number): void {
  926. const question = this.currentQuestion();
  927. if (!question) return;
  928. const options = question.QOption.map((item, index) => ({ ...item, checked: index === optionIndex }));
  929. this.questions.update((items) => items.map((item, index) => index === this.currentIndex() ? { ...item, QOption: options, checked: true } : item));
  930. const result: 0 | 1 = this.cleanText(option.text) === this.cleanText(question.QContent) ? 1 : 0;
  931. this.setExamAnswer({ qid: question.ID, qtype: String(question.QType ?? ''), answer: option.value, result });
  932. this.advanceExam();
  933. }
  934. skipExamQuestion(): void {
  935. const question = this.currentQuestion();
  936. if (!question) return;
  937. this.setExamAnswer({ qid: question.ID, qtype: String(question.QType ?? ''), answer: '', result: 2 });
  938. this.advanceExam();
  939. }
  940. submitExam(): void {
  941. if(this.submitting())return;
  942. this.stopExamTimer();
  943. const ask = this.askInfo();
  944. const user = this.session.user();
  945. const answers = this.answers();
  946. const mu = {
  947. AskID: ask['ID'],
  948. Answer: JSON.stringify(answers),
  949. Remin: '',
  950. ZType: 0,
  951. Zstatus: 0,
  952. Source: '',
  953. UserID: user?.userId,
  954. CDate: this.dateTime(true),
  955. };
  956. this.submitting.set(true);
  957. this.api.post<string | number>('vote_add', { mu: JSON.stringify(mu) }).subscribe({
  958. next: ({ result }) => this.saveExamLog(result),
  959. error: (error: ApiError) => {
  960. this.submitting.set(false);
  961. this.platform.toast(error.message, 'error');
  962. },
  963. });
  964. }
  965. restart(): void {
  966. if (this.isExamPage) {
  967. this.loadExam();
  968. return;
  969. }
  970. this.load();
  971. }
  972. leave(): void {
  973. this.clearLearningStorage();
  974. void this.router.navigateByUrl('/pages/home/index', { replaceUrl: true });
  975. }
  976. private loadNodes(): void {
  977. this.loading.set(true);
  978. this.error.set('');
  979. this.nodes.set([]);
  980. this.selectedNodes.set(new Set());
  981. const pid = this.isCatalogPage
  982. ? WORD_CATALOG_CATEGORIES[this.catalogCategoryIndex()].pid
  983. : this.query('nid') || this.query('pid');
  984. const params: Record<string, unknown> = { pid, cpage: 1, psize: 100 };
  985. if (this.isUnitListPage) {
  986. const learner = this.canStartPointReading ? this.session.student() : this.session.user();
  987. if (!learner?.userId) {
  988. this.loading.set(false);
  989. this.error.set('未找到当前学员,请返回学习记录重新选择学员');
  990. return;
  991. }
  992. params['ifunit'] = 1;
  993. params['userId'] = learner.userId;
  994. params['bindingId'] = this.query('bindingId');
  995. }
  996. this.api.get<unknown>('node_list', params).pipe(finalize(() => this.loading.set(false))).subscribe({
  997. next: (nodes) => {
  998. const rows = this.findList(nodes.result);
  999. if (this.isUnitListPage && !this.canStartPointReading && !rows.length && pid) {
  1000. void this.router.navigate(['/pages/stu/stu_abc'], {
  1001. queryParams: { nids: pid, readonly: 1 },
  1002. replaceUrl: true,
  1003. });
  1004. return;
  1005. }
  1006. this.nodes.set(rows);
  1007. },
  1008. error: (error: ApiError) => this.error.set(error.message
  1009. || (this.isCatalogPage ? '词库暂时无法加载,请稍后重试' : '学习单元暂时无法加载,请稍后重试')),
  1010. });
  1011. }
  1012. loadMoreSelection():void{if(!this.selectionLoading()&&this.words().length<this.selectionTotal()){this.selectionPage.update(p=>p+1);this.loadSelection(true);}}
  1013. private loadSelection(more=false): void {
  1014. 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);};
  1015. const failure=(error:ApiError)=>{if(more){this.selectionPage.update(p=>p-1);this.platform.toast(error.message,'error');}else this.error.set(error.message);};
  1016. if (this.meta.path === 'pages/stu/stu_abc') {
  1017. const student = this.session.student() ?? this.session.user();this.selectionLoading.set(true);
  1018. this.selectionRequest=this.api.get<unknown>('e_ck_list',{checkwords:2,nids:this.query('nids')||this.query('nid'),modelId:52,cpage:this.selectionPage(),psize:100,uid:student?.userId}).pipe(finalize(()=>{this.selectionLoading.set(false);this.loading.set(false);})).subscribe({next:({result,page})=>accept(result,page?.itemCount),error:failure});return;
  1019. }
  1020. if (this.meta.path === 'pages/his/his_words') {
  1021. this.api.post<unknown>('e_record_detail', { id: this.query('id') }).pipe(finalize(() => this.loading.set(false))).subscribe({
  1022. next: ({ result, addon }) => {
  1023. const words = this.findList(result).map((item) => this.toWord(item)).filter((word) => word.word);
  1024. this.words.set(words);
  1025. this.wordPreviewTotal.set(words.length);
  1026. const sourceAddon = this.findList(addon)[0];
  1027. if (sourceAddon) this.orderInfo.set(sourceAddon);
  1028. },
  1029. error: (error: ApiError) => this.error.set(error.message),
  1030. });
  1031. return;
  1032. }
  1033. const owner = Number(this.session.user()?.groupId) === 3 ? this.session.student() : this.session.user();
  1034. this.selectionLoading.set(true);
  1035. this.selectionRequest=this.api.get<unknown>('e_words_list',{uid:owner?.userId,cpage:this.selectionPage(),psize:100}).pipe(finalize(()=>{this.selectionLoading.set(false);this.loading.set(false);})).subscribe({next:({result,page})=>accept(result,page?.itemCount),error:failure});
  1036. }
  1037. private loadStageWords(): void {
  1038. const nid = this.query('nid');
  1039. if (nid && this.isReadOnlyWordView) {
  1040. this.loadReadOnlyWords();
  1041. return;
  1042. }
  1043. if (nid) {
  1044. this.api.get<unknown>('content_list', { nid, modelId: 52, cpage: 1, psize: 300 }).pipe(finalize(() => this.loading.set(false))).subscribe({
  1045. next: ({ result }) => this.initializeStage(this.findList(result).map((item) => this.toWord(item)).filter((word) => word.word)),
  1046. error: (error: ApiError) => this.error.set(error.message),
  1047. });
  1048. return;
  1049. }
  1050. const stored = this.readLearningWords();
  1051. this.loading.set(false);
  1052. if (!stored.length) {
  1053. this.error.set('请先选择本次学习的单词');
  1054. return;
  1055. }
  1056. this.initializeStage(stored);
  1057. }
  1058. private loadReadOnlyWords(pageChange = false, previousPage = 1): void {
  1059. const learner = this.session.student() ?? this.session.user();
  1060. this.api.get<unknown>('e_ck_list', {
  1061. checkwords: 2,
  1062. nids: this.query('nid'),
  1063. modelId: 52,
  1064. cpage: this.wordPreviewPage(),
  1065. psize: this.wordPreviewPageSize,
  1066. uid: learner?.userId,
  1067. }).pipe(finalize(() => {
  1068. if (pageChange) this.wordPreviewLoading.set(false);
  1069. else this.loading.set(false);
  1070. })).subscribe({
  1071. next: ({ result, page }) => {
  1072. const words = this.findList(result).map((item) => this.toWord(item)).filter((word) => word.word);
  1073. this.words.set(words);
  1074. this.wordPreviewTotal.set(Math.max(words.length, Number(page?.itemCount ?? 0)));
  1075. if (pageChange) {
  1076. setTimeout(() => document.getElementById('readonly-word-title')?.scrollIntoView({ behavior: 'smooth', block: 'start' }));
  1077. }
  1078. },
  1079. error: (error: ApiError) => {
  1080. if (pageChange) {
  1081. this.wordPreviewPage.set(previousPage);
  1082. this.platform.toast('该页单词加载失败,请重试', 'error');
  1083. return;
  1084. }
  1085. this.error.set(error.message);
  1086. },
  1087. });
  1088. }
  1089. private initializeStage(source: Word[]): void {
  1090. if (!source.length) {
  1091. this.error.set('本关暂无单词,请返回重新选择学习内容');
  1092. return;
  1093. }
  1094. const words = this.isStudyListPage ? source : this.shuffle(source);
  1095. this.words.set(words);
  1096. if (this.isStudyListPage) {
  1097. this.studyStep.set(1);
  1098. this.repetitions.set({});
  1099. } else if (this.isMatchingPage) {
  1100. this.matchLeft.set(this.shuffle(words));
  1101. this.matchRight.set(this.shuffle(words));
  1102. } else if (this.isListeningPage) {
  1103. this.prepareChoiceOptions();
  1104. setTimeout(() => this.play(), 120);
  1105. } else if (this.isSpellingPage) {
  1106. this.prepareSpelling();
  1107. setTimeout(() => this.play(), 120);
  1108. }
  1109. }
  1110. private finishStudyRound(): void {
  1111. if (this.studyStep() < 3) {
  1112. const next = (this.studyStep() + 1) as 2 | 3;
  1113. this.studyStep.set(next);
  1114. this.words.set(next === 2 ? [...this.words()].reverse() : this.shuffle(this.words()));
  1115. this.repetitions.set({});
  1116. this.platform.toast(next === 2 ? '进入乱序学习' : '进入中文挑战', 'success');
  1117. return;
  1118. }
  1119. this.navigateStage('/pages/stu/stu3');
  1120. }
  1121. private prepareChoiceOptions(): void {
  1122. const current = this.current();
  1123. if (!current) {
  1124. this.choiceOptions.set([]);
  1125. return;
  1126. }
  1127. const distractors = this.shuffle(this.words().filter((word) => word.id !== current.id)).slice(0, 3);
  1128. this.choiceOptions.set(this.shuffle([current, ...distractors]));
  1129. if (distractors.length < 3) {
  1130. this.api.get<unknown>('content_list', { modelId: 52, orders: 'NEWID()', cpage: 1, psize: 8 }).subscribe({
  1131. next: ({ result }) => {
  1132. const extras = this.findList(result).map((item) => this.toWord(item)).filter((word) => word.id !== current.id && !distractors.some((item) => item.id === word.id));
  1133. this.choiceOptions.set(this.shuffle([current, ...distractors, ...extras]).slice(0, 4));
  1134. },
  1135. error: () => undefined,
  1136. });
  1137. }
  1138. }
  1139. private prepareSpelling(): void {
  1140. const word = this.current();
  1141. this.assembled.set('');
  1142. this.spellingCorrect.set(false);
  1143. this.letters.set(this.shuffle((word?.word ?? '').split('').map((value) => ({ value, used: false }))));
  1144. }
  1145. private finishSpellingFlow(): void {
  1146. const currentPage = Number(this.storageGet('_page_current_learn') ?? 1);
  1147. if (this.hasNextWordBatch) {
  1148. this.completed.set(false);
  1149. this.storageSet('_page_current_learn', currentPage + 1);
  1150. this.navigateStage('/pages/stu/stu_con');
  1151. return;
  1152. }
  1153. const mode = String(this.storageGet('learn_mode') ?? '');
  1154. if (mode === 'newword') {
  1155. this.completed.set(false);
  1156. this.clearLearningStorage();
  1157. void this.router.navigateByUrl('/pages/member/starshop', { replaceUrl: true });
  1158. } else if (mode === 'history_word') {
  1159. this.completed.set(false);
  1160. this.clearLearningStorage();
  1161. void this.router.navigateByUrl('/pages/his/his', { replaceUrl: true });
  1162. } else if (this.meta.path === 'pages/stu/pl_stu5') {
  1163. if (this.query('orderId')) {
  1164. this.createPracticeLearningRecord();
  1165. } else {
  1166. this.createStandalonePracticeLearningRecord();
  1167. }
  1168. } else {
  1169. this.navigateStage('/pages/stu/stu6');
  1170. }
  1171. }
  1172. private loadReviewWords(): void {
  1173. const words = this.readAllLearningWords();
  1174. this.words.set(words);
  1175. this.loading.set(false);
  1176. if (!words.length) {
  1177. this.error.set('请先选择本次学习的单词');
  1178. return;
  1179. }
  1180. const user = this.session.user();
  1181. this.api.get<unknown>('content_list', {
  1182. modelId: 56,
  1183. psize: 2,
  1184. myfield2: `UserId=${(this.canStartPointReading ? this.session.student() : user)?.userId}|dqrq=${this.compactDate()}`,
  1185. }).subscribe({
  1186. next: ({ result }) => this.learnedRecord.set(this.findList(result)[0] ?? {}),
  1187. error: (error:ApiError) => this.error.set(error.message),
  1188. });
  1189. }
  1190. private updateUnitRecord(): Observable<unknown> {
  1191. const nids = this.query('nids');
  1192. const bookId = this.query('pnid');
  1193. if (!nids || !bookId) return of(null);
  1194. const wordIds: Record<string, string> = {};
  1195. for (const nodeId of nids.split(',')) {
  1196. wordIds[nodeId] = this.words().filter((word) => word.nodeId === nodeId).map((word) => word.wordId).join(',');
  1197. }
  1198. return this.api.post('unit_record_update', {
  1199. nids,
  1200. userId: (this.canStartPointReading ? this.session.student() : this.session.user())?.userId,
  1201. bookId,
  1202. wordIds: JSON.stringify(wordIds),
  1203. });
  1204. }
  1205. private saveLearningRecord(): void {
  1206. const user = this.session.user();
  1207. const student = Number(user?.groupId) === 3 ? this.session.student() : null;
  1208. const owner = student ?? user;
  1209. const existing = this.learnedRecord();
  1210. const oldItems = this.parseArray(existing['xxqs']);
  1211. const records = new Map<string, SourceItem>();
  1212. for (const item of oldItems) records.set(String(item['GeneralID'] ?? ''), item);
  1213. for (const word of this.words()) {
  1214. records.set(word.wordId, { GeneralID: word.wordId, Title: word.word, check: this.reviewValue(word) });
  1215. }
  1216. const xxqs = [...records.values()];
  1217. const learned = xxqs.length;
  1218. const ygg = xxqs.filter((item) => Number(item['check']) === 1).length;
  1219. const djq = xxqs.filter((item) => Number(item['check']) === 2).length;
  1220. const content: SourceItem = {
  1221. ModelID: 56,
  1222. nodeId: 291,
  1223. inputer: user?.honeyName,
  1224. status: 99,
  1225. Hits: learned,
  1226. title: owner?.honeyName,
  1227. };
  1228. let action = 'content_add_zt';
  1229. if (existing['GeneralID']) {
  1230. content['GeneralID'] = existing['GeneralID'];
  1231. content['UpDateTime'] = this.dateOnly();
  1232. action = 'content_update';
  1233. }
  1234. const addon: SourceItem = {
  1235. con: `完成了${learned}个单词的学习@${this.dateTime()}`,
  1236. dqrq: this.compactDate(),
  1237. pl: student ? user?.userId : 0,
  1238. UserID: owner?.userId,
  1239. learned,
  1240. ygg,
  1241. djq,
  1242. xxqs: JSON.stringify(xxqs),
  1243. };
  1244. if (!existing['xxqs']) addon['fxrl'] = '';
  1245. this.submitting.set(true);
  1246. this.persistWordsAsLearned(this.words(), owner).pipe(
  1247. switchMap(()=>this.updateUnitRecord()),
  1248. switchMap(() => this.api.post(action, { content: JSON.stringify(content), addon: JSON.stringify(addon) })),
  1249. finalize(() => this.submitting.set(false)),
  1250. ).subscribe({
  1251. next: () => {
  1252. this.platform.toast('提交成功', 'success');
  1253. void this.router.navigate(['/pages/member/myorder'], { queryParams: { pnid: this.query('pnid') }, replaceUrl: true });
  1254. },
  1255. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  1256. });
  1257. }
  1258. private loadPracticeEnd(): void {
  1259. const orderId = this.query('orderId') || this.query('id');
  1260. const coachId = this.session.user()?.userId;
  1261. if (!orderId || !coachId) {
  1262. this.loading.set(false);
  1263. this.error.set('缺少预约或老师信息,请返回课程重新进入');
  1264. return;
  1265. }
  1266. this.api.get<unknown>('e_order_detail', { id: orderId }).pipe(
  1267. switchMap(({ result }) => {
  1268. const order = this.findList(result)[0] ?? (result as SourceItem);
  1269. const studentId = Number(order?.['szyh'] ?? order?.['yhid'] ?? 0);
  1270. if (!studentId) return throwError(() => new ApiError('预约记录缺少学员信息,请返回课程重试'));
  1271. this.orderInfo.set(order);
  1272. if (this.session.student()?.userId !== studentId) {
  1273. this.session.setStudent({ userId: studentId, groupId: 1, honeyName: String(order['HoneyName'] ?? order['honeyName'] ?? '学员') });
  1274. }
  1275. // Restrict the read to this appointment, its student and the signed-in coach.
  1276. return this.api.get<unknown>('content_list', {
  1277. modelId: 56, psize: 1,
  1278. myfield2: `UserId=${studentId}|dsid=${orderId}|pl=${coachId}`,
  1279. });
  1280. }),
  1281. switchMap(({ result }) => {
  1282. const record = this.findList(result)[0] ?? {};
  1283. this.learnedRecord.set(record);
  1284. if (!record['GeneralID']) return throwError(() => new ApiError('未找到本次陪练学习记录,请返回课程重试'));
  1285. return this.api.get<unknown>('e_record_detail', { id: record['GeneralID'] });
  1286. }),
  1287. finalize(() => this.loading.set(false)),
  1288. ).subscribe({
  1289. next: ({ result }) => {
  1290. const words = this.findList(result).map((item) => this.toWord(item)).filter((word) => word.word);
  1291. this.words.set(words);
  1292. this.reviewState.set(Object.fromEntries(words.map((word) => [word.id, Number(word['check']) === 1 ? 1 : Number(word['check']) === 2 ? 2 : 0])));
  1293. },
  1294. error: (error: ApiError) => this.error.set(error.message),
  1295. });
  1296. }
  1297. private submitPracticeEnd(): void {
  1298. const user = this.session.user();
  1299. const student = this.session.student();
  1300. const owner = Number(user?.groupId) === 3 ? student : user;
  1301. const xxqs = this.words().map((word) => ({ GeneralID: word.wordId, Title: word.word, check: this.reviewValue(word) }));
  1302. const addon = {
  1303. learned: xxqs.length,
  1304. ygg: xxqs.filter((item) => item.check === 1).length,
  1305. djq: xxqs.filter((item) => item.check === 2).length,
  1306. xxqs: JSON.stringify(xxqs),
  1307. };
  1308. this.submitting.set(true);
  1309. this.api.post('stu_record_update_v2', {
  1310. orderId: this.query('orderId') || this.query('id'),
  1311. uid: owner?.userId,
  1312. inputer: owner?.honeyName,
  1313. addon: JSON.stringify(addon),
  1314. }).pipe(finalize(() => this.submitting.set(false))).subscribe({
  1315. next: () => {
  1316. this.clearLearningStorage();
  1317. void this.router.navigate(['/pages/shop/get_order'], {
  1318. queryParams: { id: this.query('orderId') || this.query('id'), feedback: '1' },
  1319. replaceUrl: true,
  1320. });
  1321. },
  1322. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  1323. });
  1324. }
  1325. private createPracticeLearningRecord(): void {
  1326. const allWords = this.readAllLearningWords();
  1327. const user = this.session.user();
  1328. const student = this.session.student();
  1329. const owner = Number(user?.groupId) === 3 ? student : user;
  1330. const xxqs = allWords.map((word) => ({ GeneralID: word.wordId, Title: word.word, check: 0 }));
  1331. const addon = {
  1332. con: `完成了${xxqs.length}个单词的学习@${this.dateTime()}`,
  1333. szmdid: this.orderInfo()['szmd'],
  1334. dqrq: this.compactDate(),
  1335. dsid: this.query('orderId'),
  1336. pl: Number(user?.groupId) === 3 ? user?.userId : 0,
  1337. UserID: owner?.userId,
  1338. learned: xxqs.length,
  1339. ygg: 0,
  1340. djq: 0,
  1341. xxqs: JSON.stringify(xxqs),
  1342. };
  1343. this.submitting.set(true);
  1344. this.persistWordsAsLearned(allWords, owner).pipe(
  1345. switchMap(() => this.api.post('stu_record_update_v2', {
  1346. orderId: this.query('orderId'),
  1347. uid: owner?.userId,
  1348. inputer: user?.honeyName,
  1349. addon: JSON.stringify(addon),
  1350. })),
  1351. finalize(() => this.submitting.set(false)),
  1352. ).subscribe({
  1353. next: () => this.navigateStage('/pages/stu/pl_end'),
  1354. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  1355. });
  1356. }
  1357. private createStandalonePracticeLearningRecord(): void {
  1358. const allWords = this.readAllLearningWords();
  1359. const user = this.session.user();
  1360. const student = this.session.student();
  1361. if (Number(user?.groupId) === 3 && !student?.userId) {
  1362. this.platform.toast('请先选择学员', 'error');
  1363. return;
  1364. }
  1365. const owner = Number(user?.groupId) === 3 ? student : user;
  1366. const xxqs = allWords.map((word) => ({ GeneralID: word.wordId, Title: word.word, check: 0 }));
  1367. const content: SourceItem = {
  1368. ModelID: 56,
  1369. nodeId: 291,
  1370. inputer: user?.honeyName,
  1371. status: 99,
  1372. Hits: xxqs.length,
  1373. title: owner?.honeyName,
  1374. };
  1375. const addon: SourceItem = {
  1376. con: `完成了${xxqs.length}个单词的学习@${this.dateTime()}`,
  1377. dqrq: this.compactDate(),
  1378. pl: Number(user?.groupId) === 3 ? user?.userId : 0,
  1379. UserID: owner?.userId,
  1380. learned: xxqs.length,
  1381. ygg: 0,
  1382. djq: 0,
  1383. xxqs: JSON.stringify(xxqs),
  1384. fxrl: '',
  1385. createReviewPlan: false,
  1386. bindingId: this.query('bindingId') || undefined,
  1387. };
  1388. this.submitting.set(true);
  1389. this.persistWordsAsLearned(allWords, owner).pipe(
  1390. switchMap(() => this.api.post('content_add_zt', {
  1391. content: JSON.stringify(content),
  1392. addon: JSON.stringify(addon),
  1393. })),
  1394. finalize(() => this.submitting.set(false)),
  1395. ).subscribe({
  1396. next: () => {
  1397. this.clearLearningStorage();
  1398. this.platform.toast('学习记录已保存', 'success');
  1399. void this.router.navigateByUrl('/pages/his/his', { replaceUrl: true });
  1400. },
  1401. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  1402. });
  1403. }
  1404. private loadRecord(): void {
  1405. this.api.post<unknown>('e_record_detail', { id: this.query('id') }).pipe(finalize(() => this.loading.set(false))).subscribe({
  1406. next: ({ result, addon }) => {
  1407. this.words.set(this.findList(result).map((item) => this.toWord(item)).filter((word) => word.word));
  1408. this.orderInfo.set(this.findList(addon)[0] ?? {});
  1409. },
  1410. error: (error: ApiError) => this.error.set(error.message),
  1411. });
  1412. }
  1413. turnReviewPage(delta:number):void{this.reviewListPage.update(p=>Math.max(1,Math.min(this.reviewPageData()?.page.pageCount||1,p+delta)));this.loadCalendar();}
  1414. retryCalendar(): void { this.loadCalendar(); }
  1415. private loadCalendar(initial = false): void {
  1416. const requestId=++this.calendarRequestId;
  1417. this.calendarRequest?.unsubscribe();
  1418. this.calendarError.set('');
  1419. if (initial) this.loading.set(true); else this.calendarLoading.set(true);
  1420. this.calendarRequest = this.api.post<ReviewPage>('app_review_page',{uid:this.session.user()?.userId,studentId:this.memoryStudentId()||undefined,date:this.memorySelectedDate()||this.dateOnly(),page:this.reviewListPage(),pageSize:20}).pipe(finalize(()=>{
  1421. if(requestId!==this.calendarRequestId)return;
  1422. if(initial)this.loading.set(false);else this.calendarLoading.set(false);
  1423. })).subscribe({next:({result})=>{
  1424. if(requestId!==this.calendarRequestId)return;
  1425. this.reviewPageData.set(result);this.calendarItems.set(result.items);
  1426. if(!this.memorySelectedDate())this.memorySelectedDate.set(this.dateOnly());
  1427. },error:(e:ApiError)=>{
  1428. if(requestId!==this.calendarRequestId)return;
  1429. if(initial)this.error.set(e.message);else this.calendarError.set(e.message);
  1430. }});
  1431. }
  1432. private calendarRequestId=0;
  1433. private loadAntiForget(): void {
  1434. const user = this.session.user();
  1435. const date = this.query('date') || this.compactDate();
  1436. this.antiStartedAt = Date.now();
  1437. this.api.get<unknown>('content_list', {
  1438. nid: 76,
  1439. modelId: 54,
  1440. myfield: `fxrl=${date}`,
  1441. myfield2: `UserId=${user?.userId}`,
  1442. cpage: 1,
  1443. psize: 30,
  1444. orders: 'CreateTime=asc',
  1445. }).pipe(finalize(() => this.loading.set(false))).subscribe({
  1446. next: ({ result }) => {
  1447. const words: Word[] = [];
  1448. for (const record of this.findList(result)) {
  1449. for (const item of this.parseArray(record['xxqs'])) words.push(this.toWord({ ...item, recordId: record['GeneralID'] }));
  1450. }
  1451. this.words.set(words.filter((word) => word.word));
  1452. },
  1453. error: (error: ApiError) => this.error.set(error.message),
  1454. });
  1455. if (this.query('hid')) {
  1456. this.api.get<unknown>('content_get', { id: this.query('hid') }).subscribe({
  1457. next: ({ result }) => this.antiHistory.set(this.findList(result)[0] ?? {}),
  1458. error: () => undefined,
  1459. });
  1460. }
  1461. this.api.get<unknown>('content_list', { nid: 255, modelId: 55, cpage: 1, psize: 30, myfield2: `UserId=${user?.userId}`, orders: 'CreateTime=asc' }).subscribe({
  1462. next: ({ result }) => this.myNewWords.set(this.findList(result)[0] ?? {}),
  1463. error: () => undefined,
  1464. });
  1465. }
  1466. private updateAntiProgress(word: Word): void {
  1467. const historyId = this.query('hid');
  1468. if (!historyId) return;
  1469. const seenWords = this.words().filter((item) => this.seen().has(item.id));
  1470. const previousIds = String(this.antiHistory()['xxjlid'] ?? '').split(',').filter(Boolean);
  1471. const recordId = String(word['recordId'] ?? '');
  1472. if (recordId && !previousIds.includes(recordId)) previousIds.push(recordId);
  1473. const scqs = seenWords.map((item) => ({ GeneralID: item.wordId, Title: item.word, gldy: item['gldy'] }));
  1474. const wordIds = `,${scqs.map((item) => item.GeneralID).join(',')},`;
  1475. this.api.post('content_update', {
  1476. content: JSON.stringify({ GeneralID: historyId }),
  1477. addon: JSON.stringify({
  1478. xxjlid: previousIds.join(','),
  1479. scqs: JSON.stringify(scqs),
  1480. yxx: scqs.length,
  1481. scqs2: wordIds,
  1482. times: Math.round((Date.now() - this.antiStartedAt) / 1000),
  1483. num: this.words().length,
  1484. }),
  1485. }).subscribe({ error: () => undefined });
  1486. }
  1487. private loadExam(): void {
  1488. this.turnAskId();
  1489. const askId = Number(this.storageGet('askId') ?? 1);
  1490. const user = this.session.user();
  1491. this.api.get<unknown>('vote_ask', { id: askId }).subscribe({
  1492. next: ({ result }) => this.askInfo.set(this.findList(result)[0] ?? {}),
  1493. error: () => undefined,
  1494. });
  1495. this.api.get<unknown>('content_list', { nid: 389, modelId: 61, cpage: 1, psize: 2, myfield2: `UserID=${user?.userId}`, orders: 'CreateTime=desc' }).subscribe({
  1496. next: ({ result }) => this.previousExam.set(this.findList(result)[0] ?? {}),
  1497. error: () => undefined,
  1498. });
  1499. this.api.get<unknown>('vote_question', { askid: askId }).pipe(finalize(() => this.loading.set(false))).subscribe({
  1500. next: ({ result }) => {
  1501. const questions = this.shuffle(this.findList(result).map((item) => this.toQuestion(item)));
  1502. this.questions.set(questions);
  1503. this.answers.set(questions.map((question) => ({ qid: question.ID, qtype: String(question.QType ?? ''), answer: '', result: 2 })));
  1504. },
  1505. error: (error: ApiError) => this.error.set(error.message),
  1506. });
  1507. }
  1508. private turnAskId(): void {
  1509. const current = Number(this.storageGet('askId') ?? 0);
  1510. this.storageSet('askId', current === 1 ? 2 : 1);
  1511. }
  1512. examScoreValue(exam: SourceItem): number {
  1513. return Number(exam['df'] ?? 0);
  1514. }
  1515. examAnalysis(exam: SourceItem): string {
  1516. const score = this.examScoreValue(exam);
  1517. if (score === 0) return '当前处于零基础阶段,可以从最常用的基础词汇开始建立词汇库。';
  1518. if (score <= 2) return '词汇量约为 100-200,处于英语入门或小学一、二年级水平。';
  1519. if (score <= 6) return '词汇量约为 200-400,相当于小学三、四年级水平。';
  1520. if (score <= 12) return '词汇量约为 400-600,相当于小学五、六年级水平。';
  1521. if (score <= 15) return '词汇量约为 600-900,相当于初一水平。';
  1522. if (score <= 18) return '词汇量约为 1000-1500,相当于初二水平。';
  1523. if (score <= 21) return '词汇量约为 1600-1800,相当于初三水平。';
  1524. if (score <= 33) return '词汇量约为 1800-2500,相当于高一水平。';
  1525. if (score <= 39) return '词汇量约为 2500-3000,相当于高二水平。';
  1526. if (score <= 42) return '词汇量约为 3000-3500,相当于高三一般水平。';
  1527. return '词汇量约为 3500-4500,达到高三较高或大学四级水平。';
  1528. }
  1529. examAdvice(exam: SourceItem): string {
  1530. const score = this.examScoreValue(exam);
  1531. if (score <= 6) return '建议先系统学习自然拼读并背诵小学、初中基础词汇,打牢读、认、写基础。';
  1532. if (score <= 12) return '建议重点背诵初中词汇,并通过简单阅读和听力练习持续扩展词汇量。';
  1533. if (score <= 21) return '建议继续背诵初高中核心词汇,配合英文阅读、听力和写作练习巩固运用。';
  1534. if (score <= 39) return '建议学习高二、高三词汇,并通过时文外刊、国家地理和 TED 演讲提升理解与表达。';
  1535. return '建议拓展大学四、六级或雅思托福词汇,通过 BBC、VOA 和英文原著把新词用于真实语境。';
  1536. }
  1537. private setExamAnswer(answer: ExamAnswer): void {
  1538. this.answers.update((items) => items.map((item, index) => index === this.currentIndex() ? answer : item));
  1539. }
  1540. private advanceExam(): void {
  1541. if (this.currentIndex() >= this.questions().length - 1) {
  1542. this.submitExam();
  1543. return;
  1544. }
  1545. this.currentIndex.update((value) => value + 1);
  1546. this.startExamTimer();
  1547. }
  1548. private startExamTimer(): void {
  1549. this.stopExamTimer();
  1550. this.timer.set(10);
  1551. this.examTimer = setInterval(() => {
  1552. if (this.timer() <= 1) {
  1553. this.skipExamQuestion();
  1554. } else {
  1555. this.timer.update((value) => value - 1);
  1556. }
  1557. }, 1000);
  1558. }
  1559. private stopExamTimer(): void {
  1560. if (this.examTimer) clearInterval(this.examTimer);
  1561. this.examTimer = null;
  1562. }
  1563. private saveExamLog(answerId: string | number): void {
  1564. const user = this.session.user();
  1565. const answers = this.answers();
  1566. const score = answers.filter((item) => item.result === 1).length;
  1567. const previous = this.previousExam();
  1568. this.examScore.set(score);
  1569. const content: SourceItem = { ModelID: 61, nodeId: 389, inputer: user?.honeyName, status: 99, Hits: 1, title: user?.honeyName };
  1570. const addon = {
  1571. askid: this.currentQuestion()?.AskID ?? this.askInfo()['ID'],
  1572. prev_score: previous['df'] ?? 0,
  1573. totalScore: answers.length,
  1574. wrong: answers.filter((item) => item.result === 0).length,
  1575. dontKnow: answers.filter((item) => item.result === 2).length,
  1576. answerid: answerId || 0,
  1577. df: score,
  1578. UserID: user?.userId,
  1579. };
  1580. let action = 'content_add';
  1581. if (previous['GeneralID']) {
  1582. content['GeneralID'] = previous['GeneralID'];
  1583. action = 'content_update';
  1584. }
  1585. this.api.post(action, { content: JSON.stringify(content), addon: JSON.stringify(addon) }).pipe(finalize(() => this.submitting.set(false))).subscribe({
  1586. next: () => {
  1587. this.examStarted.set(false);
  1588. this.examSubmitted.set(true);
  1589. this.platform.toast('答题结果已保存', 'success');
  1590. },
  1591. error: (error: ApiError) => this.platform.toast(error.message, 'error'),
  1592. });
  1593. }
  1594. private beginSelectedFlow(chosen: Word[], mode: '' | 'newword' | 'history_word'): void {
  1595. this.clearLearningStorage();
  1596. if (mode) this.storageSet('learn_mode', mode);
  1597. const pages: Word[][] = [];
  1598. for (let index = 0; index < chosen.length; index += 6) pages.push(chosen.slice(index, index + 6));
  1599. const storageKey = mode === 'newword' ? 'choose_newword_learn' : mode === 'history_word' ? 'choose_hisword_learn' : 'choose_word_learn';
  1600. this.storageSet(storageKey, pages[0] ?? chosen);
  1601. this.storageSet('_page_current_learn', 1);
  1602. this.storageSet('_page_total_page', pages.length);
  1603. this.storageSet('_page_word_orilist', pages);
  1604. sessionStorage.setItem(this.learningStorageKey('selectedWords'), JSON.stringify(pages[0] ?? chosen));
  1605. void this.router.navigate(['/pages/stu/stu_con'], {
  1606. replaceUrl: true,
  1607. state: { learningReturnUrl: this.router.url },
  1608. queryParams: {
  1609. nids: this.query('nids') || this.query('nid'),
  1610. pnid: this.query('pnid'),
  1611. bindingId: this.query('bindingId'),
  1612. orderId: this.query('orderId'),
  1613. },
  1614. });
  1615. }
  1616. private navigateStage(path: string): void {
  1617. void this.router.navigate([path], {
  1618. replaceUrl: true,
  1619. state: { learningReturnUrl: history.state?.learningReturnUrl },
  1620. queryParams: {
  1621. nid: this.query('nid'),
  1622. nids: this.query('nids'),
  1623. pnid: this.query('pnid'),
  1624. bindingId: this.query('bindingId'),
  1625. orderId: this.query('orderId') || this.query('id'),
  1626. },
  1627. });
  1628. }
  1629. private readLearningWords(): Word[] {
  1630. const currentPage = Number(this.storageGet('_page_current_learn') ?? 1);
  1631. const pages = this.parseArray(this.storageGet('_page_word_orilist'));
  1632. if (pages.length) {
  1633. const page = pages[currentPage - 1];
  1634. if (Number.isInteger(currentPage) && currentPage > 0 && Array.isArray(page)) {
  1635. const mode = String(this.storageGet('learn_mode') ?? '');
  1636. const key = mode === 'newword' ? 'choose_newword_learn' : mode === 'history_word' ? 'choose_hisword_learn' : 'choose_word_learn';
  1637. this.storageSet(key, page);
  1638. sessionStorage.setItem(this.learningStorageKey('selectedWords'), JSON.stringify(page));
  1639. return page.map((item) => this.toWord(item as SourceItem));
  1640. }
  1641. return [];
  1642. }
  1643. const mode = String(this.storageGet('learn_mode') ?? '');
  1644. const key = mode === 'newword' ? 'choose_newword_learn' : mode === 'history_word' ? 'choose_hisword_learn' : 'choose_word_learn';
  1645. const stored = this.parseArray(this.storageGet(key));
  1646. if (stored.length) return stored.map((item) => this.toWord(item));
  1647. return this.parseArray(sessionStorage.getItem(this.learningStorageKey('selectedWords'))).map((item) => this.toWord(item));
  1648. }
  1649. private readAllLearningWords(): Word[] {
  1650. const pages = this.parseArray(this.storageGet('_page_word_orilist'));
  1651. if (pages.length && pages.every((page) => Array.isArray(page))) {
  1652. return pages.flatMap((page) => (page as SourceItem[]).map((item) => this.toWord(item)));
  1653. }
  1654. return this.readLearningWords();
  1655. }
  1656. private clearLearningStorage(): void { this.draft().clear(); }
  1657. private resetPageState(): void {
  1658. this.stopExamTimer();
  1659. this.nodes.set([]);
  1660. this.selectedNodes.set(new Set());
  1661. this.words.set([]);
  1662. this.wordPreviewPage.set(1);
  1663. this.wordPreviewTotal.set(0);
  1664. this.wordPreviewLoading.set(false);
  1665. this.calendarLoading.set(false);
  1666. this.calendarError.set('');
  1667. this.selected.set(new Set());
  1668. this.selectionRevealed.set(new Set());
  1669. this.selectionAssessment.set({});
  1670. this.activeSelectionBucket.set('pending');
  1671. this.currentIndex.set(0);
  1672. this.revealed.set(false);
  1673. this.completed.set(false);
  1674. this.correct.set(0);
  1675. this.unknown.set([]);
  1676. this.studyStep.set(1);
  1677. this.repetitions.set({});
  1678. this.matchLeft.set([]);
  1679. this.matchRight.set([]);
  1680. this.leftChoice.set('');
  1681. this.rightChoice.set('');
  1682. this.choiceOptions.set([]);
  1683. this.reviewState.set({});
  1684. this.seen.set(new Set());
  1685. this.recordRevealed.set(new Set());
  1686. this.calendarItems.set([]);
  1687. this.memoryStudentId.set('');
  1688. this.examStarted.set(false);
  1689. this.examSubmitted.set(false);
  1690. }
  1691. private toWord(item: SourceItem): Word {
  1692. const detailValue = Array.isArray(item['detail']) ? item['detail'][0] : item['detail'];
  1693. const detail = detailValue && typeof detailValue === 'object' ? detailValue as SourceItem : {};
  1694. const source = { ...detail, ...item };
  1695. const id = String(item['GeneralID'] ?? detail['GeneralID'] ?? item['ID'] ?? item['id'] ?? item['gid'] ?? item['Title'] ?? detail['Title'] ?? '');
  1696. const wordId = String(detail['GeneralID'] ?? item['GeneralID'] ?? item['gldy'] ?? id);
  1697. return {
  1698. ...source,
  1699. detail,
  1700. id,
  1701. wordId,
  1702. nodeId: String(item['NodeID'] ?? detail['NodeID'] ?? item['nodeId'] ?? ''),
  1703. word: String(item['Title'] ?? detail['Title'] ?? item['word'] ?? detail['word'] ?? item['Word'] ?? ''),
  1704. meaning: String(item['sy'] ?? detail['sy'] ?? item['jssy'] ?? detail['jssy'] ?? item['Translate'] ?? detail['Translate'] ?? item['Meaning'] ?? ''),
  1705. phonetic: String(item['yb'] ?? detail['yb'] ?? item['Phonetic'] ?? detail['Phonetic'] ?? ''),
  1706. audio: String(item['yp'] ?? detail['yp'] ?? item['dy'] ?? detail['dy'] ?? ''),
  1707. };
  1708. }
  1709. private toNewWord(item: SourceItem): Word {
  1710. const detailValue = Array.isArray(item['detail']) ? item['detail'][0] : item['detail'];
  1711. const detail = detailValue && typeof detailValue === 'object' ? detailValue as SourceItem : {};
  1712. const detailTitle = String(detail['Title'] ?? '').trim();
  1713. const storedTitle = String(item['Title'] ?? '').split('@')[0].trim();
  1714. return this.toWord({ ...item, Title: detailTitle || storedTitle });
  1715. }
  1716. private toQuestion(item: SourceItem): ExamQuestion {
  1717. let options: ExamOption[] = [];
  1718. const raw = item['QOption'];
  1719. if (Array.isArray(raw)) {
  1720. options = raw as ExamOption[];
  1721. } else if (typeof raw === 'string') {
  1722. try { options = JSON.parse(raw) as ExamOption[]; } catch { options = []; }
  1723. }
  1724. return {
  1725. ...item,
  1726. ID: String(item['ID'] ?? item['GeneralID'] ?? ''),
  1727. AskID: String(item['AskID'] ?? ''),
  1728. QType: String(item['QType'] ?? ''),
  1729. QTitle: String(item['QTitle'] ?? ''),
  1730. QContent: this.cleanText(String(item['QContent'] ?? '')),
  1731. QOption: options,
  1732. };
  1733. }
  1734. private wordAudioUrl(path: string): string {
  1735. if (/^(data:|https?:\/\/|\/)/i.test(path)) return this.api.assetUrl(path);
  1736. return this.api.assetUrl(`UploadFiles/${path}`);
  1737. }
  1738. private setWordSelected(word: Word, shouldSelect: boolean): boolean {
  1739. const current = this.selected();
  1740. if (shouldSelect && !current.has(word.id) && current.size >= this.selectionLimit) {
  1741. this.platform.toast(`本次最多选择 ${this.selectionLimit} 个单词`, 'error');
  1742. return false;
  1743. }
  1744. const next = new Set(current);
  1745. if (shouldSelect) next.add(word.id);
  1746. else next.delete(word.id);
  1747. this.selected.set(next);
  1748. return true;
  1749. }
  1750. private setSelectionAssessment(word: Word, assessment: 'known' | 'unknown'): void {
  1751. this.selectionAssessment.update((current) => ({ ...current, [word.id]: assessment }));
  1752. }
  1753. private clearSelectionAssessment(word: Word): void {
  1754. this.selectionAssessment.update((current) => Object.fromEntries(Object.entries(current).filter(([id]) => id !== word.id)) as Record<string, 'known' | 'unknown'>);
  1755. }
  1756. private persistWordsAsLearned(words: Word[], owner: AppUser | null | undefined): Observable<unknown> {
  1757. if (!words.length) return of(null);
  1758. return this.api.post('e_add_words', {
  1759. uid: owner?.userId,
  1760. wordsId: words.map((word) => word.wordId).join(','),
  1761. kcid: this.query('pnid') || this.query('kcid') || this.orderInfo()['kcid'],
  1762. save: 1,
  1763. requestKey:this.draft().command('learn:'+words.map(w=>w.wordId).sort().join(',')),
  1764. });
  1765. }
  1766. private commitKnownWords(words: Word[]): void {
  1767. const ids = new Set(words.map((word) => word.id));
  1768. this.words.update((current) => current.map((word) => ids.has(word.id) ? { ...word, w_learned: Math.max(1, Number(word['w_learned'] ?? 0)) } : word));
  1769. this.selectionAssessment.update((current) => Object.fromEntries(Object.entries(current).filter(([id]) => !ids.has(id))) as Record<string, 'known' | 'unknown'>);
  1770. }
  1771. private findList(value: unknown): SourceItem[] {
  1772. if (Array.isArray(value)) return value as SourceItem[];
  1773. if (value && typeof value === 'object') {
  1774. for (const nested of Object.values(value)) {
  1775. if (Array.isArray(nested)) return nested as SourceItem[];
  1776. if (nested && typeof nested === 'object') {
  1777. for (const child of Object.values(nested)) if (Array.isArray(child)) return child as SourceItem[];
  1778. }
  1779. }
  1780. }
  1781. return [];
  1782. }
  1783. private parseArray(value: unknown): SourceItem[] {
  1784. if (Array.isArray(value)) return value as SourceItem[];
  1785. if (typeof value !== 'string' || !value) return [];
  1786. try {
  1787. const parsed = JSON.parse(value) as unknown;
  1788. return Array.isArray(parsed) ? parsed as SourceItem[] : [];
  1789. } catch {
  1790. return [];
  1791. }
  1792. }
  1793. private shuffle<T>(items: T[]): T[] {
  1794. const copy = [...items];
  1795. for (let index = copy.length - 1; index > 0; index -= 1) {
  1796. const target = Math.floor(Math.random() * (index + 1));
  1797. [copy[index], copy[target]] = [copy[target], copy[index]];
  1798. }
  1799. return copy;
  1800. }
  1801. private draft():LearningDraft {
  1802. const learner=this.canStartPointReading?this.session.student():this.session.user();
  1803. return new LearningDraft(`xiaoshu.learning.${this.session.user()?.userId}.${learner?.userId}.${this.query('orderId')||this.query('bindingId')||'practice'}`);
  1804. }
  1805. private learningStorageKey(key:string):string{return this.draft().key(key);}
  1806. private storageGet(key:string):unknown{return this.draft().get(key);}
  1807. private storageSet(key:string,value:unknown):void{this.draft().set(key,value);}
  1808. private query(name: string): string {
  1809. return this.route.snapshot.queryParamMap.get(name) ?? '';
  1810. }
  1811. private cleanText(value: string): string {
  1812. return value.replace(/<\/?[^>]*>/g, '').replace(/&nbsp;/gi, '').trim();
  1813. }
  1814. private dateOnly(): string {
  1815. const date = new Date();
  1816. return `${date.getFullYear()}-${this.pad(date.getMonth() + 1)}-${this.pad(date.getDate())}`;
  1817. }
  1818. private compactDate(): string {
  1819. return this.dateOnly().replaceAll('-', '');
  1820. }
  1821. private dateTime(seconds = false): string {
  1822. const date = new Date();
  1823. return `${this.dateOnly()} ${this.pad(date.getHours())}:${this.pad(date.getMinutes())}${seconds ? `:${this.pad(date.getSeconds())}` : ''}`;
  1824. }
  1825. private pad(value: number): string {
  1826. return String(value).padStart(2, '0');
  1827. }
  1828. }