#!/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:
        print('\n【 按照service.py中的确切SQL查询 】')
        
        # 从accounts表获取account_id
        cur.execute("SELECT account_id FROM accounts WHERE account_code = '701'")
        aid_row = cur.fetchone()
        if aid_row:
            aid = aid_row['account_id']
            print(f"account_code='701' 的 account_id = {aid}")
            
            # 当期增减（date_from ～ date_to）
            # 修正された仕訳（親となった仕訳）は除外
            cur.execute("""
                SELECT
                    COALESCE(SUM(l.debit), 0)  AS debit,
                    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 %s AND %s
                   AND j.is_deleted = false
                   AND child.journal_entry_id IS NULL
            """, (aid, '2025-06-01', '2025-06-30'))
            row = cur.fetchone()
            print(f"\nSQL查询结果:")
            print(f"  debit = {row['debit']}")
            print(f"  credit = {row['credit']}")
            
            print(f"\n试算表显示的期末残高credit: 5,482,728")
            print(f"SQL查询结果credit: {row['credit']}")
            
            if row['credit'] != 5482728:
                print(f"\n⚠️  不匹配！差异 = {5482728 - row['credit']}")
            
            # 查看所有被LEFT JOIN排除的记录
            print(f"\n【 被LEFT JOIN排除的记录 (has child) 】")
            cur.execute("""
                SELECT 
                  j.journal_entry_id,
                  j.entry_date, 
                  j.description,
                  l.debit,
                  l.credit,
                  COUNT(child.journal_entry_id) as child_count
                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 %s AND %s
                  AND j.is_deleted = false
                GROUP BY j.journal_entry_id, j.entry_date, j.description, l.debit, l.credit
                HAVING COUNT(child.journal_entry_id) > 0
                ORDER BY j.entry_date
            """, (aid, '2025-06-01', '2025-06-30'))
            
            excluded_credit = 0
            for row in cur.fetchall():
                print(f"  Entry#{row['journal_entry_id']:>3} {row['entry_date']} | Credit={row['credit']:>10} | Children={row['child_count']} | {row['description'][:40]}")
                excluded_credit += row['credit']
            
            print(f"\n被排除的credit合计: {excluded_credit}")
