# -*- coding: utf-8 -*-
"""专项复验：t2 主表 MTD 两列 / 下钻成本合计 vs v2 原表 / 测算跳转 / 控制台 / 宽度"""
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

URL = sys.argv[1] if len(sys.argv) > 1 else 'file:///data/workspace/南部大区城市看板/南部大区经营看板_v3.html'
PORT = 9344
CHROME = '/usr/bin/chromium'


def main():
    prof = tempfile.mkdtemp(prefix='v3mtd_')
    proc = subprocess.Popen([CHROME, '--headless=new', '--disable-gpu', '--no-sandbox', '--hide-scrollbars',
                             '--force-device-scale-factor=1', '--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)
    out = {}
    try:
        assert cdp.wait_up(), 'chromium 未就绪'
        cdp.connect(URL)
        cdp.send('Runtime.enable')
        cdp.send('Log.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)
        out['meta'] = cdp.ev("({mtd_end:DATA.meta.mtd_end, pageMonth:(DATA.meta.mtd_end||'').slice(0,6)})")

        # --- A. 两列 vs DATA（11月 = 页面数据月，应逐位一致）+ 10月 vs 快照 ---
        out['cells'] = cdp.ev("""(function(){
          function grab(c){
            var tr=document.querySelector('#v3main tr.v3mrow[data-city="'+c+'"]');
            var td=tr.children;
            return {city:td[0].textContent.replace(/\\s+/g,' ').trim(), users:td[1].textContent.trim(),
                    taonei:td[2].textContent.trim(), rev:td[3].textContent.trim(), kd:td[4].textContent.trim(),
                    gp:td[5].textContent.replace(/\\s+/g,' ').trim(), gpm:td[6].textContent.trim(),
                    gpu:td[7].textContent.replace(/\\s+/g,' ').trim(), jy_t:td[8].textContent.trim(),
                    jy_g:td[9].textContent.replace(/\\s+/g,' ').trim(), mj_t:td[10].textContent.trim(),
                    mj_g:td[11].textContent.replace(/\\s+/g,' ').trim()};
          }
          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]={gz:grab('广州市'), region:grab('__REGION__'),
                  note:document.getElementById('v3MoNote').textContent.replace(/\\s+/g,' ').trim()};
          });
          var s=document.getElementById('v3Month'); s.value='202610'; s.dispatchEvent(new Event('change',{bubbles:true}));
          return o;})()""")

        out['data'] = cdp.ev("""(function(){
          var g=DATA.cities12['广州市'];
          var items={rent:g['租金'].mtd, ele:g['电费'].mtd, labor:g['全职人力&资产折旧'].mtd,
                     install:g['安装成本'].mtd, other:g['其他成本'].mtd, mk:g['营销费'].mtd, cost:g['成本'].mtd};
          var sum=items.rent+items.ele+items.labor+items.install+items.other;
          return {items:items, sum5:sum, cost:items.cost, diff5:items.cost-sum,
                  rev_mtd:g['收入'].mtd, gp_mtd:g['毛利额'].mtd, gpm:g['毛利率'].mtd,
                  snap10:(window.V3_M&&V3_M['202610']&&V3_M['202610']['广州市'])||null,
                  snap11:(window.V3_M&&V3_M['202611']&&V3_M['202611']['广州市'])||null,
                  agg10:(DATA.agg_trend||{})['202610']||null, ach10:(DATA.award.achieve_gp||{})['202610']||null};})()""")

        # --- B. v2 原表 #tblDirect 广州行（成本/收入/毛利）---
        out['v2_row'] = cdp.ev("""(function(){
          var tr=document.querySelector('#tblDirect tr.clickable[data-c="广州市"]');
          if(!tr) return null;
          var cells=Array.from(tr.children).map(td=>td.textContent.replace(/\\s+/g,' ').trim());
          return {cells:cells};})()""")

        # --- C. 下钻：模块数 + 成本合计（精确值，从渲染 DOM 反算）---
        out['drill'] = cdp.ev("""(function(){
          closeAllByClick:
          var tr=document.querySelector('#v3main tr.v3mrow[data-city="广州市"]'); tr.click();
          var d=document.querySelector('#v3main tr.v3detail');
          if(!d) return {ok:false};
          var rows=Array.from(d.querySelectorAll('.v3sub tbody tr'));
          var costTotal=null, rowsTxt=rows.map(function(r){return Array.from(r.children).map(function(c){return c.textContent.replace(/\\s+/g,' ').trim();});});
          rows.forEach(function(r){ var t=Array.from(r.children).map(function(c){return c.textContent.replace(/\\s+/g,' ').trim();});
            if(t[0].indexOf('成本合计')===0) costTotal=t[1]; });
          return {ok:true, modules:d.querySelectorAll('.v3mod').length,
                  mod_titles:Array.from(d.querySelectorAll('.v3mod h4')).map(function(x){return x.textContent.replace(/\\s+/g,' ').trim().slice(0,26);}),
                  cost_total_txt:costTotal, rows:rowsTxt};})()""")

        # --- D. 测算按钮 ---
        out['planner'] = cdp.ev("""(function(){
          var s=document.getElementById('v3Month'); s.value='202610'; s.dispatchEvent(new Event('change',{bubbles:true}));
          document.querySelector('#v3main tr.v3mrow[data-city="广州市"] .v3go').click(); return true;})()""")
        time.sleep(2.2)
        out['planner_state'] = cdp.ev("""(function(){
          var sc=document.querySelector('#plBar select[data-k="scope"]');
          var ms=document.querySelector('#plBar select[data-k="month"]');
          return {t6_on:document.getElementById('t6').classList.contains('on'),
                  t6_visible:document.getElementById('t6').offsetParent!==null,
                  scope:sc?sc.value:null, month:ms?ms.value:null,
                  plbar:!!document.getElementById('plBar')};})()""")

        # 再验证：切到 11 月后点测算，t6 应为 11 月
        out['planner2'] = cdp.ev("""(function(){
          document.querySelector('.tabs button[data-t="t2"]').click();
          var s=document.getElementById('v3Month'); s.value='202611'; s.dispatchEvent(new Event('change',{bubbles:true}));
          document.querySelector('#v3main tr.v3mrow[data-city="广州市"] .v3go').click(); return true;})()""")
        time.sleep(2.2)
        out['planner_state2'] = cdp.ev("""(function(){
          var sc=document.querySelector('#plBar select[data-k="scope"]');
          var ms=document.querySelector('#plBar select[data-k="month"]');
          return {scope:sc?sc.value:null, month:ms?ms.value:null};})()""")

        # 恢复 10 月
        cdp.ev("""(function(){document.querySelector('.tabs button[data-t="t2"]').click();
          var s=document.getElementById('v3Month'); s.value='202610'; s.dispatchEvent(new Event('change',{bubbles:true}));})()""")
        time.sleep(0.5)

        MEAS = """(function(){
          var de=document.documentElement, out=[];
          Array.from(document.querySelectorAll('body *')).forEach(function(el){
            var r=el.getBoundingClientRect();
            if(r.width>0 && r.right>de.clientWidth+1){ out.push({tag:el.tagName,id:el.id,right:Math.round(r.right)}); }
          });
          return {de_sw:de.scrollWidth, de_cw:de.clientWidth, overflow:de.scrollWidth-de.clientWidth,
                  n_offenders:out.length, top:out.slice(0,3),
                  v3wrap_inner_scroll:(function(){var w=document.querySelector('#v3main').parentNode; return w.scrollWidth-w.clientWidth;})()};})()"""

        def w(px, drill=False):
            cdp.send('Emulation.setDeviceMetricsOverride', {'width': px, 'height': 900, 'deviceScaleFactor': 1, 'mobile': px < 500})
            time.sleep(1.5)
            return cdp.ev(MEAS)

        out['w1280'] = w(1280)
        out['w375'] = w(375)
        out['w768'] = w(768)
        cdp.send('Emulation.setDeviceMetricsOverride', {'width': 375, 'height': 900, 'deviceScaleFactor': 1, 'mobile': True})
        time.sleep(1.0)
        cdp.ev("(function(){var tr=document.querySelector('#v3main tr.v3mrow[data-city=\"广州市\"]'); if(!document.querySelector('#v3main tr.v3detail')) tr.click();})()")
        time.sleep(0.6)
        out['w375_drill'] = cdp.ev(MEAS)
        out['w375_drill_modules'] = cdp.ev("document.querySelectorAll('#v3main tr.v3detail .v3mod').length")
        out['w375_cost_total'] = cdp.ev("""(function(){var d=document.querySelector('#v3main tr.v3detail');
          var out=null; Array.from(d.querySelectorAll('.v3sub tbody tr')).forEach(function(r){
            var t=Array.from(r.children).map(function(c){return c.textContent.replace(/\\s+/g,' ').trim();});
            if(t[0].indexOf('成本合计')===0) out=t[1]; }); return out;})()""")
        cdp.send('Emulation.setDeviceMetricsOverride', {'width': 1280, 'height': 900, 'deviceScaleFactor': 1, 'mobile': False})

        out['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(out, ensure_ascii=False, indent=1))


if __name__ == '__main__':
    main()
