/* NY 问卷考试系统数据平台 - 前端逻辑 */ (function () { 'use strict'; const $ = (s, r) => (r || document).querySelector(s); const $$ = (s, r) => Array.prototype.slice.call((r || document).querySelectorAll(s)); const state = { projects: [], questions: [], rows: [], absent: [], unmatched: [], roster: [], // 完整名单(含班级),用于按班级重算统计 prevMap: {}, // sid -> 摘要,用于高亮变化 prevSids: new Set(), // 上一次刷新出现的 sid newSids: new Set(), // 本次刷新新增的 sid(绿色底纹) hasPrev: false, fullScore: 100, sortKey: 'submit_ts', sortAsc: false, timer: null, loading: false, lastSig: '' }; /* ---------------- 本地存储 ---------------- */ // 浏览器关闭后仍然保留,账号/密码等敏感配置除外;进入页面时优先读缓存,再后台异步刷新 const LS = { get(k, def) { try { const v = localStorage.getItem(k); return v == null ? def : JSON.parse(v); } catch (e) { return def; } }, set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) { /* 隐私模式 */ } }, del(k) { try { localStorage.removeItem(k); } catch (e) {} } }; const LS_PROJECTS = 'ny_projects'; const LS_LASTPID = 'ny_last_pid'; const LS_LASTQID = 'ny_last_qid'; const LS_FILTERS = 'ny_filters'; // {cls, grp} -> 跟随 projectId const LS_LAYOUT = 'ny_layout'; const LS_ROSTER = 'ny_roster_cache'; // 名单 cache(用于首屏补齐班级/组别下拉) const dataKey = pid => 'ny_data_' + pid; /* ---------------- 通用 ---------------- */ async function api(action, opts) { opts = opts || {}; const init = { method: opts.method || 'GET' }; if (opts.body) { init.headers = { 'Content-Type': 'application/json' }; init.body = JSON.stringify(opts.body); } if (opts.form) { init.method = 'POST'; init.body = opts.form; } let url = 'api.php?action=' + encodeURIComponent(action); if (opts.params) { for (const k in opts.params) { if (opts.params[k] !== '' && opts.params[k] != null) { url += '&' + k + '=' + encodeURIComponent(opts.params[k]); } } } const res = await fetch(url, init); const text = await res.text(); let json; try { json = JSON.parse(text); } catch (e) { throw new Error('服务端返回异常(可能 PHP 报错):' + text.slice(0, 300)); } if (!json.ok) throw new Error(json.msg || '请求失败'); return json.data; } function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); } function setConn(cls, text) { const el = $('#conn'); el.className = 'conn ' + cls; el.innerHTML = '' + esc(text) + ''; } function showAlert(msg, type) { const el = $('#alert'); if (!msg) { el.classList.add('hidden'); return; } el.textContent = msg; el.className = 'alert' + (type === 'info' ? ' info' : ''); } /* ---------------- 问卷列表 ---------------- */ // 把数组渲染到 #projectSel(抽出便于缓存复用) function renderProjects() { const sel = $('#projectSel'); const keep = sel.value; sel.innerHTML = ''; if (!state.projects.length) { sel.innerHTML = ''; } else { const ph = document.createElement('option'); ph.value = ''; ph.textContent = '请选择问卷 / 考试'; sel.appendChild(ph); // 双策略识别文件夹: // 1) mode 字段含 'folder'(卷王默认) // 2) 被其他项目作为 parent_id 引用(部分版本无 mode 字段,回退推断) const isFolder = p => (p.mode || '').toLowerCase().includes('folder'); const parentIds = new Set(); state.projects.forEach(p => { const pid = (p.parent_id || '0'); if (pid && pid !== '0' && pid !== '') parentIds.add(pid); }); const folderSet = new Set(); state.projects.forEach(p => { if (isFolder(p) || parentIds.has(p.id)) folderSet.add(p.id); }); const childOf = fid => state.projects.filter(p => !folderSet.has(p.id) && (p.parent_id || '0') === fid); const mkOpt = p => { const o = document.createElement('option'); o.value = p.id; o.textContent = (p.mode ? '[' + p.mode + '] ' : '') + p.name + '(' + (p.total || 0) + '份)'; return o; }; // 根项(不在任何文件夹里的) state.projects.filter(p => !folderSet.has(p.id)) .forEach(p => sel.appendChild(mkOpt(p))); // 文件夹及子项(空文件夹不显示,避免点击报错) state.projects.filter(p => folderSet.has(p.id)).forEach(f => { const kids = childOf(f.id); if (!kids.length) return; const og = document.createElement('optgroup'); og.label = '📁 ' + f.name; kids.forEach(p => og.appendChild(mkOpt(p))); sel.appendChild(og); }); } if (keep && state.projects.some(p => p.id === keep)) sel.value = keep; else if (state.deeplinkProject && state.projects.some(p => p.id === state.deeplinkProject)) sel.value = state.deeplinkProject; else { const last = LS.get(LS_LASTPID, ''); if (last && state.projects.some(p => p.id === last)) sel.value = last; } const surveyCount = state.projects.filter(p => !((p.mode || '').toLowerCase().includes('folder'))).length; setConn('conn-on', (state._fromCache ? '缓存 · ' : '') + '已连接 · ' + surveyCount + ' 个问卷'); showAlert(''); if (sel.value) refresh(); } async function loadProjects() { setConn('conn-load', '连接中…'); // 1) 先读本地缓存 → 立刻渲染,避免空白 const cached = LS.get(LS_PROJECTS, []); if (Array.isArray(cached) && cached.length) { state.projects = cached; state._fromCache = true; renderProjects(); } // 2) 再异步刷新 try { const list = await api('projects'); state.projects = list || []; state._fromCache = false; LS.set(LS_PROJECTS, state.projects); renderProjects(); } catch (e) { if (!cached || !cached.length) { setConn('conn-err', '连接失败'); showAlert('无法连接卷王系统:' + e.message + '\n请点击右上角【设置】检查系统地址、接口前缀与账号密码。'); } else { showAlert('⚠️ 后台刷新失败,已显示本地缓存:' + e.message); } } } /* ---------------- 数据刷新 ---------------- */ function applyData(d, opts) { opts = opts || {}; state.questions = d.questions || []; state.rows = d.rows || []; state.absent = d.absent || []; state.unmatched = d.unmatched || []; state.roster = d.roster || []; state.fullScore = (d.config && d.config.full_score) ? (parseInt(d.config.full_score, 10) || 100) : 100; const cur = new Set(state.rows.map(r => r.sid).filter(Boolean)); if (state.hasPrev) state.newSids = new Set(Array.from(cur).filter(s => !state.prevSids.has(s))); else state.newSids = new Set(); state.hasPrev = true; renderNameFields(d); renderStats(); renderTable(); state.prevSids = cur; populateClasses(); populateGroups(); renderAbsent(); renderUnmatched(); renderHints(); $('#lastUpdate').textContent = d.updated_at || '—'; setConn('conn-on', (opts.fromCache ? '缓存 · ' : '') + '实时 · ' + (d.project && d.project.name || '')); if (!opts.fromCache) showAlert(''); } async function refresh(silent) { const pid = $('#projectSel').value; if (!pid) return; if (state.loading && !silent) return; state.loading = true; if (!silent) setConn('conn-load', '拉取数据…'); // 1) 先读本地缓存 → 立即渲染,刷新期间保持视觉稳定 const cached = LS.get(dataKey(pid), null); if (cached && cached.updated_at) { try { applyData(cached, { fromCache: true }); } catch (e) { /* 旧格式缓存忽略 */ } } // 2) 后台异步拉真实数据 try { const d = await api('data', { params: { projectId: pid, nameQid: $('#nameFieldSel').value } }); applyData(d); LS.set(dataKey(pid), d); LS.set(LS_LASTPID, pid); LS.set(LS_LASTQID, $('#nameFieldSel').value || ''); // 名单缓存一份(便于刷新前/失败时仍能渲染班级/组别下拉) LS.set(LS_ROSTER, { ts: Date.now(), students: d.roster || [] }); } catch (e) { if (!cached) { if (!silent) setConn('conn-err', '数据获取失败'); showAlert(e.message); } else { showAlert('⚠️ 后台刷新失败,已显示本地缓存:' + e.message); } } finally { state.loading = false; $('#liveDot').classList.add('on'); setTimeout(() => $('#liveDot').classList.remove('on'), 900); } } function renderNameFields(d) { const sel = $('#nameFieldSel'); const keep = sel.value; sel.innerHTML = ''; const cands = d.name_candidates || []; cands.forEach(q => { const o = document.createElement('option'); o.value = q.id; o.textContent = '姓名题:' + (q.title || q.id); sel.appendChild(o); }); (d.questions || []).forEach(q => { if (cands.some(c => c.id === q.id)) return; const o = document.createElement('option'); o.value = q.id; o.textContent = (q.title || q.id) + '(' + (q.type || '') + ')'; sel.appendChild(o); }); const lastQid = LS.get(LS_LASTQID, ''); if (keep) sel.value = keep; else if (state.deeplinkQid) sel.value = state.deeplinkQid; else if (lastQid && (cands.some(c => c.id === lastQid) || (d.questions || []).some(q => q.id === lastQid))) sel.value = lastQid; else if (d.name_qid) sel.value = d.name_qid; } function populateClasses() { const sel = $('#clsSel'); const cur = sel.value; const set = new Set(); (state.roster || []).forEach(s => { if (s.cls) set.add(s.cls); }); const vals = Array.from(set).sort((a, b) => a.localeCompare(b, 'zh', { numeric: true })); sel.innerHTML = '' + vals.map(v => '').join(''); // 优先保留用户当前已选项;否则按本地缓存恢复(跟随 projectId) const pid = $('#projectSel').value; const cache = pid ? (LS.get(LS_FILTERS, {})[pid] || {}) : {}; if (vals.indexOf(cur) >= 0) sel.value = cur; else if (cache.cls && vals.indexOf(cache.cls) >= 0) sel.value = cache.cls; else sel.value = ''; } // 组别下拉:仅显示当前所选班级内出现的组别("全部班级" 时显示所有组别) function populateGroups() { const cls = $('#clsSel').value; const grpSel = $('#grpSel'); if (!grpSel) return; const cur = grpSel.value; const set = new Set(); (state.roster || []).forEach(s => { if (cls && (s.cls || '') !== cls) return; if (s.grp) set.add(s.grp); }); const vals = Array.from(set).sort(); grpSel.innerHTML = '' + vals.map(v => '').join(''); const pid = $('#projectSel').value; const cache = pid ? (LS.get(LS_FILTERS, {})[pid] || {}) : {}; if (vals.indexOf(cur) >= 0) grpSel.value = cur; else if (cache.grp && vals.indexOf(cache.grp) >= 0) grpSel.value = cache.grp; else grpSel.value = ''; } function rememberFilters() { const pid = $('#projectSel').value; if (!pid) return; const all = LS.get(LS_FILTERS, {}); all[pid] = { cls: $('#clsSel').value, grp: $('#grpSel').value, ts: Date.now() }; LS.set(LS_FILTERS, all); } // 按当前所选班级 + 组别(或无)客户端重算统计卡片 function computeDisplayStats(cls, grp) { const allStudents = state.roster || []; let students = cls ? allStudents.filter(s => (s.cls || '') === cls) : allStudents; let rows = cls ? state.rows.filter(r => (r.cls || '') === cls) : state.rows; if (grp) { students = students.filter(s => (s.grp || '') === grp); rows = rows.filter(r => (r.grp || '') === grp); } const total = students.length; const submitted = rows.length; const absent = Math.max(0, total - submitted); const rate = total > 0 ? Math.round(submitted / total * 1000) / 10 : 0; const scores = rows.map(r => r.score).filter(v => v !== null && v !== undefined); const avg = scores.length ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length * 100) / 100 : null; const full = state.fullScore || 100; const passCount = rows.filter(r => r.score !== null && r.score !== undefined && r.score >= 0.6 * full).length; const passRate = submitted > 0 ? Math.round(passCount / submitted * 1000) / 10 : 0; let maxScore = null, minScore = null; const maxNames = [], minNames = []; rows.forEach(r => { if (r.score === null || r.score === undefined) return; if (maxScore === null || r.score > maxScore) { maxScore = r.score; maxNames.length = 0; maxNames.push(r.name); } else if (r.score === maxScore) maxNames.push(r.name); if (minScore === null || r.score < minScore) { minScore = r.score; minNames.length = 0; minNames.push(r.name); } else if (r.score === minScore) minNames.push(r.name); }); const durs = rows.map(r => r.duration).filter(v => v !== null && v !== undefined); const avgDur = durs.length ? Math.round(durs.reduce((a, b) => a + b, 0) / durs.length) : null; return { total, submitted, absent, rate, avg, passRate, maxScore, minScore, maxNames, minNames, avgDur }; } function renderStats() { const cls = $('#clsSel').value; const grp = $('#grpSel').value; const st = computeDisplayStats(cls, grp); const set = (id, v) => { const el = $(id); if (el) el.textContent = v; }; set('#sTotal', st.total); set('#sSubmit', st.submitted); set('#sAbsent', st.absent); set('#sAvg', st.avg == null ? '-' : st.avg); set('#sMax', st.maxScore == null ? '-' : st.maxScore); set('#sMin', st.minScore == null ? '-' : st.minScore); set('#sPass', st.passRate + '%'); set('#sDur', st.avgDur == null ? '-' : fmtDur(st.avgDur)); } // 各面板计数文字按所选班级 + 组别过滤(成绩明细 / 缺考名单) // 缺考数与统计卡片保持一致:过滤后名单 − 过滤后提交(而非二次过滤后端 absent 数组) function renderHints() { const cls = $('#clsSel').value; const grp = $('#grpSel').value; const rowsForCls = cls ? state.rows.filter(r => (r.cls || '') === cls) : state.rows; const rosterForCls = cls ? (state.roster || []).filter(s => (s.cls || '') === cls) : (state.roster || []); const rowsForGrp = grp ? rowsForCls.filter(r => (r.grp || '') === grp) : rowsForCls; const rosterForGrp = grp ? rosterForCls.filter(s => (s.grp || '') === grp) : rosterForCls; const absentForGrp = Math.max(0, rosterForGrp.length - rowsForGrp.length); $('#tableHint').textContent = '共 ' + rowsForGrp.length + ' 人已提交 · 名单 ' + rosterForGrp.length + ' 人'; $('#absentHint').textContent = absentForGrp ? '共 ' + absentForGrp + ' 人' : ''; } function fmtDur(sec) { if (sec == null) return '-'; if (sec < 60) return sec + ' 秒'; const m = Math.floor(sec / 60), s = sec % 60; if (m < 60) return m + ' 分 ' + String(s).padStart(2, '0') + ' 秒'; const h = Math.floor(m / 60); return h + ' 小时 ' + String(m % 60).padStart(2, '0') + ' 分'; } function scoreClass(v) { if (v == null) return ''; if (v >= 90) return 'score-high'; if (v >= 60) return 'score-mid'; return 'score-low'; } function renderTable() { const kw = $('#kw').value.trim().toLowerCase(); const clsFilter = $('#clsSel').value; const grpFilter = $('#grpSel').value; let rows = state.rows.slice(); if (clsFilter) rows = rows.filter(r => (r.cls || '') === clsFilter); if (grpFilter) rows = rows.filter(r => (r.grp || '') === grpFilter); if (kw) rows = rows.filter(r => String(r.sid).toLowerCase().includes(kw) || String(r.name).toLowerCase().includes(kw)); const k = state.sortKey, dir = state.sortAsc ? 1 : -1; rows.sort((a, b) => { let x = a[k], y = b[k]; if (k === 'sid' || k === 'cls') { const na = parseFloat(x), nb = parseFloat(y); if (!isNaN(na) && !isNaN(nb)) return (na - nb) * dir; return String(x == null ? '' : x).localeCompare(String(y == null ? '' : y), 'zh', { numeric: true }) * dir; } if (x == null) x = -1; if (y == null) y = -1; if (typeof x === 'string') return x.localeCompare(String(y), 'zh', { numeric: true }) * dir; return (x - y) * dir; }); const tb = $('#tbody'); if (!rows.length) { tb.innerHTML = '