import pathlib, re, sys

BASE = pathlib.Path('/Users/liuxinyuan/Desktop/Hermes输出-工作类')
src = BASE / '工具/客户拉通大表_demo_v8_研发填写板块.html'
dst = BASE / '工具/客户拉通大表_demo_v10_活动任务闭环_20261031_V01.html'

s = src.read_text(encoding='utf-8')
orig = s

# 1) 标题与副标题
s = s.replace('客户拉通大表 · 两层设计 DEMO', '客户拉通大表 · 活动任务闭环 DEMO', 1)
s = s.replace('① 第一层｜项目推移表（默认<b>轨道视图</b>，可切表格视图） ｜ ② 第二层｜活动录入与待办',
              '① 第一层｜项目推移表 ｜ ② 第二层｜活动录入与待办 ｜ ③ 任务闭环｜活动派单', 1)

# 2) 第三 Tab
old_tabs = '    <button class="tab" data-t="l2">② 第二层｜活动录入与待办</button>\n  </div>'
new_tabs = ('    <button class="tab" data-t="l2">② 第二层｜活动录入与待办</button>\n'
            '    <button class="tab" data-t="l3">③ 任务闭环｜活动派单</button>\n  </div>')
assert old_tabs in s
s = s.replace(old_tabs, new_tabs, 1)

# 3) 研发填写板块：保留 DOM 以免 R&D 脚本报错，但整体隐藏（先下线）
start = '<div class="grp-title">研发填写板块'
end = '<div class="grp-title">已录入活动'
a = s.index(start); b = s.index(end)
assert a < b
s = s[:a] + '<div id="rdBlock" style="display:none">\n' + s[a:b] + '</div>\n' + s[b:]

# 4) 第三面板（iframe 复用任务闭环单页）
panel = '''  <div class="panel" id="panel-l3" style="display:none">
    <div class="logic">
      <b>任务闭环</b>：销售在「活动录入」写完活动后，勾选需要的支持类型（技术 / 质量 / 研发 / 售后 / 冻干 / 其他），
      填写执行人与执行节点，提交即生成任务。执行人接单回填，销售验收关闭，卡点进入分析。
      原「研发填写板块」已下线，由本页承接。
    </div>
    <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:10px 0">
      <span class="note" style="margin:0">任务来源：活动录入页「支持任务」；本页嵌入任务闭环工作台（同源 localStorage 演示）。</span>
      <button id="taskRefresh" type="button" style="border:1px solid var(--line);background:#fff;border-radius:8px;padding:6px 12px;font-size:12px;cursor:pointer">刷新任务</button>
    </div>
    <iframe id="taskFrame" src="客户项目任务闭环_Demo_20261031_V01.html?embed=1"
      style="width:100%;height:calc(100vh - 235px);min-height:720px;border:1px solid var(--line);border-radius:12px;background:#fff"></iframe>
  </div>

'''
marker = '<!-- 三轨落盘弹层 -->'
assert marker in s
s = s.replace(marker, panel + marker, 1)

# 5) Tab 切换
old_js = "  $('panel-l2').style.display = b.dataset.t==='l2' ? '' : 'none';\n});"
new_js = ("  $('panel-l2').style.display = b.dataset.t==='l2' ? '' : 'none';\n"
          "  $('panel-l3').style.display = b.dataset.t==='l3' ? '' : 'none';\n"
          "  if(b.dataset.t==='l3' && $('taskFrame')) $('taskFrame').src='客户项目任务闭环_Demo_20261031_V01.html?embed=1&t='+Date.now();\n});")
assert old_js in s
s = s.replace(old_js, new_js, 1)

# 6) v8 活动 → 任务 localStorage 桥
bridge = r'''
/* ===== 活动支持类型 → 任务闭环（localStorage 演示桥） ===== */
const V8_TASK_KEY = 'bior_support_tasks_v1';
function v8Type(st){
  const t = (st && st.type) || '';
  if (t.indexOf('技术') >= 0) return '技术支持测试单';
  if (t.indexOf('质量') >= 0) return '质量支持单';
  if (t.indexOf('研发') >= 0) return '研发优化单';
  if (t.indexOf('售后') >= 0) return '售后单';
  if (t.indexOf('冻干') >= 0) return '冻干单';
  return '其他';
}
function pushV8Tasks(m){
  const picked = m.supportTypes || [];
  if (!picked.length) return 0;
  let old = [];
  try { old = JSON.parse(localStorage.getItem(V8_TASK_KEY) || '[]') || []; } catch(e) { old = []; }
  let added = 0;
  picked.forEach(function(st, i){
    const id = 'SUP-' + m.actId + '-' + (i + 1);
    if (old.some(function(x){ return x.id === id; })) return;
    const typ = v8Type(st);
    old.push({
      id: id, activityId: m.actId, activityType: m.type, customer: m.cust,
      project: m.opp || '', sales: m.sales || '', date: m.date || '',
      type: typ, assignee: (m.tech || '周工'), due: ((m.todos && m.todos[0] && m.todos[0].due) || ''),
      requirement: ((m.todos && m.todos[0] && m.todos[0].item) || (st.note || '') || '由活动生成的支持任务'),
      title: (m.cust || '') + ' · ' + typ, priority: 'P1', status: 'todo',
      createdAt: (m.date || '') + ' ' + '09:00'
    });
    added++;
  });
  if (added) { try { localStorage.setItem(V8_TASK_KEY, JSON.stringify(old)); } catch(e) {} }
  return added;
}
function seedV8Tasks(){
  let n = 0;
  (activities || []).forEach(function(m){ n += pushV8Tasks(m); });
  return n;
}
'''
anchor = "$('btnSubmit').onclick=()=>{"
assert anchor in s
s = s.replace(anchor, bridge + "\n" + anchor, 1)

# 7) 提交时写任务
old_push = "  activities.push(m);\n"
new_push = "  activities.push(m);\n  const _newTasks = pushV8Tasks(m);\n"
assert old_push in s
s = s.replace(old_push, new_push, 1)

# 8) 结果提示补充任务数
old_ok = "  $('formOk').textContent='已提交：'+m.actId+'（三轨落盘）'"
new_ok = "  $('formOk').textContent='已提交：'+m.actId+'（三轨落盘；支持任务 +'+_newTasks+'）'"
assert old_ok in s
s = s.replace(old_ok, new_ok, 1)

# 9) 初始化 seed
s = s.replace("/* ================= §13 商机性质筛选 & 风险预警区 ================= */",
              "setTimeout(seedV8Tasks, 0);\n\n/* ================= §13 商机性质筛选 & 风险预警区 ================= */", 1)

dst.write_text(s, encoding='utf-8')
print('WROTE', dst)
print('size', len(s), 'orig', len(orig))
print('rdBlock', s.count('id="rdBlock"'), 'panel-l3', s.count('id="panel-l3"'), 'bridge', s.count('function pushV8Tasks'))
