ujs_zhengfang_v9.0.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. // 江苏大学(ujs.edu.cn) 拾光课程表适配脚本
  2. // 基于正方教务系统接口适配
  3. // 出现问题请联系作者或者提交直接pr更改,这更加快速
  4. // 基于GSMC修改
  5. // 作者:洛初 Github@gongfuture
  6. // 2026.03.30 第一版
  7. // 通过正方接口 xskbcx_cxXsgrkb 拉取个人课表,解析课程名、教师、教室、星期、节次和周次(含单双周)。
  8. // 交互上依次询问学年、学期与作息类型(夏令时/冬令时/智能选择,智能选择按固定切令时日期判定)。
  9. // 按课程所在楼栋匹配上午与下午作息,写入课程的自定义时间;导入课程、课表配置与预设时间段。
  10. // 2026.08.23 第二版
  11. // 桥接接口升级至 v2(window.shiguangBridge / window.shiguangBridgePromise)。
  12. // 补充开学日期:从首页日历区块取当前学期起止日期写入 semesterStartDate,总周数改为按实际周次取值;
  13. // 取不到开学日期时跳过配置保存,避免覆盖用户已有设置。
  14. // 课程备注补充重修标记、选课备注(体育项目、微专业等)与周次原文。
  15. // 集中实践课(军训、毕业设计等)无星期节次无法排课,改为弹窗提示手动添加。
  16. // 教师与教室为空不再丢弃课程;修正京江各号楼的楼栋匹配;支持校外 WebVPN 访问。
  17. /**
  18. * 解析周次字符串,处理单双周和周次范围。
  19. */
  20. function parseWeeks(weekStr) {
  21. if (!weekStr) return [];
  22. const weekSets = weekStr.split(',');
  23. let weeks = [];
  24. for (const set of weekSets) {
  25. const trimmedSet = set.trim();
  26. const rangeMatch = trimmedSet.match(/(\d+)-(\d+)周/);
  27. const singleMatch = trimmedSet.match(/^(\d+)周/); // 匹配以数字周结束的
  28. let start = 0;
  29. let end = 0;
  30. let processed = false;
  31. if (rangeMatch) { // 范围, 如 "1-5周"
  32. start = Number(rangeMatch[1]);
  33. end = Number(rangeMatch[2]);
  34. processed = true;
  35. } else if (singleMatch) { // 单个周, 如 "6周"
  36. start = end = Number(singleMatch[1]);
  37. processed = true;
  38. }
  39. if (processed) {
  40. // 确定单双周
  41. const isSingle = trimmedSet.includes('(单)');
  42. const isDouble = trimmedSet.includes('(双)');
  43. for (let w = start; w <= end; w++) {
  44. if (isSingle && w % 2 === 0) continue; // 单周跳过偶数
  45. if (isDouble && w % 2 !== 0) continue; // 双周跳过奇数
  46. weeks.push(w);
  47. }
  48. }
  49. }
  50. // 去重并排序
  51. return [...new Set(weeks)].sort((a, b) => a - b);
  52. }
  53. /**
  54. * 拼接教务系统接口地址。
  55. * 校内直连时 location.origin 就是教务域名,前缀为空;
  56. * 校外经 WebVPN 访问时路径带有 /http/<hex> 前缀,必须保留,否则会变成跨域请求。
  57. */
  58. function buildApiUrl(path) {
  59. const prefixMatch = window.location.pathname.match(/^\/http\/[0-9a-f]+/i);
  60. const prefix = prefixMatch ? prefixMatch[0] : "";
  61. return window.location.origin + prefix + path;
  62. }
  63. /**
  64. * 拼装课程备注。
  65. * xm 只有姓名,kcmc 只有课程名,以下信息只存在于原始字段里,
  66. * 放进备注方便用户核对:重修标记、选课备注(体育项目、微专业等)、周次原文。
  67. */
  68. function buildCourseRemark(rawCourse) {
  69. const parts = [];
  70. const retakeFlag = String(rawCourse.cxbjmc || "").trim();
  71. if (retakeFlag) {
  72. parts.push(retakeFlag);
  73. }
  74. const selectionNote = String(rawCourse.xkbz || "").trim();
  75. if (selectionNote) {
  76. parts.push(selectionNote);
  77. }
  78. const weekDesc = String(rawCourse.zcd || "").trim();
  79. if (weekDesc) {
  80. parts.push(weekDesc);
  81. }
  82. return parts.join(" | ");
  83. }
  84. /**
  85. * 解析集中实践课列表(sjkList)。
  86. * 这类课程(军事技能训练、形势与政策等)只有课程名、教师和起止周,
  87. * 没有星期和节次,无法映射到周课表,只能提示用户手动添加。
  88. */
  89. function parsePracticeCourses(jsonData) {
  90. if (!jsonData || !Array.isArray(jsonData.sjkList)) {
  91. return [];
  92. }
  93. return jsonData.sjkList
  94. .map((item) => ({
  95. name: String(item.kcmc || "").trim(),
  96. teacher: String(item.jsxm || "").trim(),
  97. weekDesc: String(item.qsjsz || "").trim()
  98. }))
  99. .filter((item) => item.name);
  100. }
  101. /**
  102. * 解析 API 返回的 JSON 数据。
  103. */
  104. function parseJsonData(jsonData) {
  105. console.log("JS: parseJsonData 正在解析 JSON 数据...");
  106. // 检查JSON结构:新的数据在 kbList 字段中
  107. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  108. console.warn("JS: JSON 数据结构错误或缺少 kbList 字段。");
  109. return [];
  110. }
  111. const rawCourseList = jsonData.kbList;
  112. const finalCourseList = [];
  113. for (const rawCourse of rawCourseList) {
  114. // 关键字段检查:只有 kcmc(课名), xqj(星期), jcs(节次范围), zcd(周次描述) 是排课必需的。
  115. // xm(教师) 与 cdmc(教室) 在实践课、线上课、未排地点的课程上可能为空,
  116. // 缺这两项不影响排课,不能因此丢弃整门课程。
  117. if (!rawCourse.kcmc || !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) {
  118. continue;
  119. }
  120. const weeksArray = parseWeeks(rawCourse.zcd);
  121. // 周次有效性检查
  122. if (weeksArray.length === 0) {
  123. continue;
  124. }
  125. // 解析节次范围,例如 "1-2"
  126. const sectionParts = rawCourse.jcs.split('-');
  127. const startSection = Number(sectionParts[0]);
  128. const endSection = Number(sectionParts[sectionParts.length - 1]);
  129. const day = Number(rawCourse.xqj); // xqj: 星期几 (周一为1, 周日为7)
  130. // 数字有效性检查
  131. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) || day < 1 || day > 7 || startSection > endSection) {
  132. // console.warn(`JS: 课程 ${rawCourse.kcmc} 星期或节次数据无效,跳过。`);
  133. continue;
  134. }
  135. const remark = buildCourseRemark(rawCourse);
  136. const course = {
  137. name: String(rawCourse.kcmc).trim(),
  138. teacher: String(rawCourse.xm || "").trim(),
  139. position: String(rawCourse.cdmc || "").trim(),
  140. day: day,
  141. startSection: startSection,
  142. endSection: endSection,
  143. weeks: weeksArray
  144. };
  145. if (remark) {
  146. course.remark = remark;
  147. }
  148. finalCourseList.push(course);
  149. }
  150. finalCourseList.sort((a, b) =>
  151. a.day - b.day ||
  152. a.startSection - b.startSection ||
  153. a.name.localeCompare(b.name)
  154. );
  155. console.log(`JS: JSON 数据解析完成,共找到 ${finalCourseList.length} 门课程。`);
  156. return finalCourseList;
  157. }
  158. /**
  159. * 检查当前是否处于夏令时作息时间段。
  160. * @returns true 夏令时 false 冬令时
  161. */
  162. async function whetherSummerTimeSlot() {
  163. // // 教务处 校历/作息时间 公告页
  164. // const url = "https://jwc.ujs.edu.cn/index/xl_zuo_xi_shi_jian.htm";
  165. // let title = "";
  166. // try {
  167. // const response = await fetch(url);
  168. // if (!response.ok) {
  169. // throw new Error(`网络请求失败。状态码: ${response.status} (${response.statusText})`);
  170. // }
  171. // const html = await response.text();
  172. // const doc = new DOMParser().parseFromString(html, "text/html");
  173. // // 优先按页面固定 id 读取:#line_u8_0, #line_u8_1 ...
  174. // for (let i = 0; i < 30; i++) {
  175. // const a = doc.querySelector(`#line_u8_${i} > a`);
  176. // if (!a) continue;
  177. // title = (a.getAttribute("title") || a.textContent || "").trim();
  178. // if (title.includes("作息时间表")) {
  179. // break;
  180. // }
  181. // }
  182. // // 若固定 id 没取到,则扫描所有链接文本
  183. // if (title.trim().length === 0) {
  184. // const links = doc.querySelectorAll("a");
  185. // for (const link of links) {
  186. // title = (link.getAttribute("title") || link.textContent || "").trim();
  187. // if (title.includes("作息时间表")) {
  188. // break;
  189. // }
  190. // }
  191. // }
  192. // // 从公告中提取日期
  193. // if (title.trim().length === 0) {
  194. // throw new Error("未找到作息时间公告标题。");
  195. // }
  196. // const match = title.match(/[((]\s*(\d{4})年(\d{1,2})月(\d{1,2})日起执行\s*[))]/);
  197. // if (!match) {
  198. // throw new Error("公告标题格式不匹配,无法提取执行日期。");
  199. // }
  200. // const y = Number(match[1]);
  201. // const m = Number(match[2]);
  202. // const d = Number(match[3]);
  203. // const changeDate = new Date(y, m - 1, d);
  204. // const now = new Date();
  205. // if (changeDate.getMonth() === 3 && now >= changeDate ) { // 4月7日开始夏令时
  206. // return true;
  207. // } else if (changeDate.getMonth() === 9 && now < changeDate) { // 10月7日开始冬令时
  208. // return true;
  209. // } else {
  210. // return false;
  211. // }
  212. // } catch (error) {
  213. // console.error('JS: 获取作息时间公告失败:', error);
  214. // window.shiguangBridge.showToast("无法获取作息时间公告,智能选择回退到预设时间。");
  215. // // 预设日期
  216. // const summerStart = new Date(new Date().getFullYear(), 3, 7); // 4月7日
  217. // const winterStart = new Date(new Date().getFullYear(), 9, 7); // 10月7日
  218. // const now = new Date();
  219. // if (now >= summerStart && now < winterStart) {
  220. // return true; // 夏令时
  221. // } else {
  222. // return false; // 冬令时
  223. // }
  224. // }
  225. // CORS 问题导致无法获取公告页,智能选择回退到预设时间。
  226. // 冬令时是十一假期结束后调整,取 10 月 7 日;夏令时公告历年均为 4 月 7 日起执行。
  227. // 参考教务处历年作息时间表公告:https://jwc.ujs.edu.cn/index/xl_zuo_xi_shi_jian.htm
  228. // 预设日期
  229. const summerStart = new Date(new Date().getFullYear(), 3, 7); // 4月7日
  230. const winterStart = new Date(new Date().getFullYear(), 9, 7); // 10月7日
  231. const now = new Date();
  232. if (now >= summerStart && now < winterStart) {
  233. return true; // 夏令时
  234. } else {
  235. return false; // 冬令时
  236. }
  237. }
  238. /**
  239. * 计算本次导入的作息何时失效。
  240. * 作息时间是导入时一次性写死的,不会自动跟随切令时变化,
  241. * 所以这里返回下一个「切到另一种令时」的日期,用于提示用户届时重新导入。
  242. * 夏令时 4 月 7 日起执行,冬令时十一假期后(10 月 7 日)起执行。
  243. */
  244. function getNextTimeSlotSwitchDate(isSummerTime) {
  245. const now = new Date();
  246. const year = now.getFullYear();
  247. const targetLabel = isSummerTime ? "冬令时" : "夏令时";
  248. const candidates = [
  249. { date: new Date(year, 3, 7), label: "夏令时" },
  250. { date: new Date(year, 9, 7), label: "冬令时" },
  251. { date: new Date(year + 1, 3, 7), label: "夏令时" },
  252. { date: new Date(year + 1, 9, 7), label: "冬令时" }
  253. ];
  254. const next = candidates.find((item) => item.date > now && item.label === targetLabel);
  255. return {
  256. label: next.label,
  257. text: `${next.date.getFullYear()}年${next.date.getMonth() + 1}月${next.date.getDate()}日`
  258. };
  259. }
  260. /**
  261. * 检查是否在登录页面。
  262. * 校内直连时地址是 http://jwxt.ujs.edu.cn/sso/jziotlogin,
  263. * 校外经 WebVPN 时地址是 https://webvpn.ujs.edu.cn/http/<hex>/sso/jziotlogin,
  264. * 因此按路径结尾判断,两种入口都能识别。
  265. */
  266. function isLoginPage() {
  267. return window.location.pathname.endsWith("/sso/jziotlogin");
  268. }
  269. function validateYearInput(input) {
  270. console.log("JS: validateYearInput 被调用,输入: " + input);
  271. if (/^[0-9]{4}$/.test(input)) {
  272. console.log("JS: validateYearInput 验证通过。");
  273. return false;
  274. } else {
  275. console.log("JS: validateYearInput 验证失败。");
  276. return "请输入四位数字的学年!";
  277. }
  278. }
  279. async function promptUserToStart() {
  280. console.log("JS: 流程开始:显示公告。");
  281. return await window.shiguangBridgePromise.showAlert(
  282. "教务系统课表导入",
  283. "导入前请确保您已在浏览器中成功登录教务系统",
  284. "好的,开始导入"
  285. );
  286. }
  287. async function getAcademicYear() {
  288. const currentYear = new Date().getFullYear().toString();
  289. const currentMonth = new Date().getMonth() + 1; // 月份从0开始,所以加1
  290. // 如果当前月份在8月或之后,默认学年是当前年份-下一年份,否则是上一年份-当前年份
  291. const defaultYear = currentMonth >= 8 ? currentYear : (Number(currentYear) - 1).toString();
  292. console.log("JS: 提示用户输入学年。");
  293. return await window.shiguangBridgePromise.showPrompt(
  294. "选择学年",
  295. "请输入要导入课程的起始学年(如2025-2026 应该填2025):",
  296. defaultYear,
  297. "validateYearInput"
  298. );
  299. }
  300. async function selectSemester() {
  301. const semesters = ["第一学期", "第二学期"];
  302. const currentMonth = new Date().getMonth() + 1; // 月份从0开始,所以加1
  303. const defaultSemesterIndex = currentMonth >= 8 ? 0 : 1; // 如果当前月份在8月或之后,默认选择第一学期,否则选择第二学期
  304. console.log("JS: 提示用户选择学期。");
  305. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  306. "选择学期",
  307. JSON.stringify(semesters),
  308. defaultSemesterIndex
  309. );
  310. return semesterIndex;
  311. }
  312. async function selectTimeSlot() {
  313. const timeSlots = ["智能选择" ,"夏令时", "冬令时"];
  314. console.log("JS: 提示用户选择作息类型。");
  315. const timeSlotIndex = await window.shiguangBridgePromise.showSingleSelection(
  316. "选择作息时间",
  317. JSON.stringify(timeSlots),
  318. 0
  319. );
  320. return timeSlotIndex;
  321. }
  322. async function reselectTimeSlot(selectedTimeSlot) {
  323. const options = ["对的对的,就是这个", "不对不对,应该是另外一个"];
  324. const dialogTitle = "当前智能选择结果为: \n " + (selectedTimeSlot ? "夏令时" : "冬令时") + "\n是否更改选择?";
  325. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  326. dialogTitle,
  327. JSON.stringify(options),
  328. 0
  329. );
  330. if (selectedIndex === null || selectedIndex === -1) {
  331. return false;
  332. }
  333. // 选中第 2 项(索引 1)表示“需要改成另外一个”。
  334. return selectedIndex === 1;
  335. }
  336. /**
  337. * 将选择索引转换为 API 所需的学期码。
  338. */
  339. function getSemesterCode(semesterIndex) {
  340. // semesterIndex 3 (第一学期), 12 (第二学期)
  341. return semesterIndex === 0 ? "3" : "12";
  342. }
  343. /**
  344. * 获取教务系统当前学期的起止日期。
  345. * 首页日历区块的标题形如 "2026-2027学年1学期(2026-08-31至2027-02-21)",
  346. * 其中起始日期就是第 1 周周一,正是 semesterStartDate 需要的值。
  347. * 注意:该接口忽略 xnm/xqm 参数,只返回当前学期,
  348. * 因此只有用户选择的学年学期与返回值一致时才能使用。
  349. */
  350. async function fetchCurrentSemesterRange() {
  351. const url = buildApiUrl("/xtgl/index_cxAreaFive.html?localeKey=zh_CN&gnmkdm=index");
  352. try {
  353. const response = await fetch(url, {
  354. "headers": {
  355. "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
  356. },
  357. "body": "",
  358. "method": "POST",
  359. "credentials": "include"
  360. });
  361. if (!response.ok) {
  362. throw new Error(`状态码 ${response.status}`);
  363. }
  364. const html = await response.text();
  365. const match = html.match(/(\d{4})-\d{4}学年(\d)学期\s*[((](\d{4}-\d{2}-\d{2})至(\d{4}-\d{2}-\d{2})[))]/);
  366. if (!match) {
  367. console.warn("JS: 未能从日历区块解析出学期起止日期。");
  368. return null;
  369. }
  370. const range = {
  371. academicYear: match[1],
  372. semesterIndex: Number(match[2]) - 1,
  373. startDate: match[3],
  374. endDate: match[4]
  375. };
  376. console.log("JS: 教务系统当前学期:", range);
  377. return range;
  378. } catch (error) {
  379. console.warn("JS: 获取学期起止日期失败:", error);
  380. return null;
  381. }
  382. }
  383. /**
  384. * 计算课表配置。
  385. *
  386. * 应用侧的 saveCourseConfig 是整体覆盖而非字段级合并:没有传入的字段会被写成模型默认值,
  387. * 其中 semesterStartDate 的默认值是 null,会把用户已经设置好的开学日期清空。
  388. * 所以拿不到真实开学日期时返回 null,由调用方跳过整个配置保存,宁可不写也不要写坏。
  389. *
  390. * defaultClassDuration / defaultBreakDuration 不显式传入,会被重置为应用默认的 45 / 10 分钟,
  391. * 与江大「45 分钟一节、课间 10 分钟」一致,因此没有副作用。
  392. */
  393. function buildCourseConfig(courses, semesterRange, firstDayOfWeek) {
  394. if (!semesterRange) {
  395. return null;
  396. }
  397. let maxWeek = 0;
  398. for (const course of courses) {
  399. for (const week of course.weeks) {
  400. if (week > maxWeek) {
  401. maxWeek = week;
  402. }
  403. }
  404. }
  405. return {
  406. semesterStartDate: semesterRange.startDate,
  407. // 只增不减:默认 20 周,课表里出现更大的周次时才扩展。
  408. semesterTotalWeeks: Math.max(maxWeek, 20),
  409. firstDayOfWeek: firstDayOfWeek
  410. };
  411. }
  412. /**
  413. * 请求和解析课程数据
  414. */
  415. async function fetchAndParseCourses(academicYear, semesterIndex) {
  416. window.shiguangBridge.showToast("正在请求课表数据...");
  417. const semesterCode = getSemesterCode(semesterIndex);
  418. // API URL 和请求体
  419. const xnmXqmBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  420. const url = buildApiUrl("/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151");
  421. console.log(`JS: 发送请求到 ${url}, body: ${xnmXqmBody}`);
  422. const requestOptions = {
  423. "headers": {
  424. "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
  425. },
  426. "body": xnmXqmBody,
  427. "method": "POST",
  428. "credentials": "include"
  429. };
  430. try {
  431. const response = await fetch(url, requestOptions);
  432. if (!response.ok) {
  433. throw new Error(`网络请求失败。状态码: ${response.status} (${response.statusText})`);
  434. }
  435. const jsonText = await response.text();
  436. let jsonData;
  437. try {
  438. jsonData = JSON.parse(jsonText);
  439. } catch (e) {
  440. console.error('JS: JSON 解析失败,可能是会话过期:', e);
  441. window.shiguangBridge.showToast("数据返回格式错误,可能是您未成功登录或会话已过期。");
  442. return null;
  443. }
  444. const courses = parseJsonData(jsonData);
  445. if (courses.length === 0) {
  446. window.shiguangBridge.showToast("未找到任何课程数据,请检查所选学年学期是否正确或本学期无课,或教务系统需要二次登录。");
  447. return null;
  448. }
  449. console.log(`JS: 课程数据解析成功,共找到 ${courses.length} 门课程。`);
  450. console.log("JS: 课程列表预览:", courses.slice(0, 5)); // 预览前5门课程
  451. // 集中实践课(军训、形势与政策等)没有星期和节次,无法排进周课表,单独取出用于提示。
  452. const practiceCourses = parsePracticeCourses(jsonData);
  453. if (practiceCourses.length > 0) {
  454. console.log(`JS: 检测到 ${practiceCourses.length} 门集中实践课,无法自动导入。`);
  455. }
  456. // qsxqj: 教务系统设置的一周起始星期几,缺失时按周一处理。
  457. const rawFirstDay = Number(jsonData.qsxqj);
  458. const firstDayOfWeek = (rawFirstDay >= 1 && rawFirstDay <= 7) ? rawFirstDay : 1;
  459. return {
  460. courses: courses,
  461. practiceCourses: practiceCourses,
  462. firstDayOfWeek: firstDayOfWeek
  463. };
  464. } catch (error) {
  465. window.shiguangBridge.showToast(`请求或解析失败: ${error.message}`);
  466. console.error('JS: Fetch/Parse Error:', error);
  467. return null;
  468. }
  469. }
  470. async function saveCourses(parsedCourses) {
  471. window.shiguangBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
  472. console.log(`JS: 尝试保存 ${parsedCourses.length} 门课程...`);
  473. try {
  474. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses, null, 2));
  475. console.log("JS: 课程保存成功!");
  476. return true;
  477. } catch (error) {
  478. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  479. console.error('JS: Save Courses Error:', error);
  480. return false;
  481. }
  482. }
  483. /**
  484. * 只在能拿到真实开学日期时写入课表配置。
  485. * 拿不到就完全不调用 saveCourseConfig —— 应用侧是整体覆盖,
  486. * 传入不含 semesterStartDate 的配置会把用户已设置的开学日期清空。
  487. */
  488. async function saveCourseConfigIfPossible(courses, academicYear, semesterIndex, firstDayOfWeek) {
  489. const semesterRange = await fetchCurrentSemesterRange();
  490. let usableRange = null;
  491. if (semesterRange) {
  492. const sameYear = semesterRange.academicYear === String(academicYear);
  493. const sameSemester = semesterRange.semesterIndex === semesterIndex;
  494. if (sameYear && sameSemester) {
  495. usableRange = semesterRange;
  496. } else {
  497. console.log(
  498. `JS: 所选学年学期(${academicYear}/第${semesterIndex + 1}学期)` +
  499. `不是教务系统当前学期(${semesterRange.academicYear}/第${semesterRange.semesterIndex + 1}学期),跳过开学日期写入。`
  500. );
  501. }
  502. }
  503. const config = buildCourseConfig(courses, usableRange, firstDayOfWeek);
  504. if (!config) {
  505. window.shiguangBridge.showToast("未取到本学期开学日期,已跳过课表配置,请在应用内手动设置开学日期。");
  506. console.log("JS: 无可用开学日期,跳过 saveCourseConfig 以保留用户现有配置。");
  507. return;
  508. }
  509. try {
  510. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  511. window.shiguangBridge.showToast(
  512. `课表配置更新成功!开学日期 ${config.semesterStartDate},总周数 ${config.semesterTotalWeeks} 周。`
  513. );
  514. } catch (error) {
  515. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  516. console.error('JS: Save Config Error:', error);
  517. }
  518. }
  519. // 上午作息时间
  520. // 北固及本部主楼、主A楼、生环楼、汽车能动楼、京江楼
  521. const AMorningTimeSlots = [
  522. { number: 1, startTime: "08:00", endTime: "08:45" },
  523. { number: 2, startTime: "08:55", endTime: "09:40" },
  524. { number: 3, startTime: "10:00", endTime: "10:45" },
  525. { number: 4, startTime: "10:55", endTime: "11:40" },
  526. ];
  527. // 三江楼、材料楼、机械楼、新校区各教学楼
  528. const BMorningTimeSlots = [
  529. { number: 1, startTime: "08:00", endTime: "08:45" },
  530. { number: 2, startTime: "08:55", endTime: "09:40" },
  531. { number: 3, startTime: "10:10", endTime: "10:55" },
  532. { number: 4, startTime: "11:05", endTime: "11:50" },
  533. ];
  534. // 三山楼、讲堂群、实践楼
  535. const CMorningTimeSlots = [
  536. { number: 1, startTime: "08:00", endTime: "08:45" },
  537. { number: 2, startTime: "08:55", endTime: "09:40" },
  538. { number: 3, startTime: "10:20", endTime: "11:05" },
  539. { number: 4, startTime: "11:15", endTime: "12:00" },
  540. ];
  541. // 夏令时
  542. // 下午作息时间
  543. // 北固
  544. const DSummerAfternoonTimeSlots = [
  545. { number: 5, startTime: "14:00", endTime: "14:45" },
  546. { number: 6, startTime: "14:55", endTime: "15:40" },
  547. { number: 7, startTime: "15:50", endTime: "16:35" },
  548. { number: 8, startTime: "16:45", endTime: "17:30" },
  549. ];
  550. // 本部
  551. const ESummerAfternoonTimeSlots = [
  552. { number: 5, startTime: "14:00", endTime: "14:45" },
  553. { number: 6, startTime: "14:55", endTime: "15:40" },
  554. { number: 7, startTime: "16:00", endTime: "16:45" },
  555. { number: 8, startTime: "16:55", endTime: "17:40" },
  556. ];
  557. // 晚上作息时间
  558. const SummerEveningTimeSlots = [
  559. { number: 9, startTime: "19:00", endTime: "19:45" },
  560. { number: 10, startTime: "19:55", endTime: "20:40" },
  561. { number: 11, startTime: "20:50", endTime: "21:35" },
  562. ];
  563. // 冬令时
  564. // 下午作息时间
  565. // 北固
  566. const DWinterAfternoonTimeSlots = [
  567. { number: 5, startTime: "13:30", endTime: "14:15" },
  568. { number: 6, startTime: "14:25", endTime: "15:10" },
  569. { number: 7, startTime: "15:20", endTime: "16:05" },
  570. { number: 8, startTime: "16:15", endTime: "17:00" },
  571. ];
  572. // 本部
  573. const EWinterAfternoonTimeSlots = [
  574. { number: 5, startTime: "13:30", endTime: "14:15" },
  575. { number: 6, startTime: "14:25", endTime: "15:10" },
  576. { number: 7, startTime: "15:30", endTime: "16:15" },
  577. { number: 8, startTime: "16:25", endTime: "17:10" },
  578. ];
  579. // 晚上作息时间
  580. const WinterEveningTimeSlots = [
  581. { number: 9, startTime: "18:30", endTime: "19:15" },
  582. { number: 10, startTime: "19:25", endTime: "20:10" },
  583. { number: 11, startTime: "20:20", endTime: "21:05" },
  584. ];
  585. // 全局默认作息
  586. // 夏令时
  587. const SummerTimeSlots = [...AMorningTimeSlots, ...ESummerAfternoonTimeSlots, ...SummerEveningTimeSlots];
  588. // 冬令时
  589. const WinterTimeSlots = [...AMorningTimeSlots, ...EWinterAfternoonTimeSlots, ...WinterEveningTimeSlots];
  590. function getCampusTypeFromPosition(position) {
  591. const normalized = String(position || "").replace(/\s+/g, " ").trim();
  592. if (!normalized) return null;
  593. // const firstPart = normalized.split(" ")[0] || "";
  594. // if (firstPart.includes("北固")) return "D";
  595. // if (firstPart.includes("本部")) return "E";
  596. // // 兜底:有些数据可能不按空格分段,补充全文匹配。
  597. // if (normalized.includes("北固")) return "D";
  598. // if (normalized.includes("本部")) return "E";
  599. // api好像不返回前缀了,我也不确定北固是怎么样的格式,只能这么写了()
  600. const firstPart = normalized.split(" ")[0] || "";
  601. if (firstPart.includes("北固") || normalized.includes("北固")) return "D";
  602. return "E"; // 其他默认本部
  603. // return null;
  604. }
  605. function getMorningTypeFromPosition(position) {
  606. const text = String(position || "").trim();
  607. // 教务系统返回的是「京江2号楼2101」「京江3号楼3407」这类名称,没有「京江楼」这个写法,
  608. // 所以这里匹配「京江」而不是「京江楼」。
  609. if (text.includes("主A楼") || text.includes("京江")) return "A";
  610. if (text.includes("三江楼")) return "B";
  611. if (text.includes("三山楼") || text.includes("讲堂群")) return "C";
  612. return null;
  613. }
  614. function buildCourseTimeSlotsByPosition(position, isSummerTime) {
  615. const morningType = getMorningTypeFromPosition(position);
  616. const campusType = getCampusTypeFromPosition(position);
  617. // 仅对指定楼宇做自定义。
  618. if (!morningType || !campusType) {
  619. return null;
  620. }
  621. const morningTimeSlots = morningType === "A"
  622. ? AMorningTimeSlots
  623. : morningType === "B"
  624. ? BMorningTimeSlots
  625. : CMorningTimeSlots;
  626. const afternoonTimeSlots = isSummerTime
  627. ? (campusType === "D" ? DSummerAfternoonTimeSlots : ESummerAfternoonTimeSlots)
  628. : (campusType === "D" ? DWinterAfternoonTimeSlots : EWinterAfternoonTimeSlots);
  629. const eveningTimeSlots = isSummerTime ? SummerEveningTimeSlots : WinterEveningTimeSlots;
  630. return [...morningTimeSlots, ...afternoonTimeSlots, ...eveningTimeSlots];
  631. }
  632. function applyCustomTimeToCourses(courses, isSummerTime) {
  633. let customizedCount = 0;
  634. let skippedCount = 0;
  635. const updatedCourses = courses.map((course) => {
  636. const courseTimeSlots = buildCourseTimeSlotsByPosition(course.position, isSummerTime);
  637. if (!courseTimeSlots) {
  638. skippedCount += 1;
  639. return course;
  640. }
  641. const slotMap = new Map(courseTimeSlots.map((slot) => [slot.number, slot]));
  642. const startSlot = slotMap.get(course.startSection);
  643. const endSlot = slotMap.get(course.endSection);
  644. if (!startSlot || !endSlot) {
  645. skippedCount += 1;
  646. console.warn(`JS: 课程 ${course.name} 的节次(${course.startSection}-${course.endSection})未命中自定义时间映射,回退为普通节次。`);
  647. return course;
  648. }
  649. customizedCount += 1;
  650. return {
  651. ...course,
  652. isCustomTime: true,
  653. customStartTime: startSlot.startTime,
  654. customEndTime: endSlot.endTime,
  655. };
  656. });
  657. console.log(`JS: 自定义时间处理完成,命中 ${customizedCount} 门,跳过 ${skippedCount} 门。`);
  658. return updatedCourses;
  659. }
  660. async function importPresetTimeSlots(timeSlots) {
  661. console.log(`JS: 准备导入 ${timeSlots.length} 个预设时间段。`);
  662. if (timeSlots.length > 0) {
  663. window.shiguangBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
  664. try {
  665. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  666. window.shiguangBridge.showToast("预设时间段导入成功!");
  667. console.log("JS: 预设时间段导入成功。");
  668. } catch (error) {
  669. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  670. console.error('JS: Save Time Slots Error:', error);
  671. }
  672. } else {
  673. window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
  674. console.warn("JS: 警告:传入时间段为空,未导入时间段信息。");
  675. }
  676. }
  677. async function runImportFlow() {
  678. if (isLoginPage()) {
  679. window.shiguangBridge.showToast("导入失败:请先登录教务系统!");
  680. console.log("JS: 检测到当前在登录页面,终止导入。");
  681. return;
  682. }
  683. const alertConfirmed = await promptUserToStart();
  684. if (!alertConfirmed) {
  685. window.shiguangBridge.showToast("用户取消了导入。");
  686. console.log("JS: 用户取消了导入流程。");
  687. return;
  688. }
  689. // // 与后续流程并发执行,提前缓存智能选择结果。
  690. // const smartTimeSlotPromise = whetherSummerTimeSlot();
  691. // console.log("JS: 智能作息判定已并发启动。");
  692. const academicYear = await getAcademicYear();
  693. if (academicYear === null) {
  694. window.shiguangBridge.showToast("导入已取消。");
  695. console.log("JS: 获取学年失败/取消,流程终止。");
  696. return;
  697. }
  698. console.log(`JS: 已选择学年: ${academicYear}`);
  699. const semesterIndex = await selectSemester();
  700. if (semesterIndex === null || semesterIndex === -1) {
  701. window.shiguangBridge.showToast("导入已取消。");
  702. console.log("JS: 选择学期失败/取消,流程终止。");
  703. return;
  704. }
  705. console.log(`JS: 已选择学期索引: ${semesterIndex}`);
  706. const timeSlotIndex = await selectTimeSlot();
  707. if (timeSlotIndex === null || timeSlotIndex === -1) {
  708. window.shiguangBridge.showToast("导入已取消。");
  709. console.log("JS: 选择作息类型失败/取消,流程终止。");
  710. return;
  711. }
  712. let isSummerTime = false;
  713. if (timeSlotIndex === 1) {
  714. isSummerTime = true;
  715. } else if (timeSlotIndex === 2) {
  716. isSummerTime = false;
  717. } else {
  718. // try {
  719. // isSummerTime = await smartTimeSlotPromise;
  720. // } catch (error) {
  721. // console.error("JS: 智能作息判定异常,回退重新判定:", error);
  722. // isSummerTime = await whetherSummerTimeSlot();
  723. // }
  724. isSummerTime = await whetherSummerTimeSlot();
  725. const shouldReselect = await reselectTimeSlot(isSummerTime);
  726. if (shouldReselect) {
  727. isSummerTime = !isSummerTime;
  728. }
  729. }
  730. console.log(`JS: 作息类型: ${isSummerTime ? "夏令时" : "冬令时"}`);
  731. const result = await fetchAndParseCourses(academicYear, semesterIndex);
  732. if (result === null) {
  733. console.log("JS: 课程获取或解析失败,流程终止。");
  734. return;
  735. }
  736. const { courses, practiceCourses, firstDayOfWeek } = result;
  737. const coursesWithCustomTime = applyCustomTimeToCourses(courses, isSummerTime);
  738. // 作息时间在导入时一次性写入,不会自动跟随切令时变化,需要明确告知用户。
  739. // 同时说明只有部分教学楼收录了独立作息,其余楼栋使用默认作息时间。
  740. const nextSwitch = getNextTimeSlotSwitchDate(isSummerTime);
  741. await window.shiguangBridgePromise.showAlert(
  742. "作息时间提示",
  743. `本次按${isSummerTime ? "夏令时" : "冬令时"}导入。作息时间在导入时写入,不会自动跟随学校切换令时。\n` +
  744. `${nextSwitch.text}起学校切换为${nextSwitch.label},届时请重新导入课表,或在应用内手动修改时间段。\n\n` +
  745. "脚本已根据课程所在位置匹配作息时间,部分课程可能与预设时间不符。\n" +
  746. "请在课表页面核对课程时间,如有错误请手动修改课程所在位置或节次信息。\n\n" +
  747. "已收录独立作息的楼栋:主A楼、京江各号楼、三江楼、三山楼、讲堂群。\n" +
  748. "其余楼栋(各学院楼、各实验室、运动场、未排地点等)使用默认作息时间。\n\n" +
  749. "欢迎其他楼栋的同学提供课程时间信息以完善脚本!",
  750. "我知道了"
  751. );
  752. if (practiceCourses.length > 0) {
  753. const practiceList = practiceCourses
  754. .map((item) => {
  755. const teacher = item.teacher ? `(${item.teacher})` : "";
  756. const weekDesc = item.weekDesc ? ` ${item.weekDesc}` : "";
  757. return `· ${item.name}${teacher}${weekDesc}`;
  758. })
  759. .join("\n");
  760. console.log("JS: 集中实践课列表:", practiceCourses);
  761. await window.shiguangBridgePromise.showAlert(
  762. "集中实践课需手动添加",
  763. `本学期有 ${practiceCourses.length} 门集中实践课,教务系统未给出星期和节次,无法自动导入:\n\n` +
  764. practiceList +
  765. "\n\n请按实际安排在应用内手动添加。",
  766. "我知道了"
  767. );
  768. }
  769. const saveResult = await saveCourses(coursesWithCustomTime);
  770. if (!saveResult) {
  771. console.log("JS: 课程保存失败,流程终止。");
  772. return;
  773. }
  774. await saveCourseConfigIfPossible(coursesWithCustomTime, academicYear, semesterIndex, firstDayOfWeek);
  775. await importPresetTimeSlots(isSummerTime ? SummerTimeSlots : WinterTimeSlots);
  776. window.shiguangBridge.showToast(`课程导入成功,共导入 ${coursesWithCustomTime.length} 门课程!`);
  777. console.log("JS: 整个导入流程执行完毕并成功。");
  778. window.shiguangBridge.notifyTaskCompletion();
  779. }
  780. runImportFlow();