-- =====================================================================================
-- Admin 订单统计 - 订单类型分布统计 RPC
-- 位置：docs/sql/30_rpc/order/
-- 对象类型：RPC 函数（SECURITY DEFINER）
-- 版本：v1
-- 说明：按订单类型（普通、收银、核销）统计指定时间段内的销售额及其占比
-- =====================================================================================

CREATE OR REPLACE FUNCTION public.rpc_admin_order_type_stats(
    p_start_time TIMESTAMPTZ,
    p_end_time TIMESTAMPTZ
)
RETURNS JSONB
SECURITY DEFINER
SET search_path = public
LANGUAGE plpgsql
AS $$
DECLARE
    v_total_amount DECIMAL(12,2);
    v_items JSONB;
BEGIN
    -- 1. 权限检查
    IF NOT EXISTS (
        SELECT 1 FROM public.ak_users 
        WHERE auth_id = auth.uid() AND role IN ('admin', 'analytics')
    ) THEN
        RAISE EXCEPTION 'Permission denied';
    END IF;

    -- 2. 计算总销售额（用于算占比）
    SELECT COALESCE(SUM(total_amount), 0) INTO v_total_amount
    FROM public.ml_orders
    WHERE created_at >= p_start_time AND created_at <= p_end_time
      AND order_status != 5; -- 排除已取消

    -- 3. 按类型统计
    SELECT jsonb_agg(t) INTO v_items
    FROM (
        SELECT
            CASE o.order_type
                WHEN 1 THEN '普通订单'
                WHEN 2 THEN '收银订单'
                WHEN 3 THEN '核销订单'
                ELSE '其他类型'
            END AS name,
            COALESCE(SUM(o.total_amount), 0) AS amount,
            CASE 
                WHEN v_total_amount > 0 THEN ROUND((COALESCE(SUM(o.total_amount), 0) / v_total_amount * 100), 2)
                ELSE 0 
            END AS rate
        FROM public.ml_orders o
        WHERE o.created_at >= p_start_time AND o.created_at <= p_end_time
          AND o.order_status != 5
        GROUP BY o.order_type
        ORDER BY amount DESC
    ) t;

    RETURN COALESCE(v_items, '[]'::jsonb);
END;
$$;
