#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
经理 KPI 口径修正：部门目标取「权威口径固定值」，不按在职人数加总
==================================================================
用户口径（2026-09-20）：「刘欣的目标是 3400 万，也就是销售拓展部的目标是 3400 万。
不因有人员进出而降低部门目标。」
原实现：_annual = Σ(本部门在职人员 target) = 29,700,004 ✗（离职人员的份额被扣掉了）
修正后：
  年目标 = 数据/月度目标_2026统一.json（yearTargets2026.depts[部门].annual，单位万）= 34,000,000 ✓
  12 个月目标 = 同文件 months（加总正好 = 年目标）
  12 个月实际 = h1Monthly.depts[部门].actuals(1-6月) + dash.depts[部门].h2_actual_months(7-12月)
  区域经理（浙江/广东）：没有区域级官方目标 → 仍用本区域在职人员加总（并在 label 标注）
"""
import io, sys, shutil
PC, MB = '工具/index.html', '工具/app.html'
APPLY = '--apply' in sys.argv

OLD = """  // ── 部门经理：本部门 KPI（2026-09-20 刘欣案；经理≠管理员，不得看全公司）──
  if (role === 'manager') {
    var _nd = normDeptName(u.dept);
    var _uo = String(u.dept || '');
    var _region = _uo.indexOf('浙江') >= 0 ? '浙江' : (_uo.indexOf('广东') >= 0 ? '广东' : '');
    var _regNames = null;
    if (_region) {
      _regNames = ((state.data.personnel || {}).personnel || []).filter(function(x) {
        var rg = String((x && x.region) || '');
        if (!rg) return false;
        return _region === '浙江' ? rg.indexOf('浙江') >= 0 : (rg.indexOf('广东') >= 0 || rg.indexOf('广州') >= 0);
      }).map(function(x) { return x.name; });
      if (!_regNames.length) _regNames = null;
    }
    var _fit = function(x) {
      if (normDeptName(x.dept || x.department) !== _nd) return false;
      if (_regNames && _regNames.indexOf(x.name) < 0) return false;
      if (_region && x.region && String(x.region).indexOf(_region) < 0) return false;
      return true;
    };
    var _people = (dash.people || []).filter(_fit);
    var _dRows = (dash.depts || []).filter(function(dp) { return normDeptName(dp.dept) === _nd; });
    var _dr = _dRows[0] || (_dRows.length ? _dRows[0] : {});
    var _sum = function(a) { var t = 0; (a || []).forEach(function(v) { t += (v || 0); }); return t; };
    var _annual = _people.reduce(function(s, p) { return s + (p.target || 0); }, 0) || (_dr.target || 0);
    var _ytd = _people.reduce(function(s, p) { return s + (p.h1_total || 0) + (p.h2_actual || 0); }, 0);
    if (!_ytd) _ytd = (_dr.h1_total || 0) + (_dr.h2_actual || 0);
    var _h1m = (_dr.h1_months || []).slice(0, 6), _h2m = (_dr.h2_months || []).slice(0, 6);
    var _h2a = (_dr.h2_actual_months || []).slice(0, 6);
    var _mi = Math.max(0, new Date().getMonth() - 6);
    var _isH2 = new Date().getMonth() >= 6;
    var _mT = _isH2 ? (_h2m[_mi] || 0) : (_h1m[new Date().getMonth()] || 0);
    var _mA = _isH2 ? (_h2a[_mi] || 0) : 0;
    var _lm = new Date().getMonth(); // 上月（0-based）
    var _last = (_lm >= 7) ? (_h2a[_lm - 7] || 0) : 0;
    var _q3T = _sum(_h2m.slice(0, 3)), _q3A = _sum(_h2a.slice(0, 3));
    return { label: _nd, dept: _nd, role: 'manager', annual: _annual, ytd: _ytd,
             pct: _annual ? Math.round(_ytd / _annual * 1000) / 10 : 0,
             monthly: { targets: _h1m, actuals: [] }, h2Targets: _h2m, h2Actuals: _h2a,
             yearTargets: _h1m.concat(_h2m), yearActuals: [0, 0, 0, 0, 0, 0].concat(_h2a),
             current: _mA, last: _last, monthTarget: _mT, monthActual: _mA,
             q3Target: _q3T, q3Actual: _q3A, deptMembers: _people.map(function(p) { return p.name; }) };
  }
