hnie_01.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. // 湖南工程学院(hnie.edu.cn) 强智教务适配脚本
  2. // 双季作息:一个学期可能存在两种作息,用户手动选择
  3. // 年份输入验证
  4. window.validateYearInput = function(input) {
  5. return /^[0-9]{4}$/.test(input) ? false : "请输入四位数字的学年!";
  6. };
  7. // 解析周次字符串为数组
  8. function parseWeeks(weekStr) {
  9. const weeks = [];
  10. if (!weekStr) return weeks;
  11. const pureWeekData = weekStr.split('(')[0];
  12. pureWeekData.split(',').forEach(seg => {
  13. if (seg.includes('-')) {
  14. const [s, e] = seg.split('-').map(Number);
  15. if (!isNaN(s) && !isNaN(e)) {
  16. for (let i = s; i <= e; i++) weeks.push(i);
  17. }
  18. } else {
  19. const w = parseInt(seg);
  20. if (!isNaN(w)) weeks.push(w);
  21. }
  22. });
  23. return [...new Set(weeks)].sort((a, b) => a - b);
  24. }
  25. // 节次合并与去重
  26. function mergeAndDistinctCourses(courses) {
  27. if (courses.length <= 1) return courses;
  28. courses.sort((a, b) => {
  29. return a.name.localeCompare(b.name) ||
  30. a.day - b.day ||
  31. a.startSection - b.startSection ||
  32. a.weeks.join(',').localeCompare(b.weeks.join(','));
  33. });
  34. const merged = [];
  35. let current = courses[0];
  36. for (let i = 1; i < courses.length; i++) {
  37. const next = courses[i];
  38. const isSameCourse =
  39. current.name === next.name &&
  40. current.teacher === next.teacher &&
  41. current.position === next.position &&
  42. current.day === next.day &&
  43. current.weeks.join(',') === next.weeks.join(',');
  44. const isContinuous = current.endSection + 1 === next.startSection;
  45. if (isSameCourse && isContinuous) {
  46. current.endSection = next.endSection;
  47. } else if (isSameCourse && current.startSection === next.startSection && current.endSection === next.endSection) {
  48. continue;
  49. } else {
  50. merged.push(current);
  51. current = next;
  52. }
  53. }
  54. merged.push(current);
  55. return merged;
  56. }
  57. // 解析课程数据
  58. function parseTimetableToModel(doc) {
  59. const timetable = doc.getElementById('timetable');
  60. if (!timetable) return [];
  61. let rawCourses = [];
  62. const rows = Array.from(timetable.querySelectorAll('tr')).filter(r => r.querySelector('td'));
  63. rows.forEach(row => {
  64. const cells = row.querySelectorAll('td');
  65. cells.forEach((cell, dayIndex) => {
  66. const day = dayIndex + 1;
  67. const detailDivs = cell.querySelectorAll('div.kbcontent, div.kbcontent1');
  68. detailDivs.forEach(div => {
  69. const rawHtml = div.innerHTML.trim();
  70. if (!rawHtml || rawHtml === "&nbsp;" || div.innerText.trim().length < 2) return;
  71. const blocks = rawHtml.split(/---------------------|----------------------/);
  72. blocks.forEach(block => {
  73. if (!block.trim()) return;
  74. const tempDiv = document.createElement('div');
  75. tempDiv.innerHTML = block;
  76. let name = "";
  77. for (let node of tempDiv.childNodes) {
  78. if (node.nodeType === 3 && node.textContent.trim() !== "") {
  79. name = node.textContent.trim();
  80. break;
  81. }
  82. }
  83. if (!name) {
  84. const nameFont = tempDiv.querySelector('font:not([title])');
  85. if (nameFont) name = nameFont.innerText.trim();
  86. }
  87. const teacherRaw = tempDiv.querySelector('font[title="教师"]')?.innerText || "";
  88. const teacher = teacherRaw.replace("任课教师:", "").trim();
  89. const position = tempDiv.querySelector('font[title="教室"]')?.innerText || "未知地点";
  90. const weekStr = tempDiv.querySelector('font[title="周次(节次)"]')?.innerText || "";
  91. let startSection = 0;
  92. let endSection = 0;
  93. if (weekStr) {
  94. const sectionPart = weekStr.match(/\[(.*?)节\]/);
  95. if (sectionPart && sectionPart[1]) {
  96. const sections = sectionPart[1].split('-').map(Number).filter(n => !isNaN(n));
  97. if (sections.length > 0) {
  98. startSection = sections[0];
  99. endSection = sections[sections.length - 1];
  100. }
  101. }
  102. }
  103. if (name && startSection > 0) {
  104. rawCourses.push({
  105. "name": name,
  106. "teacher": teacher || "未知教师",
  107. "weeks": parseWeeks(weekStr),
  108. "position": position,
  109. "day": day,
  110. "startSection": startSection,
  111. "endSection": endSection
  112. });
  113. }
  114. });
  115. });
  116. });
  117. });
  118. return mergeAndDistinctCourses(rawCourses);
  119. }
  120. // 从教学周历解析开学日期和结束日期
  121. function parseWeekCalendar(html) {
  122. const parser = new DOMParser();
  123. const doc = parser.parseFromString(html, 'text/html');
  124. const table = doc.getElementById('kbtable');
  125. if (!table) return null;
  126. const rows = table.querySelectorAll('tr');
  127. let firstWeekMonday = null;
  128. let lastWeekSaturday = null;
  129. for (const row of rows) {
  130. const cells = row.querySelectorAll('td');
  131. if (cells.length < 2) continue;
  132. const firstCell = cells[0].innerText.trim();
  133. if (!/^\d+$/.test(firstCell)) continue;
  134. const weekNum = parseInt(firstCell);
  135. if (weekNum === 1) {
  136. // 第1周,找周一(索引2:周号0、周日1、周一2)
  137. if (cells.length > 2) {
  138. firstWeekMonday = cells[2].getAttribute('title');
  139. }
  140. }
  141. // 记录最后一周
  142. if (cells.length > 7) {
  143. lastWeekSaturday = cells[7].getAttribute('title');
  144. }
  145. }
  146. return { firstWeekMonday, lastWeekSaturday };
  147. }
  148. // 保存课表配置
  149. async function saveAppConfig(startDate) {
  150. const config = {
  151. "semesterTotalWeeks": 20,
  152. "firstDayOfWeek": 1,
  153. "semesterStartDate": startDate
  154. };
  155. return await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
  156. }
  157. // 双季作息时间表
  158. const winterSlots = [
  159. { "number": 1, "startTime": "08:00", "endTime": "08:45" },
  160. { "number": 2, "startTime": "08:55", "endTime": "09:40" },
  161. { "number": 3, "startTime": "10:10", "endTime": "10:55" },
  162. { "number": 4, "startTime": "11:05", "endTime": "11:50" },
  163. { "number": 5, "startTime": "14:00", "endTime": "14:45" },
  164. { "number": 6, "startTime": "14:55", "endTime": "15:40" },
  165. { "number": 7, "startTime": "16:10", "endTime": "16:55" },
  166. { "number": 8, "startTime": "17:05", "endTime": "17:50" },
  167. { "number": 9, "startTime": "19:00", "endTime": "19:45" },
  168. { "number": 10, "startTime": "19:55", "endTime": "20:40" },
  169. { "number": 11, "startTime": "20:50", "endTime": "21:35" }
  170. ];
  171. const summerSlots = [
  172. { "number": 1, "startTime": "08:00", "endTime": "08:45" },
  173. { "number": 2, "startTime": "08:55", "endTime": "09:40" },
  174. { "number": 3, "startTime": "10:10", "endTime": "10:55" },
  175. { "number": 4, "startTime": "11:05", "endTime": "11:50" },
  176. { "number": 5, "startTime": "14:30", "endTime": "15:15" },
  177. { "number": 6, "startTime": "15:25", "endTime": "16:10" },
  178. { "number": 7, "startTime": "16:40", "endTime": "17:25" },
  179. { "number": 8, "startTime": "17:35", "endTime": "18:20" },
  180. { "number": 9, "startTime": "19:30", "endTime": "20:15" },
  181. { "number": 10, "startTime": "20:25", "endTime": "21:10" },
  182. { "number": 11, "startTime": "21:20", "endTime": "22:05" }
  183. ];
  184. // 保存时间段(根据用户选择)
  185. async function saveAppTimeSlots(timeSlots) {
  186. return await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
  187. }
  188. // 流程编排
  189. async function runImportFlow() {
  190. try {
  191. const confirmed = await window.shiguangBridgePromise.showAlert("提示", "请确保已成功登录教务系统。是否开始导入?", "开始");
  192. if (!confirmed) return;
  193. // 选择学年
  194. const year = await window.shiguangBridgePromise.showPrompt("选择学年", "请输入要导入课程的起始学年(例如 2026-2027 应输入2026):", "", "validateYearInput");
  195. if (!year) return;
  196. // 选择学期
  197. const semesterIndex = await window.shiguangBridgePromise.showSingleSelection("选择学期", JSON.stringify(["第一学期", "第二学期"]), -1);
  198. if (semesterIndex === null) return;
  199. // 选择作息时间类型
  200. const scheduleIndex = await window.shiguangBridgePromise.showSingleSelection(
  201. "选择作息时间",
  202. JSON.stringify(["冬令时", "夏令时"]),
  203. -1
  204. );
  205. if (scheduleIndex === null) return;
  206. const semesterId = `${year}-${parseInt(year) + 1}-${semesterIndex + 1}`;
  207. window.shiguangBridge.showToast("正在获取学期日期...");
  208. // 请求教学周历获取开学日期
  209. let semesterStartDate = null;
  210. try {
  211. let calendarBody = `xnxq01id=${semesterId}`;
  212. for (let i = 1; i <= 20; i++) {
  213. calendarBody += `&xqt=${i}&xqt=${i}`;
  214. }
  215. const calendarResp = await fetch("/jsxsd/jxzl/jxzl_query", {
  216. method: "POST",
  217. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  218. body: calendarBody,
  219. credentials: "include"
  220. });
  221. const calendarHtml = await calendarResp.text();
  222. const calendarInfo = parseWeekCalendar(calendarHtml);
  223. if (calendarInfo && calendarInfo.firstWeekMonday) {
  224. // 转换格式:2026年09月07日 -> 2026-09-07
  225. const raw = calendarInfo.firstWeekMonday;
  226. const m = raw.match(/(\d{4})年(\d{2})月(\d{2})/);
  227. if (m) semesterStartDate = `${m[1]}-${m[2]}-${m[3]}`;
  228. window.shiguangBridge.showToast(`开学日期: ${semesterStartDate}`);
  229. }
  230. } catch (e) {
  231. console.error("获取学期日期失败:", e);
  232. }
  233. window.shiguangBridge.showToast("正在请求课程数据...");
  234. const response = await fetch("/jsxsd/xskb/xskb_list.do", {
  235. method: "POST",
  236. headers: { "Content-Type": "application/x-www-form-urlencoded" },
  237. body: `cj0701id=&zc=&demo=&xnxq01id=${semesterId}&sfFD=1&wkbkc=1`,
  238. credentials: "include"
  239. });
  240. const html = await response.text();
  241. const finalCourses = parseTimetableToModel(new DOMParser().parseFromString(html, "text/html"));
  242. if (finalCourses.length === 0) {
  243. window.shiguangBridge.showToast("未发现课程,请检查学期选择或登录状态。");
  244. return;
  245. }
  246. await saveAppConfig(semesterStartDate);
  247. const selectedSlots = scheduleIndex === 0 ? winterSlots : summerSlots;
  248. await saveAppTimeSlots(selectedSlots);
  249. await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(finalCourses));
  250. window.shiguangBridge.showToast(`成功导入 ${finalCourses.length} 门课程`);
  251. window.shiguangBridge.notifyTaskCompletion();
  252. } catch (error) {
  253. window.shiguangBridge.showToast("异常: " + error.message);
  254. }
  255. }
  256. runImportFlow();