import os
import psycopg2
import pandas as pd
from dotenv import load_dotenv
from datetime import datetime

# 加载环境变量
load_dotenv('/root/.openclaw/workspace/secrets.env')

# 数据库配置
db_config = {
    'host': 'bj-postgres-16pob4sg.sql.tencentcdb.com',
    'port': 28591,
    'user': 'ai_member',
    'password': os.getenv('POSTGRES_ONLINE_PASSWORD'),
    'database': 'vala_bi'
}

# 账期参数
start_date = '2026-03-01'
end_date = '2026-03-31'

# 替换SQL参数
sql = f"""
WITH all_refund_records AS (
  SELECT
    out_trade_no AS order_no,
    SUM(refund_amount_int) / 100 AS total_refund_amount,
    MAX(CASE WHEN refund_type = 2 THEN 1 ELSE 0 END) AS is_full_refund,
    MAX(refund_type) AS refund_type,
    MAX(DATE(updated_at)) AS latest_refund_date
  FROM bi_refund_order
  WHERE status = 3
  GROUP BY out_trade_no
),
order_base AS (
  SELECT 
    o.id AS order_id,
    o.out_trade_no AS order_no,
    o.trade_no,
    o.pay_amount_int / 100 AS pay_amount,
    CASE WHEN DATE(o.created_at) < '2026-05-01' THEN 0.01 ELSE 0.06 END AS tax_rate,
    (o.pay_amount_int / 100) * CASE WHEN DATE(o.created_at) < '2026-05-01' THEN 0.01 ELSE 0.06 END AS tax_amount,
    (o.pay_amount_int / 100) * (1 - CASE WHEN DATE(o.created_at) < '2026-05-01' THEN 0.01 ELSE 0.06 END) AS after_tax_amount,
    (DATE(o.created_at) + INTERVAL '7 days')::DATE AS amortization_start_date,
    o.order_status,
    a.id AS account_id,
    o.key_from,
    o.sale_channel,
    DATE(o.created_at) AS order_date,
    CASE WHEN ar.order_no IS NOT NULL THEN 1 ELSE 0 END AS has_refund,
    COALESCE(ar.total_refund_amount, 0) AS total_refund_amount,
    COALESCE(ar.is_full_refund, 0) AS is_full_refund,
    ar.refund_type,
    ar.latest_refund_date
  FROM bi_vala_order o
  JOIN bi_vala_app_account a ON o.account_id = a.id
  LEFT JOIN all_refund_records ar ON o.out_trade_no = ar.order_no
  WHERE 
    o.created_at >= '2025-09-01'
    AND o.order_status IN (3,4)
    AND o.pay_amount_int >= 1000
    AND a.status = 1
),
order_cycle AS (
  SELECT 
    order_no,
    COUNT(DISTINCT id) * 90 AS total_cycle_days
  FROM bi_vala_seasonal_ticket
  WHERE status != -1
  GROUP BY order_no
),
refund_records AS (
  SELECT 
    r.out_trade_no AS order_no,
    r.refund_amount_int / 100 AS refund_amount,
    r.refund_type,
    DATE(r.updated_at) AS refund_date
  FROM bi_refund_order r
  JOIN order_base o ON r.out_trade_no = o.order_no OR r.trade_no = o.trade_no
  WHERE 
    r.status = 3
    AND r.updated_at BETWEEN '{start_date}' AND '{end_date}'
),
order_amortization AS (
  SELECT
    ob.order_no,
    ob.pay_amount,
    ob.tax_rate,
    ob.tax_amount,
    ob.after_tax_amount,
    oc.total_cycle_days,
    ob.amortization_start_date,
    ob.order_date,
    ob.has_refund,
    ob.total_refund_amount,
    ob.is_full_refund,
    ob.refund_type,
    GREATEST(0, ('{end_date}'::DATE - ob.amortization_start_date) + 1) AS amortized_days,
    LEAST(
      GREATEST(0, ('{end_date}'::DATE - GREATEST(ob.amortization_start_date, '{start_date}'::DATE)) + 1),
      oc.total_cycle_days
    ) AS current_period_amortized_days,
    ob.after_tax_amount / oc.total_cycle_days AS daily_amortization_amount,
    ob.tax_amount / oc.total_cycle_days AS daily_tax_amount
  FROM order_base ob
  JOIN order_cycle oc ON ob.order_no = oc.order_no
  WHERE oc.total_cycle_days > 0
)
SELECT
  order_no,
  ROUND(pay_amount, 2) AS pay_amount,
  ROUND(tax_rate * 100, 1) AS tax_rate_percent,
  ROUND(tax_amount, 2) AS tax_amount,
  ROUND(after_tax_amount, 2) AS after_tax_amount,
  total_cycle_days,
  amortized_days,
  ROUND(amortized_days * daily_amortization_amount, 2) AS historical_amortized_amount,
  ROUND(current_period_amortized_days * daily_amortization_amount, 2) AS current_period_amortization_amount,
  ROUND(after_tax_amount - (amortized_days * daily_amortization_amount), 2) AS remaining_amortization_amount,
  GREATEST(0, total_cycle_days - amortized_days) AS remaining_cycle_days
FROM order_amortization
"""