"""

NEW = """  // ── 部门经理：本部门 KPI（2026-09-20 刘欣案；经理≠管理员，不得看全公司）──
  // 口径铁律：部门年目标取「权威固定值」，绝不按在职人数加总（人员进出不降低部门目标）
  if (role === 'manager') {
    var _nd = normDeptName(u.dept);
    var _uo = String(u.dept || '');
    var _region = _uo.indexOf('浙江') >= 0 ? '浙江' : (_uo.indexOf('广东') >= 0 ? '广东' : '');
    var _regNames = null;
    if (_region) {
      _regNames = ((state.data.personnel || {}).personnel || []).filter(function(x) {
        var rg = String((x && x.region) || '');
        if (!rg) return false;
        return _region === '浙江' ? rg.indexOf('浙江') >= 0 : (rg.indexOf('广东') >= 0 || rg.indexOf('广州') >= 0);
      }).map(function(x) { return x.name; });
      if (!_regNames.length) _regNames = null;
    }
    var _fit = function(x) {
      if (normDeptName(x.dept || x.department) !== _nd) return false;
      if (_regNames && _regNames.indexOf(x.name) < 0) return false;
      if (_region && x.region && String(x.region).indexOf(_region) < 0) return false;
      return true;
    };
    var _people = (dash.people || []).filter(_fit);
    var _dRows = (dash.depts || []).filter(function(dp) { return normDeptName(dp.dept) === _nd; });
    var _dr = _dRows[0] || {};
    var _sum = function(a) { var t = 0; (a || []).forEach(function(v) { t += (v || 0); }); return t; };
    var _pTarget = _people.reduce(function(s, p) { return s + (p.target || 0); }, 0);
    // 权威口径：数据/月度目标_2026统一.json（按部门），annual 单位「万」；1-12 月加总 = 年目标
    var _uniD = ((d.yearTargets2026 || {}).depts || {})[_nd] || null;
    var _h1D = (((d.h1Monthly || {}).depts) || {})[_nd] || null;
    var _annual = _region ? _pTarget : (_uniD && _uniD.annual ? _uniD.annual * 10000 : (_dr.target || _pTarget));
    var _ytd = _people.reduce(function(s, p) { return s + (p.h1_total || 0) + (p.h2_actual || 0); }, 0);
    if (!_ytd) _ytd = (_dr.h1_total || 0) + (_dr.h2_actual || 0);
    var _monU = (_uniD && (_uniD.months || []).length >= 12) ? _uniD.months.slice(0, 12) : null;
    var _h1m = _monU ? _monU.slice(0, 6) : (_dr.h1_months || []).slice(0, 6);
    var _h2m = _monU ? _monU.slice(6, 12) : (_dr.h2_months || []).slice(0, 6);
    var _h1a = (_h1D && (_h1D.actuals || []).length >= 6) ? _h1D.actuals.slice(0, 6) : [0, 0, 0, 0, 0, 0];
    var _h2a = (_dr.h2_actual_months || []).slice(0, 6);
    var _yearT = _h1m.concat(_h2m), _yearA = _h1a.concat(_h2a);
    var _nowM = new Date().getMonth() + 1;
    var _mT = _monU ? (_monU[_nowM - 1] || 0) : (_nowM >= 7 ? (_h2m[_nowM - 7] || 0) : (_h1m[_nowM - 1] || 0));
    var _mA = _nowM >= 7 ? (_h2a[_nowM - 7] || 0) : (_h1a[_nowM - 1] || 0);
    var _last = _nowM >= 2 ? (_yearA[_nowM - 2] || 0) : 0;
    var _q3T = _sum(_h2m.slice(0, 3)), _q3A = _sum(_h2a.slice(0, 3));
    return { label: _nd + (_region ? '·' + _region : ''), dept: _nd, role: 'manager', region: _region,
             annual: _annual, ytd: _ytd,
             pct: _annual ? Math.round(_ytd / _annual * 1000) / 10 : 0,
             monthly: { targets: _h1m, actuals: _h1a }, h2Targets: _h2m, h2Actuals: _h2a,
             yearTargets: _yearT, yearActuals: _yearA,
             current: _mA, last: _last, monthTarget: _mT, monthActual: _mA,
             q3Target: _q3T, q3Actual: _q3A, deptMembers: _people.map(function(p) { return p.name; }) };
  }
"""

def run(path):
    s = io.open(path, encoding='utf-8').read()
    if OLD not in s:
        print('  ⚠️  %s 未找到旧块（可能已更新）' % path); return 0
    s = s.replace(OLD, NEW, 1)
    if APPLY:
        io.open(path, 'w', encoding='utf-8').write(s)
    print('  ✅ %s 经理 KPI 分支已改为「权威部门目标」' % path)
    return 1

shutil.copy(PC, PC + '.bak_before_mgr4')
shutil.copy(MB, MB + '.bak_before_mgr4')
n = run(PC) + run(MB)
print('\n  %s 共 %d 个文件' % ('📦 已写入' if APPLY else '（预演）', n))
