cup_02.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. // resources/CUP/cup_02.js
  2. // 中国石油大学(北京)研究生拾光课程表适配脚本
  3. // https://gmis.cup.edu.cn/gmis/student/default/index
  4. // 教务平台:南京南软
  5. // 适配开发者:larryyan
  6. // ==========================================
  7. // 0. 全局配置与验证函数
  8. // ==========================================
  9. const PRESET_TIME_CONFIG = {
  10.     campuses: {
  11.         MainCampus: {
  12.             startTimes: {
  13.                 morning: "08:00",
  14.                 afternoon: "13:30",
  15.                 evening: "18:30"
  16.             },
  17.             sectionCounts: {
  18.                 morning: 4,
  19.                 afternoon: 4,
  20.                 evening: 3
  21.             },
  22.             durations: {
  23.                 classMinutes: 45,
  24.                 shortBreakMinutes: 5,
  25.                 longBreakMinutes: 30
  26.             }
  27.         },
  28.         Karamay: {
  29.             startTimes: {
  30.                 morning: "09:30",
  31.                 afternoon: "16:00",
  32.                 evening: "20:30"
  33.             },
  34.             sectionCounts: {
  35.                 morning: 5,
  36.                 afternoon: 4,
  37.                 evening: 3
  38.             },
  39.             durations: {
  40.                 classMinutes: 45,
  41.                 shortBreakMinutes: 5,
  42.                 longBreakMinutes: 20
  43.             },
  44.         }
  45.     },
  46.     common: {
  47.         longBreakAfter: {
  48.             morning: 2,
  49.             afternoon: 2,
  50.             evening: 0  // 晚间课程无大课间
  51.         }
  52.     }
  53. };
  54. const CAMPUS_OPTIONS = [
  55.     { id: "MainCampus", label: "主校区" },
  56.     { id: "Karamay", label: "克拉玛依校区" }
  57. ];
  58. /**
  59.  * 验证开学日期的输入格式
  60.  */
  61. function validateDateInput(input) {
  62.     if (/^\d{4}[-\/\.]\d{2}[-\/\.]\d{2}$/.test(input)) {
  63.         return false;
  64.     } else {
  65.         return "请输入正确的日期格式,例如: 2025-09-01";
  66.     }
  67. }
  68. // ==========================================
  69. // 业务流程函数
  70. // ==========================================
  71. // 1. 显示一个公告信息弹窗
  72. async function promptUserToStart() {
  73.     console.log("即将显示公告弹窗...");
  74.     const confirmed = await window.AndroidBridgePromise.showAlert(
  75.         "重要通知",
  76.         "导入前请确保您已成功登录教务系统,并选定正确的学期。",
  77.         "好的,开始"
  78.     );
  79.     return confirmed === true;
  80. }
  81. // 2. 选择校区 (使用配置项)
  82. async function selectCampus() {
  83.     // 从配置中提取用于展示的名称数组
  84.     const campusLabels = CAMPUS_OPTIONS.map(opt => opt.label);
  85.    
  86.     const selectedIndex = await window.AndroidBridgePromise.showSingleSelection(
  87.         "选择所在校区",
  88.         JSON.stringify(campusLabels),
  89.         0
  90.     );
  91.     if (selectedIndex !== null && selectedIndex >= 0) {
  92.         const selectedCampus = CAMPUS_OPTIONS[selectedIndex];
  93.         if (!selectedCampus) {
  94.             throw new Error("校区选择结果无效。");
  95.         }
  96.         // 返回选中的校区 ID ("MainCampus" 或 "Karamay")
  97.         return selectedCampus.id;
  98.     }
  99.     return null;
  100. }
  101. // 3. 获取学期信息
  102. async function getTermCode() {
  103.     if (typeof $ === 'undefined' || !$.ajax) {
  104.         throw new Error("未检测到 jQuery 环境,请确保在正确的课表页面执行。");
  105.     }
  106.     const termData = await new Promise((resolve, reject) => {
  107.         $.ajax({
  108.             type: 'get',
  109.             dataType: 'json',
  110.             url: '/gmis/default/bindterm',
  111.             cache: false,
  112.             success: function (data) { resolve(data); },
  113.             error: function (xhr, status, error) { reject(new Error(`网络请求失败,状态码: ${xhr.status} ${error}`)); }
  114.         });
  115.     });
  116.     if (!termData || termData.length === 0) {
  117.         throw new Error("未能获取到有效的学期列表数据。");
  118.     }
  119.     const semesterTexts = [];
  120.     const semesterValues = [];
  121.     let defaultSelectedIndex = 0;
  122.     termData.forEach((item, index) => {
  123.         semesterTexts.push(item.termname);
  124.         semesterValues.push(item.termcode);
  125.         if (item.selected) {
  126.             defaultSelectedIndex = index;
  127.         }
  128.     });
  129.     const selectedIndex = await window.AndroidBridgePromise.showSingleSelection(
  130.         "选择导入学期",
  131.         JSON.stringify(semesterTexts),
  132.         defaultSelectedIndex
  133.     );
  134.     if (selectedIndex !== null && selectedIndex >= 0) {
  135.         return semesterValues[selectedIndex];
  136.     }
  137.     return null;
  138. }
  139. // 4. 获取课程数据
  140. async function fetchData(termCode) {
  141.     if (typeof $ === 'undefined' || !$.ajax) {
  142.         throw new Error("未检测到 jQuery 环境,请确保在正确的课表页面执行。");
  143.     }
  144.     const response = await new Promise((resolve, reject) => {
  145.         $.ajax({
  146.             type: 'post',
  147.             dataType: 'json',
  148.             url: "../pygl/py_kbcx_ew",
  149.             data: { 'kblx': 'xs', 'termcode': termCode },
  150.             cache: false,
  151.             success: function (data) { resolve(data); },
  152.             error: function (xhr, status, error) { reject(new Error(`网络请求失败,状态码: ${xhr.status} ${error}`)); }
  153.         });
  154.     });
  155.     if (!response || !response.rows) {
  156.         throw new Error("接口返回数据为空或解密后格式不正确");
  157.     }
  158.     return response.rows;
  159. }
  160. // 5. 导入课程数据
  161. async function parseCourses(py_kbcx_ew, isKaramayCampus) {   
  162.     // 用于存放每一小节课的临时数组
  163.     let allCourseBlocks = [];
  164. // 辅助函数 1:根据 jcid 转换成标准的节次编号
  165.     function getStandardSection(jcid) {
  166.         if (jcid >= 11 && jcid <= 15) return jcid - 10;
  167.         let afternoonOffset = isKaramayCampus ? 5 : 4;
  168.         if (jcid >= 21 && jcid <= 24) return jcid - 20 + afternoonOffset;
  169.         let eveningOffset = isKaramayCampus ? 9 : 8;
  170.         if (jcid >= 31 && jcid <= 33) return jcid - 30 + eveningOffset;
  171.         return 1; // 默认兜底
  172.     }
  173.     // 辅助函数 2:解析类似 "连续周 1-12周" 或 "单周 1-11周" 的字符串,返回数字数组
  174.     function parseWeeks(weekStr) {
  175.         let weeks = [];
  176.         let isSingle = weekStr.includes('单');
  177.         let isDouble = weekStr.includes('双');
  178.         let matches = weekStr.match(/\d+-\d+|\d+/g);
  179.         if (matches) {
  180.             matches.forEach(m => {
  181.                 if (m.includes('-')) {
  182.                     let [start, end] = m.split('-').map(Number);
  183.                     for (let i = start; i <= end; i++) {
  184.                         if (isSingle && i % 2 === 0) continue;
  185.                         if (isDouble && i % 2 !== 0) continue;
  186.                         weeks.push(i);
  187.                     }
  188.                 } else {
  189.                     let w = Number(m);
  190.                     if (isSingle && w % 2 === 0) return;
  191.                     if (isDouble && w % 2 !== 0) return;
  192.                     weeks.push(w);
  193.                 }
  194.             });
  195.         }
  196.         return [...new Set(weeks)].sort((a, b) => a - b);
  197.     }
  198.     // --- 第一步:将按“行”排列的数据,拆解提取出每一小节课 ---
  199.     py_kbcx_ew.forEach(row => {
  200.         // 本校区强行剔除上午第5节 (jcid === 15)
  201.         if (!isKaramayCampus && row.jcid === 15) {
  202.             return;
  203.         }
  204.         let currentSection = getStandardSection(row.jcid);
  205.         // 遍历星期一 (z1) 到星期日 (z7)
  206.         for (let day = 1; day <= 7; day++) {
  207.             let zVal = row['z' + day];
  208.             if (zVal) {
  209.                 // 如果同一个时间有两门课(比如单双周不同),按 <br/> 拆分
  210.                 let classParts = zVal.split(/<br\s*\/?>/i);
  211.                
  212.                 classParts.forEach(part => {
  213.                     let match = part.match(/(.*?)\[(.*?)\]([^\[]*)(?:\[(.*?)\])?$/);
  214.                    
  215.                     if (match) {
  216.                         allCourseBlocks.push({
  217.                             name: match[1].trim(),                   // 提取:课程名
  218.                             weekStr: match[2].trim(),                // 提取:原始周次字符串 (用于后续比对)
  219.                             weeks: parseWeeks(match[2]),             // 解析:纯数字周次数组
  220.                             teacher: match[3] ? match[3].trim() : "",// 提取:老师
  221.                             position: match[4] ? match[4].trim() : "未知地点", // 提取:上课地点
  222.                             day: day,                                // 星期几
  223.                             section: currentSection                  // 当前是第几节
  224.                         });
  225.                     }
  226.                 });
  227.             }
  228.         }
  229.     });
  230.     // --- 第二步:将连续的小节课“合并”成一门完整的课 ---
  231.     let mergedCourses = [];
  232.     allCourseBlocks.forEach(block => {
  233.         // 寻找是否已经有相邻的课可以合并 (同星期、同课名、同老师、同地点、同周次,且节次刚好挨着)
  234.         let existingCourse = mergedCourses.find(c =>
  235.             c.day === block.day &&
  236.             c.name === block.name &&
  237.             c.teacher === block.teacher &&
  238.             c.position === block.position &&
  239.             c.weekStr === block.weekStr &&
  240.             c.endSection === block.section - 1 // 核心:判断是否紧挨着上一节
  241.         );
  242.         if (existingCourse) {
  243.             // 如果可以合并,就把结束节次往后延
  244.             existingCourse.endSection = block.section;
  245.         } else {
  246.             // 如果不能合并,就作为一门新课加入
  247.             mergedCourses.push({
  248.                 name: block.name,
  249.                 teacher: block.teacher,
  250.                 position: block.position,
  251.                 day: block.day,
  252.                 startSection: block.section,
  253.                 endSection: block.section,
  254.                 weeks: block.weeks,
  255.                 weekStr: block.weekStr
  256.             });
  257.         }
  258.     });
  259.     // 清理掉多余的辅助比对字段,输出最终给拾光 App 的标准格式
  260.     const finalCourses = mergedCourses.map(c => {
  261.         delete c.weekStr;
  262.         return c;
  263.     });
  264.     const result = await window.AndroidBridgePromise.saveImportedCourses(JSON.stringify(finalCourses));
  265.     if (result !== true) {
  266.         throw new Error("课程导入失败,请查看日志。");
  267.     }
  268. }
  269. // 6. 导入预设时间段
  270. async function importPresetTimeSlots(campusId) {   
  271.     const campusConfig = PRESET_TIME_CONFIG.campuses[campusId];
  272.     const commonConfig = PRESET_TIME_CONFIG.common;
  273.     const generatedSlots = [];
  274.     let currentSectionNum = 1;
  275.     // 辅助函数:把 HH:mm 转换成分钟数 (例如 08:00 -> 480)
  276.     function timeToMinutes(timeStr) {
  277.         const [h, m] = timeStr.split(':').map(Number);
  278.         return h * 60 + m;
  279.     }
  280.     // 辅助函数:把分钟数转换成 HH:mm
  281.     function minutesToTime(mins) {
  282.         const h = Math.floor(mins / 60).toString().padStart(2, '0');
  283.         const m = (mins % 60).toString().padStart(2, '0');
  284.         return `${h}:${m}`;
  285.     }
  286.     // 按照上午、下午、晚上的顺序生成
  287.     const periods = ["morning", "afternoon", "evening"];
  288.    
  289.     periods.forEach(period => {
  290.         const count = campusConfig.sectionCounts[period];
  291.         if (count === 0) return; // 如果该时段没课,跳过
  292.         let currentMins = timeToMinutes(campusConfig.startTimes[period]);
  293.         const longBreakPos = commonConfig.longBreakAfter[period];
  294.         for (let i = 1; i <= count; i++) {
  295.             const startStr = minutesToTime(currentMins);
  296.             currentMins += campusConfig.durations.classMinutes; // 加上课时间
  297.             const endStr = minutesToTime(currentMins);
  298.             generatedSlots.push({
  299.                 number: currentSectionNum,
  300.                 startTime: startStr,
  301.                 endTime: endStr
  302.             });
  303.             currentSectionNum++;
  304.             // 如果不是该时段的最后一节课,则加上课间休息时间,推算出下一节的开始时间
  305.             if (i < count) {
  306.                 if (i === longBreakPos) {
  307.                     currentMins += campusConfig.durations.longBreakMinutes;
  308.                 } else {
  309.                     currentMins += campusConfig.durations.shortBreakMinutes;
  310.                 }
  311.             }
  312.         }
  313.     });
  314.     const result = await window.AndroidBridgePromise.savePresetTimeSlots(JSON.stringify(generatedSlots));
  315.     if (result !== true) {
  316.         throw new Error("时间段导入失败,请查看日志。");
  317.     }
  318. }
  319. // 7. 导入课表配置
  320. async function saveConfig() {
  321.     let startDate = await window.AndroidBridgePromise.showPrompt(
  322.         "输入开学日期",
  323.         "请输入本学期开学日期 (格式: YYYY-MM-DD):",
  324.         "2025-09-01",          
  325.         "validateDateInput"    
  326.     );
  327.     if (startDate === null) {
  328.         startDate = "2025-09-01";
  329.     } else {
  330.         startDate = startDate.trim().replace(/[\/\.]/g, '-');
  331.     }
  332.     const courseConfigData = {
  333.         "semesterStartDate": startDate,
  334.         "semesterTotalWeeks": 25,
  335.         "defaultClassDuration": 45,
  336.         "defaultBreakDuration": 5,
  337.         "firstDayOfWeek": 1
  338.     };
  339.     const configJsonString = JSON.stringify(courseConfigData);
  340.     const result = await window.AndroidBridgePromise.saveCourseConfig(configJsonString);
  341.     if (result !== true) {
  342.         throw new Error("导入配置失败,请查看日志。");
  343.     }
  344. }
  345. /**
  346.  * 编排整个课程导入流程。
  347.  */
  348. async function runImportFlow() {
  349.     try {
  350.         // 1. 公告和前置检查。
  351.         const alertConfirmed = await promptUserToStart();
  352.         if (!alertConfirmed) {
  353.             throw new Error("导入已取消。");
  354.         }
  355.        
  356.         // 2. 选择校区。 (获取校区ID)
  357.         const campusId = await selectCampus();
  358.         if (campusId === null) {
  359.             throw new Error("导入已取消:未选择校区。");
  360.         }
  361.        
  362.         // 生成一个 boolean 给解析课程使用
  363.         const isKaramayCampus = (campusId === "Karamay");
  364.         // 3. 获取学期。
  365.         const termCode = await getTermCode();
  366.         if (termCode === null) {
  367.             throw new Error("导入已取消:未选择学期。");
  368.         }
  369.         // 4. 获取课程数据
  370.         const py_kbcx_ew = await fetchData(termCode);
  371.         // 5. 解析课程信息。 (传入 boolean)
  372.         await parseCourses(py_kbcx_ew, isKaramayCampus);
  373.        
  374.         // 6. 导入时间段数据。 (传入字符串 campusId,供引擎推算)
  375.         await importPresetTimeSlots(campusId);
  376.        
  377.         // 7. 保存配置数据
  378.         await saveConfig();
  379.         // 8. 流程**完全成功**,发送结束信号。
  380.         AndroidBridge.notifyTaskCompletion();
  381.     } catch (error) {
  382.         const message = error && error.message ? error.message : "导入流程执行失败。";
  383.         if (typeof AndroidBridge !== 'undefined') {
  384.             AndroidBridge.showToast(message);
  385.         }
  386.         console.error("runImportFlow error:", error);
  387.     }
  388. }
  389. // 启动所有演示
  390. runImportFlow();