import psycopg2
import pandas as pd

# 读取密码
DB_PASSWORD = ""
with open('/root/.openclaw/workspace/secrets.env', 'r') as f:
    for line in f:
        if line.startswith('PG_ONLINE_PASSWORD='):
            DB_PASSWORD = line.strip().split('=', 1)[1].strip('"\'')
            break

# 数据库连接
conn = psycopg2.connect(
    host='bj-postgres-16pob4sg.sql.tencentcdb.com',
    port=28591,
    user='ai_member',
    password=DB_PASSWORD,
    database='vala_bi'
)

# 查询2025年9月到2026年2月下单3月退费的订单
sql = """
SELECT 
    o.out_trade_no AS order_no,
    DATE(o.created_at) AS order_create_date,
    o.pay_amount_int / 100 AS pay_amount,
    o.order_status,
    DATE(r.updated_at) AS refund_date,
    CAST(r.refund_amount AS NUMERIC) / 100 AS refund_amount,
    CASE r.refund_type WHEN 1 THEN '仅退款' WHEN 2 THEN '全额退货退款' WHEN 3 THEN '部分退货退款' END AS refund_type
FROM bi_vala_order o
JOIN bi_refund_order r ON o.out_trade_no = r.trade_no
WHERE 
    o.created_at BETWEEN '2025-09-01 00:00:00' AND '2026-02-28 23:59:59'
    AND r.updated_at BETWEEN '2026-03-01 00:00:00' AND '2026-03-31 23:59:59'
    AND r.status = 3
"""

df = pd.read_sql(sql, conn)
conn.close()

print("🔍 2025年9月-2026年2月下单、2026年3月退费的订单列表：")
print(f"共找到{len(df)}条符合条件的记录：")
if not df.empty:
    print(df.to_string(index=False))
else:
    print("无符合条件的记录")
