# -*- coding: utf-8 -*-
"""检查 t2 主表表头提示删除后的宽度/溢出（多视口）"""
import json, shutil, subprocess, tempfile, time, urllib.request
import websocket

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


class CDP:
    def __init__(s, p):
        s.port = p; s.id = 0; s.ws = None
    def http(s, path):
        with urllib.request.urlopen('http://127.0.0.1:%d%s' % (s.port, path), timeout=5) as r:
            return json.loads(r.read().decode())
    def wait_up(s, sec=40):
        t0 = time.time()
        while time.time() - t0 < sec:
            try:
                s.http('/json/version'); return True
            except Exception:
                time.sleep(0.2)
        return False
    def connect(s):
        for _ in range(80):
            for t in s.http('/json/list'):
                if t.get('type') == 'page':
                    s.ws = websocket.create_connection(t['webSocketDebuggerUrl'], timeout=60, max_size=1 << 26)
                    return
            time.sleep(0.2)
        raise RuntimeError('no page')
    def send(s, m, p=None):
        s.id += 1; mid = s.id
        s.ws.send(json.dumps({'id': mid, 'method': m, 'params': p or {}}))
        while True:
            r = json.loads(s.ws.recv())
            if r.get('id') == mid:
                if 'error' in r:
                    raise RuntimeError(r['error'])
                return r.get('result', {})
    def ev(s, e):
        r = s.send('Runtime.evaluate', {'expression': e, 'returnByValue': True})
        if 'exceptionDetails' in r:
            raise RuntimeError(json.dumps(r['exceptionDetails'], ensure_ascii=False)[:400])
        return r.get('result', {}).get('value')


MEAS = r"""(function(){
  var d=document.documentElement, b=document.body;
  var t=document.querySelector('#v3main'), w=t? t.parentElement : null;
  var th=document.querySelectorAll('#v3main thead th');
  var subs=Array.from(th).map(function(x){var s=x.querySelector('.v3sub2'); return s? s.textContent.trim():'';});
  return {vw:d.clientWidth, pageScroll:d.scrollWidth, bodyScroll:b.scrollWidth,
          pageOverflow:Math.max(d.scrollWidth,b.scrollWidth)-d.clientWidth,
          tableW: t? Math.round(t.getBoundingClientRect().width):null,
          wrapW: w? Math.round(w.getBoundingClientRect().width):null,
          wrapScrollW: w? w.scrollWidth:null,
          wrapOverflow: w? Math.max(0, w.scrollWidth-w.clientWidth):null,
          nTh: th.length,
          hints: subs.filter(function(s){return s.indexOf('下行为较时间进度毛利差额')>=0;}),
          allSubs: subs};
})()"""

prof = tempfile.mkdtemp(prefix='chr_w_')
p = subprocess.Popen(['/usr/bin/chromium', '--headless=new', '--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage',
                      '--remote-allow-origins=*', '--remote-debugging-port=%d' % PORT,
                      '--user-data-dir=' + prof, '--window-size=1440,900', URL],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
c = CDP(PORT)
out = {}
try:
    assert c.wait_up(); c.connect()
    c.send('Runtime.enable')
    for _ in range(120):
        if c.ev("!!document.querySelector('#v3main tr.v3mrow')"):
            break
        time.sleep(0.3)
    c.ev("(function(){var b=document.querySelector('.tabs button[data-t=\"t2\"]'); if(b)b.click();})()")
    time.sleep(1.8)
    for w in (1920, 1600, 1440, 1366, 1280, 1024, 768, 375):
        c.send('Emulation.setDeviceMetricsOverride', {'width': w, 'height': 900, 'deviceScaleFactor': 1, 'mobile': w < 500})
        time.sleep(1.3)
        out[w] = c.ev(MEAS)
    out['console'] = []
finally:
    try:
        c.ws.close()
    except Exception:
        pass
    p.terminate()
    try:
        p.wait(timeout=10)
    except Exception:
        p.kill()
    shutil.rmtree(prof, ignore_errors=True)

for w in (1920, 1600, 1440, 1366, 1280, 1024, 768, 375):
    d = out[w]
    print('vw=%-5d 页面溢出=%3dpx | 表格宽=%s 容器宽=%s 容器内溢出=%spx | th=%d | 长提示数=%d'
          % (w, d['pageOverflow'], d['tableW'], d['wrapW'], d['wrapOverflow'], d['nTh'], len(d['hints'])))
print('表头小字：', out[1440]['allSubs'])
