from fastapi import Query, Request
from tortoise.expressions import Q


class QueryParams:
    def __init__(self,
                 request: Request,
                 page: int = Query(1, description="页码"),
                 page_size: int = Query(10, description="每页数量"),
                ):
        self.page = page
        self.page_size = page_size
        self.query_kwargs = dict(request.query_params)

        self.q = Q()
        for key, value in self.query_kwargs.items():
            if key not in ['page', 'page_size']:
                # 使用 contains 方法实现包含查询
                self.q &= Q(**{f"{key}__contains": value})
        
    def get_offset(self):
        return (self.page - 1) * self.page_size
    
    def search_query(self, model, order=('-created_at',)):
        query = model.filter(self.q)
        return query, query.offset((self.page - 1) * self.page_size).limit(self.page_size).order_by(*order)
    