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'
)

# 查询指定订单
order_no = "dd202602111013471770776027390252"
sql = """
SELECT 
    o.out_trade_no AS order_no,
    o.created_at AS order_create_time,
    o.pay_amount_int / 100 AS pay_amount,
    o.order_status,
    r.updated_at AS refund_finish_time,
    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
LEFT JOIN bi_refund_order r ON o.out_trade_no = r.trade_no AND r.status = 3
WHERE o.out_trade_no = %s
"""

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

if df.empty:
    print(f"未找到订单号为 {order_no} 的记录")
else:
    row = df.iloc[0]
    print(f"订单号：{row['order_no']}")
    print(f"下单时间：{row['order_create_time'].strftime('%Y-%m-%d %H:%M:%S') if pd.notna(row['order_create_time']) else '无'}")
    print(f"订单金额：{row['pay_amount']}元")
    print(f"订单状态：{row['order_status']}")
    if pd.notna(row['refund_finish_time']):
        print(f"退款完成时间：{row['refund_finish_time'].strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"退款金额：{row['refund_amount']}元")
        print(f"退款类型：{row['refund_type']}")
    else:
        print("该订单无退费记录")
