Explorar el Código

Merge pull request #875 from ShiGuangSchedule/pending

星河欲转 hace 2 semanas
padre
commit
fc9e1be9b9
Se han modificado 4 ficheros con 498 adiciones y 322 borrados
  1. 5 0
      index/root_index.yaml
  2. 8 0
      resources/GDCP/adapters.yaml
  3. 352 0
      resources/GDCP/gdcp_01.js
  4. 133 322
      resources/XATU/myschool.js

+ 5 - 0
index/root_index.yaml

@@ -1297,3 +1297,8 @@ schools:
     name: "西北农林科技大学"
     initial: "X"
     resource_folder: "NWAFU"
+
+  - id: "GDCP"
+    name: "广东交通职业技术学院"
+    initial: "G"
+    resource_folder: "GDCP"

+ 8 - 0
resources/GDCP/adapters.yaml

@@ -0,0 +1,8 @@
+adapters:
+  - adapter_id: "GDCP_01"
+    adapter_name: "广东交通职业技术学院强智教务"
+    category: "BACHELOR_AND_ASSOCIATE"
+    asset_js_path: "gdcp_01.js"
+    import_url: "https://cas.gdcp.edu.cn/"
+    maintainer: "小漫君"
+    description: "登录融合门户并进入新教务系统后导入,选择学期与上课校区,按教学楼应用学校作息,并读取开学日期与总周数。"

+ 352 - 0
resources/GDCP/gdcp_01.js

