# -*- coding: utf-8 -*-
"""校验：直营城市播报主表表头纵向冻结（滚动容器 + sticky）"""
import json, shutil, subprocess, tempfile, time, urllib.request
import websocket

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


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)[:300])
        return r.get('result', {}).get('value')


prof = tempfile.mkdtemp(prefix='chr_fix_')
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,820', URL],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
c = CDP(PORT)
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(2)
    init = c.ev(r"""(function(){
      var t=document.querySelector('#v3main'), box=t.closest('.v3wrap');
      var th=t.querySelector('thead th');
      return {hasSticky: box.classList.contains('v3sticky'),
              boxH: Math.round(box.getBoundingClientRect().height),
              boxScrollH: box.scrollHeight, boxClientH: box.clientHeight,
              thTop: Math.round(th.getBoundingClientRect().top),
              thPos: getComputedStyle(th).position,
              pageOverflow: document.documentElement.scrollWidth - document.documentElement.clientWidth};
    })()""")
    print('初始:', init)
    # 真·整页滚动：滚 window，不再动 box
    print('页滚:', c.ev("""(function(){
      var t=document.querySelector('#v3main'), th=t.querySelector('thead th'), box=t.closest('.v3wrap');
      var y0=window.scrollY; window.scrollTo(0, y0 + box.getBoundingClientRect().top + 260);
      var r=th.getBoundingClientRect(), b=box.getBoundingClientRect();
      return {scrollY:Math.round(window.scrollY), boxTop:Math.round(b.top), thTop:Math.round(r.top),
              stuck: Math.abs(r.top)<=1, pageScrollable: document.documentElement.scrollHeight>window.innerHeight};
    })()"""))
    c.ev("window.scrollTo(0,0)"); time.sleep(0.3)
    scrolled = c.ev(r"""(function(){
      var t=document.querySelector('#v3main'), box=t.closest('.v3wrap');
      box.scrollTop = 420;
      var th=t.querySelector('thead th'), tr=t.querySelector('tbody tr.v3mrow');
      return {boxScrollTop: box.scrollTop,
              thTopAfter: Math.round(th.getBoundingClientRect().top),
              thVisible: th.getBoundingClientRect().top >= box.getBoundingClientRect().top - 1,
              firstRowTop: Math.round(tr.getBoundingClientRect().top),
              boxTop: Math.round(box.getBoundingClientRect().top)};
    })()""")
    print('滚动后:', scrolled)
    # 复位并测宽
    c.ev("(function(){var t=document.querySelector('#v3main'); t.closest('.v3wrap').scrollTop=0;})()")
    for w in (1920, 1440, 1366, 1310, 1300, 1280, 375):
        c.send('Emulation.setDeviceMetricsOverride', {'width': w, 'height': 820, 'deviceScaleFactor': 1, 'mobile': w < 500})
        time.sleep(1.3)
        print(w, c.ev(r"""(function(){
          var t=document.querySelector('#v3main'), box=t.closest('.v3wrap'), th=t.querySelector('thead th');
          return {pageOverflow: Math.max(document.documentElement.scrollWidth,document.body.scrollWidth)-document.documentElement.clientWidth,
                  boxClientH: box.clientHeight, boxScrollH: box.scrollHeight, thTop: Math.round(th.getBoundingClientRect().top),
                  thPos: getComputedStyle(th).position};
        })()"""))
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)
