gdou.js 24 KB

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