gxmu.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /**
  2. * 广西医科大学智慧教务系统课表导入适配脚本
  3. * 通过 getCalendarWeekDatas 接口获取课表数据(POST,返回 JSON、全学期)
  4. * 课程节次直接由接口字段 ps(起始节次) / pe(结束节次) 提供
  5. */
  6. // 广西医科大学作息时间表(第1-12节)
  7. const GXMU_TIME_SLOTS = [
  8. { number: 1, startTime: "08:20", endTime: "09:00" },
  9. { number: 2, startTime: "09:05", endTime: "09:45" },
  10. { number: 3, startTime: "10:05", endTime: "10:45" },
  11. { number: 4, startTime: "10:50", endTime: "11:30" },
  12. { number: 5, startTime: "11:35", endTime: "12:15" },
  13. { number: 6, startTime: "14:30", endTime: "15:10" },
  14. { number: 7, startTime: "15:15", endTime: "15:55" },
  15. { number: 8, startTime: "16:15", endTime: "16:55" },
  16. { number: 9, startTime: "17:00", endTime: "17:40" },
  17. { number: 10, startTime: "19:00", endTime: "19:40" },
  18. { number: 11, startTime: "19:45", endTime: "20:25" },
  19. { number: 12, startTime: "20:30", endTime: "21:10" }
  20. ];
  21. function parseWeeks(weekStr) {
  22. // 兼容逗号分段的周次;数字按数值排序去重
  23. const weeks = [];
  24. weekStr.split(',').forEach(part => {
  25. part = part.trim();
  26. const n = Number(part);
  27. if (!isNaN(n) && n >= 1) weeks.push(n);
  28. });
  29. return [...new Set(weeks)].sort((a, b) => a - b);
  30. }
  31. /**
  32. * 解析接口返回的单条课程记录,映射为课表所需结构
  33. */
  34. function mapCourseRecord(record) {
  35. const weeks = parseWeeks(record.zc || "");
  36. if (weeks.length === 0) return null;
  37. const day = parseInt(record.xq, 10);
  38. const startSection = parseInt(record.ps, 10);
  39. const endSection = parseInt(record.pe, 10);
  40. if (!day || day < 1 || day > 7) return null;
  41. if (!startSection || isNaN(startSection)) return null;
  42. return {
  43. name: record.kcmc || "",
  44. teacher: record.teaxms || "未知教师",
  45. position: record.jxcdmc || "未知地点",
  46. day: day,
  47. startSection: startSection,
  48. endSection: isNaN(endSection) ? startSection : endSection,
  49. weeks: weeks
  50. };
  51. }
  52. /**
  53. * 从接口返回的 JSON 数据中提取并映射全部课程
  54. */
  55. function transformSchedule(jsonData) {
  56. console.log("JS: transformSchedule 正在解析课时数据...");
  57. const data = jsonData && Array.isArray(jsonData.data) ? jsonData.data : [];
  58. console.log(`JS: 接口返回 ${data.length} 条课程记录`);
  59. const rawCourses = data
  60. .map(mapCourseRecord)
  61. .filter(Boolean);
  62. console.log(`JS: 解析出 ${rawCourses.length} 条课程记录`);
  63. // 同一门课会因周次分段生成多个课时记录,按组合键去重
  64. const seen = new Set();
  65. const courses = [];
  66. for (const c of rawCourses) {
  67. const key = `${c.name}|${c.day}|${c.startSection}|${c.endSection}|${c.weeks.join(',')}|${c.teacher}|${c.position}`;
  68. if (seen.has(key)) continue;
  69. seen.add(key);
  70. courses.push(c);
  71. }
  72. console.log(`JS: 去重后剩 ${courses.length} 门课程`);
  73. return courses;
  74. }
  75. function isLoginPage() {
  76. const url = window.location.href;
  77. return url.includes('login') || url.includes('lyuapServer');
  78. }
  79. function validateYearInput(input) {
  80. if (/^[0-9]{4}$/.test(input)) return false;
  81. return "请输入四位数字的学年!";
  82. }
  83. async function promptUserToStart() {
  84. console.log("JS: 流程开始:显示公告。");
  85. return await window.shiguangBridgePromise.showAlert(
  86. "教务系统课表导入",
  87. "导入前请确保您已在浏览器中成功登录教务系统",
  88. "好的,开始导入"
  89. );
  90. }
  91. async function getAcademicYear() {
  92. const currentYear = new Date().getFullYear().toString();
  93. return await window.shiguangBridgePromise.showPrompt(
  94. "选择学年",
  95. "请输入要导入课程的起始学年(例如 2025-2026 应输入2025,将匹配 202501 学期):",
  96. currentYear,
  97. "validateYearInput"
  98. );
  99. }
  100. async function selectSemester() {
  101. const semesters = ["第一学期 (0)", "第二学期 (1)"];
  102. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  103. "选择学期",
  104. JSON.stringify(semesters),
  105. 0
  106. );
  107. return semesterIndex;
  108. }
  109. async function fetchAndParseCourses(academicYear, semesterIndex) {
  110. window.shiguangBridge.showToast("正在请求课表数据...");
  111. const semesterCode = semesterIndex === 0 ? "01" : "02";
  112. const xnxqdm = `${academicYear}${semesterCode}`;
  113. // zc 传空表示全部周;d1/d2 为参考周起止日期,zc 为空时服务端返回全学期
  114. const today = new Date();
  115. const startOfWeek = new Date(today);
  116. startOfWeek.setDate(today.getDate() - today.getDay() + 1);
  117. const endOfWeek = new Date(startOfWeek);
  118. endOfWeek.setDate(startOfWeek.getDate() + 6);
  119. const pad = n => String(n).padStart(2, '0');
  120. const fmtDate = d => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} 00:00:00`;
  121. const body = `xnxqdm=${xnxqdm}&zc=&d1=${encodeURIComponent(fmtDate(startOfWeek))}&d2=${encodeURIComponent(fmtDate(endOfWeek))}`;
  122. const url = "https://jwxt.gxmu.edu.cn/new/student/xsgrkb/getCalendarWeekDatas";
  123. console.log(`JS: 请求课表接口: ${url}`);
  124. console.log(`JS: 请求体: ${body}`);
  125. try {
  126. const response = await fetch(url, {
  127. method: "POST",
  128. headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" },
  129. credentials: "include",
  130. body: body
  131. });
  132. if (!response.ok) {
  133. throw new Error(`网络请求失败。状态码: ${response.status}`);
  134. }
  135. const jsonData = await response.json();
  136. const courses = transformSchedule(jsonData);
  137. if (courses.length === 0) {
  138. window.shiguangBridge.showToast("未找到任何课程数据,请检查所选学年学期是否正确。");
  139. return null;
  140. }
  141. console.log(`JS: 课程数据解析成功,共找到 ${courses.length} 门课程。`);
  142. return { courses };
  143. } catch (error) {
  144. window.shiguangBridge.showToast(`请求或解析失败: ${error.message}`);
  145. console.error('JS: Fetch/Parse Error:', error);
  146. return null;
  147. }
  148. }
  149. async function saveCourses(parsedCourses) {
  150. window.shiguangBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
  151. try {
  152. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses, null, 2));
  153. return true;
  154. } catch (error) {
  155. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  156. console.error('JS: Save Courses Error:', error);
  157. return false;
  158. }
  159. }
  160. async function saveTimeSlots(timeSlots) {
  161. if (!timeSlots || timeSlots.length === 0) return;
  162. try {
  163. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  164. console.log("JS: 作息时间保存成功");
  165. } catch (error) {
  166. console.error('JS: Save TimeSlots Error:', error);
  167. }
  168. }
  169. async function runImportFlow() {
  170. if (isLoginPage()) {
  171. window.shiguangBridge.showToast("导入失败:请先登录教务系统!");
  172. return;
  173. }
  174. const alertConfirmed = await promptUserToStart();
  175. if (!alertConfirmed) {
  176. window.shiguangBridge.showToast("用户取消了导入。");
  177. return;
  178. }
  179. const academicYear = await getAcademicYear();
  180. if (academicYear === null) {
  181. window.shiguangBridge.showToast("导入已取消。");
  182. return;
  183. }
  184. const semesterIndex = await selectSemester();
  185. if (semesterIndex === null || semesterIndex === -1) {
  186. window.shiguangBridge.showToast("导入已取消。");
  187. return;
  188. }
  189. const result = await fetchAndParseCourses(academicYear, semesterIndex);
  190. if (result === null) {
  191. return;
  192. }
  193. const { courses } = result;
  194. const saveResult = await saveCourses(courses);
  195. if (!saveResult) {
  196. return;
  197. }
  198. await saveTimeSlots(GXMU_TIME_SLOTS);
  199. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  200. window.shiguangBridge.notifyTaskCompletion();
  201. }
  202. runImportFlow();