// ==================== 整改管理(C1 完整闭环) ====================
const RECT_STATUS = ['草稿','待派发','整改中','待审核','待初验','待评估','已办结'];
let rectFilter = {status:'', overdue:false, keyword:'', page:1};
async function renderRectifications(){
const qsArr = [];
if(rectFilter.status) qsArr.push('status='+encodeURIComponent(rectFilter.status));
if(rectFilter.overdue) qsArr.push('overdue=1');
if(rectFilter.keyword) qsArr.push('keyword='+encodeURIComponent(rectFilter.keyword));
const query = qsArr.length ? ('?'+qsArr.join('&')) : '';
const [rows, stats] = await Promise.all([api('/rectifications'+query), api('/rectifications/stats')]);
window._rects = rows;
qs('pageActions').innerHTML = `
下载导入模板
导出Excel
`;
const cards = [
{n:stats.total, l:'工单总数'}, {n:stats.by_status['整改中']||0, l:'整改中', c:'b-cyan'},
{n:stats.by_status['待审核']||0, l:'待审核', c:'b-amber'}, {n:stats.by_status['待初验']||0, l:'待初验', c:'b-purple'},
{n:stats.by_status['待评估']||0, l:'待评估', c:'b-purple'}, {n:stats.by_status['已办结']||0, l:'已办结', c:'b-green'},
{n:stats.overdue, l:'超期工单', c:'b-red'}
];
qs('content').innerHTML = `
${cards.map(x=>`
`).join('')}
`;
}
function setRectFilter(status, overdue){
rectFilter = Object.assign({}, rectFilter, {status: status||'', overdue: !!overdue, page: 1});
renderRectifications();
}
function rectSearch(){
rectFilter.keyword = (qs('rectKeyword')||{}).value || '';
rectFilter.page = 1;
renderRectifications();
}
function rectSearchReset(){ rectFilter={status:'',overdue:false,keyword:'',page:1}; renderRectifications(); }
function rectGoPage(n){
rectFilter.page = n;
const rows = window._rects || [];
const paged = pageRows(rows, n);
rectFilter.page = paged.page;
qs('rectTableWrap').innerHTML = rectTable(paged.items) + pagerHtml(paged.page, paged.total, paged.pages, 'rectGoPage');
}
function rectStatusBadge(s){
const map = {'草稿':'b-gray','待派发':'b-amber','整改中':'b-cyan','待审核':'b-purple','待初验':'b-purple','待评估':'b-purple','已办结':'b-green'};
return ''+esc(s||'')+'';
}
function rectActions(r){
let b = '';
const st = r.status;
if(st==='草稿' || st==='待派发'){
b += ` `;
b += ` `;
} else if(st==='整改中'){
b += ` `;
} else if(st==='待审核'){
b += ` `;
} else if(st==='待初验'){
b += ` `;
} else if(st==='待评估'){
b += ` `;
}
b += ` `;
b += ``;
return b;
}
function rectTable(rows){
return tableHtml([
{label:'工单编号',render:r=>''+esc(r.work_no||'-')+''},
{label:'问题',render:r=>''+esc(r.issue)+''},
{label:'责任部门/人',render:r=>esc((r.dept||'-')+' / '+(r.owner||'-'))},
{label:'等级',render:r=>statusBadge(r.level)},
{label:'期限',render:r=>''+fmt(r.deadline)+''},
{label:'进度',render:r=>progressBar(r.progress)},
{label:'状态',render:r=>rectStatusBadge(r.status)},
{label:'操作',render:r=>rectActions(r)}
], rows);
}
async function openRectForm(id){
if(!cache.projects.length) cache.projects = await api('/projects');
const r = id ? (window._rects||[]).find(x=>x.id===id) : null;
state.modalType='rect_form'; state.modalId=id||null;
const pOpts = cache.projects.map(p=>``).join('');
qs('modalTitle').textContent = id ? '编辑整改工单' : '新建整改工单';
qs('modalBody').innerHTML = `
`;
qs('modalSaveBtn').textContent='保存';
qs('modalMask').classList.add('show');
}
async function openRectAction(id, kind){
const r = (window._rects||[]).find(x=>x.id===id);
if(!r) return;
state.modalType='rect_'+kind; state.modalId=id;
const title = {dispatch:'派发工单', feedback:'提交整改反馈', audit:'审核工单', initial:'整改初验(六必问)', evaluate:'整改专项评估'}[kind];
let body = ``;
if(kind==='dispatch'){
body += `
`;
} else if(kind==='feedback'){
body += `
`;
} else if(kind==='audit' || kind==='initial' || kind==='evaluate'){
if(kind==='initial'){
body += ['问题是否查清','责任是否落实','整改是否到位','制度是否完善','问责是否严格','效果是否明显'].map((q,i)=>
``).join('');
}
const opts = kind==='audit' ? ['通过','驳回'] : kind==='initial' ? ['通过','驳回'] : ['整改到位','整改不到位'];
body += ``;
}
qs('modalTitle').textContent = title;
qs('modalBody').innerHTML = body;
qs('modalSaveBtn').textContent='提交';
qs('modalMask').classList.add('show');
}
async function saveRectModal(){
const t = state.modalType, id = state.modalId;
if(t==='rect_import'){
const input = qs('ri_file');
if(!input || !input.files.length){ toast('请选择文件'); return; }
const fd = new FormData(); fd.append('file', input.files[0]);
const res = await fetch(API+'/rectifications/import',{method:'POST',body:fd});
const data = await res.json();
if(!res.ok){ toast('导入失败:'+(data.detail||res.status)); return; }
closeModal(); toast(`导入完成:成功 ${data.ok} 条` + (data.errors&&data.errors.length?(',失败 '+data.errors.length+' 条'):''));
renderRectifications(); return;
}
if(t==='rect_form'){
const data = {
issue: qs('rt_issue').value, project_id: qs('rt_project').value?Number(qs('rt_project').value):null,
dept: qs('rt_dept').value, owner: qs('rt_owner').value, level: qs('rt_level').value,
priority: qs('rt_priority').value, deadline: qs('rt_deadline').value,
branch: (qs('rt_branch')||{}).value || '总院区',
requirement: qs('rt_requirement').value
};
if(id) await api('/rectifications/'+id,{method:'PUT',body:JSON.stringify(data)});
else await api('/rectifications',{method:'POST',body:JSON.stringify(data)});
closeModal(); toast('工单已保存'); renderRectifications(); return;
}
const r = (window._rects||[]).find(x=>x.id===id) || {};
let action = '';
let data = {};
if(t==='rect_dispatch'){
action='dispatch';
data={owner:qs('ra_owner').value, deadline:qs('ra_deadline').value, comment:qs('ra_comment').value};
} else if(t==='rect_feedback'){
action='feedback';
data={feedback:qs('ra_feedback').value, actual_date:qs('ra_actual').value, progress:Number(qs('ra_progress').value||0), comment:''};
} else {
const result = qs('ra_result').value;
data.comment = qs('ra_comment').value;
if(t==='rect_audit') action = result==='通过'?'audit_pass':'audit_reject';
else if(t==='rect_initial'){
action = result==='通过'?'initial_pass':'initial_reject';
for(let i=1;i<=6;i++) data['q'+i]=qs('ra_q'+i).value;
} else if(t==='rect_evaluate') action = result==='整改到位'?'evaluate_pass':'evaluate_reject';
}
const res = await api(`/rectifications/${id}/action`,{method:'POST',body:JSON.stringify({action,data})});
if(!res.ok){ toast(res.message||'操作失败'); return; }
closeModal(); toast(res.message||'操作成功'); renderRectifications();
}
async function viewRectHistory(id){
const rows = await api(`/rectifications/${id}/history`);
state.modalType='view';
qs('modalTitle').textContent='工单流转记录';
qs('modalBody').innerHTML = tableHtml([
{label:'时间',key:'created_at'},{label:'操作',key:'action'},
{label:'状态变化',render:r=>esc((r.from_status||'-')+' → '+(r.to_status||'-'))},
{label:'意见',key:'comment'},{label:'操作人',key:'operator'}
], rows);
qs('modalSaveBtn').textContent='关闭'; qs('modalMask').classList.add('show');
}
function openRectImport(){
state.modalType='rect_import';
qs('modalTitle').textContent='批量导入整改工单';
qs('modalBody').innerHTML = `
请先下载导入模板,按表头填写;问题描述为必填。
`;
qs('modalSaveBtn').textContent='开始导入'; qs('modalMask').classList.add('show');
}
async function importFindings(){
if(!confirm('从审计分析结果和检查风险数据导入高风险问题?已导入的不重复。')) return;
toast('正在导入...');
try{ const r=await api('/rectifications/import-findings',{method:'POST'}); toast('导入完成,新增 '+r.created+' 项'); renderRectifications(); }
catch(e){ toast('导入失败:'+e.message); }
}
// ==================== 整改报表(C2) ====================
let rectDim = 'dept';
let rectBranch = '';
const RECT_DIMS = {branch:'分院', dept:'责任部门', project:'关联项目', year:'年度'};
async function renderRectReports(){
const query = 'dimension=' + rectDim + (rectBranch ? '&branch=' + encodeURIComponent(rectBranch) : '');
const [map, stats, rep] = await Promise.all([
api('/rectifications/map'),
api('/rectifications/stats'),
api('/rectifications/report?' + query)
]);
qs('pageActions').innerHTML = `
导出报表Excel`;
const branchHtml = map.length ? map.map(b=>`
${esc(b.name)}
${b.total}
已办结 ${b.done} · 超期 ${b.overdue} · 完成率 ${b.done_rate}%
${(b.departments||[]).slice(0,4).map(d=>`${esc(d.name)} ${d.total}`).join('')}
`).join('') : '暂无整改工单数据,先在「整改管理」创建或导入工单
';
qs('content').innerHTML = `
${stats.done_rate}%
整改完成率
已办结 ${stats.done} / ${stats.total}
${(stats.by_status['待审核']||0)+(stats.by_status['待初验']||0)+(stats.by_status['待评估']||0)}
待流转工单
组织分布 点击分院下钻查看科室分布
${rectBranch?`← 返回全部分院`:''}
${branchHtml}
${rectBranch?esc(rectBranch)+' · ':''}${RECT_DIMS[rep.dimension]}分布
${RECT_DIMS[rep.dimension]}统计明细 共 ${rep.rows.length} 行
${tableHtml([
{label:RECT_DIMS[rep.dimension],render:r=>''+esc(r.name)+''},
{label:'工单总数',render:r=>r.total},
{label:'已办结',render:r=>''+r.done+''},
{label:'未办结',render:r=>r.pending},
{label:'超期',render:r=>''+r.overdue+''},
{label:'完成率',render:r=>progressBar(r.done_rate)}
], rep.rows)}
`;
const top = rep.rows.slice(0,10);
drawChart('rectBar', {type:'bar', data:{labels:top.map(x=>x.name), datasets:[{label:'工单数', data:top.map(x=>x.total), backgroundColor:'rgba(79,209,255,.55)', borderRadius:6}]}, options:chartOpts(false)});
const t = rep.trend || [];
drawChart('rectTrend', {type:'line', data:{labels:t.map(x=>x.month), datasets:[
{label:'新建', data:t.map(x=>x.created), borderColor:'#4fd1ff', backgroundColor:'rgba(79,209,255,.12)', fill:true, tension:.35, pointRadius:3},
{label:'办结', data:t.map(x=>x.closed), borderColor:'#5ee6a8', backgroundColor:'rgba(94,230,168,.12)', fill:true, tension:.35, pointRadius:3}
]}, options:Object.assign(chartOpts(true), {plugins:{legend:{display:true, labels:{color:'#9db8cc',font:{size:11}}}}})});
}
function rectSetDim(v){ rectDim = v; rectBranch=''; renderRectReports(); }
function rectSetBranch(b){ rectBranch = b; rectDim = b ? 'dept' : 'dept'; renderRectReports(); }