gxcme.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. // 广西机电职业技术学院(gxcme.edu.cn) 拾光课程表适配脚本
  2. // 基于正方教务系统Mobile版接口适配
  3. function mergeAndDistinctCourses(courses) {
  4. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  5. const list = courses.map(c => ({
  6. ...c,
  7. name: c.name || '',
  8. teacher: c.teacher || '',
  9. position: c.position || '',
  10. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  11. }));
  12. list.sort((a, b) => {
  13. return a.name.localeCompare(b.name) ||
  14. a.teacher.localeCompare(b.teacher) ||
  15. a.position.localeCompare(b.position) ||
  16. (a.day || 0) - (b.day || 0) ||
  17. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  18. (a.startSection || 0) - (b.startSection || 0);
  19. });
  20. const step1Merged = [];
  21. let current = list[0];
  22. for (let i = 1; i < list.length; i++) {
  23. const next = list[i];
  24. const isSameCourseAndWeeks =
  25. current.name === next.name &&
  26. current.teacher === next.teacher &&
  27. current.position === next.position &&
  28. 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 &&
  56. cur.teacher === nxt.teacher &&
  57. cur.position === nxt.position &&
  58. cur.day === nxt.day &&
  59. cur.startSection === nxt.startSection &&
  60. cur.endSection === nxt.endSection;
  61. if (isSameCourseAndSection) {
  62. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  63. } else {
  64. step2Merged.push(cur);
  65. cur = nxt;
  66. }
  67. }
  68. step2Merged.push(cur);
  69. return step2Merged;
  70. }
  71. function parseWeeks(weekStr) {
  72. if (!weekStr) return [];
  73. const weekSets = weekStr.split(',');
  74. let weeks = [];
  75. for (const set of weekSets) {
  76. const trimmedSet = set.trim();
  77. const rangeMatch = trimmedSet.match(/(\d+)-(\d+)周/);
  78. const singleMatch = trimmedSet.match(/^(\d+)周/);
  79. let start = 0, end = 0, processed = false;
  80. if (rangeMatch) {
  81. start = Number(rangeMatch[1]);
  82. end = Number(rangeMatch[2]);
  83. processed = true;
  84. } else if (singleMatch) {
  85. start = end = Number(singleMatch[1]);
  86. processed = true;
  87. }
  88. if (processed) {
  89. const isSingle = trimmedSet.includes('(单)');
  90. const isDouble = trimmedSet.includes('(双)');
  91. for (let w = start; w <= end; w++) {
  92. if (isSingle && w % 2 === 0) continue;
  93. if (isDouble && w % 2 !== 0) continue;
  94. weeks.push(w);
  95. }
  96. }
  97. }
  98. return [...new Set(weeks)].sort((a, b) => a - b);
  99. }
  100. function parseJsonData(jsonData) {
  101. if (!jsonData || !Array.isArray(jsonData.kbList)) return [];
  102. const initialCourseList = [];
  103. for (const rawCourse of jsonData.kbList) {
  104. if (!rawCourse.kcmc || !rawCourse.xm || !rawCourse.cdmc ||
  105. !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) continue;
  106. const weeksArray = parseWeeks(rawCourse.zcd);
  107. if (weeksArray.length === 0) continue;
  108. const sectionParts = rawCourse.jcs.split('-');
  109. const startSection = Number(sectionParts[0]);
  110. const endSection = Number(sectionParts[sectionParts.length - 1]);
  111. const day = Number(rawCourse.xqj);
  112. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) ||
  113. day < 1 || day > 7 || startSection > endSection) continue;
  114. initialCourseList.push({
  115. name: rawCourse.kcmc.trim(),
  116. teacher: rawCourse.xm.trim(),
  117. position: rawCourse.cdmc.trim(),
  118. day: day,
  119. startSection: startSection,
  120. endSection: endSection,
  121. weeks: weeksArray
  122. });
  123. }
  124. return mergeAndDistinctCourses(initialCourseList);
  125. }
  126. async function promptUserToStart() {
  127. return await window.shiguangBridgePromise.showAlert(
  128. "教务系统课表导入",
  129. "导入前请确保您已在浏览器中成功登录教务系统",
  130. "好的,开始导入"
  131. );
  132. }
  133. async function fetchAcademicOptions() {
  134. const url = "/jwglxt/kbcx/xskbcxZccx_cxXskbcxIndex.html?gnmkdm=N2154&layout=default";
  135. try {
  136. const response = await fetch(url, { method: "GET", credentials: "include" });
  137. if (!response.ok) return null;
  138. const htmlText = await response.text();
  139. const parser = new DOMParser();
  140. const doc = parser.parseFromString(htmlText, "text/html");
  141. const allYearOptions = Array.from(doc.querySelectorAll("#xnm option"))
  142. .filter(opt => opt.value !== "")
  143. .map(opt => ({
  144. value: opt.value,
  145. text: opt.textContent.trim(),
  146. selected: opt.hasAttribute("selected")
  147. }));
  148. const semesterOptions = Array.from(doc.querySelectorAll("#xqm option"))
  149. .filter(opt => opt.value !== "")
  150. .map(opt => ({
  151. value: opt.value,
  152. text: opt.textContent.trim(),
  153. selected: opt.hasAttribute("selected")
  154. }));
  155. if (allYearOptions.length === 0 || semesterOptions.length === 0) return null;
  156. const selectedIndex = allYearOptions.findIndex(opt => opt.selected);
  157. if (selectedIndex === -1) {
  158. return {
  159. yearOptions: allYearOptions.slice(0, 5),
  160. semesterOptions,
  161. defaultYearIndex: 0,
  162. defaultSemesterIndex: semesterOptions.findIndex(opt => opt.selected) !== -1
  163. ? semesterOptions.findIndex(opt => opt.selected) : 0
  164. };
  165. }
  166. const start = Math.max(0, selectedIndex - 2);
  167. const end = Math.min(allYearOptions.length, selectedIndex + 3);
  168. return {
  169. yearOptions: allYearOptions.slice(start, end),
  170. semesterOptions,
  171. defaultYearIndex: selectedIndex - start,
  172. defaultSemesterIndex: semesterOptions.findIndex(opt => opt.selected) !== -1
  173. ? semesterOptions.findIndex(opt => opt.selected) : 0
  174. };
  175. } catch (e) {
  176. return null;
  177. }
  178. }
  179. async function selectAcademicYearAndSemester() {
  180. const optionsData = await fetchAcademicOptions();
  181. if (!optionsData) {
  182. window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确保登录状态。");
  183. return null;
  184. }
  185. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  186. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  187. "选择学年",
  188. JSON.stringify(yearOptions.map(item => item.text)),
  189. defaultYearIndex
  190. );
  191. if (yearIndex === null || yearIndex === -1) return null;
  192. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  193. "选择学期",
  194. JSON.stringify(semesterOptions.map(item => item.text)),
  195. defaultSemesterIndex
  196. );
  197. if (semesterIndex === null || semesterIndex === -1) return null;
  198. return {
  199. academicYear: yearOptions[yearIndex].value,
  200. semesterCode: semesterOptions[semesterIndex].value
  201. };
  202. }
  203. async function fetchSemesterStartDate(academicYear, semesterCode) {
  204. const url = "/jwglxt/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154";
  205. try {
  206. const response = await fetch(url, {
  207. method: "POST",
  208. headers: {
  209. "accept": "application/json, text/javascript, */*; q=0.01",
  210. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  211. "x-requested-with": "XMLHttpRequest"
  212. },
  213. body: `xnm=${academicYear}&xqm=${semesterCode}`,
  214. credentials: "include"
  215. });
  216. if (response.ok) {
  217. const json = await response.json();
  218. if (Array.isArray(json) && json.length > 0) {
  219. const firstWeekObj = json.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  220. if (firstWeekObj.rq) {
  221. const startDateStr = firstWeekObj.rq.split('/')[0];
  222. if (/^\d{4}-\d{2}-\d{2}$/.test(startDateStr)) return startDateStr;
  223. }
  224. if (firstWeekObj.zcrq) {
  225. const match = firstWeekObj.zcrq.match(/(\d{4}-\d{2}-\d{2})/);
  226. if (match) return match[1];
  227. }
  228. }
  229. }
  230. } catch (e) {}
  231. return null;
  232. }
  233. async function fetchAndParseCourses(academicYear, semesterCode) {
  234. const targetUrl = "/jwglxt/kbcx/xskbcxMobile_cxXsKb.html?gnmkdm=N2154";
  235. const [courseResponse, semesterStartDate] = await Promise.all([
  236. fetch(targetUrl, {
  237. method: "POST",
  238. headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
  239. body: `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck`,
  240. credentials: "include"
  241. }),
  242. fetchSemesterStartDate(academicYear, semesterCode)
  243. ]);
  244. try {
  245. if (courseResponse.ok) {
  246. const jsonData = await courseResponse.json();
  247. if (jsonData && jsonData.kbList) {
  248. const parsedCourses = parseJsonData(jsonData);
  249. if (parsedCourses.length > 0) {
  250. return {
  251. courses: parsedCourses,
  252. config: {
  253. semesterStartDate: semesterStartDate,
  254. semesterTotalWeeks: 20
  255. }
  256. };
  257. }
  258. }
  259. }
  260. } catch (e) {}
  261. window.shiguangBridge.showToast("未能获取课表数据,请检查网络环境或登录状态。");
  262. return null;
  263. }
  264. async function saveCourses(parsedCourses) {
  265. try {
  266. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses));
  267. return true;
  268. } catch (error) {
  269. window.shiguangBridge.showToast("课程保存失败: " + error.message);
  270. return false;
  271. }
  272. }
  273. const TimeSlots = [
  274. { number: 1, startTime: "08:10", endTime: "08:50" },
  275. { number: 2, startTime: "09:00", endTime: "09:40" },
  276. { number: 3, startTime: "09:40", endTime: "10:20" },
  277. { number: 4, startTime: "10:30", endTime: "11:10" },
  278. { number: 5, startTime: "11:20", endTime: "12:00" },
  279. { number: 6, startTime: "12:10", endTime: "12:50" },
  280. { number: 7, startTime: "14:40", endTime: "15:20" },
  281. { number: 8, startTime: "15:30", endTime: "16:10" },
  282. { number: 9, startTime: "16:10", endTime: "16:50" },
  283. { number: 10, startTime: "17:00", endTime: "17:40" },
  284. { number: 11, startTime: "17:50", endTime: "18:30" },
  285. { number: 12, startTime: "19:30", endTime: "20:10" },
  286. { number: 13, startTime: "20:20", endTime: "21:00" },
  287. { number: 14, startTime: "21:00", endTime: "21:40" }
  288. ];
  289. async function importPresetTimeSlots(timeSlots) {
  290. if (timeSlots.length === 0) return;
  291. try { await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots)); } catch (e) {}
  292. }
  293. async function runImportFlow() {
  294. const alertConfirmed = await promptUserToStart();
  295. if (!alertConfirmed) {
  296. window.shiguangBridge.showToast("用户取消了导入。");
  297. return;
  298. }
  299. const selection = await selectAcademicYearAndSemester();
  300. if (!selection) {
  301. window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
  302. return;
  303. }
  304. const { academicYear, semesterCode } = selection;
  305. const result = await fetchAndParseCourses(academicYear, semesterCode);
  306. if (result === null) return;
  307. const { courses, config } = result;
  308. const saveResult = await saveCourses(courses);
  309. if (!saveResult) return;
  310. try {
  311. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  312. } catch (error) {}
  313. await importPresetTimeSlots(TimeSlots);
  314. window.shiguangBridge.showToast("课程导入成功,共导入 " + courses.length + " 门课程!");
  315. window.shiguangBridge.notifyTaskCompletion();
  316. }
  317. runImportFlow();