#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
前端：给「部门经理」按本部门放权（2026-09-20，针对刘欣-销售拓展部经理）
=====================================================================
问题：
1) getFilteredCustomers 里 manager 分支按 `c.dept === dept` 过滤，而客户数据里没有 dept 字段
   → 经理在客户 Tab 一个客户都看不到。
2) 客户池 / 订单 / 客诉 / 拜访准备四处对非 admin 一律「只看自己」→ 经理看不到本部门数据。
做法：新增 normDeptName() / deptScope() 两个函数，按「人事表里同部门在职成员」算作用域，
     销售不受影响（作用域=本人）；admin/gm 不受影响（全部）。
"""
import os
import re
import sys
import json

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
F = os.path.join(ROOT, '工具', 'index.html')

HELPERS = """/* ── 数据作用域（2026-09-20）：经理看本部门，销售看本人，admin/gm 看全部 ── */
function normDeptName(d) {
  d = String(d || '');
  if (d.indexOf('大客户') >= 0) return '大客户部';
  if (d.indexOf('生命科学') >= 0 || d === '浙江' || d === '广东') return '生命科学销售部';
  if (d.indexOf('拓展部') >= 0) return '销售拓展部';
  return d;
}
// 返回 {names:[本部门在职成员], region:'浙江'|'广东'|''}；admin/gm 返回 null（看全部）
function deptScope() {
  var u = state.user || {};
  var role = u.role || 'sales';
  if (role === 'admin' || role === 'gm') return null;
  if (role !== 'manager') return { names: [u.name || ''], region: '' };
  var p = ((state.data.personnel || {}).personnel || []).filter(function(x) { return x.status === '在职'; });
  var nd = normDeptName(u.dept);
  var names = p.filter(function(x) { return normDeptName(x.dept || x.department) === nd; }).map(function(x) { return x.name; });
  var region = '';
  if (nd === '生命科学销售部') {
    if (String(u.dept || '').indexOf('浙江') >= 0) region = '浙江';
    else if (String(u.dept || '').indexOf('广东') >= 0) region = '广东';
  }
  return { names: names, region: region };
}
function inScope(sc, name) { return !!sc && sc.names.indexOf(name) >= 0; }

"""

PATCHES = [
    # 1) 插入 helper
    ("function getFilteredCustomers() {", HELPERS + "function getFilteredCustomers() {"),
    # 2) 客户 Tab（ERP 客户表）
    ("""  // manager: 本部门
  if (role === 'manager') return custs.filter(function(c) { return c.dept === dept; });""",
     """  // manager: 本部门（按部门成员归属算，客户表里没有 dept 字段）
  if (role === 'manager') return custs.filter(function(c) { return inScope(deptScope(), c.salesperson || c.sales); });"""),
    # 3) 客户池 Tab（MCP 客户）
    ("""  var userName = (state.user||{}).name;
  if (userName && ((state.user||{}).role!=='admin')) {
    all = all.filter(function(c){return c.owner===userName||(c.operators||[]).indexOf(userName)>=0;});
  }""",
     """  var userName = (state.user||{}).name;
  var _scCust = deptScope();
  if (_scCust) {
    all = all.filter(function(c){
      if (_scCust.region) return String(c.dept||'').indexOf(_scCust.region) >= 0 || _scCust.names.indexOf(c.owner) >= 0;
      return _scCust.names.indexOf(c.owner) >= 0 || (c.operators||[]).some(function(op){return _scCust.names.indexOf(op)>=0;});
    });
  }"""),
    # 4) 看板：订单
    ("""  // 基础隔离：非admin只看自己
  if (!isAdmin) {
    orders = orders.filter(function(o) { return o.creator === userName; });
  }""",
     """  // 基础隔离：admin全部 / 经理本部门 / 销售本人
  var _scDash = deptScope();
  if (_scDash) {
    orders = orders.filter(function(o) { return inScope(_scDash, o.creator); });
  }"""),
    # 5) 看板：MCP 客户
    ("""  if (!isAdmin) {
    mcpFiltered = mcpAll.filter(function(c){return c.owner===userName||(c.operators||[]).indexOf(userName)>=0;});
  }""",
     """  if (_scDash) {
    mcpFiltered = mcpAll.filter(function(c){
      if (c.owner === userName || (c.operators||[]).indexOf(userName) >= 0) return true;
      return _scDash.names.indexOf(c.owner) >= 0 || (c.operators||[]).some(function(op){return _scDash.names.indexOf(op)>=0;});
    });
  }"""),
    # 6) 拜访准备：可见客户
    ("""  if (role === 'manager') {
    var mcpDept = (dept === '销售拓展部') ? '诊断原料销售拓展部' : dept;
    return mcpAll.filter(function(c) { return c.dept === mcpDept; });
  }""",
     """  if (role === 'manager') {
    var _scVp = deptScope();
    if (!_scVp) return mcpAll;
    return mcpAll.filter(function(c) {
      if (_scVp.region) return String(c.dept||'').indexOf(_scVp.region) >= 0;
      return _scVp.names.indexOf(c.owner) >= 0 || (c.operators||[]).some(function(op){return _scVp.names.indexOf(op)>=0;})
             || normDeptName(c.dept) === normDeptName(dept);
    });
  }"""),
    # 7) 客诉 Tab
    ("""  var u = state.user || {};
  if (u.role !== 'admin' && u.role !== 'gm') {
    items = items.filter(function(c){return c.creator === u.name;});
  }""",
     """  var u = state.user || {};
  var _scComp = deptScope();
  if (_scComp) {
    items = items.filter(function(c){
      if (c.creator === u.name) return true;
      return _scComp.names.indexOf(c.creator) >= 0;
    });
  }"""),
]


def main(apply):
    h = open(F, encoding='utf-8').read()
    ok = 0
    for old, new in PATCHES:
        n = h.count(old)
        tag = '✓' if n == 1 else ('跳过(已改)' if n == 0 and new[:40] in h else '✗ 命中 %d 次' % n)
        if n == 1:
            h = h.replace(old, new, 1)
            ok += 1
        elif n == 0 and new[:60] in h:
            tag = '已是最新'
        print('  %-4s %s' % (tag, old.strip().splitlines()[0][:64]))
    print('  共应用 %d/%d 处' % (ok, len(PATCHES)))
    if apply and ok:
        open(F, 'w', encoding='utf-8').write(h)
        print('  ✅ 已写入 %s' % F)
    elif not apply:
        print('  （预览模式；加 --apply 生效）')


if __name__ == '__main__':
    main('--apply' in sys.argv[1:])
