# -*- coding: utf-8 -*-
"""改动前后逐列 diff：证明只有 MTD收入(第4列) / MTD毛利额(第6列) 变化"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _cdp_check import CDP  # noqa: E402

CHROME = '/usr/bin/chromium'
GRAB = """(function(){
  var o={};
  ['202610','202611','202612'].forEach(function(m){
    var s=document.getElementById('v3Month'); s.value=m; s.dispatchEvent(new Event('change',{bubbles:true}));
    o[m]={};
    Array.from(document.querySelectorAll('#v3main tr.v3mrow')).forEach(function(tr){
      o[m][tr.getAttribute('data-city')]=Array.from(tr.children).map(function(td){return td.textContent.replace(/\\s+/g,' ').trim();});
    });
  });
  return o;})()"""


def run(url, port):
    prof = tempfile.mkdtemp(prefix='v3diff_')
    proc = subprocess.Popen([CHROME, '--headless=new', '--disable-gpu', '--no-sandbox', '--hide-scrollbars',
                             '--remote-debugging-port=%d' % port, '--user-data-dir=' + prof,
                             '--window-size=1280,900', '--remote-allow-origins=*', 'about:blank'],
                            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    cdp = CDP(port)
    try:
        assert cdp.wait_up(), 'chromium'
        cdp.connect(url)
        cdp.send('Runtime.enable')
        cdp.send('Page.enable')
        cdp.send('Emulation.setDeviceMetricsOverride', {'width': 1280, 'height': 900, 'deviceScaleFactor': 1, 'mobile': False})
        cdp.send('Page.navigate', {'url': url})
        assert cdp.wait_for("!!(window.DATA && document.querySelector('#v3main tr.v3mrow'))", 40)
        time.sleep(1.0)
        return cdp.ev(GRAB)
    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)


before = run('file:///tmp/v3_before_mtdfix.html', 9355)
after = run('file:///data/workspace/南部大区城市看板/南部大区经营看板_v3.html', 9356)
HDR = ['城市(+测算)'] * 0
res = {}
for m in ('202610', '202611', '202612'):
    for c in before[m]:
        b, a = before[m][c], after[m][c]
        for i, (x, y) in enumerate(zip(b, a)):
            if x != y:
                res.setdefault(m, []).append({'city': c, 'col': i, 'before': x, 'after': y})
print(json.dumps(res, ensure_ascii=False, indent=1))
