gdou.js 26 KB

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