czimt.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. // 常州机电职业技术学院(czimt.edu.cn) 拾光课程表适配脚本
  2. // 基于正方教务系统接口适配
  3. function parseWeeks(weekStr) {
  4. if (!weekStr) return [];
  5. const weekSets = weekStr.split(',');
  6. let weeks = [];
  7. for (const set of weekSets) {
  8. const trimmedSet = set.trim();
  9. const rangeMatch = trimmedSet.match(/(\d+)-(\d+)周/);
  10. const singleMatch = trimmedSet.match(/^(\d+)周/);
  11. let start = 0, end = 0, processed = false;
  12. if (rangeMatch) {
  13. start = Number(rangeMatch[1]);
  14. end = Number(rangeMatch[2]);
  15. processed = true;
  16. } else if (singleMatch) {
  17. start = end = Number(singleMatch[1]);
  18. processed = true;
  19. }
  20. if (processed) {
  21. const isSingle = trimmedSet.includes('(单)');
  22. const isDouble = trimmedSet.includes('(双)');
  23. for (let w = start; w <= end; w++) {
  24. if (isSingle && w % 2 === 0) continue;
  25. if (isDouble && w % 2 !== 0) continue;
  26. weeks.push(w);
  27. }
  28. }
  29. }
  30. return [...new Set(weeks)].sort((a, b) => a - b);
  31. }
  32. function parseJsonData(jsonData) {
  33. console.log("JS: 正在解析 JSON 数据...");
  34. if (!jsonData || !Array.isArray(jsonData.kbList)) {
  35. console.warn("JS: JSON 数据结构错误或缺少 kbList 字段。");
  36. return [];
  37. }
  38. const rawCourseList = jsonData.kbList;
  39. const finalCourseList = [];
  40. for (const rawCourse of rawCourseList) {
  41. if (!rawCourse.kcmc || !rawCourse.xm || !rawCourse.cdmc ||
  42. !rawCourse.xqj || !rawCourse.jcs || !rawCourse.zcd) {
  43. console.warn("JS: 课程数据字段缺失,跳过:", rawCourse.kcmc || "未知课程");
  44. continue;
  45. }
  46. const weeksArray = parseWeeks(rawCourse.zcd);
  47. if (weeksArray.length === 0) {
  48. console.warn("JS: 周次解析失败,跳过:", rawCourse.kcmc);
  49. continue;
  50. }
  51. const sectionParts = String(rawCourse.jcs).split('-');
  52. const startSection = Number(sectionParts[0]);
  53. const endSection = Number(sectionParts[sectionParts.length - 1]);
  54. const day = Number(rawCourse.xqj);
  55. if (isNaN(day) || isNaN(startSection) || isNaN(endSection) ||
  56. day < 1 || day > 7 || startSection > endSection) {
  57. console.warn("JS: 课程", rawCourse.kcmc, "星期或节次数据无效,跳过。");
  58. continue;
  59. }
  60. const campus = rawCourse.xqmc ? String(rawCourse.xqmc).trim() : "";
  61. const classroom = String(rawCourse.cdmc).trim();
  62. const position = campus ? `${classroom}(${campus})` : classroom;
  63. const xslxbj = rawCourse.xslxbj ? String(rawCourse.xslxbj).trim() : "";
  64. const name = xslxbj ? `${String(rawCourse.kcmc).trim()}${xslxbj}` : String(rawCourse.kcmc).trim();
  65. finalCourseList.push({
  66. name: name,
  67. teacher: String(rawCourse.xm).trim(),
  68. position: position,
  69. day: day,
  70. startSection: startSection,
  71. endSection: endSection,
  72. weeks: weeksArray,
  73. isCustomTime: false
  74. });
  75. }
  76. finalCourseList.sort((a, b) =>
  77. a.day - b.day ||
  78. a.startSection - b.startSection ||
  79. a.name.localeCompare(b.name)
  80. );
  81. console.log(`JS: JSON 数据解析完成,共找到 ${finalCourseList.length} 门课程。`);
  82. return finalCourseList;
  83. }
  84. async function promptUserToStart() {
  85. return await window.shiguangBridgePromise.showAlert(
  86. "常机电学生课表导入",
  87. "导入前请确保您已成功登录教务系统。",
  88. "开始导入"
  89. );
  90. }
  91. /**
  92. * 从教务系统获取学年学期选项
  93. * 学年:以选中项为中心,取前2年+后2年,共5个选项
  94. */
  95. async function fetchAcademicOptions() {
  96. const targetUrls = [
  97. "https://webapp.czimt.edu.cn/http/77726476706e69737468656265737421fae042d2242a65557d468aa2/kbcx/xskbcx_cxXskbcxIndex.html?vpn-12-o1-jwc.czmec.cn&gnmkdm=N2151",
  98. "http://jwc.czmec.cn/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151"
  99. ];
  100. for (const url of targetUrls) {
  101. try {
  102. const response = await fetch(url, {
  103. method: "GET",
  104. credentials: "include"
  105. });
  106. if (!response.ok) continue;
  107. const htmlText = await response.text();
  108. const parser = new DOMParser();
  109. const doc = parser.parseFromString(htmlText, "text/html");
  110. const allYearOptions = Array.from(doc.querySelectorAll("#xnm option"))
  111. .filter(opt => opt.value !== "")
  112. .map(opt => ({
  113. value: opt.value,
  114. text: opt.textContent.trim(),
  115. selected: opt.selected
  116. }));
  117. const semesterOptions = Array.from(doc.querySelectorAll("#xqm option"))
  118. .filter(opt => opt.value !== "")
  119. .map(opt => ({
  120. value: opt.value,
  121. text: opt.textContent.trim(),
  122. selected: opt.selected
  123. }));
  124. if (allYearOptions.length === 0 || semesterOptions.length === 0) continue;
  125. const selectedIndex = allYearOptions.findIndex(opt => opt.selected);
  126. if (selectedIndex === -1) {
  127. return {
  128. yearOptions: allYearOptions.slice(0, 5),
  129. semesterOptions,
  130. defaultYearIndex: 0,
  131. defaultSemesterIndex: Math.max(0, semesterOptions.findIndex(opt => opt.selected))
  132. };
  133. }
  134. const start = Math.max(0, selectedIndex - 2);
  135. const end = Math.min(allYearOptions.length, selectedIndex + 3);
  136. const defaultSemesterIndex = semesterOptions.findIndex(opt => opt.selected);
  137. return {
  138. yearOptions: allYearOptions.slice(start, end),
  139. semesterOptions,
  140. defaultYearIndex: selectedIndex - start,
  141. defaultSemesterIndex: defaultSemesterIndex !== -1 ? defaultSemesterIndex : 0
  142. };
  143. } catch (e) {
  144. console.error(`JS: 获取学年学期选项失败: ${url}`);
  145. }
  146. }
  147. return null;
  148. }
  149. /**
  150. * 提示用户选择学年和学期
  151. */
  152. async function selectAcademicYearAndSemester() {
  153. const optionsData = await fetchAcademicOptions();
  154. if (!optionsData) {
  155. window.shiguangBridge.showToast("从教务系统读取学年学期失败,请确保登录状态。");
  156. return null;
  157. }
  158. const { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = optionsData;
  159. const yearTexts = yearOptions.map(item => item.text);
  160. const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
  161. "选择学年",
  162. JSON.stringify(yearTexts),
  163. defaultYearIndex
  164. );
  165. if (yearIndex === null || yearIndex === -1) return null;
  166. const selectedYearCode = yearOptions[yearIndex].value;
  167. const semesterTexts = semesterOptions.map(item => item.text);
  168. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
  169. "选择学期",
  170. JSON.stringify(semesterTexts),
  171. defaultSemesterIndex
  172. );
  173. if (semesterIndex === null || semesterIndex === -1) return null;
  174. const selectedSemesterCode = semesterOptions[semesterIndex].value;
  175. return {
  176. academicYear: selectedYearCode,
  177. semesterCode: selectedSemesterCode
  178. };
  179. }
  180. /**
  181. * 获取学期开学日期
  182. * 优先找第1周的记录,从 rq / zcrq 字段中提取日期
  183. */
  184. async function fetchSemesterStartDate(academicYear, semesterCode) {
  185. const targetUrls = [
  186. "https://webapp.czimt.edu.cn/http/77726476706e69737468656265737421fae042d2242a65557d468aa2/kbcx/xskbcxZccx_cxZcByXnxq.html?vpn-12-o1-jwc.czmec.cn&gnmkdm=N2154",
  187. "http://jwc.czmec.cn/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154"
  188. ];
  189. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}`;
  190. for (const url of targetUrls) {
  191. try {
  192. const response = await fetch(url, {
  193. method: "POST",
  194. headers: {
  195. "accept": "application/json, text/javascript, */*; q=0.01",
  196. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
  197. "x-requested-with": "XMLHttpRequest"
  198. },
  199. body: requestBody,
  200. credentials: "include"
  201. });
  202. if (!response.ok) continue;
  203. const json = await response.json();
  204. if (!Array.isArray(json) || json.length === 0) continue;
  205. // 优先找第1周,否则取第一项
  206. const firstWeekObj = json.find(item => String(item.zs) === "1" || String(item.zsmc) === "1") || json[0];
  207. // rq 是该周每天的日期列表(逗号或斜杠分隔),取第一个即周一
  208. if (firstWeekObj.rq) {
  209. const match = String(firstWeekObj.rq).match(/(\d{4}-\d{2}-\d{2})/);
  210. if (match) return match[1];
  211. }
  212. if (firstWeekObj.zcrq) {
  213. const match = String(firstWeekObj.zcrq).match(/(\d{4}-\d{2}-\d{2})/);
  214. if (match) return match[1];
  215. }
  216. } catch (e) {
  217. console.error(`JS: 获取开学日期失败: ${url}`);
  218. }
  219. }
  220. return null;
  221. }
  222. async function fetchAndParseCourses(academicYear, semesterCode) {
  223. const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=&kclxdm=`;
  224. // 与课程请求并行获取开学日期
  225. const semesterStartDatePromise = fetchSemesterStartDate(academicYear, semesterCode);
  226. const targetUrls = [
  227. "https://webapp.czimt.edu.cn/http/77726476706e69737468656265737421fae042d2242a65557d468aa2/kbcx/xskbcx_cxXsgrkb.html?vpn-12-o1-jwc.czmec.cn&gnmkdm=N2151",
  228. "http://jwc.czmec.cn/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151"
  229. ];
  230. for (const url of targetUrls) {
  231. try {
  232. const response = await fetch(url, {
  233. method: "POST",
  234. headers: {
  235. "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  236. },
  237. body: requestBody,
  238. credentials: "include"
  239. });
  240. if (response.ok) {
  241. const jsonText = await response.text();
  242. const jsonData = JSON.parse(jsonText);
  243. if (jsonData && jsonData.kbList) {
  244. const parsedCourses = parseJsonData(jsonData);
  245. if (parsedCourses.length > 0) {
  246. return {
  247. courses: parsedCourses,
  248. config: {
  249. semesterStartDate: await semesterStartDatePromise,
  250. semesterTotalWeeks: 20
  251. }
  252. };
  253. }
  254. }
  255. }
  256. } catch (e) {
  257. console.error(`Entry failed: ${url}`);
  258. }
  259. }
  260. window.shiguangBridge.showToast("未能获取课表数据,请检查网络环境或登录状态。");
  261. return null;
  262. }
  263. async function saveCourses(parsedCourses) {
  264. window.shiguangBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
  265. console.log(`JS: 尝试保存 ${parsedCourses.length} 门课程...`);
  266. try {
  267. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses, null, 2));
  268. console.log("JS: 课程保存成功!");
  269. return true;
  270. } catch (error) {
  271. window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
  272. console.error('JS: Save Courses Error:', error);
  273. return false;
  274. }
  275. }
  276. const TimeSlots = [
  277. { number: 1, startTime: "08:20", endTime: "09:00" },
  278. { number: 2, startTime: "09:05", endTime: "09:45" },
  279. { number: 3, startTime: "10:00", endTime: "10:40" },
  280. { number: 4, startTime: "10:45", endTime: "11:25" },
  281. { number: 5, startTime: "13:45", endTime: "14:25" },
  282. { number: 6, startTime: "14:30", endTime: "15:10" },
  283. { number: 7, startTime: "15:25", endTime: "16:05" },
  284. { number: 8, startTime: "16:10", endTime: "16:50" },
  285. { number: 9, startTime: "18:00", endTime: "18:40" },
  286. { number: 10, startTime: "18:45", endTime: "19:25" },
  287. { number: 11, startTime: "19:35", endTime: "20:15" },
  288. { number: 12, startTime: "20:20", endTime: "21:00" }
  289. ];
  290. async function importPresetTimeSlots(timeSlots) {
  291. console.log(`JS: 准备导入 ${timeSlots.length} 个预设时间段。`);
  292. if (timeSlots.length > 0) {
  293. window.shiguangBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
  294. try {
  295. await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  296. window.shiguangBridge.showToast("预设时间段导入成功!");
  297. console.log("JS: 预设时间段导入成功。");
  298. } catch (error) {
  299. window.shiguangBridge.showToast("导入时间段失败: " + error.message);
  300. console.error('JS: Save Time Slots Error:', error);
  301. }
  302. } else {
  303. window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
  304. console.warn("JS: 警告:传入时间段为空,未导入时间段信息。");
  305. }
  306. }
  307. async function runImportFlow() {
  308. const alertConfirmed = await promptUserToStart();
  309. if (!alertConfirmed) {
  310. window.shiguangBridge.showToast("用户取消了导入。");
  311. return;
  312. }
  313. const selection = await selectAcademicYearAndSemester();
  314. if (!selection) {
  315. window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
  316. return;
  317. }
  318. const { academicYear, semesterCode } = selection;
  319. console.log(`JS: 已选择学年: ${academicYear}, 学期代码: ${semesterCode}`);
  320. const result = await fetchAndParseCourses(academicYear, semesterCode);
  321. if (result === null) {
  322. console.log("JS: 课程获取或解析失败,流程终止。");
  323. return;
  324. }
  325. const { courses, config } = result;
  326. const timeSlotResult = await importPresetTimeSlots(TimeSlots);
  327. if (!timeSlotResult) {
  328. console.log("JS: 预设时间段导入失败或跳过,继续导入课程...");
  329. }
  330. await new Promise(resolve => setTimeout(resolve, 500));
  331. const saveResult = await saveCourses(courses);
  332. if (!saveResult) {
  333. console.log("JS: 课程保存失败,流程终止。");
  334. return;
  335. }
  336. try {
  337. await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  338. let configMsg = `课表配置更新成功!总周数:${config.semesterTotalWeeks}周。`;
  339. if (config.semesterStartDate) {
  340. configMsg += ` 开学日期:${config.semesterStartDate}`;
  341. }
  342. window.shiguangBridge.showToast(configMsg);
  343. } catch (error) {
  344. window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
  345. }
  346. window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
  347. console.log("JS: 整个导入流程执行完毕并成功。");
  348. window.shiguangBridge.notifyTaskCompletion();
  349. }
  350. runImportFlow();