cmc_01.js 13 KB

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