#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""本地验收：LS「课题组」Tab 改造（管理员全量 / 销售仅本人）。"""
import io
import json
import sys

from playwright.sync_api import sync_playwright

U = 'http://127.0.0.1:8765/工具/index.html'
GT = json.load(io.open('/Users/liuxinyuan/Desktop/Hermes输出-工作类/数据/ls_groups.json', encoding='utf-8'))
OK = True


def chk(label, cond, detail=''):
    global OK
    print('  %s %-42s %s' % ('✅' if cond else '❌', label, detail))
    if not cond:
        OK = False


def boot(pg, name, role, line):
    pg.goto(U, wait_until='load')
    pg.wait_for_timeout(800)
    pg.evaluate("""async (p) => {
        document.getElementById('loginOverlay').style.display='none';
        document.getElementById('app').style.display='block';
        state.user = {name:p.name, role:p.role, dept:'销售管理', line:p.line};
        state.currentLine = 'ls';
        var d = await fetch('../数据/ls_groups.json?v='+Date.now(), {cache:'no-store'}).then(r=>r.json());
        state.data = state.data || {};
        state.data.lsGroups = d;
        if (typeof switchTab === 'function') { switchTab('groups'); }
        state.tab = 'groups'; render();
    }""", {'name': name, 'role': role, 'line': line})
    pg.wait_for_timeout(700)


with sync_playwright() as p:
    br = p.chromium.launch(channel='chrome', headless=True)
    pg = br.new_page(viewport={'width': 1500, 'height': 1000})
    errs = []
    pg.on('pageerror', lambda e: errs.append(str(e)))

    print('① 管理员视角（刘新元 / admin）')
    boot(pg, '刘新元', 'admin', 'both')
    cards = pg.evaluate("() => [...document.querySelectorAll('.stats-grid')].map(g=>[...g.children].map(c=>"
                        "c.querySelector('.value').innerText.trim()+'|'+c.querySelector('.label').innerText.trim()))")
    print('    KPI 卡：', cards)
    chk('KPI 两排（8 张）', len(cards) == 2 and sum(len(r) for r in cards) == 8, str(sum(len(r) for r in cards)))
    flat = {r.split('|')[1]: r.split('|')[0] for row in cards for r in row}
    chk('有采购记录 = %d' % GT['paids'], flat.get('💰 有采购记录') == str(GT['paids']), str(flat.get('💰 有采购记录')))
    chk('累计成交额 = %.2f万' % (GT['amount_total'] / 1e4), flat.get('💵 累计成交额', '').startswith('%.2f' % (GT['amount_total'] / 1e4)), str(flat.get('💵 累计成交额')))
    chk('成交货号 = %d' % GT['skus_total'], flat.get('🧾 成交货号') == str(GT['skus_total']), str(flat.get('🧾 成交货号')))
    chk('覆盖客户 = %d' % GT['customers_total'], flat.get('🏢 覆盖客户') == str(GT['customers_total']), str(flat.get('🏢 覆盖客户')))

    heads = pg.evaluate("() => [...document.querySelectorAll('.data-table thead th')].map(t=>t.innerText.trim())")
    print('    表头：', heads)
    for h in ['课题组', '累计成交额', '订单/货号', '最近成交', '客户']:
        chk('表头含「%s」' % h, h in heads)
    rows = pg.evaluate("() => document.querySelectorAll('.data-table tbody tr').length")
    chk('行数 = %d（全部课题组）' % len(GT['groups']), rows == len(GT['groups']), str(rows))
    body = pg.evaluate("() => document.querySelector('.data-table tbody').innerText")
    chk('出现「归并」标记', '归并' in body)
    chk('TOP1 戴春艳课题组（¥32,664）在首行', '戴春艳课题组' in body.split('\n')[0] and '32,664' in body)
    chk('金额带千分位', '¥32,664' in body, '¥32,664' if '¥32,664' in body else '未见')
    note = pg.evaluate("() => document.querySelector('main').innerText")
    chk('标注在谈/全量课题组数', '在谈' in note and str(GT['total']) in note)
    chk('标注订单区间与口径', GT['order_period'] in note and '标准销售订单' in note, GT['order_period'])
    pg.screenshot(path='/tmp/ls_groups_admin.png', full_page=False)

    print('\n② 销售视角（吴云 / manager）')
    boot(pg, '吴云', 'manager', 'ls')
    rows2 = pg.evaluate("() => document.querySelectorAll('.data-table tbody tr').length")
    cards2 = pg.evaluate("() => [...document.querySelectorAll('.stats-grid')].map(g=>[...g.children].map(c=>"
                         "c.querySelector('.value').innerText.trim()+'|'+c.querySelector('.label').innerText.trim()))")
    flat2 = {r.split('|')[1]: r.split('|')[0] for row in cards2 for r in row}
    gt_wu = sum(g['amt'] for g in GT['groups'] if g['sales'] == '吴云')
    n_wu = sum(1 for g in GT['groups'] if g['sales'] == '吴云')
    print('    吴云课题组 %d 个 ｜ 成交额 %.2f万（接口口径）' % (n_wu, gt_wu / 1e4))
    chk('仅显示吴云的课题组', rows2 == n_wu, '%d vs %d' % (rows2, n_wu))
    chk('累计成交额按本人口径 %.2f万' % (gt_wu / 1e4), flat2.get('💵 累计成交额', '').startswith('%.2f' % (gt_wu / 1e4)), str(flat2.get('💵 累计成交额')))
    chk('本人视角标注「仅本人」', '仅本人' in pg.evaluate("() => document.querySelector('main').innerText"))
    chk('销售员列全为吴云', pg.evaluate("() => [...new Set([...document.querySelectorAll('.data-table tbody tr')].map(r=>r.children[3].innerText.trim()))]") == ['吴云'])

    chk('0 JS 错误', len(errs) == 0, str(errs[:2]))
    br.close()

print('\n%s' % ('✅ 全部通过' if OK else '❌ 有失败项'))
sys.exit(0 if OK else 1)
