cqepc.js 15 KB

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