# -*- coding: utf-8 -*-
"""给 排班工具.html 注入一段辖区认领测试脚本，输出 build/_area_e2e.html"""
import io, os

SRC = r"D:\workbbbbbb\排班工具.html"
OUT = r"D:\workbbbbbb\build\_area_e2e.html"

ERRTRAP = ('<script>window.__ERRS=[];window.addEventListener("error",function(e){'
           'window.__ERRS.push((e.message||"")+" @line"+e.lineno);});</script>')

TEST = r"""
<script>
setTimeout(function () {
  var out = [];
  try {
    var b = document.getElementById('btnAutoArea');
    b.click();
    var s = window.__PB.state();
    var all = s.areas.map(function (a) { return a.r2; });
    var cnt = {};
    all.forEach(function (n) { cnt[n] = 0; });
    var per = [], ns = [];
    s.people.forEach(function (p) {
      var arr = (p.areas || []).filter(function (x) { return !!x; });
      ns.push(arr.length);
      per.push(p.n + ':' + arr.length + '[' + arr.join(',') + ']');
      arr.forEach(function (n) { cnt[n] = (cnt[n] || 0) + 1; });
    });
    var miss = all.filter(function (n) { return !cnt[n]; });
    var dup = Object.keys(cnt).filter(function (n) { return cnt[n] > 1; });
    out.push('people=' + s.people.length);
    out.push('perCounts=' + ns.join(','));
    out.push('spread=' + (Math.max.apply(null, ns) - Math.min.apply(null, ns)));
    out.push('total=' + ns.reduce(function (a, b) { return a + b; }, 0) + '/' + all.length);
    out.push('miss=' + miss.length + '(' + miss.join('|') + ')');
    out.push('dup=' + dup.length + '(' + dup.join('|') + ')');
    out.push('cover=' + document.getElementById('areaCover').textContent);
    out.push('stat2=' + document.getElementById('areaStat2').textContent);
    out.push('missCardHidden=' + (document.getElementById('areaMissCard').style.display === 'none'));
    out.push('detail=' + per.join(' ; '));
  } catch (e) {
    out.push('ERR ' + e.message + ' @@ ' + String(e.stack).slice(0, 200));
  }
  out.push('ERRS=' + ((window.__ERRS || []).join(' ; ') || 'none'));
  var d = document.createElement('div');
  d.id = 'E2E';
  d.textContent = out.join(' || ');
  document.body.appendChild(d);
}, 1200);
</script>
"""

html = io.open(SRC, encoding='utf-8').read()
i = html.find('<script>window.__PAIBAN_DATA__')
assert i > 0, 'data script not found'
html = html[:i] + ERRTRAP + html[i:]
end = html.rfind('</body>')
assert end > 0
html = html[:end] + TEST + html[end:]
io.open(OUT, 'w', encoding='utf-8').write(html)
print('out=', OUT, 'size=', round(os.path.getsize(OUT) / 1024.0, 1), 'KB')
