#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""把「逐月拆分」看板 Tab 挂进工作台双入口（index.html / app.html）。
不删除、不修改任何现有 Tab：仅在 TABS 新增一项、switch 新增一个 case、
并新增 renderSandept 函数（内嵌 iframe，带身份参数）。"""
import io, os, re, sys

W = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
FILES = [os.path.join(W, '工具/index.html'), os.path.join(W, '工具/app.html')]

TAB_LINE = "  { id: 'dashboard', group: 'biz', label: '看板', icon: '📊', lines: ['da','ls'] },\n"
NEW_TAB = "  { id: 'sandept', group: 'biz', label: '逐月拆分', icon: '📈', lines: ['da','ls'] },\n"
SW_OLD = "case 'dashboard': renderDashboard(main); break;\n"
SW_NEW = "case 'dashboard': renderDashboard(main); break;\n    case 'sandept': renderSandept(main); break;\n"
FN_ANCHOR = "function renderDashboard(main) {"

FN = r"""/* ===== 三部门逐月拆分（工作台内嵌看板 · SANDPT_TAB_V1）=====
   内嵌 iframe 承载 工具/仪表盘/三部门逐月拆分_demo.html；身份经 URL 参数透传（子页 file:// 下拿不到登录态）。 */
function sandeptUserQS() {
  try {
    var u = state.user || {};
    if (!u.name) return '';
    return '&u=' + encodeURIComponent(u.name) + '&r=' + encodeURIComponent(u.role || '') +
           '&d=' + encodeURIComponent(u.dept || '') +
           '&l=' + encodeURIComponent(state.currentLine || u.line || 'da');
  } catch (e) { return ''; }
}
function renderSandept(main) {
  main.innerHTML =
    '<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;flex-wrap:wrap">' +
      '<h2 style="font-size:20px;font-weight:900;margin:0">\U0001F4C8 三部门逐月拆分</h2>' +
      '<span style="color:var(--sub);font-size:13px">部门 × 月度矩阵 · 结构 · 驱动 · 下钻（按当前身份行级过滤，客户名明细仅本人可见）</span>' +
      '<button style="margin-left:auto;border:1px solid var(--border);background:#fff;color:var(--pri);font:inherit;font-size:13px;font-weight:600;padding:6px 14px;border-radius:8px;cursor:pointer" ' +
        'onclick="renderSandept(document.getElementById(\'main\'))">\U0001F504 刷新</button>' +
    '</div>' +
    '<div style="height:calc(100vh - 150px);min-height:760px;background:#fff;border-radius:10px;overflow:hidden;border:1px solid var(--border)">' +
      '<iframe id="sandeptFrame" src="/工具/仪表盘/三部门逐月拆分_demo.html?v=20261006a' + sandeptUserQS() + '" ' +
        'style="width:100%;height:100%;border:none" title="三部门逐月拆分"></iframe>' +
    '</div>';
}

"""

for f in FILES:
    s = io.open(f, encoding='utf-8').read()
    n0 = len(s)
    assert s.count(TAB_LINE) == 1, '%s: TABS 锚点 %d' % (f, s.count(TAB_LINE))
    assert s.count(SW_OLD) == 1, '%s: switch 锚点 %d' % (f, s.count(SW_OLD))
    assert s.count(FN_ANCHOR) == 1, '%s: renderDashboard 锚点 %d' % (f, s.count(FN_ANCHOR))
    assert s.count("id: 'sandept'") == 0, '%s: 已存在 sandept' % f
    s = s.replace(TAB_LINE, TAB_LINE + NEW_TAB, 1)
    s = s.replace(SW_OLD, SW_NEW, 1)
    s = s.replace(FN_ANCHOR, FN + FN_ANCHOR, 1)
    io.open(f, 'w', encoding='utf-8').write(s)
    print('%s: %d -> %d  (+%d)' % (os.path.basename(f), n0, len(s), len(s) - n0))
    # 结构自检
    t = io.open(f, encoding='utf-8').read()
    print('   TABS sandept=%d  switch case=%d  renderSandept def=%d  </body>=%d  <script>=%d </script>=%d'
          % (t.count("id: 'sandept'"), t.count("case 'sandept'"), t.count('function renderSandept'),
             t.count('</body>'), len(re.findall(r'<script', t)), t.count('</script>')))
