Jelajahi Sumber

feat: 广东海洋大学教务适配优化 (#521)

Mccurtain 3 minggu lalu
induk
melakukan
3ac997b87e
1 mengubah file dengan 515 tambahan dan 217 penghapusan
  1. 515 217
      resources/GDOU/gdou.js

+ 515 - 217
resources/GDOU/gdou.js

@@ -1,71 +1,115 @@
 /**
 /**
- * 广东海洋大学教务适配
- * @date 2026-7-30
+ * 广东海洋大学教务课表导入适配
+ * @date 2026-08-27
  * @author Mccurtain
  * @author Mccurtain
- * @version 1.1
+ * @version 2.0
  */
  */
 
 
+(function () {
+
+// ==================== 常量 ====================
+
+// venues 为整栋楼使用特殊作息的楼名(包含匹配,如 "实验楼" 会命中 "实验楼301"、"网球场(实验楼东面)");
+// venuePatterns 为楼名简写正则(如海滨 "实"+房间号 = 实验楼简写,实506-1计算机(2)室);
+// outdoorKeywords 为特殊作息的室外场地关键词。
+
+const CAMPUS_CONFIGS = [
+    {
+        id: "huguang",
+        label: "湖光校区",
+        venues: ["广学楼", "明德楼"],
+        venuePatterns: [],
+        outdoorKeywords: []
+    },
+    {
+        id: "haibin",
+        label: "海滨校区",
+        venues: ["实验楼"],
+        venuePatterns: [{ name: "实验楼简写", pattern: /^实\d/ }],
+        outdoorKeywords: ["球场", "东面", "南面", "西面", "北面"]
+    }
+];
+
+// 全校统一作息时间(1-10 节),未指定特殊作息的教室使用
+const TimeSlots = [
+    { number: 1, startTime: "08:10", endTime: "08:55" },
+    { number: 2, startTime: "09:00", endTime: "09:45" },
+    { number: 3, startTime: "10:15", endTime: "11:00" },
+    { number: 4, startTime: "11:05", endTime: "11:50" },
+    { number: 5, startTime: "14:30", endTime: "15:15" },
+    { number: 6, startTime: "15:20", endTime: "16:05" },
+    { number: 7, startTime: "16:30", endTime: "17:15" },
+    { number: 8, startTime: "17:20", endTime: "18:05" },
+    { number: 9, startTime: "19:30", endTime: "20:15" },
+    { number: 10, startTime: "20:25", endTime: "21:10" }
+];
+
+// 指定楼/室外场地的特殊作息时间块(连堂)
+const SPECIAL_TIME_BLOCKS = [
+    { startSection: 3, endSection: 4, startTime: "10:05", endTime: "11:35" },
+    { startSection: 7, endSection: 8, startTime: "16:25", endTime: "17:50" }
+];
+
+// ==================== 解析函数 ====================
+
 /**
 /**
- * 解析周次字符串,处理单双周和周次范围。
- * 兼容格式:"1-16周"、"6周"、"1-8周(单)"、"1-10周(双)"、"1-5周,9周"
+ * 将周次字符串展开为具体周次数组
+ * 支持范围(如 1-16周)、单周(如 6周)、单双周(如 1-8周(单))、
+ * 以及逗号分隔的多种写法混合,全角逗号也会被兼容
  */
  */
 function parseWeeks(weekStr) {
 function parseWeeks(weekStr) {
     if (!weekStr) return [];
     if (!weekStr) return [];
 
 
-    const normalizedWeekStr = String(weekStr).replace(/,/g, ',');
-    const weekSets = normalizedWeekStr.split(',');
-    let weeks = [];
+    const groups = String(weekStr).replace(/,/g, ',').split(',');
+    const weeks = [];
 
 
-    for (const set of weekSets) {
-        const trimmedSet = set.trim();
+    for (const group of groups) {
+        const item = group.trim();
 
 
-        const rangeMatch = trimmedSet.match(/(\d+)\s*-\s*(\d+)\s*周?/);
-        const singleMatch = trimmedSet.match(/^(\d+)\s*周?/); // 匹配单个周次
+        // 先尝试匹配 "起-止周",再尝试匹配单个周次
+        const rangeMatch = item.match(/(\d+)\s*-\s*(\d+)\s*周?/);
+        const singleMatch = item.match(/^(\d+)\s*周?/);
 
 
         let start = 0;
         let start = 0;
         let end = 0;
         let end = 0;
-        let processed = false;
+        let matched = false;
 
 
-        if (rangeMatch) { // 范围, 如 "1-5周"
+        if (rangeMatch) {
             start = Number(rangeMatch[1]);
             start = Number(rangeMatch[1]);
             end = Number(rangeMatch[2]);
             end = Number(rangeMatch[2]);
-            processed = true;
-        } else if (singleMatch) { // 单个周, 如 "6周"
+            matched = true;
+        } else if (singleMatch) {
             start = end = Number(singleMatch[1]);
             start = end = Number(singleMatch[1]);
-            processed = true;
+            matched = true;
         }
         }
 
 
-        if (processed && start >= 1 && end >= start) {
-            // 确定单双周
-            const isSingle = trimmedSet.includes('(单)');
-            const isDouble = trimmedSet.includes('(双)');
+        if (matched && start >= 1 && end >= start) {
+            const isOddOnly = item.includes('(单)');
+            const isEvenOnly = item.includes('(双)');
 
 
             for (let w = start; w <= end; w++) {
             for (let w = start; w <= end; w++) {
-                if (isSingle && w % 2 === 0) continue; // 单周跳过偶数
-                if (isDouble && w % 2 !== 0) continue; // 双周跳过奇数
+                if (isOddOnly && w % 2 === 0) continue; // 单周:跳过偶数周
+                if (isEvenOnly && w % 2 !== 0) continue; // 双周:跳过奇数周
                 weeks.push(w);
                 weeks.push(w);
             }
             }
         }
         }
     }
     }
 
 
-    // 去重并排序
     return [...new Set(weeks)].sort((a, b) => a - b);
     return [...new Set(weeks)].sort((a, b) => a - b);
 }
 }
 
 
 /**
 /**
- * 解析节次字符串,例如 "1-2"、"1-2节" 或单节 "3"。
- * 返回 null 表示接口返回了无法识别的节次格式。
+ * 解析节次字段,如 "1-2"、"3"、"1-2节",得到起止节次
+ * 格式无法识别或数值不合法时返回 null
  */
  */
 function parseSectionRange(sectionStr) {
 function parseSectionRange(sectionStr) {
-    const sectionText = sectionStr == null ? '' : String(sectionStr);
-    const sectionMatch = sectionText.match(/^\s*(?:第)?(\d+)\s*(?:-\s*(\d+))?\s*节?\s*$/);
+    const text = sectionStr == null ? '' : String(sectionStr);
+    const match = text.match(/^\s*(?:第)?(\d+)\s*(?:-\s*(\d+))?\s*节?\s*$/);
 
 
-    if (!sectionMatch) {
-        return null;
-    }
+    if (!match) return null;
 
 
-    const startSection = Number(sectionMatch[1]);
-    const endSection = Number(sectionMatch[2] || sectionMatch[1]);
+    const startSection = Number(match[1]);
+    const endSection = Number(match[2] || match[1]);
 
 
     if (!Number.isInteger(startSection) || !Number.isInteger(endSection) ||
     if (!Number.isInteger(startSection) || !Number.isInteger(endSection) ||
         startSection < 1 || endSection < startSection) {
         startSection < 1 || endSection < startSection) {
@@ -75,293 +119,547 @@ function parseSectionRange(sectionStr) {
     return { startSection, endSection };
     return { startSection, endSection };
 }
 }
 
 
+// 提前公选课课程名
+function normalizeCourseName(rawName) {
+    const name = String(rawName).trim();
+    if (!name) return name;
+
+    const match = name.match(/^[((]([^()()]+)[))]\s*/);
+    if (!match) return name;
+
+    const rest = name.slice(match[0].length);
+    if (!rest) return name;
+
+    return `${rest}(${match[1]})`;
+}
+
 /**
 /**
- * 解析正方 v9 课表查询接口返回的 JSON 数据。
+ * 节次与周次合并去重函数
+ * @param {Array<Object>} courses 原始解析课程数组
+ * @returns {Array<Object>} 合并去重后的课程数组
  */
  */
-function parseJsonData(jsonData) {
-    console.log("JS: parseJsonData 正在解析 JSON 数据...");
+function mergeAndDistinctCourses(courses) {
+    if (!Array.isArray(courses) || courses.length <= 1) return courses;
+
+    // 规范化数据,周次统一排序,便于比较
+    const list = courses.map(c => ({
+        ...c,
+        name: c.name || '',
+        teacher: c.teacher || '',
+        position: c.position || '',
+        weeks: Array.isArray(c.weeks) ? [...c.weeks].sort((a, b) => a - b) : []
+    }));
+
+    // 第一步:按课程、周次排序后合并连续节次,同时剔除完全重复项
+    list.sort((a, b) =>
+        a.name.localeCompare(b.name) ||
+        a.teacher.localeCompare(b.teacher) ||
+        a.position.localeCompare(b.position) ||
+        (a.day || 0) - (b.day || 0) ||
+        a.weeks.join(',').localeCompare(b.weeks.join(',')) ||
+        (a.startSection || 0) - (b.startSection || 0)
+    );
 
 
-    // 正方 v9 个人课表数据放在 kbList 字段中
-    if (!jsonData || !Array.isArray(jsonData.kbList)) {
-        console.warn("JS: JSON 数据结构错误或缺少 kbList 字段。");
-        return [];
-    }
+    const step1 = [];
+    let current = list[0];
+
+    for (let i = 1; i < list.length; i++) {
+        const next = list[i];
 
 
-    const rawCourseList = jsonData.kbList;
-    const finalCourseList = [];
+        const isSameCourse =
+            current.name === next.name &&
+            current.teacher === next.teacher &&
+            current.position === next.position &&
+            current.day === next.day &&
+            current.weeks.join(',') === next.weeks.join(',');
 
 
-    for (const rawCourse of rawCourseList) {
-        if (!rawCourse || typeof rawCourse !== 'object') {
+        if (isSameCourse && current.endSection + 1 === next.startSection) {
+            // 节次紧邻,延长结束节次:1-2 节 + 3-4 节 -> 1-4 节
+            current.endSection = next.endSection;
+        } else if (isSameCourse && current.startSection === next.startSection && current.endSection === next.endSection) {
+            // 完全重复的记录,跳过
             continue;
             continue;
+        } else {
+            step1.push(current);
+            current = next;
         }
         }
+    }
+    step1.push(current);
+
+    // 第二步:按课程、节次排序后合并相同节次的周次
+    step1.sort((a, b) =>
+        a.name.localeCompare(b.name) ||
+        a.teacher.localeCompare(b.teacher) ||
+        a.position.localeCompare(b.position) ||
+        (a.day || 0) - (b.day || 0) ||
+        (a.startSection || 0) - (b.startSection || 0) ||
+        (a.endSection || 0) - (b.endSection || 0)
+    );
 
 
-        // 课程名、星期、节次和周次是解析所必需的;教师或教室为空时仍保留课程。
-        if (!rawCourse.kcmc || rawCourse.xqj == null ||
-            rawCourse.jcs == null || rawCourse.zcd == null) {
-            continue;
+    const step2 = [];
+    let cur = step1[0];
+
+    for (let i = 1; i < step1.length; i++) {
+        const nxt = step1[i];
+
+        const isSameSection =
+            cur.name === nxt.name &&
+            cur.teacher === nxt.teacher &&
+            cur.position === nxt.position &&
+            cur.day === nxt.day &&
+            cur.startSection === nxt.startSection &&
+            cur.endSection === nxt.endSection;
+
+        if (isSameSection) {
+            // 周次取并集:1-8 周 + 9-16 周 -> 1-16 周
+            cur.weeks = Array.from(new Set([...cur.weeks, ...nxt.weeks])).sort((a, b) => a - b);
+        } else {
+            step2.push(cur);
+            cur = nxt;
         }
         }
+    }
+    step2.push(cur);
 
 
-        const weeksArray = parseWeeks(rawCourse.zcd);
+    return step2;
+}
 
 
-        // 周次有效性检查
-        if (weeksArray.length === 0) {
-            continue;
-        }
+// ==================== 特殊作息处理 ====================
 
 
-        const sectionRange = parseSectionRange(rawCourse.jcs);
-        if (!sectionRange) {
-            console.warn(`JS: 跳过无法解析节次的课程:${rawCourse.kcmc}`);
-            continue;
-        }
+/**
+ * 判断位置是否命中特殊场地(指定楼或室外场地),返回命中的类型与关键词
+ * 楼名与室外关键词取并集,包含任一即可;命中者打标特殊作息
+ * @returns {{type: 'venue'|'outdoor', key: string}|null}
+ */
+function matchesSpecialVenue(positionText, campusConfig) {
+    const venueHit = campusConfig.venues.find(venue => positionText.includes(venue));
+    if (venueHit) return { type: 'venue', key: venueHit };
+    const patternHit = (campusConfig.venuePatterns || []).find(p => p.pattern.test(positionText));
+    if (patternHit) return { type: 'venue', key: patternHit.name };
+    const outdoorHit = campusConfig.outdoorKeywords.find(keyword => positionText.includes(keyword));
+    if (outdoorHit) return { type: 'outdoor', key: outdoorHit };
+    return null;
+}
 
 
-        const day = Number(rawCourse.xqj); // xqj: 星期几 (周一为1, 周日为7)
+/**
+ * 判断课程是否命中特殊作息(正向策略)
+ * 命中指定楼/室外场地的课程,在节次恰为特殊时间块(3-4/7-8 节)时打标特殊时间;
+ * 其他普通教室不打标,使用 TimeSlots 全校统一作息。
+ * 返回对象附带 reason 判定原因,供内部诊断与本地验证脚本使用(不写入导出课程)。
+ */
+function getCustomTime(position, startSection, endSection, campusConfig) {
+    const positionText = position == null ? '' : String(position);
+    const hit = matchesSpecialVenue(positionText, campusConfig);
+    if (!hit) return { marked: false, reason: 'no-block' };
 
 
-        // 数字有效性检查
-        if (isNaN(day) || day < 1 || day > 7) {
-            continue;
-        }
+    const block = SPECIAL_TIME_BLOCKS.find(
+        b => b.startSection === startSection && b.endSection === endSection
+    );
+    if (block) return { marked: true, startTime: block.startTime, endTime: block.endTime, reason: `special-${hit.type}:${hit.key}` };
+    return { marked: false, reason: `special-${hit.type}:${hit.key}-no-block` };
+}
+
+// ==================== 数据解析 ====================
+
+/**
+ * 解析正方 v9 课表接口返回的 JSON,提取有效课程
+ * 数据位于 kbList 字段;课程名/星期/节次/周次缺失或不合法的记录会被跳过,
+ * 教师、教室允许为空
+ */
+function parseJsonData(jsonData, campusConfig) {
+    if (!jsonData || !Array.isArray(jsonData.kbList)) return [];
+
+    const courses = [];
+
+    for (const raw of jsonData.kbList) {
+        if (!raw || typeof raw !== 'object') continue;
+        if (!raw.kcmc || raw.xqj == null || raw.jcs == null || raw.zcd == null) continue;
+
+        const weeks = parseWeeks(raw.zcd);
+        if (weeks.length === 0) continue;
+
+        const sectionRange = parseSectionRange(raw.jcs);
+        if (!sectionRange) continue;
+
+        const day = Number(raw.xqj); // 1=周一 ... 7=周日
+        if (isNaN(day) || day < 1 || day > 7) continue;
+
+        // 直接基于原始接口字段 cdmc 构造课程位置
+        const position = raw.cdmc == null ? '' : String(raw.cdmc).trim();
 
 
         const course = {
         const course = {
-            name: String(rawCourse.kcmc).trim(),
-            teacher: rawCourse.xm == null ? '' : String(rawCourse.xm).trim(),
-            position: rawCourse.cdmc == null ? '' : String(rawCourse.cdmc).trim(),
-            day: day,
+            name: normalizeCourseName(raw.kcmc),
+            teacher: raw.xm == null ? '' : String(raw.xm).trim(),
+            position,
+            day,
             startSection: sectionRange.startSection,
             startSection: sectionRange.startSection,
             endSection: sectionRange.endSection,
             endSection: sectionRange.endSection,
-            weeks: weeksArray
+            weeks
         };
         };
 
 
-        finalCourseList.push(course);
-    }
+        // 边解析边判断:直接对原始教室字段 cdmc 判断是否命中特殊作息,
+        // 命中则在写入课程对象的同时打好 isCustomTime 标记,App 将优先显示自定义时间
+        const customTime = getCustomTime(position, course.startSection, course.endSection, campusConfig);
+        if (customTime.marked) {
+            course.isCustomTime = true;
+            course.customStartTime = customTime.startTime;
+            course.customEndTime = customTime.endTime;
+        }
 
 
-    finalCourseList.sort((a, b) =>
-        a.day - b.day ||
-        a.startSection - b.startSection ||
-        a.name.localeCompare(b.name)
-    );
+        courses.push(course);
+    }
 
 
-    console.log(`JS: JSON 数据解析完成,共找到 ${finalCourseList.length} 门课程。`);
-    return finalCourseList;
+    const mergedCourses = mergeAndDistinctCourses(courses);
+
+    // 合并可能改变节次区间(如 1-2 节 + 3-4 节 -> 1-4 节),对已打标课程做最终校验:
+    // 合并后的区间不再精确命中特殊时间块时,撤销打标,避免特殊时间被错误扩散
+    return mergedCourses.map(course => {
+        if (!course.isCustomTime) return course;
+        const customTime = getCustomTime(course.position, course.startSection, course.endSection, campusConfig);
+        if (!customTime.marked) {
+            const plain = { ...course };
+            delete plain.isCustomTime;
+            delete plain.customStartTime;
+            delete plain.customEndTime;
+            return plain;
+        }
+        return course;
+    });
 }
 }
 
 
+// ==================== 日期工具 ====================
+
 /**
 /**
- * showPrompt 的校验函数:限定四位数字学年。
+ * 把教务返回的日期字段规范为 yyyy-MM-dd
+ * 兼容 "-"、"."、"/" 以及中文"年月日"等分隔写法
  */
  */
-function validateYearInput(input) {
-    console.log("JS: validateYearInput 被调用,输入: " + input);
-    if (/^[0-9]{4}$/.test(input)) {
-        console.log("JS: validateYearInput 验证通过。");
-        return false;
-    } else {
-        console.log("JS: validateYearInput 验证失败。");
-        return "请输入四位数字的学年!";
-    }
+function normalizeStartDate(value) {
+    const match = String(value || "").match(/(\d{4})[-\/.年](\d{1,2})[-\/.月](\d{1,2})/);
+    if (!match) return null;
+    return `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}`;
 }
 }
 
 
 /**
 /**
- * 根据当前日期推断学年起始年份。
- * 中国高校通常在 9 月开始新学年,因此 1-8 月默认使用上一年。
+ * 在校历响应中查找第 1 周开学日期
+ * 兼容顶层数组、data/list/rows 等包装对象,以及 zrq/zcrq/rq/ksrq 字段
  */
  */
-function getDefaultAcademicYear(date = new Date()) {
-    const currentYear = date.getFullYear();
-    const academicYearStart = date.getMonth() >= 8 ? currentYear : currentYear - 1;
-    return academicYearStart.toString();
-}
+function findSemesterStartDate(value) {
+    if (value == null) return null;
+
+    if (typeof value !== "object") return normalizeStartDate(value);
+
+    if (Array.isArray(value)) {
+        const firstWeek = value.find(item =>
+            item && typeof item === "object" &&
+            (String(item.zs) === "1" || String(item.zsmc) === "1")
+        ) || value[0];
+        const found = findSemesterStartDate(firstWeek);
+        if (found) return found;
+
+        for (const item of value) {
+            const date = findSemesterStartDate(item);
+            if (date) return date;
+        }
+        return null;
+    }
 
 
-async function promptUserToStart() {
-    console.log("JS: 流程开始:显示公告。");
-    return await window.shiguangBridgePromise.showAlert(
-        "广东海洋大学教务系统课表导入",
-        "导入前请确保您已在浏览器中成功登录广东海洋大学教务系统(jw.gdou.edu.cn)。\n本脚本将通过接口直接获取课表,无需停留在特定页面。",
-        "好的,开始导入"
-    );
-}
+    for (const field of ["zrq", "zcrq", "rq", "ksrq"]) {
+        const date = normalizeStartDate(value[field]);
+        if (date) return date;
+    }
 
 
-async function getAcademicYear() {
-    const currentYear = getDefaultAcademicYear();
-    console.log("JS: 提示用户输入学年。");
-    return await window.shiguangBridgePromise.showPrompt(
-        "选择学年",
-        "请输入要导入课程的起始学年(例如 2025-2026 应输入 2025):",
-        currentYear,
-        "validateYearInput"
-    );
-}
+    for (const item of Object.values(value)) {
+        const date = findSemesterStartDate(item);
+        if (date) return date;
+    }
 
 
-async function selectSemester() {
-    const semesters = ["第一学期", "第二学期"];
-    console.log("JS: 提示用户选择学期。");
-    const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
-        "选择学期",
-        JSON.stringify(semesters),
-        0
-    );
-    return semesterIndex;
+    return null;
 }
 }
 
 
+// ==================== 教务接口 ====================
+
 /**
 /**
- * 将选择索引转换为正方教务接口所需的学期码。
- * 正方 v9:第一学期 = "3",第二学期 = "12"
+ * 读取课表查询页里的学年/学期下拉选项
+ * 成功返回 { yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex };
+ * 读取失败返回 null,由调用方回退到默认值
  */
  */
-function getSemesterCode(semesterIndex) {
-    return semesterIndex === 0 ? "3" : "12";
+async function fetchAcademicOptions() {
+    const url = "https://jw.gdou.edu.cn/kbcx/xskbcx_cxXskbcxIndex.html?gnmkdm=N2151&layout=default";
+
+    try {
+        const response = await fetch(url, { method: "GET", credentials: "include" });
+        if (!response.ok) return null;
+
+        const doc = new DOMParser().parseFromString(await response.text(), "text/html");
+
+        // 解析单个下拉框;默认选中项优先跟随 select 当前值,其次取 selected 属性
+        const readSelect = (select) => {
+            if (!select) return null;
+            const options = Array.from(select.querySelectorAll("option"))
+                .map(opt => ({ value: opt.value, text: opt.textContent.trim() || opt.value }))
+                .filter(opt => opt.value !== "");
+            if (options.length === 0) return null;
+            const valueIndex = options.findIndex(opt => opt.value === select.value);
+            const selectedIndex = options.findIndex(opt => opt.selected);
+            return { options, defaultIndex: valueIndex !== -1 ? valueIndex : Math.max(0, selectedIndex) };
+        };
+
+        const yearData = readSelect(doc.querySelector("#xnm"));
+        const semesterData = readSelect(doc.querySelector("#xqm"));
+        if (!yearData || !semesterData) return null;
+
+        return {
+            yearOptions: yearData.options,
+            semesterOptions: semesterData.options,
+            defaultYearIndex: yearData.defaultIndex,
+            defaultSemesterIndex: semesterData.defaultIndex
+        };
+    } catch (e) {
+        return null;
+    }
 }
 }
 
 
 /**
 /**
- * 请求正方 v9 课表接口并解析课程数据。
+ * 查询指定学期的周次安排,取出第 1 周的日期作为开学日期,并返回该学期总周数
+ * 接口失败时返回 null,不影响主流程
  */
  */
-async function fetchAndParseCourses(academicYear, semesterIndex) {
-    const semesterCode = getSemesterCode(semesterIndex);
-    const requestBody = `xnm=${academicYear}&xqm=${semesterCode}&kzlx=ck&xsdm=&kclbdm=`;
-
-    // 广东海洋大学正方教务 v9 个人课表查询接口
-    const targetUrl = "https://jw.gdou.edu.cn/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151";
+async function fetchSemesterInfo(academicYear, semesterCode) {
+    const url = "https://jw.gdou.edu.cn/kbcx/xskbcxZccx_cxZcByXnxq.html?gnmkdm=N2154";
+    const body = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}`;
 
 
     try {
     try {
-        const response = await fetch(targetUrl, {
+        const response = await fetch(url, {
             method: "POST",
             method: "POST",
             headers: {
             headers: {
-                "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
+                "accept": "application/json, text/javascript, */*; q=0.01",
+                "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
+                "x-requested-with": "XMLHttpRequest"
             },
             },
-            body: requestBody,
+            body,
             credentials: "include"
             credentials: "include"
         });
         });
 
 
-        if (!response.ok) {
-            window.shiguangBridge.showToast(`课表请求失败:HTTP ${response.status}`);
-            console.error(`JS: 接口返回非 200 状态码:${response.status}`);
-            return null;
-        }
+        if (!response.ok) return null;
 
 
-        const jsonText = await response.text();
-        const jsonData = JSON.parse(jsonText);
+        const weeks = await response.json();
+        if (!Array.isArray(weeks) || weeks.length === 0) return null;
 
 
-        if (!jsonData || !Array.isArray(jsonData.kbList) || jsonData.kbList.length === 0) {
-            window.shiguangBridge.showToast("未查询到课表数据,请检查学年/学期是否选择正确,或确认已登录教务系统。");
+        return {
+            startDate: findSemesterStartDate(weeks),
+            totalWeeks: weeks.length
+        };
+    } catch (e) {
+        return null;
+    }
+}
+
+/**
+ * 请求课表接口并解析课程,同时并行获取学期信息
+ * 成功返回 { courses, config },失败返回 null
+ */
+async function fetchAndParseCourses(academicYear, semesterCode, campusConfig) {
+    const body = `xnm=${encodeURIComponent(academicYear)}&xqm=${encodeURIComponent(semesterCode)}&kzlx=ck&xsdm=&kclbdm=`;
+    const courseUrl = "https://jw.gdou.edu.cn/kbcx/xskbcx_cxXsgrkb.html?gnmkdm=N2151";
+
+    const [courseResponse, semesterInfo] = await Promise.all([
+        fetch(courseUrl, {
+            method: "POST",
+            headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
+            body,
+            credentials: "include"
+        }),
+        fetchSemesterInfo(academicYear, semesterCode)
+    ]);
+
+    try {
+        if (!courseResponse.ok) {
+            window.shiguangBridge.showToast(`课表请求失败:HTTP ${courseResponse.status}`);
             return null;
             return null;
         }
         }
 
 
-        const parsedCourses = parseJsonData(jsonData);
-        if (parsedCourses.length === 0) {
-            window.shiguangBridge.showToast("课表数据为空或解析失败,请确认所选学年学期。");
+        const courses = parseJsonData(JSON.parse(await courseResponse.text()), campusConfig);
+
+        if (courses.length === 0) {
+            window.shiguangBridge.showToast("未查询到课表数据,请检查学年/学期选择或登录状态。");
             return null;
             return null;
         }
         }
 
 
+        // 总周数取接口返回值与课程最大周次中的较大者,保证不截断课表
+        const maxCourseWeek = courses.reduce((max, c) => Math.max(max, ...c.weeks), 0);
+
         return {
         return {
-            courses: parsedCourses,
-            // CourseConfigJsonModel(wiki 1.3):所有字段可选,未提供则用默认值。
-            // GDOU 各节课间隔不统一,因此用 TimeSlot 节次表达时间,此处仅设置总周数。
+            courses,
             config: {
             config: {
-                semesterStartDate: null,       // 未提供校历日期,App 不会按日期计算当前周
-                semesterTotalWeeks: 20          // 本学期总周数
+                semesterStartDate: semesterInfo ? semesterInfo.startDate : null,
+                semesterTotalWeeks: Math.max(maxCourseWeek, semesterInfo ? semesterInfo.totalWeeks : 20)
             }
             }
         };
         };
     } catch (e) {
     } catch (e) {
-        console.error("JS: 获取课表失败:", e);
-        window.shiguangBridge.showToast("获取课表失败,请确认已登录教务系统且网络可访问 jw.gdou.edu.cn。");
+        window.shiguangBridge.showToast("获取课表失败,请确认已登录且网络可访问 jw.gdou.edu.cn。");
         return null;
         return null;
     }
     }
 }
 }
 
 
-async function saveCourses(parsedCourses) {
-    window.shiguangBridge.showToast(`正在保存 ${parsedCourses.length} 门课程...`);
-    console.log(`JS: 尝试保存 ${parsedCourses.length} 门课程...`);
+// ==================== 交互 ====================
+
+/**
+ * 按当前月份推断学年起始年份:9 月及以后属于新学年,其余月份沿用上一学年
+ */
+function getDefaultAcademicYear(date = new Date()) {
+    const currentYear = date.getFullYear();
+    return (date.getMonth() >= 8 ? currentYear : currentYear - 1).toString();
+}
+
+/**
+ * 弹出导入确认提示,说明使用前提
+ */
+async function promptUserToStart() {
+    return await window.shiguangBridgePromise.showAlert(
+        "广东海洋大学教务系统课表导入",
+        "导入前请确认已在浏览器中登录教务系统(jw.gdou.edu.cn)。\n脚本将通过接口直接获取课表,无需停留在特定页面。",
+        "好的,开始导入"
+    );
+}
+
+/**
+ * 弹出校区选择框,决定使用哪套特殊作息规则
+ * 取消返回 null,由调用方终止流程
+ */
+async function selectCampus() {
+    const campusIndex = await window.shiguangBridgePromise.showSingleSelection(
+        "选择校区",
+        JSON.stringify(CAMPUS_CONFIGS.map(item => item.label)),
+        0
+    );
+    if (campusIndex === null || campusIndex === -1) return null;
+    return CAMPUS_CONFIGS[campusIndex];
+}
+
+/**
+ * 依次弹出学年、学期选择框
+ * 选项优先来自教务系统;若读取失败,则按当前月份给出默认学年,
+ * 学期码(3=第一学期,12=第二学期)
+ */
+async function selectAcademicYearAndSemester() {
+    const options = await fetchAcademicOptions();
+
+    let yearOptions;
+    let semesterOptions;
+    let defaultYearIndex;
+    let defaultSemesterIndex;
+
+    if (options) {
+        ({ yearOptions, semesterOptions, defaultYearIndex, defaultSemesterIndex } = options);
+    } else {
+        const year = getDefaultAcademicYear();
+        const isFirstSemester = new Date().getMonth() >= 8;
+        yearOptions = [{ value: year, text: `${year}-${Number(year) + 1}` }];
+        semesterOptions = [
+            { value: "3", text: "第一学期" },
+            { value: "12", text: "第二学期" }
+        ];
+        defaultYearIndex = 0;
+        defaultSemesterIndex = isFirstSemester ? 0 : 1;
+        window.shiguangBridge.showToast("未读取到教务系统学年学期选项,已使用默认值,请核对。");
+    }
+
+    const yearIndex = await window.shiguangBridgePromise.showSingleSelection(
+        "选择学年",
+        JSON.stringify(yearOptions.map(item => item.text)),
+        defaultYearIndex
+    );
+    if (yearIndex === null || yearIndex === -1) return null;
+
+    const semesterIndex = await window.shiguangBridgePromise.showSingleSelection(
+        "选择学期",
+        JSON.stringify(semesterOptions.map(item => item.text)),
+        defaultSemesterIndex
+    );
+    if (semesterIndex === null || semesterIndex === -1) return null;
+
+    return {
+        academicYear: yearOptions[yearIndex].value,
+        semesterCode: semesterOptions[semesterIndex].value
+    };
+}
+
+// ==================== 保存 ====================
+
+async function saveCourses(courses) {
     try {
     try {
-        await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(parsedCourses, null, 2));
-        console.log("JS: 课程保存成功!");
+        await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
         return true;
         return true;
     } catch (error) {
     } catch (error) {
         window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
         window.shiguangBridge.showToast(`课程保存失败: ${error.message}`);
-        console.error('JS: Save Courses Error:', error);
         return false;
         return false;
     }
     }
 }
 }
 
 
-// 广东海洋大学通用上课时间
-const TimeSlots = [
-    { number: 1, startTime: "08:10", endTime: "08:55" },
-    { number: 2, startTime: "09:00", endTime: "09:45" },
-    { number: 3, startTime: "10:15", endTime: "11:00" },
-    { number: 4, startTime: "11:05", endTime: "11:50" },
-    { number: 5, startTime: "14:30", endTime: "15:15" },
-    { number: 6, startTime: "15:20", endTime: "16:05" },
-    { number: 7, startTime: "16:30", endTime: "17:15" },
-    { number: 8, startTime: "17:20", endTime: "18:05" },
-    { number: 9, startTime: "19:30", endTime: "20:15" },
-    { number: 10, startTime: "20:25", endTime: "21:10" }
-];
-
+/**
+ * 将预设作息时间导入 App
+ */
 async function importPresetTimeSlots(timeSlots) {
 async function importPresetTimeSlots(timeSlots) {
-    console.log(`JS: 准备导入 ${timeSlots.length} 个预设时间段。`);
-    if (timeSlots.length > 0) {
-        window.shiguangBridge.showToast(`正在导入 ${timeSlots.length} 个预设时间段...`);
-        try {
-            await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
-            window.shiguangBridge.showToast("预设时间段导入成功!");
-            console.log("JS: 预设时间段导入成功。");
-        } catch (error) {
-            window.shiguangBridge.showToast("导入时间段失败: " + error.message);
-            console.error('JS: Save Time Slots Error:', error);
-        }
-    } else {
+    if (timeSlots.length === 0) {
         window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
         window.shiguangBridge.showToast("警告:时间段为空,未导入时间段信息。");
-        console.warn("JS: 警告:传入时间段为空,未导入时间段信息。");
+        return;
+    }
+
+    try {
+        await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(timeSlots));
+        window.shiguangBridge.showToast("预设时间段导入成功!");
+    } catch (error) {
+        window.shiguangBridge.showToast("导入时间段失败: " + error.message);
     }
     }
 }
 }
 
 
+// ==================== 主流程 ====================
+
 async function runImportFlow() {
 async function runImportFlow() {
-    const alertConfirmed = await promptUserToStart();
-    if (!alertConfirmed) {
+    // 1. 确认导入
+    const confirmed = await promptUserToStart();
+    if (!confirmed) {
         window.shiguangBridge.showToast("用户取消了导入。");
         window.shiguangBridge.showToast("用户取消了导入。");
-        console.log("JS: 用户取消了导入流程。");
         return;
         return;
     }
     }
 
 
-    const academicYear = await getAcademicYear();
-    if (academicYear === null) {
-        window.shiguangBridge.showToast("导入已取消。");
-        console.log("JS: 获取学年失败/取消,流程终止。");
+    // 2. 选择学年学期
+    const selection = await selectAcademicYearAndSemester();
+    if (!selection) {
+        window.shiguangBridge.showToast("未选择学年学期,导入流程终止。");
         return;
         return;
     }
     }
-    console.log(`JS: 已选择学年: ${academicYear}`);
 
 
-    const semesterIndex = await selectSemester();
-    if (semesterIndex === null || semesterIndex === -1) {
-        window.shiguangBridge.showToast("导入已取消。");
-        console.log("JS: 选择学期失败/取消,流程终止。");
+    // 3. 选择校区(决定特殊作息规则)
+    const campusConfig = await selectCampus();
+    if (!campusConfig) {
+        window.shiguangBridge.showToast("未选择校区,导入流程终止。");
         return;
         return;
     }
     }
-    console.log(`JS: 已选择学期索引: ${semesterIndex}`);
 
 
-    const result = await fetchAndParseCourses(academicYear, semesterIndex);
-    if (result === null) {
-        console.log("JS: 课程获取或解析失败,流程终止。");
-        return;
-    }
+    // 4. 拉取并解析课程
+    const result = await fetchAndParseCourses(selection.academicYear, selection.semesterCode, campusConfig);
+    if (result === null) return;
     const { courses, config } = result;
     const { courses, config } = result;
 
 
-    const saveResult = await saveCourses(courses);
-    if (!saveResult) {
-        console.log("JS: 课程保存失败,流程终止。");
-        return;
-    }
+    // 5. 保存课程
+    if (!(await saveCourses(courses))) return;
 
 
+    // 6. 保存课表配置(开学日期、总周数)
     try {
     try {
         await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
         await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
-        window.shiguangBridge.showToast(`课表配置更新成功!总周数:${config.semesterTotalWeeks}周。`);
+        let msg = `课表配置更新成功!总周数:${config.semesterTotalWeeks}周。`;
+        if (config.semesterStartDate) msg += ` 开学日期:${config.semesterStartDate}`;
+        window.shiguangBridge.showToast(msg);
     } catch (error) {
     } catch (error) {
         window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
         window.shiguangBridge.showToast(`课表配置保存失败: ${error.message}`);
-        console.error('JS: Save Config Error:', error);
-        return;
     }
     }
 
 
+    // 7. 导入预设作息时间
     await importPresetTimeSlots(TimeSlots);
     await importPresetTimeSlots(TimeSlots);
 
 
     window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
     window.shiguangBridge.showToast(`课程导入成功,共导入 ${courses.length} 门课程!`);
-    console.log("JS: 整个导入流程执行完毕并成功。");
+    window.shiguangBridge.showToast(`若课程时间有误,请提交issue或联系开发者!`);
     window.shiguangBridge.notifyTaskCompletion();
     window.shiguangBridge.notifyTaskCompletion();
 }
 }
 
 
-// 脚本执行入口
 runImportFlow();
 runImportFlow();
-
+})();