-- 上周(2026-05-11~2026-05-17)有课消的付费用户，按 L1/L2 分类

WITH last_week_active_chars AS (
    SELECT DISTINCT user_id FROM bi_user_chapter_play_record_0 WHERE play_status = 1 AND created_at >= '2026-05-11' AND created_at < '2026-05-18'
    UNION
    SELECT DISTINCT user_id FROM bi_user_chapter_play_record_1 WHERE play_status = 1 AND created_at >= '2026-05-11' AND created_at < '2026-05-18'
    UNION
    SELECT DISTINCT user_id FROM bi_user_chapter_play_record_2 WHERE play_status = 1 AND created_at >= '2026-05-11' AND created_at < '2026-05-18'
    UNION
    SELECT DISTINCT user_id FROM bi_user_chapter_play_record_3 WHERE play_status = 1 AND created_at >= '2026-05-11' AND created_at < '2026-05-18'
    UNION
    SELECT DISTINCT user_id FROM bi_user_chapter_play_record_4 WHERE play_status = 1 AND created_at >= '2026-05-11' AND created_at < '2026-05-18'
    UNION
    SELECT DISTINCT user_id FROM bi_user_chapter_play_record_5 WHERE play_status = 1 AND created_at >= '2026-05-11' AND created_at < '2026-05-18'
    UNION
    SELECT DISTINCT user_id FROM bi_user_chapter_play_record_6 WHERE play_status = 1 AND created_at >= '2026-05-11' AND created_at < '2026-05-18'
    UNION
    SELECT DISTINCT user_id FROM bi_user_chapter_play_record_7 WHERE play_status = 1 AND created_at >= '2026-05-11' AND created_at < '2026-05-18'
),
last_week_active_accounts AS (
    SELECT DISTINCT c.account_id
    FROM last_week_active_chars lw
    JOIN bi_vala_app_character c ON lw.user_id = c.id
),
paying_active AS (
    SELECT DISTINCT lw.account_id
    FROM last_week_active_accounts lw
    WHERE EXISTS (
        SELECT 1 FROM bi_vala_order o
        JOIN bi_vala_app_account a ON o.account_id = a.id AND a.status = 1
        WHERE o.account_id = lw.account_id
          AND o.order_status IN (3, 4)
          AND o.pay_success_date IS NOT NULL
    )
),
user_goods_agg AS (
    SELECT 
        pa.account_id,
        array_agg(DISTINCT o.goods_id) AS goods_ids
    FROM paying_active pa
    JOIN bi_vala_order o ON pa.account_id = o.account_id
    WHERE o.order_status IN (3, 4)
      AND o.pay_success_date IS NOT NULL
    GROUP BY pa.account_id
),
classified AS (
    SELECT 
        account_id,
        CASE 
            WHEN 61 = ANY(goods_ids) THEN 'L1+L2'
            WHEN (57 = ANY(goods_ids) OR 60 = ANY(goods_ids) OR 63 = ANY(goods_ids))
                 AND (31 = ANY(goods_ids) OR 32 = ANY(goods_ids) OR 33 = ANY(goods_ids) OR 54 = ANY(goods_ids))
            THEN 'L1+L2'
            WHEN 57 = ANY(goods_ids) OR 60 = ANY(goods_ids) OR 63 = ANY(goods_ids) THEN '仅L1'
            WHEN 31 = ANY(goods_ids) OR 32 = ANY(goods_ids) OR 33 = ANY(goods_ids) OR 54 = ANY(goods_ids) THEN '仅L2'
            ELSE '其他'
        END AS level_type
    FROM user_goods_agg
)
SELECT 
    level_type,
    COUNT(*) AS user_count
FROM classified
GROUP BY level_type
ORDER BY 
    CASE level_type
        WHEN '仅L1' THEN 1
        WHEN '仅L2' THEN 2
        WHEN 'L1+L2' THEN 3
        WHEN '其他' THEN 4
    END;
