#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
sys.path.insert(0, 'backend')

os.environ['DB_HOST'] = '192.168.0.61'
os.environ['DB_NAME'] = 'njts_acct'
os.environ['DB_USER'] = 'njts_app'
os.environ['DB_PASSWORD'] = 'njts_app2025'
os.environ['DB_PORT'] = '55432'

from app.core.database import get_connection

with get_connection() as conn:
    with conn.cursor() as cur:
        # 修复 Entry#360 的 parent_entry_id
        print('修复前:')
        cur.execute('SELECT journal_entry_id, parent_entry_id, description FROM journal_entries WHERE journal_entry_id IN (357, 360)')
        for row in cur.fetchall():
            print(f'  Entry#{row["journal_entry_id"]}: parent_entry_id={row["parent_entry_id"]} | {row["description"][:50]}')
        
        # 执行修复
        print('\n执行修复...')
        cur.execute('UPDATE journal_entries SET parent_entry_id = 357 WHERE journal_entry_id = 360')
        conn.commit()
        print('✓ 已修复: Entry#360 现在 parent_entry_id = 357')
        
        # 验证修复
        print('\n修复后:')
        cur.execute('SELECT journal_entry_id, parent_entry_id, description FROM journal_entries WHERE journal_entry_id IN (357, 360)')
        for row in cur.fetchall():
            print(f'  Entry#{row["journal_entry_id"]}: parent_entry_id={row["parent_entry_id"]} | {row["description"][:50]}')
        
        # 验证试算表中的数据是否被正确过滤
        print('\n验证试算表credit金额:')
        cur.execute("SELECT account_id FROM accounts WHERE account_code = '701'")
        aid = cur.fetchone()['account_id']
        
        cur.execute("""
            SELECT
                COALESCE(SUM(l.credit), 0) AS credit
            FROM journal_lines l
            JOIN journal_entries j
                ON j.journal_entry_id = l.journal_entry_id
            LEFT JOIN journal_entries child
                ON child.parent_entry_id = j.journal_entry_id
            WHERE l.account_id = %s
              AND j.entry_date BETWEEN '2025-06-01' AND '2025-06-30'
              AND j.is_deleted = false
              AND child.journal_entry_id IS NULL
        """, (aid,))
        result = cur.fetchone()
        print(f'  修复后的credit = {result["credit"]}')
        print(f'  期望值 = 4,082,728')
        if result["credit"] == 4082728:
            print('  ✓✓✓ 完美！问题已解决！')
        else:
            print(f'  差异 = {result["credit"] - 4082728}')
