// ==================== 核心:API / 工具 / 分页 / 页签 / 弹窗 ====================
const API = '/api/da';
let state = {tab:'dashboard', modalType:null, modalId:null};
const charts = {};
let cache = {projects:[], categories:[], rules:[]};
function esc(s){ return (s===null||s===undefined?'':String(s)).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }
function fmt(v){ return (v===null||v===undefined||v==='')?'—':esc(v); }
function toast(msg){ const t=document.getElementById('toast'); t.textContent=msg; t.classList.add('show'); clearTimeout(t._timer); t._timer=setTimeout(()=>t.classList.remove('show'),3000); }
let _loadingCount = 0;
function showLoading(){
_loadingCount++;
const el = document.getElementById('globalLoading');
if(el) el.classList.add('active');
}
function hideLoading(){
_loadingCount = Math.max(0, _loadingCount - 1);
if(_loadingCount === 0){ const el = document.getElementById('globalLoading'); if(el) el.classList.remove('active'); }
}
async function api(path, opt={}){
showLoading();
try{
const res = await fetch(API+path, Object.assign({headers:{'Content-Type':'application/json'}}, opt));
if (res.status===401){ location.href='/login'; throw new Error('未登录'); }
if (!res.ok){ let d=''; try{ d=(await res.json()).detail||''; }catch(e){} throw new Error(d||('HTTP '+res.status)); }
return await res.json();
} finally {
hideLoading();
}
}
window.addEventListener('unhandledrejection', function(ev){
try{
const msg = (ev.reason && ev.reason.message) || '操作失败';
if(msg && msg !== '未登录'){ toast('操作失败:'+msg); }
}catch(e){}
});
function statusBadge(s){
const map = {'实施中':'b-cyan','报告阶段':'b-purple','整改阶段':'b-amber','已归档':'b-green','已完成':'b-green',
'进行中':'b-cyan','未开始':'b-gray','待整改':'b-amber','整改中':'b-cyan','待验收':'b-purple','已验收':'b-green','已超期':'b-red',
'正常':'b-green','异常':'b-red','待修复':'b-amber','已导入':'b-green','待执行':'b-gray','执行中':'b-cyan',
'已完成':'b-green','执行失败':'b-red','启用':'b-green','停用':'b-gray','R1':'b-red','R2':'b-amber','R3':'b-cyan','R4':'b-gray',
'高':'b-red','中':'b-amber','低':'b-green','极高':'b-red'};
return ''+esc(s||'—')+'';
}
function progressBar(v){ v=Number(v||0); return '
'; }
function tableHtml(columns, rows, actions){
if (!rows.length) return '暂无数据
';
let h=''+columns.map(c=>'| '+c.label+' | ').join('');
if (actions) h+='操作 | ';
h+='
';
rows.forEach(r=>{ h+=''+columns.map(c=>'| '+(c.render?c.render(r):fmt(r[c.key]))+' | ').join(''); if(actions) h+=''+actions(r)+' | '; h+='
'; });
return h+'
';
}
function qs(id){ return document.getElementById(id); }
const PAGE_SIZE = 10;
function pageRows(rows, page, size){
size = size || PAGE_SIZE;
const total = rows.length, pages = Math.max(1, Math.ceil(total / size));
const p = Math.min(Math.max(1, page || 1), pages);
return {items: rows.slice((p - 1) * size, p * size), total, pages, page: p};
}
function pagerHtml(page, total, pages, goFn, size){
size = size || PAGE_SIZE;
if(!total) return '';
const start = (page - 1) * size + 1, end = Math.min(page * size, total);
return ``;
}
const TAB_META = {
dashboard:['审计驾驶舱','聚合真实审计项目、资料、风险与合同数据'],
workflow:['审计作业','底稿 · 取证 · 报告全流程管理'],
parsed:['文档解析','单文件快速解析 + 多文件批量 OCR 任务'],
extract:['合同/单据抽取','合同关键字段 / 单据信息提取,双屏校对与人工纠偏'],
rules:['审计规则库','规则分类、风险等级、规则类型与启停管理'],
tasks:['审计任务','选择项目和规则发起审计,自动扫描资料生成疑点'],
rectifications:['整改管理','整改台账、六必问验收,可从审计发现一键导入'],
rectreports:['整改报表','分院/科室/项目/年度多维统计、组织分布与趋势'],
datasources:['数据资源','真实业务数据库、文件目录与外部数据源接入'],
models:['分析模型','基于真实业务数据运行统计分析模型'],
etl:['数据导入','上传 CSV / Excel,解析后写入临时结果表'],
workflows:['流程配置','项目立项、整改验收、报告签发流程模板'],
logs:['操作日志','记录规则、任务、整改等操作留痕']
};
async function switchTab(tab, el){
state.tab = tab;
document.querySelectorAll('.nav-item').forEach(n=>n.classList.remove('active'));
if (el) el.classList.add('active'); else { const n=document.querySelector('.nav-item[data-tab="'+tab+'"]'); if(n) n.classList.add('active'); }
qs('pageTitle').textContent = TAB_META[tab][0];
qs('pageSub').textContent = TAB_META[tab][1];
qs('pageActions').innerHTML = '';
qs('content').innerHTML = '正在加载…
';
const renderers = {dashboard:renderDashboard, workflow:renderWorkflow, parsed:renderParsed, extract:renderExtractTasks, rules:renderRules, tasks:renderTasks, rectifications:renderRectifications, datasources:renderDatasources,
models:renderModels, etl:renderEtl, workflows:renderWorkflows, logs:renderLogs, rectreports:renderRectReports};
try {
await renderers[tab]();
} catch(e) {
qs('content').innerHTML = `页面加载失败
${esc(e && e.message || String(e))}
`;
}
}
function openAuditSystem(){
const url = `${location.protocol}//${location.hostname}:8000/`;
try {
if (window.self !== window.top) { window.top.location.hash = '#/audit'; return; }
} catch(e) {}
window.open(url, '_blank');
}
async function submitModal(){
try {
if (state.modalType==='accept'){
const payload={status:'已验收',progress:document.getElementById('acceptResult').value==='通过'?100:60};
for(let i=1;i<=6;i++) payload['q'+i]=qs('q'+i).value;
payload.result=qs('acceptResult').value;
if (payload.result!=='通过'){ payload.status='整改中'; }
await api('/rectifications/'+state.modalId,{method:'PUT',body:JSON.stringify(payload)});
closeModal(); toast('验收已提交'); renderRectifications(); return;
}
if (state.modalType==='view'){ closeModal(); return; }
if (state.modalType && state.modalType.startsWith('rect_')){ await saveRectModal(); return; }
if (state.modalType==='wf'){ await wfSave(); return; }
if (state.modalType==='task'){
const ids = Array.from(document.querySelectorAll('.rule-cb:checked')).map(x=>Number(x.value));
if (!ids.length){ toast('请至少选择一条规则'); return; }
const scheduleType = qs('t_schedule') ? qs('t_schedule').value : '立即';
const scheduledAt = qs('t_scheduled') ? qs('t_scheduled').value : '';
if(scheduleType !== '立即' && !scheduledAt){ toast('请选择执行时间'); return; }
const payload={name:qs('t_name').value, task_type:qs('t_type').value,
project_id: qs('t_project').value ? Number(qs('t_project').value) : null,
rule_ids: ids, mode: qs('t_mode').value,
schedule_type: scheduleType, scheduled_at: scheduledAt};
const r=await api('/tasks',{method:'POST',body:JSON.stringify(payload)});
closeModal();
toast(scheduleType==='立即' ? ('任务创建并执行完成,命中 '+r.hits+' 条疑点') : '任务已排期,将按计划自动执行');
switchTab('tasks'); return;
}
const data={};
if (state.modalType==='rule'){
const catSel=qs('f_category'); const catId=Number(catSel.value);
const cat=cache.categories.find(c=>c.id===catId);
Object.assign(data,{name:qs('f_name').value, category_id:catId, category_name:cat?cat.name:'',
risk_level:qs('f_level').value, rule_type:qs('f_type').value, status:qs('f_status').value,
description:qs('f_desc').value, tags:qs('f_tags').value});
try{ data.params=JSON.parse(qs('f_params').value||'{}'); }catch(e){ toast('规则参数不是合法 JSON'); return; }
if (state.modalId) data.id=state.modalId;
await api('/rules',{method:'POST',body:JSON.stringify(data)});
closeModal(); toast('规则已保存'); switchTab('rules'); return;
}
if (state.modalType==='rectification'){
Object.assign(data,{issue:qs('r_issue').value,project_id:qs('r_project').value?Number(qs('r_project').value):null,
dept:qs('r_dept').value,owner:qs('r_owner').value,level:qs('r_level').value,
deadline:qs('r_deadline').value,status:qs('r_status').value,progress:Number(qs('r_progress').value||0)});
if (state.modalId) { await api('/rectifications/'+state.modalId,{method:'PUT',body:JSON.stringify(data)}); }
else { await api('/rectifications',{method:'POST',body:JSON.stringify(data)}); }
closeModal(); toast('整改已保存'); switchTab('rectifications'); return;
}
if (state.modalType==='datasource'){
Object.assign(data,{name:qs('d_name').value,type:qs('d_type').value,endpoint:qs('d_endpoint').value,
auth_type:qs('d_auth').value,schedule:qs('d_schedule').value,status:qs('d_status').value});
await api('/datasources',{method:'POST',body:JSON.stringify(data)});
closeModal(); toast('数据源已保存'); switchTab('datasources'); return;
}
if (state.modalType==='model'){
Object.assign(data,{name:qs('m_name').value,category:qs('m_category').value,risk_level:qs('m_level').value,
rule_type:qs('m_type').value,query_key:qs('m_query').value,description:qs('m_desc').value,status:'启用'});
if (state.modalId) data.id=state.modalId;
await api('/models',{method:'POST',body:JSON.stringify(data)});
closeModal(); toast('模型已保存'); switchTab('models'); return;
}
if (state.modalType==='workflow'){
Object.assign(data,{name:qs('w_name').value,business:qs('w_business').value,status:'启用',
nodes:(qs('w_nodes').value||'').split('\n').filter(x=>x.trim()).map(line=>{const p=line.split('|');return {name:(p[0]||'').trim(),type:(p[1]||'或签').trim()};})});
if (state.modalId) data.id=state.modalId;
await api('/workflows',{method:'POST',body:JSON.stringify(data)});
closeModal(); toast('流程已保存'); switchTab('workflows'); return;
}
} catch(e){ toast('操作失败:'+e.message); }
}
async function delItem(list,id){
if(!confirm('确认删除该记录?删除后不可恢复。'))return;
try{ await api('/'+list+'/'+id,{method:'DELETE'}); toast('已删除'); switchTab(list); }
catch(e){ toast('删除失败:'+e.message); }
}
function closeModal(){ qs('modalMask').classList.remove('show'); state.modalType=null; state.modalId=null; }