-- 各等级付费用户的 goods_id 分布
-- 按 level + goods_id 统计用户数

WITH paying_user_goods AS (
    -- 每个付费用户的 goods_id 汇总
    SELECT 
        o.account_id,
        o.goods_id
    FROM bi_vala_order o
    JOIN bi_vala_app_account a ON o.account_id = a.id AND a.status = 1
    WHERE o.pay_success_date IS NOT NULL 
      AND o.order_status = 3
    GROUP BY o.account_id, o.goods_id
),
user_level AS (
    -- 判定 L1/L2 等级
    SELECT 
        account_id,
        array_agg(DISTINCT goods_id) AS goods_ids
    FROM paying_user_goods
    GROUP BY account_id
),
user_level_label 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
    FROM user_level
)
-- 按 level + goods_id 统计用户数
SELECT 
    l.level,
    g.goods_id,
    COUNT(DISTINCT g.account_id) AS user_count
FROM user_level_label l
JOIN paying_user_goods g ON l.account_id = g.account_id
GROUP BY l.level, g.goods_id
ORDER BY 
    CASE l.level 
        WHEN 'L1+L2' THEN 1 
        WHEN '仅L1' THEN 2 
        WHEN '仅L2' THEN 3 
        ELSE 4 
    END,
    g.goods_id;
