gzmtu.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. // 广州航海学院(gzmtu.edu.cn) 拾光课程表适配脚本
  2. /**
  3. * 节次与周次合并去重函数
  4. */
  5. function mergeAndDistinctCourses(courses) {
  6. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  7. const list = courses.map(c => ({
  8. ...c,
  9. name: c.name || '',
  10. teacher: c.teacher || '',
  11. position: c.position || '',
  12. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  13. }));
  14. list.sort((a, b) => {
  15. return a.name.localeCompare(b.name) ||
  16. a.teacher.localeCompare(b.teacher) ||
  17. a.position.localeCompare(b.position) ||
  18. (a.day || 0) - (b.day || 0) ||
  19. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  20. (a.startSection || 0) - (b.startSection || 0);
  21. });
  22. const step1Merged = [];
  23. let current = list[0];
  24. for (let i = 1; i < list.length; i++) {
  25. const next = list[i];
  26. const isSameCourseAndWeeks =
  27. current.name === next.name && current.teacher === next.teacher &&
  28. current.position === next.position && current.day === next.day &&
  29. current.weeks.join(',') === next.weeks.join(',');
  30. const isContinuous = current.endSection + 1 === next.startSection;
  31. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  32. if (isSameCourseAndWeeks && isContinuous) {
  33. current.endSection = next.endSection;
  34. } else if (isSameCourseAndWeeks && isDuplicate) {
  35. continue;
  36. } else {
  37. step1Merged.push(current);
  38. current = next;
  39. }
  40. }
  41. step1Merged.push(current);
  42. step1Merged.sort((a, b) => {
  43. return a.name.localeCompare(b.name) ||
  44. a.teacher.localeCompare(b.teacher) ||
  45. a.position.localeCompare(b.position) ||
  46. (a.day || 0) - (b.day || 0) ||
  47. (a.startSection || 0) - (b.startSection || 0) ||
  48. (a.endSection || 0) - (b.endSection || 0);
  49. });
  50. const step2Merged = [];
  51. let cur = step1Merged[0];
  52. for (let i = 1; i < step1Merged.length; i++) {
  53. const nxt = step1Merged[i];
  54. const isSameCourseAndSection =
  55. cur.name === nxt.name && cur.teacher === nxt.teacher &&
  56. cur.position === nxt.position && cur.day === nxt.day &&
  57. cur.startSection === nxt.startSection && cur.endSection === nxt.endSection;
  58. if (isSameCourseAndSection) {
  59. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  60. } else {
  61. step2Merged.push(cur);
  62. cur = nxt;
  63. }
  64. }
  65. step2Merged.push(cur);
  66. return step2Merged;
  67. }
  68. function parseWeeks(weekStr) {
  69. if (!weekStr) return [];
  70. const weekSets = weekStr.split(/[,,]/);
  71. let weeks = [];
  72. for (const set of weekSets) {
  73. const trimmedSet = set.trim();
  74. const rangeMatch = trimmedSet.match(/(\d+)-(\d+)周?/);
  75. const singleMatch = trimmedSet.match(/^(\d+)周?/);
  76. let start = 0, end = 0, processed = false;
  77. if (rangeMatch) {
  78. start = Number(rangeMatch[1]);
  79. end = Number(rangeMatch[2]);
  80. processed = true;
  81. } else if (singleMatch) {
  82. start = end = Number(singleMatch[1]);
  83. processed = true;
  84. }
  85. if (processed) {
  86. const isSingle = trimmedSet.includes('(单)');
  87. const isDouble = trimmedSet.includes('(双)');
  88. for (let w = start; w <= end; w++) {
  89. if (isSingle && w % 2 === 0) continue;
  90. if (isDouble && w % 2 !== 0) continue;
  91. weeks.push(w);
  92. }
  93. }
  94. }
  95. return [...new Set(weeks)].sort((a, b) => a - b);
  96. }
  97. function parseJsonData(jsonData) {
  98. if (!jsonData || !Array.isArray(jsonData.kbList)) return [];
  99. const initialCourseList = [];
  100. for (const rawCourse of jsonData.kbList) {
  101. const courseName = rawCourse.kcmc || rawCourse.kcmc_raw;
  102. const teacher = rawCourse.xm || "";
  103. const position = rawCourse.cdmc || rawCourse.cd_id || "";
  104. const day = Number(rawCourse.xqj);
  105. const zcd = rawCourse.zcd;
  106. const jcStr = rawCourse.jcor || rawCourse.jcs || rawCourse.jc;
  107. if (!courseName || !day || !zcd || !jcStr) continue;
  108. const weeksArray = parseWeeks(zcd);
  109. if (weeksArray.length === 0) continue;
  110. const sectionParts = jcStr.split('-').map(Number).filter(n => !isNaN(n));
  111. if (sectionParts.length === 0) continue;
  112. const startSection = Math.min(...sectionParts);
  113. const endSection = Math.max(...sectionParts);
  114. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) || day < 1 || day > 7 || startSection > endSection) continue;
  115. initialCourseList.push({
  116. name: courseName.trim(),
  117. teacher: teacher.trim(),
  118. position: position.trim(),
  119. day: day,
  120. startSection: startSection,
  121. endSection: endSection,
  122. weeks: weeksArray
  123. });
  124. }
  125. return mergeAndDistinctCourses(initialCourseList);
  126. }
  127. async function promptUserToStart() {
  128. return await window.shiguangBridgePromise.showAlert(
  129. "广州航海学院教务系统课表导入",
  130. "导入前请确保您已在浏览器中成功登录教务系统",
  131. "好的,开始导入"
  132. );
  133. }
  134. async function fetchAcademicOptions() {
  135. // 移动端强化:增加 layout=default 强制正方返回 PC 版结构,避免移动版精简页面丢失选项
  136. const url = window.location.origin + "/jwglxt/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default";
  137. try {
  138. const response = await fetch(url, { method: "GET", credentials: "include" });
  139. if (!response.ok) return null;
  140. const htmlText = await response.text();
  141. const parser = new DOMParser();
  142. const doc = parser.parseFromString(htmlText, "text/html");
  143. const allYearOptions = Array.from(doc.querySelectorAll("#xnm option"))
  144. .filter(opt => opt.value !== "")
  145. .map(opt => ({ value: opt.value, text: opt.textContent.trim(), selected: opt.selected }));
  146. const semesterOptions = Array.from(doc.querySelectorAll("#xqm option"))
  147. .filter(opt => opt.value !== "")
  148. .map(opt => ({ value: opt.value, text: opt.textContent.trim(), selected: opt.selected }));
  149. if (allYearOptions.length === 0 || semesterOptions.length === 0) return null;
  150. const selectedIndex = allYearOptions.findIndex(opt => opt.selected);
  151. if (selectedIndex === -1) {
  152. return {
  153. yearOptions: allYearOptions.slice(0, 5),
  154. semesterOptions,
  155. defaultYearIndex: 0,
  156. defaultSemesterIndex: semesterOptions.findIndex(opt => opt.selected) !== -1 ? semesterOptions.findIndex(opt => opt.selected) : 0
  157. };
  158. }
  159. const start = Math.max(0, selectedIndex - 2);
  160. const end = Math.min(allYearOptions.length, selectedIndex + 3);
  161. const yearOptions = allYearOptions.slice(start, end);
  162. const newDefaultIndex = selectedIndex - start;
  163. const defaultSemesterIndex = semesterOptions.findIndex(opt => opt.selected);
  164. return {
  165. yearOptions,
  166. semesterOptions,
  167. defaultYearIndex: newDefaultIndex,
  168. defaultSemesterIndex: defaultSemesterIndex !== -1 ? defaultSemesterIndex : 0
  169. };
  170. } catch (e) {
  171. return null;
  172. }
  173. }
  174. async function selectAcademicYearAndSemester() {
  175. let optionsData = await fetchAcademicOptions();
  176. // 移动端强化兜底:如果 API 被移动端拦截或页面解析失败,智能生成本学年的默认选项
  177. if (!optionsData) {
  178. const d = new Date();
  179. const year = d.getMonth() >= 7 ? d.getFullYear() : d.getFullYear() - 1;
  180. const isFirstSemester = d.getMonth() >= 7;
  181. optionsData = {
  182. yearOptions: [
  183. { value: (year - 1).toString(), text: `${year - 1}-${year}` },
  184. { value: year.toString(), text: `${year}-${year + 1}` },
  185. { value: (year + 1).toString(), text: `${year + 1}-${year + 2}` }
  186. ],
  187. semesterOptions: [
  188. { value: "3", text: "第一学期" },
  189. { value: "12", text: "第二学期" }
  190. ],
  191. defaultYearIndex: 1,
  192. defaultSemesterIndex: isFirstSemester ? 0 : 1
  193. };
  194. window.shiguangBridge.showToast("页面获取失败,已切换为智能学年预测");
  195. }
  196. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  197. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  198. "选择学年", JSON.stringify(yearOptions.map(item => item.text)), defaultYearIndex
  199. );
  200. if (yearIndex === null || yearIndex === -1) return null;
  201. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  202. "选择学期", JSON.stringify(semesterOptions.map(item => item.text)), defaultSemesterIndex
  203. );
  204. if (semesterIndex === null || semesterIndex === -1) return null;
  205. return {
  206. academicYear: yearOptions[yearIndex].value,
  207. semesterCode: semesterOptions[semesterIndex].value
  208. };
  209. }
  210. async function fetchSemesterStartDate(academicYear, semesterCode) {
  211. const url = window.location.origin + "/jwglxt/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154";
  212. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}`;
  213. try {
  214. const response = await fetch(url, {
  215. method: "POST",
  216. headers: {
  217. "accept": "application/json, text/javascript, */*; q=0.01",
  218. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  219. "x-requested-with": "XMLHttpRequest"
  220. },
  221. body: requestBody,
  222. credentials: "include"
  223. });
  224. if (response.ok) {
  225. const jsonText = await response.text();
  226. let json;
  227. try { json = JSON.parse(jsonText); } catch(e) { return null; }
  228. if (Array.isArray(json) && json.length > 0) {
  229. const firstWeekObj = json.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  230. if (firstWeekObj.rq) {
  231. const startDateStr = firstWeekObj.rq.split('/')[0];
  232. if (/^\d{4}-\d{2}-\d{2}$/.test(startDateStr)) return startDateStr;
  233. }
  234. if (firstWeekObj.zcrq) {
  235. const match = firstWeekObj.zcrq.match(/(\d{4}-\d{2}-\d{2})/);
  236. if (match) return match[1];
  237. }
  238. if (firstWeekObj.ksrq) {
  239. const match = firstWeekObj.ksrq.match(/(\d{4}-\d{2}-\d{2})/);
  240. if (match) return match[1];
  241. }
  242. }
  243. }
  244. } catch (e) {}
  245. return null;
  246. }
  247. async function fetchAndParseCourses(academicYear, semesterCode) {
  248. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  249. const targetUrl = window.location.origin + "/jwglxt/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151";
  250. const backupUrl = window.location.origin + "/jwglxt/kbcx/xskbcx_cxXsKb.html?gnmkdm=N2151";
  251. const [courseResponse, semesterStartDate] = await Promise.all([
  252. fetch(targetUrl, {
  253. method: "POST",
  254. headers: {
  255. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  256. "x-requested-with": "XMLHttpRequest"
  257. },
  258. body: requestBody,
  259. credentials: "include"
  260. }).catch(() => null),
  261. fetchSemesterStartDate(academicYear, semesterCode)
  262. ]);
  263. try {
  264. let resp = courseResponse;
  265. if (!resp || !resp.ok) {
  266. resp = await fetch(backupUrl, {
  267. method: "POST",
  268. headers: {
  269. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  270. "x-requested-with": "XMLHttpRequest"
  271. },
  272. body: requestBody,
  273. credentials: "include"
  274. });
  275. }
  276. if (resp && resp.ok) {
  277. const jsonText = await resp.text();
  278. const jsonData = JSON.parse(jsonText);
  279. if (jsonData && jsonData.kbList) {
  280. const parsedCourses = parseJsonData(jsonData);
  281. if (parsedCourses.length > 0) {
  282. let maxWeek = 0;
  283. for (const c of parsedCourses) {
  284. for (const w of c.weeks) {
  285. if (w > maxWeek) maxWeek = w;
  286. }
  287. }
  288. return {
  289. courses: parsedCourses,
  290. config: {
  291. semesterStartDate: semesterStartDate,
  292. semesterTotalWeeks: 20
  293. }
  294. };
  295. }
  296. }
  297. }
  298. } catch (e) {}
  299. window.shiguangBridge.showToast("未能获取课表数据,请检查网络环境或确认页面状态。");
  300. return null;
  301. }
  302. async function saveCourses(parsedCourses) {
  303. try {
  304. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses));
  305. return true;
  306. } catch (error) {
  307. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  308. return false;
  309. }
  310. }
  311. const TimeSlots = [
  312. { number: 1, startTime: "08:10", endTime: "08:55" },
  313. { number: 2, startTime: "09:05", endTime: "09:50" },
  314. { number: 3, startTime: "10:10", endTime: "10:55" },
  315. { number: 4, startTime: "11:05", endTime: "11:50" },
  316. { number: 5, startTime: "14:00", endTime: "14:45" },
  317. { number: 6, startTime: "14:55", endTime: "15:40" },
  318. { number: 7, startTime: "16:00", endTime: "16:45" },
  319. { number: 8, startTime: "16:55", endTime: "17:40" },
  320. { number: 9, startTime: "18:40", endTime: "19:25" },
  321. { number: 10, startTime: "19:35", endTime: "20:20" }
  322. ];
  323. async function importPresetTimeSlots(timeSlots) {
  324. if (timeSlots.length === 0) return;
  325. try {
  326. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  327. window.shiguangBridge.showToast("预设时间段导入成功!");
  328. } catch (error) {
  329. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  330. }
  331. }
  332. async function runImportFlow() {
  333. const alertConfirmed = await promptUserToStart();
  334. if (!alertConfirmed) {
  335. window.shiguangBridge.showToast("用户取消了导入。");
  336. return;
  337. }
  338. const selection = await selectAcademicYearAndSemester();
  339. if (!selection) {
  340. window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
  341. return;
  342. }
  343. const { academicYear, semesterCode } = selection;
  344. const result = await fetchAndParseCourses(academicYear, semesterCode);
  345. if (result === null) return;
  346. const { courses, config } = result;
  347. const saveResult = await saveCourses(courses);
  348. if (!saveResult) return;
  349. try {
  350. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  351. let configMsg = "课表配置更新成功!";
  352. if (config.semesterStartDate) {
  353. configMsg += ` 开学日期:${config.semesterStartDate}`;
  354. }
  355. window.shiguangBridge.showToast(configMsg);
  356. } catch (error) {}
  357. await importPresetTimeSlots(TimeSlots);
  358. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  359. window.shiguangBridge.notifyTaskCompletion();
  360. }
  361. runImportFlow();