@@ -0,0 +1,352 @@
+// 广东交通职业技术学院强智教务拾光适配脚本
+// 适配作者:小漫君
+// 接口与字段参考拾光 HNIU/hniu_01.js、HHTC/hhtc.js;悬浮详情处理参考 NJFU/njfu_01.js。
+// 周次与教学周历解析、合并去重沿用 QFNU/qfnu_01.js(Yumu-banxia)及官方 Wiki。
+// 校区选择、按教学楼设置课程独立时间参考 GDOU/gdou.js(Mccurtain)。
+// 上游:https://github.com/ShiGuangSchedule/shiguang_warehouse/tree/pending/resources
+// 以上参考实现按上游 MIT 许可复用;本校使用已确认的 xskb_list.do 接口与详表结构。
+
+const GDCP_TIMETABLE_URL = 'https://jw.gdcp.edu.cn/jsxsd/xskb/xskb_list.do';
+const GDCP_CALENDAR_URL = 'https://jw.gdcp.edu.cn/jsxsd/jxzl/jxzl_query';
+
+// 来源:学校《各校区上课作息时间表》(用户提供)。
+// 第 7~8、9~10 节各为 80 分钟连堂,网格按每小节 40 分钟连续排列;课程保留整段实际时间。
+const GDCP_TIME_SLOTS = [
+    { number: 1, startTime: '08:30', endTime: '09:10' },
+    { number: 2, startTime: '09:15', endTime: '09:55' },
+    { number: 3, startTime: '10:10', endTime: '10:50' },
+    { number: 4, startTime: '10:55', endTime: '11:35' },
+    { number: 5, startTime: '14:15', endTime: '14:55' },
+    { number: 6, startTime: '15:00', endTime: '15:40' },
+    { number: 7, startTime: '15:55', endTime: '16:35' },
+    { number: 8, startTime: '16:35', endTime: '17:15' },
+    { number: 9, startTime: '18:05', endTime: '18:45' },
+    { number: 10, startTime: '18:45', endTime: '19:25' }
+];
+const GDCP_LATE_MORNING = [
+    { number: 3, startTime: '10:30', endTime: '11:10' },
+    { number: 4, startTime: '11:15', endTime: '11:55' }
+];
+const GDCP_CAMPUSES = [
+    // 轨道楼(16#)未列入原表;用户明确确认第 3、4 节使用 10:10 起的作息。
+    { name: '天河校区', early: ['9号楼', '10号楼', '12号楼', '图书馆', '公路楼', '汽车实训楼', '轨道楼'], late: ['2号楼', '运动场'] },
+    { name: '花都校区', early: ['1号楼', '图书馆'], late: ['10号楼', '15号楼', '16号楼', '运动场'] },
+    { name: '国际校区', early: ['教学楼', '运动场'], late: [] },
+    { name: '清远校区', early: ['厚德楼', '明德楼', '立业楼', '创新楼', '求是楼', '笃实楼'], late: ['融新楼', '融创楼', '运动场', '体育馆'] }
+];
+
+function applyCampusTimes(courses, campus) {
+    return courses.map(function ({ building, ...course }) {
+        if (course.startSection < 1 || course.endSection > GDCP_TIME_SLOTS.length) {
+            throw new Error('学校作息表只提供第 1~10 节,课程“' + course.name + '”的节次超出范围。');
+        }
+        const slots = GDCP_TIME_SLOTS.slice();
+        if (course.startSection <= 4 && course.endSection >= 3) {
+            // 教务实测楼名含【】、编号前导零与校区后缀;操场对应学校作息表的运动场。
+            const venue = building.replace(/[【】]/g, '').replace(/((?:天河|花都|国际|清远))$/, '')
+                .replace(/^0+(\d+号楼)$/, '$1').replace(/^操场$/, '运动场');
+            const matches = function (name) { return venue === name || venue.startsWith(name + '('); };
+            if (!campus.early.some(matches)) {
+                // 国际校区的“其他区域”是学校表格明确规定的第二套作息。
+                if (!campus.late.some(matches) && campus.name !== '国际校区') {
+                    throw new Error(campus.name + '的“' + building + '”未列入学校作息表,无法确定第 3、4 节时间。');
+                }
+                slots[2] = GDCP_LATE_MORNING[0];
+                slots[3] = GDCP_LATE_MORNING[1];
+            }
+        }
+        // 学校与用户课表都将这两组小节视为一个完整时间块,不能按普通课间拆开。
+        const startTime = course.startSection === 8 ? '15:55' : course.startSection === 10 ? '18:05' : slots[course.startSection - 1].startTime;
+        const endTime = course.endSection === 7 ? '17:15' : course.endSection === 9 ? '19:25' : slots[course.endSection - 1].endTime;
+        return {
+            ...course,
+            isCustomTime: true,
+            customStartTime: startTime,
+            customEndTime: endTime
+        };
+    });
+}
+
+async function fetchTimetableDoc(parameters) {
+    const options = { credentials: 'include' };
+    if (parameters !== undefined) {
+        options.method = 'POST';
+        options.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
+        options.body = parameters.toString();
+    }
+    const response = await fetch(GDCP_TIMETABLE_URL, options);
+    if (!response.ok) throw new Error('课表请求失败(HTTP ' + response.status + ')。');
+    return new DOMParser().parseFromString(await response.text(), 'text/html');
+}
+
+// 来源:QFNU/qfnu_01.js,保留原实现。
+function parseWeeksAndSections(text) {
+    const result = { weeks: [], sections: [] };
+    const content = String(text || '').trim();
+    if (!content) return result;
+
+    const parity = /双/.test(content) ? 2 : (/单/.test(content) ? 1 : 0);
+    const bracketIndex = content.indexOf('[');
+    const cleaned = (bracketIndex >= 0 ? content.slice(0, bracketIndex) : content)
+        .replace(/第/g, '')
+        .replace(/至|到|~/g, '-')
+        .replace(/[((][^()()]*[))]/g, '')
+        .replace(/周/g, '');
+
+    cleaned.split(/[,,、;;\s]+/).forEach(function (segment) {
+        const item = segment.trim();
+        const range = item.match(/^(\d+)\s*[-–—]\s*(\d+)$/);
+        if (range) {
+            for (let week = parseInt(range[1], 10); week <= parseInt(range[2], 10); week++) result.weeks.push(week);
+        } else if (/^\d+$/.test(item)) {
+            result.weeks.push(parseInt(item, 10));
+        }
+    });
+
+    if (parity) {
+        result.weeks = result.weeks.filter(function (week) { return week % 2 === (parity === 1 ? 1 : 0); });
+    }
+    result.weeks = Array.from(new Set(result.weeks)).sort(function (a, b) { return a - b; });
+
+    const sectionMatch = content.match(/\[([^\]]*)\]/);
+    if (sectionMatch) {
+        (sectionMatch[1].match(/\d+/g) || []).forEach(function (number) {
+            const section = parseInt(number, 10);
+            if (result.sections.indexOf(section) < 0) result.sections.push(section);
+        });
+        result.sections.sort(function (a, b) { return a - b; });
+    }
+    return result;
+}
+
+
+function parseTimetable(doc) {
+    const table = doc.getElementById('timetable');
+    if (!table) throw new Error('未获取到课表,请确认已登录新教务系统。');
+    const courses = [];
+    Array.from(table.querySelectorAll('tr')).forEach(function (row) {
+        const cells = row.querySelectorAll('td');
+        if (cells.length !== 7) return;
+        cells.forEach(function (cell, index) {
+            const detail = cell.querySelector('div.kbcontent');
+            if (!detail) throw new Error('课表详表结构不匹配。');
+            const content = detail.cloneNode(true);
+            // NJFU 同样移除重复的悬浮信息,只解析详表中的课程字段。
+            content.querySelectorAll('.item-box').forEach(function (node) { node.remove(); });
+            if (!content.textContent.trim()) return;
+            content.innerHTML.split(/-{10,}\s*<br\s*\/?>/i).forEach(function (html) {
+                const block = doc.createElement('div');
+                block.innerHTML = html;
+                const name = block.querySelector('font:not([title])');
+                const teacher = block.querySelector('font[title="教师"]');
+                const time = block.querySelector('font[title="周次(节次)"]');
+                const position = block.querySelector('font[title="教室"]');
+                const building = block.querySelector('font[title="教学楼"]');
+                if (!name || !teacher || !time || !position || !building) throw new Error('课程字段结构不匹配。');
+                const parsed = parseWeeksAndSections(time.textContent);
+                if (!name.textContent.trim() || parsed.weeks.length === 0 || parsed.sections.length === 0) {
+                    throw new Error('课程名称、周次或节次为空。');
+                }
+                courses.push({
+                    name: name.textContent.trim(),
+                    teacher: teacher.textContent.trim(),
+                    position: position.textContent.trim(),
+                    building: building.textContent.trim(),
+                    day: index + 1,
+                    weeks: parsed.weeks,
+                    startSection: parsed.sections[0],
+                    endSection: parsed.sections[parsed.sections.length - 1]
+                });
+            });
+        });
+    });
+    return courses;
+}
+
+// 来源:QFNU/qfnu_01.js / 官方 Wiki《课程合并与去重函数》,保留原实现。
+// https://github.com/ShiGuangSchedule/shiguangschedule/wiki/课程合并与去重函数
+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) => {
+        return 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);
+    });
+
+    const step1Merged = [];
+    let current = list[0];
+
+    for (let i = 1; i < list.length; i++) {
+        const next = list[i];
+
+        const isSameCourseAndWeeks =
+            current.name === next.name &&
+            current.teacher === next.teacher &&
+            current.position === next.position &&
+            current.day === next.day &&
+            current.weeks.join(',') === next.weeks.join(',');
+
+        const isContinuous = current.endSection + 1 === next.startSection;
+        const isDuplicate = current.startSection === next.startSection && current.endSection === next.endSection;
+
+        if (isSameCourseAndWeeks && isContinuous) {
+            current.endSection = next.endSection;
+        } else if (isSameCourseAndWeeks && isDuplicate) {
+            continue;
+        } else {
+            step1Merged.push(current);
+            current = next;
+        }
+    }
+    step1Merged.push(current);
+
+    step1Merged.sort((a, b) => {
+        return 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);
+    });
+
+    const step2Merged = [];
+    let merged = step1Merged[0];
+
+    for (let i = 1; i < step1Merged.length; i++) {
+        const next = step1Merged[i];
+
+        const isSameCourseAndSection =
+            merged.name === next.name &&
+            merged.teacher === next.teacher &&
+            merged.position === next.position &&
+            merged.day === next.day &&
+            merged.startSection === next.startSection &&
+            merged.endSection === next.endSection;
+
+        if (isSameCourseAndSection) {
+            merged.weeks = Array.from(new Set([...merged.weeks, ...next.weeks])).sort((a, b) => a - b);
+        } else {
+            step2Merged.push(merged);
+            merged = next;
+        }
+    }
+    step2Merged.push(merged);
+
+    return step2Merged;
+}
+
+
+// 教学周历解析来源:QFNU/qfnu_01.js(Yumu-banxia),保留原实现。
+function parseCalendar(doc) {
+    const result = { semesterStartDate: null, totalWeeks: null };
+    const table = doc.querySelector('table');
+    if (!table) return result;
+
+    const toDate = function (text) {
+        const match = String(text || '').match(/(\d{4})\s*[-年]\s*(\d{1,2})\s*[-月]\s*(\d{1,2})/);
+        return match ? match[1] + '-' + match[2].padStart(2, '0') + '-' + match[3].padStart(2, '0') : null;
+    };
+
+    Array.from(table.querySelectorAll('tr')).forEach(function (row) {
+        const cells = Array.from(row.children);
+        const first = cells.length > 0 ? String(cells[0].textContent).trim() : '';
+        if (!/^\d+$/.test(first)) return;
+
+        const week = parseInt(first, 10);
+        result.totalWeeks = result.totalWeeks === null ? week : Math.max(result.totalWeeks, week);
+        if (week === 1 && !result.semesterStartDate && cells.length > 1) {
+            result.semesterStartDate = toDate(cells[1].getAttribute('title')) || toDate(cells[1].textContent);
+        }
+    });
+    return result;
+}
+
+async function fetchCourseConfig(semesterValue) {
+    const response = await fetch(GDCP_CALENDAR_URL, {
+        method: 'POST',
+        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
+        body: new URLSearchParams({ xnxq01id: semesterValue }).toString(),
+        credentials: 'include'
+    });
+    if (!response.ok) throw new Error('教学周历请求失败(HTTP ' + response.status + ')。');
+    const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
+    if (doc.getElementById('xnxq01id')?.value !== semesterValue) throw new Error('返回周历与所选学期不一致。');
+    const calendar = parseCalendar(doc);
+    if (!calendar.semesterStartDate || !Number.isInteger(calendar.totalWeeks) || calendar.totalWeeks < 1) {
+        throw new Error('教学周历未提供完整的首周日期或总周数。');
+    }
+    const monday = new Date(calendar.semesterStartDate + 'T00:00:00Z');
+    if (Number.isNaN(monday.getTime()) || monday.toISOString().slice(0, 10) !== calendar.semesterStartDate || monday.getUTCDay() !== 1) {
+        throw new Error('教学周历第 1 周的星期一日期无效。');
+    }
+    return {
+        semesterStartDate: calendar.semesterStartDate,
+        semesterTotalWeeks: calendar.totalWeeks,
+        firstDayOfWeek: 1,
+        defaultClassDuration: 40,
+        defaultBreakDuration: 5
+    };
+}
+
+async function runImportFlow() {
+    try {
+        if (window.location.origin !== 'https://jw.gdcp.edu.cn') {
+            await window.shiguangBridgePromise.showAlert('请进入新教务系统', '请先登录融合门户,打开“新教务系统”后再导入。', '知道了');
+            return;
+        }
+        window.shiguangBridge.showToast('正在获取学期信息…');
+        const initialDoc = await fetchTimetableDoc();
+        const semesterSelect = initialDoc.getElementById('xnxq01id');
+        const modeSelect = initialDoc.getElementById('kbjcmsid');
+        if (!semesterSelect || semesterSelect.options.length === 0 || !modeSelect || !modeSelect.value) {
+            throw new Error('未获取到学期或节次模式,请确认教务登录状态。');
+        }
+        const semesters = Array.from(semesterSelect.options);
+        const picked = await window.shiguangBridgePromise.showSingleSelection(
+            '选择学期', JSON.stringify(semesters.map(function (option) { return option.textContent.trim(); })), semesterSelect.selectedIndex
+        );
+        if (picked === null) return;
+        if (!Number.isInteger(picked) || picked < 0 || picked >= semesters.length) throw new Error('学期选择无效。');
+
+        const parameters = new URLSearchParams({
+            cj0701id: '', zc: '', demo: '', xnxq01id: semesters[picked].value, sfFD: '1', kbjcmsid: modeSelect.value
+        });
+        window.shiguangBridge.showToast('正在获取整学期课表…');
+        const doc = await fetchTimetableDoc(parameters);
+        if (doc.getElementById('xnxq01id')?.value !== semesters[picked].value) throw new Error('返回课表与所选学期不一致。');
+        const parsedCourses = mergeAndDistinctCourses(parseTimetable(doc));
+        if (parsedCourses.length === 0) {
+            await window.shiguangBridgePromise.showAlert('该学期暂无课程', '所选学期没有已排定上课时间的课程。', '知道了');
+            return;
+        }
+        const campusIndex = await window.shiguangBridgePromise.showSingleSelection(
+            '选择上课校区', JSON.stringify(GDCP_CAMPUSES.map(function (campus) { return campus.name; })), 0
+        );
+        if (campusIndex === null) return;
+        if (!Number.isInteger(campusIndex) || campusIndex < 0 || campusIndex >= GDCP_CAMPUSES.length) throw new Error('校区选择无效。');
+        const courses = applyCampusTimes(parsedCourses, GDCP_CAMPUSES[campusIndex]);
+        window.shiguangBridge.showToast('正在获取所选学期的教学周历…');
+        const config = await fetchCourseConfig(semesters[picked].value);
+        if (!await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config))) throw new Error('课表配置保存失败。');
+        if (!await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(GDCP_TIME_SLOTS))) throw new Error('作息时间保存失败。');
+        if (!await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses))) throw new Error('课程保存失败。');
+        window.shiguangBridge.showToast('已获取 ' + courses.length + ' 条课程时段,请校对上课时间。');
+        window.shiguangBridge.notifyTaskCompletion();
+    } catch (error) {
+        await window.shiguangBridgePromise.showAlert('导入失败', error.message, '知道了');
+    }
+}
+
+runImportFlow();