# 连接数据库
conn = psycopg2.connect(**db_config)

# 读取订单明细数据
order_detail_df = pd.read_sql(sql, conn)

# 计算汇总数据
total_orders = len(order_detail_df)
end_date_dt = datetime.strptime(end_date, '%Y-%m-%d').date()
# 正式订单：order_date +7天 <= end_date
formal_orders = len(order_detail_df[order_detail_df['order_date'].apply(lambda x: x + pd.Timedelta(days=7) <= end_date_dt)])
trial_orders = total_orders - formal_orders

# 计算税费相关
pre_adjustment_tax = round(order_detail_df['tax_amount'].sum(), 2)
# 冲销税费：有退费的订单的税费总和
refund_orders = order_detail_df[order_detail_df['has_refund'] == 1]
adjustment_tax = round(refund_orders['tax_amount'].sum(), 2)
# 补充税费：部分退费的订单剩余税费
partial_refund_orders = refund_orders[refund_orders['is_full_refund'] == 0]
def calc_supplement_tax(row):
    if row['pay_amount'] == 0:
        return 0
    return row['tax_amount'] * (1 - row['total_refund_amount']/row['pay_amount'])
supplement_tax = round(partial_refund_orders.apply(calc_supplement_tax, axis=1).sum(), 2)
post_adjustment_tax = round(pre_adjustment_tax - adjustment_tax + supplement_tax, 2)

# 均摊金额相关
pre_adjustment_amortization = round(order_detail_df['current_period_amortization_amount'].sum(), 2)
adjustment_amortization = round(refund_orders['historical_amortized_amount'].sum(), 2)
def calc_supplement_amortization(row):
    remaining_after_tax = row['after_tax_amount'] - (row['total_refund_amount'] * (1 - row['tax_rate']/100))
    return max(0, remaining_after_tax - row['historical_amortized_amount'])
supplement_amortization = round(partial_refund_orders.apply(calc_supplement_amortization, axis=1).sum(), 2)
post_adjustment_amortization = round(pre_adjustment_amortization - adjustment_amortization + supplement_amortization, 2)

# 创建汇总表DataFrame
summary_df = pd.DataFrame({
    '指标': [
        '总订单数',
        '正式订单数',
        '试用订单数',
        '冲销前税费（元）',
        '冲销税费（元）',
        '补充税费（元）',
        '冲销后税费（元）',
        '冲销前均摊金额（税后，元）',
        '冲销均摊金额（税后，元）',
        '补充均摊金额（税后，元）',
        '冲销后均摊金额（税后净收入，元）'
    ],
    '数值': [
        total_orders,
        formal_orders,
        trial_orders,
        pre_adjustment_tax,
        adjustment_tax,
        supplement_tax,
        post_adjustment_tax,
        pre_adjustment_amortization,
        adjustment_amortization,
        supplement_amortization,
        post_adjustment_amortization
    ]
})

# 生成Excel文件
output_path = f'/root/.openclaw/workspace/output/订单均摊结算报表_{start_date}_{end_date}.xlsx'
with pd.ExcelWriter(output_path, engine='openpyxl') as writer:
    summary_df.to_excel(writer, sheet_name='汇总表', index=False)
    order_detail_df.to_excel(writer, sheet_name='订单明细', index=False)

# 关闭数据库连接
conn.close()

print(f"报表已生成：{output_path}")
print(f"📊 账期{start_date}至{end_date}均摊结算结果：")
print(f"总订单数：{total_orders}单")
print(f"正式订单数：{formal_orders}单")
print(f"试用订单数：{trial_orders}单")
print(f"冲销后税费：{post_adjustment_tax}元")
print(f"冲销后均摊金额（税后净收入）：{post_adjustment_amortization}元")
