#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""PATCH-3：月份选择器按视图切换、视图按钮与月份翻页事件、插值开关、导出补官方数据"""
import os
BASE = "/Users/liuxinyuan/Desktop/Hermes输出-工作类"
P = os.path.join(BASE, "数据/_kpi_dashboard_template.html")
h = open(P).read()
LOG = []
def rep(old, new, label):
    global h
    assert old in h, "MISS: " + label
    h = h.replace(old, new, 1); LOG.append(label)

# 月份下拉：官方视图用通报月份
rep("""  $('selMonth').innerHTML = SCHEME.meta.months.map(m=>`<option value="${m}"${m===state.month?' selected':''}>${MONTH_LABEL[m]||m}</option>`).join('');""",
    """  if(state.view==='actual'){
    const ms = actMonths();
    if(!state.actMonth || ms.indexOf(state.actMonth)<0) state.actMonth = ms.length? ms[ms.length-1] : null;
    $('selMonth').innerHTML = ms.map(m=>`<option value="${m}"${m===state.actMonth?' selected':''}>${MONTH_LABEL[m]||m}</option>`).join('');
  } else {
    $('selMonth').innerHTML = SCHEME.meta.months.map(m=>`<option value="${m}"${m===state.month?' selected':''}>${MONTH_LABEL[m]||m}</option>`).join('');
  }""", "month options")

# 事件
rep("""$('selMonth').onchange = e=>{ state.month = e.target.value; render(); };
$('mPrev').onclick = ()=>{ const i=SCHEME.meta.months.indexOf(state.month); if(i>0){ state.month=SCHEME.meta.months[i-1]; render(); } };
$('mNext').onclick = ()=>{ const i=SCHEME.meta.months.indexOf(state.month); if(i<SCHEME.meta.months.length-1){ state.month=SCHEME.meta.months[i+1]; render(); } };""",
    """$('selMonth').onchange = e=>{ if(state.view==='actual') state.actMonth = e.target.value; else state.month = e.target.value; render(); };
$('mPrev').onclick = ()=>{ const L = state.view==='actual'? actMonths() : SCHEME.meta.months; const cur = state.view==='actual'? state.actMonth : state.month;
  const i = L.indexOf(cur); if(i>0){ if(state.view==='actual') state.actMonth=L[i-1]; else state.month=L[i-1]; render(); } };
$('mNext').onclick = ()=>{ const L = state.view==='actual'? actMonths() : SCHEME.meta.months; const cur = state.view==='actual'? state.actMonth : state.month;
  const i = L.indexOf(cur); if(i>=0 && i<L.length-1){ if(state.view==='actual') state.actMonth=L[i+1]; else state.month=L[i+1]; render(); } };
$('btnViewActual').onclick = ()=>{ state.view='actual'; render(); };
$('btnViewSim').onclick = ()=>{ state.view='sim'; render(); };""", "events")

# 插值开关
rep("""['A1','A2','A3','B0'].forEach(id=>{ const el=$('set'+id); if(el) el.value = (id==='B0'? state.below*100 : state.anchors[id[1]]*100); });""",
    """['A1','A2','A3','B0'].forEach(id=>{ const el=$('set'+id); if(el) el.value = (id==='B0'? state.below*100 : state.anchors[id[1]]*100); });
$('setIP').checked = !!state.interp;
$('setIP').onchange = e=>{ state.interp = e.target.checked; render(); };""", "interp handler")

# 导出：官方视图导出官方数据
rep("""$('btnExport').onclick = ()=>{
  const out = {month:state.month, role:ROLES[state.roleKey].name, level:ROLES[state.roleKey].level,
    generated:new Date().toISOString(), scoring:{full:state.full, anchors:state.anchors, rating:state.rating},
    people: peopleOf(state.roleKey).map(p=>({name:p.name, region:p.region, ...computePerson(p)})), raw_values:state.vals};""",
    """$('btnExport').onclick = ()=>{
  const c = state.view==='actual'? actCfg() : null;
  const out = state.view==='actual'
    ? {view:'official', month:state.actMonth, role:ROLES[state.roleKey].name, level:ROLES[state.roleKey].level,
       generated:new Date().toISOString(), official:c,
       review: (c&&c.people||[]).map(n=>{ const r = (ROLES[state.roleKey].months&&ROLES[state.roleKey].months[state.actMonth])? reviewPerson(n):null;
         return {name:n, official_total:c.total[n], official_task:c.kt[n], engine_task:(r? r.task:null), engine_total:(r? r.total:null)}; })}
    : {view:'engine', month:state.month, role:ROLES[state.roleKey].name, level:ROLES[state.roleKey].level,
    generated:new Date().toISOString(), scoring:{full:state.full, anchors:state.anchors, rating:state.rating, interp:state.interp},
    people: peopleOf(state.roleKey).map(p=>({name:p.name, region:p.region, ...computePerson(p)})), raw_values:state.vals};""", "export")

rep("""  a.download = `KPI积分卡_${ROLES[state.roleKey].name}_${MONTH_LABEL[state.month]}.json`;""",
    """  a.download = `KPI积分卡_${ROLES[state.roleKey].name}_${MONTH_LABEL[state.view==='actual'?state.actMonth:state.month]}.json`;""",
    "export name")

# 去掉无用行
rep("""  $('banner').innerHTML = $('banner').innerHTML;
}""", """}""", "drop noop")

open(P, "w").write(h)
print("PATCH-3 OK:", len(LOG), "edits")
for x in LOG: print("  -", x)
