shzq.js 18 KB

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