# -*- coding: utf-8 -*-
"""校验 t2 两列「进度VS时间」第二行：较时间进度毛利差额"""
import json, os, shutil, subprocess, sys, tempfile, time, urllib.request
import websocket

URL = 'file:///data/workspace/南部大区城市看板/南部大区经营看板_v3.html'
PORT = 9361


class CDP(object):
    def __init__(self, port):
        self.port = port; self.id = 0; self.ws = None; self.events = []

    def http(self, path):
        with urllib.request.urlopen('http://127.0.0.1:%d%s' % (self.port, path), timeout=5) as r:
            return json.loads(r.read().decode('utf-8'))

    def wait_up(self, sec=40):
        t0 = time.time()
        while time.time() - t0 < sec:
            try:
                self.http('/json/version'); return True
            except Exception:
                time.sleep(0.2)
        return False

    def connect(self):
        tgt = None
        for _ in range(80):
            for t in self.http('/json/list'):
                if t.get('type') == 'page':
                    tgt = t; break
            if tgt:
                break
            time.sleep(0.2)
        assert tgt, 'no page target'
        self.ws = websocket.create_connection(tgt['webSocketDebuggerUrl'], timeout=60, max_size=1 << 26)

    def send(self, method, params=None):
        self.id += 1; mid = self.id
        self.ws.send(json.dumps({'id': mid, 'method': method, 'params': params or {}}))
        while True:
            msg = json.loads(self.ws.recv())
            if msg.get('id') == mid:
                if 'error' in msg:
                    raise RuntimeError('%s -> %s' % (method, msg['error']))
                return msg.get('result', {})
            elif 'method' in msg:
                self.events.append(msg)

    def ev(self, expr):
        r = self.send('Runtime.evaluate', {'expression': expr, 'returnByValue': True, 'userGesture': True})
        if 'exceptionDetails' in r:
            raise RuntimeError('JS: %s' % json.dumps(r['exceptionDetails'], ensure_ascii=False)[:600])
        return r.get('result', {}).get('value')

    def wait_for(self, expr, sec=60):
        t0 = time.time()
        while time.time() - t0 < sec:
            try:
                if self.ev(expr):
                    return True
            except Exception:
                pass
            time.sleep(0.2)
        return False

    def errors(self):
        out = []
        for e in self.events:
            m, p = e.get('method'), e.get('params', {})
            if m == 'Runtime.exceptionThrown':
                d = p.get('exceptionDetails', {})
                out.append('[exception] ' + str(d.get('text')) + ' :: ' + str((d.get('exception') or {}).get('description'))[:300])
            elif m == 'Runtime.consoleAPICalled' and p.get('type') == 'error':
                out.append('[console.error] ' + ' '.join(str(a.get('value') if 'value' in a else a.get('description')) for a in p.get('args', []))[:300])
        return out


JS_CELLS = r"""
window.__cell = function(city, idx){
  var tr = document.querySelector('#v3main tr.v3mrow[data-city="'+city+'"]');
  if(!tr) return null;
  var td = tr.children[idx];
  if(!td) return null;
  var lines = Array.from(td.querySelectorAll('div')).map(function(d){
      return {t:d.textContent.trim(), color:getComputedStyle(d).color, fs:getComputedStyle(d).fontSize};
  });
  return {head: td.querySelector('b') ? td.querySelector('b').textContent.trim() : td.textContent.trim(),
          lines: lines, cls: String(td.className), h: Math.round(tr.getBoundingClientRect().height)};
};
window.__rowh = function(){
  return Array.from(document.querySelectorAll('#v3main tr.v3mrow')).map(function(tr){
    return Math.round(tr.getBoundingClientRect().height);
  });
};
window.__exp = function(city, kind){
  var D = window.DATA, T = window.TARGETS_V3, tp = D.meta.time_progress, m='202611';
  var gp = city==='__REGION__' ? null : D.cities12[city]['毛利额'].mtd;
  var tgt;
  if(city==='__REGION__'){ tgt = kind==='jy'? T.region[m].gp : T.region[m].mj_gp; gp = (window.__REG_GP)||null; }
  else { tgt = kind==='jy'? T.cities[city][m].gp : T.cities[city][m].mj_gp; }
  return {gp: gp, tgt: tgt, tp: tp};
};
window.__MEAS = function(){
  var d = document.documentElement, b = document.body;
  return {docScroll: d.scrollWidth, client: d.clientWidth, bodyScroll: b.scrollWidth,
          overflow: Math.max(d.scrollWidth, b.scrollWidth) - d.clientWidth};
};
"""

