import base64, json, os, shutil, subprocess, tempfile, time, urllib.request, websocket
URL='file:///data/workspace/南部大区城市看板/南部大区经营看板_v3.html'; PORT=9361; CHROME='/usr/bin/chromium'
OUT='/data/workspace/南部大区城市看板/v3/'
class C:
    def __init__(s,p): s.port=p; s.id=0; s.ws=None
    def http(s,p):
        with urllib.request.urlopen('http://127.0.0.1:%d%s'%(s.port,p),timeout=5) as r: return json.loads(r.read().decode())
    def up(s):
        for _ in range(150):
            try: s.http('/json/version'); return True
            except Exception: time.sleep(0.2)
    def conn(s):
        t=None
        for _ in range(60):
            for x in s.http('/json/list'):
                if x.get('type')=='page': t=x; break
            if t: break
            time.sleep(0.2)
        s.ws=websocket.create_connection(t['webSocketDebuggerUrl'],timeout=60,max_size=1<<26)
    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,'userGesture':True})
        if 'exceptionDetails' in r: raise RuntimeError(json.dumps(r['exceptionDetails'],ensure_ascii=False)[:400])
        return r.get('result',{}).get('value')
    def shot(s,name):
        r=s.send('Page.captureScreenshot',{'format':'png','captureBeyondViewport':False})
        open(OUT+name,'wb').write(base64.b64decode(r['data']))
prof=tempfile.mkdtemp(prefix='s_')
p=subprocess.Popen([CHROME,'--headless=new','--disable-gpu','--no-sandbox','--hide-scrollbars','--remote-debugging-port=%d'%PORT,'--user-data-dir='+prof,'--window-size=1280,1000','--remote-allow-origins=*','about:blank'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
c=C(PORT)
try:
    assert c.up(); c.conn(); c.send('Runtime.enable'); c.send('Page.enable')
    c.send('Emulation.setDeviceMetricsOverride',{'width':1280,'height':1000,'deviceScaleFactor':1,'mobile':False})
    c.send('Page.navigate',{'url':URL}); time.sleep(6)
    c.ev("document.querySelector('.tabs button[data-t=\"t2\"]').click()")
    c.ev("(function(){var s=document.getElementById('v3Month'); s.value='202611'; s.dispatchEvent(new Event('change',{bubbles:true}));})()")
    time.sleep(1.0)
    c.ev("document.querySelector('.v3tool').scrollIntoView()")
    time.sleep(0.5)
    c.shot('_shot_v2b_1280_main.png')
    # 下钻 + 情景表
    c.ev("document.querySelector('#v3main tr.v3mrow[data-city=\"广州市\"]').click()")
    time.sleep(1.2)
    c.ev("(function(){var t=document.querySelector('#v3main tr.v3detail table[data-tbl=\"scen\"]'); if(t) t.scrollIntoView({block:'center'});})()")
    time.sleep(0.6)
    c.shot('_shot_v2b_1280_scen.png')
    # 375
    c.send('Emulation.setDeviceMetricsOverride',{'width':375,'height':812,'deviceScaleFactor':1,'mobile':True})
    time.sleep(1.6)
    c.ev("document.querySelector('.v3tool').scrollIntoView()")
    time.sleep(0.5)
    c.shot('_shot_v2b_375_main.png')
    # 1280 全表（含右侧两奖列）
    c.send('Emulation.setDeviceMetricsOverride',{'width':1280,'height':1000,'deviceScaleFactor':1,'mobile':False})
    time.sleep(1.2)
    c.ev("document.querySelector('.v3tool').scrollIntoView()")
    time.sleep(0.5)
    c.shot('_shot_v2b_1280_main2.png')
    print('ok')
finally:
    try: c.ws.close()
    except Exception: pass
    p.terminate(); shutil.rmtree(prof,ignore_errors=True)