+ 133 - 322
resources/XATU/myschool.js

@@ -32,114 +32,48 @@ function powerSplit(paramsRaw) {
 
 function cleanArg(s) {
     s = s.trim();
-    if (s === "null") return null;
     return s.replace(/^["']|["']$/g, "");
 }
 
-/**
- * 全局课程合并逻辑
- */
+/** 按课程、教师、地点和星期合并连续节次,保持原有50周范围。 */
 function mergeContinuousLessons(lessons) {
-    if (!lessons || lessons.length === 0) return [];
-
-    // 1. 建立基于 (课程名|教师|地点|星期几) 的分组
-    const groups = {};
-    lessons.forEach(l => {
-        const key = `${l.courseSequence || ""}|${l.name}|${l.teacher}|${l.position}|${l.day}`;
-        if (!groups[key]) {
-            groups[key] = {
-                name: l.name,
-                teacher: l.teacher,
-                position: l.position,
-                day: l.day,
-                isTeachingBuilding3: l.isTeachingBuilding3,
-                credit: l.credit,
-                // 假设大学最多 50 周,构建一个:第 N 周对应哪些节次的矩阵
-                weeksMatrix: Array.from({ length: 50 }, () => new Set())
-            };
-        }
-        // 将系统传来的凌乱数据彻底打散,按“周”填入对应的“节”中,Set自动去重
-        if (l.weeks && Array.isArray(l.weeks)) {
-            l.weeks.forEach(w => {
-                if (w >= 0 && w < 50) {
-                    for (let s = l.startSection; s <= l.endSection; s++) {
-                        groups[key].weeksMatrix[w].add(s);
-                    }
-                }
-            });
+    const groups = new Map();
+    for (const lesson of lessons) {
+        const key = JSON.stringify([lesson.courseSequence, lesson.name, lesson.teacher, lesson.position, lesson.day]);
+        if (!groups.has(key)) groups.set(key, { lesson, weeks: Array.from({ length: 50 }, () => new Set()) });
+        const { weeks } = groups.get(key);
+        for (const week of lesson.weeks) {
+            if (week >= 50) continue;
+            for (let section = lesson.startSection; section <= lesson.endSection; section++) weeks[week].add(section);
         }
-    });
-
-    const merged = [];
-
-    // 2. 根据矩阵重新组装绝对精确的课程块
-    for (const key in groups) {
-        const group = groups[key];
-        const matrix = group.weeksMatrix;
-        
-        // 用于记录相同的“连续节次块”分布在哪些周次
-        // 例如 blockMap["1-2"] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
-        // 例如 blockMap["2-2"] = [10]
-        const blockMap = {};
-
-        for (let w = 0; w < matrix.length; w++) {
-            const sections = Array.from(matrix[w]).sort((a, b) => a - b);
-            if (sections.length === 0) continue;
-
-            // 寻找当前周的连续节次块
-            let start = sections[0];
-            let prev = sections[0];
-
-            for (let i = 1; i < sections.length; i++) {
-                const curr = sections[i];
-                if (curr === prev + 1) {
-                    prev = curr; // 节次连续,继续延伸
-                } else {
-                    // 节次断开,结算上一个块
-                    const blockKey = `${start}-${prev}`;
-                    if (!blockMap[blockKey]) blockMap[blockKey] = [];
-                    blockMap[blockKey].push(w);
-                    
-                    // 开启新块
-                    start = curr;
-                    prev = curr;
-                }
+    }
+    const courses = [];
+    for (const { lesson, weeks } of groups.values()) {
+        const blocks = new Map();
+        weeks.forEach((sections, week) => {
+            const sorted = [...sections].sort((a, b) => a - b);
+            for (let i = 0; i < sorted.length; i++) {
+                const start = sorted[i];
+                while (i + 1 < sorted.length && sorted[i + 1] === sorted[i] + 1) i++;
+                const key = `${start}-${sorted[i]}`;
+                if (!blocks.has(key)) blocks.set(key, []);
+                blocks.get(key).push(week);
             }
-            // 结算每周最后一个块
-            const blockKey = `${start}-${prev}`;
-            if (!blockMap[blockKey]) blockMap[blockKey] = [];
-            blockMap[blockKey].push(w);
-        }
-
-        // 3. 将聚合好的 blockMap 转换为最终的 JSON 对象
-        for (const blockKey in blockMap) {
-            const [startSec, endSec] = blockKey.split('-').map(Number);
-            merged.push({
-                name: group.name,
-                teacher: group.teacher,
-                position: group.position,
-                day: group.day,
-                startSection: startSec,
-                endSection: endSec,
-                weeks: blockMap[blockKey],
-                isTeachingBuilding3: group.isTeachingBuilding3,
-                ...(group.credit !== undefined ? { credit: group.credit } : {})
+        });
+        for (const [key, courseWeeks] of blocks) {
+            const [startSection, endSection] = key.split('-').map(Number);
+            courses.push({
+                name: lesson.courseSequence ? `${lesson.name} | ${lesson.courseSequence}` : lesson.name,
+                teacher: lesson.teacher, position: lesson.position, day: lesson.day,
+                startSection, endSection, weeks: courseWeeks,
+                credit: lesson.credit,
+                ...(/教3/.test(lesson.position) && startSection === 3 && endSection === 4 ? {
+                    isCustomTime: true, customStartTime: "10:10", customEndTime: "11:40"
+                } : {})
             });
         }
     }
-
-    // 4. 排序以便输出整洁美观
-    merged.sort((a, b) => {
-        if (a.day !== b.day) return a.day - b.day;
-        if (a.startSection !== b.startSection) return a.startSection - b.startSection;
-        return a.name.localeCompare(b.name);
-    });
-
-    return merged;
-}
-
-function isTeachingBuilding3(position) {
-    return /教3/.test(position);
+    return courses.sort((a, b) => a.day - b.day || a.startSection - b.startSection || a.name.localeCompare(b.name));
 }
 
 /** 从同一课表响应的课程列表中读取学分,按课程序号匹配,避免同名课程混淆。 */
@@ -155,15 +89,10 @@ function parseCourseCredits(html) {
         const sequenceIndex = headers.indexOf("课程序号");
         if (sequenceIndex < 0) continue;
         for (const row of table.rows) {
-            if (row === header || row.closest("table") !== table) continue;
             const sequence = row.cells[sequenceIndex]?.textContent.trim();
             const text = row.cells[creditIndex]?.textContent.trim();
-            if (!sequence || !text || !/^\d+(?:\.\d+)?$/.test(text)) continue;
-            const credit = Number(text);
-            if (!Number.isFinite(credit)) continue;
-            // 同一序号出现矛盾值时不猜测;合法的 0 学分需要保留。
-            if (credits.has(sequence) && credits.get(sequence) !== credit) credits.set(sequence, undefined);
-            else if (!credits.has(sequence)) credits.set(sequence, credit);
+            if (!sequence || !/^\d+(?:\.\d+)?$/.test(text)) continue;
+            credits.set(sequence, Number(text));
         }
     }
     return credits;
@@ -171,66 +100,56 @@ function parseCourseCredits(html) {
 
 function parseTaskActivities(html) {
     const credits = parseCourseCredits(html);
-    const rawResults = [];
-    const blocks = html.split(/var\s+teachers\s*=/);
-
-    for (let i = 1; i < blocks.length; i++) {
-        const block = blocks[i];
-        let teacherName = "未知教师";
-        const tMatch = block.match(/actTeachers\s*=\s*\[\s*\{[\s\S]*?name:\s*"(.*?)"/);
-        if (tMatch) teacherName = tMatch[1];
-
-        const activityMatch = block.match(/new\s+TaskActivity\(([\s\S]*?)\);/);
-        if (!activityMatch) continue;
-
-        const args = powerSplit(activityMatch[1]);
-        const courseSequence = (args[2] || "").match(/\(([^()]*)\)$/)?.[1] || "";
-        const credit = credits.get(courseSequence);
-        const courseName = (args[3] || "未知课程").split('(')[0];
-        const position = (args[5] || "未知地点").replace(/\(.*?\)/g, "");
-        const weeksBitmap = args[6] || "";
-        
-        const weeks = [];
-        for (let j = 0; j < weeksBitmap.length; j++) {
-            if (weeksBitmap[j] === '1') weeks.push(j);
-        }
-
-        const unitCountMatch = html.match(/unitCount\s*=\s*(\d+)/);
-        const unitCount = unitCountMatch ? parseInt(unitCountMatch[1]) : 14;
-
-        const idxRegex = /index\s*=\s*(\d+)\s*\*\s*unitCount\s*\+\s*(\d+);/g;
-        let m;
-        while ((m = idxRegex.exec(block)) !== null) {
-            const day = parseInt(m[1]) + 1; 
-            const section = parseInt(m[2]) + 1;
-
-            rawResults.push({
-                "name": courseName,
-                "courseSequence": courseSequence,
-                ...(credit !== undefined ? { credit } : {}),
-                "teacher": teacherName,
-                "position": position,
-                "day": day,
-                "startSection": section,
-                "endSection": section,
-                "weeks": weeks,
-                "isTeachingBuilding3": isTeachingBuilding3(position)
-            });
+    const lessons = [];
+    for (const block of html.split(/var\s+teachers\s*=/).slice(1)) {
+        const activities = [...block.matchAll(/new\s+TaskActivity\(([\s\S]*?)\);/g)];
+        let teacher = "未知教师";
+        for (let i = 0; i < activities.length; i++) {
+            const activity = activities[i];
+            const before = block.slice(i ? activities[i - 1].index + activities[i - 1][0].length : 0, activity.index);
+            const teachers = before.match(/actTeachers\s*=\s*(\[[\s\S]*?\])/);
+            if (teachers) {
+                teacher = [...teachers[1].matchAll(/name\s*:\s*["'](.*?)["']/g)].map(m => m[1]).join("、") || "未知教师";
+            }
+            const args = powerSplit(activity[1]);
+            const courseSequence = (args[2] || "").match(/\(([^()]*)\)$/)?.[1] || "";
+            const credit = credits.get(courseSequence);
+            const position = (args[5] || "未知地点").replace(/\(.*?\)/g, "");
+            const weeks = [...(args[6] || "")].flatMap((bit, week) => bit === "1" ? [week] : []);
+            const indexes = block.slice(activity.index + activity[0].length, activities[i + 1]?.index)
+                .matchAll(/index\s*=\s*(\d+)\s*\*\s*unitCount\s*\+\s*(\d+);/g);
+            for (const index of indexes) {
+                lessons.push({
+                    name: (args[3] || "未知课程").split('(')[0], courseSequence,
+                    teacher, position, day: Number(index[1]) + 1,
+                    startSection: Number(index[2]) + 1, endSection: Number(index[2]) + 1,
+                    weeks, credit
+                });
+            }
         }
     }
-
-    // 执行全局合并逻辑
-    return mergeContinuousLessons(rawResults);
+    return mergeContinuousLessons(lessons);
 }
 
-async function requestResponse(url, options = {}) {
-    const res = await fetch(url, { credentials: "include", ...options });
-    if (!res.ok) throw new Error(`网络请求失败: ${res.status}`);
-    return res;
-}
-
-async function request(url, options = {}) {
-    return await (await requestResponse(url, options)).text();
+async function request(path, body) {
+    const controller = new AbortController();
+    const timer = setTimeout(() => controller.abort(), 15000);
+    try {
+        const res = await fetch(`http://jwgl2018.xatu.edu.cn/eams/${path}`, {
+            credentials: "include", signal: controller.signal,
+            ...(body !== undefined ? {
+                method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body
+            } : {})
+        });
+        if (!res.ok) throw new Error(`教务请求失败:HTTP ${res.status}`);
+        const html = await res.text();
+        return { html, serverTime: Date.parse(res.headers.get("Date") || "") };
+    } catch (e) {
+        if (controller.signal.aborted) throw new Error("教务请求超时,请稍后重试");
+        throw e;
+    } finally {
+        clearTimeout(timer);
+    }
 }
 
 /** 根据教务首页的当前教学周,推算第一教学周的周一(北京时间)。 */
@@ -244,215 +163,107 @@ function inferCurrentSemester(html, referenceTime) {
 
     const week = Number(weekText);
     const totalWeeks = Number(totalMatch[1]);
-    if (week < 1 || week > totalWeeks || totalWeeks > 53 || !Number.isFinite(referenceTime)) return null;
+    if (week < 1 || week > totalWeeks || totalWeeks > 53) return null;
 
-    // 用 UTC 方法处理已平移到北京时间的日期,避免设备时区和夏令时影响。
-    const start = new Date(referenceTime + 8 * 60 * 60 * 1000);
+    // 固定按教务的 UTC+8 日期计算第一周周一。
+    const start = new Date(referenceTime + 8 * 3600000);
     start.setUTCHours(0, 0, 0, 0);
-    const daysSinceMonday = (start.getUTCDay() + 6) % 7;
-    start.setUTCDate(start.getUTCDate() - daysSinceMonday - (week - 1) * 7);
+    start.setUTCDate(start.getUTCDate() - (start.getUTCDay() + 6) % 7 - (week - 1) * 7);
 
-    // 学期选择器没有起止日期;按推算出的起始月份识别本校的秋季/春季学期。
     const isAutumn = start.getUTCMonth() >= 6;
-    const schoolYearStart = start.getUTCFullYear() - (isAutumn ? 0 : 1);
+    const year = start.getUTCFullYear() - (isAutumn ? 0 : 1);
     return {
-        schoolYear: `${schoolYearStart}-${schoolYearStart + 1}`,
-        term: isAutumn ? "1" : "2",
+        schoolYear: `${year}-${year + 1}`, term: isAutumn ? "1" : "2",
         semesterStartDate: start.toISOString().slice(0, 10),
         semesterTotalWeeks: totalWeeks
     };
 }
 
-async function getCurrentSemesterConfig(semester) {
+async function getCurrentSemesterConfig() {
     try {
-        const res = await requestResponse("http://jwgl2018.xatu.edu.cn/eams/homeExt!main.action?sf_request_type=ajax");
-        const serverTime = Date.parse(res.headers.get("Date") || "");
-        const current = inferCurrentSemester(await res.text(), Number.isFinite(serverTime) ? serverTime : Date.now());
+        const { html, serverTime } = await request("homeExt!main.action?sf_request_type=ajax");
+        const current = inferCurrentSemester(html, Number.isFinite(serverTime) ? serverTime : Date.now());
         if (!current) throw new Error("未能识别当前教学周");
-        if (semester.schoolYear !== current.schoolYear || semester.term !== current.term) {
-            window.shiguangBridge.showToast("历史或其他学期开学日期请手动设置");
-            return null;
-        }
-        return {
-            semesterStartDate: current.semesterStartDate,
-            semesterTotalWeeks: current.semesterTotalWeeks
-        };
+        return current;
     } catch (e) {
         console.warn(`[开学日期推算] ${e.message}`);
-        window.shiguangBridge.showToast("无法推算开学日期,请在导入后手动设置");
+        window.shiguangBridge.showToast(`${e.message};开学日期请手动设置`);
         return null;
     }
 }
 
 async function detectParameters() {
-    const html = await request("http://jwgl2018.xatu.edu.cn/eams/courseTableForStd.action?sf_request_type=ajax");
+    const { html } = await request("courseTableForStd.action?sf_request_type=ajax");
     const idsMatch = html.match(/bg\.form\.addInput\(form,"ids","(\d+)"\)/);
     const tagIdMatch = html.match(/id="(semesterBar\d+Semester)"/);
     if (!idsMatch || !tagIdMatch) return null;
     return { ids: idsMatch[1], tagId: tagIdMatch[1] };
 }
 
-async function getSelectedSemester(tagId) {
-    const raw = await request(`http://jwgl2018.xatu.edu.cn/eams/dataQuery.action?sf_request_type=ajax`, {
-        method: "POST",
-        headers: { "Content-Type": "application/x-www-form-urlencoded" },
-        body: `tagId=${encodeURIComponent(tagId)}&dataType=semesterCalendar`
-    });
-    const data = Function(`return (${raw});`)();
-    const list = [];
-    for (let key in data.semesters) {
-        data.semesters[key].forEach(s => list.push({
-            id: s.id,
-            schoolYear: s.schoolYear,
-            term: String(s.name),
-            name: `${s.schoolYear} ${s.name}学期`
-        }));
-    }
-    const idx = await window.shiguangBridgePromise.showSingleSelection("选择学期", JSON.stringify(list.map(s => s.name)), -1);
-    return idx !== null ? list[idx] : null;
+async function getSelectedSemester({ tagId }, current) {
+    const { html } = await request("dataQuery.action?sf_request_type=ajax",
+        `tagId=${encodeURIComponent(tagId)}&dataType=semesterCalendar`);
+    const data = Function(`return (${html});`)();
+    const list = Object.values(data.semesters).flat().map(s => ({
+        id: s.id, name: `${s.schoolYear}学年 ${String(s.name) === "1" ? "秋季" : "春季"}学期`,
+        isCurrent: s.schoolYear === current?.schoolYear && String(s.name) === current?.term
+    }));
+    const currentIndex = list.findIndex(s => s.isCurrent);
+    const idx = await window.shiguangBridgePromise.showSingleSelection("选择学期",
+        JSON.stringify(list.map(s => s.name + (s.isCurrent ? "(当前学期)" : ""))),
+        currentIndex);
+    return idx === null ? null : list[idx];
 }
 
 async function fetchAndParseCourses(semesterId, ids) {
-    const html = await request(`http://jwgl2018.xatu.edu.cn/eams/courseTableForStd!courseTable.action?sf_request_type=ajax`, {
-        method: "POST",
-        headers: { "Content-Type": "application/x-www-form-urlencoded" },
-        body: `ignoreHead=1&setting.kind=std&semester.id=${semesterId}&ids=${ids}`
-    });
+    const { html } = await request("courseTableForStd!courseTable.action?sf_request_type=ajax",
+        `ignoreHead=1&setting.kind=std&semester.id=${encodeURIComponent(semesterId)}&ids=${encodeURIComponent(ids)}`);
     return parseTaskActivities(html);
 }
 
-/** 将已排定考试转换成单次自定义时间课程;未排定、无效或超出学期的记录不导入。 */
-function parseExamCourses(html, config) {
-    const doc = new DOMParser().parseFromString(html, "text/html");
-    const startTime = Date.parse(`${config.semesterStartDate}T00:00:00Z`);
-    const exams = [];
-    const seen = new Set();
-    let foundTable = false;
-    for (const table of doc.querySelectorAll("table")) {
-        const header = Array.from(table.rows).find(row =>
-            Array.from(row.cells).some(cell => cell.tagName === "TH" && cell.textContent.trim() === "考试日期"));
-        if (!header) continue;
-        const headers = Array.from(header.cells).map(cell => cell.textContent.trim());
-        const get = (row, name) => row.cells[headers.indexOf(name)]?.textContent.trim() || "";
-        if (!["课程名称", "课程序号", "考试安排", "考试地点"].every(name => headers.includes(name))) continue;
-        foundTable = true;
-        for (const row of table.rows) {
-            if (row === header || row.closest("table") !== table) continue;
-            const dateText = get(row, "考试日期");
-            const timeMatch = get(row, "考试安排").match(/^(\d{1,2}:\d{2})\s*[~~--]\s*(\d{1,2}:\d{2})$/);
-            if (!/^\d{4}-\d{2}-\d{2}$/.test(dateText) || !timeMatch) continue;
-            const date = new Date(`${dateText}T00:00:00Z`);
-            if (!Number.isFinite(date.getTime()) || date.toISOString().slice(0, 10) !== dateText) continue;
-            const times = timeMatch.slice(1).map(time => time.padStart(5, "0"));
-            if (!times.every(time => /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(time)) || times[0] >= times[1]) continue;
-            const week = Math.floor((date.getTime() - startTime) / (7 * 86400000)) + 1;
-            const name = get(row, "课程名称");
-            if (!name || !Number.isInteger(week) || week < 1 || week > config.semesterTotalWeeks) continue;
-            const seat = get(row, "考场座位号");
-            const room = get(row, "考试地点");
-            const position = `${room === "无" ? "" : room}${seat ? `(座位 ${seat})` : ""}`;
-            const key = JSON.stringify([get(row, "课程序号"), dateText, times, position]);
-            if (seen.has(key)) continue;
-            seen.add(key);
-            exams.push({
-                name: `【考试】${name}`,
-                teacher: "",
-                position,
-                day: date.getUTCDay() || 7,
-                weeks: [week],
-                isCustomTime: true,
-                customStartTime: times[0],
-                customEndTime: times[1]
-            });
-        }
-    }
-    if (!foundTable) throw new Error("未识别到考试安排表");
-    return exams;
-}
-
-async function getOptionalExamCourses(semester, config) {
-    // 历史学期没有可靠的开学日期,无法将考试日期换算成对应教学周。
-    if (!config) return [];
-    const choice = await window.shiguangBridgePromise.showSingleSelection(
-        "是否同时导入考试安排", JSON.stringify(["仅导入课程", "同时导入已排定考试(单次课程)"]), 0);
-    if (choice !== 1) return [];
-    try {
-        const html = await request(`http://jwgl2018.xatu.edu.cn/eams/stdExamTable!examTable.action?semester.id=${encodeURIComponent(semester.id)}&examBatch.id=0`);
-        const exams = parseExamCourses(html, config);
-        window.shiguangBridge.showToast(exams.length ? `已读取 ${exams.length} 场考试` : "当前学期暂无可导入的已排定考试");
-        return exams;
-    } catch (e) {
-        console.warn(`[考试导入] ${e.message}`);
-        window.shiguangBridge.showToast("考试安排读取失败,仅导入课程");
-        return [];
-    }
-}
-
 async function applyTimeSlots() {
     const slots = [
-        { "number": 1, "startTime": "08:20", "endTime": "09:05" }, 
-        { "number": 2, "startTime": "09:15", "endTime": "10:00" },
-        { "number": 3, "startTime": "10:20", "endTime": "11:05" },
-        { "number": 4, "startTime": "11:15", "endTime": "12:00" },
-        { "number": 5, "startTime": "14:00", "endTime": "14:45" },
-        { "number": 6, "startTime": "14:55", "endTime": "15:40" },
-        { "number": 7, "startTime": "16:00", "endTime": "16:45" }, 
-        { "number": 8, "startTime": "16:55", "endTime": "17:40" },
-        { "number": 9, "startTime": "18:10", "endTime": "18:55" }, 
-        { "number": 10, "startTime": "19:05", "endTime": "19:50" },
-        { "number": 11, "startTime": "20:00", "endTime": "20:45" },
-        { "number": 12, "startTime": "20:55", "endTime": "21:40" },
-    ];
+        ["08:20", "09:05"], ["09:15", "10:00"],
+        ["10:20", "11:05"], ["11:15", "12:00"],
+        ["14:00", "14:45"], ["14:55", "15:40"],
+        ["16:00", "16:45"], ["16:55", "17:40"],
+        ["18:10", "18:55"], ["19:05", "19:50"],
+        ["20:00", "20:45"], ["20:55", "21:40"]
+    ].map(([startTime, endTime], i) => ({ number: i + 1, startTime, endTime }));
     return await window.shiguangBridgePromise.savePresetTimeSlots(JSON.stringify(slots));
 }
 
-
-function adjustTeachingBuilding3Courses(courses) {
-    return courses.map(course => {
-        // 检查是否是教3楼且正好是第3-4节两节课
-        if (course.isTeachingBuilding3 && 
-            course.startSection === 3 && 
-            course.endSection === 4) {
-            // 设置为自定义时间模式
-            course.isCustomTime = true;
-            course.customStartTime = "10:10";
-            course.customEndTime = "11:40";
-        }
-        return course;
-    });
-}
-
 async function runImportFlow() {
     try {
         window.shiguangBridge.showToast("开始探测教务参数...");
         const params = await detectParameters();
         if (!params) throw new Error("未能识别教务参数,请确认已登录");
 
-        const semester = await getSelectedSemester(params.tagId);
+        const current = await getCurrentSemesterConfig();
+        const semester = await getSelectedSemester(params, current);
         if (!semester) return; 
 
         window.shiguangBridge.showToast("正在同步课表...");
-        let courses = await fetchAndParseCourses(semester.id, params.ids);
+        const courses = await fetchAndParseCourses(semester.id, params.ids);
         
-        if (!courses || courses.length === 0) throw new Error("未解析到课程数据");
+        if (!courses.length) throw new Error("未解析到课程数据");
 
-        // 调整教3楼课程时间
-        courses = adjustTeachingBuilding3Courses(courses);
-
-        const config = await getCurrentSemesterConfig(semester);
-        const exams = await getOptionalExamCourses(semester, config);
-        courses = courses.concat(exams);
-        await applyTimeSlots();
-        if (config) {
-            await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify(config));
-            window.shiguangBridge.showToast(`已推算第一教学周周一为 ${config.semesterStartDate}`);
+        if (current && !semester.isCurrent) window.shiguangBridge.showToast("历史或其他学期开学日期请手动设置");
+        if (!await applyTimeSlots()) {
+            console.error("作息时间保存失败,导入未完成");
+            return;
         }
-        const saveResult = await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses));
-        
-        if (saveResult) {
-            window.shiguangBridge.showToast(`成功导入 ${courses.length} 个课程条目`);
-            window.shiguangBridge.notifyTaskCompletion();
+        if (semester.isCurrent && !await window.shiguangBridgePromise.saveCourseConfig(JSON.stringify({
+            semesterStartDate: current.semesterStartDate,
+            semesterTotalWeeks: current.semesterTotalWeeks
+        }))) {
+            throw new Error("学期配置保存失败,导入未完成");
+        }
+        if (!await window.shiguangBridgePromise.saveImportedCourses(JSON.stringify(courses))) {
+            throw new Error("课程保存失败,导入未完成");
         }
+        window.shiguangBridge.showToast(`成功导入 ${courses.length} 个课程条目`);
+        window.shiguangBridge.notifyTaskCompletion();
     } catch (e) {
         console.error(`[异常] ${e.message}`);
         window.shiguangBridge.showToast(e.message);