qqhrit.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. // 齐齐哈尔工程学院(qqhrit.com) 拾光课程表适配脚本
  2. // 基于正方教务系统接口适配
  3. // 非该大学开发者适配,开发者无法及时发现问题
  4. // 出现问题请提issues或者提交pr更改,这更加快速
  5. /**
  6. * 节次与周次合并去重函数
  7. * @param {Array<Object>} courses 原始解析课程数组
  8. * @returns {Array<Object>} 合并去重后的课程数组
  9. */
  10. function mergeAndDistinctCourses(courses) {
  11. if (!Array.isArray(courses) || courses.length <= 1) return courses;
  12. // 1. 深拷贝并规范周次数据,过滤无效项
  13. const list = courses.map(c => ({
  14. ...c,
  15. name: c.name || '',
  16. teacher: c.teacher || '',
  17. position: c.position || '',
  18. weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
  19. }));
  20. // 阶段 1:合并连续节次与完全重复记录(前提:名称、教师、地点、星期、周次一致)
  21. list.sort((a, b) => {
  22. return a.name.localeCompare(b.name) ||
  23. a.teacher.localeCompare(b.teacher) ||
  24. a.position.localeCompare(b.position) ||
  25. (a.day || 0) - (b.day || 0) ||
  26. a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
  27. (a.startSection || 0) - (b.startSection || 0);
  28. });
  29. const step1Merged = [];
  30. let current = list[0];
  31. for (let i = 1; i < list.length; i++) {
  32. const next = list[i];
  33. const isSameCourseAndWeeks =
  34. current.name === next.name &&
  35. current.teacher === next.teacher &&
  36. current.position === next.position &&
  37. current.day === next.day &&
  38. current.weeks.join(',') === next.weeks.join(',');
  39. const isContinuous = current.endSection + 1 === next.startSection;
  40. const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
  41. if (isSameCourseAndWeeks && isContinuous) {
  42. // 节次连续:延长结束节次 (如 1-2 节 + 3-4 节 -> 1-4 节)
  43. current.endSection = next.endSection;
  44. } else if (isSameCourseAndWeeks && isDuplicate) {
  45. // 完全重复:跳过
  46. continue;
  47. } else {
  48. step1Merged.push(current);
  49. current = next;
  50. }
  51. }
  52. step1Merged.push(current);
  53. // 阶段 2:合并同节次的周次(前提:名称、教师、地点、星期、开始/结束节次一致)
  54. step1Merged.sort((a, b) => {
  55. return a.name.localeCompare(b.name) ||
  56. a.teacher.localeCompare(b.teacher) ||
  57. a.position.localeCompare(b.position) ||
  58. (a.day || 0) - (b.day || 0) ||
  59. (a.startSection || 0) - (b.startSection || 0) ||
  60. (a.endSection || 0) - (b.endSection || 0);
  61. });
  62. const step2Merged = [];
  63. let cur = step1Merged[0];
  64. for (let i = 1; i < step1Merged.length; i++) {
  65. const nxt = step1Merged[i];
  66. const isSameCourseAndSection =
  67. cur.name === nxt.name &&
  68. cur.teacher === nxt.teacher &&
  69. cur.position === nxt.position &&
  70. cur.day === nxt.day &&
  71. cur.startSection === nxt.startSection &&
  72. cur.endSection === nxt.endSection;
  73. if (isSameCourseAndSection) {
  74. // 周次合并去重 (如 1-8 周 + 9-16 周 -> 1-16 周)
  75. cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
  76. } else {
  77. step2Merged.push(cur);
  78. cur = nxt;
  79. }
  80. }
  81. step2Merged.push(cur);
  82. return step2Merged;
  83. }
  84. /**
  85. * 解析周次字符串,处理单双周和周次范围
  86. */
  87. function parseWeeks(weekStr) {
  88. if (!weekStr) return [];
  89. const weekSets = weekStr.split(',');
  90. let weeks = [];
  91. for (const set of weekSets) {
  92. const trimmedSet = set.trim();
  93. const rangeMatch = trimmedSet.match(/(\d+)-(\d+)周/);
  94. const singleMatch = trimmedSet.match(/^(\d+)周/);
  95. let start = 0;
  96. let end = 0;
  97. let processed = false;
  98. if (rangeMatch) {
  99. start = Number(rangeMatch[1]);
  100. end = Number(rangeMatch[2]);
  101. processed = true;
  102. } else if (singleMatch) {
  103. start = end = Number(singleMatch[1]);
  104. processed = true;
  105. }
  106. if (processed) {
  107. const isSingle = trimmedSet.includes('(单)');
  108. const isDouble = trimmedSet.includes('(双)');
  109. for (let w = start; w <= end; w++) {
  110. if (isSingle && w % 2 === 0) continue;
  111. if (isDouble && w % 2 !== 0) continue;
  112. weeks.push(w);
  113. }
  114. }
  115. }
  116. return [...new Set(weeks)].sort((a, b) => a - b);
  117. }
  118. /**
  119. * 独立处理课程时间逻辑的函数
  120. */
  121. function applyCustomTimeLogic(courses) {
  122. // 方案1:周末全天
  123. const TIME_SCHEME_1 = [
  124. { number: 1, startTime: "08:20", endTime: "09:05" },
  125. { number: 2, startTime: "09:05", endTime: "09:50" },
  126. { number: 3, startTime: "10:00", endTime: "10:45" },
  127. { number: 4, startTime: "10:45", endTime: "11:30" },
  128. { number: 5, startTime: "13:30", endTime: "14:15" },
  129. { number: 6, startTime: "14:15", endTime: "15:00" },
  130. { number: 7, startTime: "15:20", endTime: "16:05" },
  131. { number: 8, startTime: "16:05", endTime: "16:50" },
  132. { number: 9, startTime: "18:00", endTime: "18:45" },
  133. { number: 10, startTime: "18:45", endTime: "19:30" },
  134. { number: 11, startTime: "19:30", endTime: "20:15" }
  135. ];
  136. // 方案2:2#/3# 专用(3-4节)
  137. const TIME_SCHEME_2 = [
  138. { number: 3, startTime: "10:20", endTime: "11:05" },
  139. { number: 4, startTime: "11:15", endTime: "12:00" }
  140. ];
  141. // 方案3:图/馆/齐三机床 专用(3-4节)
  142. const TIME_SCHEME_3 = [
  143. { number: 3, startTime: "09:55", endTime: "10:40" },
  144. { number: 4, startTime: "10:50", endTime: "11:35" }
  145. ];
  146. return courses.map(course => {
  147. const is23Sharp = /(2#|3#)/.test(course.position);
  148. const isLibMachine = /(图|馆|齐三机床)/.test(course.position);
  149. const isWeekend = (course.day === 6 || course.day === 7);
  150. const isSpecialPos = (is23Sharp || isLibMachine);
  151. const isEndpoint3or4 = (course.startSection === 3 || course.startSection === 4 ||
  152. course.endSection === 3 || course.endSection === 4);
  153. const shouldApplyCustom = isWeekend || (isSpecialPos && isEndpoint3or4);
  154. if (shouldApplyCustom) {
  155. let startSlot, endSlot;
  156. if (isWeekend) {
  157. startSlot = TIME_SCHEME_1.find(s => s.number === course.startSection);
  158. endSlot = TIME_SCHEME_1.find(s => s.number === course.endSection);
  159. } else {
  160. // 工作日特殊教室逻辑
  161. const scheme = is23Sharp ? TIME_SCHEME_2 : TIME_SCHEME_3;
  162. const getSectionTime = (sec) => {
  163. if (sec === 3 || sec === 4) {
  164. return scheme.find(s => s.number === sec);
  165. }
  166. return TimeSlots.find(s => s.number === sec);
  167. };
  168. startSlot = getSectionTime(course.startSection);
  169. endSlot = getSectionTime(course.endSection);
  170. }
  171. if (startSlot && endSlot) {
  172. return {
  173. ...course,
  174. isCustomTime: true,
  175. customStartTime: startSlot.startTime,
  176. customEndTime: endSlot.endTime
  177. };
  178. }
  179. }
  180. return course;
  181. });
  182. }
  183. /**
  184. * 解析 API 返回的 JSON 数据
  185. */
  186. function parseJsonData(jsonData) {
  187. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  188. return [];
  189. }
  190. const rawCourseList = jsonData.kbList;
  191. const initialCourseList = [];
  192. for (const rawCourse of rawCourseList) {
  193. if (!rawCourse.kcmc || !rawCourse.xm || !rawCourse.cdmc ||
  194. !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) {
  195. continue;
  196. }
  197. const weeksArray = parseWeeks(rawCourse.zcd);
  198. if (weeksArray.length === 0) {
  199. continue;
  200. }
  201. const sectionParts = rawCourse.jcs.split('-');
  202. const startSection = Number(sectionParts[0]);
  203. const endSection = Number(sectionParts[sectionParts.length - 1]);
  204. const day = Number(rawCourse.xqj);
  205. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) ||
  206. day < 1 || day > 7 || startSection > endSection) {
  207. continue;
  208. }
  209. initialCourseList.push({
  210. name: rawCourse.kcmc.trim(),
  211. teacher: rawCourse.xm.trim(),
  212. position: rawCourse.cdmc.trim(),
  213. day: day,
  214. startSection: startSection,
  215. endSection: endSection,
  216. weeks: weeksArray
  217. });
  218. }
  219. const mergedCourses = mergeAndDistinctCourses(initialCourseList);
  220. return applyCustomTimeLogic(mergedCourses);
  221. }
  222. async function promptUserToStart() {
  223. return await window.shiguangBridgePromise.showAlert(
  224. "教务系统课表导入",
  225. "导入前请确保您已在浏览器中成功登录教务系统",
  226. "好的,开始导入"
  227. );
  228. }
  229. /**
  230. * 从教务系统获取学年学期选项
  231. * 学年:以选中项为中心,取前2年+后2年,共5个选项
  232. */
  233. async function fetchAcademicOptions() {
  234. const url = "http://jwxt.qqhrit.com:20266/jwglxt/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151";
  235. try {
  236. const response = await fetch(url, {
  237. method: "GET",
  238. credentials: "include"
  239. });
  240. if (!response.ok) return null;
  241. const htmlText = await response.text();
  242. const parser = new DOMParser();
  243. const doc = parser.parseFromString(htmlText, "text/html");
  244. const allYearOptions = Array.from(doc.querySelectorAll("#xnm option"))
  245. .filter(opt => opt.value !== "")
  246. .map(opt => ({
  247. value: opt.value,
  248. text: opt.textContent.trim(),
  249. selected: opt.selected
  250. }));
  251. const semesterOptions = Array.from(doc.querySelectorAll("#xqm option"))
  252. .filter(opt => opt.value !== "")
  253. .map(opt => ({
  254. value: opt.value,
  255. text: opt.textContent.trim(),
  256. selected: opt.selected
  257. }));
  258. if (allYearOptions.length === 0 || semesterOptions.length === 0) {
  259. return null;
  260. }
  261. const selectedIndex = allYearOptions.findIndex(opt => opt.selected);
  262. if (selectedIndex === -1) {
  263. return {
  264. yearOptions: allYearOptions.slice(0, 5),
  265. semesterOptions,
  266. defaultYearIndex: 0,
  267. defaultSemesterIndex: semesterOptions.findIndex(opt => opt.selected) !== -1
  268. ? semesterOptions.findIndex(opt => opt.selected)
  269. : 0
  270. };
  271. }
  272. const start = Math.max(0, selectedIndex - 2);
  273. const end = Math.min(allYearOptions.length, selectedIndex + 3);
  274. const yearOptions = allYearOptions.slice(start, end);
  275. const newDefaultIndex = selectedIndex - start;
  276. const defaultSemesterIndex = semesterOptions.findIndex(opt => opt.selected);
  277. return {
  278. yearOptions,
  279. semesterOptions,
  280. defaultYearIndex: newDefaultIndex,
  281. defaultSemesterIndex: defaultSemesterIndex !== -1 ? defaultSemesterIndex : 0
  282. };
  283. } catch (e) {
  284. return null;
  285. }
  286. }
  287. /**
  288. * 提示用户选择学年和学期
  289. */
  290. async function selectAcademicYearAndSemester() {
  291. const optionsData = await fetchAcademicOptions();
  292. if (!optionsData) {
  293. window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确保登录状态。");
  294. return null;
  295. }
  296. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  297. const yearTexts = yearOptions.map(item => item.text);
  298. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  299. "选择学年",
  300. JSON.stringify(yearTexts),
  301. defaultYearIndex
  302. );
  303. if (yearIndex === null || yearIndex === -1) return null;
  304. const selectedYearCode = yearOptions[yearIndex].value;
  305. const semesterTexts = semesterOptions.map(item => item.text);
  306. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  307. "选择学期",
  308. JSON.stringify(semesterTexts),
  309. defaultSemesterIndex
  310. );
  311. if (semesterIndex === null || semesterIndex === -1) return null;
  312. const selectedSemesterCode = semesterOptions[semesterIndex].value;
  313. return {
  314. academicYear: selectedYearCode,
  315. semesterCode: selectedSemesterCode
  316. };
  317. }
  318. /**
  319. * 获取学期开学日期
  320. */
  321. async function fetchSemesterStartDate(academicYear, semesterCode) {
  322. const url = "http://jwxt.qqhrit.com:20266/jwglxt/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154";
  323. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}`;
  324. try {
  325. const response = await fetch(url, {
  326. method: "POST",
  327. headers: {
  328. "accept": "application/json, text/javascript, */*; q=0.01",
  329. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  330. "x-requested-with": "XMLHttpRequest"
  331. },
  332. body: requestBody,
  333. credentials: "include"
  334. });
  335. if (response.ok) {
  336. const json = await response.json();
  337. if (Array.isArray(json) && json.length > 0) {
  338. // 优先找第1周,否则取第一项
  339. const firstWeekObj = json.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  340. if (firstWeekObj.rq) {
  341. const startDateStr = firstWeekObj.rq.split('/')[0];
  342. if (/^\d{4}-\d{2}-\d{2}$/.test(startDateStr)) {
  343. return startDateStr;
  344. }
  345. }
  346. if (firstWeekObj.zcrq) {
  347. const match = firstWeekObj.zcrq.match(/(\d{4}-\d{2}-\d{2})/);
  348. if (match) return match[1];
  349. }
  350. // 某些系统用 ksrq 字段
  351. if (firstWeekObj.ksrq) {
  352. const match = firstWeekObj.ksrq.match(/(\d{4}-\d{2}-\d{2})/);
  353. if (match) return match[1];
  354. }
  355. }
  356. }
  357. } catch (e) {
  358. // 获取失败不影响主流程
  359. }
  360. return null;
  361. }
  362. /**
  363. * 请求和解析课程数据
  364. */
  365. async function fetchAndParseCourses(academicYear, semesterCode) {
  366. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
  367. const targetUrl = "http://jwxt.qqhrit.com:20266/jwglxt/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151";
  368. // 并行获取课程数据和开学日期
  369. const [courseResponse, semesterStartDate] = await Promise.all([
  370. fetch(targetUrl, {
  371. method: "POST",
  372. headers: {
  373. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  374. },
  375. body: requestBody,
  376. credentials: "include"
  377. }),
  378. fetchSemesterStartDate(academicYear, semesterCode)
  379. ]);
  380. try {
  381. if (courseResponse.ok) {
  382. const jsonText = await courseResponse.text();
  383. const jsonData = JSON.parse(jsonText);
  384. if (jsonData && jsonData.kbList) {
  385. const parsedCourses = parseJsonData(jsonData);
  386. if (parsedCourses.length > 0) {
  387. return {
  388. courses: parsedCourses,
  389. config: {
  390. semesterStartDate: semesterStartDate,
  391. semesterTotalWeeks: 20
  392. }
  393. };
  394. }
  395. }
  396. }
  397. } catch (e) {
  398. // 请求失败
  399. }
  400. window.shiguangBridge.showToast("未能获取课表数据,请检查网络环境或登录状态。");
  401. return null;
  402. }
  403. async function saveCourses(parsedCourses) {
  404. try {
  405. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses));
  406. return true;
  407. } catch (error) {
  408. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  409. return false;
  410. }
  411. }
  412. const TimeSlots = [
  413. { number: 1, startTime: "08:00", endTime: "08:45" },
  414. { number: 2, startTime: "08:55", endTime: "09:40" },
  415. { number: 3, startTime: "10:05", endTime: "10:50" },
  416. { number: 4, startTime: "11:00", endTime: "11:45" },
  417. { number: 5, startTime: "13:30", endTime: "14:15" },
  418. { number: 6, startTime: "14:25", endTime: "15:10" },
  419. { number: 7, startTime: "15:20", endTime: "16:05" },
  420. { number: 8, startTime: "16:05", endTime: "16:50" },
  421. { number: 9, startTime: "18:00", endTime: "18:45" },
  422. { number: 10, startTime: "18:45", endTime: "19:30" },
  423. { number: 11, startTime: "19:30", endTime: "20:15" }
  424. ];
  425. async function importPresetTimeSlots(timeSlots) {
  426. if (timeSlots.length === 0) {
  427. window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
  428. return;
  429. }
  430. try {
  431. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  432. window.shiguangBridge.showToast("预设时间段导入成功!");
  433. } catch (error) {
  434. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  435. }
  436. }
  437. async function runImportFlow() {
  438. const alertConfirmed = await promptUserToStart();
  439. if (!alertConfirmed) {
  440. window.shiguangBridge.showToast("用户取消了导入。");
  441. return;
  442. }
  443. const selection = await selectAcademicYearAndSemester();
  444. if (!selection) {
  445. window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
  446. return;
  447. }
  448. const { academicYear, semesterCode } = selection;
  449. const result = await fetchAndParseCourses(academicYear, semesterCode);
  450. if (result === null) {
  451. return;
  452. }
  453. const { courses, config } = result;
  454. const saveResult = await saveCourses(courses);
  455. if (!saveResult) {
  456. return;
  457. }
  458. try {
  459. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  460. let configMsg = "课表配置更新成功!";
  461. if (config.semesterStartDate) {
  462. configMsg += ` 开学日期:${config.semesterStartDate}`;
  463. }
  464. window.shiguangBridge.showToast(configMsg);
  465. } catch (error) {
  466. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  467. }
  468. await importPresetTimeSlots(TimeSlots);
  469. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  470. window.shiguangBridge.notifyTaskCompletion();
  471. }
  472. runImportFlow();