gdouyj.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. /**
  2. * 广东海洋大学阳江校区教务适配
  3. * @date 2026-7-30
  4. * @author Mccurtain (原始 GDOU 适配)
  5. * @adapted-by Yihe-ng (阳江校区作息与适配)
  6. * @version 1.1
  7. */
  8. (function () {
  9. /**
  10. * 节次与周次合并去重函数。
  11. * @param {Array<Object>} courses 原始解析课程数组
  12. * @returns {Array<Object>} 合并去重后的课程数组
  13. */
  14. function mergeAndDistinctCourses(courses) {
  15. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  16. const list = courses.map(course => ({
  17. ...course,
  18. name: course.name || '',
  19. teacher: course.teacher || '',
  20. position: course.position || '',
  21. weeks: Array.isArray(course.weeks) ? [...course.weeks].sort((a, b) => a - b) : []
  22. }));
  23. // 阶段 1:合并相同课程、星期、周次下的连续节次和重复记录。
  24. list.sort((a, b) =>
  25. a.name.localeCompare(b.name) ||
  26. a.teacher.localeCompare(b.teacher) ||
  27. a.position.localeCompare(b.position) ||
  28. (a.day || 0) - (b.day || 0) ||
  29. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  30. (a.startSection || 0) - (b.startSection || 0)
  31. );
  32. const sectionMerged = [];
  33. let current = list[0];
  34. for (let i = 1; i < list.length; i++) {
  35. const next = list[i];
  36. const sameCourseAndWeeks =
  37. current.name === next.name &&
  38. current.teacher === next.teacher &&
  39. current.position === next.position &&
  40. current.day === next.day &&
  41. current.weeks.join(',') === next.weeks.join(',');
  42. const isContinuous = current.endSection + 1 === next.startSection;
  43. const isDuplicate = current.startSection === next.startSection &&
  44. current.endSection === next.endSection;
  45. if (sameCourseAndWeeks && isContinuous) {
  46. current.endSection = next.endSection;
  47. } else if (sameCourseAndWeeks && isDuplicate) {
  48. continue;
  49. } else {
  50. sectionMerged.push(current);
  51. current = next;
  52. }
  53. }
  54. sectionMerged.push(current);
  55. // 阶段 2:合并相同节次下分段返回的周次。
  56. sectionMerged.sort((a, b) =>
  57. a.name.localeCompare(b.name) ||
  58. a.teacher.localeCompare(b.teacher) ||
  59. a.position.localeCompare(b.position) ||
  60. (a.day || 0) - (b.day || 0) ||
  61. (a.startSection || 0) - (b.startSection || 0) ||
  62. (a.endSection || 0) - (b.endSection || 0)
  63. );
  64. const result = [];
  65. let currentCourse = sectionMerged[0];
  66. for (let i = 1; i < sectionMerged.length; i++) {
  67. const nextCourse = sectionMerged[i];
  68. const sameCourseAndSection =
  69. currentCourse.name === nextCourse.name &&
  70. currentCourse.teacher === nextCourse.teacher &&
  71. currentCourse.position === nextCourse.position &&
  72. currentCourse.day === nextCourse.day &&
  73. currentCourse.startSection === nextCourse.startSection &&
  74. currentCourse.endSection === nextCourse.endSection;
  75. if (sameCourseAndSection) {
  76. currentCourse.weeks = Array.from(new Set([
  77. ...currentCourse.weeks,
  78. ...nextCourse.weeks
  79. ])).sort((a, b) => a - b);
  80. } else {
  81. result.push(currentCourse);
  82. currentCourse = nextCourse;
  83. }
  84. }
  85. result.push(currentCourse);
  86. return result;
  87. }
  88. /**
  89. * 解析周次字符串,处理单双周和周次范围。
  90. * 兼容格式:"1-16周"、"6周"、"1-8周(单)"、"1-10周(双)"、"1-5周,9周"
  91. */
  92. function parseWeeks(weekStr) {
  93. if (!weekStr) return [];
  94. const normalizedWeekStr = String(weekStr).replace(/,/g, ',');
  95. const weekSets = normalizedWeekStr.split(',');
  96. let weeks = [];
  97. for (const set of weekSets) {
  98. const trimmedSet = set.trim();
  99. const rangeMatch = trimmedSet.match(/(\d+)\s*-\s*(\d+)\s*周?/);
  100. const singleMatch = trimmedSet.match(/^(\d+)\s*周?/); // 匹配单个周次
  101. let start = 0;
  102. let end = 0;
  103. let processed = false;
  104. if (rangeMatch) { // 范围, 如 "1-5周"
  105. start = Number(rangeMatch[1]);
  106. end = Number(rangeMatch[2]);
  107. processed = true;
  108. } else if (singleMatch) { // 单个周, 如 "6周"
  109. start = end = Number(singleMatch[1]);
  110. processed = true;
  111. }
  112. if (processed && start >= 1 && end >= start) {
  113. // 确定单双周
  114. const isSingle = trimmedSet.includes('(单)');
  115. const isDouble = trimmedSet.includes('(双)');
  116. for (let w = start; w <= end; w++) {
  117. if (isSingle && w % 2 === 0) continue; // 单周跳过偶数
  118. if (isDouble && w % 2 !== 0) continue; // 双周跳过奇数
  119. weeks.push(w);
  120. }
  121. }
  122. }
  123. // 去重并排序
  124. return [...new Set(weeks)].sort((a, b) => a - b);
  125. }
  126. /**
  127. * 解析节次字符串,例如 "1-2"、"1-2节" 或单节 "3"。
  128. * 返回 null 表示接口返回了无法识别的节次格式。
  129. */
  130. function parseSectionRange(sectionStr) {
  131. const sectionText = sectionStr == null ? '' : String(sectionStr);
  132. const sectionMatch = sectionText.match(/^\s*(?:第)?(\d+)\s*(?:-\s*(\d+))?\s*节?\s*$/);
  133. if (!sectionMatch) {
  134. return null;
  135. }
  136. const startSection = Number(sectionMatch[1]);
  137. const endSection = Number(sectionMatch[2] || sectionMatch[1]);
  138. if (!Number.isInteger(startSection) || !Number.isInteger(endSection) ||
  139. startSection < 1 || endSection < startSection) {
  140. return null;
  141. }
  142. return { startSection, endSection };
  143. }
  144. /**
  145. * 阳江校区其他场地(非慎思楼)的作息。
  146. * 只有第 3、4 节在校区作息表中是不同的连续时间块,使用自定义时间表示。
  147. */
  148. const OTHER_VENUE_SECTION_3_4_TIME = { startTime: "10:10", endTime: "11:40" };
  149. function getOtherVenueCustomTime(position, startSection, endSection) {
  150. const positionText = position == null ? '' : String(position);
  151. if (!positionText || positionText.includes("慎思楼")) {
  152. return null;
  153. }
  154. if (startSection !== 3 || endSection !== 4) {
  155. return null;
  156. }
  157. return OTHER_VENUE_SECTION_3_4_TIME;
  158. }
  159. function applyOtherVenueCustomTime(courses) {
  160. return courses.map(course => {
  161. const customTime = getOtherVenueCustomTime(
  162. course.position,
  163. course.startSection,
  164. course.endSection
  165. );
  166. if (!customTime) return course;
  167. return {
  168. ...course,
  169. isCustomTime: true,
  170. customStartTime: customTime.startTime,
  171. customEndTime: customTime.endTime
  172. };
  173. });
  174. }
  175. /**
  176. * 解析正方 v9 课表查询接口返回的 JSON 数据。
  177. */
  178. function parseJsonData(jsonData) {
  179. console.log("JS: parseJsonData 正在解析 JSON 数据...");
  180. // 正方 v9 个人课表数据放在 kbList 字段中
  181. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  182. console.warn("JS: JSON 数据结构错误或缺少 kbList 字段。");
  183. return [];
  184. }
  185. const rawCourseList = jsonData.kbList;
  186. const initialCourseList = [];
  187. for (const rawCourse of rawCourseList) {
  188. if (!rawCourse || typeof rawCourse !== 'object') {
  189. continue;
  190. }
  191. // 课程名、星期、节次和周次是解析所必需的;教师或教室为空时仍保留课程。
  192. if (!rawCourse.kcmc || rawCourse.xqj == null ||
  193. rawCourse.jcs == null || rawCourse.zcd == null) {
  194. continue;
  195. }
  196. const weeksArray = parseWeeks(rawCourse.zcd);
  197. // 周次有效性检查
  198. if (weeksArray.length === 0) {
  199. continue;
  200. }
  201. const sectionRange = parseSectionRange(rawCourse.jcs);
  202. if (!sectionRange) {
  203. console.warn(`JS: 跳过无法解析节次的课程:${rawCourse.kcmc}`);
  204. continue;
  205. }
  206. const day = Number(rawCourse.xqj); // xqj: 星期几 (周一为1, 周日为7)
  207. // 数字有效性检查
  208. if (isNaN(day) || day < 1 || day > 7) {
  209. continue;
  210. }
  211. initialCourseList.push({
  212. name: String(rawCourse.kcmc).trim(),
  213. teacher: rawCourse.xm == null ? '' : String(rawCourse.xm).trim(),
  214. position: rawCourse.cdmc == null ? '' : String(rawCourse.cdmc).trim(),
  215. day: day,
  216. startSection: sectionRange.startSection,
  217. endSection: sectionRange.endSection,
  218. weeks: weeksArray
  219. });
  220. }
  221. const mergedCourses = mergeAndDistinctCourses(initialCourseList);
  222. const finalCourseList = applyOtherVenueCustomTime(mergedCourses);
  223. finalCourseList.sort((a, b) =>
  224. a.day - b.day ||
  225. a.startSection - b.startSection ||
  226. a.name.localeCompare(b.name)
  227. );
  228. console.log(`JS: JSON 数据解析与合并完成,共找到 ${finalCourseList.length} 门课程。`);
  229. return finalCourseList;
  230. }
  231. async function promptUserToStart() {
  232. console.log("JS: 流程开始:显示公告。");
  233. return await window.shiguangBridgePromise.showAlert(
  234. "广东海洋大学阳江校区教务系统课表导入",
  235. "请先登录广东海洋大学教务系统(jw.gdou.edu.cn),并在个人课表页选择要导入的学年学期。点击确认后按提示继续即可。",
  236. "好的,开始导入"
  237. );
  238. }
  239. /**
  240. * 从 select 元素解析学年和学期选项。
  241. * 默认索引优先使用当前 select.value,确保跟随用户在页面上的实际选择。
  242. */
  243. function parseSelectOptions(selectElement) {
  244. if (!selectElement || typeof selectElement.querySelectorAll !== "function") {
  245. return { options: [], defaultIndex: 0 };
  246. }
  247. const options = [];
  248. let defaultIndex = 0;
  249. Array.from(selectElement.querySelectorAll("option")).forEach(option => {
  250. const value = String(option.value || "").trim();
  251. if (!value) return;
  252. const text = String(option.textContent || "").trim() || value;
  253. if (option.selected) defaultIndex = options.length;
  254. options.push({ value, text });
  255. });
  256. const currentValue = String(selectElement.value || "").trim();
  257. const currentIndex = options.findIndex(option => option.value === currentValue);
  258. if (currentIndex !== -1) defaultIndex = currentIndex;
  259. return { options, defaultIndex };
  260. }
  261. function parseAcademicOptionsFromDocument(doc) {
  262. if (!doc || typeof doc.querySelector !== "function") return null;
  263. const yearData = parseSelectOptions(doc.querySelector("#xnm"));
  264. const semesterData = parseSelectOptions(doc.querySelector("#xqm"));
  265. if (yearData.options.length === 0 || semesterData.options.length === 0) return null;
  266. return {
  267. yearOptions: yearData.options,
  268. semesterOptions: semesterData.options,
  269. defaultYearIndex: yearData.defaultIndex,
  270. defaultSemesterIndex: semesterData.defaultIndex
  271. };
  272. }
  273. function isOnTimetablePage() {
  274. const pathname = typeof window !== "undefined" && window.location
  275. ? window.location.pathname
  276. : "";
  277. return typeof pathname === "string" && pathname.includes("xskbcx_cxXskbcxIndex.html");
  278. }
  279. function getCurrentPageAcademicOptions() {
  280. if (!isOnTimetablePage() || typeof document === "undefined" || !document.querySelector) {
  281. return null;
  282. }
  283. return parseAcademicOptionsFromDocument(document);
  284. }
  285. /**
  286. * 从正方课表页读取学年和学期选项。
  287. * 学期码直接使用教务系统返回的 value,例如第一学期为 3、第二学期为 12。
  288. */
  289. async function fetchAcademicOptions() {
  290. const currentPageOptions = getCurrentPageAcademicOptions();
  291. if (currentPageOptions) {
  292. console.log("JS: 使用当前课表页的学年学期选项。");
  293. return currentPageOptions;
  294. }
  295. const url = "https://jw.gdou.edu.cn/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default";
  296. try {
  297. const response = await fetch(url, {
  298. method: "GET",
  299. credentials: "include"
  300. });
  301. if (!response.ok) return null;
  302. const htmlText = await response.text();
  303. const doc = new DOMParser().parseFromString(htmlText, "text/html");
  304. const optionsData = parseAcademicOptionsFromDocument(doc);
  305. if (!optionsData) return null;
  306. const selectedYearIndex = optionsData.defaultYearIndex;
  307. const start = Math.max(0, selectedYearIndex - 2);
  308. const end = Math.min(optionsData.yearOptions.length, selectedYearIndex + 3);
  309. return {
  310. ...optionsData,
  311. yearOptions: optionsData.yearOptions.slice(start, end),
  312. defaultYearIndex: selectedYearIndex - start
  313. };
  314. } catch (error) {
  315. console.warn("JS: 读取学年学期选项失败:", error);
  316. return null;
  317. }
  318. }
  319. /**
  320. * 使用教务系统返回的选项让用户选择学年和学期。
  321. * 学年和学期码直接使用 option 的 value,避免本地手动映射。
  322. */
  323. async function selectAcademicYearAndSemester() {
  324. const optionsData = await fetchAcademicOptions();
  325. if (!optionsData) {
  326. window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确保登录状态。");
  327. return null;
  328. }
  329. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  330. const yearTexts = yearOptions.map(option => option.text);
  331. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  332. "选择学年",
  333. JSON.stringify(yearTexts),
  334. defaultYearIndex
  335. );
  336. if (yearIndex === null || yearIndex === -1 || !yearOptions[yearIndex]) return null;
  337. const selectedYearCode = yearOptions[yearIndex].value;
  338. const semesterTexts = semesterOptions.map(option => option.text);
  339. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  340. "选择学期",
  341. JSON.stringify(semesterTexts),
  342. defaultSemesterIndex
  343. );
  344. if (semesterIndex === null || semesterIndex === -1 || !semesterOptions[semesterIndex]) return null;
  345. const selectedSemesterCode = semesterOptions[semesterIndex].value;
  346. return {
  347. academicYear: selectedYearCode,
  348. semesterCode: selectedSemesterCode
  349. };
  350. }
  351. /**
  352. * 将正方返回的日期字段规范为 yyyy-MM-dd。
  353. */
  354. function normalizeStartDate(value) {
  355. const match = String(value || "").match(/(\d{4})[-\/.年](\d{1,2})[-\/.月](\d{1,2})/);
  356. if (!match) return null;
  357. return `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`;
  358. }
  359. /**
  360. * 从正方校历响应中查找第一周日期。
  361. * 兼容顶层数组、data/list/rows 等包装对象,以及 zrq/zcrq/rq/ksrq 字段。
  362. */
  363. function findSemesterStartDate(value) {
  364. if (value == null) return null;
  365. if (typeof value !== "object") {
  366. return normalizeStartDate(value);
  367. }
  368. if (Array.isArray(value)) {
  369. const firstWeek = value.find(item =>
  370. item && typeof item === "object" &&
  371. (String(item.zs) === "1" || String(item.zsmc) === "1")
  372. ) || value[0];
  373. const firstWeekDate = findSemesterStartDate(firstWeek);
  374. if (firstWeekDate) return firstWeekDate;
  375. for (const item of value) {
  376. const date = findSemesterStartDate(item);
  377. if (date) return date;
  378. }
  379. return null;
  380. }
  381. for (const field of ["zrq", "zcrq", "rq", "ksrq"]) {
  382. const date = normalizeStartDate(value[field]);
  383. if (date) return date;
  384. }
  385. for (const item of Object.values(value)) {
  386. const date = findSemesterStartDate(item);
  387. if (date) return date;
  388. }
  389. return null;
  390. }
  391. /**
  392. * 获取所选学期的第一周开学日期。
  393. * 日期接口失败时返回 null,不阻断课表导入。
  394. */
  395. async function fetchSemesterStartDate(academicYear, semesterCode) {
  396. const url = "https://jw.gdou.edu.cn/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154";
  397. const requestBody = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}`;
  398. try {
  399. const response = await fetch(url, {
  400. method: "POST",
  401. headers: {
  402. "accept": "application/json, text/javascript, */*; q=0.01",
  403. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  404. "x-requested-with": "XMLHttpRequest"
  405. },
  406. body: requestBody,
  407. credentials: "include"
  408. });
  409. if (!response.ok) {
  410. console.warn(`JS: 开学日期接口请求失败:HTTP ${response.status}`);
  411. return null;
  412. }
  413. const responseText = await response.text();
  414. let json;
  415. try {
  416. json = JSON.parse(responseText);
  417. } catch (error) {
  418. console.warn("JS: 开学日期接口未返回 JSON,可能登录已过期。", error);
  419. return null;
  420. }
  421. const startDate = findSemesterStartDate(json);
  422. if (!startDate) console.warn("JS: 校历响应中未找到第 1 周开学日期。");
  423. return startDate;
  424. } catch (error) {
  425. console.warn("JS: 获取学期开学日期失败:", error);
  426. }
  427. return null;
  428. }
  429. /**
  430. * 请求正方 v9 课表接口并解析课程数据。
  431. */
  432. async function fetchAndParseCourses(academicYear, semesterCode) {
  433. const requestBody = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}&kzlx=ck&xsdm=&kclbdm=`;
  434. // 广东海洋大学正方教务 v9 个人课表查询接口
  435. const targetUrl = "https://jw.gdou.edu.cn/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151";
  436. try {
  437. // 课表和校历互不依赖,并行请求以减少导入等待时间。
  438. const [courseResponse, semesterStartDate] = await Promise.all([
  439. fetch(targetUrl, {
  440. method: "POST",
  441. headers: {
  442. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  443. },
  444. body: requestBody,
  445. credentials: "include"
  446. }),
  447. fetchSemesterStartDate(academicYear, semesterCode)
  448. ]);
  449. if (!courseResponse.ok) {
  450. window.shiguangBridge.showToast(`课表请求失败:HTTP ${courseResponse.status}`);
  451. console.error(`JS: 接口返回非 200 状态码:${courseResponse.status}`);
  452. return null;
  453. }
  454. const jsonText = await courseResponse.text();
  455. const jsonData = JSON.parse(jsonText);
  456. if (!jsonData || !Array.isArray(jsonData.kbList) || jsonData.kbList.length === 0) {
  457. window.shiguangBridge.showToast("未查询到课表数据,请检查学年/学期是否选择正确,或确认已登录教务系统。");
  458. return null;
  459. }
  460. const parsedCourses = parseJsonData(jsonData);
  461. if (parsedCourses.length === 0) {
  462. window.shiguangBridge.showToast("课表数据为空或解析失败,请确认所选学年学期。");
  463. return null;
  464. }
  465. return {
  466. courses: parsedCourses,
  467. // CourseConfigJsonModel(wiki 1.3):所有字段可选,未提供则用默认值。
  468. // GDOU 各节课间隔不统一,因此用 TimeSlot 节次表达时间。
  469. config: {
  470. semesterStartDate,
  471. semesterTotalWeeks: 20
  472. }
  473. };
  474. } catch (e) {
  475. console.error("JS: 获取课表失败:", e);
  476. window.shiguangBridge.showToast("获取课表失败,请确认已登录教务系统且网络可访问 jw.gdou.edu.cn。");
  477. return null;
  478. }
  479. }
  480. async function saveCourses(parsedCourses) {
  481. window.shiguangBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
  482. console.log(`JS: 尝试保存 ${parsedCourses.length} 门课程...`);
  483. try {
  484. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses, null, 2));
  485. console.log("JS: 课程保存成功!");
  486. return true;
  487. } catch (error) {
  488. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  489. console.error('JS: Save Courses Error:', error);
  490. return false;
  491. }
  492. }
  493. // 阳江校区慎思楼上课时间(根据用户提供的校区作息表)
  494. const TimeSlots = [
  495. { number: 1, startTime: "08:10", endTime: "08:55" },
  496. { number: 2, startTime: "09:05", endTime: "09:50" },
  497. { number: 3, startTime: "10:20", endTime: "11:05" },
  498. { number: 4, startTime: "11:15", endTime: "12:00" },
  499. { number: 5, startTime: "14:30", endTime: "15:15" },
  500. { number: 6, startTime: "15:20", endTime: "16:05" },
  501. { number: 7, startTime: "16:20", endTime: "17:05" },
  502. { number: 8, startTime: "17:10", endTime: "17:55" },
  503. { number: 9, startTime: "19:30", endTime: "20:15" },
  504. { number: 10, startTime: "20:25", endTime: "21:10" }
  505. ];
  506. async function importPresetTimeSlots(timeSlots) {
  507. console.log(`JS: 准备导入 ${timeSlots.length} 个预设时间段。`);
  508. if (timeSlots.length > 0) {
  509. window.shiguangBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
  510. try {
  511. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  512. window.shiguangBridge.showToast("预设时间段导入成功!");
  513. console.log("JS: 预设时间段导入成功。");
  514. } catch (error) {
  515. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  516. console.error('JS: Save Time Slots Error:', error);
  517. }
  518. } else {
  519. window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
  520. console.warn("JS: 警告:传入时间段为空,未导入时间段信息。");
  521. }
  522. }
  523. async function runImportFlow() {
  524. const alertConfirmed = await promptUserToStart();
  525. if (!alertConfirmed) {
  526. window.shiguangBridge.showToast("用户取消了导入。");
  527. console.log("JS: 用户取消了导入流程。");
  528. return;
  529. }
  530. const selection = await selectAcademicYearAndSemester();
  531. if (!selection) {
  532. window.shiguangBridge.showToast("导入已取消。");
  533. console.log("JS: 获取学年学期失败/取消,流程终止。");
  534. return;
  535. }
  536. const { academicYear, semesterCode } = selection;
  537. console.log(`JS: 已确定学年学期:${academicYear},学期码:${semesterCode}`);
  538. const result = await fetchAndParseCourses(academicYear, semesterCode);
  539. if (result === null) {
  540. console.log("JS: 课程获取或解析失败,流程终止。");
  541. return;
  542. }
  543. const { courses, config } = result;
  544. const saveResult = await saveCourses(courses);
  545. if (!saveResult) {
  546. console.log("JS: 课程保存失败,流程终止。");
  547. return;
  548. }
  549. try {
  550. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  551. const configMessage = config.semesterStartDate
  552. ? `课表配置更新成功!总周数:${config.semesterTotalWeeks}周,开学日期:${config.semesterStartDate}。`
  553. : `课表配置更新成功!总周数:${config.semesterTotalWeeks}周,未获取到开学日期,已继续导入。`;
  554. window.shiguangBridge.showToast(configMessage);
  555. } catch (error) {
  556. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  557. console.error('JS: Save Config Error:', error);
  558. return;
  559. }
  560. await importPresetTimeSlots(TimeSlots);
  561. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  562. console.log("JS: 整个导入流程执行完毕并成功。");
  563. window.shiguangBridge.notifyTaskCompletion();
  564. }
  565. // 脚本执行入口
  566. runImportFlow();
  567. })();