# -*- coding: utf-8 -*-
"""三端 1:1 回归 · 数据一致性比对
比对对象：
  左：demo（pad.html 内置 CADRES，12 名）
  右：MySQL rmsys.cadres（12 名）
逐人逐字段比对，输出差异清单。
"""
import json
import re
import subprocess

import pymysql

# ---------- 左：demo ----------
DEMO_JSON = '/tmp/demo_cadres.json'


def dump_demo():
    js = r'''
const fs=require('fs');
const s=fs.readFileSync('/data/www/files/rmsys/pad.html','utf8');
const i=s.indexOf('var CADRES');const st=s.indexOf('[',i);
let d=0,q=null,esc=false,e=-1;
for(let k=st;k<s.length;k++){const c=s[k];
 if(q){if(esc){esc=false;continue}if(c==='\\'){esc=true;continue}if(c===q)q=null;continue}
 if(c==="'"||c==='"'||c==='`'){q=c;continue}
 if(c==='['||c==='{')d++;else if(c===']'||c==='}'){d--;if(d===0){e=k;break}}}
process.stdout.write(JSON.stringify(eval(s.slice(st,e+1))));
'''
    out = subprocess.run(['node', '-e', js], capture_output=True, text=True, check=True)
    return json.loads(out.stdout)


demo = dump_demo()

# ---------- 右：数据库 ----------
c = pymysql.connect(host='192.168.20.66', user='tanghouhu', password='admin123#@!',
                    database='rmsys', charset='utf8mb4')
cur = c.cursor(pymysql.cursors.DictCursor)
cur.execute('''select c.*, d.Code as deptCode, mc.SortNo, mc.IssueNo
               from cadres c left join depts d on d.Id=c.DeptId
               left join meetingcadres mc on mc.CadreId=c.Id and mc.MeetingId=1
               order by c.Id''')
db_rows = cur.fetchall()
c.close()

# ---------- 字段映射 ----------
def db_of(r):
    return {
        'name': r['Name'], 'dept': r['deptCode'], 'seq': r['SortNo'],
        'sex': r['Sex'], 'nation': r['Nation'], 'birth': r['Birth'],
        'native': r['NativePlace'], 'birthplace': r['BirthPlace'],
        'party': r['PartyDate'], 'work': r['WorkDate'], 'health': r['Health'],
        'tech': r['TechPost'], 'expertise': r['Expertise'],
        'ef': '%s·%s' % (r['EduFullLevel'] or '', r['EduFullDegree'] or ''),
        'ep': '%s·%s' % (r['EduInLevel'] or '', r['EduInDegree'] or ''),
        'current': r['CurrentPost'], 'proposed': r['ProposedPost'],
        'dismiss': r['DismissPost'] or '', 'rewards': r['Rewards'],
        'exams': r['Exams'], 'reason': r['AppointReason'],
        'kw': r['Kw'], 'perf': r['Perf'], 'care': r['Care'], 'suggest': r['Suggest'],
    }


def demo_of(d):
    return {
        'name': d['name'], 'dept': d['dept'], 'seq': d['seq'],
        'sex': d['sex'], 'nation': d['nation'], 'birth': d['birth'],
        'native': d['native'], 'birthplace': d['birthplace'],
        'party': d['party'], 'work': d['work'], 'health': d['health'],
        'tech': d['tech'], 'expertise': d['expertise'],
        'ef': '%s·%s' % (d['ef'].get('level', ''), d['ef'].get('degree', '')),
        'ep': '%s·%s' % (d['ep'].get('level', ''), d['ep'].get('degree', '')),
        'current': d['current'], 'proposed': d['proposed'],
        'dismiss': d['dismiss'] or '', 'rewards': d['rewards'],
        'exams': d['exams'], 'reason': d['reason'],
        'kw': d.get('kw'), 'perf': d.get('perf'), 'care': d.get('care'), 'suggest': d.get('suggest'),
    }


FIELDS = ['name', 'dept', 'seq', 'sex', 'nation', 'birth', 'native', 'birthplace', 'party',
          'work', 'health', 'tech', 'expertise', 'ef', 'ep', 'current', 'proposed', 'dismiss',
          'rewards', 'exams', 'reason', 'kw', 'perf', 'care', 'suggest']

print('=== 数据一致性比对（demo vs MySQL）===')
print('demo %d 人 / 库 %d 人' % (len(demo), len(db_rows)))

diffs = []
for d, r in zip(demo, db_rows):
    a, b = demo_of(d), db_of(r)
    for f in FIELDS:
        va, vb = a.get(f), b.get(f)
        va = '' if va is None else str(va)
        vb = '' if vb is None else str(vb)
        if va != vb:
            diffs.append((d['name'], f, va, vb))

if not diffs:
    print('✔ 25 个字段 × 12 人 全部一致，无差异')
else:
    print('差异 %d 处：' % len(diffs))
    for n, f, va, vb in diffs[:30]:
        print('  %-4s %-10s demo=%s | db=%s' % (n, f, va[:36], vb[:36]))

# ---------- 简历 / 家庭 / 批注 ----------
print()
print('=== 子表比对 ===')
cur_c = pymysql.connect(host='192.168.20.66', user='tanghouhu', password='admin123#@!',
                        database='rmsys', charset='utf8mb4')
cu = cur_c.cursor()
bad = 0
for d, r in zip(demo, db_rows):
    cid = r['Id']
    cu.execute('select Period,Content from cadreresumes where CadreId=%s order by Sort', (cid,))
    db_res = [(x[0] or '', x[1] or '') for x in cu.fetchall()]
    dm_res = [(x[0], x[1]) for x in d.get('resume', [])]
    if db_res != dm_res:
        bad += 1
        print('  简历不一致: %s  demo %d 条 / db %d 条' % (d['name'], len(dm_res), len(db_res)))
    cu.execute('select Relation,Name,Age,Political,WorkUnit from cadrefamilies where CadreId=%s order by Sort', (cid,))
    db_fam = [(x[0] or '', x[1] or '', x[2] or '', x[3] or '', x[4] or '') for x in cu.fetchall()]
    dm_fam = [(x.get('rel', ''), x.get('name', ''), x.get('age', ''), x.get('pol', ''), x.get('org', ''))
              for x in d.get('family', [])]
    if db_fam != dm_fam:
        bad += 1
        print('  家庭不一致: %s  demo %d 条 / db %d 条' % (d['name'], len(dm_fam), len(db_fam)))
    cu.execute('select Content from cadrenotes where CadreId=%s order by Id', (cid,))
    db_nt = [x[0] for x in cu.fetchall()]
    dm_nt = [x.get('text', '') for x in (d.get('notes') or [])]
    if db_nt != dm_nt:
        bad += 1
        print('  批注不一致: %s  demo %d 条 / db %d 条' % (d['name'], len(dm_nt), len(db_nt)))

print('✔ 简历 62 条 / 家庭 24 条 / 批注 5 条 全部一致' if bad == 0 else '子表差异 %d 处' % bad)
cur_c.close()