report = {}
prof = tempfile.mkdtemp(prefix='chr_amt_')
proc = subprocess.Popen(['/usr/bin/chromium', '--headless=new', '--no-sandbox', '--disable-gpu',
                         '--disable-dev-shm-usage', '--remote-debugging-port=%d' % PORT,
                         '--remote-allow-origins=*', '--user-data-dir=' + prof, '--window-size=1280,900', URL],
                        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
cdp = CDP(PORT)
try:
    assert cdp.wait_up(), 'chromium 未就绪'
    cdp.connect()
    cdp.send('Runtime.enable'); cdp.send('Log.enable'); cdp.send('Page.enable')
    assert cdp.wait_for("!!document.querySelector('#v3main tr.v3mrow')", 90), '主表未渲染'
    cdp.ev("(function(){var b=document.querySelector('.tabs button[data-t=\"t2\"]'); if(b) b.click();})()")
    time.sleep(1.8)
    cdp.ev(JS_CELLS)

    # 列序号：0城市 1换电用户 2套内 3收入 4客单价 5毛利额 6毛利率 7单用户毛利
    # 8经营奖目标 9经营奖达成 10经营奖进度VS时间 11茅台奖目标 12茅台奖达成 13茅台奖进度VS时间
    report['广州_经营奖'] = cdp.ev("__cell('广州市',10)")
    report['广州_茅台奖'] = cdp.ev("__cell('广州市',13)")
    report['大区_经营奖'] = cdp.ev("__cell('__REGION__',10)")
    report['大区_茅台奖'] = cdp.ev("__cell('__REGION__',13)")

    # 期望值：直接由页面数据算
    report['期望'] = cdp.ev("""(function(){
      var D=window.DATA,T=window.TARGETS_V3,tp=D.meta.time_progress,m='202611';
      function f(city){
        var gp = city==='__REGION__' ? window.__REG_GP_TMP : D.cities12[city]['毛利额'].mtd;
        var tc = city==='__REGION__' ? T.region[m] : T.cities[city][m];
        return {gp:gp, jy:(gp-tc.gp*tp)/1e4, mj:(gp-tc.mj_gp*tp)/1e4};
      }
      // 大区毛利额从表里读（含联营）
      var reg=document.querySelector('#v3main tr.v3mrow[data-city="__REGION__"]');
      window.__REG_GP_TMP = null;
      return {gz:f('广州市'), tp:tp,
              reg_gp_txt: reg? reg.children[5].textContent.trim():null};
    })()""")

    report['行高'] = cdp.ev("__rowh()")
    report['归因行'] = cdp.ev("""(function(){
      var out=[]; document.querySelectorAll('#v3main tr.v3attr').forEach(function(tr){
        var p=tr.previousElementSibling;
        out.push({city:p?p.getAttribute('data-city'):null,
                  visible: tr.getBoundingClientRect().height>0,
                  head: (tr.querySelector('.vt')||{}).textContent||null});
      }); return out; })()""")

    # 12 月：切月后检查
    cdp.ev("(function(){var s=document.getElementById('v3Month'); if(s){s.value='202612'; s.dispatchEvent(new Event('change'));}})()")
    time.sleep(1.8)
    report['12月_广州_经营奖'] = cdp.ev("__cell('广州市',10)")
    report['12月_广州_茅台奖'] = cdp.ev("__cell('广州市',13)")

    # 下钻点击仍可用
    cdp.ev("(function(){var s=document.getElementById('v3Month'); s.value='202611'; s.dispatchEvent(new Event('change'));})()")
    time.sleep(1.5)
    report['下钻'] = cdp.ev("""(function(){
      var tr=document.querySelector('#v3main tr.v3mrow[data-city="广州市"]');
      tr.click();
      var d=document.querySelector('#v3main tr.v3detail');
      return {open: !!d, scen: !!document.querySelector('#v3main tr.v3detail table[data-tbl="scen"]')};
    })()""")
    time.sleep(0.6)

    cdp.ev("(function(){document.querySelectorAll('#v3main tr.v3detail').forEach(function(x){x.remove();});})()")
    time.sleep(0.4)
    for w in (1280, 375):
        cdp.send('Emulation.setDeviceMetricsOverride', {'width': w, 'height': 900, 'deviceScaleFactor': 1, 'mobile': w < 500})
        time.sleep(1.5)
        report['w%d' % w] = cdp.ev('__MEAS()')
        cdp.ev('__rowh()')

    report['文案守卫'] = cdp.ev("""(function(){
      var t=document.querySelector('#t2').innerText||'';
      return {月底预计缺口:t.indexOf('月底预计缺口')>=0, 预计缺口:t.indexOf('预计缺口')>=0,
              较时间进度毛利差额:t.indexOf('较时间进度毛利差额')>=0};
    })()""")
    report['console_errors'] = cdp.errors()
finally:
    try:
        cdp.ws.close()
    except Exception:
        pass
    proc.terminate()
    try:
        proc.wait(timeout=10)
    except Exception:
        proc.kill()
    shutil.rmtree(prof, ignore_errors=True)

print(json.dumps(report, ensure_ascii=False, indent=1))
