gdou.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. /**
  2. * 广东海洋大学教务课表导入适配
  3. * @date 2026-08-27
  4. * @author Mccurtain
  5. * @version 2.0
  6. */
  7. (function () {
  8. // ==================== 常量 ====================
  9. // venues 为整栋楼使用特殊作息的楼名(包含匹配,如 "实验楼" 会命中 "实验楼301"、"网球场(实验楼东面)");
  10. // venuePatterns 为楼名简写正则(如海滨 "实"+房间号 = 实验楼简写,实506-1计算机(2)室);
  11. // outdoorKeywords 为特殊作息的室外场地关键词。
  12. const CAMPUS_CONFIGS = [
  13. {
  14. id: "huguang",
  15. label: "湖光校区",
  16. venues: ["广学楼", "明德楼"],
  17. venuePatterns: [],
  18. outdoorKeywords: []
  19. },
  20. {
  21. id: "haibin",
  22. label: "海滨校区",
  23. venues: ["实验楼"],
  24. venuePatterns: [{ name: "实验楼简写", pattern: /^实\d/ }],
  25. outdoorKeywords: ["球场", "东面", "南面", "西面", "北面"]
  26. }
  27. ];
  28. // 全校统一作息时间(1-10 节),未指定特殊作息的教室使用
  29. const TimeSlots = [
  30. { number: 1, startTime: "08:10", endTime: "08:55" },
  31. { number: 2, startTime: "09:00", endTime: "09:45" },
  32. { number: 3, startTime: "10:15", endTime: "11:00" },
  33. { number: 4, startTime: "11:05", endTime: "11:50" },
  34. { number: 5, startTime: "14:30", endTime: "15:15" },
  35. { number: 6, startTime: "15:20", endTime: "16:05" },
  36. { number: 7, startTime: "16:30", endTime: "17:15" },
  37. { number: 8, startTime: "17:20", endTime: "18:05" },
  38. { number: 9, startTime: "19:30", endTime: "20:15" },
  39. { number: 10, startTime: "20:25", endTime: "21:10" }
  40. ];
  41. // 指定楼/室外场地的特殊作息时间块(连堂)
  42. const SPECIAL_TIME_BLOCKS = [
  43. { startSection: 3, endSection: 4, startTime: "10:05", endTime: "11:35" },
  44. { startSection: 7, endSection: 8, startTime: "16:25", endTime: "17:50" }
  45. ];
  46. // ==================== 解析函数 ====================
  47. /**
  48. * 将周次字符串展开为具体周次数组
  49. * 支持范围(如 1-16周)、单周(如 6周)、单双周(如 1-8周(单))、
  50. * 以及逗号分隔的多种写法混合,全角逗号也会被兼容
  51. */
  52. function parseWeeks(weekStr) {
  53. if (!weekStr) return [];
  54. const groups = String(weekStr).replace(/,/g, ',').split(',');
  55. const weeks = [];
  56. for (const group of groups) {
  57. const item = group.trim();
  58. // 先尝试匹配 "起-止周",再尝试匹配单个周次
  59. const rangeMatch = item.match(/(\d+)\s*-\s*(\d+)\s*周?/);
  60. const singleMatch = item.match(/^(\d+)\s*周?/);
  61. let start = 0;
  62. let end = 0;
  63. let matched = false;
  64. if (rangeMatch) {
  65. start = Number(rangeMatch[1]);
  66. end = Number(rangeMatch[2]);
  67. matched = true;
  68. } else if (singleMatch) {
  69. start = end = Number(singleMatch[1]);
  70. matched = true;
  71. }
  72. if (matched && start >= 1 && end >= start) {
  73. const isOddOnly = item.includes('(单)');
  74. const isEvenOnly = item.includes('(双)');
  75. for (let w = start; w <= end; w++) {
  76. if (isOddOnly && w % 2 === 0) continue; // 单周:跳过偶数周
  77. if (isEvenOnly && w % 2 !== 0) continue; // 双周:跳过奇数周
  78. weeks.push(w);
  79. }
  80. }
  81. }
  82. return [...new Set(weeks)].sort((a, b) => a - b);
  83. }
  84. /**
  85. * 解析节次字段,如 "1-2"、"3"、"1-2节",得到起止节次
  86. * 格式无法识别或数值不合法时返回 null
  87. */
  88. function parseSectionRange(sectionStr) {
  89. const text = sectionStr == null ? '' : String(sectionStr);
  90. const match = text.match(/^\s*(?:第)?(\d+)\s*(?:-\s*(\d+))?\s*节?\s*$/);
  91. if (!match) return null;
  92. const startSection = Number(match[1]);
  93. const endSection = Number(match[2] || match[1]);
  94. if (!Number.isInteger(startSection) || !Number.isInteger(endSection) ||
  95. startSection < 1 || endSection < startSection) {
  96. return null;
  97. }
  98. return { startSection, endSection };
  99. }
  100. // 提前公选课课程名
  101. function normalizeCourseName(rawName) {
  102. const name = String(rawName).trim();
  103. if (!name) return name;
  104. const match = name.match(/^[((]([^()()]+)[))]\s*/);
  105. if (!match) return name;
  106. const rest = name.slice(match[0].length);
  107. if (!rest) return name;
  108. return `${rest}(${match[1]})`;
  109. }
  110. /**
  111. * 节次与周次合并去重函数
  112. * @param {Array<Object>} courses 原始解析课程数组
  113. * @returns {Array<Object>} 合并去重后的课程数组
  114. */
  115. function mergeAndDistinctCourses(courses) {
  116. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  117. // 规范化数据,周次统一排序,便于比较
  118. const list = courses.map(c => ({
  119. ...c,
  120. name: c.name || '',
  121. teacher: c.teacher || '',
  122. position: c.position || '',
  123. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  124. }));
  125. // 第一步:按课程、周次排序后合并连续节次,同时剔除完全重复项
  126. list.sort((a, b) =>
  127. a.name.localeCompare(b.name) ||
  128. a.teacher.localeCompare(b.teacher) ||
  129. a.position.localeCompare(b.position) ||
  130. (a.day || 0) - (b.day || 0) ||
  131. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  132. (a.startSection || 0) - (b.startSection || 0)
  133. );
  134. const step1 = [];
  135. let current = list[0];
  136. for (let i = 1; i < list.length; i++) {
  137. const next = list[i];
  138. const isSameCourse =
  139. current.name === next.name &&
  140. current.teacher === next.teacher &&
  141. current.position === next.position &&
  142. current.day === next.day &&
  143. current.weeks.join(',') === next.weeks.join(',');
  144. if (isSameCourse && current.endSection + 1 === next.startSection) {
  145. // 节次紧邻,延长结束节次:1-2 节 + 3-4 节 -> 1-4 节
  146. current.endSection = next.endSection;
  147. } else if (isSameCourse && current.startSection === next.startSection && current.endSection === next.endSection) {
  148. // 完全重复的记录,跳过
  149. continue;
  150. } else {
  151. step1.push(current);
  152. current = next;
  153. }
  154. }
  155. step1.push(current);
  156. // 第二步:按课程、节次排序后合并相同节次的周次
  157. step1.sort((a, b) =>
  158. a.name.localeCompare(b.name) ||
  159. a.teacher.localeCompare(b.teacher) ||
  160. a.position.localeCompare(b.position) ||
  161. (a.day || 0) - (b.day || 0) ||
  162. (a.startSection || 0) - (b.startSection || 0) ||
  163. (a.endSection || 0) - (b.endSection || 0)
  164. );
  165. const step2 = [];
  166. let cur = step1[0];
  167. for (let i = 1; i < step1.length; i++) {
  168. const nxt = step1[i];
  169. const isSameSection =
  170. cur.name === nxt.name &&
  171. cur.teacher === nxt.teacher &&
  172. cur.position === nxt.position &&
  173. cur.day === nxt.day &&
  174. cur.startSection === nxt.startSection &&
  175. cur.endSection === nxt.endSection;
  176. if (isSameSection) {
  177. // 周次取并集:1-8 周 + 9-16 周 -> 1-16 周
  178. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  179. } else {
  180. step2.push(cur);
  181. cur = nxt;
  182. }
  183. }
  184. step2.push(cur);
  185. return step2;
  186. }
  187. // ==================== 特殊作息处理 ====================
  188. /**
  189. * 判断位置是否命中特殊场地(指定楼或室外场地),返回命中的类型与关键词
  190. * 楼名与室外关键词取并集,包含任一即可;命中者打标特殊作息
  191. * @returns {{type: 'venue'|'outdoor', key: string}|null}
  192. */
  193. function matchesSpecialVenue(positionText, campusConfig) {
  194. const venueHit = campusConfig.venues.find(venue => positionText.includes(venue));
  195. if (venueHit) return { type: 'venue', key: venueHit };
  196. const patternHit = (campusConfig.venuePatterns || []).find(p => p.pattern.test(positionText));
  197. if (patternHit) return { type: 'venue', key: patternHit.name };
  198. const outdoorHit = campusConfig.outdoorKeywords.find(keyword => positionText.includes(keyword));
  199. if (outdoorHit) return { type: 'outdoor', key: outdoorHit };
  200. return null;
  201. }
  202. /**
  203. * 判断课程是否命中特殊作息(正向策略)
  204. * 命中指定楼/室外场地的课程,在节次恰为特殊时间块(3-4/7-8 节)时打标特殊时间;
  205. * 其他普通教室不打标,使用 TimeSlots 全校统一作息。
  206. * 返回对象附带 reason 判定原因,供内部诊断与本地验证脚本使用(不写入导出课程)。
  207. */
  208. function getCustomTime(position, startSection, endSection, campusConfig) {
  209. const positionText = position == null ? '' : String(position);
  210. const hit = matchesSpecialVenue(positionText, campusConfig);
  211. if (!hit) return { marked: false, reason: 'no-block' };
  212. const block = SPECIAL_TIME_BLOCKS.find(
  213. b => b.startSection === startSection && b.endSection === endSection
  214. );
  215. if (block) return { marked: true, startTime: block.startTime, endTime: block.endTime, reason: `special-${hit.type}:${hit.key}` };
  216. return { marked: false, reason: `special-${hit.type}:${hit.key}-no-block` };
  217. }
  218. // ==================== 数据解析 ====================
  219. /**
  220. * 解析正方 v9 课表接口返回的 JSON,提取有效课程
  221. * 数据位于 kbList 字段;课程名/星期/节次/周次缺失或不合法的记录会被跳过,
  222. * 教师、教室允许为空
  223. */
  224. function parseJsonData(jsonData, campusConfig) {
  225. if (!jsonData || !Array.isArray(jsonData.kbList)) return [];
  226. const courses = [];
  227. for (const raw of jsonData.kbList) {
  228. if (!raw || typeof raw !== 'object') continue;
  229. if (!raw.kcmc || raw.xqj == null || raw.jcs == null || raw.zcd == null) continue;
  230. const weeks = parseWeeks(raw.zcd);
  231. if (weeks.length === 0) continue;
  232. const sectionRange = parseSectionRange(raw.jcs);
  233. if (!sectionRange) continue;
  234. const day = Number(raw.xqj); // 1=周一 ... 7=周日
  235. if (isNaN(day) || day < 1 || day > 7) continue;
  236. // 直接基于原始接口字段 cdmc 构造课程位置
  237. const position = raw.cdmc == null ? '' : String(raw.cdmc).trim();
  238. const course = {
  239. name: normalizeCourseName(raw.kcmc),
  240. teacher: raw.xm == null ? '' : String(raw.xm).trim(),
  241. position,
  242. day,
  243. startSection: sectionRange.startSection,
  244. endSection: sectionRange.endSection,
  245. weeks
  246. };
  247. // 边解析边判断:直接对原始教室字段 cdmc 判断是否命中特殊作息,
  248. // 命中则在写入课程对象的同时打好 isCustomTime 标记,App 将优先显示自定义时间
  249. const customTime = getCustomTime(position, course.startSection, course.endSection, campusConfig);
  250. if (customTime.marked) {
  251. course.isCustomTime = true;
  252. course.customStartTime = customTime.startTime;
  253. course.customEndTime = customTime.endTime;
  254. }
  255. courses.push(course);
  256. }
  257. const mergedCourses = mergeAndDistinctCourses(courses);
  258. // 合并可能改变节次区间(如 1-2 节 + 3-4 节 -> 1-4 节),对已打标课程做最终校验:
  259. // 合并后的区间不再精确命中特殊时间块时,撤销打标,避免特殊时间被错误扩散
  260. return mergedCourses.map(course => {
  261. if (!course.isCustomTime) return course;
  262. const customTime = getCustomTime(course.position, course.startSection, course.endSection, campusConfig);
  263. if (!customTime.marked) {
  264. const plain = { ...course };
  265. delete plain.isCustomTime;
  266. delete plain.customStartTime;
  267. delete plain.customEndTime;
  268. return plain;
  269. }
  270. return course;
  271. });
  272. }
  273. // ==================== 日期工具 ====================
  274. /**
  275. * 把教务返回的日期字段规范为 yyyy-MM-dd
  276. * 兼容 "-"、"."、"/" 以及中文"年月日"等分隔写法
  277. */
  278. function normalizeStartDate(value) {
  279. const match = String(value || "").match(/(\d{4})[-\/.年](\d{1,2})[-\/.月](\d{1,2})/);
  280. if (!match) return null;
  281. return `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`;
  282. }
  283. /**
  284. * 在校历响应中查找第 1 周开学日期
  285. * 兼容顶层数组、data/list/rows 等包装对象,以及 zrq/zcrq/rq/ksrq 字段
  286. */
  287. function findSemesterStartDate(value) {
  288. if (value == null) return null;
  289. if (typeof value !== "object") return normalizeStartDate(value);
  290. if (Array.isArray(value)) {
  291. const firstWeek = value.find(item =>
  292. item && typeof item === "object" &&
  293. (String(item.zs) === "1" || String(item.zsmc) === "1")
  294. ) || value[0];
  295. const found = findSemesterStartDate(firstWeek);
  296. if (found) return found;
  297. for (const item of value) {
  298. const date = findSemesterStartDate(item);
  299. if (date) return date;
  300. }
  301. return null;
  302. }
  303. for (const field of ["zrq", "zcrq", "rq", "ksrq"]) {
  304. const date = normalizeStartDate(value[field]);
  305. if (date) return date;
  306. }
  307. for (const item of Object.values(value)) {
  308. const date = findSemesterStartDate(item);
  309. if (date) return date;
  310. }
  311. return null;
  312. }
  313. // ==================== 教务接口 ====================
  314. /**
  315. * 读取课表查询页里的学年/学期下拉选项
  316. * 成功返回 { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex };
  317. * 读取失败返回 null,由调用方回退到默认值
  318. */
  319. async function fetchAcademicOptions() {
  320. const url = "https://jw.gdou.edu.cn/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default";
  321. try {
  322. const response = await fetch(url, { method: "GET", credentials: "include" });
  323. if (!response.ok) return null;
  324. const doc = new DOMParser().parseFromString(await response.text(), "text/html");
  325. // 解析单个下拉框;默认选中项优先跟随 select 当前值,其次取 selected 属性
  326. const readSelect = (select) => {
  327. if (!select) return null;
  328. const options = Array.from(select.querySelectorAll("option"))
  329. .map(opt => ({ value: opt.value, text: opt.textContent.trim() || opt.value }))
  330. .filter(opt => opt.value !== "");
  331. if (options.length === 0) return null;
  332. const valueIndex = options.findIndex(opt => opt.value === select.value);
  333. const selectedIndex = options.findIndex(opt => opt.selected);
  334. return { options, defaultIndex: valueIndex !== -1 ? valueIndex : Math.max(0, selectedIndex) };
  335. };
  336. const yearData = readSelect(doc.querySelector("#xnm"));
  337. const semesterData = readSelect(doc.querySelector("#xqm"));
  338. if (!yearData || !semesterData) return null;
  339. return {
  340. yearOptions: yearData.options,
  341. semesterOptions: semesterData.options,
  342. defaultYearIndex: yearData.defaultIndex,
  343. defaultSemesterIndex: semesterData.defaultIndex
  344. };
  345. } catch (e) {
  346. return null;
  347. }
  348. }
  349. /**
  350. * 查询指定学期的周次安排,取出第 1 周的日期作为开学日期,并返回该学期总周数
  351. * 接口失败时返回 null,不影响主流程
  352. */
  353. async function fetchSemesterInfo(academicYear, semesterCode) {
  354. const url = "https://jw.gdou.edu.cn/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154";
  355. const body = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}`;
  356. try {
  357. const response = await fetch(url, {
  358. method: "POST",
  359. headers: {
  360. "accept": "application/json, text/javascript, */*; q=0.01",
  361. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  362. "x-requested-with": "XMLHttpRequest"
  363. },
  364. body,
  365. credentials: "include"
  366. });
  367. if (!response.ok) return null;
  368. const weeks = await response.json();
  369. if (!Array.isArray(weeks) || weeks.length === 0) return null;
  370. return {
  371. startDate: findSemesterStartDate(weeks),
  372. totalWeeks: weeks.length
  373. };
  374. } catch (e) {
  375. return null;
  376. }
  377. }
  378. /**
  379. * 请求课表接口并解析课程,同时并行获取学期信息
  380. * 成功返回 { courses, config },失败返回 null
  381. */
  382. async function fetchAndParseCourses(academicYear, semesterCode, campusConfig) {
  383. const body = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}&kzlx=ck&xsdm=&kclbdm=`;
  384. const courseUrl = "https://jw.gdou.edu.cn/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151";
  385. const [courseResponse, semesterInfo] = await Promise.all([
  386. fetch(courseUrl, {
  387. method: "POST",
  388. headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
  389. body,
  390. credentials: "include"
  391. }),
  392. fetchSemesterInfo(academicYear, semesterCode)
  393. ]);
  394. try {
  395. if (!courseResponse.ok) {
  396. window.shiguangBridge.showToast(`课表请求失败:HTTP ${courseResponse.status}`);
  397. return null;
  398. }
  399. const courses = parseJsonData(JSON.parse(await courseResponse.text()), campusConfig);
  400. if (courses.length === 0) {
  401. window.shiguangBridge.showToast("未查询到课表数据,请检查学年/学期选择或登录状态。");
  402. return null;
  403. }
  404. // 总周数取接口返回值与课程最大周次中的较大者,保证不截断课表
  405. const maxCourseWeek = courses.reduce((max, c) => Math.max(max, ...c.weeks), 0);
  406. return {
  407. courses,
  408. config: {
  409. semesterStartDate: semesterInfo ? semesterInfo.startDate : null,
  410. semesterTotalWeeks: Math.max(maxCourseWeek, semesterInfo ? semesterInfo.totalWeeks : 20)
  411. }
  412. };
  413. } catch (e) {
  414. window.shiguangBridge.showToast("获取课表失败,请确认已登录且网络可访问 jw.gdou.edu.cn。");
  415. return null;
  416. }
  417. }
  418. // ==================== 交互 ====================
  419. /**
  420. * 按当前月份推断学年起始年份:9 月及以后属于新学年,其余月份沿用上一学年
  421. */
  422. function getDefaultAcademicYear(date = new Date()) {
  423. const currentYear = date.getFullYear();
  424. return (date.getMonth() >= 8 ? currentYear : currentYear - 1).toString();
  425. }
  426. /**
  427. * 弹出导入确认提示,说明使用前提
  428. */
  429. async function promptUserToStart() {
  430. return await window.shiguangBridgePromise.showAlert(
  431. "广东海洋大学教务系统课表导入",
  432. "导入前请确认已在浏览器中登录教务系统(jw.gdou.edu.cn)。\n脚本将通过接口直接获取课表,无需停留在特定页面。",
  433. "好的,开始导入"
  434. );
  435. }
  436. /**
  437. * 弹出校区选择框,决定使用哪套特殊作息规则
  438. * 取消返回 null,由调用方终止流程
  439. */
  440. async function selectCampus() {
  441. const campusIndex = await window.shiguangBridgePromise.showSingleSelection(
  442. "选择校区",
  443. JSON.stringify(CAMPUS_CONFIGS.map(item => item.label)),
  444. 0
  445. );
  446. if (campusIndex === null || campusIndex === -1) return null;
  447. return CAMPUS_CONFIGS[campusIndex];
  448. }
  449. /**
  450. * 依次弹出学年、学期选择框
  451. * 选项优先来自教务系统;若读取失败,则按当前月份给出默认学年,
  452. * 学期码(3=第一学期,12=第二学期)
  453. */
  454. async function selectAcademicYearAndSemester() {
  455. const options = await fetchAcademicOptions();
  456. let yearOptions;
  457. let semesterOptions;
  458. let defaultYearIndex;
  459. let defaultSemesterIndex;
  460. if (options) {
  461. ({ yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = options);
  462. } else {
  463. const year = getDefaultAcademicYear();
  464. const isFirstSemester = new Date().getMonth() >= 8;
  465. yearOptions = [{ value: year, text: `${year}-${Number(year) + 1}` }];
  466. semesterOptions = [
  467. { value: "3", text: "第一学期" },
  468. { value: "12", text: "第二学期" }
  469. ];
  470. defaultYearIndex = 0;
  471. defaultSemesterIndex = isFirstSemester ? 0 : 1;
  472. window.shiguangBridge.showToast("未读取到教务系统学年学期选项,已使用默认值,请核对。");
  473. }
  474. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  475. "选择学年",
  476. JSON.stringify(yearOptions.map(item => item.text)),
  477. defaultYearIndex
  478. );
  479. if (yearIndex === null || yearIndex === -1) return null;
  480. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  481. "选择学期",
  482. JSON.stringify(semesterOptions.map(item => item.text)),
  483. defaultSemesterIndex
  484. );
  485. if (semesterIndex === null || semesterIndex === -1) return null;
  486. return {
  487. academicYear: yearOptions[yearIndex].value,
  488. semesterCode: semesterOptions[semesterIndex].value
  489. };
  490. }
  491. // ==================== 保存 ====================
  492. async function saveCourses(courses) {
  493. try {
  494. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
  495. return true;
  496. } catch (error) {
  497. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  498. return false;
  499. }
  500. }
  501. /**
  502. * 将预设作息时间导入 App
  503. */
  504. async function importPresetTimeSlots(timeSlots) {
  505. if (timeSlots.length === 0) {
  506. window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
  507. return;
  508. }
  509. try {
  510. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  511. window.shiguangBridge.showToast("预设时间段导入成功!");
  512. } catch (error) {
  513. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  514. }
  515. }
  516. // ==================== 主流程 ====================
  517. async function runImportFlow() {
  518. // 1. 确认导入
  519. const confirmed = await promptUserToStart();
  520. if (!confirmed) {
  521. window.shiguangBridge.showToast("用户取消了导入。");
  522. return;
  523. }
  524. // 2. 选择学年学期
  525. const selection = await selectAcademicYearAndSemester();
  526. if (!selection) {
  527. window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
  528. return;
  529. }
  530. // 3. 选择校区(决定特殊作息规则)
  531. const campusConfig = await selectCampus();
  532. if (!campusConfig) {
  533. window.shiguangBridge.showToast("未选择校区,导入流程终止。");
  534. return;
  535. }
  536. // 4. 拉取并解析课程
  537. const result = await fetchAndParseCourses(selection.academicYear, selection.semesterCode, campusConfig);
  538. if (result === null) return;
  539. const { courses, config } = result;
  540. // 5. 保存课程
  541. if (!(await saveCourses(courses))) return;
  542. // 6. 保存课表配置(开学日期、总周数)
  543. try {
  544. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  545. let msg = `课表配置更新成功!总周数:${config.semesterTotalWeeks}周。`;
  546. if (config.semesterStartDate) msg += ` 开学日期:${config.semesterStartDate}`;
  547. window.shiguangBridge.showToast(msg);
  548. } catch (error) {
  549. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  550. }
  551. // 7. 导入预设作息时间
  552. await importPresetTimeSlots(TimeSlots);
  553. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  554. window.shiguangBridge.showToast(`若课程时间有误,请提交issue或联系开发者!`);
  555. window.shiguangBridge.notifyTaskCompletion();
  556. }
  557. runImportFlow();
  558. })();