import psycopg2
import sys

# 数据库连接
try:
    conn = psycopg2.connect(
        host="192.168.0.61",
        port=55432,
        database="njts_acct",
        user="njts_app",
        password="njts_app2025"
    )
except Exception as e:
    print(f"数据库连接失败: {e}")
    sys.exit(1)

cur = conn.cursor()

# 查询所有科目
try:
    cur.execute("""
        SELECT 
            account_id,
            account_code,
            account_name,
            account_type
        FROM accounts
        ORDER BY CAST(account_code AS INTEGER)
    """)
    results = cur.fetchall()
except Exception as e:
    print(f"查询失败: {e}")
    sys.exit(1)

print("=" * 120)
print("全科目リスト - 科目代码范围分析")
print("=" * 120)

ranges = [
    ("100-199 (资产-现金预金)", 100, 199),
    ("200-299 (资产-应收账款)", 200, 299),
    ("300-399 (资产-有价证券)", 300, 399),
    ("400-499 (资产-固定资产)", 400, 499),
    ("500-599 (负债)", 500, 599),
    ("600-699 (纯资产)", 600, 699),
    ("700-799 (收益/收入)", 700, 799),
    ("800-899 (费用)", 800, 899),
    ("900-999 (其他)", 900, 999),
]

for label, min_code, max_code in ranges:
    print(f"\n【{label}】")
    
    filtered = [(id, code, name, typ) for id, code, name, typ in results 
                if min_code <= int(code) <= max_code]
    
    if filtered:
        for account_id, account_code, account_name, account_type in filtered:
            print(f"  {account_code:>3s} - {account_name:35s} (ID:{account_id:>3d}, Type:{account_type:10s})")
    else:
        print("  (无科目)")

# 打印按 account_type 的分类
print("\n" + "=" * 120)
print("按 account_type 分类")
print("=" * 120)

cur.execute("""
    SELECT DISTINCT account_type
    FROM accounts
    ORDER BY account_type
""")
types = cur.fetchall()

for (acc_type,) in types:
    print(f"\n【{acc_type}】")
    
    filtered = [(id, code, name) for id, code, name, typ in results if typ == acc_type]
    
    for account_id, account_code, account_name in filtered:
        code_int = int(account_code)
        if 700 <= code_int < 800:
            category = "收益"
        elif 800 <= code_int < 900:
            category = "费用"
        else:
            category = "其他"
        print(f"  {account_code:>3s} - {account_name:35s} (ID:{account_id:>3d})")

print("\n" + "=" * 120)
print("科目代码范围统计")
print("=" * 120)

code_ranges = {
    "700-799": (700, 799),
    "800-899": (800, 899),
    "505": (505, 505),
}

for label, (min_code, max_code) in code_ranges.items():
    count = len([1 for _, code, _, _ in results if min_code <= int(code) <= max_code])
    print(f"{label}: {count} 个科目")

cur.close()
conn.close()

print("\n✓ 查询完成")
