cmc_01.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. // 成都医学院教务(乘方教务)适配器
  2. // 流程:选一次学期(课表与考试共用)→ 导入课表 → 询问是否导入考试 → 合并保存
  3. // 接口:
  4. // GET /new/student/xsgrkb/week.page 课表页(学期下拉 + 作息表)
  5. // POST /new/student/xsgrkb/getCalendarWeekDatas 整学期课程数据
  6. // POST /new/student/xsksrw/paginateXsksrw 学生考试任务
  7. // 周次字符串
  8. function parseWeeks(weekStr) {
  9. if (!weekStr) return [];
  10. const weeks = weekStr.split(",").map(w => parseInt(w.trim(), 10)).filter(w => !isNaN(w) && w > 0);
  11. return [...new Set(weeks)].sort((a, b) => a - b);
  12. }
  13. // 解析按周场地字符串
  14. function parseVenueWeeks(jxcdmc2) {
  15. const venueMap = new Map();
  16. let lastRoom = null;
  17. String(jxcdmc2 || "").split(",").forEach(part => {
  18. const match = part.trim().match(/^(.*?)-(\d+)$/);
  19. if (!match) return;
  20. const room = match[1].trim();
  21. const week = parseInt(match[2], 10);
  22. if (room) lastRoom = room;
  23. if (!lastRoom || isNaN(week)) return;
  24. if (!venueMap.has(lastRoom)) venueMap.set(lastRoom, []);
  25. venueMap.get(lastRoom).push(week);
  26. });
  27. return venueMap;
  28. }
  29. // 课程地点
  30. function resolvePosition(item) {
  31. const primary = String(item.jxcdmc || "").trim();
  32. if (primary) return primary;
  33. if (String(item.bapjxcd || "") === "1") return "不用场地";
  34. return "待定";
  35. }
  36. function cleanTeacherName(raw) {
  37. return String(raw || "").replace(/\[[^\]]*\]/g, "").trim();
  38. }
  39. // 课表接口数据
  40. function parseCourseList(apiJson, slotMap) {
  41. if (!apiJson) throw new Error("课表接口无响应");
  42. if (apiJson.code !== 0) {
  43. const message = String(apiJson.message || "").trim();
  44. throw new Error(message || `课表接口返回错误(code=${apiJson.code})`);
  45. }
  46. if (!Array.isArray(apiJson.data)) throw new Error("课表接口返回格式不正确");
  47. const courseMap = new Map();
  48. apiJson.data.forEach(item => {
  49. const day = parseInt(item.xq, 10);
  50. const startSection = parseInt(item.ps, 10);
  51. const endSection = parseInt(item.pe, 10);
  52. const allWeeks = parseWeeks(item.zc);
  53. if (!item.kcmc || !allWeeks.length || isNaN(day) || isNaN(startSection) || isNaN(endSection) ||
  54. day < 1 || day > 7 || startSection > endSection) return;
  55. const teacher = cleanTeacherName(item.teaxms || item.pkr) || "未知";
  56. const venues = parseVenueWeeks(item.jxcdmc2);
  57. const venueEntries = venues.size > 0
  58. ? Array.from(venues.entries(), ([position, weeks]) => ({ position, weeks: [...new Set(weeks)].sort((a, b) => a - b) }))
  59. : [{ position: resolvePosition(item), weeks: allWeeks }];
  60. venueEntries.forEach(({ position, weeks }) => {
  61. const course = { name: item.kcmc.trim(), teacher, position, day, startSection, endSection, weeks };
  62. const actualStart = String(item.qssj || "").slice(0, 5);
  63. const actualEnd = String(item.jssj || "").slice(0, 5);
  64. const expectedStart = slotMap[startSection] && slotMap[startSection].start;
  65. const expectedEnd = slotMap[endSection] && slotMap[endSection].end;
  66. if (actualStart && actualEnd && (actualStart !== expectedStart || actualEnd !== expectedEnd)) {
  67. course.isCustomTime = true;
  68. course.customStartTime = actualStart;
  69. course.customEndTime = actualEnd;
  70. }
  71. const key = [course.name, teacher, position, day,
  72. course.isCustomTime ? actualStart + actualEnd : `${startSection}-${endSection}`, weeks.join(",")].join("__");
  73. if (!courseMap.has(key)) courseMap.set(key, course);
  74. });
  75. });
  76. return Array.from(courseMap.values()).sort((a, b) =>
  77. a.day - b.day || a.startSection - b.startSection || a.endSection - b.endSection || a.name.localeCompare(b.name)
  78. );
  79. }
  80. // 考试安排数据
  81. function parseExamList(rows, slots) {
  82. const exams = [];
  83. rows.forEach(item => {
  84. const day = parseInt(item.xq, 10);
  85. const week = parseInt(item.zc, 10);
  86. const [startTime, endTime] = String(item.kssj || "").split("--").map(part => part.trim().slice(0, 5));
  87. const validTime = startTime && endTime && /^\d{2}:\d{2}$/.test(startTime) && /^\d{2}:\d{2}$/.test(endTime);
  88. if (!item.kcmc || isNaN(day) || day < 1 || day > 7 || isNaN(week) || week < 1 || !validTime) return;
  89. const examType = String(item.kslbmc || "").trim().replace(/考试$/, "");
  90. const exam = {
  91. name: `${item.kcmc.trim()}${examType ? `(${examType})` : ""}`,
  92. teacher: "",
  93. position: String(item.kscdmc || "").trim() || "待定",
  94. day,
  95. weeks: [week]
  96. };
  97. const matched = slots && slots.find(s => s.startTime === startTime && s.endTime === endTime);
  98. if (matched) {
  99. exam.startSection = exam.endSection = matched.number;
  100. } else {
  101. exam.isCustomTime = true;
  102. exam.customStartTime = startTime;
  103. exam.customEndTime = endTime;
  104. }
  105. exams.push(exam);
  106. });
  107. return exams;
  108. }
  109. // 从 week.page 源码提取作息表
  110. function parseBusinessHoursFromHtml(htmlText) {
  111. const match = htmlText.match(/var\s+businessHours\s*=\s*\$\.parseJSON\('(\[.*?\])'\);/);
  112. const slots = [];
  113. const map = {};
  114. if (match) {
  115. JSON.parse(match[1]).forEach(item => {
  116. const number = parseInt(item.jcdm, 10);
  117. const startTime = String(item.qssj || "").slice(0, 5);
  118. const endTime = String(item.jssj || "").slice(0, 5);
  119. if (isNaN(number) || !startTime || !endTime) return;
  120. slots.push({ number, startTime, endTime });
  121. map[number] = { start: startTime, end: endTime };
  122. });
  123. slots.sort((a, b) => a.number - b.number);
  124. }
  125. return { slots, map };
  126. }
  127. // 插入午间段期中考试时间
  128. function withLunchSlot(slots) {
  129. return slots
  130. .map(s => s.number >= 6 ? { ...s, number: s.number + 1 } : s)
  131. .concat([{ number: 6, startTime: "12:15", endTime: "14:15" }])
  132. .sort((a, b) => a.number - b.number);
  133. }
  134. // 读取页面中的学期下拉框
  135. function extractSemesterOptions(doc) {
  136. const selectElem = doc.getElementById("xnxqdm");
  137. if (!selectElem) return null;
  138. const semesters = [];
  139. const semesterValues = [];
  140. let defaultIndex = 0;
  141. Array.from(selectElem.querySelectorAll("option")).forEach(option => {
  142. if (!option.value) return;
  143. semesters.push(option.innerText.trim());
  144. semesterValues.push(option.value);
  145. if (option.selected || option.hasAttribute("selected")) defaultIndex = semesters.length - 1;
  146. });
  147. if (semesters.length === 0) return null;
  148. const start = Math.max(0, defaultIndex - 1);
  149. const end = Math.min(semesters.length, defaultIndex + 10);
  150. return {
  151. semesters: semesters.slice(start, end),
  152. semesterValues: semesterValues.slice(start, end),
  153. defaultIndex: defaultIndex - start
  154. };
  155. }
  156. // 导入前提示用户先登录教务系统
  157. async function promptUserToStart() {
  158. return await window.shiguangBridgePromise.showAlert(
  159. "成都医学院教务导入",
  160. "请先确保已登录教务系统,再继续导入。",
  161. "我已登录"
  162. );
  163. }
  164. // 从页面已有学期中选择目标学期
  165. async function selectSemester(semesterOptions) {
  166. const selectedIndex = await window.shiguangBridgePromise.showSingleSelection(
  167. "选择学期",
  168. JSON.stringify(semesterOptions.semesters),
  169. semesterOptions.defaultIndex
  170. );
  171. if (selectedIndex === null || selectedIndex < 0) return null;
  172. return {
  173. label: semesterOptions.semesters[selectedIndex],
  174. value: semesterOptions.semesterValues[selectedIndex]
  175. };
  176. }
  177. // 询问是否同时导入考试
  178. async function askImportExams() {
  179. const bridge = window.shiguangBridgePromise;
  180. if (!bridge || typeof bridge.showAlert !== "function") return true;
  181. return await bridge.showAlert(
  182. "导入考试安排",
  183. "是否同时导入本学期的考试安排?\n(期中/期末/补考将显示在课表对应日期)",
  184. "确定导入"
  185. );
  186. }
  187. // 获取课表页 HTML(含学期列表与作息表)
  188. async function fetchSchedulePage() {
  189. const response = await fetch("/new/student/xsgrkb/week.page", { method: "GET", credentials: "include" });
  190. if (!response.ok) throw new Error(`无法打开课表页面(HTTP ${response.status})`);
  191. return response.text();
  192. }
  193. // 乘方统一表单 POST(课表/考试共用),附带 JSON 请求头与会话
  194. async function postForm(url, formData) {
  195. const response = await fetch(url, {
  196. method: "POST",
  197. headers: {
  198. "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
  199. "X-Requested-With": "XMLHttpRequest"
  200. },
  201. credentials: "include",
  202. body: formData.toString()
  203. });
  204. if (!response.ok) throw new Error(`请求失败(HTTP ${response.status})`);
  205. return response;
  206. }
  207. // 请求指定学期的课程数据
  208. async function fetchCourseData(xnxqdm) {
  209. const year = parseInt(xnxqdm.slice(0, 4), 10);
  210. const formData = new URLSearchParams();
  211. formData.append("xnxqdm", xnxqdm);
  212. formData.append("zc", "");
  213. formData.append("d1", `${year}-08-01 00:00:00`);
  214. formData.append("d2", `${year + 1}-08-31 23:59:59`);
  215. return (await postForm("/new/student/xsgrkb/getCalendarWeekDatas", formData)).json();
  216. }
  217. // 分页拉取指定学期的全部考试任务
  218. async function fetchExamData(xnxqdm) {
  219. const allRows = [];
  220. const pageSize = 100;
  221. let page = 1;
  222. for (;;) {
  223. const formData = new URLSearchParams();
  224. formData.append("xnxqdm", xnxqdm);
  225. formData.append("page", String(page));
  226. formData.append("rows", String(pageSize));
  227. formData.append("sort", "zc,xq,jcdm2");
  228. formData.append("order", "asc");
  229. const json = await (await postForm("/new/student/xsksrw/paginateXsksrw", formData)).json();
  230. const rows = Array.isArray(json.rows) ? json.rows : [];
  231. allRows.push(...rows);
  232. const total = parseInt(json.total, 10);
  233. if (!total || allRows.length >= total || rows.length === 0) break;
  234. page += 1;
  235. }
  236. return allRows;
  237. }
  238. async function saveCourses(courses) {
  239. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
  240. }
  241. async function saveTimeSlots(timeSlots) {
  242. if (timeSlots.length === 0) return;
  243. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  244. }
  245. // 编排导入流程:提示 → 选学期 → 请求课表与考试 → 合并保存课程与作息时间
  246. async function runImportFlow() {
  247. try {
  248. const confirmed = await promptUserToStart();
  249. if (!confirmed) { window.shiguangBridge.showToast("导入已取消"); return; }
  250. const pageHtml = await fetchSchedulePage();
  251. const semesterOptions = extractSemesterOptions(new DOMParser().parseFromString(pageHtml, "text/html"));
  252. if (!semesterOptions) throw new Error("未找到学期列表,请先登录教务系统");
  253. const semester = await selectSemester(semesterOptions);
  254. if (!semester) { window.shiguangBridge.showToast("导入已取消"); return; }
  255. const { slots, map: slotMap } = parseBusinessHoursFromHtml(pageHtml);
  256. window.shiguangBridge.showToast(`正在获取 ${semester.label} 的课表...`);
  257. const courses = parseCourseList(await fetchCourseData(semester.value), slotMap);
  258. if (courses.length === 0) {
  259. await window.shiguangBridgePromise.showAlert(
  260. "提示",
  261. "该学期没有获取到课程数据,请检查登录状态和所选学期。",
  262. "确定"
  263. );
  264. return;
  265. }
  266. const exams = [];
  267. let timeSlots = slots;
  268. if (await askImportExams()) {
  269. timeSlots = withLunchSlot(slots);
  270. courses.forEach(c => {
  271. if (c.startSection >= 6) c.startSection += 1;
  272. if (c.endSection >= 6) c.endSection += 1;
  273. });
  274. window.shiguangBridge.showToast("正在获取考试安排...");
  275. exams.push(...parseExamList(await fetchExamData(semester.value), timeSlots));
  276. if (exams.length === 0) window.shiguangBridge.showToast("该学期暂时没有考试安排");
  277. }
  278. await saveCourses([...courses, ...exams]);
  279. try {
  280. await saveTimeSlots(timeSlots);
  281. } catch (error) {
  282. window.shiguangBridge.showToast(`课程已导入,作息时间导入失败:${error.message}`);
  283. }
  284. const examTip = exams.length > 0 ? `成功导入 ${exams.length} 门考试` : "导入完成";
  285. window.shiguangBridge.showToast(examTip);
  286. window.shiguangBridge.notifyTaskCompletion();
  287. } catch (error) {
  288. await window.shiguangBridgePromise.showAlert(
  289. "导入失败",
  290. error.message || String(error),
  291. "确定"
  292. );
  293. }
  294. }
  295. runImportFlow();