CREATE OR REPLACE FUNCTION "public"."get_review_files_with_details"("p_keyword" text=NULL::text, "p_typeid" _int4=NULL::integer[], "p_evaluations_status" int4=NULL::integer, "p_date_from" date=NULL::date, "p_date_to" date=NULL::date, "p_sort_order" text='created_at_desc'::text, "p_page" int4=1, "p_page_size" int4=10, "p_document_ids" _int4=NULL::integer[], "p_user_id" int4=NULL::integer)
  RETURNS TABLE("id" int4, "status" varchar, "path" varchar, "file_name" varchar, "file_code" varchar, "file_type_name" varchar, "file_type_id" int4, "file_size" int4, "upload_time" timestamptz, "created_at" timestamptz, "evaluations_status" int4, "audit_status" int4, "created_by_user_id" int4, "issue_count" int8, "total_score" numeric, "pass_count" int8, "warning_count" int8, "fail_count" int8, "manual_count" int8, "issues" jsonb) AS $BODY$
DECLARE
    offset_val integer;
    sort_column text;
    sort_direction text;
BEGIN
    offset_val := (p_page - 1) * p_page_size;
		
		-- 如果p_user_id为NULL，直接返回0
    IF p_user_id IS NULL THEN
        RETURN;
    END IF;

    SELECT
        CASE
            WHEN p_sort_order = 'upload_time_asc' THEN 'created_at'
            WHEN p_sort_order = 'upload_time_desc' THEN 'created_at'
            WHEN p_sort_order = 'issue_count_asc' THEN 'issue_count'
            WHEN p_sort_order = 'issue_count_desc' THEN 'issue_count'
            ELSE 'created_at' -- 默认排序字段
        END,
        CASE
            WHEN p_sort_order LIKE '%_asc' THEN 'ASC'
            ELSE 'DESC'
        END
    INTO sort_column, sort_direction;

    RETURN QUERY EXECUTE format('
        WITH doc_agg AS (
            SELECT
                er.document_id,
                COUNT(*) FILTER (WHERE (er.evaluated_results->>''result'')::boolean = false) AS issue_count,
                SUM(ep.score) FILTER (WHERE (er.evaluated_results->>''result'')::boolean = true) AS total_score,
                COUNT(*) FILTER (WHERE (er.evaluated_results->>''result'')::boolean = true) AS pass_count,
                COUNT(*) FILTER (WHERE (er.evaluated_results->>''result'')::boolean = false AND (ep.suggestion_message_type = ''warning'' OR ep.suggestion_message_type = ''info'')) AS warning_count,
                COUNT(*) FILTER (WHERE (er.evaluated_results->>''result'')::boolean = false AND ep.suggestion_message_type = ''error'') AS fail_count,
                COUNT(*) FILTER (WHERE ep.post_action = ''manual'') AS manual_count,
                jsonb_agg(
                    jsonb_build_object(
                        ''severity'', ep.suggestion_message_type,
                        ''message'', er.evaluated_results->>''message''
                    )
                ) FILTER (WHERE (er.evaluated_results->>''result'')::boolean = false) AS issues
            FROM evaluation_results er
            JOIN evaluation_points ep ON er.evaluation_point_id = ep.id
            GROUP BY er.document_id
        )
        SELECT
            d.id,
            d.status,
            d.path,
            d.name AS file_name,
            d.document_number AS file_code,
            dt.name AS file_type_name,
            d.type_id AS file_type_id,
            d.file_size,
            d.upload_time::timestamptz,
            d.created_at,
            d.evaluations_status,
            d.audit_status,
            d.user_id AS created_by_user_id,
            COALESCE(agg.issue_count, 0) AS issue_count,
            COALESCE(agg.total_score, 0) AS total_score,
            COALESCE(agg.pass_count, 0) AS pass_count,
            COALESCE(agg.warning_count, 0) AS warning_count,
            COALESCE(agg.fail_count, 0) AS fail_count,
            COALESCE(agg.manual_count, 0) AS manual_count,
            agg.issues
        FROM documents d
        LEFT JOIN document_types dt ON d.type_id = dt.id
        LEFT JOIN doc_agg agg ON d.id = agg.document_id
        WHERE
            ($1 IS NULL OR (d.name ILIKE ''%%'' || $1 || ''%%'' OR d.document_number ILIKE ''%%'' || $1 || ''%%'')) AND
            ($2 IS NULL OR d.type_id = ANY($2)) AND
            ($3 IS NULL OR d.evaluations_status = $3) AND
            ($4 IS NULL OR d.created_at >= $4) AND
            ($5 IS NULL OR d.created_at < ($5 + INTERVAL ''1 day'')) AND
            ($8 IS NULL OR d.id = ANY($8)) AND
						($9 d.user_id = $9)
        ORDER BY %I %s
        LIMIT $6 OFFSET $7
    ', sort_column, sort_direction)
    USING p_keyword, p_typeid, p_evaluations_status, p_date_from, p_date_to, p_page_size, offset_val, p_document_ids, p_user_id;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;

-- 同时创建或更新 count_review_files 函数
CREATE OR REPLACE FUNCTION "public"."count_review_files"("p_keyword" text=NULL::text, "p_typeid" _int4=NULL::integer[], "p_evaluations_status" int4=NULL::integer, "p_date_from" date=NULL::date, "p_date_to" date=NULL::date, "p_document_ids" _int4=NULL::integer[], "p_user_id" int4=NULL::integer)
  RETURNS int4 AS $BODY$
DECLARE
    total_count integer;
BEGIN
    -- 如果p_user_id为NULL，直接返回0
    IF p_user_id IS NULL THEN
        RETURN 0;
    END IF;

    SELECT COUNT(*)
    INTO total_count
    FROM documents d
    WHERE
        (p_keyword IS NULL OR (d.name ILIKE '%' || p_keyword || '%' OR d.document_number ILIKE '%' || p_keyword || '%')) AND
        (p_typeid IS NULL OR d.type_id = ANY(p_typeid)) AND
        (p_evaluations_status IS NULL OR d.evaluations_status = p_evaluations_status) AND
        (p_date_from IS NULL OR d.created_at >= p_date_from) AND
        (p_date_to IS NULL OR d.created_at < (p_date_to + INTERVAL '1 day')) AND
        (p_document_ids IS NULL OR d.id = ANY(p_document_ids)) AND
        d.user_id = p_user_id;
    
    RETURN total_count;
END;
$BODY$
  LANGUAGE plpgsql STABLE
  COST 100;