-- 本月预收账款（Sheet3）
-- 参数：{period_start} 账期起始日，{period_end} 账期结束日
-- "本月" = 账期所在月，"上月" = 账期月前一个月
-- 金额均为含税金额

WITH
-- 上月月份范围
month_range AS (
  SELECT
    '{period_start}'::date AS period_start,
    '{period_end}'::date AS period_end,
    DATE_TRUNC('month', '{period_start}'::date) AS this_month_start,
    (DATE_TRUNC('month', '{period_start}'::date) - INTERVAL '1 day')::date AS last_month_end,
    (DATE_TRUNC('month', '{period_start}'::date) - INTERVAL '1 month')::date AS last_month_start
),
-- 所有退费记录
all_refund_records AS (
  SELECT
    out_trade_no AS order_no,
    SUM(refund_amount_int)::numeric / 100 AS total_refund_amount,
    MAX(CASE WHEN refund_type = 2 THEN 1 ELSE 0 END) AS is_full_refund,
    MAX(DATE(updated_at)) AS latest_refund_date
  FROM bi_refund_order
  WHERE status = 3
    AND DATE(updated_at) <= '{period_end}'::date
  GROUP BY out_trade_no
),
-- 所有订单基础信息（含退费标记）
order_base AS (
  SELECT
    o.out_trade_no AS order_no,
    DATE(o.pay_success_date) AS order_date,
    o.pay_amount_int::numeric / 100 AS pay_amount,
    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,
    CASE WHEN ar.order_no IS NOT NULL AND COALESCE(ar.total_refund_amount, 0) >= o.pay_amount_int::numeric / 100 THEN 1 ELSE 0 END AS is_full_refund,
    ar.latest_refund_date,
    -- 转正日期 = 下单日 + 7天
    DATE(o.pay_success_date) + INTERVAL '7 days' AS amortization_start_date,
    -- 有效金额（部分退费 = 原金额 - 退费；未退费 = 原金额；全额退费 = 0）
    CASE
      WHEN ar.order_no IS NOT NULL AND COALESCE(ar.total_refund_amount, 0) >= o.pay_amount_int::numeric / 100 THEN 0
      ELSE o.pay_amount_int::numeric / 100 - COALESCE(ar.total_refund_amount, 0)
    END AS effective_amount,
    o.order_status
  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
  CROSS JOIN month_range mr
  WHERE
    o.pay_success_date >= mr.last_month_start
    AND o.pay_success_date <= mr.period_end
    AND o.order_status IN (3,4)
    AND o.pay_amount_int >= 1000
    AND a.status = 1
),
-- 标记订单分类
order_classified AS (
  SELECT
    ob.*,
    mr.*,
    -- 上月下单
    CASE WHEN ob.order_date >= mr.last_month_start AND ob.order_date <= mr.last_month_end THEN 1 ELSE 0 END AS is_last_month_order,
    -- 本月下单
    CASE WHEN ob.order_date >= mr.this_month_start AND ob.order_date <= mr.period_end THEN 1 ELSE 0 END AS is_this_month_order,
    -- 上月未转正（转正日 > 上月最后一天）
    CASE WHEN ob.amortization_start_date > mr.last_month_end THEN 1 ELSE 0 END AS not_formal_in_last_month,
    -- 本月已转正（转正日 <= 账期结束日）
    CASE WHEN ob.amortization_start_date <= mr.period_end THEN 1 ELSE 0 END AS formal_in_this_month,
    -- 上月已全额退费
    CASE WHEN ob.has_refund = 1 AND ob.is_full_refund = 1 AND ob.latest_refund_date <= mr.last_month_end THEN 1 ELSE 0 END AS full_refund_in_last_month,
    -- 本月退费金额（退费日期在账期内）
    CASE WHEN ob.has_refund = 1
              AND ob.latest_refund_date >= mr.period_start
              AND ob.latest_refund_date <= mr.period_end
         THEN ob.total_refund_amount
         ELSE 0
    END AS refund_in_period
  FROM order_base ob
  CROSS JOIN month_range mr
)
SELECT
  '上月订单转正' AS "分类",
  -- 新增：上月下单 + 上月未转正 + 剔除上月全额退费 + 部分退费算有效金额
  ROUND(SUM(
    CASE WHEN is_last_month_order = 1
              AND not_formal_in_last_month = 1
              AND full_refund_in_last_month = 0
         THEN effective_amount
         ELSE 0
    END
  )::numeric, 2) AS "新增",
  -- 退费：这些订单在本月的退费金额
  ROUND(SUM(
    CASE WHEN is_last_month_order = 1
              AND not_formal_in_last_month = 1
              AND full_refund_in_last_month = 0
         THEN refund_in_period
         ELSE 0
    END
  )::numeric, 2) AS "退费"

FROM order_classified

UNION ALL

SELECT
  '本月订单转正' AS "分类",
  -- 新增：本月下单 + 本月已转正 + 不考虑退费（原订单金额）
  ROUND(SUM(
    CASE WHEN is_this_month_order = 1
              AND formal_in_this_month = 1
         THEN pay_amount
         ELSE 0
    END
  )::numeric, 2) AS "新增",
  -- 退费：这些订单在本月的退费金额
  ROUND(SUM(
    CASE WHEN is_this_month_order = 1
              AND formal_in_this_month = 1
         THEN refund_in_period
         ELSE 0
    END
  )::numeric, 2) AS "退费"

FROM order_classified

UNION ALL

SELECT
  '本月订单未转正' AS "分类",
  -- 新增：本月下单 + 本月未转正 + 不考虑退费
  ROUND(SUM(
    CASE WHEN is_this_month_order = 1
              AND formal_in_this_month = 0
         THEN pay_amount
         ELSE 0
    END
  )::numeric, 2) AS "新增",
  -- 退费：这些订单在本月的退费金额
  ROUND(SUM(
    CASE WHEN is_this_month_order = 1
              AND formal_in_this_month = 0
         THEN refund_in_period
         ELSE 0
    END
  )::numeric, 2) AS "退费"

FROM order_classified;
